repo_name
string
path
string
copies
string
size
string
content
string
license
string
lboss75/vds
libs_server/vds_ws_api/websocket_api.cpp
1
35169
/* Copyright (c) 2017, Vadim Malyshev, lboss75@gmail.com All rights reserved */ #include "stdafx.h" #include "websocket_api.h" #include "db_model.h" #include "transaction_log_record_dbo.h" #include "transaction_block.h" #include "websocket.h" #include "channel_message_dbo.h" #include "dht_network_client.h" #include "dht_network.h" #include "device_record_dbo.h" #include "../private/dht_network_client_p.h" #include "transaction_block_builder.h" #include "node_storage_dbo.h" #include "local_data_dbo.h" #include "server_api.h" #include "datacoin_balance_dbo.h" #include "server.h" #include "sync_replica_map_dbo.h" #include "chunk_replica_data_dbo.h" vds::websocket_api::websocket_api() : subscribe_timer_("WebSocket API Subscribe Timer") { } vds::async_task<vds::expected<void>> vds::websocket_api::process_api_message( const vds::service_provider* sp, std::shared_ptr<vds::websocket_output> output_stream, std::shared_ptr<vds::websocket_api> api, vds::const_data_buffer data) { GET_EXPECTED_ASYNC(message, vds::json_parser::parse("Web Socket API", data)); std::list<vds::lambda_holder_t<vds::async_task<vds::expected<void>>>> post_tasks; GET_EXPECTED_ASYNC(result, co_await api->process_message(sp, output_stream, message, post_tasks)); GET_EXPECTED_ASYNC(result_str, result->str()); GET_EXPECTED_ASYNC(stream, co_await output_stream->start(result_str.length(), false)); CHECK_EXPECTED_ASYNC(co_await stream->write_async((const uint8_t*)result_str.c_str(), result_str.length())); for (auto& task : post_tasks) { CHECK_EXPECTED_ASYNC(co_await task()); } co_return vds::expected<void>(); } vds::async_task<vds::expected<std::shared_ptr<vds::stream_output_async<uint8_t>>>> vds::websocket_api::open_connection( const vds::service_provider * sp, std::shared_ptr<http_async_serializer> output_stream, const http_message & request) { auto api = std::make_shared<websocket_api>(); return websocket::open_connection( sp, output_stream, request, [sp, api]( bool /*is_binary*/, std::shared_ptr<websocket_output> output_stream ) -> async_task<expected<std::shared_ptr<stream_output_async<uint8_t>>>> { return expected<std::shared_ptr<vds::stream_output_async<uint8_t>>>(std::make_shared<collect_data>([sp, output_stream, api](const_data_buffer data)->async_task<expected<void>> { mt_service::async(sp, [sp, output_stream, api, data]() { process_api_message(sp, output_stream, api, data).then([](){}); }); co_return expected<void>(); })); }); } vds::async_task<vds::expected<std::shared_ptr<vds::json_value>>> vds::websocket_api::process_message( const vds::service_provider * sp, std::shared_ptr<websocket_output> output_stream, const std::shared_ptr<json_value> & message, std::list<lambda_holder_t<async_task<expected<void>>>> & post_tasks) { auto request = std::dynamic_pointer_cast<json_object>(message); if (!request) { co_return make_unexpected<std::runtime_error>("JSON object is expected"); } int id; GET_EXPECTED_ASYNC(isOk, request->get_property("id", id)); if (!isOk) { co_return make_unexpected<std::runtime_error>("id field is expected"); } auto result = co_await process_message(sp, output_stream, id, request, post_tasks); if (!result.has_error()) { co_return std::move(result.value()); } auto res = std::make_shared<json_object>(); res->add_property("id", id); res->add_property("error", result.error()->what()); co_return res; } vds::async_task<vds::expected<std::shared_ptr<vds::json_value>>> vds::websocket_api::process_message( const vds::service_provider * sp, std::shared_ptr<websocket_output> output_stream, int id, const std::shared_ptr<json_object> & request, std::list<lambda_holder_t<async_task<expected<void>>>> & post_tasks) { std::string method_name; GET_EXPECTED_ASYNC(isOk, request->get_property("invoke", method_name)); if (!isOk) { co_return make_unexpected<std::runtime_error>("method name is expected"); } auto r = std::make_shared<json_object>(); r->add_property("id", id); if ("login" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 1) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'login'"); } auto login = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!login) { co_return make_unexpected<std::runtime_error>("missing login argument at invoke method 'login'"); } CHECK_EXPECTED_ASYNC(co_await this->login(sp, r, login->value())); } else if ("log_head" == method_name) { CHECK_EXPECTED_ASYNC(co_await this->log_head(sp, r)); } else if ("upload" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'upload'"); } auto body_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!body_str) { co_return make_unexpected<std::runtime_error>("missing body argument at invoke method 'upload'"); } GET_EXPECTED_ASYNC(body, base64::to_bytes(body_str->value())); CHECK_EXPECTED_ASYNC(co_await this->upload(sp, r, body)); } else if ("looking_block" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() != 1) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'looking_block'"); } auto id_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!id_str) { co_return make_unexpected<std::runtime_error>("missing argument at invoke method 'looking_block'"); } GET_EXPECTED_ASYNC(obj_id, base64::to_bytes(id_str->value())); CHECK_EXPECTED_ASYNC(co_await this->looking_block(sp, r, obj_id)); } else if ("prepare_download" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() != dht::network::service::GENERATE_HORCRUX) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'download'"); } std::vector<const_data_buffer> object_ids; for (decltype(args->size()) i = 0; i < args->size(); ++i) { auto id_str = std::dynamic_pointer_cast<json_primitive>(args->get(i)); if (!id_str) { co_return make_unexpected<std::runtime_error>("missing argument at invoke method 'download'"); } GET_EXPECTED_ASYNC(obj_id, base64::to_bytes(id_str->value())); object_ids.push_back(obj_id); } CHECK_EXPECTED_ASYNC(co_await this->download(sp, r, object_ids)); } else if ("download" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() != dht::network::service::GENERATE_HORCRUX) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'download'"); } std::vector<const_data_buffer> object_ids; for(decltype(args->size()) i = 0; i < args->size(); ++i){ auto id_str = std::dynamic_pointer_cast<json_primitive>(args->get(i)); if (!id_str) { co_return make_unexpected<std::runtime_error>("missing argument at invoke method 'download'"); } GET_EXPECTED_ASYNC(obj_id, base64::to_bytes(id_str->value())); object_ids.push_back(obj_id); } CHECK_EXPECTED_ASYNC(co_await this->download(sp, r, object_ids)); } else if ("devices" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'devices'"); } auto owner_id_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!owner_id_str) { co_return make_unexpected<std::runtime_error>("missing body argument at invoke method 'devices'"); } GET_EXPECTED_ASYNC(owner_id, base64::to_bytes(owner_id_str->value())); CHECK_EXPECTED_ASYNC(co_await this->devices(sp, r, owner_id)); } else if ("broadcast" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'broadcast'"); } auto body_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!body_str || body_str->value().empty()) { co_return make_unexpected<std::runtime_error>("missing body argument at invoke method 'broadcast'"); } GET_EXPECTED_ASYNC(body, base64::to_bytes(body_str->value())); CHECK_EXPECTED_ASYNC(co_await this->broadcast(sp, r, body)); } else if ("get_channel_messages" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 1) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'get_channel_messages'"); } auto channel_id_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!channel_id_str) { co_return make_unexpected<std::runtime_error>("missing channel_id argument at invoke method 'get_channel_messages'"); } GET_EXPECTED_ASYNC(channel_id, base64::to_bytes(channel_id_str->value())); #undef max int64_t last_id = std::numeric_limits<int64_t>::max(); int limit = 1000; if (1 < args->size()) { auto last_id_str = std::dynamic_pointer_cast<json_primitive>(args->get(1)); if (!last_id_str) { co_return make_unexpected<std::runtime_error>("invalid last_id argument at invoke method 'get_channel_messages'"); } #ifdef _WIN32 last_id = _atoi64(last_id_str->value().c_str()); #else last_id = atoll(last_id_str->value().c_str()); #endif } if (2 < args->size()) { auto limit_str = std::dynamic_pointer_cast<json_primitive>(args->get(2)); if (!limit_str) { co_return make_unexpected<std::runtime_error>("invalid limit argument at invoke method 'get_channel_messages'"); } limit = atoi(limit_str->value().c_str()); if (limit > 1000) { limit = 1000; } } CHECK_EXPECTED_ASYNC(co_await this->get_channel_messages(sp, r, channel_id, last_id, limit)); } else if ("allocate_storage" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 2) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'allocate_storage'"); } auto public_key_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!public_key_str || public_key_str->value().empty()) { co_return make_unexpected<std::runtime_error>("missing public_key argument at invoke method 'allocate_storage'"); } GET_EXPECTED_ASYNC(public_key_der, base64::to_bytes(public_key_str->value())); GET_EXPECTED_ASYNC(public_key, asymmetric_public_key::parse_der(public_key_der)); auto folder = std::dynamic_pointer_cast<json_primitive>(args->get(1)); if (!folder || folder->value().empty()) { co_return make_unexpected<std::runtime_error>("missing folder argument at invoke method 'allocate_storage'"); } CHECK_EXPECTED_ASYNC(co_await this->allocate_storage(sp, r, std::move(public_key), foldername(folder->value()))); } else if ("subscribe" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 2) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'subscribe'"); } auto cb = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!cb) { co_return make_unexpected<std::runtime_error>("missing cb argument at invoke method 'subscribe'"); } auto method = std::dynamic_pointer_cast<json_primitive>(args->get(1)); if (!method) { co_return make_unexpected<std::runtime_error>("missing method argument at invoke method 'subscribe'"); } if ("channel" == method->value()) { auto channel_id = std::dynamic_pointer_cast<json_primitive>(args->get(2)); if (!channel_id) { co_return make_unexpected<std::runtime_error>("missing channel_id argument at invoke method 'subscribe/channel'"); } GET_EXPECTED_ASYNC(ch_id, base64::to_bytes(channel_id->value())); auto handler = this->subscribe_channel(sp, r, cb->value(), ch_id); post_tasks.push_back([sp, handler, output_stream]() { return handler->process(sp, output_stream); }); } else { co_return make_unexpected<std::runtime_error>("invalid subscription '" + method->value() + "'"); } if (!this->subscribe_timer_.is_started()) { CHECK_EXPECTED_ASYNC(this->start_timer(sp, output_stream)); } } else if ("balance" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 1) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'balance'"); } auto wallet_id_str = std::dynamic_pointer_cast<json_primitive>(args->get(0)); if (!wallet_id_str) { co_return make_unexpected<std::runtime_error>("missing cb argument at invoke method 'balance'"); } GET_EXPECTED_ASYNC(wallet_id, base64::to_bytes(wallet_id_str->value())); CHECK_EXPECTED_ASYNC(co_await this->get_balance(sp, r, std::move(wallet_id))); } else if ("statistics" == method_name) { CHECK_EXPECTED_ASYNC(co_await this->statistics(sp, r)); } else if ("distribution_map" == method_name) { auto args = std::dynamic_pointer_cast<json_array>(request->get_property("params")); if (!args || args->size() < 1) { co_return make_unexpected<std::runtime_error>("invalid arguments at invoke method 'distribution_map'"); } auto replica_array = std::dynamic_pointer_cast<json_array>(args->get(0)); if (!replica_array) { co_return make_unexpected<std::runtime_error>("missing replica_array argument at invoke method 'distribution_map'"); } std::list<const_data_buffer> replicas; for (size_t i = 0; i < replica_array->size(); ++i) { auto replica_str = std::dynamic_pointer_cast<json_primitive>(replica_array->get(i)); if (!replica_str) { co_return make_unexpected<std::runtime_error>("invalid item replica_array[" + std::to_string(i) + "] at invoke method 'distribution_map'"); } GET_EXPECTED_ASYNC(replica, base64::to_bytes(replica_str->value())); replicas.push_back(replica); } CHECK_EXPECTED_ASYNC(co_await this->get_distribution_map(sp, r, std::move(replicas))); } else { co_return make_unexpected<std::runtime_error>("invalid method '" + method_name + "'"); } co_return r; } vds::async_task<vds::expected<void>> vds::websocket_api::login( const vds::service_provider * sp, std::shared_ptr<json_object> result, std::string login) { CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [ login, result ](database_read_transaction & t)->expected<void> { orm::transaction_log_record_dbo t1; GET_EXPECTED(st, t.get_reader( t1.select(t1.id, t1.data) .order_by(db_desc_order(t1.order_no)))); WHILE_EXPECTED(st.execute()) const auto data = t1.data.get(st); GET_EXPECTED(block, transactions::transaction_block::create(data)); CHECK_EXPECTED(block.walk_messages( [login, &result](const transactions::create_user_transaction & message)->expected<bool> { if (login == message.user_email) { auto res = std::make_shared<json_object>(); CHECK_EXPECTED(res->add_property("public_key", message.user_public_key->str())); res->add_property("user_profile_id", base64::from_bytes(message.user_profile_id)); result->add_property("result", res); return false; } return true; })); WHILE_EXPECTED_END() return expected<void>(); })); if (!result->get_property("result")) { result->add_property("error", "User not found"); } co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::log_head( const vds::service_provider* sp, std::shared_ptr<json_object> result) { auto res = std::make_shared<json_array>(); CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [ res ](database_read_transaction& t)->expected<void> { orm::transaction_log_record_dbo t1; GET_EXPECTED(st, t.get_reader( t1.select(t1.id) .where(t1.state == orm::transaction_log_record_dbo::state_t::leaf))); std::list<const_data_buffer> leafs; WHILE_EXPECTED(st.execute()) { res->add(std::make_shared<json_primitive>(base64::from_bytes(t1.id.get(st)))); } WHILE_EXPECTED_END() return expected<void>(); })); result->add_property("result", res); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::upload(const vds::service_provider * sp, std::shared_ptr<json_object> result, const_data_buffer body) { GET_EXPECTED_ASYNC(info, co_await server_api(sp).upload_data(body)); auto res = std::make_shared<json_object>(); auto replicas = std::make_shared<json_array>(); for (const auto & p : info.replicas) { replicas->add(std::make_shared<json_primitive>(base64::from_bytes(p))); } res->add_property("replicas", replicas); res->add_property("hash", base64::from_bytes(info.data_hash)); res->add_property("replica_size", info.replica_size); result->add_property("result", res); co_return expected<void>(); } std::shared_ptr<vds::websocket_api::subscribe_handler> vds::websocket_api::subscribe_channel( const vds::service_provider * /*sp*/, std::shared_ptr<json_object> result, std::string cb, const_data_buffer channel_id) { result->add_property("result", "true"); auto handler = std::make_shared<subscribe_handler>(std::move(cb), std::move(channel_id)); this->subscribe_handlers_.push_back(handler); return handler; } vds::expected<void> vds::websocket_api::start_timer(const vds::service_provider * sp, std::shared_ptr<websocket_output> output_stream) { return this->subscribe_timer_.start(sp, std::chrono::seconds(10), [sp, this_ = this->weak_from_this(), target_ = std::weak_ptr<websocket_output>(output_stream)]()->async_task<expected<bool>> { auto pthis = this_.lock(); if (!pthis) { co_return false; } for (auto & handler : pthis->subscribe_handlers_) { CHECK_EXPECTED_ASYNC(co_await handler->process(sp, target_)); } co_return !sp->get_shutdown_event().is_shuting_down(); }); } vds::async_task<vds::expected<void>> vds::websocket_api::devices( const vds::service_provider * sp, std::shared_ptr<json_object> res, const_data_buffer owner_id) { auto result_json = std::make_shared<json_array>(); CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction([sp, result_json, owner_id](database_read_transaction & t) -> expected<void> { orm::node_storage_dbo t1; orm::local_data_dbo t2; db_value<int64_t> used_size; GET_EXPECTED(st, t.get_reader( t1.select( t1.storage_id, t1.local_path, t1.reserved_size, t1.usage_type, db_sum(t2.replica_size).as(used_size)) .left_join(t2, t2.storage_id == t1.storage_id) .where(t1.owner_id == owner_id) .group_by(t1.storage_id, t1.local_path, t1.reserved_size, t1.usage_type))); WHILE_EXPECTED(st.execute()) { if (!t1.local_path.get(st).empty()) { auto result_item = std::make_shared<json_object>(); result_item->add_property("id", base64::from_bytes(t1.storage_id.get(st))); result_item->add_property("local_path", t1.local_path.get(st)); result_item->add_property("reserved_size", t1.reserved_size.get(st)); result_item->add_property("used_size", used_size.get(st)); result_item->add_property("usage_type", std::to_string(t1.usage_type.get(st))); auto free_size_result = foldername(t1.local_path.get(st)).free_size(); if (free_size_result.has_value()) { result_item->add_property("free_size", free_size_result.value()); } result_json->add(result_item); } } WHILE_EXPECTED_END() return expected<void>(); })); res->add_property("result", result_json); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::get_channel_messages( const vds::service_provider * sp, std::shared_ptr<json_object> result, const_data_buffer channel_id, int64_t last_id, uint32_t limit) { auto items = std::make_shared<json_array>(); CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [ sp, this_ = this->weak_from_this(), channel_id, items, last_id, limit ](database_read_transaction & t)->expected<void> { auto pthis = this_.lock(); if (!pthis) { return expected<void>(); } orm::channel_message_dbo t1; GET_EXPECTED(st, t.get_reader(t1.select(t1.id, t1.block_id, t1.channel_id, t1.read_id, t1.write_id, t1.crypted_key, t1.crypted_data, t1.signature) .where(t1.channel_id == channel_id && t1.id < last_id).order_by(db_desc_order(t1.id)))); WHILE_EXPECTED(st.execute()) { auto item = std::make_shared<json_object>(); item->add_property("id", t1.id.get(st)); item->add_property("block_id", t1.block_id.get(st)); item->add_property("channel_id", t1.channel_id.get(st)); item->add_property("read_id", t1.read_id.get(st)); item->add_property("write_id", t1.write_id.get(st)); item->add_property("crypted_key", t1.crypted_key.get(st)); item->add_property("crypted_data", t1.crypted_data.get(st)); item->add_property("signature", t1.signature.get(st)); items->add(item); if (limit < items->size()) { break; } } WHILE_EXPECTED_END() return expected<void>(); })); result->add_property("result", items); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::allocate_storage( const vds::service_provider* sp, std::shared_ptr<json_object> result, asymmetric_public_key user_public_key, foldername folder) { GET_EXPECTED(json, json_parser::parse(".vds_storage.json", file::read_all(filename(folder, ".vds_storage.json")))); auto sign_info = std::dynamic_pointer_cast<json_object>(json); if (!sign_info) { return vds::make_unexpected<std::runtime_error>("Invalid format"); } std::string version; if (!sign_info->get_property("vds", version) || version != "0.1") { return vds::make_unexpected<std::runtime_error>("Invalid file version"); } std::string size_str; if (!sign_info->get_property("size", size_str)) { return vds::make_unexpected<std::runtime_error>("Missing size parameter"); } char* end; const auto size = std::strtoull(size_str.c_str(), &end, 10); if (size_str != std::to_string(size) || (nullptr != end && '\0' != *end)) { return vds::make_unexpected<std::runtime_error>("Invalid size parameter value " + size_str); } GET_EXPECTED(key_id, user_public_key.fingerprint()); const_data_buffer value; if (!sign_info->get_property("name", value) || value != key_id) { return vds::make_unexpected<std::runtime_error>("Invalid user name"); } std::string usage_type_str; if (!sign_info->get_property("usage", usage_type_str)) { return vds::make_unexpected<std::runtime_error>("Invalid folder usage"); } GET_EXPECTED(usage_type, orm::node_storage_dbo::parse_usage_type(usage_type_str)); if (!sign_info->get_property("sign", value)) { return vds::make_unexpected<std::runtime_error>("The signature is missing"); } auto sig_body = std::make_shared<json_object>(); sig_body->add_property("vds", "0.1"); sig_body->add_property("name", key_id); sig_body->add_property("size", size_str); sig_body->add_property("usage", std::to_string(usage_type)); GET_EXPECTED(body, sig_body->json_value::str()); GET_EXPECTED(sig_ok, asymmetric_sign_verify::verify( hash::sha256(), user_public_key, value, body.c_str(), body.length())); if (!sig_ok) { return vds::make_unexpected<std::runtime_error>("Invalid signature"); } return sp->get<db_model>()->async_transaction([sp, key_id, folder, size, usage_type, result](database_transaction& t) -> expected<void> { orm::node_storage_dbo t1; GET_EXPECTED(st, t.get_reader(t1.select(t1.storage_id, t1.reserved_size).where(t1.local_path == folder.full_name() && t1.owner_id == key_id))); GET_EXPECTED(exists, st.execute()); if (exists) { result->add_property("result", base64::from_bytes(t1.storage_id.get(st))); const auto current_size = t1.reserved_size.get(st); if (current_size != (int64_t)size) { return t.execute( t1 .update(t1.reserved_size = (int64_t)size) .where(t1.local_path == folder.full_name() && t1.owner_id == key_id)); } else { return expected<void>(); } } else { auto client = sp->get<dht::network::client>(); binary_serializer s; CHECK_EXPECTED(s << client->current_node_id()); CHECK_EXPECTED(s << key_id); CHECK_EXPECTED(s << folder.full_name()); GET_EXPECTED(storage_id, hash::signature(hash::sha256(), s.move_data())); result->add_property("result", base64::from_bytes(storage_id)); return t.execute( t1.insert( t1.storage_id = storage_id, t1.local_path = folder.full_name(), t1.owner_id = key_id, t1.reserved_size = (int64_t)size, t1.usage_type = usage_type)); } }); } vds::async_task<vds::expected<void>> vds::websocket_api::looking_block( const vds::service_provider* sp, std::shared_ptr<json_object> result, const_data_buffer data_hash) { CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [ data_hash, result ](database_read_transaction& t)->expected<void> { orm::chunk_replica_data_dbo t1; GET_EXPECTED(st, t.get_reader( t1.select(t1.replica, t1.replica_hash) .where(t1.object_hash == data_hash) .order_by(t1.replica))); auto res = std::make_shared<json_object>(); auto replicas = std::make_shared<json_array>(); size_t replica = 0; WHILE_EXPECTED(st.execute()) if (replica != t1.replica.get(st)) { return expected<void>(); } const auto id = base64::from_bytes(t1.replica_hash.get(st)); replicas->add(std::make_shared<json_primitive>(id)); ++replica; WHILE_EXPECTED_END() res->add_property("replicas", replicas); result->add_property("result", res); return expected<void>(); })); if (!result->get_property("result")) { const auto data_hash_str = base64::from_bytes(data_hash); result->add_property("error", "Data " + data_hash_str + " not found"); } co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::prepare_download( const vds::service_provider* sp, std::shared_ptr<json_object> result, std::vector<const_data_buffer> object_ids) { auto network_client = sp->get<dht::network::client>(); GET_EXPECTED_ASYNC(progress, co_await network_client->prepare_restore(object_ids)); result->add_property("result", progress); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::download( const vds::service_provider * sp, std::shared_ptr<json_object> result, std::vector<const_data_buffer> object_ids) { auto network_client = sp->get<dht::network::client>(); GET_EXPECTED_ASYNC(buffer, co_await network_client->restore(object_ids)); result->add_property("result", buffer); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::broadcast( const vds::service_provider* sp, std::shared_ptr<json_object> result, const_data_buffer body) { GET_EXPECTED_ASYNC(trx_id, co_await server_api(sp).broadcast(body, false)); result->add_property("result", trx_id); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::get_balance( const vds::service_provider* sp, std::shared_ptr<json_object> res, const_data_buffer wallet_id) { auto result_json = std::make_shared<json_array>(); CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [sp, result_json, wallet_id](database_read_transaction& t) -> expected<void> { orm::datacoin_balance_dbo t1; db_value<int64_t> confirmed_balance; db_value<int64_t> proposed_balance; GET_EXPECTED(st, t.get_reader( t1.select( t1.issuer, t1.currency, db_sum(t1.confirmed_balance).as(confirmed_balance), db_sum(t1.proposed_balance).as(proposed_balance)) .where(t1.owner == wallet_id) .group_by(t1.issuer, t1.currency))); WHILE_EXPECTED(st.execute()) { auto result_item = std::make_shared<json_object>(); result_item->add_property("issuer", base64::from_bytes(t1.issuer.get(st))); result_item->add_property("currency", t1.currency.get(st)); result_item->add_property("confirmed_balance", confirmed_balance.get(st)); result_item->add_property("proposed_balance", proposed_balance.get(st)); result_json->add(result_item); } WHILE_EXPECTED_END() return expected<void>(); })); res->add_property("result", result_json); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::statistics( const vds::service_provider* sp, std::shared_ptr<json_object> result) { const auto server = sp->get<vds::server>(); GET_EXPECTED_ASYNC(stat, co_await server->get_statistic()); result->add_property("result", stat.serialize()); co_return expected<void>(); } vds::async_task<vds::expected<void>> vds::websocket_api::get_distribution_map(const vds::service_provider* sp, std::shared_ptr<json_object> result, std::list<const_data_buffer> replicas) { return sp->get<db_model>()->async_read_transaction( [this, r = std::move(result), obj_ids = std::move(replicas)](database_read_transaction& t) -> expected<void> { std::map<const_data_buffer, std::vector<const_data_buffer>> replicas; for (const auto& data_hash : obj_ids) { orm::chunk_replica_data_dbo t1; GET_EXPECTED(st, t.get_reader( t1.select(t1.replica, t1.replica_hash) .where(t1.object_hash == data_hash) .order_by(t1.replica))); std::vector<const_data_buffer> replica; WHILE_EXPECTED(st.execute()) if (replica.size() != t1.replica.get(st)) { return expected<void>(); } replica.push_back(t1.replica_hash.get(st)); WHILE_EXPECTED_END() replicas[data_hash] = std::move(replica); } orm::sync_replica_map_dbo t8; auto result = std::make_shared<json_array>(); for (const auto& object_id : obj_ids) { auto item = std::make_shared<json_object>(); item->add_property("block", object_id); auto replica = std::make_shared<json_array>(); for (const auto& rep : replicas[object_id]) { auto rep_item = std::make_shared<json_object>(); rep_item->add_property("replica", rep); auto nodes = std::make_shared<json_array>(); GET_EXPECTED(st, t.get_reader(t8.select(t8.node).where(t8.replica_hash == rep))); WHILE_EXPECTED(st.execute()) { nodes->add(std::make_shared<json_primitive>(base64::from_bytes(t8.node.get(st)))); } WHILE_EXPECTED_END() rep_item->add_property("nodes", nodes); replica->add(rep_item); } item->add_property("replicas", replica); result->add(item); } r->add_property("result", result); return expected<void>(); }); } vds::websocket_api::subscribe_handler::subscribe_handler(std::string cb, const_data_buffer channel_id) : cb_(std::move(cb)), channel_id_(std::move(channel_id)), last_id_(0) { } vds::async_task<vds::expected<void>> vds::websocket_api::subscribe_handler::process( const vds::service_provider * sp, std::weak_ptr<websocket_output> output_stream) { auto items = std::make_shared<json_array>(); CHECK_EXPECTED_ASYNC(co_await sp->get<db_model>()->async_read_transaction( [ sp, this_ = this->weak_from_this(), output_stream, &items ](database_read_transaction & t)->expected<void> { auto pthis = this_.lock(); if (!pthis) { return expected<void>(); } orm::channel_message_dbo t1; GET_EXPECTED(st, t.get_reader(t1.select(t1.id, t1.block_id, t1.channel_id, t1.read_id, t1.write_id, t1.crypted_key, t1.crypted_data, t1.signature).where(t1.channel_id == pthis->channel_id_ && t1.id > pthis->last_id_).order_by(t1.id))); WHILE_EXPECTED(st.execute()) { pthis->last_id_ = t1.id.get(st); auto item = std::make_shared<json_object>(); item->add_property("id", t1.id.get(st)); item->add_property("block_id", t1.block_id.get(st)); item->add_property("channel_id", t1.channel_id.get(st)); item->add_property("read_id", t1.read_id.get(st)); item->add_property("write_id", t1.write_id.get(st)); item->add_property("crypted_key", t1.crypted_key.get(st)); item->add_property("crypted_data", t1.crypted_data.get(st)); item->add_property("signature", t1.signature.get(st)); items->add(item); } WHILE_EXPECTED_END() return expected<void>(); })); if (0 < items->size()) { auto output_stream_ = output_stream.lock(); if (output_stream_) { auto result = std::make_shared<json_object>(); result->add_property("id", this->cb_); result->add_property("result", items); GET_EXPECTED_ASYNC(result_str, result->json_value::str()); GET_EXPECTED_ASYNC(stream, co_await output_stream_->start(result_str.length(), false)); CHECK_EXPECTED_ASYNC(co_await stream->write_async((const uint8_t *)result_str.c_str(), result_str.length())); } } co_return expected<void>(); }
mit
AndrewWPhillips/HexEdit
HexEdit/CalcDlg.cpp
1
137400
// CalcDlg.cpp : implements the Goto/Calculator dialog // // Copyright (c) 2015 by Andrew W. Phillips. // // This file is distributed under the MIT license, which basically says // you can do what you want with it and I take no responsibility for bugs. // See http://www.opensource.org/licenses/mit-license.php for full details. // // Notes // The calculator dialog is handled here (CCalcDlg) but there are some related classes: // CCalcEdit - handles the text box where values are entered and results displayed // CCalcComboBox - combo that contains the edit box and provides the history list // CCalcListBox - list part of combo (used for displaying a tip window with result value) // CCalcBits - displays boxes showinh the bottom 64 bits (in an integer value) // CCalcButton - base class for all calculator buttons // // The "current value" of the calculator is stored in this class (CCalcDlg) in: // state_ - says whether the value is an integer or other type of value, is a literal // or expression, is a result (including error/overflow) or is being edited // current_ - current value if it's a simple integer literal (ie, state_ <= CALCINTLIT) // current_str_ - current value as a string if not an integer or is an int expression // Also if there is a pending binary operation then these members are also relevant: // previous_ - values of left side of operation // op_ - the binary operation // // The edit box is used to display results by setting current/current_str_ and state_ // and calling CCalcEdit::put. // #include "stdafx.h" #include <cmath> #include "HexEdit.h" #include "MainFrm.h" #include "HexEditDoc.h" #include "HexEditView.h" #include "CalcDlg.h" #include "Misc.h" #include "SystemSound.h" #include "resource.hm" // Help IDs #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCalcBits IMPLEMENT_DYNAMIC(CCalcBits, CWnd) BEGIN_MESSAGE_MAP(CCalcBits, CWnd) ON_WM_SIZE() ON_WM_ERASEBKGND() ON_WM_LBUTTONDOWN() END_MESSAGE_MAP() void CCalcBits::OnSize(UINT nType, int cx, int cy) // WM_SIZE { CWnd::OnSize(nType, cx, cy); Invalidate(); } // Draw the images for the bits in the erase background event BOOL CCalcBits::OnEraseBkgnd(CDC* pDC) { CRect rct; // used for drawing/fills etc and for calculations GetClientRect(&rct); pDC->FillSolidRect(rct, afxGlobalData.clrBarFace); //pDC->FillRect(&rct, CBrush::FromHandle((HBRUSH)GetStockObject(WHITE_BRUSH))); // Don't show anything if it's not an int if (m_pParent->state_ == CALCERROR || m_pParent->state_ >= CALCINTEXPR) return TRUE; int wndHeight = rct.Height(); calc_widths(rct); COLORREF base_colour = m_pParent->radix_ == 16 ? ::BestHexAddrCol() : m_pParent->radix_ == 10 ? ::BestDecAddrCol() : ::GetSysColor(COLOR_BTNTEXT); base_colour = ::same_hue(base_colour, 100, 35); COLORREF disabled_colour = ::tone_down(base_colour, ::afxGlobalData.clrBarFace, 0.6); COLORREF enabled_colour = ::add_contrast(base_colour, ::afxGlobalData.clrBarFace); // Set up the graphics objects we need for drawing the bits //CPen penDisabled(PS_SOLID, 0, ::tone_down(::GetSysColor(COLOR_BTNTEXT), ::afxGlobalData.clrBarFace, 0.7)); //CPen penEnabled (PS_SOLID, 0, ::GetSysColor(COLOR_BTNTEXT)); CPen penDisabled(PS_SOLID, 0, disabled_colour); CPen penEnabled (PS_SOLID, 0, enabled_colour); CFont font; LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); lf.lfHeight = 10; strcpy(lf.lfFaceName, "Tahoma"); // Simple font for small digits font.CreateFontIndirect(&lf); CFont *pOldFont = (CFont *)pDC->SelectObject(&font); // Start off with disabled colours as we draw from left (disabled side first) COLORREF colour = ::tone_down(base_colour, ::afxGlobalData.clrBarFace, 0.8); CPen * pOldPen = (CPen*) pDC->SelectObject(&penDisabled); bool enabled = false; // We need this so Rectangle() does not fill CBrush * pOldBrush = pDC->SelectObject(CBrush::FromHandle((HBRUSH)GetStockObject(NULL_BRUSH))); // Draw bits from left to right int horz = 1; // current horizontal position // Work out the size of one bit's image and the position of the left (most sig.) bit rct.left = horz; rct.right = rct.left + m_ww - 1; // Subtract 1 to leave (at least) one pixel between each bit rct.top = 1; rct.bottom = rct.top + m_hh; unsigned __int64 val; // If showing result after binop button pressed then previous_ has the displayed value if (m_pParent->state_ == CALCINTBINARY && m_pParent->op_ != binop_none) val = mpz_get_ui64(m_pParent->previous_.get_mpz_t()); else val = mpz_get_ui64(m_pParent->current_.get_mpz_t()); for (int bnum = 63; bnum >= 0; bnum--) { // When we hit the first enabled bit switch to the darker pen if (!enabled && (bnum < m_pParent->bits_ || m_pParent->bits_ == 0)) { pDC->SelectObject(&penEnabled); colour = enabled_colour; enabled = true; } if ( (val & ((__int64)1<<bnum)) != 0) pDC->FillSolidRect(rct, colour); pDC->Rectangle(&rct); // Draw numbers underneath some digits if (m_hh < wndHeight - 10 && (bnum%8 == 0 || bnum == 63)) { char buf[4]; sprintf(buf, "%d", bnum); pDC->SetTextColor(colour); pDC->SetBkColor(afxGlobalData.clrBarFace); pDC->TextOut(horz, m_hh + 1, buf, strlen(buf)); } // Move horizontally to next bit position horz += m_ww + spacing(bnum); rct.MoveToX(horz); } pDC->SelectObject(pOldBrush); pDC->SelectObject(pOldPen); pDC->SelectObject(pOldFont); return TRUE; } // Toggle a bit when clicked on (and enabled) void CCalcBits::OnLButtonDown(UINT nFlags, CPoint point) { int bnum; if (m_pParent->state_ > CALCERROR && m_pParent->state_ <= CALCINTLIT && // currently displaying an int (bnum = pos2bit(point)) > -1 && // valid bit clicked on (m_pParent->bits_ == 0 || bnum < m_pParent->bits_)) // not a disabled bit { ASSERT(bnum < 64 && bnum >= 0); mpz_class val = m_pParent->current_; mpz_combit(val.get_mpz_t(), bnum); m_pParent->Set(val); } CWnd::OnLButtonDown(nFlags, point); } // Used to decide horizontal positions of the bits int CCalcBits::spacing(int bnum) { int retval = 0; if (bnum%4 == 0) retval += m_nn; if (bnum%8 == 0) retval += m_bb; if (bnum%16 == 0) retval += m_cc; return retval; } // Work out where the bit images are to be displayed based on the width of the control void CCalcBits::calc_widths(CRect & rct) { m_ww = rct.Width()/70; // width of display for one bit ASSERT(m_ww > 3); m_hh = 4 + (rct.Height() - 6)/2; if (m_hh < 7) m_hh = 7; else if (m_hh > 16) m_hh = 16; if (m_hh > rct.Height() - 1) m_hh = rct.Height() - 1; m_nn = (rct.Width()-m_ww*64)/22; // sep between nybbles = half of rest split ~15 ways m_bb = (rct.Width()-m_ww*64-m_nn*16)/10; // sep between bytes = half of rest split ~7 ways m_cc = (rct.Width()-m_ww*64-m_nn*16-m_bb*8)/3; // sep between words = rest of space split 3 ways ASSERT(m_nn > 0 && m_bb > 0 && m_cc > 0); // sanity check } // Given a child window position (point) works out which bit is beneath it. // Returns the bit (0 to 63) or -1 if none. int CCalcBits::pos2bit(CPoint point) { if (point.y <= 0 && point.y >= m_hh - 1) return -1; // above or below // We use an iterative algorithm rather than calculate the bit directly, // as it is simpler, more maintainable (re-uses spacing() func as used above) // and should be more than fast enough for a user initiated action. int horz = 1; for (int bnum = 63; bnum >= 0; bnum--) { if (point.x < horz) return -1; // must be in a gap between two bits if (point.x < horz + m_ww - 1) return bnum; horz += m_ww + spacing(bnum); } return -1; } ///////////////////////////////////////////////////////////////////////////// // CCalcDlg dialog CCalcDlg::CCalcDlg(CWnd* pParent /*=NULL*/) : CDialog(), ctl_calc_bits_(this), purple_pen(PS_SOLID, 0, RGB(0x80, 0, 0x80)) { inited_ = false; aa_ = dynamic_cast<CHexEditApp *>(AfxGetApp()); m_sizeInitial = CSize(-1, -1); help_hwnd_ = (HWND)0; source_ = km_result; op_ = binop_none; previous_unary_op_ = unary_none; current_ = previous_ = 0; state_ = CALCINTRES; radix_ = bits_ = -1; // Set to -1 so they are set up correctly edit_.pp_ = this; // Set parent of edit control ctl_edit_combo_.pp_ = this; m_first = true; } BOOL CCalcDlg::Create(CWnd* pParentWnd /*=NULL*/) { mm_ = dynamic_cast<CMainFrame *>(AfxGetMainWnd()); if (!CDialog::Create(MAKEINTRESOURCE(IDD), pParentWnd)) // IDD_CALC { TRACE0("Failed to create Calculator dialog\n"); return FALSE; // failed to create } // Subclass the main calculator edit box CWnd *pwnd = ctl_edit_combo_.GetWindow(GW_CHILD); ASSERT(pwnd != NULL); VERIFY(edit_.SubclassWindow(pwnd->m_hWnd)); LONG style = ::GetWindowLong(edit_.m_hWnd, GWL_STYLE); ::SetWindowLong(edit_.m_hWnd, GWL_STYLE, style | ES_RIGHT | ES_WANTRETURN); // Get last used settings from registry change_base(aa_->GetProfileInt("Calculator", "Base", 16)); change_bits(aa_->GetProfileInt("Calculator", "Bits", 32)); change_signed(aa_->GetProfileInt("Calculator", "signed", 0) ? true : false); current_.set_str(aa_->GetProfileString("Calculator", "Current", "0"), 10); state_ = CALCINTUNARY; edit_.put(); edit_.get(); set_right(); memory_.set_str(aa_->GetProfileString("Calculator", "Memory", "0"), 10); // If saved memory value was restored then make it available if (memory_ != 0) button_colour(GetDlgItem(IDC_MEM_GET), true, RGB(0x40, 0x40, 0x40)); // Special setup for "GO" button ctl_go_.SetMouseCursorHand(); // Indicates that GO button takes user back to file ctl_go_.m_bDefaultClick = TRUE; // Default click goes to address (also drop-down menu for go sector etc) ctl_go_.m_bOSMenu = FALSE; VERIFY(go_menu_.LoadMenu(IDR_CALC_GO)); ctl_go_.m_hMenu = go_menu_.GetSubMenu(0)->GetSafeHmenu(); // Add drop-down menu (handled by checking m_nMenuResult in button click event - see OnGo) // Since functions menu doesn't change we only need to set it up once (load from resources) VERIFY(func_menu_.LoadMenu(IDR_FUNCTION)); ctl_func_.m_hMenu = func_menu_.GetSubMenu(0)->GetSafeHmenu(); setup_tooltips(); setup_expr(); setup_static_buttons(); ((CSpinButtonCtrl *)GetDlgItem(IDC_SPIN_RADIX))->SetRange(2, 36); ((CSpinButtonCtrl *)GetDlgItem(IDC_SPIN_BITS))->SetRange(0, 32767); // 0=Inf // ------------ Set up the "bits" child window ------------ static CString bitsClass; if (bitsClass.IsEmpty()) { // Register new window class bitsClass = AfxRegisterWndClass(0); ASSERT(!bitsClass.IsEmpty()); } CRect rct; // New window location ASSERT(GetDlgItem(IDC_BITS_PLACEHOLDER) != NULL); GetDlgItem(IDC_BITS_PLACEHOLDER)->GetWindowRect(&rct); ScreenToClient(&rct); DWORD bitsStyle = WS_CHILD | WS_VISIBLE; VERIFY(ctl_calc_bits_.Create(bitsClass, NULL, bitsStyle, rct, this, IDC_CALC_BITS)); ctl_calc_bits_.SetWindowPos(&wndTop, 0, 0, 0, 0, SWP_NOACTIVATE|SWP_NOMOVE|SWP_NOREDRAW|SWP_NOSIZE|SWP_NOOWNERZORDER); // ----------- Set up resizer control ---------------- // (See also setup_resizer - called the first time OnKickIdle is called.) // We must set the 4th parameter true else we get a resize border // added to the dialog and this really stuffs things up inside a pane. m_resizer.Create(GetSafeHwnd(), TRUE, 100, TRUE); // It needs an initial size for it's calcs GetWindowRect(&rct); m_resizer.SetInitialSize(rct.Size()); rct.bottom = rct.top + (rct.bottom - rct.top)*3/4; m_resizer.SetMinimumTrackingSize(rct.Size()); check_for_error(); // check for overflow of restored value edit_.put(); //edit_.get(); // current_str_ already contains the restored value set_right(); inited_ = true; return TRUE; } LRESULT CCalcDlg::HandleInitDialog(WPARAM wParam, LPARAM lParam) { CDialog::HandleInitDialog(wParam, lParam); return TRUE; } // HandleInitDialog // called from UpdateData void CCalcDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_EDIT, ctl_edit_combo_); DDX_Control(pDX, IDC_DIGIT_0, ctl_digit_0_); DDX_Control(pDX, IDC_DIGIT_1, ctl_digit_1_); DDX_Control(pDX, IDC_DIGIT_2, ctl_digit_2_); DDX_Control(pDX, IDC_DIGIT_3, ctl_digit_3_); DDX_Control(pDX, IDC_DIGIT_4, ctl_digit_4_); DDX_Control(pDX, IDC_DIGIT_5, ctl_digit_5_); DDX_Control(pDX, IDC_DIGIT_6, ctl_digit_6_); DDX_Control(pDX, IDC_DIGIT_7, ctl_digit_7_); DDX_Control(pDX, IDC_DIGIT_8, ctl_digit_8_); DDX_Control(pDX, IDC_DIGIT_9, ctl_digit_9_); DDX_Control(pDX, IDC_DIGIT_A, ctl_digit_a_); DDX_Control(pDX, IDC_DIGIT_B, ctl_digit_b_); DDX_Control(pDX, IDC_DIGIT_C, ctl_digit_c_); DDX_Control(pDX, IDC_DIGIT_D, ctl_digit_d_); DDX_Control(pDX, IDC_DIGIT_E, ctl_digit_e_); DDX_Control(pDX, IDC_DIGIT_F, ctl_digit_f_); DDX_Control(pDX, IDC_MEM_GET, ctl_mem_get_); DDX_Control(pDX, IDC_MARK_GET, ctl_mark_get_); DDX_Control(pDX, IDC_SEL_GET, ctl_sel_get_); DDX_Control(pDX, IDC_SEL_AT, ctl_sel_at_); DDX_Control(pDX, IDC_SEL_LEN, ctl_sel_len_); DDX_Control(pDX, IDC_MARK_AT, ctl_mark_at_); DDX_Control(pDX, IDC_EOF_GET, ctl_eof_get_); DDX_Control(pDX, IDC_BACKSPACE, ctl_backspace_); DDX_Control(pDX, IDC_CLEAR_ENTRY, ctl_clear_entry_); DDX_Control(pDX, IDC_CLEAR, ctl_clear_); DDX_Control(pDX, IDC_EQUALS, ctl_equals_); DDX_Control(pDX, IDC_AND, ctl_and_); DDX_Control(pDX, IDC_ASR, ctl_asr_); DDX_Control(pDX, IDC_DIVIDE, ctl_divide_); DDX_Control(pDX, IDC_LSL, ctl_lsl_); DDX_Control(pDX, IDC_LSR, ctl_lsr_); DDX_Control(pDX, IDC_ROL, ctl_rol_); DDX_Control(pDX, IDC_ROR, ctl_ror_); DDX_Control(pDX, IDC_XOR, ctl_xor_); DDX_Control(pDX, IDC_MOD, ctl_mod_); DDX_Control(pDX, IDC_MULTIPLY, ctl_multiply_); DDX_Control(pDX, IDC_OR, ctl_or_); DDX_Control(pDX, IDC_UNARY_DEC, ctl_unary_dec_); DDX_Control(pDX, IDC_UNARY_FACTORIAL, ctl_unary_factorial_); DDX_Control(pDX, IDC_UNARY_FLIP, ctl_unary_flip_); DDX_Control(pDX, IDC_UNARY_REV, ctl_unary_rev_); DDX_Control(pDX, IDC_UNARY_INC, ctl_unary_inc_); DDX_Control(pDX, IDC_UNARY_NOT, ctl_unary_not_); DDX_Control(pDX, IDC_UNARY_SIGN, ctl_unary_sign_); DDX_Control(pDX, IDC_UNARY_SQUARE, ctl_unary_square_); DDX_Control(pDX, IDC_SUBTRACT, ctl_subtract_); DDX_Control(pDX, IDC_MEM_CLEAR, ctl_mem_clear_); DDX_Control(pDX, IDC_MEM_ADD, ctl_mem_add_); DDX_Control(pDX, IDC_MEM_SUBTRACT, ctl_mem_subtract_); DDX_Control(pDX, IDC_MARK_ADD, ctl_mark_add_); DDX_Control(pDX, IDC_MARK_SUBTRACT, ctl_mark_subtract_); DDX_Control(pDX, IDC_GTR, ctl_gtr_); DDX_Control(pDX, IDC_LESS, ctl_less_); DDX_Control(pDX, IDC_POW, ctl_pow_); DDX_Control(pDX, IDC_MARK_AT_STORE, ctl_mark_at_store_); DDX_Control(pDX, IDC_MARK_CLEAR, ctl_mark_clear_); DDX_Control(pDX, IDC_MARK_STORE, ctl_mark_store_); DDX_Control(pDX, IDC_MEM_STORE, ctl_mem_store_); DDX_Control(pDX, IDC_SEL_AT_STORE, ctl_sel_at_store_); DDX_Control(pDX, IDC_SEL_STORE, ctl_sel_store_); DDX_Control(pDX, IDC_UNARY_ROL, ctl_unary_rol_); DDX_Control(pDX, IDC_UNARY_ROR, ctl_unary_ror_); DDX_Control(pDX, IDC_UNARY_LSL, ctl_unary_lsl_); DDX_Control(pDX, IDC_UNARY_LSR, ctl_unary_lsr_); DDX_Control(pDX, IDC_UNARY_ASR, ctl_unary_asr_); DDX_Control(pDX, IDC_UNARY_CUBE, ctl_unary_cube_); DDX_Control(pDX, IDC_UNARY_AT, ctl_unary_at_); DDX_Control(pDX, IDC_UNARY_SQUARE_ROOT, ctl_unary_square_root_); DDX_Control(pDX, IDC_SEL_LEN_STORE, ctl_sel_len_store_); DDX_Control(pDX, IDC_ADDOP, ctl_addop_); DDX_Control(pDX, IDC_GO, ctl_go_); DDX_Control(pDX, IDC_HEX_HIST, ctl_hex_hist_); DDX_Control(pDX, IDC_DEC_HIST, ctl_dec_hist_); DDX_Control(pDX, IDC_VARS, ctl_vars_); DDX_Control(pDX, IDC_FUNC, ctl_func_); } // DoDataExchange BEGIN_MESSAGE_MAP(CCalcDlg, CDialog) ON_WM_CREATE() ON_WM_DESTROY() ON_WM_SIZE() ON_WM_HELPINFO() ON_WM_CONTEXTMENU() ON_WM_DRAWITEM() ON_WM_ERASEBKGND() ON_WM_CTLCOLOR() ON_NOTIFY(TTN_SHOW, 0, OnTooltipsShow) ON_MESSAGE(WM_KICKIDLE, OnKickIdle) ON_MESSAGE(WM_INITDIALOG, HandleInitDialog) ON_BN_CLICKED(IDC_DIGIT_0, OnDigit0) ON_BN_CLICKED(IDC_DIGIT_1, OnDigit1) ON_BN_CLICKED(IDC_DIGIT_2, OnDigit2) ON_BN_CLICKED(IDC_DIGIT_3, OnDigit3) ON_BN_CLICKED(IDC_DIGIT_4, OnDigit4) ON_BN_CLICKED(IDC_DIGIT_5, OnDigit5) ON_BN_CLICKED(IDC_DIGIT_6, OnDigit6) ON_BN_CLICKED(IDC_DIGIT_7, OnDigit7) ON_BN_CLICKED(IDC_DIGIT_8, OnDigit8) ON_BN_CLICKED(IDC_DIGIT_9, OnDigit9) ON_BN_CLICKED(IDC_DIGIT_A, OnDigitA) ON_BN_CLICKED(IDC_DIGIT_B, OnDigitB) ON_BN_CLICKED(IDC_DIGIT_C, OnDigitC) ON_BN_CLICKED(IDC_DIGIT_D, OnDigitD) ON_BN_CLICKED(IDC_DIGIT_E, OnDigitE) ON_BN_CLICKED(IDC_DIGIT_F, OnDigitF) ON_BN_CLICKED(IDC_BACKSPACE, OnBackspace) ON_BN_CLICKED(IDC_CLEAR_ENTRY, OnClearEntry) ON_BN_CLICKED(IDC_CLEAR, OnClear) ON_BN_CLICKED(IDC_EQUALS, OnEquals) ON_BN_CLICKED(IDC_AND, OnAnd) ON_BN_CLICKED(IDC_ASR, OnAsr) ON_BN_CLICKED(IDC_DIVIDE, OnDivide) ON_BN_CLICKED(IDC_LSL, OnLsl) ON_BN_CLICKED(IDC_LSR, OnLsr) ON_BN_CLICKED(IDC_ROL, OnRol) ON_BN_CLICKED(IDC_ROR, OnRor) ON_BN_CLICKED(IDC_XOR, OnXor) ON_BN_CLICKED(IDC_MOD, OnMod) ON_BN_CLICKED(IDC_MULTIPLY, OnMultiply) ON_BN_CLICKED(IDC_OR, OnOr) ON_BN_CLICKED(IDC_UNARY_DEC, OnUnaryDec) ON_BN_CLICKED(IDC_UNARY_FACTORIAL, OnUnaryFactorial) ON_BN_CLICKED(IDC_UNARY_FLIP, OnUnaryFlip) ON_BN_CLICKED(IDC_UNARY_REV, OnUnaryRev) ON_BN_CLICKED(IDC_UNARY_INC, OnUnaryInc) ON_BN_CLICKED(IDC_UNARY_NOT, OnUnaryNot) ON_BN_CLICKED(IDC_UNARY_SIGN, OnUnarySign) ON_BN_CLICKED(IDC_UNARY_SQUARE, OnUnarySquare) ON_BN_CLICKED(IDC_SUBTRACT, OnSubtract) ON_BN_CLICKED(IDC_GO, OnGo) ON_BN_CLICKED(IDC_MEM_GET, OnMemGet) ON_BN_CLICKED(IDC_MEM_CLEAR, OnMemClear) ON_BN_CLICKED(IDC_MEM_ADD, OnMemAdd) ON_BN_CLICKED(IDC_MEM_SUBTRACT, OnMemSubtract) ON_BN_CLICKED(IDC_MARK_GET, OnMarkGet) ON_BN_CLICKED(IDC_MARK_AT, OnMarkAt) ON_BN_CLICKED(IDC_MARK_ADD, OnMarkAdd) ON_BN_CLICKED(IDC_MARK_SUBTRACT, OnMarkSubtract) ON_BN_CLICKED(IDC_SEL_GET, OnSelGet) ON_BN_CLICKED(IDC_SEL_AT, OnSelAt) ON_BN_CLICKED(IDC_EOF_GET, OnEofGet) ON_BN_CLICKED(IDC_GTR, OnGtr) ON_BN_CLICKED(IDC_LESS, OnLess) ON_BN_CLICKED(IDC_POW, OnPow) ON_BN_CLICKED(IDC_MARK_AT_STORE, OnMarkAtStore) ON_BN_CLICKED(IDC_MARK_CLEAR, OnMarkClear) ON_BN_CLICKED(IDC_MARK_STORE, OnMarkStore) ON_BN_CLICKED(IDC_MEM_STORE, OnMemStore) ON_BN_CLICKED(IDC_SEL_AT_STORE, OnSelAtStore) ON_BN_CLICKED(IDC_SEL_STORE, OnSelStore) ON_BN_CLICKED(IDC_UNARY_ROL, OnUnaryRol) ON_BN_CLICKED(IDC_UNARY_ROR, OnUnaryRor) ON_BN_CLICKED(IDC_UNARY_LSL, OnUnaryLsl) ON_BN_CLICKED(IDC_UNARY_LSR, OnUnaryLsr) ON_BN_CLICKED(IDC_UNARY_ASR, OnUnaryAsr) ON_BN_CLICKED(IDC_UNARY_CUBE, OnUnaryCube) ON_BN_CLICKED(IDC_UNARY_AT, OnUnaryAt) ON_BN_CLICKED(IDC_UNARY_SQUARE_ROOT, OnUnarySquareRoot) ON_BN_CLICKED(IDC_8BIT, On8bit) ON_BN_CLICKED(IDC_16BIT, On16bit) ON_BN_CLICKED(IDC_32BIT, On32bit) ON_BN_CLICKED(IDC_64BIT, On64bit) ON_BN_CLICKED(IDC_INFBIT, OnInfbit) ON_BN_CLICKED(IDC_BINARY, OnBinary) ON_BN_CLICKED(IDC_OCTAL, OnOctal) ON_BN_CLICKED(IDC_DECIMAL, OnDecimal) ON_BN_CLICKED(IDC_HEX, OnHex) ON_BN_CLICKED(IDC_SEL_LEN, OnSelLen) ON_BN_CLICKED(IDC_SEL_LEN_STORE, OnSelLenStore) ON_BN_CLICKED(IDC_ADDOP, OnAdd) // Removed ON_BN_DOUBLECLICKED stuff as d-click now seems to send two // mouse down/up events (as well as a dclick event) //ON_BN_DOUBLECLICKED(IDC_BACKSPACE, OnBackspace) ... ON_BN_CLICKED(IDC_BIG_ENDIAN_FILE_ACCESS, OnBigEndian) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_HEX_HIST, OnGetHexHist) ON_BN_CLICKED(IDC_DEC_HIST, OnGetDecHist) ON_BN_CLICKED(IDC_VARS, OnGetVar) ON_BN_CLICKED(IDC_FUNC, OnGetFunc) ON_CBN_SELCHANGE(IDC_EDIT, OnSelHistory) //ON_WM_DELETEITEM() // OnDeleteItem - message only sent for owner draw list boxes ON_EN_CHANGE(IDC_RADIX, OnChangeRadix) ON_EN_CHANGE(IDC_BITS, OnChangeBits) ON_BN_CLICKED(IDC_CALC_SIGNED, OnChangeSigned) END_MESSAGE_MAP() // Control ID and corresp help ID - used for popup context help static DWORD id_pairs[] = { IDC_EDIT, HIDC_EDIT, IDC_OP_DISPLAY, HIDC_OP_DISPLAY, IDC_BIG_ENDIAN_FILE_ACCESS, HIDC_BIG_ENDIAN_FILE_ACCESS, IDC_HEX, HIDC_HEX, IDC_DECIMAL, HIDC_DECIMAL, IDC_OCTAL, HIDC_OCTAL, IDC_BINARY, HIDC_BINARY, IDC_INFBIT, HIDC_INFBIT, IDC_64BIT, HIDC_64BIT, IDC_32BIT, HIDC_32BIT, IDC_16BIT, HIDC_16BIT, IDC_8BIT, HIDC_8BIT, IDC_MEM_GET, HIDC_MEM_GET, IDC_MEM_STORE, HIDC_MEM_STORE, IDC_MEM_CLEAR, HIDC_MEM_CLEAR, IDC_MEM_ADD, HIDC_MEM_ADD, IDC_MEM_SUBTRACT, HIDC_MEM_SUBTRACT, IDC_BACKSPACE, HIDC_BACKSPACE, IDC_CLEAR_ENTRY, HIDC_CLEAR_ENTRY, IDC_CLEAR, HIDC_CLEAR, IDC_MARK_GET, HIDC_MARK_GET, IDC_MARK_STORE, HIDC_MARK_STORE, IDC_MARK_CLEAR, HIDC_MARK_CLEAR, IDC_MARK_ADD, HIDC_MARK_ADD, IDC_MARK_SUBTRACT, HIDC_MARK_SUBTRACT, IDC_MARK_AT, HIDC_MARK_AT, IDC_MARK_AT_STORE, HIDC_MARK_AT_STORE, IDC_SEL_GET, HIDC_SEL_GET, IDC_SEL_STORE, HIDC_SEL_STORE, IDC_SEL_AT, HIDC_SEL_AT, IDC_SEL_AT_STORE, HIDC_SEL_AT_STORE, IDC_SEL_LEN, HIDC_SEL_LEN, IDC_SEL_LEN_STORE, HIDC_SEL_LEN_STORE, IDC_EOF_GET, HIDC_EOF_GET, IDC_UNARY_SQUARE, HIDC_UNARY_SQUARE, IDC_UNARY_SQUARE_ROOT, HIDC_UNARY_SQUARE_ROOT, IDC_UNARY_CUBE, HIDC_UNARY_CUBE, IDC_UNARY_FACTORIAL, HIDC_UNARY_FACTORIAL, IDC_UNARY_AT, HIDC_UNARY_AT, IDC_UNARY_ROL, HIDC_UNARY_ROL, IDC_UNARY_ROR, HIDC_UNARY_ROR, IDC_UNARY_LSL, HIDC_UNARY_LSL, IDC_UNARY_LSR, HIDC_UNARY_LSR, IDC_UNARY_ASR, HIDC_UNARY_ASR, IDC_UNARY_REV, HIDC_UNARY_REV, IDC_UNARY_NOT, HIDC_UNARY_NOT, IDC_UNARY_INC, HIDC_UNARY_INC, IDC_UNARY_DEC, HIDC_UNARY_DEC, IDC_UNARY_FLIP, HIDC_UNARY_FLIP, IDC_UNARY_SIGN, HIDC_UNARY_SIGN, IDC_EQUALS, HIDC_EQUALS, IDC_POW, HIDC_POW, IDC_MOD, HIDC_MOD, IDC_DIVIDE, HIDC_DIVIDE, IDC_MULTIPLY, HIDC_MULTIPLY, IDC_SUBTRACT, HIDC_SUBTRACT, IDC_ADDOP, HIDC_ADDOP, IDC_GTR, HIDC_GTR, IDC_LESS, HIDC_LESS, IDC_AND, HIDC_AND, IDC_OR, HIDC_OR, IDC_XOR, HIDC_XOR, IDC_ROL, HIDC_ROL, IDC_ROR, HIDC_ROR, IDC_LSL, HIDC_LSL, IDC_LSR, HIDC_LSR, IDC_ASR, HIDC_ASR, IDC_GO, HIDC_GO, IDC_DIGIT_0, HIDC_DIGIT_0, IDC_DIGIT_1, HIDC_DIGIT_0, IDC_DIGIT_2, HIDC_DIGIT_0, IDC_DIGIT_3, HIDC_DIGIT_0, IDC_DIGIT_4, HIDC_DIGIT_0, IDC_DIGIT_5, HIDC_DIGIT_0, IDC_DIGIT_6, HIDC_DIGIT_0, IDC_DIGIT_7, HIDC_DIGIT_0, IDC_DIGIT_8, HIDC_DIGIT_0, IDC_DIGIT_9, HIDC_DIGIT_0, IDC_DIGIT_A, HIDC_DIGIT_0, IDC_DIGIT_B, HIDC_DIGIT_0, IDC_DIGIT_C, HIDC_DIGIT_0, IDC_DIGIT_D, HIDC_DIGIT_0, IDC_DIGIT_E, HIDC_DIGIT_0, IDC_DIGIT_F, HIDC_DIGIT_0, 0,0 }; // Set focus to text control and move caret to end void CCalcDlg::StartEdit() { edit_.SetFocus(); //edit_.SetSel(edit_.GetWindowTextLength(), -1); // move caret to end edit_.SetSel(0, -1); // select all } // Save a calculator value to the current macro // If a value (ss) is specified save it else save the current calc value as a string void CCalcDlg::save_value_to_macro(CString ss /*= CString()*/) { if (ss.IsEmpty()) ss = current_str_; if (source_ == km_user_str && state_ >= CALCINTEXPR) aa_->SaveToMacro(km_expression, ss); else if (source_ == km_user_str) aa_->SaveToMacro(km_user_str, ss); else if (source_ != km_result) aa_->SaveToMacro(source_); source_ = km_result; // ensure it is not saved again } // Get value (current calc value, memory etc) according to current // bits_ and signed_ settings. mpz_class CCalcDlg::get_norm(mpz_class v, bool only_pos /*= false*/) const { // If infinite precision (bits_ == 0) then there is no mask // Note: this means we can return a -ve value even when signed_ == false if (bits_ == 0) return v; mpz_class retval = v & mask_; // mask off high bits // If high bit is on then make -ve. if (!only_pos && signed_ && mpz_tstbit(v.get_mpz_t(), bits_ - 1)) { // Convert to the 2's complement (invert bits and add one within bits_ range) mpz_com(retval.get_mpz_t(), retval.get_mpz_t()); retval &= mask_; ++ retval; // Now say it is -ve mpz_neg(retval.get_mpz_t(), retval.get_mpz_t()); } return retval; } void CCalcDlg::SetFromFile(FILE_ADDRESS addr) { if (!get_bytes(addr)) { state_ = CALCERROR; return; } state_ = CALCINTUNARY; edit_.put(); edit_.get(); set_right(); } // Get data from the file into calculator, reversing byte order if necessary // Returns false on error such as no file open or invalid address. bool CCalcDlg::get_bytes(FILE_ADDRESS addr) { if (bits_ == 0 || bits_%8 != 0) { current_str_ = "Bits must be divisible by 8"; return false; } const char * err_mess = mpz_set_bytes(current_.get_mpz_t(), addr, bits_/8); if (err_mess != NULL) { if (GetView() == NULL) no_file_error(); current_str_ = err_mess; return false; } state_ = CALCINTUNARY; return true; } // Put data to the file from the current calculator value bool CCalcDlg::put_bytes(FILE_ADDRESS addr) { if (bits_ == 0 || bits_%8 != 0) { TaskMessageBox("Can't write to file", "The calculator integer size (Bits) must be a multiple of 8. " "Only a whole number of bytes can be written to a file."); return false; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return false; } if (pview->ReadOnly()) { TaskMessageBox("File is read only", "The calculator cannot write to the current file when it is open in read only mode."); return false; } FILE_ADDRESS dummy; switch (addr) { case -2: // address of mark addr = pview->GetMark(); break; case -3: // address of start of selection pview->GetSelAddr(addr, dummy); break; } if (addr > pview->GetDocument()->length()) { TaskMessageBox("Can't write past EOF", "An attempt was made to write at an address past the end of file. " "The calculator won't extend a file to allow the bytes to be written."); return false; } if (!pview->OverType() && addr + bits_/8 > pview->GetDocument()->length()) { TaskMessageBox("Write extends past EOF", "The bytes to be written extends past the end of file. " "The calculator cannot write past EOF when the file is open in OVR mode."); return false; } // Get buffer for bytes (size rounded up to multiple of mpz limb size) int units = (bits_/8 + 3)/4; // number of DWORDs required mp_limb_t * buf = new mp_limb_t[units]; // Get all limbs from the big integer (little-endian) // Make sure view and calculator endianness are in sync ASSERT(pview->BigEndian() == ((CButton*)GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS))->GetCheck()); if (pview->BigEndian()) flip_bytes((unsigned char *)buf, bits_/8); // Reverse the byte order to match that used internally (Intel=little-endian) pview->GetDocument()->Change(pview->OverType() ? mod_replace : mod_insert, addr, bits_/8, (unsigned char *)buf, 0, pview); delete[] buf; return true; } void CCalcDlg::fix_values() { // Adjust mask etc depending on bits_ and signed_ (assumes 2's-complement numbers) if (bits_ == 0) return; // Indicates unlimited bits whence min/max/mask are not used mpz_class one(1); mask_ = (one << bits_) - 1; if (signed_) { // 2's complement: abs(min) == abs(max) + 1 min_val_ = - one << (bits_ - 1); max_val_ = - min_val_ - 1; } else { min_val_ = 0; max_val_ = mask_; } } // Stores a binary operation by: // - evaluating any outstanding binary operation (saved in current_) // - move current_ to previous_ ready for a new value to be entered // - store the operation (input parameter binop) in op_ // On Entry state_ can have these values: // CALCERROR, CALCOVERFLOW - causes an error // CALCINTRES - current_ is final result (eg = button) // CALCINTBINARY - binop (eg + button) but no next value yet entered // CALCINTUNARY - unary op (eg INC button) or restored value (eg MR button) // CALCINTLIT, CALCINTEXPR - combine current_ with previous_ (if op_ is valid) // > CALCINTEXPR - error: can't perform an integer operation on current value void CCalcDlg::do_binop(binop_type binop) { // First check that we can perform a binary operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } // If state_ == CALCINTBINARY we have just processed a binop and apparently // the user just wants to override. In this case we don't want to save // to previous_ as this was just done. if (state_ != CALCINTBINARY) { // If there is an active binop (op_ != binop_none) we need to calculate // it before moving current_ to previous_ CString temp = GetStringValue(); calc_binary(); check_for_error(); // check for overflow & display error messages if (state_ >= CALCINTRES) state_ = CALCINTBINARY; // Indicate that (next) binary operation is still active edit_.put(); // Displays left side of binop until user starts to enter a new value (for right side) save_value_to_macro(temp); // Get ready for new value to be entered previous_ = get_norm(current_, binop >= binop_rol && binop <= binop_asr); left_ = right_; current_ = 0; current_str_ = "0"; // don't use edit_.put()/get() here as we want top preserve the previous result until something is entered set_right(); } aa_->SaveToMacro(km_binop, long(binop)); op_ = binop; previous_unary_op_ = unary_none; } // Displays errors and aslo checks for overflow (integer literals). // Should be called after a calculation that could generate and error or overflow // (unary or binary operation) or when an integer literal has been changed (edited or // set from memory etc) or the way it is displayed could cause overflow (bits/signed). void CCalcDlg::check_for_error() { if (state_ > CALCINTLIT) return; // Check we have not overflowed bits (if we don't already have an error) if (state_ >= CALCINTRES && bits_ > 0 && // can't overflow infinite bits (bits_ == 0) (current_ < min_val_ || current_ > max_val_)) { state_ = CALCOVERFLOW; } if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, (CString)current_str_); //mm_->StatusBarText(); aa_->mac_error_ = 10; } else if (state_ == CALCOVERFLOW) { make_noise("Calculator Overflow"); AvoidableTaskDialog(IDS_CALC_OVERFLOW, "The last operation overflowed the current number of bits.\n\n" "The displayed result was adjusted for the current settings.\n" "To see the complete result please adjust the display settings.", "The current calculator value is too large (either positive or negative) or " "it is a large negative value and the current settings are for unsigned values.\n\n" "To see the full result modify the \"Bits\" and/or \"Signed\" settings, or simply " "use \"Inf\" for infinite precision (Bits = 0) to display any value without overflow." ); //mm_->StatusBarText("Overflow"); aa_->mac_error_ = 2; } } // Called when something is done that requires a file open but no file is open void CCalcDlg::no_file_error() { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_NO_FILE, "The calculator cannot perform this operation when no file is open."); aa_->mac_error_ = 10; } void CCalcDlg::not_int_error() { const char *expr_type = "Unknown"; switch (state_) { case CALCREALEXPR: case CALCREALRES: expr_type = "real"; break; case CALCDATEEXPR: case CALCDATERES: expr_type = "date"; break; case CALCSTREXPR: case CALCSTRRES: expr_type = "string"; break; case CALCBOOLEXPR: case CALCBOOLRES: expr_type = "boolean"; break; } make_noise("Calculator Error"); CString ss; ss.Format("\nYou may use the calculator to evaluate expressions of any type (integer, real, " "etc) but most calculator buttons are designed to only work with integer values.\n\n" "You cannot use this button when working with a %s expression or value.", expr_type); AvoidableTaskDialog(IDS_CALC_NOT_INT, "Calculator buttons only work with integers.", ss); //mm_->StatusBarText("Buttons only valid for integers."); aa_->mac_error_ = 10; } void CCalcDlg::make_noise(const char * ss) { #ifdef SYS_SOUNDS if (!CSystemSound::Play(ss)) #endif ::Beep(3000,400); } // Return a string representing a radix. // IMPORTANT: returns a pointer to a static buffer so don't call this function // more than once in a single expression or save the returned pointer. static const char *radix_string(int radix) { static char buf[20]; switch (radix) { case 16: return " [hex]"; case 10: return " [dec]"; case 8: return " [oct]"; case 2: return " [bin]"; default: sprintf(buf, " [radix %d]", radix); return buf; } } void CCalcDlg::update_expr() { ExprStringType disp = get_expr(true); if (state_ > CALCINTEXPR && state_ < CALCOTHER) { // non-integer expression - if it contains digits then indicate that decimal is in use if (strpbrk(CString(current_str_).GetBuffer(), "0123456789") != NULL) disp += " [dec]"; } else if (orig_radix_ != radix_) { disp += radix_string(orig_radix_); } // This is the window (readonly text box) where we show the expression CWnd * pwnd = GetDlgItem(IDC_EXPR); ASSERT(pwnd != NULL); // Get the window's size CRect rct; pwnd->GetWindowRect(&rct); // Get the text's size CClientDC dc(pwnd); int nSave = dc.SaveDC(); dc.SelectObject(pwnd->GetFont()); CSize sz = dc.GetTextExtent(CString(disp)); if (sz.cx > rct.Width()) // string is too big to display disp.Replace(EXPRSTR(" "), EXPRSTR("")); // remove spaces to make the string shorter // Get text from expression window to check if it is different from what we want int len = pwnd->GetWindowTextLength(); wchar_t * pbuf = new wchar_t[len + 2]; ::GetWindowTextW(pwnd->m_hWnd, pbuf, len+1); // If different update with the new text if (pbuf != disp) ::SetWindowTextW(pwnd->m_hWnd, (const wchar_t *)disp); delete[] pbuf; dc.RestoreDC(nSave); } void CCalcDlg::update_op() { if (aa_->refresh_off_ ||! IsVisible()) return; const char *disp = ""; switch (state_) { case CALCERROR: disp = "E"; break; case CALCOVERFLOW: disp = "O"; break; case CALCREALEXPR: case CALCREALRES: disp = "R"; break; case CALCDATEEXPR: case CALCDATERES: disp = "D"; break; case CALCSTREXPR: case CALCSTRRES: disp = "S"; break; case CALCBOOLEXPR: case CALCBOOLRES: disp = "B"; break; #ifdef _DEBUG // Normally we don't display anything for these but this helps with debugging case CALCINTRES: disp = "="; break; case CALCOTHER: disp = "??"; break; #endif case CALCINTBINARY: case CALCINTUNARY: case CALCINTLIT: case CALCINTEXPR: switch (op_) { case binop_add: disp = "+"; break; case binop_subtract: disp = "-"; break; case binop_multiply: disp = "*"; break; case binop_divide: disp = "/"; break; case binop_mod: disp = "%"; break; case binop_pow: disp = "**"; break; case binop_gtr: disp = ">"; break; case binop_less: disp = "<"; break; case binop_ror: disp = "=>"; break; case binop_rol: disp = "<="; break; case binop_lsl: disp = "<-"; break; case binop_lsr: disp = "->"; break; case binop_asr: disp = "+>"; break; case binop_and: disp = "&&"; // displays as a single & break; case binop_or: disp = "|"; break; case binop_xor: disp = "^"; break; case binop_none: disp = ""; break; default: ASSERT(0); // make sure we add new binary ops here } break; } // Check current OP contents and update if different CString ss; ASSERT(GetDlgItem(IDC_OP_DISPLAY) != NULL); GetDlgItem(IDC_OP_DISPLAY)->GetWindowText(ss); if (ss != disp) GetDlgItem(IDC_OP_DISPLAY)->SetWindowText(disp); } void CCalcDlg::do_unary(unary_type unary) { if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } // Save the value to macro before we do anything with it (unless it's a result of a previous op). // Also don't save the value if this (unary op) is the very first thing in the macro. save_value_to_macro(); calc_unary(unary); // This does that actual operation check_for_error(); // check for overflow & display error messages edit_.put(); // Save the unary operation to the current macro (if any) aa_->SaveToMacro(km_unaryop, long(unary)); // The user can't edit the result of a unary operation by pressing digits source_ = km_result; } void CCalcDlg::calc_unary(unary_type unary) { CWaitCursor wc; // show an hourglass just in case it takes a long time current_ = get_norm(current_, unary >= unary_not && unary <= unary_rev); ExprStringType tmp = right_; state_ = CALCINTUNARY; // set default (could also be error/overflow as set below) switch (unary) { case unary_inc: ++current_; if (previous_unary_op_ == unary_inc) right_ = inc_right_operand(right_); else right_.Format(EXPRSTR("(%s + 1)"), (const wchar_t *)tmp); break; case unary_dec: current_ --; if (previous_unary_op_ == unary_dec) right_ = inc_right_operand(right_); else right_.Format(EXPRSTR("(%s - 1)"), (const wchar_t *)tmp); break; case unary_sign: current_ = -current_; // Ask the user if they want to switch to signed numbers if (!signed_ && current_ < min_val_ && AvoidableTaskDialog(IDS_CALC_NEGATIVE_UNSIGNED, "You are changing the sign of a positive number.\n\n" "Do you want to change to using signed numbers?", "\nSince you are currently using unsigned numbers " "changing the sign will cause an OVERFLOW condition.", "Toggle Signed?", TDCBF_YES_BUTTON | TDCBF_NO_BUTTON) == IDYES) { change_signed(!signed_); } right_.Format(EXPRSTR("-%s"), (const wchar_t *)tmp); break; case unary_square: current_ = current_ * current_; right_.Format(EXPRSTR("(%s * %s)"), (const wchar_t *)tmp, (const wchar_t *)tmp); break; case unary_squareroot: if (mpz_sgn(current_.get_mpz_t()) < 0) { current_str_ = "Square root of negative value"; state_ = CALCERROR; } else { mpz_sqrt(current_.get_mpz_t(), current_.get_mpz_t()); right_.Format(EXPRSTR("sqrt(%s)"), (const wchar_t *)without_parens(tmp)); } break; case unary_cube: current_ = current_ * current_ * current_; right_.Format(EXPRSTR("(%s*%s*%s)"), (const wchar_t *)tmp, (const wchar_t *)tmp, (const wchar_t *)tmp); break; case unary_factorial: { mpz_fac_ui(current_.get_mpz_t(), current_.get_ui()); right_.Format(EXPRSTR("fact(%s)"), (const wchar_t *)without_parens(tmp)); } break; case unary_not: current_ = ~current_; right_.Format(EXPRSTR("~%s"), (const wchar_t *)tmp); break; case unary_rol: // ROL1 button if (bits_ == 0) { current_str_ = "Can't rotate left if bit count is unlimited"; state_ = CALCERROR; } else { // if (mpz_sgn(current_.get_mpz_t()) < 0) // mpz_neg(current_.get_mpz_t(), current_.get_mpz_t()); current_ = ((current_ << 1) | (current_ >> (bits_ - 1))) & mask_; right_.Format(EXPRSTR("rol(%s, 1, %s)"), (const wchar_t *)without_parens(tmp), bits_as_string()); } break; case unary_ror: // ROR1 button if (bits_ == 0) { current_str_ = "Can't rotate right if bit count is unlimited"; state_ = CALCERROR; } else { current_ = ((current_ >> 1) | (current_ << (bits_ - 1))) & mask_; right_.Format(EXPRSTR("ror(%s, 1, %s)"), (const wchar_t *)without_parens(tmp), bits_as_string()); } break; case unary_lsl: current_ <<= 1; if (previous_unary_op_ == unary_lsl) right_ = inc_right_operand(right_); else right_.Format(EXPRSTR("(%s << 1)"), (const wchar_t *)tmp); break; case unary_lsr: current_ >>= 1; if (previous_unary_op_ == unary_lsr) right_ = inc_right_operand(right_); else right_.Format(EXPRSTR("(%s >> 1)"), (const wchar_t *)tmp); break; case unary_asr: if (bits_ == 0) { current_ >>= 1; } else { int neg = mpz_tstbit(current_.get_mpz_t(), bits_-1); // is high bit on? current_ >>= 1; if (neg) mpz_setbit(current_.get_mpz_t(), bits_-1); right_.Format(EXPRSTR("asr(%s, 1, %s)"), (const wchar_t *)without_parens(tmp), bits_as_string()); } break; case unary_rev: // Reverse all bits { if (bits_ == 0) { current_str_ = "Can't reverse bits if bit count is unlimited"; state_ = CALCERROR; break; } // This algorithm tests the current bits by shifting right and testing // bottom bit. Any bits on sets the correspoding bit of the result as // it is shifted left. // This could be sped up using a table lookup but is probably OK for now. mpz_class temp = 0; for (int ii = 0; ii < bits_; ++ii) { temp <<= 1; // Make room for the next bit if (mpz_tstbit(current_.get_mpz_t(), 0)) mpz_setbit(temp.get_mpz_t(), 0); current_ >>= 1; // Move bits down to test the next } current_ = temp; right_.Format(EXPRSTR("reverse(%s, %s)"), (const wchar_t *)without_parens(tmp), bits_as_string()); } break; case unary_flip: // Flip byte order // This code assumes that byte order is little-endian in memory if (bits_ == 0 || bits_%8 != 0) { current_str_ = "Bits must be divisible by 8 to flip bytes"; state_ = CALCERROR; } else { int bytes = bits_ / 8; int units = (bytes + 3)/4; // number of DWORDs required mp_limb_t * buf = new mp_limb_t[units]; for (int ii = 0; ii < units; ++ii) { if (ii < mpz_size(current_.get_mpz_t())) buf[ii] = mpz_getlimbn(current_.get_mpz_t(), ii); else buf[ii] = 0; } flip_bytes((unsigned char *)buf, bytes); mpz_import(current_.get_mpz_t(), units, -1, sizeof(mp_limb_t), -1, 0, buf); delete[] buf; right_.Format(EXPRSTR("flip(%s, %s)"), (const wchar_t *)without_parens(tmp), int_as_string(bits_/8)); } break; case unary_at: if (GetView() == NULL) { no_file_error(); return; // just ignore this situation by returning with no action //current_str_ = "No file open to get data from"; //state_ = CALCERROR; } else { // Check that current_ is within file address range 0 <= x <= eof. // get)bytes does this but only on a possibly truncated (64-bit) value. mpz_class eof; mpz_set_ui64(eof.get_mpz_t(), GetView()->GetDocument()->length()); if (current_ < 0) { current_str_ = "Can't read before start of file"; state_ = CALCERROR; } else if (current_ >= eof) { current_str_ = "Can't read past end of file"; state_ = CALCERROR; } else if (!get_bytes(GetValue())) state_ = CALCERROR; else right_.Format(EXPRSTR("get(%s, %s)"), (const wchar_t *)without_parens(tmp), bits_as_string()); } break; case unary_none: default: ASSERT(0); } if (state_ == CALCERROR) right_ = "***"; previous_unary_op_ = unary; } // Handle "digit" button click void CCalcDlg::do_digit(char digit) { // Since digit buttons are "enabled" (but greyed) even when invalid we need to check for invalid digits int val = isdigit(digit) ? (digit - '0') : digit - 'A' + 10; if (val >= radix_) { #ifdef SYS_SOUNDS if (!CSystemSound::Play("Invalid Character")) #endif ::Beep(5000,200); return; } edit_.SendMessage(WM_CHAR, digit, 1); } // Calculates any pending binary operation and leaves the result in current_. Ie: // current_ = previous_ op_ current_ // Note that binary operations (from calc buttons) are only valid for integer values. // It is called when we want the final result (OnEquals/OnGo) or when we need to // calcualte the current binary operation before preparing for the next (do_binop). void CCalcDlg::calc_binary() { if (op_ == binop_none) return; // Handles case where state_ > CALCINTEXPR without changing state_ CWaitCursor wc; // show an hourglass just in case it takes a long time ASSERT(state_ != CALCERROR && state_ <= CALCINTEXPR); current_ = get_norm(current_); state_ = CALCINTRES; // default to integer result - may be overridden due to error/overflow or for CALCINTBINARY switch (op_) { case binop_add: current_ += previous_; break; case binop_subtract: current_ = previous_ - current_; break; case binop_multiply: current_ *= previous_; break; case binop_divide: if (current_ == 0) { current_str_ = "Divide by zero"; state_ = CALCERROR; } else current_ = previous_ / current_; break; case binop_mod: if (current_ == 0) { current_str_ = "Divide (modulus) by zero"; state_ = CALCERROR; } else current_ = previous_ % current_; break; case binop_pow: if (current_ > mpz_class(ULONG_MAX)) { current_ = 0; state_ = CALCOVERFLOW; } else mpz_pow_ui(current_.get_mpz_t(), previous_.get_mpz_t(), current_.get_si()); break; case binop_gtr: case binop_gtr_old: if (current_ < previous_) current_ = previous_; break; case binop_less: case binop_less_old: if (current_ > previous_) current_ = previous_; break; case binop_rol: if (bits_ == 0) { current_str_ = "Can't rotate right if bit count is unlimited"; state_ = CALCERROR; } else { mpz_class t1, t2; current_ %= bits_; mpz_mul_2exp(t1.get_mpz_t(), previous_.get_mpz_t(), current_.get_ui()); mpz_fdiv_q_2exp(t2.get_mpz_t(), previous_.get_mpz_t(), bits_ - current_.get_ui()); current_ = (t1 | t2) & mask_; } break; case binop_ror: if (bits_ == 0) { current_str_ = "Can't rotate left if bit count is unlimited"; state_ = CALCERROR; } else { mpz_class t1, t2; current_ %= bits_; mpz_fdiv_q_2exp(t1.get_mpz_t(), previous_.get_mpz_t(), current_.get_ui()); mpz_mul_2exp(t2.get_mpz_t(), previous_.get_mpz_t(), bits_ - current_.get_ui()); current_ = (t1 | t2) & mask_; } break; case binop_lsl: mpz_mul_2exp(current_.get_mpz_t(), previous_.get_mpz_t(), current_.get_ui()); break; case binop_lsr: mpz_fdiv_q_2exp(current_.get_mpz_t(), previous_.get_mpz_t(), current_.get_ui()); break; case binop_asr: if (bits_ == 0) mpz_fdiv_q_2exp(current_.get_mpz_t(), previous_.get_mpz_t(), current_.get_ui()); else { int shift = current_.get_si(); int neg = mpz_tstbit(previous_.get_mpz_t(), bits_-1); if (shift > bits_) { // All bits shifted out if (neg) current_ = -1 & mask_; else current_ = 0; } else { current_ = previous_; for (int ii = 0; ii < shift; ++ii) { current_ >>= 1; if (neg) mpz_setbit(current_.get_mpz_t(), bits_-1); // propagate high bit } } } break; case binop_and: current_ &= previous_; break; case binop_or: current_ |= previous_; break; case binop_xor: current_ ^= previous_; break; default: ASSERT(0); break; } right_ = get_expr(false); // we need parentheses in case there are further operations op_ = binop_none; previous_unary_op_ = unary_none; } // calc_binary void CCalcDlg::change_base(int base) { if (base == radix_) return; // no change radix_ = base; // Store new radix (affects edit control display) if (left_.IsEmpty() && (right_.IsEmpty() || right_ == "0") && op_ == binop_none) orig_radix_ = radix_; // If an integer literal redisplay if (inited_) { if (state_ <= CALCINTLIT) { state_ = CALCINTUNARY; // need to clear any previous overflow check_for_error(); // check for overflow edit_.put(); } source_ = km_result; aa_->SaveToMacro(km_change_base, long(radix_)); } } void CCalcDlg::change_signed(bool s) { if (s == signed_) return; // no change signed_ = s; fix_values(); // signed numbers have a different range of values if (inited_) { // If an integer expression redisplay if (state_ <= CALCINTLIT) { state_ = CALCINTUNARY; // need to clear any previous overflow check_for_error(); // check for overflow edit_.put(); } source_ = km_result; aa_->SaveToMacro(km_change_signed); } } void CCalcDlg::change_bits(int bits) { if (bits == bits_) return; // no change bits_ = bits; fix_values(); // adjust value range etc for new bits setting if (inited_) { // If an integer expression redisplay if (state_ <= CALCINTLIT) { state_ = CALCINTUNARY; // need to clear any previous overflow check_for_error(); // check for overflow edit_.put(); } source_ = km_result; aa_->SaveToMacro(km_change_bits, long(bits_)); } } void CCalcDlg::setup_resizer() { // Add all the controls and proportional change to LEFT, TOP, WIDTH, HEIGHT. // NOTE: Don't allow resize vertically of IDC_EDIT as it stuffs up the combo drop down list window size m_resizer.Add(IDC_EDIT, 0, 0, 100, 0); // edit control resizes with width m_resizer.Add(IDC_EXPR, 0, 0, 100, 0); // displays the expression that produced the current calculator value m_resizer.Add(IDC_OP_DISPLAY, 100, 0, 0, 0); // operator display sticks to right edge (moves vert) m_resizer.Add(IDC_CALC_BITS, 0, 0, 100, 13); // where "bits" are drawn // Settings controls don't move/size horizontally but move vert. and size slightly too m_resizer.Add(IDC_BIG_ENDIAN_FILE_ACCESS, 0, 13, 0, 13); m_resizer.Add(IDC_RADIX_GROUP, 0, 13, 0, 13); m_resizer.Add(IDC_DESC_RADIX, 0, 14, 0, 0); m_resizer.Add(IDC_RADIX, 0, 14, 0, 4); m_resizer.Add(IDC_SPIN_RADIX, 0, 14, 0, 4); m_resizer.Add(IDC_HEX, 0, 21, 0, 5); m_resizer.Add(IDC_DECIMAL, 0, 21, 0, 5); m_resizer.Add(IDC_OCTAL, 0, 21, 0, 5); m_resizer.Add(IDC_BINARY, 0, 21, 0, 5); m_resizer.Add(IDC_BITS_GROUP, 0, 13, 0, 13); m_resizer.Add(IDC_DESC_BITS, 0, 14, 0, 0); m_resizer.Add(IDC_BITS, 0, 14, 0, 4); m_resizer.Add(IDC_SPIN_BITS, 0, 14, 0, 4); m_resizer.Add(IDC_CALC_SIGNED, 0, 14, 0, 5); m_resizer.Add(IDC_INFBIT, 0, 21, 0, 5); m_resizer.Add(IDC_64BIT, 0, 21, 0, 5); m_resizer.Add(IDC_32BIT, 0, 21, 0, 5); m_resizer.Add(IDC_16BIT, 0, 21, 0, 5); m_resizer.Add(IDC_8BIT, 0, 21, 0, 5); // First row of buttons m_resizer.Add(IDC_MEM_GET, 1, 27, 12, 10); m_resizer.Add(IDC_MEM_STORE, 14, 27, 9, 10); m_resizer.Add(IDC_MEM_CLEAR, 23, 27, 9, 10); m_resizer.Add(IDC_MEM_ADD, 32, 27, 9, 10); m_resizer.Add(IDC_MEM_SUBTRACT, 41, 27, 8, 10); m_resizer.Add(IDC_BACKSPACE, 64, 26, 16, 10); m_resizer.Add(IDC_CLEAR_ENTRY, 80, 26, 10, 10); m_resizer.Add(IDC_CLEAR, 90, 26, 10, 10); // 2nd row of buttons m_resizer.Add(IDC_MARK_GET, 1, 37, 12, 10); m_resizer.Add(IDC_MARK_STORE, 14, 37, 9, 10); m_resizer.Add(IDC_MARK_CLEAR, 23, 37, 9, 10); m_resizer.Add(IDC_MARK_ADD, 32, 37, 9, 10); m_resizer.Add(IDC_MARK_SUBTRACT, 41, 37, 8, 10); m_resizer.Add(IDC_DIGIT_D, 50, 37, 8, 10); m_resizer.Add(IDC_DIGIT_E, 58, 37, 8, 10); m_resizer.Add(IDC_DIGIT_F, 66, 37, 8, 10); m_resizer.Add(IDC_POW, 75, 37, 8, 10); m_resizer.Add(IDC_GTR, 83, 37, 8, 10); m_resizer.Add(IDC_ROL, 91, 37, 8, 10); // 3rd row of buttons m_resizer.Add(IDC_MARK_AT, 1, 47, 12, 10); m_resizer.Add(IDC_MARK_AT_STORE, 14, 47, 9, 10); m_resizer.Add(IDC_UNARY_SQUARE, 23, 47, 9, 10); m_resizer.Add(IDC_UNARY_ROL, 32, 47, 9, 10); m_resizer.Add(IDC_UNARY_REV, 41, 47, 8, 10); m_resizer.Add(IDC_DIGIT_A, 50, 47, 8, 10); m_resizer.Add(IDC_DIGIT_B, 58, 47, 8, 10); m_resizer.Add(IDC_DIGIT_C, 66, 47, 8, 10); m_resizer.Add(IDC_MOD, 75, 47, 8, 10); m_resizer.Add(IDC_LESS, 83, 47, 8, 10); m_resizer.Add(IDC_ROR, 91, 47, 8, 10); // 4th row of buttons m_resizer.Add(IDC_SEL_GET, 1, 57, 12, 10); m_resizer.Add(IDC_SEL_STORE, 14, 57, 9, 10); m_resizer.Add(IDC_UNARY_SQUARE_ROOT, 23, 57, 9, 10); m_resizer.Add(IDC_UNARY_ROR, 32, 57, 9, 10); m_resizer.Add(IDC_UNARY_NOT, 41, 57, 8, 10); m_resizer.Add(IDC_DIGIT_7, 50, 57, 8, 10); m_resizer.Add(IDC_DIGIT_8, 58, 57, 8, 10); m_resizer.Add(IDC_DIGIT_9, 66, 57, 8, 10); m_resizer.Add(IDC_DIVIDE, 75, 57, 8, 10); m_resizer.Add(IDC_XOR, 83, 57, 8, 10); m_resizer.Add(IDC_LSL, 91, 57, 8, 10); // 5th row of buttons m_resizer.Add(IDC_SEL_AT, 1, 67, 12, 10); m_resizer.Add(IDC_SEL_AT_STORE, 14, 67, 9, 10); m_resizer.Add(IDC_UNARY_CUBE, 23, 67, 9, 10); m_resizer.Add(IDC_UNARY_LSL, 32, 67, 9, 10); m_resizer.Add(IDC_UNARY_INC, 41, 67, 8, 10); m_resizer.Add(IDC_DIGIT_4, 50, 67, 8, 10); m_resizer.Add(IDC_DIGIT_5, 58, 67, 8, 10); m_resizer.Add(IDC_DIGIT_6, 66, 67, 8, 10); m_resizer.Add(IDC_MULTIPLY, 75, 67, 8, 10); m_resizer.Add(IDC_OR, 83, 67, 8, 10); m_resizer.Add(IDC_LSR, 91, 67, 8, 10); // 6th row of buttons m_resizer.Add(IDC_SEL_LEN, 1, 77, 12, 10); m_resizer.Add(IDC_SEL_LEN_STORE, 14, 77, 9, 10); m_resizer.Add(IDC_UNARY_FACTORIAL, 23, 77, 9, 10); m_resizer.Add(IDC_UNARY_LSR, 32, 77, 9, 10); m_resizer.Add(IDC_UNARY_DEC, 41, 77, 8, 10); m_resizer.Add(IDC_DIGIT_1, 50, 77, 8, 10); m_resizer.Add(IDC_DIGIT_2, 58, 77, 8, 10); m_resizer.Add(IDC_DIGIT_3, 66, 77, 8, 10); m_resizer.Add(IDC_SUBTRACT, 75, 77, 8, 10); m_resizer.Add(IDC_AND, 83, 77, 8, 10); m_resizer.Add(IDC_ASR, 91, 77, 8, 10); // 7th row of buttons m_resizer.Add(IDC_EOF_GET, 1, 87, 12, 10); m_resizer.Add(IDC_UNARY_AT, 23, 87, 9, 10); m_resizer.Add(IDC_UNARY_ASR, 32, 87, 9, 10); m_resizer.Add(IDC_UNARY_FLIP, 41, 87, 8, 10); m_resizer.Add(IDC_DIGIT_0, 50, 87, 8, 10); m_resizer.Add(IDC_UNARY_SIGN, 58, 87, 8, 10); m_resizer.Add(IDC_EQUALS, 66, 87, 8, 10); m_resizer.Add(IDC_ADDOP, 75, 87, 8, 10); m_resizer.Add(IDC_GO, 83, 87, 16, 10); // We need this so that the resizer gets WM_SIZE event after the controls have been added. CRect cli; GetClientRect(&cli); PostMessage(WM_SIZE, SIZE_RESTORED, MAKELONG(cli.Width(), cli.Height())); } // Customize expr display (IDC_EXPR) void CCalcDlg::setup_expr() { // Make a smaller font for use with expression display etc LOGFONT lf; memset(&lf, 0, sizeof(LOGFONT)); lf.lfHeight = 11; strcpy(lf.lfFaceName, "Tahoma"); // Simple font for small digits small_fnt_.CreateFontIndirect(&lf); lf.lfHeight = 16; med_fnt_.CreateFontIndirect(&lf); GetDlgItem(IDC_EXPR)->SetFont(&small_fnt_); } void CCalcDlg::setup_tooltips() { // Set up tool tips if (ttc_.Create(this)) { ttc_.ModifyStyleEx(0, WS_EX_TOPMOST); ASSERT(GetDlgItem(IDC_BACKSPACE) != NULL); ASSERT(GetDlgItem(IDC_CLEAR_ENTRY) != NULL); ASSERT(GetDlgItem(IDC_CLEAR) != NULL); ASSERT(GetDlgItem(IDC_EQUALS) != NULL); ASSERT(GetDlgItem(IDC_AND) != NULL); ASSERT(GetDlgItem(IDC_ASR) != NULL); ASSERT(GetDlgItem(IDC_DIVIDE) != NULL); ASSERT(GetDlgItem(IDC_LSL) != NULL); ASSERT(GetDlgItem(IDC_LSR) != NULL); ASSERT(GetDlgItem(IDC_ROL) != NULL); ASSERT(GetDlgItem(IDC_ROR) != NULL); ASSERT(GetDlgItem(IDC_XOR) != NULL); ASSERT(GetDlgItem(IDC_MOD) != NULL); ASSERT(GetDlgItem(IDC_MULTIPLY) != NULL); ASSERT(GetDlgItem(IDC_OR) != NULL); ASSERT(GetDlgItem(IDC_UNARY_DEC) != NULL); ASSERT(GetDlgItem(IDC_UNARY_FACTORIAL) != NULL); ASSERT(GetDlgItem(IDC_UNARY_FLIP) != NULL); ASSERT(GetDlgItem(IDC_UNARY_REV) != NULL); ASSERT(GetDlgItem(IDC_UNARY_INC) != NULL); ASSERT(GetDlgItem(IDC_UNARY_NOT) != NULL); ASSERT(GetDlgItem(IDC_UNARY_SIGN) != NULL); ASSERT(GetDlgItem(IDC_UNARY_SQUARE) != NULL); ASSERT(GetDlgItem(IDC_SUBTRACT) != NULL); ASSERT(GetDlgItem(IDC_MEM_GET) != NULL); ASSERT(GetDlgItem(IDC_MEM_CLEAR) != NULL); ASSERT(GetDlgItem(IDC_MEM_ADD) != NULL); ASSERT(GetDlgItem(IDC_MEM_SUBTRACT) != NULL); ASSERT(GetDlgItem(IDC_MARK_GET) != NULL); ASSERT(GetDlgItem(IDC_MARK_AT) != NULL); ASSERT(GetDlgItem(IDC_MARK_ADD) != NULL); ASSERT(GetDlgItem(IDC_MARK_SUBTRACT) != NULL); ASSERT(GetDlgItem(IDC_SEL_GET) != NULL); ASSERT(GetDlgItem(IDC_SEL_AT) != NULL); ASSERT(GetDlgItem(IDC_EOF_GET) != NULL); ASSERT(GetDlgItem(IDC_GTR) != NULL); ASSERT(GetDlgItem(IDC_LESS) != NULL); ASSERT(GetDlgItem(IDC_POW) != NULL); ASSERT(GetDlgItem(IDC_MARK_AT_STORE) != NULL); ASSERT(GetDlgItem(IDC_MARK_CLEAR) != NULL); ASSERT(GetDlgItem(IDC_MARK_STORE) != NULL); ASSERT(GetDlgItem(IDC_MEM_STORE) != NULL); ASSERT(GetDlgItem(IDC_SEL_AT_STORE) != NULL); ASSERT(GetDlgItem(IDC_SEL_STORE) != NULL); ASSERT(GetDlgItem(IDC_UNARY_ROL) != NULL); ASSERT(GetDlgItem(IDC_UNARY_ROR) != NULL); ASSERT(GetDlgItem(IDC_UNARY_LSL) != NULL); ASSERT(GetDlgItem(IDC_UNARY_LSR) != NULL); ASSERT(GetDlgItem(IDC_UNARY_ASR) != NULL); ASSERT(GetDlgItem(IDC_UNARY_CUBE) != NULL); ASSERT(GetDlgItem(IDC_UNARY_AT) != NULL); ASSERT(GetDlgItem(IDC_UNARY_SQUARE_ROOT) != NULL); ASSERT(GetDlgItem(IDC_SEL_LEN) != NULL); ASSERT(GetDlgItem(IDC_SEL_LEN_STORE) != NULL); ASSERT(GetDlgItem(IDC_ADDOP) != NULL); ASSERT(GetDlgItem(IDC_GO) != NULL); ASSERT(GetDlgItem(IDC_8BIT) != NULL); ASSERT(GetDlgItem(IDC_16BIT) != NULL); ASSERT(GetDlgItem(IDC_32BIT) != NULL); ASSERT(GetDlgItem(IDC_64BIT) != NULL); ASSERT(GetDlgItem(IDC_INFBIT) != NULL); ASSERT(GetDlgItem(IDC_BINARY) != NULL); ASSERT(GetDlgItem(IDC_OCTAL) != NULL); ASSERT(GetDlgItem(IDC_DECIMAL) != NULL); ASSERT(GetDlgItem(IDC_HEX) != NULL); ASSERT(GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS) != NULL); ttc_.AddTool(GetDlgItem(IDC_MEM_GET), "Memory Recall (Ctrl+R)"); ttc_.AddTool(GetDlgItem(IDC_MEM_STORE), "Memory Store (Ctrl+M)"); ttc_.AddTool(GetDlgItem(IDC_MEM_CLEAR), "Memory Clear (Ctrl+L)"); ttc_.AddTool(GetDlgItem(IDC_MEM_ADD), "Memory Add (Ctrl+P)"); ttc_.AddTool(GetDlgItem(IDC_MEM_SUBTRACT), "Memory Subtract"); ttc_.AddTool(GetDlgItem(IDC_BACKSPACE), "Delete Last Digit"); ttc_.AddTool(GetDlgItem(IDC_CLEAR_ENTRY), "Clear Entry"); ttc_.AddTool(GetDlgItem(IDC_CLEAR), "Clear All"); ttc_.AddTool(GetDlgItem(IDC_EQUALS), "Calculate Result"); ttc_.AddTool(GetDlgItem(IDC_GO), "Jump To Resultant Address"); ttc_.AddTool(GetDlgItem(IDC_ADDOP), "Add"); ttc_.AddTool(GetDlgItem(IDC_SUBTRACT), "Subtract"); ttc_.AddTool(GetDlgItem(IDC_MULTIPLY), "Multiply"); ttc_.AddTool(GetDlgItem(IDC_DIVIDE), "Integer Divide"); ttc_.AddTool(GetDlgItem(IDC_MOD), "Remainder"); ttc_.AddTool(GetDlgItem(IDC_POW), "Integer Power"); ttc_.AddTool(GetDlgItem(IDC_GTR), "Greater of Two Values"); ttc_.AddTool(GetDlgItem(IDC_LESS), "Smaller of Two Values"); ttc_.AddTool(GetDlgItem(IDC_AND), "AND"); ttc_.AddTool(GetDlgItem(IDC_OR), "OR"); ttc_.AddTool(GetDlgItem(IDC_XOR), "Exclusive Or"); ttc_.AddTool(GetDlgItem(IDC_LSL), "Logical Shift Left"); ttc_.AddTool(GetDlgItem(IDC_LSR), "Logical Shift Right"); ttc_.AddTool(GetDlgItem(IDC_ASR), "Arithmetic Shift Right"); ttc_.AddTool(GetDlgItem(IDC_ROL), "Rotate Left"); ttc_.AddTool(GetDlgItem(IDC_ROR), "Rotate Right"); ttc_.AddTool(GetDlgItem(IDC_UNARY_FLIP), "Reverse Byte Order"); ttc_.AddTool(GetDlgItem(IDC_UNARY_REV), "Reverse Bit Order"); ttc_.AddTool(GetDlgItem(IDC_UNARY_DEC), "Subtract One"); ttc_.AddTool(GetDlgItem(IDC_UNARY_INC), "Add One"); ttc_.AddTool(GetDlgItem(IDC_UNARY_SIGN), "Change Sign"); ttc_.AddTool(GetDlgItem(IDC_UNARY_SQUARE), "Square"); ttc_.AddTool(GetDlgItem(IDC_UNARY_CUBE), "Cube"); ttc_.AddTool(GetDlgItem(IDC_UNARY_SQUARE_ROOT), "Integer Square Root"); ttc_.AddTool(GetDlgItem(IDC_UNARY_FACTORIAL), "Factorial"); ttc_.AddTool(GetDlgItem(IDC_UNARY_NOT), "NOT"); ttc_.AddTool(GetDlgItem(IDC_UNARY_ROL), "Rotate Left by One Bit"); ttc_.AddTool(GetDlgItem(IDC_UNARY_ROR), "Rotate Right by One Bit"); ttc_.AddTool(GetDlgItem(IDC_UNARY_LSL), "Logical Shift Left by One Bit"); ttc_.AddTool(GetDlgItem(IDC_UNARY_LSR), "Logical Shift Right by One Bit"); ttc_.AddTool(GetDlgItem(IDC_UNARY_ASR), "Arithmetic Shift Right by One Bit"); ttc_.AddTool(GetDlgItem(IDC_UNARY_AT), "Retrieve the Value from File"); ttc_.AddTool(GetDlgItem(IDC_MARK_GET), "Address of Mark"); ttc_.AddTool(GetDlgItem(IDC_MARK_STORE), "Move the Mark"); ttc_.AddTool(GetDlgItem(IDC_MARK_CLEAR), "Set the Mark to Start of File"); ttc_.AddTool(GetDlgItem(IDC_MARK_ADD), "Add to Mark"); ttc_.AddTool(GetDlgItem(IDC_MARK_SUBTRACT), "Subtract from Mark"); ttc_.AddTool(GetDlgItem(IDC_MARK_AT), "Get the Value at the Mark"); ttc_.AddTool(GetDlgItem(IDC_MARK_AT_STORE), "Store at Mark"); ttc_.AddTool(GetDlgItem(IDC_SEL_GET), "Cursor Location"); ttc_.AddTool(GetDlgItem(IDC_SEL_STORE), "Move the Cursor"); ttc_.AddTool(GetDlgItem(IDC_SEL_AT), "Get the Value at the Cursor"); ttc_.AddTool(GetDlgItem(IDC_SEL_AT_STORE), "Store to File at Cursor"); ttc_.AddTool(GetDlgItem(IDC_SEL_LEN), "Get the Length of the Selection"); ttc_.AddTool(GetDlgItem(IDC_SEL_LEN_STORE), "Change the Length of the Selection"); ttc_.AddTool(GetDlgItem(IDC_EOF_GET), "Get the Length of File"); ttc_.AddTool(GetDlgItem(IDC_8BIT), "Use Bytes (F12)"); ttc_.AddTool(GetDlgItem(IDC_16BIT), "Use Words (F11)"); ttc_.AddTool(GetDlgItem(IDC_32BIT), "Use Double Words (F10)"); ttc_.AddTool(GetDlgItem(IDC_64BIT), "Use Quad Words (F9)"); ttc_.AddTool(GetDlgItem(IDC_INFBIT), "Unlimited integer precision"); ttc_.AddTool(GetDlgItem(IDC_BINARY), "Use Binary Numbers (F8)"); ttc_.AddTool(GetDlgItem(IDC_OCTAL), "USe Octal Numbers (F7)"); ttc_.AddTool(GetDlgItem(IDC_DECIMAL), "Use (Signed) Decimal Numbers (F6)"); ttc_.AddTool(GetDlgItem(IDC_HEX), "Use Hexadecimal Numbers (F5)"); ttc_.AddTool(GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS), "Read/Write to File in Big-Endian Format"); ttc_.Activate(TRUE); } } void CCalcDlg::setup_static_buttons() { // Things that use the calculator value and other "admin" type buttons are red button_colour(GetDlgItem(IDC_BACKSPACE), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_CLEAR_ENTRY), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_CLEAR), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MEM_STORE), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MEM_CLEAR), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MEM_ADD), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MEM_SUBTRACT), true, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_EQUALS), true, RGB(0xC0, 0x0, 0x0)); // Binary operations are blue button_colour(GetDlgItem(IDC_ADDOP), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_SUBTRACT), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_MULTIPLY), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_DIVIDE), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_MOD), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_POW), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_GTR), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_LESS), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_XOR), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_OR), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_AND), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_LSL), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_LSR), true, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_ASR), true, RGB(0x0, 0x0, 0xC0)); // Unary operations are purple button_colour(GetDlgItem(IDC_UNARY_SIGN), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_NOT), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_INC), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_DEC), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_LSL), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_LSR), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_ASR), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_SQUARE), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_SQUARE_ROOT), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_CUBE), true, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_FACTORIAL), true, RGB(0x80, 0x0, 0x80)); // Digit buttons (0 and 1) are always "enabled" (dark grey) button_colour(GetDlgItem(IDC_DIGIT_0), true, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_1), true, RGB(0x40, 0x40, 0x40)); } void CCalcDlg::update_controls() { // Check if case has changed for edit box if (radix_ > 10 && state_ <= CALCINTLIT) { CString ss, new_ss; DWORD sel = edit_.GetSel(); edit_.GetWindowText(ss); new_ss = ss; if (theApp.hex_ucase_) new_ss.MakeUpper(); else new_ss.MakeLower(); if (new_ss != ss) { edit_.SetWindowText(ss); edit_.SetSel(sel); } } update_op(); update_expr(); update_modes(); // Radix, bits, signed controls update_digit_buttons(); update_file_buttons(); // Update misc buttons button_colour(GetDlgItem(IDC_UNARY_FLIP), bits_ > 8 && bits_%8 == 0, RGB(0x80, 0x0, 0x80)); // can't flip single byte or individual bits button_colour(GetDlgItem(IDC_UNARY_REV), bits_ > 0, RGB(0x80, 0x0, 0x80)); // Can't reverse an inf. number of bits // Can't wrap around with unlimited precision button_colour(GetDlgItem(IDC_UNARY_ROL), bits_ > 0, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_UNARY_ROR), bits_ > 0, RGB(0x80, 0x0, 0x80)); button_colour(GetDlgItem(IDC_ROL), bits_ > 0, RGB(0x0, 0x0, 0xC0)); button_colour(GetDlgItem(IDC_ROR), bits_ > 0, RGB(0x0, 0x0, 0xC0)); // Disable big-endian checkbox if there is only one byte or not using whole bytes, or no active file ASSERT(GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS) != NULL); BOOL enable = GetView() != NULL && bits_ > 8 && bits_%8 == 0; if (enable != GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS)->IsWindowEnabled()) GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS)->EnableWindow(enable); build_menus(); } void CCalcDlg::update_modes() { CString ss; char buf[6]; // Update controls showing radix ASSERT(GetDlgItem(IDC_RADIX) != NULL); GetDlgItemText(IDC_RADIX, ss); sprintf(buf, "%d", radix_); if (ss != buf) { ss = buf; SetDlgItemText(IDC_RADIX, ss); } // Update radio buttons int radix_index = -1; switch (radix_) { case 2: radix_index = 3; break; case 8: radix_index = 2; break; case 10: radix_index = 1; break; case 16: radix_index = 0; break; } ((CButton *)GetDlgItem(IDC_HEX ))->SetCheck(radix_index == 0); ((CButton *)GetDlgItem(IDC_DECIMAL))->SetCheck(radix_index == 1); ((CButton *)GetDlgItem(IDC_OCTAL ))->SetCheck(radix_index == 2); ((CButton *)GetDlgItem(IDC_BINARY ))->SetCheck(radix_index == 3); // Update controls showing number of bits ASSERT(GetDlgItem(IDC_BITS) != NULL); GetDlgItemText(IDC_BITS, ss); sprintf(buf, "%d", bits_); if (ss != buf) { ss = buf; SetDlgItemText(IDC_BITS, ss); } // Update radio buttons int bits_index = -1; switch (bits_) { case 8: bits_index = 4; break; case 16: bits_index = 3; break; case 32: bits_index = 2; break; case 64: bits_index = 1; break; case 0: bits_index = 0; break; } ((CButton *)GetDlgItem(IDC_8BIT ))->SetCheck(bits_index == 4); ((CButton *)GetDlgItem(IDC_16BIT))->SetCheck(bits_index == 3); ((CButton *)GetDlgItem(IDC_32BIT))->SetCheck(bits_index == 2); ((CButton *)GetDlgItem(IDC_64BIT))->SetCheck(bits_index == 1); ((CButton *)GetDlgItem(IDC_INFBIT))->SetCheck(bits_index == 0); // Update checkbox showing signedness ASSERT(GetDlgItem(IDC_CALC_SIGNED) != NULL); CButton *pb = (CButton *)GetDlgItem(IDC_CALC_SIGNED); BOOL enabled = pb->IsWindowEnabled(); // If we have infinite bits (bits_ == 0) then we must allow signed numbers (eg all bits on = -1) BOOL en = bits_ > 0; pb->SetCheck(!en || signed_); // turn on tick when disabled to indicate that inf bits uses signed numbers if (en != enabled) pb->EnableWindow(en); } // Fix digit buttons depending on the radix void CCalcDlg::update_digit_buttons() { // Enable/disable digit keys depending on base button_colour(GetDlgItem(IDC_DIGIT_2), radix_ > 2, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_3), radix_ > 3, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_4), radix_ > 4, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_5), radix_ > 5, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_6), radix_ > 6, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_7), radix_ > 7, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_8), radix_ > 8, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_9), radix_ > 9, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_A), radix_ > 10, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_B), radix_ > 11, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_C), radix_ > 12, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_D), radix_ > 13, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_E), radix_ > 14, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_DIGIT_F), radix_ > 15, RGB(0x40, 0x40, 0x40)); } void CCalcDlg::update_file_buttons() { ASSERT(IsVisible()); // Should only be called if dlg is visible ASSERT(GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS) != NULL); CHexEditView *pview = GetView(); int bytes = bits_ == 0 ? INT_MAX : bits_/8; // # of bytes when reading/writing file mpz_class start, eof, mark, sel_len; if (pview != NULL) { mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); mpz_set_ui64(mark.get_mpz_t(), pview->GetMark()); FILE_ADDRESS s, e; // Current selection pview->GetSelAddr(s, e); mpz_set_ui64(start.get_mpz_t(), s); mpz_set_ui64(sel_len.get_mpz_t(), e - s); } // Most file buttons are only enabled if there is an active file open and calc has an INT value in it bool basic = pview != NULL && state_ <= CALCINTEXPR; // Red buttons button_colour(GetDlgItem(IDC_MARK_STORE), basic && get_norm(current_) >= 0 && get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MARK_CLEAR), pview != NULL, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MARK_ADD), basic && mark + get_norm(current_) >= 0 && mark + get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MARK_SUBTRACT), basic && mark - get_norm(current_) >= 0 && mark - get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_MARK_AT_STORE), basic && !pview->ReadOnly() && mark <= eof && (mark + bytes <= eof || !pview->OverType()), RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_SEL_STORE), basic && get_norm(current_) >= 0 && get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_SEL_AT_STORE), basic && !pview->ReadOnly() && start <= eof && (start + bytes <= eof || !pview->OverType()), RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_SEL_LEN_STORE), basic && get_norm(current_) >= 0 && start + get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); button_colour(GetDlgItem(IDC_GO), basic && get_norm(current_) <= eof, RGB(0xC0, 0x0, 0x0)); // Dark grey buttons button_colour(GetDlgItem(IDC_MARK_GET), pview != NULL && mark <= max_val_, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_MARK_AT), pview != NULL && mark + bytes <= eof, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_SEL_GET), pview != NULL && start <= max_val_, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_SEL_AT), pview != NULL && start + bytes <= eof, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_SEL_LEN), pview != NULL && sel_len <= max_val_, RGB(0x40, 0x40, 0x40)); button_colour(GetDlgItem(IDC_EOF_GET), pview != NULL && eof <= max_val_, RGB(0x40, 0x40, 0x40)); // Purple button_colour(GetDlgItem(IDC_UNARY_AT), basic && get_norm(current_) + bytes <= eof, RGB(0x80, 0x0, 0x80)); if (pview != NULL) { CButton *pb = (CButton *)GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS); BOOL endian_state = pview->BigEndian(); BOOL previous_endian_state = pb->GetCheck(); if (endian_state != previous_endian_state) { GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS)->EnableWindow(TRUE); // enable so we can change it pb->SetCheck(pview->BigEndian()); } } // We can only use endianess if bits_ is a multiple of 8 (whole byte). // It also makes no sense for bits_ == 8 (1 byte) and bits_ == 0 (Inf. bytes) GetDlgItem(IDC_BIG_ENDIAN_FILE_ACCESS)->EnableWindow(GetView() != NULL && bits_ > 8 && bits_%8 == 0); } // Button drawing funcs for OnDrawItem below static void Draw3DFrame(CDC *pDC, CRect rcBox, COLORREF colBottomRight, COLORREF colTopLeft) { CPen *pPen2, *pPen, *pOldPen; pPen = new CPen(PS_SOLID, 1, colBottomRight); pOldPen = pDC->SelectObject(pPen); pDC->MoveTo(rcBox.right-1, rcBox.top); pDC->LineTo(rcBox.right-1, rcBox.bottom-1); pDC->LineTo(rcBox.left-1, rcBox.bottom-1); pPen2 = new CPen(PS_SOLID, 1, colTopLeft); pDC->SelectObject(pPen2); delete pPen; pDC->MoveTo(rcBox.left, rcBox.bottom-2); pDC->LineTo(rcBox.left, rcBox.top); pDC->LineTo(rcBox.right-1, rcBox.top); pDC->SelectObject(pOldPen); delete pPen2; } static void Draw3DButtonFrame(CDC *pDC, CRect rcButton, BOOL bFocus) { CPen *pPen, *pOldPen; CBrush GrayBrush(GetSysColor(COLOR_BTNSHADOW)); CBrush BlackBrush(GetSysColor(COLOR_BTNFACE)); pPen = new CPen(PS_SOLID, 1, GetSysColor(COLOR_WINDOWFRAME)); pOldPen = pDC->SelectObject(pPen); // Draw gray outside pDC->FrameRect(&rcButton, &BlackBrush); rcButton.InflateRect(-1, -1); pDC->MoveTo(rcButton.left+1, rcButton.top); pDC->LineTo(rcButton.right-1, rcButton.top); pDC->MoveTo(rcButton.left+1, rcButton.bottom-1); pDC->LineTo(rcButton.right-1, rcButton.bottom-1); pDC->MoveTo(rcButton.left, rcButton.top+1); pDC->LineTo(rcButton.left, rcButton.bottom-1); pDC->MoveTo(rcButton.right-1, rcButton.top+1); pDC->LineTo(rcButton.right-1, rcButton.bottom-1); if (bFocus) { rcButton.InflateRect(-3, -3); pDC->FrameRect(&rcButton, &GrayBrush); } pDC->SelectObject(pOldPen); delete pPen; } ///////////////////////////////////////////////////////////////////////////// // CCalcDlg message handlers int CCalcDlg::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDialog::OnCreate(lpCreateStruct) == -1) return -1; return 0; } void CCalcDlg::OnDestroy() { // All history items have a CString on the heap associated with them. We delete // the strings here (as WM_DELETEITEM is only saent for owner-draw combos). for (int ii = 0; ii < ctl_edit_combo_.GetCount(); ++ii) { CString * ps = (CString *)ctl_edit_combo_.GetItemDataPtr(ii); if (ps != NULL) { delete ps; ctl_edit_combo_.SetItemDataPtr(ii, NULL); // set it to NULL to be safe } } CDialog::OnDestroy(); small_fnt_.DeleteObject(); med_fnt_.DeleteObject(); if (m_pBrush != NULL) { delete m_pBrush; m_pBrush = NULL; } // Save some settings to the in file/registry aa_->WriteProfileInt("Calculator", "Base", radix_); aa_->WriteProfileInt("Calculator", "Bits", bits_); aa_->WriteProfileInt("Calculator", "signed", signed_ ? 1 : 0); std::string ss; ss = memory_.get_str(10); aa_->WriteProfileString("Calculator", "Memory", ss.c_str()); if (state_ <= CALCINTEXPR) // This test avoids errors being displayed during shutdown calc_binary(); ss = current_.get_str(10); aa_->WriteProfileString("Calculator", "Current", ss.c_str()); } void CCalcDlg::OnSize(UINT nType, int cx, int cy) // WM_SIZE { if (!inited_) return; if (cy < m_sizeInitial.cy*3/2) { //SetDlgItemText(IDC_RADIX_GROUP, ""); //SetDlgItemText(IDC_BITS_GROUP, ""); GetDlgItem(IDC_RADIX)->SetFont(&small_fnt_); GetDlgItem(IDC_BITS)->SetFont(&small_fnt_); } else { //SetDlgItemText(IDC_RADIX_GROUP, "Base"); //SetDlgItemText(IDC_BITS_GROUP, "Bits"); GetDlgItem(IDC_RADIX)->SetFont(&med_fnt_); GetDlgItem(IDC_BITS)->SetFont(&med_fnt_); } if (cx > 0 && m_sizeInitial.cx == -1) m_sizeInitial = CSize(cx, cy); CDialog::OnSize(nType, cx, cy); } BOOL CCalcDlg::OnHelpInfo(HELPINFO* pHelpInfo) { // Note: calling theApp.HtmlHelpWmHelp here seems to make the window go behind // and then disappear when mouse up event is seen. The only soln I could // find after a lot of experimentation is to do it later (in OnKickIdle). // theApp.HtmlHelpWmHelp((HWND)pHelpInfo->hItemHandle, id_pairs); help_hwnd_ = (HWND)pHelpInfo->hItemHandle; return TRUE; } void CCalcDlg::OnContextMenu(CWnd* pWnd, CPoint point) { theApp.HtmlHelpContextMenu(pWnd, id_pairs); } CBrush * CCalcDlg::m_pBrush = NULL; BOOL CCalcDlg::OnEraseBkgnd(CDC *pDC) { // We check for changed look in erase background event as it's done // before other drawing. This is necessary (to update m_pBrush etc) // because there is no message sent when the look changes. static UINT saved_look = 0; if (theApp.m_nAppLook != saved_look) { // Create new brush used for background of static controls if (m_pBrush != NULL) delete m_pBrush; m_pBrush = new CBrush(afxGlobalData.clrBarFace); saved_look = theApp.m_nAppLook; } CRect rct; GetClientRect(&rct); // Fill the background with a colour that matches the current BCG theme (and hence sometimes with the Windows Theme) pDC->FillSolidRect(rct, afxGlobalData.clrBarFace); return TRUE; } HBRUSH CCalcDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { if (nCtlColor == CTLCOLOR_STATIC) { pDC->SetBkMode(TRANSPARENT); // Make sure text has no background if (m_pBrush != NULL) return (HBRUSH)*m_pBrush; } return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); } LRESULT CCalcDlg::OnKickIdle(WPARAM, LPARAM) { if (m_first) { setup_resizer(); m_first = false; } update_controls(); // If help_hwnd_ is not NULL then help has been requested for that window if (help_hwnd_ != (HWND)0) { theApp.HtmlHelpWmHelp(help_hwnd_, id_pairs); help_hwnd_ = (HWND)0; // signal that it was handled } return FALSE; } void CCalcDlg::OnSelHistory() { CString ss; int nn = ctl_edit_combo_.GetCurSel(); if (nn == -1) return; // why does this happen? // If the history list has a result string with a radix value in it then // restore the radix before we restore the expression CString * ps = (CString *)ctl_edit_combo_.GetItemDataPtr(nn); if (ps != NULL && ps->GetLength() > 0 && (*ps)[0] != ' ') { char buf[2]; buf[0] = (*ps)[0]; buf[1] = '\0'; long rr = strtol(buf, NULL, 36); if (rr != radix_) change_base(rr); orig_radix_ = radix_; } ctl_edit_combo_.GetLBText(nn, ss); SetStr(ss); op_ = binop_none; previous_unary_op_ = unary_none; left_= ""; right_ = "(" + ss + ")"; } void CCalcDlg::OnChangeRadix() { if (!inited_) return; // no point in doing anything yet // Get value from radix edit box and convert to an integer CString ss; GetDlgItemText(IDC_RADIX, ss); int radix = strtol(ss, NULL, 10); if (radix > 1 && radix <= 36) // If new value is within out valid range then change_base(radix); // set the new radix value } void CCalcDlg::OnChangeBits() { if (!inited_) return; // no point in doing anything yet CString ss; GetDlgItemText(IDC_BITS, ss); int bits = strtol(ss, NULL, 10); if (bits >= 0 && bits <= 32767) // Use SHORT_MAX as max bits allowed as this is the biggest spin control value (and allows for huge numbers) change_bits(bits); } void CCalcDlg::OnChangeSigned() { if (!inited_) return; // no point in doing anything yet CButton *pb = (CButton *)GetDlgItem(IDC_CALC_SIGNED); change_signed(pb->GetCheck() == BST_CHECKED); } void CCalcDlg::OnTooltipsShow(NMHDR* pNMHDR, LRESULT* pResult) { // Without this tooltips come up behind the calculator when it's floating SetWindowPos(&wndTopMost, 0,0,0,0, SWP_NOSIZE|SWP_NOMOVE|SWP_NOACTIVATE); *pResult = 0; return; } BOOL CCalcDlg::PreTranslateMessage(MSG* pMsg) { if (ttc_.m_hWnd != 0) { ttc_.Activate(TRUE); ttc_.RelayEvent(pMsg); } if (pMsg->message == WM_KEYDOWN) { if (pMsg->wParam > VK_F1 && pMsg->wParam <= VK_F12) { switch(pMsg->wParam) { case VK_F5: OnHex(); break; case VK_F6: OnDecimal(); break; case VK_F7: OnOctal(); break; case VK_F8: OnBinary(); break; case VK_F9: On64bit(); break; // F10 is a system key (see WM_SYSKEYDOWN below) // case VK_F10: // On32bit(); // break; case VK_F11: On16bit(); break; case VK_F12: On8bit(); break; } return TRUE; } } else if (pMsg->message == WM_SYSKEYDOWN && pMsg->wParam == VK_F10) { // Handle F10 press On32bit(); return TRUE; } // Check if we are in an edit control to avoid confusing things with WM_CHAR handling if (pMsg->hwnd == edit_.m_hWnd || pMsg->hwnd == GetDlgItem(IDC_BITS)->m_hWnd || pMsg->hwnd == GetDlgItem(IDC_RADIX)->m_hWnd) { return CDialog::PreTranslateMessage(pMsg); // Just do base class handling } if (pMsg->message == WM_CHAR) { if (pMsg->wParam == '\r') { OnEquals(); // Carriage Return return TRUE; } else if (pMsg->wParam == '\x0C') { OnMemClear(); // ^L return TRUE; } else if (pMsg->wParam == '\x12') { OnMemGet(); // ^R return TRUE; } else if (pMsg->wParam == '\x0D') { OnMemStore(); // ^M return TRUE; } else if (pMsg->wParam == '\x10') { OnMemAdd(); // ^P return TRUE; } else if (isprint(pMsg->wParam)) { // Typing a digit (or any printable char) anywhere in the calculator adds the char to // the calculator edit control and sets focus to allow more typing/editing in the control. edit_.SetFocus(); edit_.SetSel(edit_.GetWindowTextLength(), -1); edit_.SendMessage(WM_CHAR, pMsg->wParam, 1); return TRUE; } } return CDialog::PreTranslateMessage(pMsg); } #define IDC_FIRST_BLUE IDC_DIGIT_0 #define IDC_FIRST_RED IDC_BACKSPACE #define IDC_FIRST_BLACK IDC_MARK_STORE #define IDC_FIRST_PURPLE IDC_POW void CCalcDlg::OnDrawItem(int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct) { if (!IsVisible()) return; ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON); CDC *pDC = CDC::FromHandle(lpDrawItemStruct->hDC); COLORREF cr = pDC->GetTextColor(); // Save text colour to restore later if (lpDrawItemStruct->itemState & ODS_DISABLED) pDC->SetTextColor(::GetSysColor(COLOR_GRAYTEXT)); else if (nIDCtl >= IDC_FIRST_BLUE && nIDCtl < IDC_FIRST_RED) pDC->SetTextColor(RGB(0, 0, 0xC0)); else if (nIDCtl >= IDC_FIRST_RED && nIDCtl < IDC_FIRST_BLACK) pDC->SetTextColor(RGB(0xC0, 0, 0)); else if (nIDCtl >= IDC_FIRST_BLACK && nIDCtl < IDC_FIRST_PURPLE) pDC->SetTextColor(RGB(0x0, 0, 0)); else if (nIDCtl >= IDC_FIRST_PURPLE) pDC->SetTextColor(RGB(0x80, 0, 0x80)); CRect rcButton(lpDrawItemStruct->rcItem); rcButton.InflateRect(-2, -2); if ((lpDrawItemStruct->itemState & ODS_SELECTED) == 0) { ::Draw3DFrame(pDC, rcButton, GetSysColor(COLOR_BTNSHADOW), GetSysColor(COLOR_BTNHIGHLIGHT)); rcButton.InflateRect(-1, -1); ::Draw3DFrame(pDC, rcButton, GetSysColor(COLOR_BTNSHADOW), GetSysColor(COLOR_BTNHIGHLIGHT)); rcButton.InflateRect(-1, -1); } pDC->FillSolidRect(&rcButton, GetSysColor(COLOR_BTNFACE)); if (nIDCtl == IDC_UNARY_SQUARE) { RECT rct = lpDrawItemStruct->rcItem; rct.right -= (rct.right - rct.left)/5; rct.top += (rct.bottom - rct.top)/10; pDC->DrawText("n", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); rct = lpDrawItemStruct->rcItem; rct.left += (rct.right - rct.left)/5; rct.bottom -= (rct.bottom - rct.top)/5; pDC->DrawText("2", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); } else if (nIDCtl == IDC_UNARY_SQUARE_ROOT) { RECT rct = lpDrawItemStruct->rcItem; rct.left += (rct.right - rct.left)/5; rct.top += (rct.bottom - rct.top)/10; pDC->DrawText("n", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); // Now draw the square root symbol CPen *ppen = pDC->SelectObject(&purple_pen); rct = lpDrawItemStruct->rcItem; pDC->MoveTo(rct.left + 3*(rct.right - rct.left)/10, rct.top + (rct.bottom - rct.top)/2); pDC->LineTo(rct.left + (rct.right - rct.left)/3, rct.top + 2*(rct.bottom - rct.top)/3); pDC->LineTo(rct.left + (rct.right - rct.left)/2, rct.top + (rct.bottom - rct.top)/3); pDC->LineTo(rct.left + 3*(rct.right - rct.left)/4, rct.top + (rct.bottom - rct.top)/3); pDC->SelectObject(ppen); } else if (nIDCtl == IDC_UNARY_CUBE) { RECT rct = lpDrawItemStruct->rcItem; rct.right -= (rct.right - rct.left)/5; rct.top += (rct.bottom - rct.top)/10; pDC->DrawText("n", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); rct = lpDrawItemStruct->rcItem; rct.left += (rct.right - rct.left)/5; rct.bottom -= (rct.bottom - rct.top)/5; pDC->DrawText("3", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); } else if (nIDCtl == IDC_POW) { RECT rct = lpDrawItemStruct->rcItem; rct.right -= (rct.right - rct.left)/4; pDC->DrawText("m", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); rct = lpDrawItemStruct->rcItem; rct.left += (rct.right - rct.left)/4; rct.bottom -= (rct.bottom - rct.top)/4; pDC->DrawText("n", &rct, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); } else { CString str; GetDlgItem(nIDCtl)->GetWindowText(str); pDC->DrawText(str, &lpDrawItemStruct->rcItem, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_NOPREFIX); } rcButton = lpDrawItemStruct->rcItem; ::Draw3DButtonFrame(pDC, rcButton, (lpDrawItemStruct->itemState & ODS_FOCUS) != 0); // Restore text colour ::SetTextColor(lpDrawItemStruct->hDC, cr); CDialog::OnDrawItem(nIDCtl, lpDrawItemStruct); } // This actually goes to a calculated address. Unlike the "Store Cursor" button, // the result is calculated (saves pressing "=" button) and the view is given focus // after the current cursor position has been moved. void CCalcDlg::OnGo() // Move cursor to current value { CHexEditView *pview = GetView(); if (pview == NULL) { // This should not happen unless we are playing back a macro no_file_error(); return; } if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Jump with invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } else if (state_ == CALCINTEXPR) { state_ = edit_.update_value(true); // re-eval the expression allowing side-effects now ASSERT(state_ == CALCINTEXPR); state_ = CALCINTLIT; // This is so that edit_.put() [below] will use current_ instead of current_str_ } // First work out if we are jumping by address or sector bool sector = ctl_go_.m_nMenuResult == ID_GOSECTOR; // If the value in current_ is not there as a result of a calculation then // save it before it is lost. save_value_to_macro(); calc_binary(); check_for_error(); // check for overflow/error edit_.put(); add_hist(); // xxx make sure it also gets added to hex or dec jump list edit_.put(); CString ss; edit_.GetWindowText(ss); if (sector) { ss = "Go To sector " + ss + " "; } else if (radix_ == 16) { mm_->NewHexJump(ss); // update jump tools with new address ss = "Go To (hex) " + ss + " "; } else if (radix_ == 10) { mm_->NewDecJump(ss); ss = "Go To (decimal) " + ss + " "; } else { ss = "Go To (calc) " + ss + " "; } mpz_class addr, eof, sector_size; addr = get_norm(current_); if (addr < 0) { TaskMessageBox("Jump to negative address", "The calculator cannot jump to an address before the start of file."); aa_->mac_error_ = 10; return; } mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); mpz_set_ui64(sector_size.get_mpz_t(), pview->GetDocument()->GetSectorSize()); if (sector && sector_size > 0) addr *= sector_size; if (addr > eof) { TaskMessageBox("Jump past EOF", "The calculator cannot jump to an address past the end of file."); aa_->mac_error_ = 10; return; } pview->MoveWithDesc(ss, mpz_get_ui64(addr.get_mpz_t())); // Give view the focus if (pview != pview->GetFocus()) pview->SetFocus(); state_ = CALCINTRES; //orig_radix_ = radix_; // remember starting radix source_ = km_result; aa_->SaveToMacro(km_go); } void CCalcDlg::OnBigEndian() { // toggle_endian(); ASSERT(GetView() != NULL); if (GetView() != NULL) { GetView()->OnToggleEndian(); aa_->SaveToMacro(km_big_endian, (__int64)-1); } } void CCalcDlg::On8bit() { change_bits(8); } void CCalcDlg::On16bit() { change_bits(16); } void CCalcDlg::On32bit() { change_bits(32); } void CCalcDlg::On64bit() { change_bits(64); } void CCalcDlg::OnInfbit() { change_bits(0); } void CCalcDlg::OnBinary() { change_base(2); change_signed(false); } void CCalcDlg::OnOctal() { change_base(8); change_signed(false); } void CCalcDlg::OnDecimal() { change_base(10); change_signed(true); } void CCalcDlg::OnHex() { if (!inited_) return; // Can't work out why we get this message during dialog creation change_base(16); change_signed(false); } void CCalcDlg::OnBackspace() // Delete back one digit { edit_.SendMessage(WM_CHAR, '\b', 1); } void CCalcDlg::OnClearEntry() // Zero current value { current_ = 0; state_ = CALCINTUNARY; edit_.put(); edit_.get(); set_right(); source_ = aa_->recording_ ? km_user_str : km_result; aa_->SaveToMacro(km_clear_entry); } void CCalcDlg::OnClear() // Zero current and remove any operators/brackets { op_ = binop_none; previous_unary_op_ = unary_none; current_ = 0; state_ = CALCINTRES; edit_.put(); edit_.get(); left_.Empty(); set_right(); source_ = aa_->recording_ ? km_user_str : km_result; aa_->SaveToMacro(km_clear); } void CCalcDlg::OnEquals() // Calculate result { TRACE("CALCULATOR EQUALS: expr:%.200s\r\n", (const char *)CString(get_expr(true))); // Check if we are in error state or we don't have a valid expression if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ == CALCOTHER) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_INVALID, "The current value or expression is invalid."); //mm_->StatusBarText("Invalid expression"); return; } else if (op_ != binop_none && state_ > CALCINTEXPR) { not_int_error(); return; } // If the current calc. value is not there as a result of a calculation then save it before // it is lost. We need to do this before update_value() wipes out the expr. with the result. save_value_to_macro(); // Now we can eval. the expression with side effects and placing reult in current_str_ if (state_ >= CALCINTEXPR) state_ = edit_.update_value(true); if (state_ == CALCINTEXPR) state_ = CALCINTLIT; // This is so that edit_.put() [below] will use current_ instead of current_str_ calc_binary(); check_for_error(); // check for overflow/error edit_.put(); // We have a valid result so add it to the history list (even if just added) add_hist(); edit_.put(); // removing from hist list (in add_hist) seems to clear the edit box sometimes so put it back switch (state_) { case CALCINTRES: case CALCINTUNARY: case CALCINTBINARY: case CALCINTLIT: // Result is an integer so we can do special integer things (like enable GO button) state_ = CALCINTRES; break; case CALCREALEXPR: case CALCDATEEXPR: case CALCSTREXPR: case CALCBOOLEXPR: // Result is a valid value of a non-integer type state_ = CALCSTATE(state_ + 20); // convert valid "expression" to "result" (eg CALCDATEXEPR -> CALCDATERES) break; case CALCOVERFLOW: // it happens case CALCERROR: break; case CALCINTEXPR: // should have been converted to CALCINTLIT default: ASSERT(0); // these cases should not occur return; } //orig_radix_ = radix_; // remember starting radix source_ = km_result; aa_->SaveToMacro(km_equals); } // ---------- History and Expression Display --------- // add_hist() adds to the history list of previous calculations by adding to the // drop-down list (in which the main edit box resides) when a result is generated. // The expression that created the result is added as a string to the drop-list, and // the data-item associated with that contains the result (as a string). // The result is displayed in atip window when the user holds the mouse over an // expression in the history list. // Duplicates are removed from the list but since the same expression can generate // different result (eg if it use a variable name) then a duplicate is only one // where both the expression and the result match. void CCalcDlg::add_hist() { // We get the expression that generated the result as a full string to be added // to the tape (history window) and the drop down (history list) CString strTape = CString(get_expr(true)); // string to be added to calc tape window CString strDrop; // string to be added to drop down history if (strTape.GetLength() <= 100) strDrop = strTape; else strDrop = strTape.Left(100) + "..."; // Don't add a really long string to the drop down // The first char of the string stores the radix as a char ('2'-'9', 'A'-'Z') char buf[64]; if (state_ > CALCINTEXPR) buf[0] = ' '; // space indicates we don't care about the radix because it's not an int else if (orig_radix_ < 10) buf[0] = orig_radix_ + '0'; // 0-9 else buf[0] = orig_radix_ - 10 + 'A'; // A-Z buf[1] = '\0'; CString * pResult = new CString(buf); // Create the string to attach to the new drop-down hist list element // Put the result string on the heap so we can store it in the drop list item data edit_.get(); // Get the result string into current_str_ int len = current_str_.GetLength(); CString strAnswerOrigRadix; // result as string in original radix if (state_ >= CALCINTRES && state_ <= CALCINTEXPR) { // Short int result that needs conversion to original radix int numlen = mpz_sizeinbase(current_.get_mpz_t(), orig_radix_) + 3; char *numbuf = new char[numlen]; numbuf[numlen-1] = '\xCD'; // Get the number as a string mpz_get_str(numbuf, theApp.hex_ucase_? -orig_radix_ : orig_radix_, current_.get_mpz_t()); ASSERT(numbuf[numlen-1] == '\xCD'); strAnswerOrigRadix = numbuf; delete[] numbuf; // Add to the tape (history window) mm_->m_wndCalcHist.Add(strTape + " = " + strAnswerOrigRadix + //CString(radix_ == orig_radix_ ? "" : radix_string(orig_radix_)) ); CString(radix_string(orig_radix_)) ); } else { CString strType; switch (state_) { case CALCREALEXPR: case CALCREALRES: strType = " [REAL (dec)]"; break; case CALCDATEEXPR: case CALCDATERES: strType = " [DATE]"; break; case CALCSTREXPR: case CALCSTRRES: strType = " [STRING]"; break; case CALCBOOLEXPR: case CALCBOOLRES: strType = " [BOOLEAN]"; break; } mm_->m_wndCalcHist.Add(strTape + " = " + (CString)current_str_ + strType); } if (len < 2000 && state_ > CALCINTLIT) { // Short non-int result *pResult += current_str_; } else if (state_ > CALCINTLIT) // not integer - probably a very long string { // Long non-int result *pResult += current_str_.Left(2000); *pResult += " ..."; } else if (len < 2000 && radix_ != orig_radix_) { // Short int result in original radix *pResult += strAnswerOrigRadix; } else if (len < 2000 && radix_ == orig_radix_) { *pResult += current_str_; } else { // Large integer result (displayed in radix 10) const int extra = 2 + 1; // Need room for possible sign, EOS, and dummy (\xCD) byte int numlen = mpz_sizeinbase(current_.get_mpz_t(), 10) + extra; char *numbuf = new char[numlen]; numbuf[numlen-1] = '\xCD'; // Get the number as a string mpz_get_str(numbuf, 10, current_.get_mpz_t()); ASSERT(numbuf[numlen-1] == '\xCD'); // Copy the most sig. digits copying sign if present, including decimal point after 1st digit const char * pin = numbuf; char * pout = buf; if (*pin == '-') { *pout = '-'; ++pin, ++pout; //numlen--; // mpz_sizeinbase does not return room for sign } *pout++ = *pin++; *pout++ = theApp.dec_point_; for (int ii = 0; ii < 40; ++ii) { if (isdigit(*pin) || isalpha(*pin)) *pout++ = *pin; ++pin; } delete[] numbuf; // Add the exponent (decimal) and add initial 'A' to indicate that this number uses base 10 sprintf(pout, " E %d", numlen - 1 - extra); *pResult = CString("A") + buf; } // Find any duplicate entry in the history (expression and result) and remove it for (int ii = 0; ii < ctl_edit_combo_.GetCount(); ++ii) { // Get expression and result for this item CString ss, * ps; ctl_edit_combo_.GetLBText(ii, ss); ps = (CString *)ctl_edit_combo_.GetItemDataPtr(ii); if (ss == strDrop && ps != NULL && *ps == *pResult) { // We also have to delete the string (here and when combo is destroyed) // It would have been easy just to handle WM_DELETEITEM but // this is only sent for owner-draw combo boxes apparently. delete ps; ctl_edit_combo_.DeleteString(ii); // remove this entry break; // exit loop since the same value could not appear again } } // Add the new entry (at the top of the drop-down list) ctl_edit_combo_.InsertString(0, strDrop); ctl_edit_combo_.SetItemDataPtr(0, pResult); } // Combine the current left and right values with active binary operator to get the // expression that will re-create the value in the calculator. // Parentheses are placed around expressions if there would be a precedence issue // when combined with further operations. To avoid the parenthese (eg when just // displaying the result) pass true as the first parameter. ExprStringType CCalcDlg::get_expr(bool no_paren /* = false */) { ExprStringType retval; switch (op_) { case binop_none: if (state_ < CALCINTEXPR || right_[0] == '(' && right_[right_.GetLength()-1] == ')') retval = right_; else retval.Format(EXPRSTR("(%s)"), (const wchar_t *)right_); break; case binop_add: retval.Format(EXPRSTR("(%s + %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_subtract: retval.Format(EXPRSTR("(%s - %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_multiply: retval.Format(EXPRSTR("(%s * %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_divide: retval.Format(EXPRSTR("(%s / %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_mod: retval.Format(EXPRSTR("(%s %% %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_pow: retval.Format(EXPRSTR("pow(%s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_gtr: case binop_gtr_old: retval.Format(EXPRSTR("max(%s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_less: case binop_less_old: retval.Format(EXPRSTR("min(%s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_rol: retval.Format(EXPRSTR("rol(%s, %s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_, bits_as_string()); break; case binop_ror: retval.Format(EXPRSTR("ror(%s, %s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_, bits_as_string()); break; case binop_lsl: retval.Format(EXPRSTR("(%s << %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_lsr: retval.Format(EXPRSTR("(%s >> %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_asr: retval.Format(EXPRSTR("asr(%s, %s, %s)"), (const wchar_t *)left_, (const wchar_t *)right_, bits_as_string()); break; case binop_and: retval.Format(EXPRSTR("(%s & %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_or: retval.Format(EXPRSTR("(%s | %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; case binop_xor: retval.Format(EXPRSTR("(%s ^ %s)"), (const wchar_t *)left_, (const wchar_t *)right_); break; default: ASSERT(0); break; } int len = retval.GetLength(); if (no_paren) return without_parens(retval); else return retval; } // Checks if an expression (in a string) is enclosed in parentheses and if so removes them // and returns the expression (without parentheses) else just returns the input string. ExprStringType CCalcDlg::without_parens(const ExprStringType &ss) { int len = ss.GetLength(); if (len > 0 && ss[0] == '(') { while (--len > 0) { if (ss[len] == ')') return ss.Mid(1, len-1); else if (ss[len] != ' ') break; } } return ss; } // Set right_ (right side of current binary operation) from edit box. // This is done after a value is added or typed into the edit box. // An important consideration is to make sure that the value is evaluated // correctly in the original radix. void CCalcDlg::set_right() { // If there is nothing in the left operand yet we can change the expression radix if (left_.IsEmpty()) orig_radix_ = radix_; previous_unary_op_ = unary_none; if (state_ == CALCERROR) right_ = "***"; else if (radix_ == orig_radix_ || state_ > CALCINTLIT) right_ = current_str_; else { // Add number in original radix int numlen = mpz_sizeinbase(current_.get_mpz_t(), orig_radix_) + 3; char *numbuf = new char[numlen]; numbuf[numlen-1] = '\xCD'; // Get the number as a string mpz_get_str(numbuf, theApp.hex_ucase_? -orig_radix_ : orig_radix_, current_.get_mpz_t()); ASSERT(numbuf[numlen-1] == '\xCD'); right_ = numbuf; delete[] numbuf; } } // Increments the value (right operand) in an expression of the form "(EXPR OP VALUE)". // For example "(N + 3)" becomes "(N + 4)". ExprStringType CCalcDlg::inc_right_operand(const ExprStringType &expr) { // First get the location of the right operand in the string int pos = expr.GetLength() - 1; ASSERT(pos > 0 && expr[pos] == ')'); pos--; while (isalnum(expr[pos])) pos--; ++pos; // move to first digit int replace_pos = pos; // where we add the new value // Workout what radix to use int radix = orig_radix_; // default to current expression radix if (expr[pos] == '0') { ++pos; radix = 8; if (expr[pos] == 'x' || expr[pos] == 'X') { ++pos; radix = 16; } } // Get the current value of the right operand #ifdef UNICODE_TYPE_STRING int operand = wcstol((const wchar_t *)expr + pos, NULL, radix); #else int operand = strtol((const char *)expr + pos, NULL, radix); #endif // Re-create the expression string with incremented operand ExprStringType retval; retval.Format(EXPRSTR("%.*s%s)"), replace_pos, expr, int_as_string(operand + 1)); return retval; } ExprStringType CCalcDlg::bits_as_string() { return int_as_string(bits_); } ExprStringType CCalcDlg::int_as_string(int ii) { ExprStringType retval; int radix = orig_radix_; if (ii < 10 && ii < radix) radix = 10; // no point in doing anything fancy if it is just a single decimal digit switch(radix) { case 8: retval.Format(EXPRSTR("0%o"), ii); break; case 10: retval.Format(EXPRSTR("%d"), ii); break; default: // Just use hex for all other bases (but prefix with 0x to get right value if expression re-evaluated) if (theApp.hex_ucase_) retval.Format(EXPRSTR("0x%X"), ii); else retval.Format(EXPRSTR("0X%x"), ii); break; case 16: if (theApp.hex_ucase_) retval.Format(EXPRSTR("%X"), ii); else retval.Format(EXPRSTR("%x"), ii); break; } return retval; } // ---------- Menu button handlers --------- // Change text colour within a button to grey (disabled) or normal // pp = pointer to CCalcButton // dis = true if to display greyed out else false to display as normal // normal = normal text colour for the button void CCalcDlg::button_colour(CWnd *pp, bool enable, COLORREF normal) { ASSERT(pp != NULL); CCalcButton *pbut = DYNAMIC_DOWNCAST(CCalcButton, pp); ASSERT(pbut != NULL); if (enable) { if (pbut->GetTextColor() != normal) { pbut->SetTextColor(normal); pbut->SetTextHotColor(RGB(0,0,0)); // black pp->Invalidate(); } } else { if (pbut->GetTextColor() != RGB(0xC0, 0xC0, 0xC0)) { pbut->SetTextColor(RGB(0xC0, 0xC0, 0xC0)); // light grey pbut->SetTextHotColor(RGB(0xC0, 0xC0, 0xC0)); pp->Invalidate(); } } } // Rebuild the menus for the menu buttons at the top of the calculator void CCalcDlg::build_menus() { static clock_t last_hex_hist_build = (clock_t)0; static clock_t last_dec_hist_build = (clock_t)0; static clock_t last_var_build = (clock_t)0; CMenu mm, msub; if (last_hex_hist_build < mm_->hex_hist_changed_) { // Hex jump tool history menu mm.CreatePopupMenu(); if (mm_->hex_hist_.size() == 0) { // Display a single disabled menu item, since // disabling the button itself looks ugly mm.AppendMenu(MF_STRING | MF_GRAYED, 0, "(none)"); } else { for (size_t ii = 0; ii < mm_->hex_hist_.size(); ++ii) { // Store filter and use index as menu item ID (but add 1 since 0 means no ID used). mm.AppendMenu(MF_STRING, ii + 1, mm_->hex_hist_[ii]); } } if (ctl_hex_hist_.m_hMenu != (HMENU)0) { ::DestroyMenu(ctl_hex_hist_.m_hMenu); ctl_hex_hist_.m_hMenu = (HMENU)0; } ctl_hex_hist_.m_hMenu = mm.GetSafeHmenu(); mm.Detach(); last_hex_hist_build = mm_->hex_hist_changed_; } if (last_dec_hist_build < mm_->dec_hist_changed_) { // Decimal jump tool history mm.CreatePopupMenu(); if (mm_->dec_hist_.size() == 0) { // Display a single disabled menu item, since // disabling the button itself looks ugly mm.AppendMenu(MF_STRING | MF_GRAYED, 0, "(none)"); } else { for (size_t ii = 0; ii < mm_->dec_hist_.size(); ++ii) { // Store filter and use index as menu item ID (but add 1 since 0 means no ID used). mm.AppendMenu(MF_STRING, ii + 1, mm_->dec_hist_[ii]); } } if (ctl_dec_hist_.m_hMenu != (HMENU)0) { ::DestroyMenu(ctl_dec_hist_.m_hMenu); ctl_dec_hist_.m_hMenu = (HMENU)0; } ctl_dec_hist_.m_hMenu = mm.GetSafeHmenu(); mm.Detach(); last_dec_hist_build = mm_->dec_hist_changed_; } if (last_var_build < mm_->expr_.VarChanged()) { int ii = 1; // Just used to make sure each menu item has a unique ID vector <CString> varNames; mm.CreatePopupMenu(); varNames = mm_->expr_.GetVarNames(CJumpExpr::TYPE_INT); if (!varNames.empty()) { msub.CreatePopupMenu(); for (vector<CString>::const_iterator ps = varNames.begin(); ps != varNames.end(); ++ps) { msub.AppendMenu(MF_STRING, ii++, *ps); } if (msub.GetMenuItemCount() > 0) mm.AppendMenu(MF_POPUP, (UINT)msub.m_hMenu, "&Integer"); msub.DestroyMenu(); } varNames = mm_->expr_.GetVarNames(CJumpExpr::TYPE_REAL); if (!varNames.empty()) { msub.CreatePopupMenu(); for (vector<CString>::const_iterator ps = varNames.begin(); ps != varNames.end(); ++ps) { msub.AppendMenu(MF_STRING, ii++, *ps); } if (msub.GetMenuItemCount() > 0) mm.AppendMenu(MF_POPUP, (UINT)msub.m_hMenu, "&Real"); msub.DestroyMenu(); } varNames = mm_->expr_.GetVarNames(CJumpExpr::TYPE_STRING); if (!varNames.empty()) { msub.CreatePopupMenu(); for (vector<CString>::const_iterator ps = varNames.begin(); ps != varNames.end(); ++ps) { msub.AppendMenu(MF_STRING, ii++, *ps); } if (msub.GetMenuItemCount() > 0) mm.AppendMenu(MF_POPUP, (UINT)msub.m_hMenu, "&String"); msub.DestroyMenu(); } varNames = mm_->expr_.GetVarNames(CJumpExpr::TYPE_BOOLEAN); if (!varNames.empty()) { msub.CreatePopupMenu(); for (vector<CString>::const_iterator ps = varNames.begin(); ps != varNames.end(); ++ps) { msub.AppendMenu(MF_STRING, ii++, *ps); } if (msub.GetMenuItemCount() > 0) mm.AppendMenu(MF_POPUP, (UINT)msub.m_hMenu, "&Boolean"); msub.DestroyMenu(); } varNames = mm_->expr_.GetVarNames(CJumpExpr::TYPE_DATE); if (!varNames.empty()) { msub.CreatePopupMenu(); for (vector<CString>::const_iterator ps = varNames.begin(); ps != varNames.end(); ++ps) { msub.AppendMenu(MF_STRING, ii++, *ps); } if (msub.GetMenuItemCount() > 0) mm.AppendMenu(MF_POPUP, (UINT)msub.m_hMenu, "&Date"); msub.DestroyMenu(); } if (mm.GetMenuItemCount() == 0) { // If there are no vars then display a single disabled // menu item, since disabling the button itself looks ugly. mm.AppendMenu(MF_STRING | MF_GRAYED, 0, "(none)"); } else { // Add menu item to allow all varibales to be deleted mm.AppendMenu(MF_STRING, ID_VARS_CLEAR, "&Clear variables..."); } if (ctl_vars_.m_hMenu != (HMENU)0) { ::DestroyMenu(ctl_vars_.m_hMenu); ctl_vars_.m_hMenu = (HMENU)0; } ctl_vars_.m_hMenu = mm.GetSafeHmenu(); mm.Detach(); last_var_build = mm_->expr_.VarChanged(); } } // Handle selection from hex history menu void CCalcDlg::OnGetHexHist() { if (ctl_hex_hist_.m_nMenuResult != 0) { // Get the text of the menu item selected CMenu menu; menu.Attach(ctl_hex_hist_.m_hMenu); CString ss = get_menu_text(&menu, ctl_hex_hist_.m_nMenuResult); menu.Detach(); ss.Replace(" ", ""); // get rid of padding // We clear the current edit box before adding the chars in 2 cases: // 1. Displaying result - probably want to start a new calculation // 2. Currently just displaying a numeric value - replace it as adding extra digits is just confusing // and otherwise adding more digits may cause an overflow which would be really confusing //if (state_ != CALCOTHER) if (state_ <= CALCINTLIT || state_>= CALCOTHRES) { edit_.SetWindowText(""); state_ = CALCINTUNARY; } if (radix_ != 16) { // We need to convert the hex digits to digits in the current radix __int64 ii = ::_strtoui64(ss, NULL, 16); char buf[72]; ::_i64toa(ii, buf, radix_); ss = buf; } CString strCurr; edit_.GetWindowText(strCurr); edit_.SetFocus(); edit_.SetSel(edit_.GetWindowTextLength(), -1); if (!strCurr.IsEmpty() && !isspace(strCurr[strCurr.GetLength()-1])) edit_.SendMessage(WM_CHAR, (TCHAR)' '); for (int ii = 0; ii < ss.GetLength (); ii++) edit_.SendMessage(WM_CHAR, (TCHAR)ss[ii]); //SetDlgItemText(IDC_OP_DISPLAY, ""); inedit(km_user_str); } } // Handle decimal history menu void CCalcDlg::OnGetDecHist() { if (ctl_dec_hist_.m_nMenuResult != 0) { CMenu menu; menu.Attach(ctl_dec_hist_.m_hMenu); CString ss = get_menu_text(&menu, ctl_dec_hist_.m_nMenuResult); menu.Detach(); ss.Replace(",", "");ss.Replace(".", ""); ss.Replace(" ", ""); // get rid of padding // We clear the current edit box text in 2 cases: // 1. Currently displaying a result of previous calculation - probably want to start a new calculation // 2. Currently just displaying a numeric value - replace it by adding extra digits is just confusing // + otherwise adding more digits may cause an overflow which would be really confusing //if (state_ != CALCOTHER) if (state_ <= CALCINTLIT || state_>= CALCOTHRES) { edit_.SetWindowText(""); state_ = CALCINTUNARY; } if (radix_ != 10) { // We need to convert decimal to the current radix __int64 ii = ::_strtoi64(ss, NULL, 10); char buf[72]; ::_i64toa(ii, buf, radix_); ss = buf; } CString strCurr; edit_.GetWindowText(strCurr); edit_.SetFocus(); edit_.SetSel(edit_.GetWindowTextLength(), -1); if (!strCurr.IsEmpty() && !isspace(strCurr[strCurr.GetLength()-1])) edit_.SendMessage(WM_CHAR, (TCHAR)' '); for (int ii = 0; ii < ss.GetLength (); ii++) edit_.SendMessage(WM_CHAR, (TCHAR)ss[ii]); //SetDlgItemText(IDC_OP_DISPLAY, ""); inedit(km_user_str); } } // Handle vars menu button void CCalcDlg::OnGetVar() { if (ctl_vars_.m_nMenuResult == ID_VARS_CLEAR) { if (AvoidableTaskDialog(IDS_VARS_CLEAR, "Are you sure you want to delete all variables?", NULL, NULL, TDCBF_YES_BUTTON | TDCBF_NO_BUTTON) == IDYES) mm_->expr_.DeleteVars(); } else if (ctl_vars_.m_nMenuResult != 0) { CMenu menu; menu.Attach(ctl_vars_.m_hMenu); CString ss = get_menu_text(&menu, ctl_vars_.m_nMenuResult); menu.Detach(); if (state_ <= CALCINTLIT || state_>= CALCOTHRES) { edit_.SetWindowText(""); state_ = CALCOTHRES; } edit_.SetFocus(); edit_.SetSel(edit_.GetWindowTextLength(), -1); if (!ss.IsEmpty() && isalpha(ss[0]) && toupper(ss[0]) - 'A' + 10 < radix_) edit_.SendMessage(WM_CHAR, (TCHAR)'@'); // Prefix ID with @ so it's not treated as an integer literal for (int ii = 0; ii < ss.GetLength (); ii++) edit_.SendMessage(WM_CHAR, (TCHAR)ss[ii]); //SetDlgItemText(IDC_OP_DISPLAY, ""); inedit(km_user_str); } } // Handle function selection void CCalcDlg::OnGetFunc() { if (ctl_func_.m_nMenuResult != 0) { CMenu menu; menu.Attach(ctl_func_.m_hMenu); CString ss = get_menu_text(&menu, ctl_func_.m_nMenuResult); ss.Replace("&&", "&"); // Double-ampersand is needed in menus to show one &, but now we need to reverse that menu.Detach(); if (state_ <= CALCINTLIT || state_>= CALCOTHRES) { edit_.SetWindowText(""); state_ = CALCOTHER; // must be (incomplete) expression } edit_.SetFocus(); edit_.SetSel(edit_.GetWindowTextLength(), -1); // Remember current location so we can later wipe out the # int start, end; edit_.GetSel(start, end); // First invalidate number conversions (eg case conversions in hex mode, separator removal) by adding non-numeric char edit_.SendMessage(WM_CHAR, (TCHAR)'#'); for (int ii = 0; ii < ss.GetLength (); ii++) edit_.SendMessage(WM_CHAR, (TCHAR)ss[ii]); // Now replace the above non-numeric char (#) with a space ( ) edit_.SetSel(start, start + 1); edit_.SendMessage(WM_CHAR, (TCHAR)' '); // Select everything between brackets end = start + ss.Find(')') + 1; start += ss.Find('(') + 2; edit_.SetSel(start, end); //SetDlgItemText(IDC_OP_DISPLAY, ""); inedit(km_user_str); } } // ---------- Digits for entering numbers ---------- void CCalcDlg::OnDigit0() { do_digit('0'); } void CCalcDlg::OnDigit1() { do_digit('1'); } void CCalcDlg::OnDigit2() { do_digit('2'); } void CCalcDlg::OnDigit3() { do_digit('3'); } void CCalcDlg::OnDigit4() { do_digit('4'); } void CCalcDlg::OnDigit5() { do_digit('5'); } void CCalcDlg::OnDigit6() { do_digit('6'); } void CCalcDlg::OnDigit7() { do_digit('7'); } void CCalcDlg::OnDigit8() { do_digit('8'); } void CCalcDlg::OnDigit9() { do_digit('9'); } void CCalcDlg::OnDigitA() { do_digit('A'); } void CCalcDlg::OnDigitB() { do_digit('B'); } void CCalcDlg::OnDigitC() { do_digit('C'); } void CCalcDlg::OnDigitD() { do_digit('D'); } void CCalcDlg::OnDigitE() { do_digit('E'); } void CCalcDlg::OnDigitF() { do_digit('F'); } // ----- Binary operators ---------- void CCalcDlg::OnAdd() { do_binop(binop_add); } void CCalcDlg::OnSubtract() { do_binop(binop_subtract); } void CCalcDlg::OnMultiply() { do_binop(binop_multiply); } void CCalcDlg::OnDivide() { do_binop(binop_divide); } void CCalcDlg::OnMod() { do_binop(binop_mod); } void CCalcDlg::OnPow() { do_binop(binop_pow); } void CCalcDlg::OnAnd() { do_binop(binop_and); } void CCalcDlg::OnOr() { do_binop(binop_or); } void CCalcDlg::OnXor() { do_binop(binop_xor); } void CCalcDlg::OnLsl() { do_binop(binop_lsl); } void CCalcDlg::OnLsr() { do_binop(binop_lsr); } void CCalcDlg::OnAsr() { do_binop(binop_asr); } void CCalcDlg::OnRol() { do_binop(binop_rol); } void CCalcDlg::OnRor() { do_binop(binop_ror); } void CCalcDlg::OnGtr() // Returns the larger of it's 2 operands { do_binop(binop_gtr); } void CCalcDlg::OnLess() // Returns the smaller of it's 2 operands { do_binop(binop_less); } // --------- Unary operators ----------- void CCalcDlg::OnUnaryAt() { do_unary(unary_at); } void CCalcDlg::OnUnaryRol() { do_unary(unary_rol); } void CCalcDlg::OnUnaryRor() { do_unary(unary_ror); } void CCalcDlg::OnUnaryLsl() { do_unary(unary_lsl); } void CCalcDlg::OnUnaryLsr() { do_unary(unary_lsr); } void CCalcDlg::OnUnaryAsr() { do_unary(unary_asr); } void CCalcDlg::OnUnaryNot() { do_unary(unary_not); } void CCalcDlg::OnUnaryFlip() // Flip bytes { do_unary(unary_flip); } void CCalcDlg::OnUnaryRev() // Reverse bits { do_unary(unary_rev); } void CCalcDlg::OnUnarySign() { do_unary(unary_sign); } void CCalcDlg::OnUnaryInc() { do_unary(unary_inc); } void CCalcDlg::OnUnaryDec() { do_unary(unary_dec); } void CCalcDlg::OnUnarySquare() { do_unary(unary_square); } void CCalcDlg::OnUnarySquareRoot() { do_unary(unary_squareroot); } void CCalcDlg::OnUnaryCube() { do_unary(unary_cube); } void CCalcDlg::OnUnaryFactorial() { do_unary(unary_factorial); } // ------- Calculator memory funcs ---------- void CCalcDlg::OnMemGet() { current_ = memory_; state_ = CALCINTUNARY; check_for_error(); // check for overflow & display error messages edit_.put(); edit_.get(); set_right(); inedit(km_memget); } void CCalcDlg::OnMemStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } memory_ = get_norm(current_); if (!aa_->refresh_off_ && IsVisible()) { button_colour(GetDlgItem(IDC_MEM_GET), true, RGB(0x40, 0x40, 0x40)); // TODO This works but we have to also update tooltip after MC, M+, M- buttons, and perhaps also after radix changes // which means we can't just use the current text from the edit box. // Plus we should also display using the current radix and bits AND update after macros with refresh off. //// Update tooltip //CString ss; //edit_.GetWindowText(ss); //ttc_.UpdateTipText("Memory [" + ss + "] (Ctrl+R)", GetDlgItem(IDC_MEM_GET)); } save_value_to_macro(); aa_->SaveToMacro(km_memstore); } void CCalcDlg::OnMemClear() { memory_ = 0; if (!aa_->refresh_off_ && IsVisible()) { button_colour(GetDlgItem(IDC_MEM_GET), false, RGB(0x40, 0x40, 0x40)); } aa_->SaveToMacro(km_memclear); } void CCalcDlg::OnMemAdd() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } memory_ += get_norm(current_); if (!aa_->refresh_off_ && IsVisible()) { button_colour(GetDlgItem(IDC_MEM_GET), true, RGB(0x40, 0x40, 0x40)); } save_value_to_macro(); aa_->SaveToMacro(km_memadd); } void CCalcDlg::OnMemSubtract() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } memory_ -= get_norm(current_); if (!aa_->refresh_off_ && IsVisible()) { //update_file_buttons(); button_colour(GetDlgItem(IDC_MEM_GET), true, RGB(0x40, 0x40, 0x40)); } save_value_to_macro(); aa_->SaveToMacro(km_memsubtract); } // ----------- Mark functions -------------- void CCalcDlg::OnMarkGet() // Position of mark in the file { CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class val; mpz_set_ui64(val.get_mpz_t(), pview->GetMark()); current_ = val; state_ = CALCINTUNARY; check_for_error(); // check for overflow & display error messages edit_.put(); edit_.get(); set_right(); inedit(km_markget); } void CCalcDlg::OnMarkStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class eof, new_mark; mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); // current eof new_mark = get_norm(current_); if (new_mark < 0 || new_mark > eof) { if (new_mark < 0) TaskMessageBox("Address is negative", "The calculator cannot move the mark to before the start of file."); else TaskMessageBox("Address is past EOF", "The calculator cannot move the mark past the end of file."); aa_->mac_error_ = 10; return; } pview->SetMark(mpz_get_ui64(new_mark.get_mpz_t())); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // //update_file_buttons(); //} save_value_to_macro(); aa_->SaveToMacro(km_markstore); } void CCalcDlg::OnMarkClear() { CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } pview->SetMark(0); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // //update_file_buttons(); //} aa_->SaveToMacro(km_markclear); } void CCalcDlg::OnMarkAdd() // Add current value to mark { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class eof, mark, new_mark; mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); // current eof mpz_set_ui64(mark.get_mpz_t(), pview->GetMark()); // current mark new_mark = mark + get_norm(current_); if (new_mark < 0 || new_mark > eof) { if (new_mark < 0) TaskMessageBox("Address is negative", "The calculator cannot move the mark to before the start of file."); else TaskMessageBox("Address is past EOF", "The calculator cannot move the mark past the end of file."); aa_->mac_error_ = 10; return; } pview->SetMark(mpz_get_ui64(new_mark.get_mpz_t())); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // //update_file_buttons(); //} save_value_to_macro(); aa_->SaveToMacro(km_markadd); } void CCalcDlg::OnMarkSubtract() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class eof, mark, new_mark; mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); // current eof mpz_set_ui64(mark.get_mpz_t(), pview->GetMark()); // current mark new_mark = mark - get_norm(current_); if (new_mark < 0 || new_mark > eof) { if (new_mark < 0) TaskMessageBox("Address is negative", "The calculator cannot move the mark to before the start of file."); else TaskMessageBox("Address is past EOF", "The calculator cannot move the mark past the end of file."); aa_->mac_error_ = 10; return; } pview->SetMark(mpz_get_ui64(new_mark.get_mpz_t())); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // //update_file_buttons(); //} save_value_to_macro(); aa_->SaveToMacro(km_marksubtract); } // ----------- Other file get funcs ------------- // Get bytes at the mark into calculator // - the number of bytes is determined by bits_ // - byte order is determined by active file endian-ness (display_.big_endian) void CCalcDlg::OnMarkAt() { if (!get_bytes(-2)) // get data at mark { state_ = CALCERROR; return; } ASSERT(state_ == CALCINTUNARY); //check_for_error(); // overflow should not happen? edit_.put(); edit_.get(); set_right(); inedit(km_markat); } // Get address of caret (or start of selection) void CCalcDlg::OnSelGet() { CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } FILE_ADDRESS start, end; pview->GetSelAddr(start, end); mpz_class val; mpz_set_ui64(val.get_mpz_t(), start); current_ = val; state_ = CALCINTUNARY; check_for_error(); // check for overflow & display error messages edit_.put(); edit_.get(); set_right(); inedit(km_selget); } // Get byte(s) at the caret position - # of bytes is determined by bits_ void CCalcDlg::OnSelAt() // Value in file at cursor { if (!get_bytes(-3)) // get data at cursor/selection { state_ = CALCERROR; return; } ASSERT(state_ == CALCINTUNARY); //check_for_error(); // overflow should not occur? edit_.put(); edit_.get(); set_right(); inedit(km_selat); } // Get the selection length void CCalcDlg::OnSelLen() { CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } FILE_ADDRESS start, end; pview->GetSelAddr(start, end); mpz_class val; mpz_set_ui64(val.get_mpz_t(), end - start); current_ = val; state_ = CALCINTUNARY; check_for_error(); // check for overflow & display error messages edit_.put(); edit_.get(); set_right(); inedit(km_sellen); } // Get the length of file void CCalcDlg::OnEofGet() // Length of file { CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class val; mpz_set_ui64(val.get_mpz_t(), pview->GetDocument()->length()); current_ = val; state_ = CALCINTUNARY; check_for_error(); // check for overflow & display error messages edit_.put(); edit_.get(); set_right(); inedit(km_eofget); } // ----------- File change funcs ------------- // Change the byte(s) at (and after) the "mark" void CCalcDlg::OnMarkAtStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } FILE_ADDRESS mark = 0; if (GetView() != NULL) mark = GetView()->GetMark(); // save mark (NULL view error message displayed in put_bytes) if (!put_bytes(-2)) { aa_->mac_error_ = 10; return; } if (!GetView()->OverType()) GetView()->SetMark(mark); // Inserting at mark would have move it forward //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // //update_file_buttons(); //} save_value_to_macro(); aa_->SaveToMacro(km_markatstore); } // Set the caret position (or selection start) void CCalcDlg::OnSelStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } mpz_class eof, val; mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); // current eof val = get_norm(current_); if (val < 0) { TaskMessageBox("Negative address", "The calculator cannot move the current address before the start of file."); aa_->mac_error_ = 10; return; } if (val > eof) { TaskMessageBox("Address past EOF", "The calculator cannot move the current address past the end of file."); aa_->mac_error_ = 10; return; } pview->MoveWithDesc("Set Cursor in Calculator", GetValue()); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // // update_file_buttons(); // done indirectly through MoveToAddress via MoveWithDesc //} save_value_to_macro(); aa_->SaveToMacro(km_selstore); } // Change the byte(s) at (and after) the caret (start of selection) void CCalcDlg::OnSelAtStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } if (!put_bytes(-3)) { aa_->mac_error_ = 10; return; } //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // //update_file_buttons(); //} save_value_to_macro(); aa_->SaveToMacro(km_selatstore); } // Set the selection length from the calculator void CCalcDlg::OnSelLenStore() { // First check that we can perform an integer operation if (state_ == CALCERROR) { make_noise("Calculator Error"); AvoidableTaskDialog(IDS_CALC_ERROR, "You cannot perform this operation on an invalid value.", "The previous calculation caused an error.\n\n" "Please press the calculator \"Clear\" button to continue."); //mm_->StatusBarText("Operation on invalid value."); aa_->mac_error_ = 10; return; } else if (state_ > CALCINTEXPR) { not_int_error(); return; } CHexEditView *pview = GetView(); if (pview == NULL) { no_file_error(); return; } FILE_ADDRESS start, end; pview->GetSelAddr(start, end); mpz_class eof, addr, len; mpz_set_ui64(eof.get_mpz_t(), pview->GetDocument()->length()); // current eof mpz_set_ui64(addr.get_mpz_t(), start); len = get_norm(current_); if (len < 0) { TaskMessageBox("Negative selection length", "The calculator cannot make a selection with length less than zero."); aa_->mac_error_ = 10; return; } if (addr + len > eof) { TaskMessageBox("Selection past EOF", "The calculator cannot make a selection which extends past the end of file."); aa_->mac_error_ = 10; return; } len += addr; pview->MoveToAddress(mpz_get_ui64(addr.get_mpz_t()), mpz_get_ui64(len.get_mpz_t())); //if (!aa_->refresh_off_ && IsVisible()) //{ // edit_.SetFocus(); // edit_.Put(); // // update_file_buttons(); // done indirectly through MoveToAddress //} save_value_to_macro(); aa_->SaveToMacro(km_sellenstore); }
mit
jconst/SoundDrop
SoundDrop/libpd/pure-data/src/s_utf8.c
1
7329
/* Basic UTF-8 manipulation routines by Jeff Bezanson placed in the public domain Fall 2005 This code is designed to provide the utilities you need to manipulate UTF-8 as an internal string encoding. These functions do not perform the error checking normally needed when handling UTF-8 data, so if you happen to be from the Unicode Consortium you will want to flay me alive. I do this because error checking can be performed at the boundaries (I/O), with these routines reserved for higher performance on data known to be valid. modified by Bryan Jurish (moo) March 2009 + removed some unneeded functions (escapes, printf etc), added others */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #ifdef WIN32 #include <malloc.h> #else #include <alloca.h> #endif #include "s_utf8.h" static const uint32_t offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL, 0x03C82080UL, 0xFA082080UL, 0x82082080UL }; static const char trailingBytesForUTF8[256] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 }; /* returns length of next utf-8 sequence */ int u8_seqlen(char *s) { return trailingBytesForUTF8[(unsigned int)(unsigned char)s[0]] + 1; } /* conversions without error checking only works for valid UTF-8, i.e. no 5- or 6-byte sequences srcsz = source size in bytes, or -1 if 0-terminated sz = dest size in # of wide characters returns # characters converted dest will always be L'\0'-terminated, even if there isn't enough room for all the characters. if sz = srcsz+1 (i.e. 4*srcsz+4 bytes), there will always be enough space. */ int u8_utf8toucs2(uint16_t *dest, int sz, char *src, int srcsz) { uint16_t ch; char *src_end = src + srcsz; int nb; int i=0; while (i < sz-1) { nb = trailingBytesForUTF8[(unsigned char)*src]; if (srcsz == -1) { if (*src == 0) goto done_toucs; } else { if (src + nb >= src_end) goto done_toucs; } ch = 0; switch (nb) { /* these fall through deliberately */ case 3: ch += (unsigned char)*src++; ch <<= 6; case 2: ch += (unsigned char)*src++; ch <<= 6; case 1: ch += (unsigned char)*src++; ch <<= 6; case 0: ch += (unsigned char)*src++; } ch -= offsetsFromUTF8[nb]; dest[i++] = ch; } done_toucs: dest[i] = 0; return i; } /* srcsz = number of source characters, or -1 if 0-terminated sz = size of dest buffer in bytes returns # characters converted dest will only be '\0'-terminated if there is enough space. this is for consistency; imagine there are 2 bytes of space left, but the next character requires 3 bytes. in this case we could NUL-terminate, but in general we can't when there's insufficient space. therefore this function only NUL-terminates if all the characters fit, and there's space for the NUL as well. the destination string will never be bigger than the source string. */ int u8_ucs2toutf8(char *dest, int sz, uint16_t *src, int srcsz) { uint16_t ch; int i = 0; char *dest_end = dest + sz; while (srcsz<0 ? src[i]!=0 : i < srcsz) { ch = src[i]; if (ch < 0x80) { if (dest >= dest_end) return i; *dest++ = (char)ch; } else if (ch < 0x800) { if (dest >= dest_end-1) return i; *dest++ = (ch>>6) | 0xC0; *dest++ = (ch & 0x3F) | 0x80; } else { if (dest >= dest_end-2) return i; *dest++ = (ch>>12) | 0xE0; *dest++ = ((ch>>6) & 0x3F) | 0x80; *dest++ = (ch & 0x3F) | 0x80; } i++; } if (dest < dest_end) *dest = '\0'; return i; } /* moo: get byte length of character number, or 0 if not supported */ int u8_wc_nbytes(uint32_t ch) { if (ch < 0x80) return 1; if (ch < 0x800) return 2; if (ch < 0x10000) return 3; if (ch < 0x200000) return 4; return 0; /*-- bad input --*/ } int u8_wc_toutf8(char *dest, uint32_t ch) { if (ch < 0x80) { dest[0] = (char)ch; return 1; } if (ch < 0x800) { dest[0] = (ch>>6) | 0xC0; dest[1] = (ch & 0x3F) | 0x80; return 2; } if (ch < 0x10000) { dest[0] = (ch>>12) | 0xE0; dest[1] = ((ch>>6) & 0x3F) | 0x80; dest[2] = (ch & 0x3F) | 0x80; return 3; } if (ch < 0x110000) { dest[0] = (ch>>18) | 0xF0; dest[1] = ((ch>>12) & 0x3F) | 0x80; dest[2] = ((ch>>6) & 0x3F) | 0x80; dest[3] = (ch & 0x3F) | 0x80; return 4; } return 0; } /*-- moo --*/ int u8_wc_toutf8_nul(char *dest, uint32_t ch) { int sz = u8_wc_toutf8(dest,ch); dest[sz] = '\0'; return sz; } /* charnum => byte offset */ int u8_offset(char *str, int charnum) { char *string = str; while (charnum > 0 && *string != '\0') { if (*string++ & 0x80) { if (!isutf(*string)) { ++string; if (!isutf(*string)) { ++string; if (!isutf(*string)) { ++string; } } } } --charnum; } return (int)(string - str); } /* byte offset => charnum */ int u8_charnum(char *s, int offset) { int charnum = 0; char *string = s; char *const end = string + offset; while (string < end && *string != '\0') { if (*string++ & 0x80) { if (!isutf(*string)) { ++string; if (!isutf(*string)) { ++string; if (!isutf(*string)) { ++string; } } } } ++charnum; } return charnum; } /* reads the next utf-8 sequence out of a string, updating an index */ uint32_t u8_nextchar(char *s, int *i) { uint32_t ch = 0; int sz = 0; do { ch <<= 6; ch += (unsigned char)s[(*i)++]; sz++; } while (s[*i] && !isutf(s[*i])); ch -= offsetsFromUTF8[sz-1]; return ch; } /* number of characters */ int u8_strlen(char *s) { int count = 0; int i = 0; while (u8_nextchar(s, &i) != 0) count++; return count; } void u8_inc(char *s, int *i) { if (s[(*i)++] & 0x80) { if (!isutf(s[*i])) { ++(*i); if (!isutf(s[*i])) { ++(*i); if (!isutf(s[*i])) { ++(*i); } } } } } void u8_dec(char *s, int *i) { (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i)); }
mit
Edimartin/edk-source
edk/Camera2D.cpp
1
11322
#include "Camera2D.h" /* Library Camera2D - 2D camera in a 2D World Copyright 2013 Eduardo Moura Sales Martins (edimartin@gmail.com) 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. */ #ifdef printMessages #warning " Inside Camera2D.cpp" #endif edk::Camera2D::Camera2D(){ // this->start(); } edk::Camera2D::Camera2D(edk::vec2f32 position){ // this->start(); //set the position this->positionSave = this->position = position; } edk::Camera2D::Camera2D(edk::float32 posX,edk::float32 posY){ // this->start(); //set the position this->positionSave = this->position = edk::vec2f32(posX,posY); } edk::Camera2D::~Camera2D(){ //dtor } void edk::Camera2D::start(){ //set the start position of the camera this->positionSave = this->position = edk::vec2f32(0.0f,0.0f); //set the screen to -1 1; this->setSize(1.0f,1.0f); //set the up this->up = edk::vec2f32(0,1); //set the start angle this->angle = 0.f; } //SETTERS //set the size void edk::Camera2D::setSize(edk::size2f32 size){ // this->size=size*0.5f; } void edk::Camera2D::setSize(edk::float32 sizeW,edk::float32 sizeH){ // return this->setSize(edk::size2f32(sizeW,sizeH)); } void edk::Camera2D::setSizeW(edk::float32 width){ this->size.width = width*0.5f; } void edk::Camera2D::setSizeH(edk::float32 height){ this->size.height = height*0.5f; } //Set a rectangle to the camera bool edk::Camera2D::setRect(edk::rectf32 rect){ //test the size if(rect.size.width && rect.size.height){ //set the position of the camera this->position.x = rect.origin.x + (rect.size.width*0.5f); this->position.y = rect.origin.y + (rect.size.height*0.5f); //copi the new size for the camera this->size = rect.size * 0.5f; //then return true return true; } //else return false return false; } bool edk::Camera2D::setRect(edk::vec2f32 origin,size2f32 size){ //else return false return this->setRect(edk::rectf32(origin.x,origin.y,size.width,size.height)); } bool edk::Camera2D::setRect(edk::float32 originX,edk::float32 originY,edk::float32 width,edk::float32 height){ //else return false return this->setRect(edk::vec2f32(originX,originY),size2f32(width,height)); } //Set the points of the camera in the world bool edk::Camera2D::setPoints(edk::vec2f32 p1, edk::vec2f32 p2){ //test if p2 is bigger than p1 if(p2.x>p1.x && p2.y>p1.y){ //set the size of the camera this->size = size2f32(p2.x-p1.x,p2.y-p1.y); //then set the position of the camera this->position = edk::vec2f32( p1.x + (this->size.width*0.5f) , p1.y + (this->size.height*0.5f)); //then return true return true; } //else return false return false; } bool edk::Camera2D::setPoints(edk::float32 p1X,edk::float32 p1Y,edk::float32 p2X,edk::float32 p2Y){ // return setPoints(edk::vec2f32(p1X,p1Y), edk::vec2f32(p2X,p2Y)); } //save the position in the save buffer to calculate the distance void edk::Camera2D::savePosition(){ this->positionSave = this->position; } void edk::Camera2D::pastePosition(){ this->position = this->positionSave; } //GETTERS //get the size edk::size2f32 edk::Camera2D::getSize(){ //return the size double of the size return edk::size2f32(this->size*2); } //return the camera rect edk::rectf32 edk::Camera2D::getRect(){ return edk::rectf32(this->position.x - (this->size.width),this->position.y - (this->size.height), this->size.width*2.f,this->size.height*2.f ); } //get the distance beetween the position and save distance edk::float32 edk::Camera2D::getDistanceFromSave(){ return edk::Math::pythagoras(this->getTranslateFromSave()); } //get the camera translate from saveDistance edk::vec2f32 edk::Camera2D::getTranslateFromSave(){ return this->position - this->positionSave; } //draw the camera void edk::Camera2D::draw(){ // //test if are NOT using GUmodelview if(!edk::GU::guUsingMatrix(GU_PROJECTION)) //then set to use modelView edk::GU::guUseMatrix(GU_PROJECTION); edk::GU::guLoadIdentity(); this->drawOrthoOnly(); } void edk::Camera2D::drawOrthoOnly(){ edk::GU::guUseOrtho(-this->size.width, this->size.width, -this->size.height, this->size.height, -1.f,//nea 1.f//far ); //update the shaking animations this->animShakingAngle.updateClockAnimation(); if(this->animShakingAngle.isPlaying()){ //calculate the angle of shaking this->up = edk::Math::rotate(edk::vec2f32(1,0),(((this->angle + this->animShakingAngle.getClockX())*-1)+360.f)+90); } else{ this->up = edk::Math::rotate(edk::vec2f32(1,0),((this->angle*-1)+360.f)+90); } //shake position this->animShakingPosition.updateClockAnimation(); if(this->animShakingPosition.isPlaying()){ this->tempPosition.x = this->position.x+this->animShakingPosition.getClockX(); this->tempPosition.y = this->position.y+this->animShakingPosition.getClockY(); edk::GU::guLookAt(this->tempPosition.x,this->tempPosition.y,1.f, this->tempPosition.x,this->tempPosition.y,0.f, this->up.x,this->up.y,0.f ); } else{ edk::GU::guLookAt(this->position.x,this->position.y,1.f, this->position.x,this->position.y,0.f, this->up.x,this->up.y,0.f ); } } void edk::Camera2D::drawOrthoOnly(edk::float32 seconds){ edk::GU::guUseOrtho(-this->size.width, this->size.width, -this->size.height, this->size.height, -1.f,//nea 1.f//far ); //update the shaking animations this->animAngle.updateClockAnimation(seconds); if(this->animAngle.isPlaying()){ //calculate the angle of shaking this->up = edk::Math::rotate(edk::vec2f32(1,0),(((this->angle + this->animAngle.getClockX())*-1)+360.f)+90); } else{ this->up = edk::Math::rotate(edk::vec2f32(1,0),((this->angle*-1)+360.f)+90); } //shake position this->animPosition.updateClockAnimation(seconds); if(this->animPosition.isPlaying()){ this->tempPosition.x = this->position.x+this->animPosition.getClockX(); this->tempPosition.y = this->position.y+this->animPosition.getClockY(); edk::GU::guLookAt(this->tempPosition.x,this->tempPosition.y,1.f, this->tempPosition.x,this->tempPosition.y,0.f, this->up.x,this->up.y,0.f ); } else{ edk::GU::guLookAt(this->position.x,this->position.y,1.f, this->position.x,this->position.y,0.f, this->up.x,this->up.y,0.f ); } } //move the camera void edk::Camera2D::moveLeft(edk::float32 dist){ // this->position.x-=dist; } void edk::Camera2D::moveLeft(edk::float64 dist){ // this->position.x-=dist; } void edk::Camera2D::moveRight(edk::float32 dist){ // this->position.x+=dist; } void edk::Camera2D::moveRight(edk::float64 dist){ // this->position.x+=dist; } void edk::Camera2D::moveUp(edk::float32 dist){ // this->position.y+=dist; } void edk::Camera2D::moveUp(edk::float64 dist){ // this->position.y+=dist; } void edk::Camera2D::moveDown(edk::float32 dist){ // this->position.y-=dist; } void edk::Camera2D::moveDown(edk::float64 dist){ // this->position.y-=dist; } void edk::Camera2D::move(edk::vec2f32 position){ this->position+=position; } void edk::Camera2D::move(edk::float32 x,edk::float32 y){ this->move(edk::vec2f32(x,y)); } void edk::Camera2D::scaleX(edk::float32 dist){ // this->size.width+=dist*0.5f; } void edk::Camera2D::scaleX(edk::float64 dist){ // this->size.width+=dist*0.5f; } void edk::Camera2D::scaleY(edk::float32 dist){ // this->size.height+=dist*0.5f; } void edk::Camera2D::scaleY(edk::float64 dist){ // this->size.height+=dist*0.5f; } //set camera angle void edk::Camera2D::setAngle(edk::float32 angle){ //set the angle this->angle = angle; while(this->angle>360.f)this->angle-=360.f; while(this->angle<0.f)this->angle+=360.f; } //rotate the camera void edk::Camera2D::rotateCamera(edk::float32 angle){ this->setAngle(this->angle+angle); } //get the camera angle edk::float32 edk::Camera2D::getAngle(){ return this->angle; } //update the camera animations void edk::Camera2D::updateAnimations(){ this->animPosition.updateClockAnimation(); this->animAngle.updateClockAnimation(); if(this->animPosition.isPlaying()){ this->position.x = this->animPosition.getClockX(); this->position.y = this->animPosition.getClockY(); } if(this->animAngle.isPlaying()){ this->angle = this->animAngle.getClockX(); } } //start the animation bool edk::Camera2D::addShakingAngle(edk::float32 position,edk::float32 percent,edk::float32 interpolationDistance){ //stop the last animation this->animAngle.stop(); this->animAngle.cleanAnimations(); //create the shaking animation if(this->animAngle.addShakingFramesX(position,percent,interpolationDistance)){ this->animAngle.playForward(); //return true; return true; } return false; } bool edk::Camera2D::addShakingPosition(edk::vec2f32 position,edk::float32 random,edk::float32 percent,edk::float32 interpolationDistance){ //stop the last animation this->animPosition.stop(); this->animPosition.cleanAnimations(); //create the shaking animation if(this->animPosition.addShakingFramesXY(position,random,percent,interpolationDistance)){ this->animPosition.playForward(); //return true; return true; } return false; } //operator to copy the cameras bool edk::Camera2D::cloneFrom(edk::Camera2D* cam){ if(cam){ this->size = cam->size; return true; } return false; }
mit
RCP1/hexapod-kinematics
src/math/vector3d.cpp
1
3797
#include "vector3d.h" #include "mathConstants.h" #include <math.h> #include <string.h> Vector3d::Vector3d(float x, float y, float z) : x(x), y(y), z(z) { } Vector3d::Vector3d(const float* val, uint8_t dimension) { memset(&m_data, 0, s_dimension * sizeof(float)); for (uint8_t i = 0; i < dimension; ++i) { this->m_data[i] = val[i]; } } Vector3d::Vector3d(const Vector3d& other) { for (uint8_t i = 0; i < s_dimension; ++i) { this->m_data[i] = other.m_data[i]; } } uint8_t Vector3d::isBigger(const Vector3d& source) const { uint8_t resultBitmap = 0; for (uint8_t i = 0; i < s_dimension; ++i) { if (this->m_data[i] > source.m_data[i]) resultBitmap |= (0x01 << i); } return resultBitmap; } uint8_t Vector3d::isSmaller(const Vector3d& source) const { uint8_t resultBitmap = 0; for (uint8_t i = 0; i < s_dimension; ++i) { if (this->m_data[i] < source.m_data[i]) resultBitmap |= (0x01 << i); } return resultBitmap; } uint8_t Vector3d::isEqual(const Vector3d& source) const { uint8_t resultBitmap = 0; for (uint8_t i = 0; i < s_dimension; ++i) { if ((float)fabs(this->m_data[i] - source.m_data[i]) < math::epsilonFloat) resultBitmap |= (0x01 << i); } return resultBitmap; } Vector3d& Vector3d::operator+=(const Vector3d& source) { for (uint8_t i = 0; i < s_dimension; ++i) { this->m_data[i] += source.m_data[i]; } return *this; } Vector3d& Vector3d::operator-=(const Vector3d& source) { for (uint8_t i = 0; i < s_dimension; ++i) { this->m_data[i] -= source.m_data[i]; } return *this; } Vector3d Vector3d::operator/(const float scalar) const { if (scalar < math::epsilonFloat) { // Division through zero return *this; } Vector3d tempVec(*this); for (uint8_t i = 0; i < this->s_dimension; ++i) { tempVec.m_data[i] /= scalar; } return tempVec; } Vector3d& Vector3d::operator/=(const float scalar) { if (scalar < math::epsilonFloat) { // Division through zero return *this; } for (uint8_t i = 0; i < this->s_dimension; ++i) { this->m_data[i] /= scalar; } return *this; } Vector3d Vector3d::operator*(const float scalar) const { Vector3d tempVec(*this); for (uint8_t i = 0; i < this->s_dimension; ++i) { tempVec.m_data[i] *= scalar; } return tempVec; } Vector3d& Vector3d::operator*=(const float scalar) { for (uint8_t i = 0; i < this->s_dimension; ++i) { this->m_data[i] *= scalar; } return *this; } float Vector3d::operator*(const Vector3d& source) const { // scalar product return dot(source); } float Vector3d::dot(const Vector3d& source) const { float dotResult; for (uint8_t i = 0; i < s_dimension; ++i) { dotResult += this->m_data[i] * source.m_data[i]; } return dotResult; } Vector3d Vector3d::cross(const Vector3d& source) const { Vector3d crossedVec; crossedVec.x = this->y * source.z - this->z * source.y; crossedVec.y = this->z * source.x - this->x * source.z; crossedVec.z = this->x * source.y - this->y * source.x; return crossedVec; } void Vector3d::norm() { float length = this->length(); if (length < math::epsilonFloat) { return; } *this /= length; } float Vector3d::length() { float squareRoot = 0.f; for (uint8_t i = 0; i < s_dimension; ++i) { squareRoot += (m_data[i] * m_data[i]); } squareRoot = sqrtf(squareRoot); return squareRoot; } void Vector3d::clear() { for (uint8_t i = 0; i < s_dimension; ++i) { m_data[i] = 0.f; } }
mit
dscotese/bitcoin
src/node/interfaces.cpp
1
30052
// Copyright (c) 2018-2021 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 <addrdb.h> #include <banman.h> #include <chain.h> #include <chainparams.h> #include <deploymentstatus.h> #include <external_signer.h> #include <init.h> #include <interfaces/chain.h> #include <interfaces/handler.h> #include <interfaces/node.h> #include <interfaces/wallet.h> #include <mapport.h> #include <net.h> #include <net_processing.h> #include <netaddress.h> #include <netbase.h> #include <node/blockstorage.h> #include <node/coin.h> #include <node/context.h> #include <node/transaction.h> #include <node/ui_interface.h> #include <policy/feerate.h> #include <policy/fees.h> #include <policy/policy.h> #include <policy/rbf.h> #include <policy/settings.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <rpc/protocol.h> #include <rpc/server.h> #include <shutdown.h> #include <support/allocators/secure.h> #include <sync.h> #include <timedata.h> #include <txmempool.h> #include <uint256.h> #include <univalue.h> #include <util/check.h> #include <util/system.h> #include <util/translation.h> #include <validation.h> #include <validationinterface.h> #include <warnings.h> #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <any> #include <memory> #include <optional> #include <utility> #include <boost/signals2/signal.hpp> using interfaces::BlockTip; using interfaces::Chain; using interfaces::FoundBlock; using interfaces::Handler; using interfaces::MakeHandler; using interfaces::Node; using interfaces::WalletLoader; namespace node { namespace { #ifdef ENABLE_EXTERNAL_SIGNER class ExternalSignerImpl : public interfaces::ExternalSigner { public: ExternalSignerImpl(::ExternalSigner signer) : m_signer(std::move(signer)) {} std::string getName() override { return m_signer.m_name; } private: ::ExternalSigner m_signer; }; #endif class NodeImpl : public Node { private: ChainstateManager& chainman() { return *Assert(m_context->chainman); } public: explicit NodeImpl(NodeContext& context) { setContext(&context); } void initLogging() override { InitLogging(*Assert(m_context->args)); } void initParameterInteraction() override { InitParameterInteraction(*Assert(m_context->args)); } bilingual_str getWarnings() override { return GetWarnings(true); } uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); } bool baseInitialize() override { return AppInitBasicSetup(gArgs) && AppInitParameterInteraction(gArgs, /*use_syscall_sandbox=*/false) && AppInitSanityChecks() && AppInitLockDataDirectory() && AppInitInterfaces(*m_context); } bool appInitMain(interfaces::BlockAndHeaderTipInfo* tip_info) override { return AppInitMain(*m_context, tip_info); } void appShutdown() override { Interrupt(*m_context); Shutdown(*m_context); } void startShutdown() override { StartShutdown(); // Stop RPC for clean shutdown if any of waitfor* commands is executed. if (gArgs.GetBoolArg("-server", false)) { InterruptRPC(); StopRPC(); } } bool shutdownRequested() override { return ShutdownRequested(); } void mapPort(bool use_upnp, bool use_natpmp) override { StartMapPort(use_upnp, use_natpmp); } bool getProxy(Network net, Proxy& proxy_info) override { return GetProxy(net, proxy_info); } size_t getNodeCount(ConnectionDirection flags) override { return m_context->connman ? m_context->connman->GetNodeCount(flags) : 0; } bool getNodesStats(NodesStats& stats) override { stats.clear(); if (m_context->connman) { std::vector<CNodeStats> stats_temp; m_context->connman->GetNodeStats(stats_temp); stats.reserve(stats_temp.size()); for (auto& node_stats_temp : stats_temp) { stats.emplace_back(std::move(node_stats_temp), false, CNodeStateStats()); } // Try to retrieve the CNodeStateStats for each node. if (m_context->peerman) { TRY_LOCK(::cs_main, lockMain); if (lockMain) { for (auto& node_stats : stats) { std::get<1>(node_stats) = m_context->peerman->GetNodeStateStats(std::get<0>(node_stats).nodeid, std::get<2>(node_stats)); } } } return true; } return false; } bool getBanned(banmap_t& banmap) override { if (m_context->banman) { m_context->banman->GetBanned(banmap); return true; } return false; } bool ban(const CNetAddr& net_addr, int64_t ban_time_offset) override { if (m_context->banman) { m_context->banman->Ban(net_addr, ban_time_offset); return true; } return false; } bool unban(const CSubNet& ip) override { if (m_context->banman) { m_context->banman->Unban(ip); return true; } return false; } bool disconnectByAddress(const CNetAddr& net_addr) override { if (m_context->connman) { return m_context->connman->DisconnectNode(net_addr); } return false; } bool disconnectById(NodeId id) override { if (m_context->connman) { return m_context->connman->DisconnectNode(id); } return false; } std::vector<std::unique_ptr<interfaces::ExternalSigner>> listExternalSigners() override { #ifdef ENABLE_EXTERNAL_SIGNER std::vector<ExternalSigner> signers = {}; const std::string command = gArgs.GetArg("-signer", ""); if (command == "") return {}; ExternalSigner::Enumerate(command, signers, Params().NetworkIDString()); std::vector<std::unique_ptr<interfaces::ExternalSigner>> result; for (auto& signer : signers) { result.emplace_back(std::make_unique<ExternalSignerImpl>(std::move(signer))); } return result; #else // This result is indistinguishable from a successful call that returns // no signers. For the current GUI this doesn't matter, because the wallet // creation dialog disables the external signer checkbox in both // cases. The return type could be changed to std::optional<std::vector> // (or something that also includes error messages) if this distinction // becomes important. return {}; #endif // ENABLE_EXTERNAL_SIGNER } int64_t getTotalBytesRecv() override { return m_context->connman ? m_context->connman->GetTotalBytesRecv() : 0; } int64_t getTotalBytesSent() override { return m_context->connman ? m_context->connman->GetTotalBytesSent() : 0; } size_t getMempoolSize() override { return m_context->mempool ? m_context->mempool->size() : 0; } size_t getMempoolDynamicUsage() override { return m_context->mempool ? m_context->mempool->DynamicMemoryUsage() : 0; } bool getHeaderTip(int& height, int64_t& block_time) override { LOCK(::cs_main); if (::pindexBestHeader) { height = ::pindexBestHeader->nHeight; block_time = ::pindexBestHeader->GetBlockTime(); return true; } return false; } int getNumBlocks() override { LOCK(::cs_main); return chainman().ActiveChain().Height(); } uint256 getBestBlockHash() override { const CBlockIndex* tip = WITH_LOCK(::cs_main, return chainman().ActiveChain().Tip()); return tip ? tip->GetBlockHash() : Params().GenesisBlock().GetHash(); } int64_t getLastBlockTime() override { LOCK(::cs_main); if (chainman().ActiveChain().Tip()) { return chainman().ActiveChain().Tip()->GetBlockTime(); } return Params().GenesisBlock().GetBlockTime(); // Genesis block's time of current network } double getVerificationProgress() override { const CBlockIndex* tip; { LOCK(::cs_main); tip = chainman().ActiveChain().Tip(); } return GuessVerificationProgress(Params().TxData(), tip); } bool isInitialBlockDownload() override { return chainman().ActiveChainstate().IsInitialBlockDownload(); } bool getReindex() override { return node::fReindex; } bool getImporting() override { return node::fImporting; } void setNetworkActive(bool active) override { if (m_context->connman) { m_context->connman->SetNetworkActive(active); } } bool getNetworkActive() override { return m_context->connman && m_context->connman->GetNetworkActive(); } CFeeRate getDustRelayFee() override { return ::dustRelayFee; } UniValue executeRpc(const std::string& command, const UniValue& params, const std::string& uri) override { JSONRPCRequest req; req.context = m_context; req.params = params; req.strMethod = command; req.URI = uri; return ::tableRPC.execute(req); } std::vector<std::string> listRpcCommands() override { return ::tableRPC.listCommands(); } void rpcSetTimerInterfaceIfUnset(RPCTimerInterface* iface) override { RPCSetTimerInterfaceIfUnset(iface); } void rpcUnsetTimerInterface(RPCTimerInterface* iface) override { RPCUnsetTimerInterface(iface); } bool getUnspentOutput(const COutPoint& output, Coin& coin) override { LOCK(::cs_main); return chainman().ActiveChainstate().CoinsTip().GetCoin(output, coin); } TransactionError broadcastTransaction(CTransactionRef tx, CAmount max_tx_fee, std::string& err_string) override { return BroadcastTransaction(*m_context, std::move(tx), err_string, max_tx_fee, /*relay=*/ true, /*wait_callback=*/ false); } WalletLoader& walletLoader() override { return *Assert(m_context->wallet_loader); } std::unique_ptr<Handler> handleInitMessage(InitMessageFn fn) override { return MakeHandler(::uiInterface.InitMessage_connect(fn)); } std::unique_ptr<Handler> handleMessageBox(MessageBoxFn fn) override { return MakeHandler(::uiInterface.ThreadSafeMessageBox_connect(fn)); } std::unique_ptr<Handler> handleQuestion(QuestionFn fn) override { return MakeHandler(::uiInterface.ThreadSafeQuestion_connect(fn)); } std::unique_ptr<Handler> handleShowProgress(ShowProgressFn fn) override { return MakeHandler(::uiInterface.ShowProgress_connect(fn)); } std::unique_ptr<Handler> handleInitWallet(InitWalletFn fn) override { return MakeHandler(::uiInterface.InitWallet_connect(fn)); } std::unique_ptr<Handler> handleNotifyNumConnectionsChanged(NotifyNumConnectionsChangedFn fn) override { return MakeHandler(::uiInterface.NotifyNumConnectionsChanged_connect(fn)); } std::unique_ptr<Handler> handleNotifyNetworkActiveChanged(NotifyNetworkActiveChangedFn fn) override { return MakeHandler(::uiInterface.NotifyNetworkActiveChanged_connect(fn)); } std::unique_ptr<Handler> handleNotifyAlertChanged(NotifyAlertChangedFn fn) override { return MakeHandler(::uiInterface.NotifyAlertChanged_connect(fn)); } std::unique_ptr<Handler> handleBannedListChanged(BannedListChangedFn fn) override { return MakeHandler(::uiInterface.BannedListChanged_connect(fn)); } std::unique_ptr<Handler> handleNotifyBlockTip(NotifyBlockTipFn fn) override { return MakeHandler(::uiInterface.NotifyBlockTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) { fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()}, GuessVerificationProgress(Params().TxData(), block)); })); } std::unique_ptr<Handler> handleNotifyHeaderTip(NotifyHeaderTipFn fn) override { return MakeHandler( ::uiInterface.NotifyHeaderTip_connect([fn](SynchronizationState sync_state, const CBlockIndex* block) { fn(sync_state, BlockTip{block->nHeight, block->GetBlockTime(), block->GetBlockHash()}, /* verification progress is unused when a header was received */ 0); })); } NodeContext* context() override { return m_context; } void setContext(NodeContext* context) override { m_context = context; } NodeContext* m_context{nullptr}; }; bool FillBlock(const CBlockIndex* index, const FoundBlock& block, UniqueLock<RecursiveMutex>& lock, const CChain& active) { if (!index) return false; if (block.m_hash) *block.m_hash = index->GetBlockHash(); if (block.m_height) *block.m_height = index->nHeight; if (block.m_time) *block.m_time = index->GetBlockTime(); if (block.m_max_time) *block.m_max_time = index->GetBlockTimeMax(); if (block.m_mtp_time) *block.m_mtp_time = index->GetMedianTimePast(); if (block.m_in_active_chain) *block.m_in_active_chain = active[index->nHeight] == index; if (block.m_next_block) FillBlock(active[index->nHeight] == index ? active[index->nHeight + 1] : nullptr, *block.m_next_block, lock, active); if (block.m_data) { REVERSE_LOCK(lock); if (!ReadBlockFromDisk(*block.m_data, index, Params().GetConsensus())) block.m_data->SetNull(); } block.found = true; return true; } class NotificationsProxy : public CValidationInterface { public: explicit NotificationsProxy(std::shared_ptr<Chain::Notifications> notifications) : m_notifications(std::move(notifications)) {} virtual ~NotificationsProxy() = default; void TransactionAddedToMempool(const CTransactionRef& tx, uint64_t mempool_sequence) override { m_notifications->transactionAddedToMempool(tx, mempool_sequence); } void TransactionRemovedFromMempool(const CTransactionRef& tx, MemPoolRemovalReason reason, uint64_t mempool_sequence) override { m_notifications->transactionRemovedFromMempool(tx, reason, mempool_sequence); } void BlockConnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override { m_notifications->blockConnected(*block, index->nHeight); } void BlockDisconnected(const std::shared_ptr<const CBlock>& block, const CBlockIndex* index) override { m_notifications->blockDisconnected(*block, index->nHeight); } void UpdatedBlockTip(const CBlockIndex* index, const CBlockIndex* fork_index, bool is_ibd) override { m_notifications->updatedBlockTip(); } void ChainStateFlushed(const CBlockLocator& locator) override { m_notifications->chainStateFlushed(locator); } std::shared_ptr<Chain::Notifications> m_notifications; }; class NotificationsHandlerImpl : public Handler { public: explicit NotificationsHandlerImpl(std::shared_ptr<Chain::Notifications> notifications) : m_proxy(std::make_shared<NotificationsProxy>(std::move(notifications))) { RegisterSharedValidationInterface(m_proxy); } ~NotificationsHandlerImpl() override { disconnect(); } void disconnect() override { if (m_proxy) { UnregisterSharedValidationInterface(m_proxy); m_proxy.reset(); } } std::shared_ptr<NotificationsProxy> m_proxy; }; class RpcHandlerImpl : public Handler { public: explicit RpcHandlerImpl(const CRPCCommand& command) : m_command(command), m_wrapped_command(&command) { m_command.actor = [this](const JSONRPCRequest& request, UniValue& result, bool last_handler) { if (!m_wrapped_command) return false; try { return m_wrapped_command->actor(request, result, last_handler); } catch (const UniValue& e) { // If this is not the last handler and a wallet not found // exception was thrown, return false so the next handler can // try to handle the request. Otherwise, reraise the exception. if (!last_handler) { const UniValue& code = e["code"]; if (code.isNum() && code.get_int() == RPC_WALLET_NOT_FOUND) { return false; } } throw; } }; ::tableRPC.appendCommand(m_command.name, &m_command); } void disconnect() final { if (m_wrapped_command) { m_wrapped_command = nullptr; ::tableRPC.removeCommand(m_command.name, &m_command); } } ~RpcHandlerImpl() override { disconnect(); } CRPCCommand m_command; const CRPCCommand* m_wrapped_command; }; class ChainImpl : public Chain { private: ChainstateManager& chainman() { return *Assert(m_node.chainman); } public: explicit ChainImpl(NodeContext& node) : m_node(node) {} std::optional<int> getHeight() override { LOCK(::cs_main); const CChain& active = Assert(m_node.chainman)->ActiveChain(); int height = active.Height(); if (height >= 0) { return height; } return std::nullopt; } uint256 getBlockHash(int height) override { LOCK(::cs_main); const CChain& active = Assert(m_node.chainman)->ActiveChain(); CBlockIndex* block = active[height]; assert(block); return block->GetBlockHash(); } bool haveBlockOnDisk(int height) override { LOCK(cs_main); const CChain& active = Assert(m_node.chainman)->ActiveChain(); CBlockIndex* block = active[height]; return block && ((block->nStatus & BLOCK_HAVE_DATA) != 0) && block->nTx > 0; } CBlockLocator getTipLocator() override { LOCK(cs_main); const CChain& active = Assert(m_node.chainman)->ActiveChain(); return active.GetLocator(); } std::optional<int> findLocatorFork(const CBlockLocator& locator) override { LOCK(cs_main); const CChainState& active = Assert(m_node.chainman)->ActiveChainstate(); if (const CBlockIndex* fork = active.FindForkInGlobalIndex(locator)) { return fork->nHeight; } return std::nullopt; } bool findBlock(const uint256& hash, const FoundBlock& block) override { WAIT_LOCK(cs_main, lock); const CChain& active = Assert(m_node.chainman)->ActiveChain(); return FillBlock(m_node.chainman->m_blockman.LookupBlockIndex(hash), block, lock, active); } bool findFirstBlockWithTimeAndHeight(int64_t min_time, int min_height, const FoundBlock& block) override { WAIT_LOCK(cs_main, lock); const CChain& active = Assert(m_node.chainman)->ActiveChain(); return FillBlock(active.FindEarliestAtLeast(min_time, min_height), block, lock, active); } bool findAncestorByHeight(const uint256& block_hash, int ancestor_height, const FoundBlock& ancestor_out) override { WAIT_LOCK(cs_main, lock); const CChain& active = Assert(m_node.chainman)->ActiveChain(); if (const CBlockIndex* block = m_node.chainman->m_blockman.LookupBlockIndex(block_hash)) { if (const CBlockIndex* ancestor = block->GetAncestor(ancestor_height)) { return FillBlock(ancestor, ancestor_out, lock, active); } } return FillBlock(nullptr, ancestor_out, lock, active); } bool findAncestorByHash(const uint256& block_hash, const uint256& ancestor_hash, const FoundBlock& ancestor_out) override { WAIT_LOCK(cs_main, lock); const CChain& active = Assert(m_node.chainman)->ActiveChain(); const CBlockIndex* block = m_node.chainman->m_blockman.LookupBlockIndex(block_hash); const CBlockIndex* ancestor = m_node.chainman->m_blockman.LookupBlockIndex(ancestor_hash); if (block && ancestor && block->GetAncestor(ancestor->nHeight) != ancestor) ancestor = nullptr; return FillBlock(ancestor, ancestor_out, lock, active); } bool findCommonAncestor(const uint256& block_hash1, const uint256& block_hash2, const FoundBlock& ancestor_out, const FoundBlock& block1_out, const FoundBlock& block2_out) override { WAIT_LOCK(cs_main, lock); const CChain& active = Assert(m_node.chainman)->ActiveChain(); const CBlockIndex* block1 = m_node.chainman->m_blockman.LookupBlockIndex(block_hash1); const CBlockIndex* block2 = m_node.chainman->m_blockman.LookupBlockIndex(block_hash2); const CBlockIndex* ancestor = block1 && block2 ? LastCommonAncestor(block1, block2) : nullptr; // Using & instead of && below to avoid short circuiting and leaving // output uninitialized. Cast bool to int to avoid -Wbitwise-instead-of-logical // compiler warnings. return int{FillBlock(ancestor, ancestor_out, lock, active)} & int{FillBlock(block1, block1_out, lock, active)} & int{FillBlock(block2, block2_out, lock, active)}; } void findCoins(std::map<COutPoint, Coin>& coins) override { return FindCoins(m_node, coins); } double guessVerificationProgress(const uint256& block_hash) override { LOCK(cs_main); return GuessVerificationProgress(Params().TxData(), chainman().m_blockman.LookupBlockIndex(block_hash)); } bool hasBlocks(const uint256& block_hash, int min_height, std::optional<int> max_height) override { // hasBlocks returns true if all ancestors of block_hash in specified // range have block data (are not pruned), false if any ancestors in // specified range are missing data. // // For simplicity and robustness, min_height and max_height are only // used to limit the range, and passing min_height that's too low or // max_height that's too high will not crash or change the result. LOCK(::cs_main); if (const CBlockIndex* block = chainman().m_blockman.LookupBlockIndex(block_hash)) { if (max_height && block->nHeight >= *max_height) block = block->GetAncestor(*max_height); for (; block->nStatus & BLOCK_HAVE_DATA; block = block->pprev) { // Check pprev to not segfault if min_height is too low if (block->nHeight <= min_height || !block->pprev) return true; } } return false; } RBFTransactionState isRBFOptIn(const CTransaction& tx) override { if (!m_node.mempool) return IsRBFOptInEmptyMempool(tx); LOCK(m_node.mempool->cs); return IsRBFOptIn(tx, *m_node.mempool); } bool isInMempool(const uint256& txid) override { if (!m_node.mempool) return false; LOCK(m_node.mempool->cs); return m_node.mempool->exists(GenTxid::Txid(txid)); } bool hasDescendantsInMempool(const uint256& txid) override { if (!m_node.mempool) return false; LOCK(m_node.mempool->cs); auto it = m_node.mempool->GetIter(txid); return it && (*it)->GetCountWithDescendants() > 1; } bool broadcastTransaction(const CTransactionRef& tx, const CAmount& max_tx_fee, bool relay, std::string& err_string) override { const TransactionError err = BroadcastTransaction(m_node, tx, err_string, max_tx_fee, relay, /*wait_callback=*/false); // Chain clients only care about failures to accept the tx to the mempool. Disregard non-mempool related failures. // Note: this will need to be updated if BroadcastTransactions() is updated to return other non-mempool failures // that Chain clients do not need to know about. return TransactionError::OK == err; } void getTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants, size_t* ancestorsize, CAmount* ancestorfees) override { ancestors = descendants = 0; if (!m_node.mempool) return; m_node.mempool->GetTransactionAncestry(txid, ancestors, descendants, ancestorsize, ancestorfees); } void getPackageLimits(unsigned int& limit_ancestor_count, unsigned int& limit_descendant_count) override { limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); } bool checkChainLimits(const CTransactionRef& tx) override { if (!m_node.mempool) return true; LockPoints lp; CTxMemPoolEntry entry(tx, 0, 0, 0, false, 0, lp); CTxMemPool::setEntries ancestors; auto limit_ancestor_count = gArgs.GetIntArg("-limitancestorcount", DEFAULT_ANCESTOR_LIMIT); auto limit_ancestor_size = gArgs.GetIntArg("-limitancestorsize", DEFAULT_ANCESTOR_SIZE_LIMIT) * 1000; auto limit_descendant_count = gArgs.GetIntArg("-limitdescendantcount", DEFAULT_DESCENDANT_LIMIT); auto limit_descendant_size = gArgs.GetIntArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000; std::string unused_error_string; LOCK(m_node.mempool->cs); return m_node.mempool->CalculateMemPoolAncestors( entry, ancestors, limit_ancestor_count, limit_ancestor_size, limit_descendant_count, limit_descendant_size, unused_error_string); } CFeeRate estimateSmartFee(int num_blocks, bool conservative, FeeCalculation* calc) override { if (!m_node.fee_estimator) return {}; return m_node.fee_estimator->estimateSmartFee(num_blocks, calc, conservative); } unsigned int estimateMaxBlocks() override { if (!m_node.fee_estimator) return 0; return m_node.fee_estimator->HighestTargetTracked(FeeEstimateHorizon::LONG_HALFLIFE); } CFeeRate mempoolMinFee() override { if (!m_node.mempool) return {}; return m_node.mempool->GetMinFee(gArgs.GetIntArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000); } CFeeRate relayMinFee() override { return ::minRelayTxFee; } CFeeRate relayIncrementalFee() override { return ::incrementalRelayFee; } CFeeRate relayDustFee() override { return ::dustRelayFee; } bool havePruned() override { LOCK(cs_main); return node::fHavePruned; } bool isReadyToBroadcast() override { return !node::fImporting && !node::fReindex && !isInitialBlockDownload(); } bool isInitialBlockDownload() override { return chainman().ActiveChainstate().IsInitialBlockDownload(); } bool shutdownRequested() override { return ShutdownRequested(); } void initMessage(const std::string& message) override { ::uiInterface.InitMessage(message); } void initWarning(const bilingual_str& message) override { InitWarning(message); } void initError(const bilingual_str& message) override { InitError(message); } void showProgress(const std::string& title, int progress, bool resume_possible) override { ::uiInterface.ShowProgress(title, progress, resume_possible); } std::unique_ptr<Handler> handleNotifications(std::shared_ptr<Notifications> notifications) override { return std::make_unique<NotificationsHandlerImpl>(std::move(notifications)); } void waitForNotificationsIfTipChanged(const uint256& old_tip) override { if (!old_tip.IsNull()) { LOCK(::cs_main); const CChain& active = Assert(m_node.chainman)->ActiveChain(); if (old_tip == active.Tip()->GetBlockHash()) return; } SyncWithValidationInterfaceQueue(); } std::unique_ptr<Handler> handleRpc(const CRPCCommand& command) override { return std::make_unique<RpcHandlerImpl>(command); } bool rpcEnableDeprecated(const std::string& method) override { return IsDeprecatedRPCEnabled(method); } void rpcRunLater(const std::string& name, std::function<void()> fn, int64_t seconds) override { RPCRunLater(name, std::move(fn), seconds); } int rpcSerializationFlags() override { return RPCSerializationFlags(); } util::SettingsValue getSetting(const std::string& name) override { return gArgs.GetSetting(name); } std::vector<util::SettingsValue> getSettingsList(const std::string& name) override { return gArgs.GetSettingsList(name); } util::SettingsValue getRwSetting(const std::string& name) override { util::SettingsValue result; gArgs.LockSettings([&](const util::Settings& settings) { if (const util::SettingsValue* value = util::FindKey(settings.rw_settings, name)) { result = *value; } }); return result; } bool updateRwSetting(const std::string& name, const util::SettingsValue& value, bool write) override { gArgs.LockSettings([&](util::Settings& settings) { if (value.isNull()) { settings.rw_settings.erase(name); } else { settings.rw_settings[name] = value; } }); return !write || gArgs.WriteSettingsFile(); } void requestMempoolTransactions(Notifications& notifications) override { if (!m_node.mempool) return; LOCK2(::cs_main, m_node.mempool->cs); for (const CTxMemPoolEntry& entry : m_node.mempool->mapTx) { notifications.transactionAddedToMempool(entry.GetSharedTx(), 0 /* mempool_sequence */); } } NodeContext& m_node; }; } // namespace } // namespace node namespace interfaces { std::unique_ptr<Node> MakeNode(node::NodeContext& context) { return std::make_unique<node::NodeImpl>(context); } std::unique_ptr<Chain> MakeChain(node::NodeContext& context) { return std::make_unique<node::ChainImpl>(context); } } // namespace interfaces
mit
WinnowTag/winnow
tests/check_tagger_builder.c
1
6926
// General info: http://doc.winnowtag.org/open-source // Source code repository: http://github.com/winnowtag // Questions and feedback: contact@winnowtag.org // // Copyright (c) 2007-2011 The Kaphan Foundation // // 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. // contact@winnowtag.org #include <check.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "../src/tagger.h" #include "assertions.h" #include "fixtures.h" static char * document; static ItemCacheOptions item_cache_options = {1, 3650, 2}; static ItemCache * item_cache; static void read_document(void) { setup_fixture_path(); FILE *file; if (NULL != (file = fopen("fixtures/complete_tag.atom", "r"))) { fseek(file, 0, SEEK_END); int size = ftell(file); document = calloc(size, sizeof(char)); fseek(file, 0, SEEK_SET); fread(document, sizeof(char), size, file); document[size] = 0; fclose(file); } system("rm -Rf /tmp/valid-copy && cp -Rf fixtures/valid /tmp/valid-copy && chmod -R 755 /tmp/valid-copy"); item_cache_create(&item_cache, "/tmp/valid-copy", &item_cache_options); } static void free_document(void) { teardown_fixture_path(); if (document) { free(document); } } START_TEST (test_load_tagger_from_tag_definition_document_sets_last_classified) { Tagger *tagger = build_tagger(document, item_cache); assert_equal(1208222183, tagger->last_classified); } END_TEST START_TEST (test_load_tagger_from_tag_definition_document_sets_updated) { Tagger *tagger = build_tagger(document, item_cache); assert_equal(1206840258, tagger->updated); } END_TEST START_TEST (test_load_tagger_from_tag_definition_document_sets_bias) { Tagger *tagger = build_tagger(document, item_cache); assert_equal_f(1.2, tagger->bias); } END_TEST START_TEST (test_load_tagger_from_tag_definition_document_sets_training_url) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->training_url); assert_equal_s("http://trunk.mindloom.org:80/seangeo/tags/a-religion/training.atom", tagger->training_url); } END_TEST START_TEST (test_load_tagger_from_tag_definition_document_sets_classifier_taggings_url) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->classifier_taggings_url); assert_equal_s("http://localhost:8888/results", tagger->classifier_taggings_url); } END_TEST START_TEST (test_load_tagging_from_tag_definition_document_set_tagger_term) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->term); assert_equal_s("a-religion", tagger->term); } END_TEST START_TEST (test_load_tagging_from_tag_definition_document_set_tagger_scheme) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->scheme); assert_equal_s("http://trunk.mindloom.org:80/seangeo/tags/", tagger->scheme); } END_TEST START_TEST (test_load_tagger_from_tag_definition_document_sets_tag_id) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->tag_id); assert_equal_s("http://trunk.mindloom.org:80/seangeo/tags/a-religion", tagger->tag_id); } END_TEST START_TEST (test_loads_right_number_of_positive_examples) { Tagger *tagger = build_tagger(document, item_cache); assert_equal(4, tagger->positive_example_count); } END_TEST START_TEST (test_loads_right_positive_examples) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->positive_examples); assert_equal_s("urn:peerworks.org:entry#753459", tagger->positive_examples[0]); assert_equal_s("urn:peerworks.org:entry#886294", tagger->positive_examples[1]); assert_equal_s("urn:peerworks.org:entry#888769", tagger->positive_examples[2]); assert_equal_s("urn:peerworks.org:entry#884409", tagger->positive_examples[3]); } END_TEST START_TEST (test_loads_right_number_of_negative_examples) { Tagger *tagger = build_tagger(document, item_cache); assert_equal(1, tagger->negative_example_count); } END_TEST START_TEST (test_loads_right_negative_examples) { Tagger *tagger = build_tagger(document, item_cache); assert_not_null(tagger->negative_examples); assert_equal_s("urn:peerworks.org:entry#880389", tagger->negative_examples[0]); } END_TEST Suite * tag_loading_suite(void) { Suite *s = suite_create("Tag_loading"); TCase *tc_complete_tag = tcase_create("complete_tag.atom"); tcase_add_checked_fixture(tc_complete_tag, read_document, free_document); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_last_classified); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_updated); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_bias); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_training_url); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_classifier_taggings_url); tcase_add_test(tc_complete_tag, test_load_tagger_from_tag_definition_document_sets_tag_id); tcase_add_test(tc_complete_tag, test_loads_right_number_of_positive_examples); tcase_add_test(tc_complete_tag, test_loads_right_number_of_negative_examples); tcase_add_test(tc_complete_tag, test_loads_right_positive_examples); tcase_add_test(tc_complete_tag, test_loads_right_negative_examples); tcase_add_test(tc_complete_tag, test_load_tagging_from_tag_definition_document_set_tagger_term); tcase_add_test(tc_complete_tag, test_load_tagging_from_tag_definition_document_set_tagger_scheme); suite_add_tcase(s, tc_complete_tag); return s; } int main(void) { initialize_logging("test.log"); int number_failed; SRunner *sr = srunner_create(tag_loading_suite()); srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); close_log(); return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
mit
jordsti/stigame
StiGame/core/Surface.cpp
1
10675
#include "Surface.h" #include "SDL.h" #include "SDL_image.h" #include "Dimension.h" #include "Primitive.h" #include <string> #include <iostream> #include "Logger.h" #include "SDL2_rotozoom.h" namespace StiGame { Surface::Surface(void) { releaseSurface = true; empty = true; width = 0; height = 0; sdlSurface = SDL_CreateRGBSurface(0, width, height, 32, 0, 0, 0, 0); } Surface::Surface(int m_width,int m_height) { releaseSurface = true; empty = false; width = m_width; height = m_height; //sdl 2 -> default mask to add as a attribute of surface ? sdlSurface = SDL_CreateRGBSurface(0 , width, height, 32, 0, 0, 0, 0); } void Surface::setAlpha(int n_alpha) { if(n_alpha > 255 || n_alpha < 0) { return; } Uint8 r=0,g=0,b=0,a=0; for(int h=0; h<sdlSurface->h; h++) { for(int w=0; w<sdlSurface->w; w++) { Uint8 *pc = (Uint8 *)sdlSurface->pixels + h * sdlSurface->pitch + w * 4; Uint32 pval = *(Uint32 *)pc; SDL_GetRGBA(pval, sdlSurface->format, &r, &g, &b, &a); if(a > n_alpha) { Uint32 nc = SDL_MapRGBA(sdlSurface->format , r, g, b, n_alpha); *(Uint32 *)pc = nc; } } } } void Surface::setTransparentColor(Color *color) { setTransparentColor(color->getRed(), color->getGreen(), color->getBlue()); } void Surface::setTransparentColor(Uint8 r, Uint8 g, Uint8 b) { if(sdlSurface != nullptr) { Uint32 colorkey = SDL_MapRGBA(sdlSurface->format, r, g, b, 0); SDL_SetColorKey(sdlSurface, SDL_TRUE, colorkey); } } void Surface::makeTransparent(void) { if(sdlSurface != nullptr) { Uint32 colorkey = SDL_MapRGBA(sdlSurface->format, 0, 0, 0, 0); SDL_Rect *src = getRect(); SDL_FillRect(sdlSurface, src, colorkey); SDL_SetColorKey(sdlSurface, SDL_TRUE, colorkey); delete src; } } Surface::Surface(SDL_Surface *sur) { releaseSurface = false; if(sur != nullptr) { sdlSurface = sur; empty = false; width = sur->w; height = sur->h; } } Surface::Surface(std::string m_path) { releaseSurface = true; sdlSurface = IMG_Load(m_path.c_str()); if(sdlSurface) { width = sdlSurface->w; height = sdlSurface->h; empty = false; } else { width = 0; height = 0; empty = true; } } void Surface::loadFromFile(const char* path) { freeSurface(); sdlSurface = IMG_Load(path); if(sdlSurface) { width = sdlSurface->w; height = sdlSurface->h; empty = false; } else { width = 0; height = 0; empty = true; } } void Surface::lock(void) { SDL_LockSurface(sdlSurface); } void Surface::unlock(void) { SDL_UnlockSurface(sdlSurface); } Rectangle *Surface::getRectangle(void) { return getRectangle(0, 0); } Rectangle *Surface::getRectangle(int m_x, int m_y) { Rectangle *rect = new Rectangle(); rect->setPoint(m_x, m_y); rect->setDimension(width, height); return rect; } SDL_Rect *Surface::getRect(void) { SDL_Rect *rect = new SDL_Rect(); rect->w = width; rect->h = height; return rect; } SDL_Rect *Surface::getRect(int x, int y) { SDL_Rect *rect = getRect(); rect->x = x; rect->y = y; return rect; } void Surface::freeSurface(void) { if(releaseSurface && sdlSurface != nullptr && width > 0 && height > 0) { SDL_FreeSurface(sdlSurface); width = 0; height = 0; empty = true; sdlSurface = nullptr; } } void Surface::fill(Uint32 c) { SDL_Rect region = SDL_Rect(); region.x = 0; region.y = 0; region.w = width; region.h = height; int rs = SDL_FillRect(sdlSurface, &region, c); } void Surface::fill(Color *c) { if(!c->isMapped()) { c->mapColor(sdlSurface->format); } fill(c->getMap()); } void Surface::fillRect(SDL_Rect *region, Uint32 color) { int rs = SDL_FillRect(sdlSurface, region, color); if(rs != 0) { //shit happens //error Logger::Error(SDL_GetError()); } } void Surface::fillRect(SDL_Rect *region, Color *color) { if(!color->isMapped()) { color->mapColor(sdlSurface->format); } fillRect(region, color->getMap()); } void Surface::fillRect(Rectangle *rect, Color *color) { if(!color->isMapped()) { color->mapColor(sdlSurface->format); } SDL_Rect *region = new SDL_Rect(); region->x = rect->getX(); region->y = rect->getY(); region->w = rect->getWidth(); region->h = rect->getHeight(); fillRect(region, color); delete region; } void Surface::updatePointer(SDL_Surface *surface) { if((sdlSurface != surface && surface != nullptr) || (sdlSurface == surface && surface != nullptr && (sdlSurface->w != width || sdlSurface->h != height))) { width = surface->w; height = surface->h; sdlSurface = surface; } } void Surface::blit(SDL_Surface *src, SDL_Rect *srcRect, SDL_Rect *dstRect) { int rs = SDL_BlitSurface(src, srcRect, sdlSurface, dstRect); if(rs != 0) { //error Logger::Error(SDL_GetError()); } } void Surface::blit(Surface *m_surface, Rectangle *src, Rectangle *dst) { SDL_Rect sdl_src = SDL_Rect(); SDL_Rect sdl_dst = SDL_Rect(); Rectangle::Copy(src, &sdl_src); Rectangle::Copy(dst, &sdl_dst); blit(m_surface, &sdl_src, &sdl_dst); } void Surface::blit(Surface *m_surface, Point *pt) { SDL_Rect sdl_dst; sdl_dst.x = pt->getX(); sdl_dst.y = pt->getY(); sdl_dst.w = m_surface->getWidth(); sdl_dst.h = m_surface->getHeight(); blit(m_surface, &sdl_dst); } void Surface::blit(Surface *m_surface, Rectangle *dst) { SDL_Rect sdl_dst = SDL_Rect(); Rectangle::Copy(dst, &sdl_dst); SDL_Rect src = SDL_Rect(); src.w = m_surface->getWidth(); src.h = m_surface->getHeight(); blit(m_surface, &src, &sdl_dst); } void Surface::blit(Surface *m_surface, SDL_Rect *dst) { SDL_Rect src = SDL_Rect(); src.w = m_surface->getWidth(); src.h = m_surface->getHeight(); blit(m_surface, &src, dst); } void Surface::blit(Surface *src, SDL_Rect *srcRect, SDL_Rect *dstRect) { int rs = SDL_BlitSurface( src->getSDLSurface(), srcRect, sdlSurface, dstRect); if(rs != 0) { //error //std::cout << "Blit Error" << std::endl; //std::cout << SDL_GetError() << std::endl; Logger::Error(SDL_GetError()); } } SDL_Surface *Surface::getSDLSurface(void) { return sdlSurface; } void Surface::draw(Primitive *prim, Color *color) { prim->draw(sdlSurface, color); } void Surface::fill(Primitive *prim, Color *color) { prim->fill(sdlSurface, color); } bool Surface::getReleaseSurface(void) { return releaseSurface; } void Surface::setReleaseSurface(bool m_release) { releaseSurface = m_release; } void Surface::updateSDLRect(SDL_Rect *rect) { rect->w = width; rect->h = height; } void Surface::updateSDLRect(SDL_Rect *rect, int m_x, int m_y) { updateSDLRect(rect); rect->x = m_x; rect->y = m_y; } void Surface::updateSDLRect(SDL_Rect *rect, Point *pt) { updateSDLRect(rect); rect->x = pt->getX(); rect->y = pt->getY(); } Uint32 Surface::getPixelInt(int p_x, int p_y) { Uint32 pc = 0; Uint8 *target_pixel = (Uint8 *)sdlSurface->pixels + p_y * sdlSurface->pitch + p_x * 4; pc = (*(Uint32*)target_pixel); return pc; } Pixel* Surface::getPixel(Point *pt) { return getPixel(pt->getX(), pt->getY()); } Pixel* Surface::getPixel(int p_x, int p_y) { Uint32 px = getPixelInt(p_x, p_y); return new Pixel(px, sdlSurface->format); } void Surface::saveBmp(std::string dest) { if(SDL_SaveBMP(sdlSurface, dest.c_str()) != 0) { //error handling //SDL_GetError(); Logger::Error(SDL_GetError()); } } void Surface::setClipRect(SDL_Rect *rect) { SDL_SetClipRect(sdlSurface, rect); } void Surface::updateClipRect(SDL_Rect *rect) { SDL_GetClipRect(sdlSurface, rect); } void Surface::setBlendMode(SDL_BlendMode mode) { if(SDL_SetSurfaceBlendMode(sdlSurface, mode) != 0) { Logger::Error(SDL_GetError()); } } SDL_BlendMode Surface::getBlendMode(void) { SDL_BlendMode mode; if(SDL_GetSurfaceBlendMode(sdlSurface, &mode) == 0) { Logger::Error(SDL_GetError()); } return mode; } void Surface::setAlphaMod(Uint8 alpha) { if(SDL_SetSurfaceAlphaMod(sdlSurface, alpha)) { Logger::Error(SDL_GetError()); } } Uint8 Surface::getAlphaMod(void) { Uint8 alpha = 255; if(SDL_GetSurfaceAlphaMod(sdlSurface, &alpha) == 0) { Logger::Error(SDL_GetError()); } return alpha; } void Surface::setColorMod(Uint8 r, Uint8 g, Uint8 b) { if(SDL_SetSurfaceColorMod(sdlSurface, r, g, b) == 0) { Logger::Error(SDL_GetError()); } } void Surface::setColorMod(Color *color) { setColorMod(color->getRed(), color->getGreen(), color->getBlue()); } Color Surface::getColotMod(void) { Uint8 r,g,b; if(SDL_GetSurfaceColorMod(sdlSurface, &r, &g, &b) == 0) { Logger::Error(SDL_GetError()); } return Color(r, g, b); } Surface* Surface::shrink(int factor_x, int factor_y) { Surface *shrinked = new Surface(shrinkSurface(sdlSurface, factor_x, factor_y)); shrinked->setReleaseSurface(true); return shrinked; } Surface::~Surface(void) { freeSurface(); } } #ifdef C_WRAPPER extern "C" { StiGame::Surface* Surface_new() { return new StiGame::Surface(); } void Surface_saveBmp(StiGame::Surface *surface, char* dest, int length) { std::string dest_string (dest, length); surface->saveBmp(dest_string); } int Surface_getWidth(StiGame::Surface *surface) { return surface->getWidth(); } int Surface_getHeight(StiGame::Surface *surface) { return surface->getHeight(); } char* Surface_getPixels(StiGame::Surface *surface) { return static_cast<char*>(surface->getSDLSurface()->pixels); } } #endif // C_WRAPPER
mit
rangsimanketkaew/NWChem
src/ddscf/fast/anlfit.F
1
20823
* call anl_fit_init * end double precision function anl_fit(n, l, x) * * $Id$ * implicit none #include "canlfit.fh" integer n, l double precision x c c Return the value of Anl(x) computed from the table c or asymptotic formula. See anl_fit_init. c integer nlcnt, i, k double precision d, value, rx, rx2 c if (x .lt. anl_xcut(n)) then nlcnt = anl_mapnl(l,n) i = int(anl_scale*x) d = x - anl_table(0,i,nlcnt) value = anl_table(anl_order+1,i,nlcnt) do k = anl_order,1,-1 value = anl_table(k,i,nlcnt) + d*value enddo anl_fit = value else rx = 1.0d0/x value = anl_fac(l,n)*rx rx2 = rx*rx do i = 1, l value = value * rx2 enddo anl_fit = value ! anl_fac(l,n)/x**(2*l+1) endif c end subroutine anl_fit_group(nmax, x, values) implicit none #include "canlfit.fh" integer nmax double precision x double precision values(*) c c Return the value of Anl(x) computed from the table c or asymptotic formula for all n and l up to nmax. c c No error checking is being performed for reasons of speed. c c Several values are returned, as follows. c c ind = 1 c do n = 0, nmax c . do l = n, 0, -2 c . values(ind) = anl_fit(n, l, x) c . ind = ind + 1 c . enddo c end c integer i, k, n, l, ind double precision d, d2, d3, value, rx, rx2 double precision rx2l1(0:anl_maxn) c if (x .lt. anl_xcut(nmax)) then i = int(anl_scale*x) d = x - anl_table(0,i,1) if (anl_order .eq. 3) then d2 = d*d d3 = d*d2 do ind = 1, anl_nlsum(nmax) values(ind) = anl_table(1,i,ind) + d*anl_table(2,i,ind) + $ d2*anl_table(3,i,ind) + d3*anl_table(4,i,ind) enddo else do ind = 1, anl_nlsum(nmax) value = anl_table(anl_order+1,i,ind) do k = anl_order,1,-1 value = anl_table(k,i,ind) + d*value enddo values(ind) = value enddo endif else rx = 1.0d0/x rx2 = rx*rx rx2l1(0) = rx ! x^-(2l+1) do l = 1, nmax rx2l1(l) = rx2l1(l-1)*rx2 enddo c ind = 1 do n = 0, nmax do l = n, 0, -2 values(ind) = anl_fac(l,n)*rx2l1(l) ind = ind + 1 enddo enddo endif c end subroutine anl_fit_group_0(nmax, x, values) implicit none #include "canlfit.fh" integer nmax double precision x double precision values(*) c c Return the value of Anl(x) computed from the table c or asymptotic formula for all n and l up to nmax. c c HARDWIRED FOR NMAX = 0 c c No error checking is being performed for reaons of speed. c c Several values are returned, as follows. c c ind = 1 c do n = 0, nmax c . do l = n, 0, -2 c . values(ind) = anl_fit(n, l, x) c . ind = ind + 1 c . enddo c end c integer i, k double precision d, d2, d3 c if (x .lt. anl_xcut(0)) then i = int(anl_scale*x) d = x - anl_table(0,i,1) if (anl_order .eq. 3) then d2 = d*d d3 = d2*d values(1) = anl_table(1,i,1) + d*anl_table(2,i,1) + $ d2*anl_table(3,i,1) + d3*anl_table(4,i,1) else values(1) = anl_table(anl_order+1,i,1) do k = anl_order,1,-1 values(1) = anl_table(k,i,1) + d*values(1) enddo endif else values(1) = anl_fac(0,0)/x endif c end subroutine anl_fit_group_1(nmax, x, values) implicit none #include "canlfit.fh" integer nmax double precision x double precision values(*) c c Return the value of Anl(x) computed from the table c or asymptotic formula for all n and l up to nmax. c c HARDWIRED FOR NMAX = 1 c c No error checking is being performed for reaons of speed. c c Several values are returned, as follows. c c ind = 1 c do n = 0, nmax c . do l = n, 0, -2 c . values(ind) = anl_fit(n, l, x) c . ind = ind + 1 c . enddo c end c integer i, k double precision d, d2, d3, rx, rx2, rx3 c if (x .lt. anl_xcut(1)) then i = int(anl_scale*x) d = x - anl_table(0,i,1) if (anl_order .eq. 3) then d2 = d*d d3 = d2*d values(1) = anl_table(1,i,1) + d*anl_table(2,i,1) + $ d2*anl_table(3,i,1) + d3*anl_table(4,i,1) values(2) = anl_table(1,i,2) + d*anl_table(2,i,2) + $ d2*anl_table(3,i,2) + d3*anl_table(4,i,2) else values(1) = anl_table(anl_order+1,i,1) values(2) = anl_table(anl_order+1,i,2) do k = anl_order,1,-1 values(1) = anl_table(k,i,1) + d*values(1) values(2) = anl_table(k,i,2) + d*values(2) enddo endif else rx = 1.0d0/x rx2 = rx*rx rx3 = rx2*rx values(1) = anl_fac(0,0)*rx values(2) = anl_fac(1,1)*rx3 endif c end subroutine anl_fit_group_2(nmax, x, values) implicit none #include "canlfit.fh" integer nmax double precision x double precision values(*) c c Return the value of Anl(x) computed from the table c or asymptotic formula for all n and l up to nmax. c c HARDWIRED FOR NMAX = 2 c c No error checking is being performed for reaons of speed. c c Several values are returned, as follows. c c ind = 1 c do n = 0, nmax c . do l = n, 0, -2 c . values(ind) = anl_fit(n, l, x) c . ind = ind + 1 c . enddo c end c integer i, k, ind double precision d, d2, d3, rx, rx2, rx3 c if (x .lt. anl_xcut(2)) then ind = 1 i = int(anl_scale*x) d = x - anl_table(0,i,1) if (anl_order .eq. 3) then d2 = d*d d3 = d2*d values(1) = anl_table(1,i,1) + d*anl_table(2,i,1) + $ d2*anl_table(3,i,1) + d3*anl_table(4,i,1) values(2) = anl_table(1,i,2) + d*anl_table(2,i,2) + $ d2*anl_table(3,i,2) + d3*anl_table(4,i,2) values(3) = anl_table(1,i,3) + d*anl_table(2,i,3) + $ d2*anl_table(3,i,3) + d3*anl_table(4,i,3) values(4) = anl_table(1,i,4) + d*anl_table(2,i,4) + $ d2*anl_table(3,i,4) + d3*anl_table(4,i,4) else values(1) = anl_table(anl_order+1,i,1) values(2) = anl_table(anl_order+1,i,2) values(3) = anl_table(anl_order+1,i,3) values(4) = anl_table(anl_order+1,i,4) do k = anl_order,1,-1 values(1) = anl_table(k,i,1) + d*values(1) values(2) = anl_table(k,i,2) + d*values(2) values(3) = anl_table(k,i,3) + d*values(3) values(4) = anl_table(k,i,4) + d*values(4) enddo endif else rx = 1.0d0/x rx2 = rx*rx rx3 = rx2*rx values(1) = anl_fac(0,0)*rx values(2) = anl_fac(1,1)*rx3 values(3) = anl_fac(2,2)*rx3*rx2 values(4) = anl_fac(0,2)*rx endif c end subroutine anl_fit_init implicit none #include "errquit.fh" #include "canlfit.fh" c integer n, l, i, nlcnt, k double precision f(0:anl_npt), h, x, value, anl, pi, dfac, $ anl_fit, maxerr, maxrelerr, test logical initialized external anl, anl_fit data initialized /.false./ if (initialized) return initialized = .true. c c Initialize interpolation tables used for 0..xhi c h = anl_xhi/dble(anl_npt) anl_scale = 1.0d0/h c do n = 0, anl_maxn anl_xcut(n) = anl_xhi ! Initial value - reset below do l = 0, anl_maxn anl_mapnl(l,n) = 999999999 ! Make invalid access disastrous anl_fac(l,n) = 1d+300 enddo enddo c maxerr = 0.0d0 maxrelerr = 0.0d0 nlcnt = 0 do n = 0,anl_maxn do l = n,0,-2 nlcnt = nlcnt + 1 if (nlcnt .gt. anl_maxnl) call errquit $ (' anlfit: too many functions?', nlcnt, INPUT_ERR) anl_mapnl(l,n) = nlcnt do i = 0,anl_npt f(i) = anl(n,l,dble(i)*h) enddo call interp_table_make(anl_npt, anl_order, 0.0d0, $ anl_xhi, f, $ anl_table(0,0,anl_mapnl(l,n))) c c Verify accuracy of interpolation at midpoints of regions c ... make sure we have either ANL_ACC sig. fig. or an absolute c accuracy of ANL_ACC c do i = 0,anl_npt-1 x = h*(0.5d0+dble(i)) c$$$ d = x - anl_table(0,i,nlcnt) c$$$ value = anl_table(anl_order+1,i,nlcnt) c$$$ do k = anl_order,1,-1 c$$$ value = anl_table(k,i,nlcnt) + d*value c$$$ enddo value = anl_fit(n,l,x) test = anl(n,l,x) maxerr = max(maxerr,abs(value-test)) maxrelerr = max(maxrelerr,abs(value-test)/test) if (abs(value-test) .gt. $ max(anl_acc,anl_acc*value)) then write(6,1) n, l, x, value, anl(n,l,x), $ value-anl(n,l,x) 1 format(' fit error ', 2i5, 3f20.14, 1p, d9.1) call errquit('anlfit: bad iterpolation',i, INPUT_ERR) endif enddo enddo anl_nlsum(n) = nlcnt enddo c write(6,*) ' MAXERR ', maxerr c write(6,*) ' MAXRELERR ', maxrelerr ** write(6,*) ' used ', nlcnt, ' tables out of ', anl_maxnl c c Initialize prefactors for asymptotic form used beyond xhi c c (n+l+1)!! * sqrt(Pi) / [2^((n+l)/2+2) * (2*l+1) * x^(2*l+1)] c pi = 4.0d0*atan(1.0d0) do n = 0, anl_maxn do l = n, 0, -2 dfac = 1.0d0 do k = (n+l+1),1,-2 dfac = dfac * dble(k) enddo anl_fac(l,n) = dfac * sqrt(pi) / $ ((2.0d0*dble(l)+1.0d0)*2.0d0**((n+l)/2+2)) c c Verify asymptotic form at xhi c value = anl(n,l,anl_xhi) if (abs(value-anl_fit(n,l,anl_xhi)).gt.anl_acc) then write(6,2) n, l, dfac, value, anl_fac(l,n), $ anl_fit(n,l,anl_xhi), $ anl_fit(n,l,anl_xhi)-value 2 format(' prefac err ', 2i5, 4f20.14,1p,d12.4) call errquit('anlfit: bad asymptote ', n*1000+l, & INPUT_ERR) endif enddo c c Find where asymptotic form becomes accurate. Worst case c is always l=0/2. c l = mod(n,2) do x = 3.0d0, anl_xhi, 0.1d0 if (abs(anl_fac(l,n)/x**(2*l+1)-anl(n,l,x)).le.anl_acc)then anl_xcut(n) = x goto 333 endif enddo call errquit('aln_fit_init: failed to find asymptote?',n, & UNKNOWN_ERR) 333 continue enddo c end double precision function anl(n,l,x) implicit none integer n, l double precision x c c Compute the radial part of the potential due to a c general gaussian function times a real, solid, spherical harmonic c c A(x) = 0.5*x**(n-l) (n+l+1)F((n+l)/2,x**2) + (n-l)*x**l*I(n-l-1)/2 c integer k double precision ik, xkm1, xsq, fnl double precision fm_slow_but_accurate external fm_slow_but_accurate if (mod(n-l+1,2) .ne. 1) stop 543 if (n.lt.l) then stop 544 else if (n .eq. l) then ik = 0.0d0 else ik = 1.0d0 xsq = x*x xkm1 = xsq do k = 3, n-l-1, 2 ik = 0.5d0*dble(k-1)*ik + xkm1 xkm1 = xkm1 * xsq enddo ik = ik * exp(-x*x) * 0.5d0 * write(6,*) ' n-l-1, x, ik ', n-l-1, x, ik endif fnl = fm_slow_but_accurate((n+l)/2,x*x) if (n.eq.l) then anl = (0.5d0*dble(n+l+1)*fnl) / dble(l+l+1) else anl = (0.5d0*(x**(n-l))*dble(n+l+1)*fnl + $ 0.5d0*dble(n-l)*ik) / dble(l+l+1) endif c ** call fmvector(1,1,x*x,fm) ** anl = 0.5d0*3.0d0*fm(2) end double precision function fm_slow_but_accurate(m,t) implicit none integer m double precision t c c Return Fm(t) computed by downward recursion so c that it has full precision. c double precision et, twot, fp integer j c if (t .gt. 690.0d0) then et = 0.0d0 else et = exp(-t) endif twot = 2.0d0 * t c fp = 0.0d0 do j = 200, m, -1 fp = (twot*fp + et) / dble(j+j+1) enddo c fm_slow_but_accurate = fp c end subroutine interp_table_make(n, order, xlo, xhi, f, table) implicit none integer n, order double precision xlo, xhi, table(0:order+1,0:n-1), f(0:n) c c Given a tabulation of f at n+1 evenly spaced points in [xlo:xhi] c return in table+base+scale the info necessary to compute a piecewise c interpolating polynomial approximation. c c The approximation may be computed from the table at a point c xlo <= x <= xhi by the following c c scale = dble(n)/(xhi-xlo) c k = int((x-base)*scale) c d = x-table(0,k) c f = table(order+1,k) c do i = order,1,-1 c . f = table(i,k) + d*f c enddo c integer i, j, jlo, jhi integer ordermax parameter (ordermax = 10) double precision x(ordermax+1), c(ordermax+1), y(ordermax+1), $ work(2*ordermax+2), h, xx c h = (xhi - xlo) / dble(n) c * do i = 0, n * write(6,*) ' f ', i, f(i) * enddo c do i = 0,n-1 xx = xlo + dble(i)*h ! Reference point for interpolation c c Figure out which points we're going to interpolate c jlo = i - order/2 jhi = jlo + order if (jlo .lt. 0) then jlo = 0 jhi = jlo + order else if (jhi .gt. n) then jhi = n jlo = jhi - order endif do j = jlo, jhi x(j-jlo+1) = (xlo + dble(j)*h) - xx y(j-jlo+1) = f(j) enddo c call dplint(order+1,x,y,c) call dpolcf(0.0d0,order+1,x,c,table(1,i),work) table(0,i) = xx c * write(6,*) ' Table ', i, jlo, jhi, xx * write(6,1) (table(j,i),j=0,order+1) * 1 format(f10.4,2x,10(f12.6)) c enddo c end c$$$ implicit double precision (a-h, o-z) c$$$ double precision x(4), c(4), y(4), d(4), work(8) c$$$ xx = 0.0d0 c$$$ n = 4 c$$$ x(1) = 0 c$$$ x(2) = 1 c$$$ x(3) = 2 c$$$ x(4) = 3 c$$$ c$$$ y(1) = 0 c$$$ y(2) = 3 c$$$ y(3) = 1 c$$$ y(4) = 3 c$$$ c$$$ call dplint(n,x,y,c) c$$$ call dpolcf(xx,n,x,c,d,work) c$$$ c$$$ write(6,*) d c$$$ end c$$$ SUBROUTINE DPOLCF (XX, N, X, C, D, WORK) C***BEGIN PROLOGUE DPOLCF C***PURPOSE Compute the coefficients of the polynomial fit (including C Hermite polynomial fits) produced by a previous call to C POLINT. C***LIBRARY SLATEC C***CATEGORY E1B C***TYPE DOUBLE PRECISION (POLCOF-S, DPOLCF-D) C***KEYWORDS COEFFICIENTS, POLYNOMIAL C***AUTHOR Huddleston, R. E., (SNLL) C***DESCRIPTION C C Abstract C Subroutine DPOLCF computes the coefficients of the polynomial C fit (including Hermite polynomial fits ) produced by a previous C call to DPLINT. The coefficients of the polynomial, expanded C about XX, are stored in the array D. The expansion is of the form C P(Z) = D(1) + D(2)*(Z-XX) +D(3)*((Z-XX)**2) + ... + C D(N)*((Z-XX)**(N-1)). C Between the call to DPLINT and the call to DPOLCF the variable N C and the arrays X and C must not be altered. C C ***** INPUT PARAMETERS C *** All TYPE REAL variables are DOUBLE PRECISION *** C C XX - The point about which the Taylor expansion is to be made. C C N - **** C * N, X, and C must remain unchanged between the C X - * call to DPLINT and the call to DPOLCF. C C - **** C C ***** OUTPUT PARAMETER C *** All TYPE REAL variables are DOUBLE PRECISION *** C C D - The array of coefficients for the Taylor expansion as C explained in the abstract C C ***** STORAGE PARAMETER C C WORK - This is an array to provide internal working storage. It C must be dimensioned by at least 2*N in the calling program. C C C **** Note - There are two methods for evaluating the fit produced C by DPLINT. You may call DPOLVL to perform the task, or you may C call DPOLCF to obtain the coefficients of the Taylor expansion and C then write your own evaluation scheme. Due to the inherent errors C in the computations of the Taylor expansion from the Newton C coefficients produced by DPLINT, much more accuracy may be C expected by calling DPOLVL as opposed to writing your own scheme. C C***REFERENCES (NONE) C***ROUTINES CALLED (NONE) C***REVISION HISTORY (YYMMDD) C 890213 DATE WRITTEN C 891006 Cosmetic changes to prologue. (WRB) C 891024 Corrected KEYWORD section. (WRB) C 891024 REVISION DATE from Version 3.2 C 891214 Prologue converted to Version 4.0 format. (BAB) C***END PROLOGUE DPOLCF C INTEGER I,IM1,K,KM1,KM1PI,KM2N,KM2NPI,N,NM1,NMKP1,NPKM1 DOUBLE PRECISION C(*),D(*),PONE,PTWO,X(*),XX,WORK(*) C***FIRST EXECUTABLE STATEMENT DPOLCF DO 10010 K=1,N D(K)=C(K) 10010 CONTINUE IF (N.EQ.1) RETURN WORK(1)=1.0D0 PONE=C(1) NM1=N-1 DO 10020 K=2,N KM1=K-1 NPKM1=N+K-1 WORK(NPKM1)=XX-X(KM1) WORK(K)=WORK(NPKM1)*WORK(KM1) PTWO=PONE+WORK(K)*C(K) PONE=PTWO 10020 CONTINUE D(1)=PTWO IF (N.EQ.2) RETURN DO 10030 K=2,NM1 KM1=K-1 KM2N=K-2+N NMKP1=N-K+1 DO 10030 I=2,NMKP1 KM2NPI=KM2N+I IM1=I-1 KM1PI=KM1+I WORK(I)=WORK(KM2NPI)*WORK(IM1)+WORK(I) D(K)=D(K)+WORK(I)*D(KM1PI) 10030 CONTINUE RETURN END SUBROUTINE DPLINT (N, X, Y, C) C***BEGIN PROLOGUE DPLINT C***PURPOSE Produce the polynomial which interpolates a set of discrete C data points. C***LIBRARY SLATEC C***CATEGORY E1B C***TYPE DOUBLE PRECISION (POLINT-S, DPLINT-D) C***KEYWORDS POLYNOMIAL INTERPOLATION C***AUTHOR Huddleston, R. E., (SNLL) C***DESCRIPTION C C Abstract C Subroutine DPLINT is designed to produce the polynomial which C interpolates the data (X(I),Y(I)), I=1,...,N. DPLINT sets up C information in the array C which can be used by subroutine DPOLVL C to evaluate the polynomial and its derivatives and by subroutine C DPOLCF to produce the coefficients. C C Formal Parameters C *** All TYPE REAL variables are DOUBLE PRECISION *** C N - the number of data points (N .GE. 1) C X - the array of abscissas (all of which must be distinct) C Y - the array of ordinates C C - an array of information used by subroutines C ******* Dimensioning Information ******* C Arrays X,Y, and C must be dimensioned at least N in the calling C program. C C***REFERENCES L. F. Shampine, S. M. Davenport and R. E. Huddleston, C Curve fitting by polynomials in one variable, Report C SLA-74-0270, Sandia Laboratories, June 1974. C***ROUTINES CALLED XERMSG C***REVISION HISTORY (YYMMDD) C 740601 DATE WRITTEN C 891006 Cosmetic changes to prologue. (WRB) C 891006 REVISION DATE from Version 3.2 C 891214 Prologue converted to Version 4.0 format. (BAB) C 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ) C 920501 Reformatted the REFERENCES section. (WRB) C***END PROLOGUE DPLINT INTEGER I,K,KM1,N DOUBLE PRECISION DIF,C(*),X(*),Y(*) C***FIRST EXECUTABLE STATEMENT DPLINT IF (N .LE. 0) GO TO 91 C(1)=Y(1) IF(N .EQ. 1) RETURN DO 10010 K=2,N C(K)=Y(K) KM1=K-1 DO 10010 I=1,KM1 C CHECK FOR DISTINCT X VALUES DIF = X(I)-X(K) IF (DIF .EQ. 0.0) GO TO 92 C(K) = (C(I)-C(K))/DIF 10010 CONTINUE RETURN 91 write(6,*) 'SLATEC', 'DPLINT', 'N IS ZERO OR NEGATIVE.', 2, 1 RETURN 92 write(6,*) 'SLATEC', 'DPLINT', + 'THE ABSCISSAS ARE NOT DISTINCT.', 2, 1 RETURN END
mit
blyk/BlackCode-Fuse
Onboarding/.build/Android-Release/jni/_root.MainView.cpp
2
12809
// This file was generated based on 'C:\Users\Kuro\Desktop\GitHub\BlackCode-Fuse\Onboarding\.cache\GeneratedCode\MainView.g.uno'. // WARNING: Changes might be lost if you edit this file directly. #include <_root.MainView.Fuse_Elements_Element_float_Opacity_Property.h> #include <_root.MainView.Fuse_Triggers_Timeline_double_TargetProgress_Property.h> #include <_root.MainView.h> #include <_root.Onboarding_bundle.h> #include <Fuse.Animations.Animator.h> #include <Fuse.Animations.Change-1.h> #include <Fuse.Animations.Easing.h> #include <Fuse.Animations.Move.h> #include <Fuse.Animations.TrackAnimator.h> #include <Fuse.Animations.TransformAnimator-1.h> #include <Fuse.AppBase.h> #include <Fuse.BasicTheme.BasicTheme.h> #include <Fuse.Behavior.h> #include <Fuse.Controls.Control.h> #include <Fuse.Controls.DockPanel.h> #include <Fuse.Controls.Image.h> #include <Fuse.Controls.Page.h> #include <Fuse.Controls.PageControl.h> #include <Fuse.Controls.Panel.h> #include <Fuse.Controls.Rectangle.h> #include <Fuse.Controls.Shape.h> #include <Fuse.Controls.StackPanel.h> #include <Fuse.Controls.Text.h> #include <Fuse.Controls.TextControl.h> #include <Fuse.Drawing.Brush.h> #include <Fuse.Drawing.StaticSolidColor.h> #include <Fuse.Elements.Alignment.h> #include <Fuse.Elements.Element.h> #include <Fuse.Gestures.WhilePressed.h> #include <Fuse.ITranslationMode.h> #include <Fuse.Layouts.Dock.h> #include <Fuse.Layouts.Orientation.h> #include <Fuse.Navigation.WhileActive.h> #include <Fuse.Node.h> #include <Fuse.Theme.h> #include <Fuse.Translation.h> #include <Fuse.TranslationModes.h> #include <Fuse.Triggers.Timeline.h> #include <Fuse.Triggers.Trigger.h> #include <Uno.BundleFile.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Double.h> #include <Uno.Float.h> #include <Uno.Float4.h> #include <Uno.String.h> #include <Uno.UX.BundleFileSource.h> #include <Uno.UX.FileSource.h> #include <Uno.UX.Property-1.h> static uString* STRINGS[5]; static uType* TYPES[25]; namespace g{ // public partial sealed class MainView :1 // { // static MainView() :22 static void MainView__cctor__fn(uType* __type) { } ::g::Fuse::AppBase_type* MainView_typeof() { static uSStrong< ::g::Fuse::AppBase_type*> type; if (type != NULL) return type; uTypeOptions options; options.FieldCount = 21; options.ObjectSize = sizeof(MainView); options.TypeSize = sizeof(::g::Fuse::AppBase_type); type = (::g::Fuse::AppBase_type*)uClassType::New("MainView", options); type->SetBase(::g::Fuse::App_typeof()); type->fp_ctor_ = (void*)MainView__New1_fn; type->fp_cctor_ = MainView__cctor__fn; ::STRINGS[0] = uString::Const("Cubeit"); ::STRINGS[1] = uString::Const("Collect and Share"); ::STRINGS[2] = uString::Const("LOGIN"); ::STRINGS[3] = uString::Const("Slide"); ::STRINGS[4] = uString::Const("logo"); ::TYPES[0] = ::g::Fuse::Elements::Element_typeof(); ::TYPES[1] = ::g::Fuse::Animations::Change_typeof()->MakeType(::g::Uno::Double_typeof()); ::TYPES[2] = ::g::Uno::UX::Property_typeof()->MakeType(::g::Uno::Double_typeof()); ::TYPES[3] = ::g::Fuse::Animations::Change_typeof()->MakeType(::g::Uno::Float_typeof()); ::TYPES[4] = ::g::Uno::UX::Property_typeof()->MakeType(::g::Uno::Float_typeof()); ::TYPES[5] = ::g::Fuse::AppBase_typeof(); ::TYPES[6] = ::g::Fuse::Controls::Panel_typeof(); ::TYPES[7] = ::g::Fuse::Node_typeof(); ::TYPES[8] = ::g::Fuse::Controls::Control_typeof(); ::TYPES[9] = ::g::Fuse::Drawing::Brush_typeof(); ::TYPES[10] = ::g::Fuse::Controls::StackPanel_typeof(); ::TYPES[11] = ::g::Fuse::Controls::Image_typeof(); ::TYPES[12] = ::g::Uno::UX::FileSource_typeof(); ::TYPES[13] = ::g::Onboarding_bundle_typeof(); ::TYPES[14] = ::g::Fuse::Controls::TextControl_typeof(); ::TYPES[15] = ::g::Fuse::Controls::Rectangle_typeof(); ::TYPES[16] = ::g::Fuse::Controls::Shape_typeof(); ::TYPES[17] = ::g::Fuse::Behavior_typeof(); ::TYPES[18] = ::g::Fuse::Triggers::Trigger_typeof(); ::TYPES[19] = ::g::Fuse::Animations::Animator_typeof(); ::TYPES[20] = ::g::Fuse::Animations::TrackAnimator_typeof(); ::TYPES[21] = ::g::Fuse::Animations::TransformAnimator_typeof()->MakeType(::g::Fuse::Translation_typeof()); ::TYPES[22] = ::g::Fuse::Animations::Move_typeof(); ::TYPES[23] = ::g::Fuse::TranslationModes_typeof(); ::TYPES[24] = ::g::Fuse::BasicTheme::BasicTheme_typeof(); type->SetFields(16, ::g::Fuse::Controls::Image_typeof(), offsetof(::g::MainView, logo), 0, MainView__Fuse_Elements_Element_float_Opacity_Property_typeof(), offsetof(::g::MainView, logo_Opacity_inst), 0, ::g::Fuse::Controls::Page_typeof(), offsetof(::g::MainView, Slide), 0, ::g::Fuse::Triggers::Timeline_typeof(), offsetof(::g::MainView, timeline), 0, MainView__Fuse_Triggers_Timeline_double_TargetProgress_Property_typeof(), offsetof(::g::MainView, timeline_TargetProgress_inst), 0); return type; } // public MainView() :25 void MainView__ctor_3_fn(MainView* __this) { __this->ctor_3(); } // internal void InitializeUX() :29 void MainView__InitializeUX_fn(MainView* __this) { __this->InitializeUX(); } // public MainView New() :25 void MainView__New1_fn(MainView** __retval) { *__retval = MainView::New1(); } // public MainView() [instance] :25 void MainView::ctor_3() { ctor_2(); InitializeUX(); } // internal void InitializeUX() [instance] :29 void MainView::InitializeUX() { timeline = ::g::Fuse::Triggers::Timeline::New1(); timeline_TargetProgress_inst = MainView__Fuse_Triggers_Timeline_double_TargetProgress_Property::New1(timeline); logo = ::g::Fuse::Controls::Image::New2(); logo_Opacity_inst = MainView__Fuse_Elements_Element_float_Opacity_Property::New1(logo); ::g::Fuse::Controls::PageControl* temp = ::g::Fuse::Controls::PageControl::New2(); ::g::Fuse::Controls::Page* temp1 = ::g::Fuse::Controls::Page::New2(); ::g::Fuse::Controls::DockPanel* temp2 = ::g::Fuse::Controls::DockPanel::New2(); ::g::Fuse::Controls::StackPanel* temp3 = ::g::Fuse::Controls::StackPanel::New2(); ::g::Fuse::Controls::Image* temp4 = ::g::Fuse::Controls::Image::New2(); ::g::Fuse::Controls::Text* temp5 = ::g::Fuse::Controls::Text::New2(); ::g::Fuse::Controls::Text* temp6 = ::g::Fuse::Controls::Text::New2(); ::g::Fuse::Controls::Rectangle* temp7 = ::g::Fuse::Controls::Rectangle::New2(); ::g::Fuse::Controls::Text* temp8 = ::g::Fuse::Controls::Text::New2(); ::g::Fuse::Gestures::WhilePressed* temp9 = ::g::Fuse::Gestures::WhilePressed::New1(); ::g::Fuse::Drawing::StaticSolidColor* temp10 = ::g::Fuse::Drawing::StaticSolidColor::New1(::g::Uno::Float4__New2(1.0f, 1.0f, 1.0f, 1.0f)); ::g::Fuse::Drawing::StaticSolidColor* temp11 = ::g::Fuse::Drawing::StaticSolidColor::New1(::g::Uno::Float4__New2(0.9058824f, 0.2980392f, 0.2352941f, 1.0f)); Slide = ::g::Fuse::Controls::Page::New2(); ::g::Fuse::Navigation::WhileActive* temp12 = ::g::Fuse::Navigation::WhileActive::New1(); ::g::Fuse::Animations::Change* temp13 = (::g::Fuse::Animations::Change*)::g::Fuse::Animations::Change::New1(::TYPES[1/*Fuse.Animations.Change<double>*/], timeline_TargetProgress_inst); ::g::Fuse::Animations::Change* temp14 = (::g::Fuse::Animations::Change*)::g::Fuse::Animations::Change::New1(::TYPES[3/*Fuse.Animations.Change<float>*/], logo_Opacity_inst); ::g::Fuse::Animations::Move* temp15 = ::g::Fuse::Animations::Move::New1(); ::g::Fuse::Drawing::StaticSolidColor* temp16 = ::g::Fuse::Drawing::StaticSolidColor::New1(::g::Uno::Float4__New2(0.5137255f, 0.5137255f, 0.5137255f, 1.0f)); Background(::g::Uno::Float4__New2(0.9333333f, 0.9333333f, 0.9333333f, 1.0f)); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp1); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), Slide); temp1->Background(temp11); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp1->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp2); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp2->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp3); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp2->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp7); temp3->Orientation(1); temp3->Padding(::g::Uno::Float4__New2(0.0f, 150.0f, 0.0f, 0.0f)); ::g::Fuse::Controls::DockPanel::SetDock(temp3, 2); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp3->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp4); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp3->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp5); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp3->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp6); temp4->Width(100.0f); temp4->Height(100.0f); temp4->File(::g::Uno::UX::BundleFileSource::New1(::g::Onboarding_bundle::logo31b50f77())); temp5->Value(::STRINGS[0/*"Cubeit"*/]); temp5->FontSize(32.0f); temp5->TextColor(::g::Uno::Float4__New2(1.0f, 1.0f, 1.0f, 1.0f)); temp5->Alignment(10); temp5->Margin(::g::Uno::Float4__New2(0.0f, 20.0f, 0.0f, 0.0f)); temp6->Value(::STRINGS[1/*"Collect and...*/]); temp6->FontSize(20.0f); temp6->TextColor(::g::Uno::Float4__New2(1.0f, 1.0f, 1.0f, 1.0f)); temp6->Alignment(10); temp6->Margin(::g::Uno::Float4__New2(0.0f, 8.0f, 0.0f, 0.0f)); temp7->CornerRadius(::g::Uno::Float4__New2(5.0f, 5.0f, 5.0f, 5.0f)); temp7->Width(200.0f); temp7->Height(48.0f); temp7->Margin(::g::Uno::Float4__New2(0.0f, 40.0f, 0.0f, 150.0f)); ::g::Fuse::Controls::DockPanel::SetDock(temp7, 3); temp7->Fill(temp10); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp7->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), temp8); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp7->Behaviors()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[17/*Fuse.Behavior*/])), temp9); temp8->Value(::STRINGS[2/*"LOGIN"*/]); temp8->FontSize(16.0f); temp8->TextColor(::g::Uno::Float4__New2(0.9058824f, 0.2980392f, 0.2352941f, 1.0f)); temp8->Alignment(10); uPtr(Slide)->Name(::STRINGS[3/*"Slide"*/]); uPtr(Slide)->Background(temp16); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(uPtr(Slide)->Children()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[7/*Fuse.Node*/])), logo); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(uPtr(Slide)->Behaviors()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[17/*Fuse.Behavior*/])), temp12); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(uPtr(Slide)->Behaviors()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[17/*Fuse.Behavior*/])), timeline); uPtr(logo)->Width(100.0f); uPtr(logo)->Height(100.0f); uPtr(logo)->Name(::STRINGS[4/*"logo"*/]); uPtr(logo)->File(::g::Uno::UX::BundleFileSource::New1(::g::Onboarding_bundle::logo31b50f77())); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(temp12->Animators()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[19/*Fuse.Animations.Animator*/])), temp13); ::g::Fuse::Animations::Change__set_Value_fn(temp13, uCRef(1.0)); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(uPtr(timeline)->Animators()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[19/*Fuse.Animations.Animator*/])), temp14); ::g::Uno::Collections::ICollection::Add_ex(uInterface(uPtr(uPtr(timeline)->Animators()), ::g::Uno::Collections::ICollection_typeof()->MakeType(::TYPES[19/*Fuse.Animations.Animator*/])), temp15); ::g::Fuse::Animations::Change__set_Value_fn(temp14, uCRef(0.5f)); temp14->Easing(25); temp14->Duration(1.0); temp15->Y(-1.0f); temp15->Easing(26); temp15->Duration(1.0); temp15->Delay(1.0); temp15->RelativeTo(::g::Fuse::TranslationModes::Size()); temp15->Target(logo); RootNode(temp); Theme(::g::Fuse::BasicTheme::BasicTheme::Singleton1()); } // public MainView New() [static] :25 MainView* MainView::New1() { MainView* obj1 = (MainView*)uNew(MainView_typeof()); obj1->ctor_3(); return obj1; } // } } // ::g
mit
hillerlab/GenomeAlignmentTools
kent/src/hg/lib/jksql.c
2
135925
/***************************************************************************** * Copyright (C) 2000 Jim Kent. This source code may be freely used * * for personal, academic, and non-profit purposes. Commercial use * * permitted only by explicit agreement with Jim Kent (jim_kent@pacbell.net) * *****************************************************************************/ /* jksql.c - Stuff to manage interface with SQL database. */ /* * Configuration: */ #include "common.h" #include "portable.h" #include "errAbort.h" #include <mysql.h> #include "dlist.h" #include "dystring.h" #include "jksql.h" #include "sqlNum.h" #include "hgConfig.h" #include "cheapcgi.h" /* a function to get mysql results, either mysql_use_result or mysql_store_result */ /* a) mysql_use_result means that after a query, the results are stored on the server and return row-by-row * b) mysql_store_result means that the results are returned together * * a) means less memory, b) longer transfer times (latency of network * number of rows) * */ typedef MYSQL_RES * STDCALL ResGetter(MYSQL *mysql); #define DEFAULTGETTER mysql_use_result /* flags controlling sql monitoring facility */ static unsigned monitorInited = FALSE; /* initialized yet? */ static unsigned monitorFlags = 0; /* flags indicating what is traced */ static long monitorEnterTime = 0; /* time current tasked started */ static long long sqlTotalTime = 0; /* total real milliseconds */ static long sqlTotalQueries = 0; /* total number of queries */ static boolean monitorHandlerSet = FALSE; /* is exit handler installed? */ static unsigned traceIndent = 0; /* how much to indent */ static char *indentStr = " "; static boolean sqlParanoid = FALSE; /* extra squawking */ /* statistics */ static unsigned totalNumConnects = 0; static unsigned maxNumConnections = 0; struct sqlProfile /* a configuration profile for connecting to a server */ { struct sqlProfile *next; char *name; // name of profile char *host; // host name for database server unsigned int port; // port for database server char *socket; // unix-domain socket path for database server char *user; // database server user name char *password; // database server password char *db; // database if specified in config struct slName *dbs; // database associated with profile, can be NULL. // ssl char *key; // path to ssl client key.pem char *cert; // path to ssl client cert.pem char *ca; // path to ssl certificate authority ca.pem char *caPath; // path to directory containing ssl .pem certs (only OpenSSL) char *cipher; // list of permissible ciphers to use char *crl; // path to file containing certificate revocation lists in PEM format char *crlPath; // path to directory containing crl files (only OpenSSL) char *verifyServerCert; // Client will check server cert Subject CN={host} // Boolean connection flag, if NON-NULL and != "0" then it is on. }; struct sqlConnection /* This is an item on a list of sql open connections. */ { MYSQL *conn; /* Connection. Can be NULL if not connected yet. */ struct sqlProfile *profile; /* profile, or NULL if not opened via a profile */ struct dlNode *node; /* Pointer to list node. */ struct dlList *resultList; /* Any open results. */ boolean hasHardLock; /* TRUE if table has a non-advisory lock. */ boolean inCache; /* debugging flag to indicate it's in a cache */ boolean isFree; /* is this connection free for reuse; alway FALSE * unless managed by a cache */ int hasTableCache; /* to avoid repeated checks for cache table name existence, -1 if not initialized yet, otherwise like a boolean */ struct sqlConnection *failoverConn; /* tried if a query fails on the main connection. */ /* Can be NULL. */ char *db; /* to be able to connect later (if conn is NULL), we need to */ /* store the database */ }; struct sqlResult /* This is an item on a list of sql open results. */ { MYSQL_RES *result; /* Result. */ struct dlNode *node; /* Pointer to list node we're on. */ struct sqlConnection *conn; /* Pointer to connection. */ long fetchTime; /* cummulative time taken by row fetches for this result */ }; static struct dlList *sqlOpenConnections = NULL; static unsigned sqlNumOpenConnections = 0; char *failoverProfPrefix = "slow-"; // prefix for failover profile of main profile (="slow-db") static struct hash *profiles = NULL; // profiles parsed from hg.conf, by name static struct sqlProfile *defaultProfile = NULL; // default profile, also in profiles list static struct hash* dbToProfile = NULL; // db to sqlProfile // forward declarations to keep the git diffs clean static struct sqlResult *sqlUseOrStore(struct sqlConnection *sc, char *query, ResGetter *getter, boolean abort); static boolean sqlConnectIfUnconnected(struct sqlConnection *sc, bool abort); bool sqlConnMustUseFailover(struct sqlConnection *sc); static char *envOverride(char *envName, char *defaultVal) /* look up envName in environment, if it exists and is non-empty, return its * value, otherwise return defaultVal */ { char *val = getenv(envName); if (isEmpty(val)) return defaultVal; else return val; } char *getDefaultProfileName() /* Return default profile name, handling initialization if needed */ { static char *defaultProfileName = NULL; if (!defaultProfileName) defaultProfileName = envOverride("HGDB_PROF", "db"); // name of default profile for main connection return defaultProfileName; } static struct sqlProfile *sqlProfileClone(struct sqlProfile *o) /* clone profile object (does not include ->dbs) */ { struct sqlProfile *sp; AllocVar(sp); sp->name = cloneString(o->name); sp->host = cloneString(o->host); sp->port = o->port; sp->socket = cloneString(o->socket); sp->user = cloneString(o->user); sp->password = cloneString(o->password); sp->db = cloneString(o->db); sp->key = cloneString(o->key); sp->cert = cloneString(o->cert); sp->ca = cloneString(o->ca); sp->caPath = cloneString(o->caPath); sp->cipher = cloneString(o->cipher); sp->crl = cloneString(o->crl); sp->crlPath = cloneString(o->crlPath); sp->verifyServerCert = cloneString(o->verifyServerCert); return sp; } struct sqlProfile *sqlProfileFromPairs(struct slPair *pairs) /* create a new profile object (does not include ->dbs) */ { struct sqlProfile *sp; AllocVar(sp); struct slPair *p; for(p=pairs; p; p=p->next) { char *value = (char *)p->val; if (sameString(p->name,"name")) sp->name = cloneString(value); if (sameString(p->name,"host")) sp->host = cloneString(value); if (sameString(p->name,"port")) sp->port = atoi(value); if (sameString(p->name,"socket")) sp->socket = cloneString(value); if (sameString(p->name,"user")) sp->user = cloneString(value); if (sameString(p->name,"password")) sp->password = cloneString(value); if (sameString(p->name,"db")) sp->db = cloneString(value); if (sameString(p->name,"key")) sp->key = cloneString(value); if (sameString(p->name,"cert")) sp->cert = cloneString(value); if (sameString(p->name,"ca")) sp->ca = cloneString(value); if (sameString(p->name,"caPath")) sp->caPath = cloneString(value); if (sameString(p->name,"cipher")) sp->cipher = cloneString(value); if (sameString(p->name,"crl")) sp->crl = cloneString(value); if (sameString(p->name,"crlPath")) sp->crlPath = cloneString(value); if (sameString(p->name,"verifyServerCert")) sp->verifyServerCert = cloneString(value); } return sp; } static void sqlProfileAssocDb(struct sqlProfile *sp, char *db) /* associate a db with a profile. If it is already associated with this * profile, don't do anything.*/ { struct sqlProfile *sp2 = hashFindVal(dbToProfile, db); if ((sp2 != NULL) && (sp2 != sp)) errAbort("databases %s already associated with profile %s, trying to associated it with %s", db, sp2->name, sp->name); if (sp2 == NULL) { hashAdd(dbToProfile, db, sp); slSafeAddHead(&sp->dbs, slNameNew(db)); } } static void sqlProfileCreate(struct sqlProfile *sp) /* create a profile and add to global data structures */ { hashAdd(profiles, sp->name, sp); if (sameString(sp->name, getDefaultProfileName())) defaultProfile = sp; // save default } static void sqlProfileAddProfIf(char *profileName) /* check if a config prefix is a profile, and if so, add a * sqlProfile object for it if doesn't already exist. */ { char *host = cfgOption2(profileName, "host"); char *portstr = cfgOption2(profileName, "port"); char *socket = cfgOption2(profileName, "socket"); char *user = cfgOption2(profileName, "user"); char *password = cfgOption2(profileName, "password"); char *db = cfgOption2(profileName, "db"); // ssl char *key = cfgOption2(profileName, "key"); char *cert = cfgOption2(profileName, "cert"); char *ca = cfgOption2(profileName, "ca"); char *caPath = cfgOption2(profileName, "caPath"); char *cipher = cfgOption2(profileName, "cipher"); char *crl = cfgOption2(profileName, "crl"); char *crlPath = cfgOption2(profileName, "crlPath"); char *verifyServerCert = cfgOption2(profileName, "verifyServerCert"); unsigned int port = 0; if ((host != NULL) && (user != NULL) && (password != NULL) && (hashLookup(profiles, profileName) == NULL)) { /* for the default profile, allow environment variable override */ if (sameString(profileName, getDefaultProfileName())) { host = envOverride("HGDB_HOST", host); portstr = envOverride("HGDB_PORT", portstr); socket = envOverride("HGDB_SOCKET", socket); user = envOverride("HGDB_USER", user); password = envOverride("HGDB_PASSWORD", password); db = envOverride("HGDB_DB", db); // ssl key = envOverride("HGDB_KEY", key); cert = envOverride("HGDB_CERT", cert); ca = envOverride("HGDB_CA", ca); caPath = envOverride("HGDB_CAPATH", caPath); cipher = envOverride("HGDB_CIPHER", cipher); crl = envOverride("HGDB_CRL", crl); crlPath = envOverride("HGDB_CRLPATH", crlPath); verifyServerCert = envOverride("HGDB_VERIFY_SERVER_CERT", verifyServerCert); } if (portstr != NULL) port = atoi(portstr); struct sqlProfile *sp; AllocVar(sp); sp->name = cloneString(profileName); sp->host = cloneString(host); sp->port = port; sp->socket = cloneString(socket); sp->user = cloneString(user); sp->password = cloneString(password); sp->db = cloneString(db); sp->key = cloneString(key); sp->cert = cloneString(cert); sp->ca = cloneString(ca); sp->caPath = cloneString(caPath); sp->cipher = cloneString(cipher); sp->crl = cloneString(crl); sp->crlPath = cloneString(crlPath); sp->verifyServerCert = cloneString(verifyServerCert); sqlProfileCreate(sp); } } static void sqlProfileAddProfs(struct slName *cnames) /* load the profiles from list of config names */ { struct slName *cname; for (cname = cnames; cname != NULL; cname = cname->next) { char *dot1 = strchr(cname->name, '.'); // first dot in name if ((dot1 != NULL) && sameString(dot1, ".host")) { *dot1 = '\0'; sqlProfileAddProfIf(cname->name); *dot1 = '.'; } } } void sqlProfileAddDb(char *profileName, char *db) /* add a mapping of db to profile. If database is already associated with * this profile, it is ignored. If it is associated with a different profile, * it is an error. */ { struct sqlProfile *sp = hashFindVal(profiles, profileName); if (sp == NULL) errAbort("can't find profile %s for database %s in hg.conf", profileName, db); sqlProfileAssocDb(sp, db); } static void sqlProfileAddDbs(struct slName *cnames) /* add mappings of db to profile from ${db}.${profile} entries. * would have liked to have automatically added ${profile}.db * entries, but backupcentral, etc, would map multiple profiles * to a databases, so this is done manually in hdb.c. */ { struct slName *cname; for (cname = cnames; cname != NULL; cname = cname->next) { char *dot1 = strchr(cname->name, '.'); // first dot in name if ((dot1 != NULL) && sameString(dot1, ".profile")) { char *profileName = cfgVal(cname->name); *dot1 = '\0'; sqlProfileAddDb(profileName, cname->name); *dot1 = '.'; } } } static void sqlProfileLoad(void) /* load the profiles from config */ { profiles = hashNew(8); dbToProfile = hashNew(12); struct slName *cnames = cfgNames(); sqlProfileAddProfs(cnames); sqlProfileAddDbs(cnames); slFreeList(&cnames); } static struct sqlProfile* sqlProfileFindByName(char *profileName, char *database) /* find a profile by name, checking that database matches if found */ { struct sqlProfile* sp = hashFindVal(profiles, profileName); if (sp == NULL) return NULL; #if UNUSED // FIXME: this breaks hgHeatMap, enable when logicalDb removed if ((database != NULL) && (sp->dbs != NULL) && !slNameInList(sp->dbs, database)) errAbort("attempt to obtain SQL profile %s for database %s, " "which is not associate with this database-specific profile", profileName, database); #endif return sp; } static struct sqlProfile* sqlProfileFindByDatabase(char *database) /* find a profile using database as profile name, return the default if not * found */ { if (!database) return defaultProfile; struct sqlProfile *sp = hashFindVal(dbToProfile, database); if (sp == NULL) sp = defaultProfile; return sp; } static struct sqlProfile* sqlProfileGet(char *profileName, char *database) /* lookup a profile using the profile resolution algorithm: * - If a profile is specified: * - search hg.conf for the profile, if found: * - if database is specified, then either * - the profile should not specify a database * - the database must match the database in the profile * - If a profile is not specified: * - search hg.conf for a profile with the same name as the database * - if there is no profile named the same as the database, use * the default profile of "db" * return NULL if not found. */ { //assert((profileName != NULL) || (database != NULL)); if (profiles == NULL) sqlProfileLoad(); if (profileName != NULL) return sqlProfileFindByName(profileName, database); else return sqlProfileFindByDatabase(database); } static struct sqlProfile* sqlProfileGetFailover(struct sqlProfile* sp, char *database) /* try to find a failover profile for a profile x or return NULL*/ { if (sp==NULL || sp->name==NULL) return NULL; char *failoverProfName = catTwoStrings(failoverProfPrefix, sp->name); struct sqlProfile *failoverProf = sqlProfileGet(failoverProfName, database); freez(&failoverProfName); return failoverProf; } static struct sqlProfile* sqlProfileMustGet(char *profileName, char *database) /* lookup a profile using the profile resolution algorithm or die trying */ { struct sqlProfile* sp = sqlProfileGet(profileName, database); if (sp == NULL) { if (profileName == NULL) errAbort("can't find database %s in hg.conf, should have a default named \"db\"", database); else if (database == NULL) errAbort("can't find profile %s in hg.conf", profileName); else errAbort("can't find profile %s for database %s in hg.conf", profileName, database); } return sp; } struct slName* sqlProfileGetNames() /* Get a list of all profile names. slFreeList result when done */ { if (profiles == NULL) sqlProfileLoad(); struct slName *names = NULL; struct hashCookie cookie = hashFirst(profiles); struct hashEl* hel; while ((hel = hashNext(&cookie)) != NULL) slAddHead(&names, slNameNew(hel->name)); return names; } static void replaceStr(char **str, char *val) /* free str and replace with clone new value */ { freeMem(*str); *str = cloneString(val); } void sqlProfileConfig(struct slPair *pairs) /* Set configuration for the profile. This overrides an existing profile in * hg.conf or defines a new one. Results are unpredictable if a connect cache * has been established for this profile. */ { struct sqlProfile *spIn = sqlProfileFromPairs(pairs); struct sqlProfile *sp = sqlProfileGet(spIn->name, NULL); if (sp == NULL) return sqlProfileCreate(spIn); replaceStr(&sp->host, spIn->host); replaceStr(&sp->socket, spIn->socket); sp->port = spIn->port; replaceStr(&sp->user, spIn->user); replaceStr(&sp->password, spIn->password); replaceStr(&sp->db, spIn->db); replaceStr(&sp->key, spIn->key); replaceStr(&sp->cert, spIn->cert); replaceStr(&sp->ca, spIn->ca); replaceStr(&sp->caPath, spIn->caPath); replaceStr(&sp->cipher, spIn->cipher); replaceStr(&sp->crl, spIn->crl); replaceStr(&sp->crlPath, spIn->crlPath); replaceStr(&sp->verifyServerCert, spIn->verifyServerCert); } void sqlProfileConfigDefault(struct slPair *pairs) /* Set configuration for the default profile. This overrides an existing * profile in hg.conf or defines a new one. Results are unpredictable if a * connect cache has been established for this profile. */ { struct slPair *found = slPairFind(pairs, "name"); if (found) found->val = cloneString(getDefaultProfileName()); else slPairAdd(&pairs, "name", cloneString(getDefaultProfileName())); sqlProfileConfig(pairs); } char *sqlProfileToMyCnf(char *profileName) /* Read in profile named, * and create a multi-line setting string usable in my.cnf files. * Return Null if profile not found. */ { struct sqlProfile *sp = sqlProfileGet(profileName, NULL); if (!sp) return NULL; struct dyString *dy = dyStringNew(256); if (sp->host) dyStringPrintf(dy, "host=%s\n", sp->host); if (sp->user) dyStringPrintf(dy, "user=%s\n", sp->user); if (sp->password) dyStringPrintf(dy, "password=%s\n", sp->password); if (sp->db) dyStringPrintf(dy, "database=%s\n", sp->db); if (sp->port) dyStringPrintf(dy, "port=%d\n", sp->port); if (sp->socket) dyStringPrintf(dy, "socket=%s\n", sp->socket); if (sp->key) dyStringPrintf(dy, "ssl-key=%s\n", sp->key); if (sp->cert) dyStringPrintf(dy, "ssl-cert=%s\n", sp->cert); if (sp->ca) dyStringPrintf(dy, "ssl-ca=%s\n", sp->ca); if (sp->caPath) dyStringPrintf(dy, "ssl-capath=%s\n", sp->caPath); if (sp->cipher) dyStringPrintf(dy, "ssl-cipher=%s\n", sp->cipher); #if (MYSQL_VERSION_ID >= 50603) // mysql version "5.6.3" if (sp->crl) dyStringPrintf(dy, "ssl-crl=%s\n", sp->crl); if (sp->crlPath) dyStringPrintf(dy, "ssl-crlpath=%s\n", sp->crlPath); #endif if (sp->verifyServerCert && !sameString(sp->verifyServerCert,"0")) dyStringPrintf(dy, "ssl-verify-server-cert\n"); return dyStringCannibalize(&dy); } static void monitorInit(void) /* initialize monitoring on the first call */ { unsigned flags = 0; char *val; /* there is special code in cheap.cgi to pass these from cgiOption to env */ val = getenv("JKSQL_TRACE"); if ((val != NULL) && sameString(val, "on")) flags |= JKSQL_TRACE; val = getenv("JKSQL_PROF"); if ((val != NULL) && sameString(val, "on")) flags |= JKSQL_PROF; if (flags != 0) sqlMonitorEnable(flags); monitorInited = TRUE; } static void monitorEnter(void) /* called at the beginning of a routine that is monitored, initialize if * necessary and start timing if enabled */ { if (!monitorInited) monitorInit(); assert(monitorEnterTime == 0); /* no recursion allowed */ if (monitorFlags) { monitorEnterTime = clock1000(); } } static long monitorLeave(void) /* called at the end of a routine that is monitored, updates time count. * returns time since enter. */ { long deltaTime = 0; if (monitorFlags) { deltaTime = clock1000() - monitorEnterTime; assert(monitorEnterTime > 0); if (monitorFlags & JKSQL_PROF) sqlTotalTime += deltaTime; monitorEnterTime = 0; } return deltaTime; } static char *scConnDb(struct sqlConnection *sc) /* Return sc->db, unless it is NULL -- if NULL, return a string for * fprint'd messages. */ { return (sc->db ? sc->db : "?"); } static char *scConnProfile(struct sqlConnection *sc) /* Return sc->profile->name, unless profile is NULL -- if NULL, return a string for * fprint'd messages. */ { return (sc->profile ? sc->profile->name : "<noProfile>"); } static void monitorPrintInfo(struct sqlConnection *sc, char *name) /* print a monitor message, with connection id and databases. */ { long int threadId = 0; if (sc->conn) threadId = sc->conn->thread_id; fprintf(stderr, "%.*s%s %ld %s\n", traceIndent, indentStr, name, threadId, scConnDb(sc)); fflush(stderr); } static void monitorPrint(struct sqlConnection *sc, char *name, char *format, ...) /* print a monitor message, with connection id, databases, and * printf style message.*/ { if (!(monitorFlags & JKSQL_TRACE)) return; va_list args; long int threadId = 0; if (sc->conn) threadId = sc->conn->thread_id; fprintf(stderr, "%.*s%s %ld %s %s ", traceIndent, indentStr, name, threadId, sqlGetHost(sc), scConnDb(sc)); va_start(args, format); vfprintf(stderr, format, args); va_end(args); fputc('\n', stderr); fflush(stderr); } static void monitorPrintTime(void) /* print total time */ { /* only print if not explictly disabled */ if (monitorFlags & JKSQL_PROF) { fprintf(stderr, "%.*sSQL_TOTAL_TIME %0.3fs\n", traceIndent, indentStr, ((double)sqlTotalTime)/1000.0); fprintf(stderr, "%.*sSQL_TOTAL_QUERIES %ld\n", traceIndent, indentStr, sqlTotalQueries); fflush(stderr); } } static void monitorPrintQuery(struct sqlConnection *sc, char *query) /* print a query, replacing newlines with \n */ { char *cleaned = replaceChars(query, "\n", "\\n"); monitorPrint(sc, "SQL_QUERY", "%s", cleaned); freeMem(cleaned); } void sqlMonitorEnable(unsigned flags) /* Enable disable tracing or profiling of SQL queries. * If JKSQL_TRACE is specified, then tracing of each SQL query is enabled, * along with the timing of the queries. * If JKSQL_PROF is specified, then time spent in SQL queries is logged * and printed when the program exits or when sqlMonitorDisable is called. * * These options can also be enabled by setting the JKSQL_TRACE and/or * JKSQL_PROF environment variables to "on". The cheapcgi module will set * these environment variables if the corresponding CGI variables are set * to "on". These may also be set in the .hg.conf file. While this method * of setting these parameters is a bit of a hack, it avoids uncessary * dependencies. */ { monitorFlags = flags; if ((monitorFlags & JKSQL_PROF) && !monitorHandlerSet) { /* only add once */ atexit(monitorPrintTime); monitorHandlerSet = TRUE; } monitorInited = TRUE; } void sqlMonitorSetIndent(unsigned indent) /* set the sql indent level indent to the number of spaces to indent each * trace, which can be helpful in making voluminous trace info almost * readable. */ { traceIndent = indent; } void sqlMonitorDisable(void) /* Disable tracing or profiling of SQL queries. */ { if (monitorFlags & JKSQL_PROF) monitorPrintTime(); monitorFlags = 0; sqlTotalTime = 0; /* allow reenabling */ sqlTotalQueries = 0; } void sqlFreeResult(struct sqlResult **pRes) /* Free up a result. */ { struct sqlResult *res = *pRes; if (res != NULL) { if (monitorFlags & JKSQL_TRACE) monitorPrint(res->conn, "SQL_FETCH", "%0.3fs", ((double) res->fetchTime)/1000.0); if (res->result != NULL) { monitorEnter(); mysql_free_result(res->result); monitorLeave(); } if (res->node != NULL) { dlRemove(res->node); freeMem(res->node); } freez(pRes); } } void sqlDisconnect(struct sqlConnection **pSc) /* Close down connection. */ { struct sqlConnection *sc = *pSc; long deltaTime; if (sc != NULL) { if (sc->inCache) errAbort("sqlDisconnect called on connection associated with a cache"); assert(!sc->isFree); MYSQL *conn = sc->conn; struct dlList *resList = sc->resultList; struct dlNode *node = sc->node; if (resList != NULL) { struct dlNode *resNode, *resNext; for (resNode = resList->head; resNode->next != NULL; resNode = resNext) { struct sqlResult *res = resNode->val; resNext = resNode->next; sqlFreeResult(&res); } freeDlList(&resList); } if (conn != NULL) { if (sc->hasHardLock) sqlHardUnlockAll(sc); if (monitorFlags & JKSQL_TRACE) monitorPrintInfo(sc, "SQL_DISCONNECT"); monitorEnter(); mysql_close(conn); deltaTime = monitorLeave(); if (monitorFlags & JKSQL_TRACE) monitorPrint(sc, "SQL_TIME", "%0.3fs", ((double)deltaTime)/1000.0); } if (node != NULL) { dlRemove(node); freeMem(node); } freeMem(sc->db); // also close failover connection if (sc->failoverConn != NULL) sqlDisconnect(&sc->failoverConn); freez(pSc); sqlNumOpenConnections--; } } char* sqlGetDatabase(struct sqlConnection *sc) /* Get the database associated with an connection. Warning: return may be NULL! */ { return sc->db; } char* sqlGetHost(struct sqlConnection *sc) /* Get the host associated with a connection or NULL. */ { if (sc->conn) return sc->conn->host; if (sc->profile->host) return sc->profile->host; return NULL; } struct slName *sqlGetAllDatabase(struct sqlConnection *sc) /* Get a list of all database on the server */ { char query[32]; sqlSafef(query, sizeof query, "show databases"); struct sqlResult *sr = sqlGetResult(sc, query); char **row; struct slName *databases = NULL; while ((row = sqlNextRow(sr)) != NULL) { if (!startsWith("mysql", row[0])) /* Avoid internal databases. */ slSafeAddHead(&databases, slNameNew(row[0])); } sqlFreeResult(&sr); return databases; } static bool sqlTableExistsOnMain(struct sqlConnection *sc, char *tableName) /* Return TRUE if the table can be queried using sc's main conn; * don't check failoverConn or the table cache (showTableCache in hg.conf). */ { // if the whole db does not exist on the main server, then the table is certainly not there if (sqlConnMustUseFailover(sc)) return FALSE; char query[1024]; sqlSafef(query, sizeof(query), "SELECT 1 FROM %-s LIMIT 0", sqlCkIl(tableName)); struct sqlResult *sr; // temporarily remove failover connection, we don't want the failover switch here struct sqlConnection *failoverConn = sc->failoverConn; sc->failoverConn=NULL; sr = sqlUseOrStore(sc, query, DEFAULTGETTER, FALSE); sc->failoverConn=failoverConn; bool ret = FALSE; if (sr!=NULL) { monitorPrint(sc, "SQL_TABLE_EXISTS", "%s", tableName); ret = TRUE; sqlFreeResult(&sr); } else monitorPrint(sc, "SQL_TABLE_NOT_EXISTS", "%s", tableName); return ret; } static struct sqlConnection *sqlTableCacheFindConn(struct sqlConnection *conn) /* Check if table name caching is configured and the cache table is also present * on the server of the connection. Returns the connection or NULL */ { char *tableListTable = cfgOption("showTableCache"); if (tableListTable == NULL) return NULL; // to avoid hundreds of repeated table existence checks, we keep the result // of sqlTableCacheFindConn in the sqlConn object if (conn->hasTableCache==-1) // -1 => undefined { conn->hasTableCache = (int) sqlTableExistsOnMain(conn, tableListTable); if (conn->failoverConn && !conn->hasTableCache) { monitorPrint(conn, "SQL_FAILOVER_NO_TABLE_CACHE_FOR_DB", "%s", conn->db); return NULL; } } if (conn->hasTableCache) { monitorPrint(conn, "SQL_FOUND_TABLE_CACHE", "%s", tableListTable); return conn; } else { monitorPrint(conn, "SQL_NOT_FOUND_TABLE_CACHE", "%s", tableListTable); return NULL; } } static bool sqlTableCacheTableExists(struct sqlConnection *conn, char *maybeTable) /* check if table exists in table name cache */ // (see redmine 3780 for some historical background on this caching) { char query[1024]; char *tableListTable = cfgVal("showTableCache"); char table[2048]; safecpy(table, sizeof table, maybeTable); char *dot = strchr(table, '.'); if (dot) { *dot = 0; sqlSafef(query, sizeof(query), "SELECT count(*) FROM %s.%s WHERE tableName='%s'", table, tableListTable, dot+1); } else sqlSafef(query, sizeof(query), "SELECT count(*) FROM %s WHERE tableName='%s'", tableListTable, table); return (sqlQuickNum(conn, query)!=0); } static struct slName *sqlTableCacheQuery(struct sqlConnection *conn, char *likeExpr) /* This function queries the tableCache table. It is used by the sqlTableList * function, so it doe not have to connect to the main sql server just to get a list of table names. * Returns all table names from the table name cache as a list. * Can optionally filter with a likeExpr e.g. "LIKE snp%". */ { char *tableList = cfgVal("showTableCache"); struct slName *list = NULL, *el; char query[1024]; // mysql SHOW TABLES is sorted alphabetically by default if (likeExpr==NULL) sqlSafef(query, sizeof(query), "SELECT DISTINCT tableName FROM %s ORDER BY tableName", tableList); else sqlSafef(query, sizeof(query), "SELECT DISTINCT tableName FROM %s WHERE tableName LIKE '%s' ORDER BY tableName", tableList, likeExpr); struct sqlResult *sr = sqlGetResult(conn, query); char **row; while ((row = sqlNextRow(sr)) != NULL) { el = slNameNew(row[0]); slAddHead(&list, el); } slReverse(&list); sqlFreeResult(&sr); return list; } static struct slName *sqlListTablesForConn(struct sqlConnection *conn, char *likeExpr) /* run SHOW TABLES on connection and return a slName list. LIKE expression * can be NULL or string e.g. "LIKE 'snp%'" */ { char query[256]; if (likeExpr == NULL) safef(query, sizeof(query), NOSQLINJ "SHOW TABLES"); else safef(query, sizeof(query), NOSQLINJ "SHOW TABLES LIKE '%s'", likeExpr); struct slName *list = NULL, *el; struct sqlResult *sr; char **row; sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { el = slNameNew(row[0]); slAddHead(&list, el); } slReverse(&list); sqlFreeResult(&sr); return list; } struct slName *sqlListTablesLike(struct sqlConnection *conn, char *likeExpr) /* Return list of tables in database associated with conn. Optionally filter list with * given LIKE expression that can be NULL or string e.g. "LIKE 'snp%'". */ { struct slName *list = NULL; struct sqlConnection *cacheConn = sqlTableCacheFindConn(conn); if (cacheConn) list = sqlTableCacheQuery(cacheConn, likeExpr); else list = sqlListTablesForConn(conn, likeExpr); if (conn->failoverConn != NULL) { struct slName *failoverList = sqlListTablesForConn(conn->failoverConn, likeExpr); slSortMergeUniq(&list, failoverList, slNameCmp, slNameFree); } return list; } struct slName *sqlListTables(struct sqlConnection *sc) /* Return list of tables in database associated with conn. */ { return sqlListTablesLike(sc, NULL); } struct sqlResult *sqlDescribe(struct sqlConnection *conn, char *table) /* run the sql DESCRIBE command or get a cached table description and return the sql result */ { char query[1024]; struct sqlConnection *cacheConn = sqlTableCacheFindConn(conn); if (cacheConn) { char *tableListTable = cfgVal("showTableCache"); sqlSafef(query, sizeof(query), "SELECT Field, Type, NullAllowed, isKey, hasDefault, Extra FROM %s WHERE tableName='%s'", \ tableListTable, table); conn = cacheConn; } else sqlSafef(query, sizeof(query), "DESCRIBE %s", table); struct sqlResult *sr; sr = sqlGetResult(conn, query); return sr; } struct slName *sqlListFields(struct sqlConnection *conn, char *table) /* Return list of fields in table. */ { char **row; struct slName *list = NULL, *el; struct sqlResult *sr = NULL; sr = sqlDescribe(conn, table); while ((row = sqlNextRow(sr)) != NULL) { el = slNameNew(row[0]); slAddHead(&list, el); } sqlFreeResult(&sr); slReverse(&list); return list; } void sqlAddDatabaseFields(char *database, struct hash *hash) /* Add fields from the one database to hash. */ { struct sqlConnection *conn = sqlConnect(database); struct slName *table, *tableList = sqlListTables(conn); struct sqlResult *sr; char **row; char fullName[512]; for (table = tableList; table != NULL; table = table->next) { sr = sqlDescribe(conn, table->name); while ((row = sqlNextRow(sr)) != NULL) { safef(fullName, sizeof(fullName), "%s.%s.%s", database, table->name, row[0]); hashAdd(hash, fullName, NULL); } sqlFreeResult(&sr); } slFreeList(&tableList); sqlDisconnect(&conn); } struct hash *sqlAllFields(void) /* Get hash of all fields in database.table.field format. */ { struct hash *fullHash = hashNew(18); struct hash *dbHash = sqlHashOfDatabases(); struct hashEl *dbList, *db; dbList = hashElListHash(dbHash); for (db = dbList; db != NULL; db = db->next) sqlAddDatabaseFields(db->name, fullHash); slFreeList(&dbList); hashFree(&dbHash); return fullHash; } void sqlCleanupAll(void) /* Cleanup all open connections and resources. */ { if (sqlOpenConnections) { struct dlNode *conNode, *conNext; struct sqlConnection *conn; for (conNode = sqlOpenConnections->head; conNode->next != NULL; conNode = conNext) { conn = conNode->val; conNext = conNode->next; conn->inCache = FALSE; // really should be cleaning up caches too conn->isFree = FALSE; sqlDisconnect(&conn); } freeDlList(&sqlOpenConnections); } } static void sqlInitTracking(void) /* Initialize tracking and freeing of resources. */ { if (sqlOpenConnections == NULL) { sqlOpenConnections = newDlList(); atexit(sqlCleanupAll); } } static struct sqlConnection *sqlConnRemoteFillIn(struct sqlConnection *sc, struct sqlProfile *sp, char *database, boolean abort, boolean addAsOpen) /* Fill the sqlConnection object: Connect to database somewhere as somebody. * Database maybe NULL to just connect to the server. If abort is set display * error message and abort on error. This is the core function that connects to * a MySQL server. */ { MYSQL *conn; long deltaTime; sqlInitTracking(); sc->resultList = newDlList(); if (addAsOpen) sc->node = dlAddValTail(sqlOpenConnections, sc); long oldTime = monitorEnterTime; monitorEnterTime = 0; monitorEnter(); if ((sc->conn = conn = mysql_init(NULL)) == NULL) // no need for monitorLeave here errAbort("Couldn't connect to mySQL."); // Fix problem where client LOCAL setting is disabled by default for security mysql_options(conn, MYSQL_OPT_LOCAL_INFILE, NULL); // Boolean option to tell client to verify that the host server certificate Subject CN equals the hostname. // If turned on this can defeat Man-In-The-Middle attacks. if (sp->verifyServerCert && !sameString(sp->verifyServerCert,"0")) { my_bool flag = TRUE; mysql_options(conn, MYSQL_OPT_SSL_VERIFY_SERVER_CERT, &flag); } #if (MYSQL_VERSION_ID >= 50603) // mysql version "5.6.3" // If certificate revocation list file provided, set mysql option if (sp->crl) mysql_options(conn, MYSQL_OPT_SSL_CRL, &sp->crl); // If path to directory with crl files provided, set mysql option if (sp->crlPath) mysql_options(conn, MYSQL_OPT_SSL_CRLPATH, &sp->crlPath); #endif if (sp->key || sp->cert || sp->ca || sp->caPath || sp->cipher) mysql_ssl_set(conn, sp->key, sp->cert, sp->ca, sp->caPath, sp->cipher); if (mysql_real_connect( conn, sp->host, /* host */ sp->user, /* user name */ sp->password, /* password */ database, /* database */ sp->port, /* port */ sp->socket, /* socket */ 0) /* flags */ == NULL) { monitorLeave(); monitorEnterTime = oldTime; if (abort) errAbort("Couldn't connect to database %s on %s as %s.\n%s", database, sp->host, sp->user, mysql_error(conn)); else if (sqlParanoid) fprintf(stderr, "Couldn't connect to database %s on %s as %s. " "mysql: %s pid=%ld\n", database, sp->host, sp->user, mysql_error(conn), (long)getpid()); return NULL; } /* Make sure the db is correct in the connect, think usually happens if there * is a mismatch between MySQL library and code. If this happens, please * figure out what is going on. Contact markd if you need help. */ if (((conn->db != NULL) && !sameString(database, conn->db)) || ((conn->db == NULL) && (database != NULL))) errAbort("apparent mismatch between mysql.h used to compile jksql.c and libmysqlclient"); sc->db=cloneString(database); if (monitorFlags & JKSQL_TRACE) monitorPrint(sc, "SQL_CONNECT", "%s %s", sp->host, sp->user); deltaTime = monitorLeave(); if (monitorFlags & JKSQL_TRACE) monitorPrint(sc, "SQL_TIME", "%0.3fs", ((double)deltaTime)/1000.0); monitorEnterTime = oldTime; sqlNumOpenConnections++; if (sqlNumOpenConnections > maxNumConnections) maxNumConnections = sqlNumOpenConnections; totalNumConnects++; sc->hasTableCache=-1; // -1 => not determined return sc; } static struct sqlConnection *sqlConnRemote(struct sqlProfile* sp, char *database, boolean abort) /* Connect to database somewhere as somebody. Database maybe NULL to just * connect to the server. If abort is set display error message and abort on * error. */ { struct sqlConnection *sc; AllocVar(sc); return sqlConnRemoteFillIn(sc, sp, database, abort, TRUE); } struct sqlConnection *sqlConnectRemote(char *host, char *user, char *password, char *database) /* Connect to database somewhere as somebody. Database maybe NULL to * just connect to the server. Abort on error. * This only takes limited connection parameters. Use Full version for access to all.*/ { struct sqlProfile *sp; AllocVar(sp); sp->host = cloneString(host); sp->user = cloneString(user); sp->password = cloneString(password); return sqlConnRemote(sp, database, TRUE); } struct sqlConnection *sqlMayConnectRemote(char *host, char *user, char *password, char *database) /* Connect to database somewhere as somebody. Database maybe NULL to * just connect to the server. Return NULL if can't connect. * This only takes limited connection parameters. Use Full version for access to all.*/ { struct sqlProfile *sp; AllocVar(sp); sp->host = cloneString(host); sp->user = cloneString(user); sp->password = cloneString(password); return sqlConnRemote(sp, database, FALSE); } struct sqlConnection *sqlConnectRemoteFull(struct slPair *pairs, char *database) /* Connect to database somewhere as somebody. Database maybe NULL to * just connect to the server. Abort on error. * Connection parameter pairs contains a list of name/values. */ { struct sqlProfile *sp = sqlProfileFromPairs(pairs); return sqlConnRemote(sp, database, TRUE); } struct sqlConnection *sqlMayConnectRemoteFull(struct slPair *pairs, char *database) /* Connect to database somewhere as somebody. Database maybe NULL to * just connect to the server. * Connection parameter pairs contains a list of name/values. Return NULL if can't connect.*/ { struct sqlProfile *sp = sqlProfileFromPairs(pairs); return sqlConnRemote(sp, database, FALSE); } static struct sqlConnection *sqlUnconnectedConn(struct sqlProfile* profile, char* database) /* create a sqlConnection object that has all information to connect but is actually * not connected yet, as indicated by a NULL mysql connection pointer */ { static struct sqlConnection *sc; AllocVar(sc); sc->conn = NULL; sc->profile = profile; // remember the profile, needed to connect later sc->db = cloneString(database); sc->hasTableCache = -1; // -1 => undefined return sc; } static struct sqlConnection *sqlConnProfile(struct sqlProfile* sp, char *database, boolean abort) /* Connect to database using the profile. Database maybe NULL to connect to * the server. Optionally abort on failure. */ { bool mainAbort = abort; struct sqlConnection *sc; // get the failover profile for the profile, if it exists struct sqlProfile *failoverProf = sqlProfileGetFailover(sp, database); // if we have a failover profile, don't abort right away if (failoverProf!=NULL) mainAbort = FALSE; // connect with the default profile sc = sqlConnRemote(sp, database, mainAbort); if (failoverProf==NULL) // the default case, without a failover connection: just return sc, can be NULL return sc; // we still have a failover profile to setup: // if the requested database exists only on the failover connection, then the main connect // failed. We just connect again without a database, but note the database if (sc==NULL) { if (monitorFlags & JKSQL_TRACE) fprintf(stderr, "SQL_CONNECT_MAIN_FAIL %s\n", database); sc = sqlConnRemote(sp, NULL, TRUE); sc->db = cloneString(database); } sc->profile = sp; // remember the profile // don't connect the failOver connection yet: lazily connect later when needed sc->failoverConn = sqlUnconnectedConn(failoverProf, database); return sc; } struct sqlConnection *sqlMayConnect(char *database) /* Connect to database on default host as default user. * Return NULL (don't abort) on failure. */ { return sqlConnProfile(sqlProfileMustGet(NULL, database), database, FALSE); } static boolean sqlConnectIfUnconnected(struct sqlConnection *sc, bool abort) /* Take a yet unconnected sqlConnection object and connect it to the sql server. * returns TRUE on success, FALSE otherwise. * This allows us to have mysql connection objects with a server name, port, * database etc, but no actual mysql connection setup yet. The connection is * only done when a query comes in. This saves a lot of time, as the failover * connection object is just tracking the database changes on the main * connection, and connects only when really necessary. */ { if (sc->conn!=NULL) return TRUE; char *profName = NULL; if (sc->profile) profName = sc->profile->name; struct sqlProfile *sp = sqlProfileMustGet(profName, sc->db); return (sqlConnRemoteFillIn(sc, sp, sc->db, abort, FALSE) != NULL); } struct sqlConnection *sqlConnect(char *database) /* Connect to database on default host as default user. */ { struct sqlProfile *defProf = sqlProfileMustGet(NULL, database); return sqlConnProfile(defProf, database, TRUE); } struct sqlConnection *sqlConnectProfile(char *profileName, char *database) /* Connect to profile or database using the specified profile. Can specify * profileName, database, or both. The profile is the prefix to the host, * user, and password variables in .hg.conf. For the default profile of "db", * the environment variables HGDB_HOST, HGDB_USER, and HGDB_PASSWORD can * override. */ { struct sqlProfile* sp = sqlProfileMustGet(profileName, database); return sqlConnRemote(sp, database, TRUE); } struct sqlConnection *sqlMayConnectProfile(char *profileName, char *database) /* Connect to profile or database using the specified profile. Can specify * profileName, database, or both. The profile is the prefix to the host, * user, and password variables in .hg.conf. For the default profile of "db", * the environment variables HGDB_HOST, HGDB_USER, and HGDB_PASSWORD can * override. Return NULL if connection fails or profile is not found. */ { struct sqlProfile* sp = sqlProfileGet(profileName, database); if (sp == NULL) return NULL; return sqlConnRemote(sp, database, FALSE); } void sqlVaWarn(struct sqlConnection *sc, char *format, va_list args) /* Default error message handler. */ { MYSQL *conn = sc->conn; if (format != NULL) { vaWarn(format, args); } warn("mySQL error %d: %s (profile=%s, host=%s, db=%s)", mysql_errno(conn), mysql_error(conn), scConnProfile(sc), sqlGetHost(sc), scConnDb(sc)); } void sqlWarn(struct sqlConnection *sc, char *format, ...) /* Printf formatted error message that adds on sql * error message. */ { va_list args; va_start(args, format); sqlVaWarn(sc, format, args); va_end(args); } void sqlAbort(struct sqlConnection *sc, char *format, ...) /* Printf formatted error message that adds on sql * error message and abort. */ { va_list args; va_start(args, format); sqlVaWarn(sc, format, args); va_end(args); noWarnAbort(); } struct sqlConnection *sqlFailoverConn(struct sqlConnection *sc) /* Returns the failover connection of a connection or NULL. * (Needed because the sqlConnection is not in the .h file) */ { return sc->failoverConn; } bool sqlConnMustUseFailover(struct sqlConnection *sc) /* Returns true if a connection has a failover connection and * the current db does not exist on the main connection. */ { // a db that is different between the sqlConnection object and mysql means that we have // moved previously to a db that does not exist on the main connection server if ((sc->failoverConn != NULL) && differentStringNullOk(sc->db, sc->conn->db)) { monitorPrint(sc, "SQL_MAINCONN_DB_INVALID", "%s != %s", sc->db, sc->conn->db); return TRUE; } return FALSE; } char *sqlHostInfo(struct sqlConnection *sc) /* Returns the mysql host info for the connection, must be connected. */ { return (char *) mysql_get_host_info(sc->conn); } static struct sqlResult *sqlUseOrStore(struct sqlConnection *sc, char *query, ResGetter *getter, boolean abort) /* Returns NULL if result was empty and getter==mysql_use_result. * Otherwise returns a structure that you can do sqlRow() on. * Watch out for subtle differences between mysql_store_result and mysql_use_result. * We seem to be only using mysql_use_result these days, * but mysql_store_result has left a big footprint in the code/comments. * In particular, mysql_store_result can return NULL indicating an empty resultset. * But mysql_use_result cannot do that. Instead NULL return means error * and the user must call next_row to see if there's anything in the resultset. */ { struct sqlResult *res = NULL; struct sqlConnection *scMain = sc; long deltaTime; boolean fixedMultipleNOSQLINJ = FALSE; ++sqlTotalQueries; if (monitorFlags & JKSQL_TRACE) monitorPrintQuery(sc, query); if (startsWith(NOSQLINJ "", query)) { query += strlen(NOSQLINJ ""); // We know this query has been vetted for sql injection, skip over this tag. } else { sqlCheckError("Unvetted query: %s", query); } // additional check finds errors of multiple NOSQLINJ tags if (strstr(query, NOSQLINJ "")) { sqlCheckError("Oops, multiple occurrences of NOSQLINJ tag in query: %s", query); query = replaceChars(query, NOSQLINJ "", ""); fixedMultipleNOSQLINJ = TRUE; } if (sqlConnMustUseFailover(sc)) sc = sc->failoverConn; sqlConnectIfUnconnected(sc, abort); assert(!sc->isFree); monitorEnter(); int mysqlError = mysql_real_query(sc->conn, query, strlen(query)); // if the query fails on the main connection, connect the failover connection and try there if (mysqlError != 0 && sc->failoverConn && sameWord(sqlGetDatabase(sc), sqlGetDatabase(sc->failoverConn))) { if (monitorFlags & JKSQL_TRACE) monitorPrint(sc, "SQL_FAILOVER", "%s -> %s | %s", scConnProfile(sc), scConnProfile(sc->failoverConn), query); sc = sc->failoverConn; if (sqlConnectIfUnconnected(sc, FALSE)) mysqlError = mysql_real_query(sc->conn, query, strlen(query)); else // This database does not exist on the (slow-db) failover mysql server // It makes more sense to the show the error message we got from our main db sc = scMain; } if (mysqlError != 0) { if (abort) { monitorLeave(); if (sameOk(cfgOption("noSqlInj.dumpStack"), "on")) dumpStack("DEBUG Can't start query"); // Extra debugging info. DEBUG REMOVE sqlAbort(sc, "Can't start query:\n%s\n", query); } } else { MYSQL_RES *resSet; if ((resSet = getter(sc->conn)) == NULL) { if (mysql_errno(sc->conn) != 0) { monitorLeave(); sqlAbort(sc, "Can't use query:\n%s", query); } } else { AllocVar(res); res->conn = sc; res->result = resSet; res->node = dlAddValTail(sc->resultList, res); res->fetchTime = 0L; } } deltaTime = monitorLeave(); if (monitorFlags & JKSQL_TRACE) monitorPrint(sc, "SQL_TIME", "%0.3fs", ((double)deltaTime)/1000.0); if (fixedMultipleNOSQLINJ) freeMem(query); return res; } void sqlRenameTable(struct sqlConnection *sc, char *table1, char *table2) /* Rename table1 to table2 */ { char query[256]; sqlSafef(query, sizeof(query), "rename table %s to %s", table1, table2); sqlUpdate(sc, query); } void sqlDropTable(struct sqlConnection *sc, char *table) /* Drop table if it exists. */ { if (sqlTableExists(sc, table)) { char query[256]; sqlSafef(query, sizeof(query), "drop table %s", table); sqlUpdate(sc, query); } } void sqlCopyTable(struct sqlConnection *sc, char *table1, char *table2) /* Copy table1 to table2 */ { char query[256]; if (table1 == NULL || table2 == NULL) return; sqlSafef(query, sizeof(query), "create table %s like %s", table2, table1); sqlUpdate(sc, query); sqlSafef(query, sizeof(query), "insert into %s select * from %s", table2, table1); sqlUpdate(sc, query); } void sqlGetLockWithTimeout(struct sqlConnection *sc, char *name, int wait) /* Tries to get an advisory lock on the process, waiting for wait seconds. */ /* Blocks another client from obtaining a lock with the same name. */ { char query[256]; struct sqlResult *res; char **row = NULL; sqlSafef(query, sizeof(query), "select get_lock('%s', %d)", name, wait); res = sqlGetResult(sc, query); while ((row=sqlNextRow(res))) { if (sameWord(*row, "1")) // success break; else if (sameWord(*row, "0")) // timed out errAbort("Attempt to GET_LOCK timed out.\nAnother client may have locked this name, %s\n.", name); else if (*row == NULL) // other error errAbort("Attempt to GET_LOCK of name, %s, caused an error\n", name); } sqlFreeResult(&res); } void sqlGetLock(struct sqlConnection *sc, char *name) /* Gets an advisory lock created by GET_LOCK in sqlGetLock. Waits up to 1000 seconds. */ { sqlGetLockWithTimeout(sc, name, 1000); } boolean sqlIsLocked(struct sqlConnection *sc, char *name) /* Tests if an advisory lock on the given name has been set. * Returns true if lock has been set, otherwise returns false. */ { char query[256]; struct sqlResult *res; char **row = NULL; boolean result = FALSE; sqlSafef(query, sizeof(query), "select is_free_lock('%s')", name); res = sqlGetResult(sc, query); while ((row=sqlNextRow(res))) { if (sameWord(*row, "1")) // lock is free (not locked) { result = FALSE; break; } else if (sameWord(*row, "0")) // lock is not free (locked) { result = TRUE; break; } else if (*row == NULL) // other error errAbort("Attempt to GET_LOCK of name, %s, caused an error\n", name); } sqlFreeResult(&res); return result; } void sqlReleaseLock(struct sqlConnection *sc, char *name) /* Releases an advisory lock created by GET_LOCK in sqlGetLock */ { char query[256]; sqlSafef(query, sizeof(query), "select release_lock('%s')", name); sqlUpdate(sc, query); } void sqlHardUnlockAll(struct sqlConnection *sc) /* Unlock any hard locked tables. */ { if (sc->hasHardLock) { char query[32]; sqlSafef(query, sizeof query, "unlock tables"); sqlUpdate(sc, query); sc->hasHardLock = FALSE; } } void sqlHardLockTables(struct sqlConnection *sc, struct slName *tableList, boolean isWrite) /* Hard lock given table list. Unlock with sqlHardUnlockAll. */ { struct dyString *dy = dyStringNew(0); struct slName *table; char *how = (isWrite ? "WRITE" : "READ"); if (sc->hasHardLock) errAbort("sqlHardLockTables repeated without sqlHardUnlockAll."); sqlDyStringPrintf(dy, "LOCK TABLES "); for (table = tableList; table != NULL; table = table->next) { sqlDyStringPrintf(dy, "%s %s", table->name, how); if (table->next != NULL) dyStringAppendC(dy, ','); } sqlUpdate(sc, dy->string); sc->hasHardLock = TRUE; dyStringFree(&dy); } void sqlHardLockTable(struct sqlConnection *sc, char *table, boolean isWrite) /* Lock a single table. Unlock with sqlHardUnlockAll. */ { struct slName *list = slNameNew(table); sqlHardLockTables(sc, list, isWrite); slFreeList(&list); } void sqlHardLockAll(struct sqlConnection *sc, boolean isWrite) /* Lock all tables in current database. Unlock with sqlHardUnlockAll. */ { struct slName *tableList = sqlListTables(sc); sqlHardLockTables(sc, tableList, isWrite); slFreeList(&tableList); } boolean sqlMaybeMakeTable(struct sqlConnection *sc, char *table, char *query) /* Create table from query if it doesn't exist already. * Returns FALSE if didn't make table. */ { if (sqlTableExists(sc, table)) return FALSE; sqlUpdate(sc, query); return TRUE; } char *sqlGetCreateTable(struct sqlConnection *sc, char *table) /* Get the Create table statement. table must exist. */ { char query[256]; struct sqlResult *res; char **row = NULL; char *statement = NULL; sqlSafef(query, sizeof(query), "show create table %s", table); res = sqlGetResult(sc, query); if ((row=sqlNextRow(res))) { // skip first column which has useless table name in it. statement = cloneString(row[1]); } sqlFreeResult(&res); return statement; } void sqlRemakeTable(struct sqlConnection *sc, char *table, char *create) /* Drop table if it exists, and recreate it. */ { sqlDropTable(sc, table); sqlUpdate(sc, create); } boolean sqlDatabaseExists(char *database) /* Return TRUE if database exists. */ { struct sqlConnection *conn = sqlMayConnect(database); boolean exists = (conn != NULL); sqlDisconnect(&conn); return exists; } boolean sqlTableExists(struct sqlConnection *sc, char *table) /* Return TRUE if a table exists. * * If a failover connection is configured in hg.conf, looks up table in the main connection first * Uses a table name cache table, if configured in hg.conf */ { char query[256]; struct sqlResult *sr; if (sameString(table,"")) { if (sameOk(cfgOption("noSqlInj.dumpStack"), "on")) { dumpStack("jksql sqlTableExists: Buggy code is feeding me empty table name. table=[%s].\n", table); fflush(stderr); // log only } return FALSE; } // TODO If the ability to supply a list of tables is hardly used, // then we could switch it to simply %s below supporting a single // table at a time more securely. if (strchr(table,',')) { if (sameOk(cfgOption("noSqlInj.dumpStack"), "on")) dumpStack("sqlTableExists called on multiple tables with table=[%s]\n", table); } if (strchr(table,'%')) { if (sameOk(cfgOption("noSqlInj.dumpStack"), "on")) { dumpStack("jksql sqlTableExists: Buggy code is feeding me junk wildcards. table=[%s].\n", table); fflush(stderr); // log only } return FALSE; } if (strchr(table,'-')) { return FALSE; // mysql does not allow tables with dash (-) so it will not be found. // hg/lib/hdb.c can generate an invalid table names with dashes while looking for split tables, // if the first chrom name has a dash in it. Examples found were: scaffold_0.1-193456 scaffold_0.1-13376 HERVE_a-int 1-1 // Assembly hubs also may have dashes in chrom names. } // use the table cache if we have one struct sqlConnection *cacheConn = sqlTableCacheFindConn(sc); if (cacheConn) return sqlTableCacheTableExists(cacheConn, table); char *err; unsigned int errNo; const int tableNotFoundCode = 1146; sqlSafef(query, sizeof(query), "SELECT 1 FROM %-s LIMIT 0", sqlCkIl(table)); if ((sr = sqlGetResultExt(sc, query, &errNo, &err)) == NULL) { if (errNo == tableNotFoundCode) return FALSE; if (sc->failoverConn) { // if not found but we have a failover connection, check on it, too if ((sr = sqlGetResultExt(sc->failoverConn, query, &errNo, &err)) == NULL) { if (errNo == tableNotFoundCode) return FALSE; } } } if (!sr) errAbort("Mysql error during sqlTableExists(%s) %d: %s", table, errNo, err); sqlFreeResult(&sr); return TRUE; } // Note: this is copied from hdb.c's hParseDbDotTable. Normally I abhor copying but I really // don't want to make jksql.c depend on hdb.h... void sqlParseDbDotTable(char *dbIn, char *dbDotTable, char *dbOut, size_t dbOutSize, char *tableOut, size_t tableOutSize) /* If dbDotTable contains a '.', then assume it is db.table and parse out into dbOut and tableOut. * If not, then it's just a table; copy dbIn into dbOut and dbDotTable into tableOut. */ { char *dot = strchr(dbDotTable, '.'); char *table = dbDotTable; if (dot != NULL) { safencpy(dbOut, dbOutSize, dbDotTable, dot - dbDotTable); table = &dot[1]; } else safecpy(dbOut, dbOutSize, dbIn); safecpy(tableOut, tableOutSize, table); } // forward declaration to avoid moving code around: static boolean sqlConnChangeDbMainOrFailover(struct sqlConnection *sc, char *database, boolean abort); bool sqlColumnExists(struct sqlConnection *conn, char *table, char *column) /* return TRUE if column exists in table. column can contain sql wildcards */ { // "show columns ... like" does not support db.table names, so temporarily change database // if table is really db.table. char *connDb = cloneString(sqlGetDatabase(conn)); char tableDb[1024]; char tableName[1024]; sqlParseDbDotTable(connDb, table, tableDb, sizeof tableDb, tableName, sizeof tableName); char query[1024]; sqlSafef(query, 1024, "SHOW COLUMNS FROM `%s` LIKE '%s'", tableName, column); boolean changeDb = differentStringNullOk(connDb, tableDb); if (changeDb) sqlConnChangeDbMainOrFailover(conn, tableDb, TRUE); char buf[1024]; char *ret = sqlQuickQuery(conn, query, buf, 1024); if (changeDb) sqlConnChangeDbMainOrFailover(conn, connDb, TRUE); freeMem(connDb); return (ret!=NULL); } int sqlTableSizeIfExists(struct sqlConnection *sc, char *table) /* Return row count if a table exists, -1 if it doesn't. */ { char query[256]; struct sqlResult *sr; char **row = 0; int ret = 0; sqlSafef(query, sizeof(query), "select count(*) from %s", table); if ((sr = sqlUseOrStore(sc, query, DEFAULTGETTER, FALSE)) == NULL) return -1; row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) ret = atoi(row[0]); sqlFreeResult(&sr); return ret; } boolean sqlTablesExist(struct sqlConnection *conn, char *tables) /* Check all tables in space delimited string exist. */ { char *dupe = cloneString(tables); char *s = dupe, *word; boolean ok = TRUE; while ((word = nextWord(&s)) != NULL) { if (!sqlTableExists(conn, word)) { ok = FALSE; break; } } freeMem(dupe); return ok; } boolean sqlTableWildExists(struct sqlConnection *sc, char *table) /* Return TRUE if table (which can include SQL wildcards) exists. * A bit slower than sqlTableExists. */ { char query[512]; struct sqlResult *sr; char **row; boolean exists; // "show tables" does not support db.table names, so temporarily change database // if table is really db.table. char *connDb = cloneString(sqlGetDatabase(sc)); char tableDb[1024]; char tableName[1024]; sqlParseDbDotTable(connDb, table, tableDb, sizeof tableDb, tableName, sizeof tableName); sqlSafef(query, sizeof(query), "show tables like '%s'", tableName); boolean changeDb = differentStringNullOk(connDb, tableDb); if (changeDb) sqlConnChangeDbMainOrFailover(sc, tableDb, TRUE); sr = sqlGetResult(sc, query); exists = ((row = sqlNextRow(sr)) != NULL); sqlFreeResult(&sr); if (changeDb) sqlConnChangeDbMainOrFailover(sc, connDb, TRUE); freeMem(connDb); return exists; } static char **sqlMaybeNextRow(struct sqlResult *sr, boolean *retOk) /* Get next row from query result; set retOk according to error status. */ { char** row = NULL; if (sr != NULL) { monitorEnter(); row = mysql_fetch_row(sr->result); sr->fetchTime += monitorLeave(); if (mysql_errno(sr->conn->conn) != 0) { if (retOk != NULL) *retOk = FALSE; } else if (retOk != NULL) *retOk = TRUE; } else if (retOk != NULL) *retOk = TRUE; return row; } struct sqlResult *sqlGetResultExt(struct sqlConnection *sc, char *query, unsigned int *errorNo, char **error) /* Returns NULL if it had an error. * Otherwise returns a structure that you can do sqlRow() on. * If there was an error, *errorNo will be set to the mysql error number, * and *error will be set to the mysql error string, which MUST NOT be freed. */ { struct sqlResult *sr = sqlUseOrStore(sc, query, DEFAULTGETTER, FALSE); if (sr == NULL) { MYSQL *conn = sc->conn; if (errorNo) *errorNo=mysql_errno(conn); if (error) *error=(char *)mysql_error(conn); } else { if (errorNo) *errorNo=0; if (error) *error=NULL; } return sr; } struct sqlResult *sqlGetResult(struct sqlConnection *sc, char *query) /* * Return a structure that you can do sqlNextRow() on. * (You need to check the return value of sqlRow to find out if there are * any results.) */ { return sqlUseOrStore(sc, query, DEFAULTGETTER, TRUE); } struct sqlResult *sqlMustGetResult(struct sqlConnection *sc, char *query) /* * Return a structure that you can do sqlNextRow() on. * DOES NOT errAbort() IF THERE ARE NO RESULTS * (These days, with mysql_use_result, we cannot know ahead of time * if there are results, we can only know by actually trying to fetch a row. * So in fact right now sqlMustGetResult is no different than sqlGetResult.) */ { struct sqlResult *res = sqlGetResult(sc,query); if (res == NULL) errAbort("Object not found in database.\nQuery was %s", query); return res; } void sqlUpdate(struct sqlConnection *conn, char *query) /* Tell database to do something that produces no results table. */ { struct sqlResult *sr; sr = sqlGetResult(conn,query); sqlFreeResult(&sr); } int sqlUpdateRows(struct sqlConnection *conn, char *query, int* matched) /* Execute an update query, returning the number of rows changed. If matched * is not NULL, it gets the total number matching the query. */ { int numChanged = 0; int numMatched = 0; const char *info; int numScan = 0; struct sqlResult *sr = sqlGetResult(conn,query); /* Rows matched: 40 Changed: 40 Warnings: 0 */ monitorEnter(); info = mysql_info(conn->conn); monitorLeave(); if (info != NULL) numScan = sscanf(info, "Rows matched: %d Changed: %d Warnings: %*d", &numMatched, &numChanged); if ((info == NULL) || (numScan < 2)) errAbort("can't get info (maybe not an sql UPDATE): %s", query); sqlFreeResult(&sr); if (matched != NULL) *matched = numMatched; return numChanged; } void sqlWarnings(struct sqlConnection *conn, int numberOfWarnings) /* Show the number of warnings requested. New feature in mysql5. */ { struct sqlResult *sr; char **row; char query[256]; struct dyString *dy = dyStringNew(0); sqlSafef(query,sizeof(query),"show warnings limit 0, %d", numberOfWarnings); sr = sqlGetResult(conn, query); dyStringPrintf(dy, "Level Code Message\n"); while ((row = sqlNextRow(sr)) != NULL) { dyStringPrintf(dy, "%s %s %s\n", row[0], row[1], row[2]); } sqlFreeResult(&sr); warn("%s", dy->string); dyStringFree(&dy); } int sqlWarnCount(struct sqlConnection *conn) /* Return the number of warnings. New feature in mysql5. */ { char query[64]; sqlSafef(query, sizeof query, "SHOW COUNT(*) WARNINGS"); return sqlQuickNum(conn, query); } void sqlLoadTabFile(struct sqlConnection *conn, char *path, char *table, unsigned options) /* Load a tab-seperated file into a database table, checking for errors. * Options are the SQL_TAB_* bit set. SQL_TAB_FILE_ON_SERVER is ignored if * sqlIsRemote() returns true. */ { assert(!conn->isFree); char tabPath[PATH_LEN]; char query[PATH_LEN+256]; int numScan, numRecs, numSkipped, numWarnings; char *localOpt, *concurrentOpt, *dupOpt; const char *info; struct sqlResult *sr; /* Doing an "alter table disable keys" command implicitly commits the current transaction. Don't want to use that optimization if we need to be transaction safe. */ /* FIXME: markd 2003/01/05: mysql 4.0.17 - the alter table enable keys hangs, * disable this optimization for now. Verify performance on small loads * before re-enabling*/ # if 0 boolean doDisableKeys = !(options & SQL_TAB_TRANSACTION_SAFE); #else boolean doDisableKeys = FALSE; #endif /* determine if tab file can be accessed directly by the database, or send * over the network */ bool sqlNeverLocal = cfgOptionBooleanDefault("db.neverLocal", 0); if (((options & SQL_TAB_FILE_ON_SERVER) && !sqlIsRemote(conn)) | sqlNeverLocal) { /* tab file on server requiries full path */ strcpy(tabPath, ""); if (path[0] != '/') { if (getcwd(tabPath, sizeof(tabPath)) == NULL) errAbort("sqlLoadTableFile: getcwd failed"); safecat(tabPath, sizeof(tabPath), "/"); } safecat(tabPath, sizeof(tabPath), path); localOpt = ""; } else { safecpy(tabPath, sizeof(tabPath), path); localOpt = "LOCAL"; } /* optimize for concurrent to others to access the table. */ if (options & SQL_TAB_FILE_CONCURRENT) concurrentOpt = "CONCURRENT"; else { concurrentOpt = ""; if (doDisableKeys) { /* disable update of indexes during load. Inompatible with concurrent, * since enable keys locks other's out. */ sqlSafef(query, sizeof(query), "ALTER TABLE %s DISABLE KEYS", table); sqlUpdate(conn, query); } } if (options & SQL_TAB_REPLACE) dupOpt = "REPLACE"; else dupOpt = ""; sqlSafef(query, sizeof(query), "LOAD DATA %s %s INFILE '%s' %s INTO TABLE %s", concurrentOpt, localOpt, tabPath, dupOpt, table); sr = sqlGetResult(conn, query); monitorEnter(); info = mysql_info(conn->conn); monitorLeave(); if (info == NULL) errAbort("no info available for result of sql query: %s", query); numScan = sscanf(info, "Records: %d Deleted: %*d Skipped: %d Warnings: %d", &numRecs, &numSkipped, &numWarnings); if (numScan != 3) errAbort("can't parse sql load info: %s", info); sqlFreeResult(&sr); /* mysql 5.0 bug: mysql_info returns unreliable warnings count, so use this instead: */ numWarnings = sqlWarnCount(conn); if ((numSkipped > 0) || (numWarnings > 0)) { boolean doAbort = TRUE; if ((numSkipped > 0) && (options & SQL_TAB_FILE_WARN_ON_ERROR)) doAbort = FALSE; /* don't abort on errors */ else if ((numWarnings > 0) && (options & (SQL_TAB_FILE_WARN_ON_ERROR|SQL_TAB_FILE_WARN_ON_WARN))) doAbort = FALSE; /* don't abort on warnings */ if (numWarnings > 0) { sqlWarnings(conn, 10); /* show the first 10 warnings */ } if (doAbort) errAbort("load of %s did not go as planned: %d record(s), " "%d row(s) skipped, %d warning(s) loading %s", table, numRecs, numSkipped, numWarnings, path); else warn("Warning: load of %s did not go as planned: %d record(s), " "%d row(s) skipped, %d warning(s) loading %s", table, numRecs, numSkipped, numWarnings, path); } if (((options & SQL_TAB_FILE_CONCURRENT) == 0) && doDisableKeys) { /* reenable update of indexes */ sqlSafef(query, sizeof(query), "ALTER TABLE %s ENABLE KEYS", table); sqlUpdate(conn, query); } } boolean sqlExists(struct sqlConnection *conn, char *query) /* Query database and return TRUE if it had a non-empty result. */ { struct sqlResult *sr; if ((sr = sqlGetResult(conn,query)) == NULL) return FALSE; else { if(sqlNextRow(sr) == NULL) { sqlFreeResult(&sr); return FALSE; } else { sqlFreeResult(&sr); return TRUE; } } } boolean sqlRowExists(struct sqlConnection *conn, char *table, char *field, char *key) /* Return TRUE if row where field = key is in table. */ { char query[256]; sqlSafef(query, sizeof(query), "select count(*) from %s where %s = '%s'", table, field, key); return sqlQuickNum(conn, query) > 0; } int sqlRowCount(struct sqlConnection *conn, char *queryTblAndCondition) /* Return count of rows that match condition. The queryTblAndCondition * should contain everying after "select count(*) FROM " */ { char query[256]; sqlSafef(query, sizeof(query), "select count(*) from %-s",queryTblAndCondition); // NOSQLINJ since we cannot check the queryTblAndCondition here, the users of this function have been fixed. return sqlQuickNum(conn, query); } struct sqlResult *sqlStoreResult(struct sqlConnection *sc, char *query) /* Returns NULL if result was empty. Otherwise returns a structure * that you can do sqlRow() on. Same interface as sqlGetResult, * but internally this keeps the entire result in memory. */ { return sqlUseOrStore(sc,query,mysql_store_result, TRUE); } char **sqlNextRow(struct sqlResult *sr) /* Get next row from query result. */ { boolean ok = FALSE; char** row = sqlMaybeNextRow(sr, &ok); if (! ok) sqlAbort(sr->conn, "nextRow failed"); return row; } char* sqlFieldName(struct sqlResult *sr) /* repeated calls to this function returns the names of the fields * the given result */ { MYSQL_FIELD *field; field = mysql_fetch_field(sr->result); if(field == NULL) return NULL; return field->name; } struct slName *sqlResultFieldList(struct sqlResult *sr) /* Return slName list of all fields in query. Can just be done once per query. */ { struct slName *list = NULL; char *field; while ((field = sqlFieldName(sr)) != NULL) slNameAddHead(&list, field); slReverse(&list); return list; } int sqlResultFieldArray(struct sqlResult *sr, char ***retArray) /* Get the fields of sqlResult, returning count, and the results * themselves in *retArray. */ { struct slName *el, *list = sqlResultFieldList(sr); int count = slCount(list); char **array; AllocArray(array, count); int i; for (el=list,i=0; el != NULL; el = el->next, ++i) array[i] = cloneString(el->name); *retArray = array; return count; } int sqlFieldColumn(struct sqlResult *sr, char *colName) /* get the column number of the specified field in the result, or * -1 if the result doesn't contain the field.*/ { int numFields = mysql_num_fields(sr->result); int i; for (i = 0; i < numFields; i++) { MYSQL_FIELD *field = mysql_fetch_field_direct(sr->result, i); if (sameString(field->name, colName)) return i; } return -1; } int sqlCountColumns(struct sqlResult *sr) /* Count the number of columns in result. */ { if(sr != NULL) return mysql_field_count(sr->conn->conn); return 0; } int sqlFieldCount(struct sqlResult *sr) /* Return number of fields in a row of result. */ { if (sr == NULL) return 0; return mysql_num_fields(sr->result); } int sqlCountColumnsInTable(struct sqlConnection *sc, char *table) /* Return the number of columns in a table */ { struct sqlResult *sr; char **row; int count; /* Read table description and count rows. */ sr = sqlDescribe(sc, table); count = 0; while ((row = sqlNextRow(sr)) != NULL) { count++; } sqlFreeResult(&sr); return count; } char *sqlQuickQuery(struct sqlConnection *sc, char *query, char *buf, int bufSize) /* Does query and returns first field in first row. Meant * for cases where you are just looking up one small thing. * Returns NULL if query comes up empty. */ { struct sqlResult *sr; char **row; char *ret = NULL; if ((sr = sqlGetResult(sc, query)) == NULL) return NULL; row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) { safecpy(buf, bufSize, row[0]); ret = buf; } sqlFreeResult(&sr); return ret; } char *sqlNeedQuickQuery(struct sqlConnection *sc, char *query, char *buf, int bufSize) /* Does query and returns first field in first row. Meant * for cases where you are just looking up one small thing. * Prints error message and aborts if query comes up empty. */ { char *s = sqlQuickQuery(sc, query, buf, bufSize); if (s == NULL) errAbort("query not found: %s", query); return s; } int sqlQuickNum(struct sqlConnection *conn, char *query) /* Get numerical result from simple query */ { struct sqlResult *sr; char **row; int ret = 0; sr = sqlGetResult(conn, query); row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) ret = atoi(row[0]); sqlFreeResult(&sr); return ret; } long long sqlQuickLongLong(struct sqlConnection *conn, char *query) /* Get long long numerical result from simple query. Returns 0 if query not found */ { struct sqlResult *sr; char **row; long long ret = 0; sr = sqlGetResult(conn, query); row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) ret = sqlLongLong(row[0]); sqlFreeResult(&sr); return ret; } double sqlQuickDouble(struct sqlConnection *conn, char *query) /* Get floating point numerical result from simple query */ { struct sqlResult *sr; char **row; double ret = 0; sr = sqlGetResult(conn, query); row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) ret = atof(row[0]); sqlFreeResult(&sr); return ret; } int sqlNeedQuickNum(struct sqlConnection *conn, char *query) /* Get numerical result or die trying. */ { char buf[32]; sqlNeedQuickQuery(conn, query, buf, sizeof(buf)); if (!((buf[0] == '-' && isdigit(buf[1])) || isdigit(buf[0]))) errAbort("Expecting numerical result to query '%s' got '%s'", query, buf); return sqlSigned(buf); } char *sqlQuickString(struct sqlConnection *sc, char *query) /* Return result of single-row/single column query in a * string that should eventually be freeMem'd. */ { struct sqlResult *sr; char **row; char *ret = NULL; if ((sr = sqlGetResult(sc, query)) == NULL) return NULL; row = sqlNextRow(sr); if (row != NULL && row[0] != NULL) ret = cloneString(row[0]); sqlFreeResult(&sr); return ret; } char *sqlNeedQuickString(struct sqlConnection *sc, char *query) /* Return result of single-row/single column query in a * string that should eventually be freeMem'd. This will * print an error message and abort if result returns empty. */ { char *s = sqlQuickString(sc, query); if (s == NULL) errAbort("query not found: %s", query); return s; } char *sqlQuickNonemptyString(struct sqlConnection *conn, char *query) /* Return first result of given query. If it is an empty string * convert it to NULL. */ { char *result = sqlQuickString(conn, query); if (result != NULL && result[0] == 0) freez(&result); return result; } struct slName *sqlQuickList(struct sqlConnection *conn, char *query) /* Return a list of slNames for a single column query. * Do a slFreeList on result when done. */ { struct slName *list = NULL, *n; struct sqlResult *sr; char **row; sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { n = slNameNew(row[0]); slAddHead(&list, n); } sqlFreeResult(&sr); slReverse(&list); return list; } struct hash *sqlQuickHash(struct sqlConnection *conn, char *query) /* Return a hash filled with results of two column query. * The first column is the key, the second the value. */ { struct hash *hash = hashNew(16); struct sqlResult *sr; char **row; sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) hashAdd(hash, row[0], cloneString(row[1])); sqlFreeResult(&sr); return hash; } struct slInt *sqlQuickNumList(struct sqlConnection *conn, char *query) /* Return a list of slInts for a single column query. * Do a slFreeList on result when done. */ { struct slInt *list = NULL, *n; struct sqlResult *sr; char **row; sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { n = slIntNew(sqlSigned(row[0])); slAddHead(&list, n); } sqlFreeResult(&sr); slReverse(&list); return list; } struct slDouble *sqlQuickDoubleList(struct sqlConnection *conn, char *query) /* Return a list of slDoubles for a single column query. * Do a slFreeList on result when done. */ { struct slDouble *list = NULL, *n; struct sqlResult *sr; char **row; sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { n = slDoubleNew(atof(row[0])); slAddHead(&list, n); } sqlFreeResult(&sr); slReverse(&list); return list; } struct slPair *sqlQuickPairList(struct sqlConnection *conn, char *query) /* Return a list of slPairs with the results of a two-column query. * Free result with slPairFreeValsAndList. */ { struct slPair *pairList = NULL; struct sqlResult *sr = sqlGetResult(conn, query); char **row; while ((row = sqlNextRow(sr)) != NULL) slAddHead(&pairList, slPairNew(row[0], cloneString(row[1]))); sqlFreeResult(&sr); slReverse(&pairList); return pairList; } int sqlTableSize(struct sqlConnection *conn, char *table) /* Find number of rows in table. */ { char query[128]; sqlSafef(query, sizeof(query), "SELECT COUNT(*) FROM %s", table); return sqlQuickNum(conn, query); } int sqlFieldIndex(struct sqlConnection *conn, char *table, char *field) /* Returns index of field in a row from table, or -1 if it * doesn't exist. */ { struct sqlResult *sr; char **row; int i = 0, ix=-1; /* Read table description into hash. */ sr = sqlDescribe(conn, table); while ((row = sqlNextRow(sr)) != NULL) { if (sameString(row[0], field)) { ix = i; break; } ++i; } sqlFreeResult(&sr); return ix; } struct slName *sqlFieldNames(struct sqlConnection *conn, char *table) /* Returns field names from a table. */ { struct slName *list = NULL; struct sqlResult *sr; char **row; sr = sqlDescribe(conn, table); while ((row = sqlNextRow(sr)) != NULL) slNameAddHead(&list, row[0]); sqlFreeResult(&sr); slReverse(&list); return list; } unsigned int sqlLastAutoId(struct sqlConnection *conn) /* Return last automatically incremented id inserted into database. */ { assert(!conn->isFree); unsigned id; monitorEnter(); id = mysql_insert_id(conn->conn); monitorLeave(); return id; } /* Stuff to manage and caches of open connections on a database. Typically * you only need 3. MySQL takes about 2 milliseconds on a local host to open * a connection. On a remote host it can be more and this caching is probably * actually necessary. However, much code has been written assuming caching, * so it is probably now necessary. */ enum {sqlConnCacheMax = 16}; struct sqlConnCache { /* the following are NULL unless explicitly specified */ char *host; /* Host machine of database. */ char *user; /* Database user name */ char *password; /* Password. */ struct sqlProfile *profile; /* restrict to this profile */ /* contents of cache */ int entryCnt; /* # open connections. */ struct sqlConnCacheEntry *entries; /* entries in the cache */ }; struct sqlConnCacheEntry /* an entry in the cache */ { struct sqlConnCacheEntry *next; struct sqlProfile *profile; /* profile for connection, can be NULL if host is explicit */ struct sqlConnection *conn; /* connection */ boolean inUse; /* is this in use? */ }; struct sqlConnCache *sqlConnCacheNewRemote(char *host, char *user, char *password) /* Set up a cache on a remote database. */ { struct sqlConnCache *cache; AllocVar(cache); cache->host = cloneString(host); cache->user = cloneString(user); cache->password = cloneString(password); return cache; } struct sqlConnCache *sqlConnCacheNew() /* Return a new connection cache. */ { struct sqlConnCache *cache; AllocVar(cache); return cache; } struct sqlConnCache *sqlConnCacheNewProfile(char *profileName) /* Return a new connection cache associated with the particular profile. */ { struct sqlConnCache *cache = sqlConnCacheNew(); cache->profile = sqlProfileMustGet(profileName, NULL); return cache; } void sqlConnCacheFree(struct sqlConnCache **pCache) /* Dispose of a connection cache. */ { struct sqlConnCache *cache; if ((cache = *pCache) != NULL) { struct sqlConnCacheEntry *scce; for (scce = cache->entries; scce != NULL; scce = scce->next) { scce->conn->inCache = FALSE; scce->conn->isFree = FALSE; sqlDisconnect(&scce->conn); } slFreeList(&cache->entries); freeMem(cache->host); freeMem(cache->user); freeMem(cache->password); freez(pCache); } } static struct sqlConnCacheEntry *sqlConnCacheAdd(struct sqlConnCache *cache, struct sqlProfile *profile, struct sqlConnection *conn) /* create and add a new cache entry */ { struct sqlConnCacheEntry *scce; AllocVar(scce); scce->profile = profile; scce->conn = conn; conn->inCache = TRUE; conn->isFree = TRUE; slAddHead(&cache->entries, scce); cache->entryCnt++; return scce; } static boolean sqlConnCacheEntryDbMatch(struct sqlConnCacheEntry *scce, char *database) /* does a database match the one in the connection cache? */ { return (sameOk(database, sqlGetDatabase(scce->conn))); } static int sqlConnChangeDb(struct sqlConnection *sc, char *database, bool mustConnect) /* change the db variable of an sqlConnection, try to change the mysql db and * return the result code. */ { // update the db variable monitorPrint(sc, "SQL_SET_DB", "%s", database); freeMem(sc->db); sc->db = cloneString(database); if (mustConnect) { if (!sqlConnectIfUnconnected(sc, FALSE)) { monitorPrint(sc, "SQL_SET_DB_FAILED", "%s", database); return -1; } } // change the db int resCode = 0; if (sc->conn) { resCode = mysql_select_db(sc->conn, database); if (resCode!=0) monitorPrint(sc, "SQL_SET_DB_ERROR", "%d", resCode); } sc->hasTableCache = -1; // -1 = undefined return resCode; } static boolean sqlConnChangeDbFailover(struct sqlConnection *sc, char *database, boolean abort) /* only fail if both main and failover cannot connect */ /* This allows to have databases that exist only on one of both servers */ { int mainConnErr = sqlConnChangeDb(sc, database, TRUE); int foConnErr = sqlConnChangeDb(sc->failoverConn, database, sqlConnMustUseFailover(sc)); if (mainConnErr!=0 && foConnErr!=0) { if (abort) { struct sqlConnection *errSc; if (foConnErr!=0) errSc = sc->failoverConn; else errSc = sc; sqlAbort(sc, "Couldn't set connection database to %s\n%s", database, mysql_error(errSc->conn)); } return FALSE; } return TRUE; } static boolean sqlConnChangeDbMain(struct sqlConnection *sc, char *database, boolean abort) /* change the database of an sql connection */ { int connErr = sqlConnChangeDb(sc, database, abort); if (connErr != 0) { if (abort) sqlAbort(sc, "Couldn't set connection database to %s", database); return FALSE; } return TRUE; } static boolean sqlConnChangeDbMainOrFailover(struct sqlConnection *sc, char *database, boolean abort) /* change the database of an sql connection, using failover if applicable */ { if (sc->failoverConn == NULL) return sqlConnChangeDbMain(sc, database, abort); else return sqlConnChangeDbFailover(sc, database, abort); } static boolean sqlConnCacheEntrySetDb(struct sqlConnCacheEntry *scce, char *database, boolean abort) /* set the connect cache and connect to the specified database */ { struct sqlConnection *sc = scce->conn; return sqlConnChangeDbMainOrFailover(sc, database, abort); } static struct sqlConnCacheEntry *sqlConnCacheFindFree(struct sqlConnCache *cache, struct sqlProfile *profile, char *database, boolean matchDatabase) /* find a free entry associated with profile and database. Return NULL if no * entries are available. Will attempt to match database if requested, this * includes connections to no database (database==NULL). */ { struct sqlConnCacheEntry *scce; for (scce = cache->entries; scce != NULL; scce = scce->next) { if (!scce->inUse && (profile == scce->profile) && ((!matchDatabase) || sqlConnCacheEntryDbMatch(scce, database))) { return scce; } } return NULL; } static struct sqlConnCacheEntry *sqlConnCacheAddNew(struct sqlConnCache *cache, struct sqlProfile *profile, char *database, boolean abort) /* create and add a new connect to the cache */ { struct sqlConnection *conn; if (cache->entryCnt >= sqlConnCacheMax) errAbort("Too many open sqlConnections for cache"); if (cache->host != NULL) { struct sqlProfile *clone = sqlProfileClone(profile); clone->host = cache->host; clone->port = 0; clone->socket = NULL; clone->user = cache->user; clone->password = cache->password; conn = sqlConnRemote(clone, database, abort); } else { conn = sqlConnProfile(profile, database, abort); } if (conn != NULL) return sqlConnCacheAdd(cache, profile, conn); else { assert(!abort); return NULL; } } static struct sqlConnection *sqlConnCacheDoAlloc(struct sqlConnCache *cache, char *profileName, char *database, boolean abort) /* Allocate a cached connection. errAbort if too many open connections. * errAbort if abort and connection fails. */ { // obtain profile struct sqlProfile *profile = NULL; if ((cache->host != NULL) && (profileName != NULL)) errAbort("can't specify profileName (%s) when sqlConnCache is create with a specific host (%s)", profileName, cache->host); if ((profileName != NULL) && (cache->profile != NULL) && !sameString(profileName, cache->profile->name)) errAbort("profile name %s doesn't match profile associated with sqlConnCache %s", profileName, cache->profile->name); if (cache->profile != NULL) profile = cache->profile; else profile = sqlProfileMustGet(profileName, database); // try getting an entry, first trying to find one for this database, then // look for any database, then add a new one struct sqlConnCacheEntry *scce = sqlConnCacheFindFree(cache, profile, database, TRUE); if (scce == NULL) { scce = sqlConnCacheFindFree(cache, profile, database, FALSE); if (scce != NULL) { if (!sqlConnCacheEntrySetDb(scce, database, abort)) scce = NULL; // got error with no abort } else scce = sqlConnCacheAddNew(cache, profile, database, abort); } if (scce != NULL) { assert(scce->conn->isFree); scce->inUse = TRUE; scce->conn->isFree = FALSE; return scce->conn; } else return NULL; } struct sqlConnection *sqlConnCacheMayAlloc(struct sqlConnCache *cache, char *database) /* Allocate a cached connection. errAbort if too many open connections, * return NULL if can't connect to server. */ { return sqlConnCacheDoAlloc(cache, NULL, database, FALSE); } struct sqlConnection *sqlConnCacheAlloc(struct sqlConnCache *cache, char *database) /* Allocate a cached connection. */ { return sqlConnCacheDoAlloc(cache, NULL, database, TRUE); } struct sqlConnection *sqlConnCacheProfileAlloc(struct sqlConnCache *cache, char *profileName, char *database) /* Allocate a cached connection given a profile and/or database. */ { return sqlConnCacheDoAlloc(cache, profileName, database, TRUE); } struct sqlConnection *sqlConnCacheProfileAllocMaybe(struct sqlConnCache *cache, char *profileName, char *database) /* Allocate a cached connection given a profile and/or database. Return NULL * if the database doesn't exist. */ { return sqlConnCacheDoAlloc(cache, profileName, database, FALSE); } void sqlConnCacheDealloc(struct sqlConnCache *cache, struct sqlConnection **pConn) /* Free up a cached connection. */ { struct sqlConnection *conn = *pConn; if (conn != NULL) { if (!conn->inCache) errAbort("sqlConnCacheDealloc called on connection that is not associated with a cache"); assert(!conn->isFree); conn->isFree = TRUE; struct sqlConnCacheEntry *scce; for (scce = cache->entries; (scce != NULL) && (scce->conn != conn); scce = scce->next) continue; if (scce == NULL) errAbort("sqlConnCacheDealloc called on cache that doesn't contain " "the given connection"); scce->inUse = FALSE; *pConn = NULL; } } unsigned long sqlEscapeStringFull(char *to, const char* from, long fromLength) /* Prepares a string for inclusion in a sql statement. Output string * must be 2*strlen(from)+1. fromLength is the length of the from data. * Specifying fromLength allows one to encode a binary string that can contain any character including 0. */ { return mysql_escape_string(to, from, fromLength); } // where am I using this? probably just cart.c and maybe cartDb.c ? // but it is worth keeping just for the cart. void sqlDyAppendEscaped(struct dyString *dy, char *s) /* Append to dy an escaped s */ { dyStringBumpBufSize(dy, dy->stringSize + strlen(s)*2); int realSize = sqlEscapeString3(dy->string+dy->stringSize, s); dy->stringSize += realSize; } unsigned long sqlEscapeString3(char *to, const char* from) /* Prepares a string for inclusion in a sql statement. Output string * must be 2*strlen(from)+1. Returns actual escaped size not counting term 0. */ { return sqlEscapeStringFull(to, from, strlen(from)); } char *sqlEscapeString2(char *to, const char* from) /* Prepares a string for inclusion in a sql statement. Output string * must be 2*strlen(from)+1 */ { sqlEscapeStringFull(to, from, strlen(from)); return to; } char *sqlEscapeString(const char* from) /* Prepares string for inclusion in a SQL statement . Remember to free * returned string. Returned string contains strlen(length)*2+1 as many bytes * as orig because in worst case every character has to be escaped.*/ { int size = (strlen(from)*2) +1; char *to = needMem(size * sizeof(char)); return sqlEscapeString2(to, from); } char *sqlEscapeTabFileString2(char *to, const char *from) /* Escape a string for including in a tab seperated file. Output string * must be 2*strlen(from)+1 */ { const char *fp = from; char *tp = to; while (*fp != '\0') { switch (*fp) { case '\\': *tp++ = '\\'; *tp++ = '\\'; break; case '\n': *tp++ = '\\'; *tp++ = 'n'; break; case '\t': *tp++ = '\\'; *tp++ = 't'; break; default: *tp++ = *fp; break; } fp++; } *tp = '\0'; return to; } char *sqlEscapeTabFileString(const char *from) /* Escape a string for including in a tab seperated file. Freez or freeMem * result when done. */ { int size = (strlen(from)*2) +1; char *to = needMem(size * sizeof(char)); return sqlEscapeTabFileString2(to, from); } static void addProfileDatabases(char *profileName, struct hash *databases) /* find databases on a profile and add to hash */ { struct sqlConnection *sc = sqlMayConnectProfile(profileName, NULL); if (sc != NULL) { struct slName *db, *dbs = sqlGetAllDatabase(sc); for (db = dbs; db != NULL; db = db->next) hashAdd(databases, db->name, NULL); sqlDisconnect(&sc); slFreeList(&dbs); } } struct hash *sqlHashOfDatabases(void) /* Get hash table with names of all databases that are online. */ { if (profiles == NULL) sqlProfileLoad(); struct hash *databases = newHash(8); // add databases found using default profile addProfileDatabases(getDefaultProfileName(), databases); // add databases found in failover profile char *failoverProfName = catTwoStrings(failoverProfPrefix, getDefaultProfileName()); addProfileDatabases(failoverProfName, databases); freez(&failoverProfName); // add other databases explicitly associated with other profiles struct hashCookie cookie = hashFirst(dbToProfile); struct hashEl *hel; while ((hel = hashNext(&cookie)) != NULL) { char *db = ((struct sqlProfile*)hel->val)->name; hashAdd(databases, db, NULL); } return databases; } struct slName *sqlListOfDatabases(void) /* Get list of all databases that are online. */ { /* build hash and convert to names list to avoid duplicates due to visiting * multiple profiles to the same server */ struct hash *dbHash = sqlHashOfDatabases(); struct hashCookie cookie = hashFirst(dbHash); struct hashEl *hel; struct slName *dbs = NULL; while ((hel = hashNext(&cookie)) != NULL) slSafeAddHead(&dbs, slNameNew(hel->name)); hashFree(&dbHash); slSort(&dbs, slNameCmp); return dbs; } boolean sqlWildcardIn(char *s) /* Return TRUE if there is a sql wildcard char in string. */ { char c; while ((c = *s++) != 0) { if (c == '_' || c == '%') return TRUE; } return FALSE; } char *sqlLikeFromWild(char *wild) /* Convert normal wildcard string to SQL wildcard by * mapping * to % and ? to _. Escape any existing % and _'s. */ { int escCount = countChars(wild, '%') + countChars(wild, '_'); int size = strlen(wild) + escCount + 1; char *retVal = needMem(size); char *s = retVal, c; while ((c = *wild++) != 0) { switch (c) { case '%': case '_': *s++ = '\\'; *s++ = c; break; case '*': *s++ = '%'; break; case '?': *s++ = '_'; break; default: *s++ = c; break; } } return retVal; } long sqlDateToUnixTime(char *sqlDate) /* Convert a SQL date such as "2003-12-09 11:18:43" to clock time * (seconds since midnight 1/1/1970 in UNIX). */ { struct tm *tm = NULL; long clockTime = 0; if (sqlDate == NULL) errAbort("Null string passed to sqlDateToUnixTime()"); AllocVar(tm); if (sscanf(sqlDate, "%4d-%2d-%2d %2d:%2d:%2d", &(tm->tm_year), &(tm->tm_mon), &(tm->tm_mday), &(tm->tm_hour), &(tm->tm_min), &(tm->tm_sec)) != 6) errAbort("Couldn't parse sql date \"%s\"", sqlDate); tm->tm_year -= 1900; tm->tm_mon -= 1; /* Ask mktime to determine whether Daylight Savings Time is in effect for * the given time: */ tm->tm_isdst = -1; clockTime = mktime(tm); if (clockTime < 0) errAbort("mktime failed (%d-%d-%d %d:%d:%d).", tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); freez(&tm); return clockTime; } char *sqlUnixTimeToDate(time_t *timep, boolean gmTime) /* Convert a clock time (seconds since 1970-01-01 00:00:00 unix epoch) * to the string: "YYYY-MM-DD HH:MM:SS" * returned string is malloced, can be freed after use * boolean gmTime requests GMT time instead of local time */ { struct tm *tm; char *ret; if (gmTime) tm = gmtime(timep); else tm = localtime(timep); ret = (char *)needMem(25*sizeof(char)); /* 25 is good for a billion years */ safef(ret, 25*sizeof(char), "%d-%02d-%02d %02d:%02d:%02d", 1900+tm->tm_year, 1+tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); return(ret); } static int getUpdateFieldIndex(struct sqlResult *sr) /* Return index of update field. * Note: does NOT work on innoDB! */ { static int updateFieldIndex = -1; if (updateFieldIndex < 0) { int ix; char *name; for (ix=0; ;++ix) { name = sqlFieldName(sr); if (name == NULL) errAbort("Can't find Update_time field in show table status result"); if (sameString("Update_time", name)) { updateFieldIndex = ix; break; } } } return updateFieldIndex; } char *sqlTableUpdate(struct sqlConnection *conn, char *table) /* Get last update time for table as an SQL string * Note: does NOT work on innoDB! */ { char query[512], **row; struct sqlResult *sr; int updateIx; char *ret; // "show table status" does not support db.table names, so temporarily change database // if table is really db.table. char *connDb = cloneString(sqlGetDatabase(conn)); char tableDb[1024]; char tableName[1024]; sqlParseDbDotTable(connDb, table, tableDb, sizeof tableDb, tableName, sizeof tableName); boolean changeDb = differentStringNullOk(connDb, tableDb); sqlSafef(query, sizeof(query), "show table status like '%s'", tableName); // the failover strategy for failoverConn does not work for this command, // as it never returns an error. So we run this on the failover server // if we have a failover connection and the table is not on the main server boolean useFailOver = conn->failoverConn && !sqlTableExistsOnMain(conn, tableName); if (useFailOver) { sqlConnectIfUnconnected(conn->failoverConn, TRUE); monitorPrintInfo(conn->failoverConn, "SQL_TABLE_STATUS_FAILOVER"); if (changeDb) sqlConnChangeDb(conn->failoverConn, tableDb, TRUE); sr = sqlGetResult(conn->failoverConn, query); } else { if (changeDb) sqlConnChangeDb(conn, tableDb, TRUE); sr = sqlGetResult(conn, query); } updateIx = getUpdateFieldIndex(sr); row = sqlNextRow(sr); if (row == NULL) errAbort("Database table %s doesn't exist", table); ret = cloneString(row[updateIx]); sqlFreeResult(&sr); if (changeDb) { if (useFailOver) sqlConnChangeDb(conn->failoverConn, connDb, TRUE); else sqlConnChangeDb(conn, connDb, TRUE); } freeMem(connDb); return ret; } time_t sqlTableUpdateTime(struct sqlConnection *conn, char *table) /* Get last update time for table. * Note: does NOT work on innoDB! */ { char *date = sqlTableUpdate(conn, table); time_t time = sqlDateToUnixTime(date); freeMem(date); return time; } static char *sqlTablePropertyFromSchema(struct sqlConnection *conn, char *db, char *table, char *field) /* Get table property. Table must exist or will abort. */ { char query[512], **row; struct sqlResult *sr; char *ret; char tableDb[1024]; char tableName[1024]; sqlParseDbDotTable(db, table, tableDb, sizeof tableDb, tableName, sizeof tableName); sqlSafef(query, sizeof(query), "SELECT %s FROM information_schema.TABLES" " WHERE TABLE_SCHEMA = '%s' AND TABLE_NAME = '%s'", field, tableDb, tableName); // the failover strategy for failoverConn does not work for this command, // as it never returns an error. So we run this on the failover server // if we have a failover connection and the table is not on the main server if (conn->failoverConn && !sqlTableExistsOnMain(conn, tableName)) { sqlConnectIfUnconnected(conn->failoverConn, TRUE); monitorPrintInfo(conn->failoverConn, "SQL_TABLE_STATUS_FAILOVER"); sr = sqlGetResult(conn->failoverConn, query); } else sr = sqlGetResult(conn, query); row = sqlNextRow(sr); if (row == NULL) errAbort("Database table %s or field %s doesn't exist", table, field); ret = cloneString(row[0]); sqlFreeResult(&sr); return ret; } unsigned long sqlTableDataSizeFromSchema(struct sqlConnection *conn, char *db, char *table) /* Get table data size. Table must exist or will abort. */ { char *sizeString = sqlTablePropertyFromSchema(conn, db, table, "data_length"); return sqlUnsignedLong(sizeString); } unsigned long sqlTableIndexSizeFromSchema(struct sqlConnection *conn, char *db, char *table) /* Get table index size. Table must exist or will abort. */ { char *sizeString = sqlTablePropertyFromSchema(conn, db, table, "index_length"); return sqlUnsignedLong(sizeString); } char *sqlGetPrimaryKey(struct sqlConnection *conn, char *table) /* Get primary key if any for table, return NULL if none. */ { struct sqlResult *sr; char **row; char *key = NULL; sr = sqlDescribe(conn, table); while ((row = sqlNextRow(sr)) != NULL) { if (sameWord(row[3], "PRI")) { key = cloneString(row[0]); break; } } sqlFreeResult(&sr); return key; } char *sqlVersion(struct sqlConnection *conn) /* Return version of MySQL database. This will be something * of the form 5.0.18-standard. */ { char query[64]; char **row; sqlSafef(query, sizeof query, "show variables like 'version'"); struct sqlResult *sr = sqlGetResult(conn, query); char *version = NULL; if ((row = sqlNextRow(sr)) != NULL) version = cloneString(row[1]); else errAbort("No mySQL version var."); sqlFreeResult(&sr); return version; } int sqlMajorVersion(struct sqlConnection *conn) /* Return major version of database. */ { char *s = sqlVersion(conn); int ver; if (!isdigit(s[0])) errAbort("Unexpected format in version: %s", s); ver = atoi(s); /* NOT sqlUnsigned please! */ freeMem(s); return ver; } int sqlMinorVersion(struct sqlConnection *conn) /* Return minor version of database. */ { char *s = sqlVersion(conn); char *words[5]; int ver; chopString(s, ".", words, ArraySize(words)); if (!isdigit(*words[1])) errAbort("Unexpected format in version: %s", s); ver = atoi(words[1]); /* NOT sqlUnsigned please! */ freeMem(s); return ver; } char** sqlGetEnumDef(struct sqlConnection *conn, char* table, char* colName) /* Get the definitions of a enum column in a table, returning a * null-terminated array of enum values. Free array when finished. */ { static char *enumPrefix = "enum("; struct sqlResult *sr; char **row; char *defStr, *defStrCp; int numValues, i; char **enumDef; /* get enum definition */ sr = sqlDescribe(conn, table); while (((row = sqlNextRow(sr)) != NULL) && !sameString(row[0], colName)) continue; if (row == NULL) errAbort("can't find column %s in DESCRIBE of %s", colName, table); /* parse definition in the form: * enum('unpicked','candidate',... ,'cantSequence') */ if (!startsWith(enumPrefix, row[1])) errAbort("%s column %s isn't an enum: %s", table, colName, row[1]); defStr = row[1] + strlen(enumPrefix); /* build char** array with string space in same block */ numValues = chopString(defStr, ",", NULL, 0); enumDef = needMem(((numValues+1) * sizeof (char**)) + strlen(defStr)+1); defStrCp = ((char*)enumDef) + ((numValues+1) * sizeof (char**)); strcpy(defStrCp, defStr); chopString(defStrCp, ",", enumDef, numValues); /* remove quotes */ for (i = 0; enumDef[i] != NULL; i++) { int len = strlen(enumDef[i]); if (enumDef[i+1] == NULL) len--; /* last entry hash close paren */ if ((enumDef[i][0] != '\'') || (enumDef[i][len-1] != '\'')) errAbort("can't find quotes in %s column %s enum value: %s", table, colName, enumDef[i]); enumDef[i][len-1] = '\0'; enumDef[i]++; } sqlFreeResult(&sr); return enumDef; } struct slName *sqlRandomSampleWithSeedConn(struct sqlConnection *conn, char *table, char *field, int count, int seed) /* Get random sample from database specifiying rand number seed, or -1 for none */ { char query[256], **row; struct sqlResult *sr; struct slName *list = NULL, *el; char seedString[256] = ""; /* The randomized-order, distinct-ing query can take a very long time on * very large tables. So create a smaller temporary table and use that. * The temporary table is visible only to the current connection, so * doesn't have to be very uniquely named, and will disappear when the * connection is closed. */ /* check if table has 'db.' prefix in it */ char *plainTable = strrchr(table, '.'); if (plainTable) plainTable++; else plainTable = table; sqlSafef(query, sizeof(query), "create temporary table hgTemp.tmp%s select %s from %s limit 100000", plainTable, field, table); sqlUpdate(conn, query); if (seed != -1) safef(seedString,sizeof(seedString),"%d",seed); sqlSafef(query, sizeof(query), "select distinct %s from hgTemp.tmp%s " "order by rand(%s) limit %d", field, plainTable, seedString, count); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { el = slNameNew(row[0]); slAddHead(&list, el); } sqlFreeResult(&sr); return list; } struct slName *sqlRandomSampleWithSeed(char *db, char *table, char *field, int count, int seed) /* Get random sample from database specifiying rand number seed, or -1 for none */ { struct sqlConnection *conn = sqlConnect(db); return sqlRandomSampleWithSeedConn(conn, table, field, count, seed); sqlDisconnect(&conn); } struct slName *sqlRandomSampleConn(struct sqlConnection *conn, char *table, char *field, int count) /* Get random sample from conn. */ { return sqlRandomSampleWithSeedConn(conn, table, field, count, -1); } struct slName *sqlRandomSample(char *db, char *table, char *field, int count) /* Get random sample from database. */ { return sqlRandomSampleWithSeed(db, table, field, count, -1); } bool sqlCanCreateTemp(struct sqlConnection *conn) /* Return True if it looks like we can write temp tables into the current database * Can be used to check if sqlRandomSampleWithSeed-functions are safe to call. * */ { // assume we can write if the current connection has no failOver connection if (conn->failoverConn==NULL) { return TRUE; } char *err; unsigned int errNo; // try a create temp query char *query = "CREATE TEMPORARY TABLE testTemp (number INT); DROP TABLE testTemp;"; struct sqlResult *sr = sqlGetResultExt(conn, query, &errNo, &err); if (sr==NULL) { return FALSE; } sqlFreeResult(&sr); return TRUE; } static struct sqlFieldInfo *sqlFieldInfoParse(char **row) /* parse a row into a sqlFieldInfo object */ { struct sqlFieldInfo *fi; AllocVar(fi); fi->field = cloneString(row[0]); fi->type = cloneString(row[1]); fi->allowsNull = sameString(row[2], "YES"); fi->key = cloneString(row[3]); fi->defaultVal = cloneString(row[4]); fi->extra = cloneString(row[5]); return fi; } struct sqlFieldInfo *sqlFieldInfoGet(struct sqlConnection *conn, char *table) /* get a list of objects describing the fields of a table */ { char query[512]; struct sqlResult *sr; char **row; struct sqlFieldInfo *fiList = NULL; sqlSafef(query, sizeof(query), "SHOW COLUMNS FROM %s", table); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) slSafeAddHead(&fiList, sqlFieldInfoParse(row)); sqlFreeResult(&sr); slReverse(&fiList); return fiList; } static void sqlFieldInfoFree(struct sqlFieldInfo **fiPtr) /* Free a sqlFieldInfo object */ { struct sqlFieldInfo *fi = *fiPtr; if (fi != NULL) { freeMem(fi->field); freeMem(fi->type); freeMem(fi->key); freeMem(fi->defaultVal); freeMem(fi->extra); freeMem(fi); *fiPtr = NULL; } } void sqlFieldInfoFreeList(struct sqlFieldInfo **fiListPtr) /* Free a list of sqlFieldInfo objects */ { struct sqlFieldInfo *fi; while ((fi = slPopHead(fiListPtr)) != NULL) sqlFieldInfoFree(&fi); } void *sqlVaQueryObjs(struct sqlConnection *conn, sqlLoadFunc loadFunc, unsigned opts, char *queryFmt, va_list args) /* Generate a query from format and args. Load one or more objects from rows * using loadFunc. Check the number of rows returned against the sqlQueryOpts * bit set. Designed for use with autoSql, although load function must be * cast to sqlLoadFunc. */ { char query[1024]; struct slList *objs = NULL; struct sqlResult *sr; char **row; vaSqlSafef(query, sizeof(query), queryFmt, args); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { slSafeAddHead(&objs, loadFunc(row)); } sqlFreeResult(&sr); slReverse(&objs); /* check what we got against the options */ if (objs == NULL) { if (opts & sqlQueryMust) errAbort("no results return from query: %s", query); } else if ((opts & sqlQuerySingle) && (objs->next != NULL)) errAbort("one results, got %d, from query: %s", slCount(objs), query); return objs; } /* Generate a query from format and args. Load one or more objects from rows * using loadFunc. Check the number of rows returned against the sqlQueryOpts * bit set. */ void *sqlQueryObjs(struct sqlConnection *conn, sqlLoadFunc loadFunc, unsigned opts, char *queryFmt, ...) /* Generate a query from format and args. Load one or more objects from rows * using loadFunc. Check the number of rows returned against the sqlQueryOpts * bit set. Designed for use with autoSql, although load function must be * cast to sqlLoadFunc. */ { struct slList *objs = NULL; va_list args; va_start(args, queryFmt); objs = sqlVaQueryObjs(conn, loadFunc, opts, queryFmt, args); va_end(args); return objs; } int sqlSaveQuery(struct sqlConnection *conn, char *query, char *outPath, boolean isFa) /* Execute query, save the resultset as a tab-separated file. * If isFa is true, than assume it is a two column fasta query and format accordingly. * Return count of rows in result set. Abort on error. */ { struct sqlResult *sr; char **row; char *sep=""; int c = 0; int count = 0; int numCols = 0; FILE *f = mustOpen(outPath,"w"); sr = sqlGetResult(conn, query); numCols = sqlCountColumns(sr); while ((row = sqlNextRow(sr)) != NULL) { sep=""; if (isFa) sep = ">"; for (c=0;c<numCols;++c) { fprintf(f,"%s%s",sep,row[c]); sep = "\t"; if (isFa) sep = "\n"; } fprintf(f,"\n"); ++count; } sqlFreeResult(&sr); carefulClose(&f); return count; } char *sqlTempTableName(struct sqlConnection *conn, char *prefix) /* Return a name for a temporary table. Name will start with * prefix. This call doesn't actually make table. (So you should * make table before next call to insure uniqueness.) However the * table name encorperates the host, pid, and time, which helps insure * uniqueness between different processes at least. FreeMem the result * when you are done. */ { int i; char tableName[PATH_LEN]; for (i=0; ;i++) { char *x = semiUniqName(prefix); safef(tableName, sizeof(tableName), "%s%d", x, i); if (!sqlTableExists(conn, tableName)) break; } return cloneString(tableName); } void sqlSetParanoid(boolean beParanoid) /* If set to TRUE, will make more diagnostic stderr messages. */ { sqlParanoid = beParanoid; } boolean sqlIsRemote(struct sqlConnection *conn) /* test if the conn appears to be to a remote system. * Current only tests for a TCP/IP connection */ { return (conn->conn->unix_socket == NULL); } static void sqlDumpProfile(struct sqlProfile *sp, FILE *fh) /* dump one db profile */ { fprintf(fh, "profile: %s host: %s user: %s dbs:", sp->name, sp->host, sp->user); struct slName *db; for (db = sp->dbs; db != NULL; db = db->next) fprintf(fh, " %s", db->name); fputc('\n', fh); } static void sqlDumpConnection(struct sqlConnection *conn, FILE *fh) /* dump an sql connection for debugging */ { fprintf(fh, "conn: profile: %s host: %s db: %s results: %d", conn->profile->name, conn->conn->host, conn->conn->db, dlCount(conn->resultList)); if (conn->hasHardLock) fputs(" hardLocked", fh); if (conn->inCache) fputs(" cached", fh); if (conn->isFree) fputs(" free", fh); fputc('\n', fh); } void sqlDump(FILE *fh) /* dump internal info about SQL configuration for debugging purposes */ { static char *dashes = "--------------------------------------------------------"; fprintf(fh, "%s\n", dashes); fprintf(fh, "defaultProfile=%s\n", (defaultProfile != NULL) ? defaultProfile->name : "NULL"); struct hashCookie cookie = hashFirst(profiles); struct hashEl *hel; while((hel = hashNext(&cookie)) != NULL) sqlDumpProfile(hel->val, fh); cookie = hashFirst(dbToProfile); while((hel = hashNext(&cookie)) != NULL) fprintf(fh, "db: %s profile: %s\n", hel->name, ((struct sqlProfile*)hel->val)->name); struct dlNode *connNode; for (connNode = sqlOpenConnections->head; !dlEnd(connNode); connNode = connNode->next) sqlDumpConnection(connNode->val, fh); fprintf(fh, "%s\n", dashes); } void sqlPrintStats(FILE *fh) /* print statistic about the number of connections and other options done by * this process. */ { fprintf(fh, "sqlStats: connects: %d maxOpen: %d\n", totalNumConnects, maxNumConnections); } /* --------- input checks to prevent sql injection --------------------------------------- */ // 0 means char is allowed // 1 means char is disallowed // although the mysql escape function can escape binary data, // we don't need to support escaping 0 for strings here. static boolean sqlCheckAllowedChars(char *s, char disAllowed[256]) /* Check each character of input against allowed character set */ { if (!s) { sqlCheckError("sqlCheckAllowedChars - Cannot check NULL"); return FALSE; } char *sOriginal = s; unsigned char c; while((c = *s++) != 0) { if (disAllowed[c]) { // just using this as a work-around // until the problem with early errors and warn/abort stacks has been fixed. char *noSqlInjLevel = cfgOptionDefault("noSqlInj.level", "abort"); if (!sameString(noSqlInjLevel, "ignore")) { fprintf(stderr, "character %c disallowed in sql string part %s\n", c, sOriginal); fflush(stderr); } return FALSE; } } return TRUE; } static void sqlCheckDisallowAllChars(char disAllowed[256]) /* Disallow all chars by setting to 1 */ { int i; for(i=0;i<256;++i) disAllowed[i] = 1; } static void sqlCheckAllowLowerChars(char allowed[256]) /* Allow lower case chars by setting to 0 */ { unsigned char c; for(c='a';c<='z';++c) allowed[c] = 0; } static void sqlCheckAllowUpperChars(char allowed[256]) /* Allow upper case chars by setting to 0 */ { unsigned char c; for(c='A';c<='Z';++c) allowed[c] = 0; } static void sqlCheckAllowDigitChars(char allowed[256]) /* Allow digit chars by setting to 0 */ { unsigned char c; for(c='0';c<='9';++c) allowed[c] = 0; } static void sqlCheckAllowChar(unsigned char c, char allowed[256]) /* Allow a char by setting to 0 */ { allowed[c] = 0; } static void sqlCheckAllowAlphaChars(char allowed[256]) /* Allow all chars by setting to 0 */ { sqlCheckAllowUpperChars(allowed); sqlCheckAllowLowerChars(allowed); } static void sqlCheckAllowAlphaNumChars(char allowed[256]) /* Allow all chars by setting to 0 */ { sqlCheckAllowAlphaChars(allowed); sqlCheckAllowDigitChars(allowed); } /* Currently used 10 times in the code via define sqlCkIl. */ char *sqlCheckIdentifiersList(char *identifiers) /* Check that only valid identifier characters are used in a comma-separated list * '.' is allowed also since some code uses it in place of an actual field name. * See hgTables/bedList.c::bedSqlFieldsExceptForChrom(). */ { static boolean init = FALSE; static char allowed[256]; if (!init) { sqlCheckDisallowAllChars(allowed); sqlCheckAllowAlphaNumChars(allowed); sqlCheckAllowChar('.', allowed); sqlCheckAllowChar('_', allowed); // sqlTableExists looks like a single table check, but apparently it has become abused // to support multiple tables e.g. sqlTableExists sqlCheckAllowChar(' ', allowed); sqlCheckAllowChar(',', allowed); sqlCheckAllowChar('\'', allowed); // single quote allowed for special case fieldname is '.' // NOTE it is important for security that no other characters be allowed here init = TRUE; } if (sameString(identifiers, "*")) // exception allowed return identifiers; if (!sqlCheckAllowedChars(identifiers, allowed)) { sqlCheckError("Illegal character found in identifier list %s", identifiers); return identifiers; } // Unfortunately, just checking that the characters are legal is far from enough to ensure safety. // the comma is required. Currently aliases and tick quotes are not supported. int len = strlen(identifiers); char c = 0; int i = 0; boolean needText = TRUE; boolean spaceOk = FALSE; boolean textDone = FALSE; // Currently identifiers list must start with an identifier, no leading spaces or comma allowed. // Currently the comma must immediately follow the identifier // Currently zero or one spaces may follow the comma // List should end with an identifier. No trailing comma or space allowed. // NOTE it is important for security that commas separate values. // We do not want to support multiple words separated by spaces. while (i < len) { c = identifiers[i]; if (c == ' ') { if (!spaceOk) { sqlCheckError("Invalid Identifiers List [%s] unexpected space character", identifiers); return identifiers; } spaceOk = FALSE; } else if (c == ',') { if (needText) { sqlCheckError("Invalid Identifiers List [%s] unexpected comma character", identifiers); return identifiers; } spaceOk = TRUE; needText = TRUE; textDone = FALSE; } else // other chars are part of the identifier { if (textDone) { sqlCheckError("Invalid Identifiers List [%s] expected comma", identifiers); return identifiers; } needText = FALSE; spaceOk = FALSE; if (c == '\'') // check for '.' exception allowed { if (i+strlen("'.'") > len) { sqlCheckError("Invalid Identifiers List [%s] quoted-literal not supported", identifiers); return identifiers; } if (identifiers[i+1] != '.') // next char must be a period { sqlCheckError("Invalid Identifiers List [%s] quoted-literal not supported", identifiers); return identifiers; } if (identifiers[i+2] != '\'') // next char must be a single-quote { sqlCheckError("Invalid Identifiers List [%s] quoted-literal not supported", identifiers); return identifiers; } i += 2; textDone = TRUE; } } ++i; } if (needText || spaceOk) { sqlCheckError("Invalid Identifiers List [%s] unexpected trailing comma or space character", identifiers); return identifiers; } return identifiers; } char *sqlCheckIdentifier(char *identifier) /* Check that only valid identifier characters are used */ { static boolean init = FALSE; static char allowed[256]; if (!init) { sqlCheckDisallowAllChars(allowed); sqlCheckAllowAlphaNumChars(allowed); sqlCheckAllowChar('.', allowed); sqlCheckAllowChar('_', allowed); // NOTE it is important for security that no other characters be allowed here init = TRUE; } /* A good idea but code is currently using empty in table names at least. See src/hg/lib/gtexTissue.c: select * from gtexTissue%s order by id This could be re-worked someday, but not now. refs #22596 if (identifier[0] == 0) // empty string not allowed since this is usually caused by an error. { sqlCheckError("Illegal empty string identifier not allowed."); } */ if (!sqlCheckAllowedChars(identifier, allowed)) { sqlCheckError("Illegal character found in identifier %s", identifier); } return identifier; } /* --------------------------- */ int sqlEscapeAllStrings(char *buffer, char *s, int bufSize, char escPunc) /* Escape all strings demarked by escPunc char. * * Returns final size not including terminating 0. * User needs to pre-allocate enough space that mysql_escape will never run out of space. * This function should be efficient on statements with many strings to be escaped. */ { char *sOrig = s; int sz = 0; int remainder = bufSize; boolean done = FALSE; while (1) { char *start = strchr(s, escPunc); char *end = NULL; if (start) { end = strchr(start+1, escPunc); // skip over punc mark if (!end) errAbort("Unexpected error in sqlEscapeAllStrings. s=[%s]", sOrig); } else { // just copy remainder of the input string to output start = strchr(s, 0); // find end of string done = TRUE; } // move any non-escaped part int moveSize = start - s; if (moveSize > remainder) errAbort("Buffer too small in sqlEscapeAllStrings. s=[%s] bufSize = %d", sOrig, bufSize); memmove(buffer, s, moveSize); buffer += moveSize; sz += moveSize; remainder -= moveSize; if (done) { if (remainder < 1) errAbort("Buffer too small for termintating zero in sqlEscapeAllStrings. s=[%s] bufSize = %d", sOrig, bufSize); --remainder; *buffer++ = 0; // terminating 0 // do not include term 0 in sz count; break; } // escape the quoted part s = start + 1; *end = 0; // mark end of "input" string, replacing escPunc. input string is temporary anyway. int inputSize = end - s; int worstCase = inputSize*2 + 1; if (worstCase > remainder) errAbort("Buffer too small for escaping in sqlEscapeAllStrings. s=[%s] bufSize = %d", sOrig, bufSize); int escSize = mysql_escape_string(buffer, s, inputSize); buffer += escSize; sz += escSize; remainder -= escSize; s = end + 1; } return sz; } int vaSqlSafefNoAbort(char* buffer, int bufSize, boolean newString, char *format, va_list args) /* VarArgs Format string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. * Scans string parameters for illegal sql chars. * Automatically escapes quoted string values. * This function should be efficient on statements with many strings to be escaped. */ { va_list orig_args; va_copy(orig_args, args); int formatLen = strlen(format); char escPunc = 0x01; // using char 1 as special char to denote strings needing escaping char *newFormat = NULL; int newFormatSize = 2*formatLen + 1; if (newString) newFormatSize += strlen(NOSQLINJ ""); newFormat = needMem(newFormatSize); char *nf = newFormat; if (newString) nf += safef(newFormat, newFormatSize, "%s", NOSQLINJ ""); char *lastPct = NULL; int escStringsCount = 0; int escStringsSize = 0; char c = 0; int i = 0; char quote = 0; boolean inPct = FALSE; boolean isLong = FALSE; boolean isLongLong = FALSE; boolean isNegated = FALSE; while (i < formatLen) { c = format[i]; *nf++ = c; // start quote if (quote==0 && (c == '\'' || c == '"' || c == '`')) quote = c; // end quote else if (c == quote) quote = 0; else if (c == '%' && !inPct) { inPct = TRUE; lastPct = nf - 1; // remember where the start was. } else if (c == '%' && inPct) inPct = FALSE; else if (inPct) { if (c == 'l') { if (isLong) isLongLong = TRUE; else isLong = TRUE; } else if (strchr("diuoxXeEfFgGpcs",c)) { inPct = FALSE; // convert to equivalent types if (c == 'i') c = 'd'; if (c == 'E') c = 'e'; if (c == 'F') c = 'f'; if (c == 'G') c = 'g'; if (c == 'o') c = 'u'; if (c == 'x') c = 'u'; if (c == 'X') c = 'u'; // we finally have the expected format // for all except s, we just want to skip it, but va_arg is the only way to do it! // signed integers if (c == 'd' && !isLong) { va_arg(args, int); } else if (c == 'd' && isLong && !isLongLong) { va_arg(args, long int); } else if (c == 'd' && isLong && isLongLong) { va_arg(args, long long int); } // unsigned integers else if (c == 'u' && !isLong) { va_arg(args, unsigned int); } else if (c == 'u' && isLong && !isLongLong) { va_arg(args, unsigned long int); } else if (c == 'u' && isLong && isLongLong) { va_arg(args, unsigned long long int); } else if (c == 'e') { va_arg(args, double); } else if (c == 'f') { va_arg(args, double); } else if (c == 'g') { va_arg(args, double); } // pointer is void * else if (c == 'p') { va_arg(args, void *); } // char get promoted to int by varargs process else if (c == 'c') { va_arg(args, int); } // finally, the string we care about! else if (c == 's') { char *s = va_arg(args, char *); if (s == NULL) sqlCheckError("%%s value is NULL which is incorrect."); if (quote == 0) { // check identifier if (!isNegated) // Not a Pre-escaped String sqlCheckIdentifier(s); } else { // check quoted literal if (!isNegated) // Not a Pre-escaped String { // go back and insert escPunc before the leading % char saved in lastPct // move the accumulated %s descriptor memmove(lastPct+1, lastPct, nf - lastPct); // this is typically very small, src and dest overlap. ++nf; *lastPct = escPunc; *nf++ = escPunc; ++escStringsCount; if (s == NULL) { escStringsSize += strlen("(null)"); } else { escStringsSize += strlen(s); // DEBUG temporary check for signs of double-escaping, can remove later for a minor speedup: if (strstr(s, "\\\\")) // this is really 2 backslashes { if (sameOk(cfgOption("noSqlInj.dumpStack"), "on")) dumpStack("potential sign of double sql-escaping in string [%s]", s); } } } } } else { errAbort("unexpected error processing vaSqlSafef, format: %s", format); } isLong = FALSE; isLongLong = FALSE; isNegated = FALSE; } else if (strchr("+-.1234567890",c)) { if (c == '-') isNegated = TRUE; } else errAbort("string format not understood in vaSqlSafef: %s", format); } ++i; } int sz = 0; if (escStringsCount > 0) { int tempSize = bufSize + 2*escStringsCount; // if it won't fit in this it will never fit. char *tempBuf = needMem(tempSize); sz = vsnprintf(tempBuf, tempSize, newFormat, orig_args); /* note that some versions return -1 if too small */ if (sz != -1 && sz + 1 <= tempSize) { // unfortunately we have to copy the string 1 more time unless we want // to force the user to allocate extra "safety space" for mysql_escape. int tempSize2 = sz + 1 + escStringsSize; // handle worst-case char *tempBuf2 = needMem(tempSize2); sz = sqlEscapeAllStrings(tempBuf2, tempBuf, tempSize2, escPunc); if (sz + 1 > tempSize2) errAbort("unexpected error in vaSqlSafefNoAbort: tempBuf2 overflowed. tempSize2=%d sz=%d", tempSize, sz); if (sz + 1 <= bufSize) // NO buffer overflow { // copy string to its final destination. memmove(buffer, tempBuf2, sz+1); // +1 for terminating 0; } freeMem(tempBuf2); } freeMem(tempBuf); } else { sz = vsnprintf(buffer, bufSize, newFormat, orig_args); /* note that some version return -1 if too small */ } freeMem(newFormat); va_end(orig_args); return sz; } int vaSqlSafef(char* buffer, int bufSize, char *format, va_list args) /* VarArgs Format string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. */ { int sz = vaSqlSafefNoAbort(buffer, bufSize, TRUE, format, args); if ((sz < 0) || (sz >= bufSize)) { buffer[bufSize-1] = (char) 0; errAbort("buffer overflow, size %d, format: %s, buffer: '%s'", bufSize, format, buffer); } return sz; } int sqlSafef(char* buffer, int bufSize, char *format, ...) /* Format string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. * Scans unquoted string parameters for illegal literal sql chars. * Escapes quoted string parameters. * NOSLQINJ tag is added to beginning. */ { int sz; va_list args; va_start(args, format); sz = vaSqlSafef(buffer, bufSize, format, args); va_end(args); return sz; } int vaSqlSafefFrag(char* buffer, int bufSize, char *format, va_list args) /* VarArgs Format string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. * Scans unquoted string parameters for illegal literal sql chars. * Escapes quoted string parameters. * NOSLQINJ tag is NOT added to beginning since it is assumed to be just a fragment of * the entire sql string. */ { int sz = vaSqlSafefNoAbort(buffer, bufSize, FALSE, format, args); if ((sz < 0) || (sz >= bufSize)) { buffer[bufSize-1] = (char) 0; errAbort("buffer overflow, size %d, format: %s, buffer: '%s'", bufSize, format, buffer); } return sz; } int sqlSafefFrag(char* buffer, int bufSize, char *format, ...) /* Format string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. * Scans unquoted string parameters for illegal literal sql chars. * Escapes quoted string parameters. * NOSLQINJ tag is NOT added to beginning since it is assumed to be just a fragment of * the entire sql string. */ { int sz; va_list args; va_start(args, format); sz = vaSqlSafefFrag(buffer, bufSize, format, args); va_end(args); return sz; } int sqlSafefAppend(char* buffer, int bufSize, char *format, ...) /* Append formatted string to buffer, vsprintf style, only with buffer overflow * checking. The resulting string is always terminated with zero byte. * Scans unquoted string parameters for illegal literal sql chars. * Escapes quoted string parameters. * NOSLQINJ tag is NOT added to beginning since it is assumed to be appended to * a properly created sql string. */ { int sz; va_list args; int len = strlen(buffer); if (len >= bufSize) errAbort("sqlSafefAppend() called on string size %d with bufSize %d too small.", len, bufSize); va_start(args, format); sz = vaSqlSafefFrag(buffer+len, bufSize-len, format, args); va_end(args); return sz; } /* --------------------------- */ void vaSqlDyStringPrintfExt(struct dyString *ds, boolean isFrag, char *format, va_list args) /* VarArgs Printf to end of dyString after scanning string parameters for illegal sql chars. * Strings inside quotes are automatically escaped. * NOSLQINJ tag is added to beginning if it is a new empty string and isFrag is FALSE. */ { /* attempt to format the string in the current space. If there * is not enough room, increase the buffer size and try again */ int avail, sz; while (TRUE) { va_list argscp; va_copy(argscp, args); avail = ds->bufSize - ds->stringSize; if (avail <= 0) { /* Don't pass zero sized buffers to vsnprintf, because who knows * if the library function will handle it. */ dyStringBumpBufSize(ds, ds->bufSize+ds->bufSize); avail = ds->bufSize - ds->stringSize; } sz = vaSqlSafefNoAbort(ds->string + ds->stringSize, avail, ds->stringSize==0 && !isFrag, format, argscp); va_end(argscp); /* note that some version return -1 if too small */ if ((sz < 0) || (sz >= avail)) { dyStringBumpBufSize(ds, ds->bufSize+ds->bufSize); } else { ds->stringSize += sz; break; } } } void vaSqlDyStringPrintf(struct dyString *ds, char *format, va_list args) /* VarArgs Printf to end of dyString after scanning string parameters for illegal sql chars. * Strings inside quotes are automatically escaped. * NOSLQINJ tag is added to beginning if it is a new empty string. * Appends to existing string. */ { vaSqlDyStringPrintfExt(ds, FALSE, format, args); } void sqlDyStringPrintf(struct dyString *ds, char *format, ...) /* Printf to end of dyString after scanning string parameters for illegal sql chars. * Strings inside quotes are automatically escaped. * NOSLQINJ tag is added to beginning if it is a new empty string. * Appends to existing string. */ { va_list args; va_start(args, format); vaSqlDyStringPrintf(ds, format, args); va_end(args); } void vaSqlDyStringPrintfFrag(struct dyString *ds, char *format, va_list args) /* VarArgs Printf to end of dyString after scanning string parameters for illegal sql chars. * Strings inside quotes are automatically escaped. * NOSLQINJ tag is NOT added to beginning since it is assumed to be just a fragment of * the entire sql string. Appends to existing string. */ { vaSqlDyStringPrintfExt(ds, TRUE, format, args); } void sqlDyStringPrintfFrag(struct dyString *ds, char *format, ...) /* Printf to end of dyString after scanning string parameters for illegal sql chars. * Strings inside quotes are automatically escaped. * NOSLQINJ tag is NOT added to beginning since it is assumed to be just a fragment of * the entire sql string. Appends to existing string. */ { va_list args; va_start(args, format); vaSqlDyStringPrintfFrag(ds, format, args); va_end(args); } struct dyString *sqlDyStringCreate(char *format, ...) /* Create a dyString with a printf style initial content * Adds the NOSQLINJ prefix. */ { int len = strlen(format) * 3; struct dyString *ds = newDyString(len); va_list args; va_start(args, format); vaSqlDyStringPrintf(ds, format, args); va_end(args); return ds; } void sqlDyStringPrintIdList(struct dyString *ds, char *fields) /* Append a comma-separated list of field identifiers. Aborts if invalid characters in list. */ { sqlDyStringPrintf(ds, "%-s", sqlCkIl(fields)); } void sqlDyStringPrintValuesList(struct dyString *ds, struct slName *list) /* Append a comma-separated, quoted and escaped list of values. */ { struct slName *el; for (el = list; el != NULL; el = el->next) { if (el != list) sqlDyStringPrintf(ds, ","); sqlDyStringPrintf(ds, "'%s'", el->name); } } void sqlCheckError(char *format, ...) /* A sql injection error has occurred. Check for settings and respond * as appropriate with error, warning, logOnly, ignore, dumpstack. * Then abort if needed. NOTE: unless it aborts, this function will return! */ { va_list args; va_start(args, format); char *noSqlInjLevel = cfgOptionDefault("noSqlInj.level", "abort"); char *noSqlInjDumpStack = cfgOption("noSqlInj.dumpStack"); if (sameOk(noSqlInjDumpStack, "on")) { va_list dump_args; va_copy(dump_args, args); vaDumpStack(format, dump_args); va_end(dump_args); } if (sameString(noSqlInjLevel, "logOnly")) { vfprintf(stderr, format, args); fprintf(stderr, "\n"); fflush(stderr); } if (sameString(noSqlInjLevel, "warn")) { vaWarn(format, args); } if (sameString(noSqlInjLevel, "abort")) { vaErrAbort(format, args); } va_end(args); } /* functions moved here from hgTables.c 2019-04-04 - Hiram */ struct sqlFieldType *sqlFieldTypeNew(char *name, char *type) /* Create a new sqlFieldType */ { struct sqlFieldType *ft; AllocVar(ft); ft->name = cloneString(name); ft->type = cloneString(type); return ft; } void sqlFieldTypeFree(struct sqlFieldType **pFt) /* Free resources used by sqlFieldType */ { struct sqlFieldType *ft = *pFt; if (ft != NULL) { freeMem(ft->name); freeMem(ft->type); freez(pFt); } } void sqlFieldTypeFreeList(struct sqlFieldType **pList) /* Free a list of dynamically allocated sqlFieldType's */ { struct sqlFieldType *el, *next; for (el = *pList; el != NULL; el = next) { next = el->next; sqlFieldTypeFree(&el); } *pList = NULL; } struct sqlFieldType *sqlFieldTypesFromAs(struct asObject *as) /* Convert asObject to list of sqlFieldTypes */ { struct sqlFieldType *ft, *list = NULL; struct asColumn *col; for (col = as->columnList; col != NULL; col = col->next) { struct dyString *type = asColumnToSqlType(col); ft = sqlFieldTypeNew(col->name, type->string); slAddHead(&list, ft); dyStringFree(&type); } slReverse(&list); return list; } struct sqlFieldType *sqlListFieldsAndTypes(struct sqlConnection *conn, char *table) /* Get list of fields including their names and types. The type currently is * just a MySQL type string. */ { struct sqlFieldType *ft, *list = NULL; char query[512]; struct sqlResult *sr; char **row; sqlSafef(query, sizeof(query), "describe %s", table); sr = sqlGetResult(conn, query); while ((row = sqlNextRow(sr)) != NULL) { ft = sqlFieldTypeNew(row[0], row[1]); slAddHead(&list, ft); } sqlFreeResult(&sr); slReverse(&list); return list; }
mit
sndnvaps/lk
dev/usb/usb.c
2
13052
/* * Copyright (c) 2008-2015 Travis Geiselbrecht * * 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 <debug.h> #include <trace.h> #include <err.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <list.h> #include <dev/usbc.h> #include <dev/usb.h> #include <lk/init.h> #define LOCAL_TRACE 0 #define MAX_STRINGS 8 static struct { bool active; uint8_t active_config; usb_config *config; struct list_node cb_list; usb_string strings[MAX_STRINGS]; } usb; typedef struct { struct list_node node; usb_callback_t cb; void *cookie; } usb_callback_container_t; static void usb_do_callbacks(usb_callback_op_t op, const union usb_callback_args *args); static void append_desc_data(usb_descriptor *desc, const void *dat, size_t len) { uint8_t *ptr = malloc(desc->len + len); memcpy(ptr, desc->desc, desc->len); memcpy(ptr + desc->len, dat, len); /* free the old buffer if it wasn't marked static */ if ((desc->flags & USB_DESC_FLAG_STATIC) == 0) free(desc->desc); desc->flags &= ~USB_DESC_FLAG_STATIC; desc->desc = ptr; desc->len += len; } /* returns the interface number assigned */ static int usb_append_interface(usb_descriptor *desc, const uint8_t *int_descr, size_t len) { uint8_t *ptr = malloc(len); int interface_num; // create a temporary copy of the interface memcpy(ptr, int_descr, len); // find the last interface used interface_num = ((uint8_t *)desc->desc)[4]; // current interface // patch our interface descriptor with the new id ptr[2] = interface_num; // append it to our config desriptor append_desc_data(desc, ptr, len); free(ptr); // patch the total length of the config descriptor and set the number of interfaces ((uint16_t *)desc->desc)[1] += len; interface_num++; ((uint8_t *)desc->desc)[4] = interface_num; return interface_num - 1; } int usb_append_interface_highspeed(const uint8_t *int_descr, size_t len) { return usb_append_interface(&usb.config->highspeed.config, int_descr, len); } int usb_append_interface_lowspeed(const uint8_t *int_descr, size_t len) { return usb_append_interface(&usb.config->lowspeed.config, int_descr, len); } void usb_set_string_descriptor(usb_descriptor *desc, const char *string) { int len = strlen(string); ushort *data; int datalen = len * 2 + 2; data = malloc(datalen); /* write length field */ data[0] = 0x0300 + datalen; /* copy the string into the uint16_t based usb string */ int i; for (i = 0; i < len; i++) { data[i + 1] = string[i]; } desc->desc = (void *)data; desc->len = datalen; } static void set_usb_id(uint16_t vendor, uint16_t product) { // patch the current configuration to with the vendor/product id ((uint16_t *)usb.config->lowspeed.device.desc)[4] = vendor; ((uint16_t *)usb.config->lowspeed.device.desc)[5] = product; ((uint16_t *)usb.config->highspeed.device.desc)[4] = vendor; ((uint16_t *)usb.config->highspeed.device.desc)[5] = product; } status_t usb_add_string(const char *string, uint8_t id) { uint i; size_t len = strlen(string); uint16_t *strbuf = malloc(len * 2 + 2); if (!strbuf) return ERR_NO_MEMORY; /* build the usb string descriptor */ strbuf[0] = 0x300 | (len * 2 + 2); for (i = 0; i < len; i++) { strbuf[i + 1] = (uint16_t)string[i]; } /* find a slot to put it */ for (i = 0; i < MAX_STRINGS; i++) { if (usb.strings[i].id == 0) { usb.strings[i].string.desc = strbuf; usb.strings[i].string.len = len * 2 + 2; usb.strings[i].id = id; return NO_ERROR; } } /* couldn't find a spot */ free(strbuf); return ERR_NO_MEMORY; } static void usb_set_active_config(uint8_t config) { if (config != usb.active_config) { usb.active_config = config; if (usb.active_config != 0) { printf("usb online\n"); usb_do_callbacks(USB_CB_ONLINE, NULL); } else { printf("usb offline\n"); usb_do_callbacks(USB_CB_OFFLINE, NULL); } } } status_t usb_register_callback(usb_callback_t cb, void *cookie) { DEBUG_ASSERT(cb); usb_callback_container_t *c = malloc(sizeof(usb_callback_container_t)); if (!c) return ERR_NO_MEMORY; c->cb = cb; c->cookie = cookie; list_add_tail(&usb.cb_list, &c->node); return NO_ERROR; } static void usb_do_callbacks(usb_callback_op_t op, const union usb_callback_args *args) { usb_callback_container_t *c; list_for_every_entry(&usb.cb_list, c, usb_callback_container_t, node) { c->cb(c->cookie, op, args); } } status_t usbc_callback(usb_callback_op_t op, const union usb_callback_args *args) { LTRACEF("op %d, args %p\n", op, args); /* start looking for specific things to handle */ if (op == USB_CB_SETUP_MSG) { bool setup_handled = false; const struct usb_setup *setup = args->setup; DEBUG_ASSERT(setup); LTRACEF("SETUP: req_type=%#x req=%#x value=%#x index=%#x len=%#x\n", setup->request_type, setup->request, setup->value, setup->index, setup->length); if ((setup->request_type & TYPE_MASK) == TYPE_STANDARD) { switch (setup->request) { case SET_ADDRESS: LTRACEF("SET_ADDRESS 0x%x\n", setup->value); usbc_ep0_ack(); usbc_set_address(setup->value); setup_handled = true; break; case SET_FEATURE: case CLEAR_FEATURE: LTRACEF("SET/CLEAR_FEATURE, feature 0x%x\n", setup->value); usbc_ep0_ack(); setup_handled = true; break; case SET_DESCRIPTOR: LTRACEF("SET_DESCRIPTOR\n"); usbc_ep0_stall(); setup_handled = true; break; case GET_DESCRIPTOR: { if ((setup->request_type & RECIP_MASK) == RECIP_DEVICE) { /* handle device descriptor fetches */ /* Get the right descriptors based on current speed */ const struct usb_descriptor_speed *speed; if (usbc_is_highspeed()) { speed = &usb.config->highspeed; } else { speed = &usb.config->lowspeed; } switch (setup->value) { case 0x100: /* device */ LTRACEF("got GET_DESCRIPTOR, device descriptor\n"); usbc_ep0_send(speed->device.desc, speed->device.len, setup->length); break; case 0x200: /* CONFIGURATION */ LTRACEF("got GET_DESCRIPTOR, config descriptor\n"); usbc_ep0_send(speed->config.desc, speed->config.len, setup->length); break; case 0x300: /* Language ID */ LTRACEF("got GET_DESCRIPTOR, language id\n"); usbc_ep0_send(usb.config->langid.desc, usb.config->langid.len, setup->length); break; case (0x301)...(0x3ff): { /* string descriptor, search our list for a match */ uint i; bool found = false; uint8_t id = setup->value & 0xff; for (i = 0; i < MAX_STRINGS; i++) { if (usb.strings[i].id == id) { usbc_ep0_send(usb.strings[i].string.desc, usb.strings[i].string.len, setup->length); found = true; break; } } if (!found) { /* couldn't find one, stall */ usbc_ep0_stall(); } break; } case 0x600: /* DEVICE QUALIFIER */ LTRACEF("got GET_DESCRIPTOR, device qualifier\n"); usbc_ep0_send(speed->device_qual.desc, speed->device_qual.len, setup->length); break; case 0xa00: /* we aint got one of these */ LTRACEF("got GET_DESCRIPTOR, debug descriptor\n"); usbc_ep0_stall(); break; default: LTRACEF("unhandled descriptor %#x\n", setup->value); // stall break; } setup_handled = true; } break; } case SET_CONFIGURATION: LTRACEF("SET_CONFIGURATION %d\n", setup->value); usbc_ep0_ack(); usb_set_active_config(setup->value); break; case GET_CONFIGURATION: LTRACEF("GET_CONFIGURATION\n"); usbc_ep0_send(&usb.active_config, 1, setup->length); break; case SET_INTERFACE: LTRACEF("SET_INTERFACE %d\n", setup->value); usbc_ep0_ack(); break; case GET_INTERFACE: { static uint8_t i = 1; LTRACEF("GET_INTERFACE\n"); usbc_ep0_send(&i, 1, setup->length); break; } case GET_STATUS: { static uint16_t i = 1; // self powered LTRACEF("GET_STATUS\n"); usbc_ep0_send(&i, 2, setup->length); break; } default: LTRACEF("unhandled standard request 0x%x\n", setup->request); } } else { LTRACEF("unhandled nonstandard request 0x%x\n", setup->request); } if (!setup_handled) { usb_do_callbacks(op, args); } } else if (op == USB_CB_RESET) { usb_do_callbacks(op, args); usb.active_config = 0; usb_do_callbacks(USB_CB_OFFLINE, args); } else { // other non setup messages, pass them down to anyone else usb_do_callbacks(op, args); } return NO_ERROR; } status_t usb_setup(usb_config *config) { DEBUG_ASSERT(config); DEBUG_ASSERT(usb.active == false); usb.config = config; return NO_ERROR; } status_t usb_start(void) { DEBUG_ASSERT(usb.config); DEBUG_ASSERT(usb.active == false); // go online usbc_set_active(true); usb.active = true; return NO_ERROR; } status_t usb_stop(void) { DEBUG_ASSERT(usb.active == true); usb.active = false; usbc_set_active(false); return NO_ERROR; } static void usb_init(uint level) { list_initialize(&usb.cb_list); } LK_INIT_HOOK(usb, usb_init, LK_INIT_LEVEL_THREADING);
mit
anditto/bitcoin
src/wallet/rpc/backup.cpp
2
91317
// Copyright (c) 2009-2021 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 <chain.h> #include <clientversion.h> #include <core_io.h> #include <fs.h> #include <interfaces/chain.h> #include <key_io.h> #include <merkleblock.h> #include <rpc/util.h> #include <script/descriptor.h> #include <script/script.h> #include <script/standard.h> #include <sync.h> #include <util/bip32.h> #include <util/system.h> #include <util/time.h> #include <util/translation.h> #include <wallet/rpc/util.h> #include <wallet/wallet.h> #include <cstdint> #include <fstream> #include <tuple> #include <string> #include <univalue.h> using interfaces::FoundBlock; namespace wallet { std::string static EncodeDumpString(const std::string &str) { std::stringstream ret; for (const unsigned char c : str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr({&c, 1}); } else { ret << c; } } return ret.str(); } static std::string DecodeDumpString(const std::string &str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos+2 < str.length()) { c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) | ((str[pos+2]>>6)*9+((str[pos+2]-'0')&15)); pos += 2; } ret << c; } return ret.str(); } static bool GetWalletAddressesForKey(const LegacyScriptPubKeyMan* spk_man, const CWallet& wallet, const CKeyID& keyid, std::string& strAddr, std::string& strLabel) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { bool fLabelFound = false; CKey key; spk_man->GetKey(keyid, key); for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) { const auto* address_book_entry = wallet.FindAddressBookEntry(dest); if (address_book_entry) { if (!strAddr.empty()) { strAddr += ","; } strAddr += EncodeDestination(dest); strLabel = EncodeDumpString(address_book_entry->GetLabel()); fLabelFound = true; } } if (!fLabelFound) { strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), wallet.m_default_address_type)); } return fLabelFound; } static const int64_t TIMESTAMP_MIN = 0; static void RescanWallet(CWallet& wallet, const WalletRescanReserver& reserver, int64_t time_begin = TIMESTAMP_MIN, bool update = true) { int64_t scanned_time = wallet.RescanFromTime(time_begin, reserver, update); if (wallet.IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } else if (scanned_time > time_begin) { throw JSONRPCError(RPC_WALLET_ERROR, "Rescan was unable to fully rescan the blockchain. Some transactions may be missing."); } } RPCHelpMan importprivkey() { return RPCHelpMan{"importprivkey", "\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n" "Hint: use importmulti to import more than one private key.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", { {"privkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The private key (see dumpprivkey)"}, {"label", RPCArg::Type::STR, RPCArg::DefaultHint{"current label if address exists, otherwise \"\""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nImport using default blank label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; if (pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } EnsureLegacyScriptPubKeyMan(*pwallet, true); WalletRescanReserver reserver(*pwallet); bool fRescan = true; { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::string strSecret = request.params[0].get_str(); std::string strLabel = ""; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } CKey key = DecodeSecret(strSecret); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CPubKey pubkey = key.GetPubKey(); CHECK_NONFATAL(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwallet->MarkDirty(); // We don't know which corresponding address will be used; // label all new addresses, and label existing addresses if a // label was passed. for (const auto& dest : GetAllDestinationsForKey(pubkey)) { if (!request.params[1].isNull() || !pwallet->FindAddressBookEntry(dest)) { pwallet->SetAddressBook(dest, strLabel, "receive"); } } // Use timestamp of 1 to scan the whole chain if (!pwallet->ImportPrivKeys({{vchAddress, key}}, 1)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } // Add the wpkh script for this key if possible if (pubkey.IsCompressed()) { pwallet->ImportScripts({GetScriptForDestination(WitnessV0KeyHash(vchAddress))}, 0 /* timestamp */); } } } if (fRescan) { RescanWallet(*pwallet, reserver); } return NullUniValue; }, }; } RPCHelpMan importaddress() { return RPCHelpMan{"importaddress", "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "If you have the full public key, you should call importpubkey instead of this.\n" "Hint: use importmulti to import more than one address.\n" "\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n" "as change, and not show up in many RPCs.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The Bitcoin address (or hex-encoded script)"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"}, {"p2sh", RPCArg::Type::BOOL, RPCArg::Default{false}, "Add the P2SH version of the script as well"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; EnsureLegacyScriptPubKeyMan(*pwallet, true); std::string strLabel; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } // Whether to import a p2sh version, too bool fP2SH = false; if (!request.params[3].isNull()) fP2SH = request.params[3].get_bool(); { LOCK(pwallet->cs_wallet); CTxDestination dest = DecodeDestination(request.params[0].get_str()); if (IsValidDestination(dest)) { if (fP2SH) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead"); } if (OutputTypeFromDestination(dest) == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets"); } pwallet->MarkDirty(); pwallet->ImportScriptPubKeys(strLabel, {GetScriptForDestination(dest)}, false /* have_solving_data */, true /* apply_label */, 1 /* timestamp */); } else if (IsHex(request.params[0].get_str())) { std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); CScript redeem_script(data.begin(), data.end()); std::set<CScript> scripts = {redeem_script}; pwallet->ImportScripts(scripts, 0 /* timestamp */); if (fP2SH) { scripts.insert(GetScriptForDestination(ScriptHash(redeem_script))); } pwallet->ImportScriptPubKeys(strLabel, scripts, false /* have_solving_data */, true /* apply_label */, 1 /* timestamp */); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address or script"); } } if (fRescan) { RescanWallet(*pwallet, reserver); { LOCK(pwallet->cs_wallet); pwallet->ReacceptWalletTransactions(); } } return NullUniValue; }, }; } RPCHelpMan importprunedfunds() { return RPCHelpMan{"importprunedfunds", "\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n", { {"rawtransaction", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "A raw transaction in hex funding an already-existing address in wallet"}, {"txoutproof", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex output from gettxoutproof that contains the transaction"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{""}, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; CMutableTransaction tx; if (!DecodeHexTx(tx, request.params[0].get_str())) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed. Make sure the tx has at least one input."); } uint256 hashTx = tx.GetHash(); CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION); CMerkleBlock merkleBlock; ssMB >> merkleBlock; //Search partial merkle tree in proof for our transaction and index in valid block std::vector<uint256> vMatch; std::vector<unsigned int> vIndex; if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) != merkleBlock.header.hashMerkleRoot) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock"); } LOCK(pwallet->cs_wallet); int height; if (!pwallet->chain().findAncestorByHash(pwallet->GetLastBlockHash(), merkleBlock.header.GetHash(), FoundBlock().height(height))) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain"); } std::vector<uint256>::const_iterator it; if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx)) == vMatch.end()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof"); } unsigned int txnIndex = vIndex[it - vMatch.begin()]; CTransactionRef tx_ref = MakeTransactionRef(tx); if (pwallet->IsMine(*tx_ref)) { pwallet->AddToWallet(std::move(tx_ref), TxStateConfirmed{merkleBlock.header.GetHash(), height, static_cast<int>(txnIndex)}); return NullUniValue; } throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction"); }, }; } RPCHelpMan removeprunedfunds() { return RPCHelpMan{"removeprunedfunds", "\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n", { {"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The hex-encoded id of the transaction you are deleting"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("removeprunedfunds", "\"a8d0c0184dde994a09ec054286f1ce581bebf46446a512166eae7628734ea0a5\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; LOCK(pwallet->cs_wallet); uint256 hash(ParseHashV(request.params[0], "txid")); std::vector<uint256> vHash; vHash.push_back(hash); std::vector<uint256> vHashOut; if (pwallet->ZapSelectTx(vHash, vHashOut) != DBErrors::LOAD_OK) { throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction."); } if(vHashOut.empty()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet."); } return NullUniValue; }, }; } RPCHelpMan importpubkey() { return RPCHelpMan{"importpubkey", "\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n" "Hint: use importmulti to import more than one public key.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", { {"pubkey", RPCArg::Type::STR, RPCArg::Optional::NO, "The hex-encoded public key"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "An optional label"}, {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Rescan the wallet for transactions"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nImport a public key with rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; EnsureLegacyScriptPubKeyMan(*pwallet, true); std::string strLabel; if (!request.params[1].isNull()) strLabel = request.params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (!request.params[2].isNull()) fRescan = request.params[2].get_bool(); if (fRescan && pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled when blocks are pruned"); } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } if (!IsHex(request.params[0].get_str())) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string"); std::vector<unsigned char> data(ParseHex(request.params[0].get_str())); CPubKey pubKey(data); if (!pubKey.IsFullyValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key"); { LOCK(pwallet->cs_wallet); std::set<CScript> script_pub_keys; for (const auto& dest : GetAllDestinationsForKey(pubKey)) { script_pub_keys.insert(GetScriptForDestination(dest)); } pwallet->MarkDirty(); pwallet->ImportScriptPubKeys(strLabel, script_pub_keys, true /* have_solving_data */, true /* apply_label */, 1 /* timestamp */); pwallet->ImportPubKeys({pubKey.GetID()}, {{pubKey.GetID(), pubKey}} , {} /* key_origins */, false /* add_keypool */, false /* internal */, 1 /* timestamp */); } if (fRescan) { RescanWallet(*pwallet, reserver); { LOCK(pwallet->cs_wallet); pwallet->ReacceptWalletTransactions(); } } return NullUniValue; }, }; } RPCHelpMan importwallet() { return RPCHelpMan{"importwallet", "\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", { {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The wallet file"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; EnsureLegacyScriptPubKeyMan(*pwallet, true); if (pwallet->chain().havePruned()) { // Exit early and print an error. // If a block is pruned after this check, we will import the key(s), // but fail the rescan with a generic error. throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled when blocks are pruned"); } WalletRescanReserver reserver(*pwallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t nTimeBegin = 0; bool fGood = true; { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); std::ifstream file; file.open(fs::u8path(request.params[0].get_str()), std::ios::in | std::ios::ate); if (!file.is_open()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); } CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nTimeBegin))); int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); // Use uiInterface.ShowProgress instead of pwallet.ShowProgress because pwallet.ShowProgress has a cancel button tied to AbortRescan which // we don't want for this progress bar showing the import progress. uiInterface.ShowProgress does not have a cancel button. pwallet->chain().showProgress(strprintf("%s " + _("Importing…").translated, pwallet->GetDisplayName()), 0, false); // show progress dialog in GUI std::vector<std::tuple<CKey, int64_t, bool, std::string>> keys; std::vector<std::pair<CScript, int64_t>> scripts; while (file.good()) { pwallet->chain().showProgress("", std::max(1, std::min(50, (int)(((double)file.tellg() / (double)nFilesize) * 100))), false); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr = SplitString(line, ' '); if (vstr.size() < 2) continue; CKey key = DecodeSecret(vstr[0]); if (key.IsValid()) { int64_t nTime = ParseISO8601DateTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (vstr[nStr].front() == '#') break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (vstr[nStr].substr(0,6) == "label=") { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } keys.push_back(std::make_tuple(key, nTime, fLabel, strLabel)); } else if(IsHex(vstr[0])) { std::vector<unsigned char> vData(ParseHex(vstr[0])); CScript script = CScript(vData.begin(), vData.end()); int64_t birth_time = ParseISO8601DateTime(vstr[1]); scripts.push_back(std::pair<CScript, int64_t>(script, birth_time)); } } file.close(); // We now know whether we are importing private keys, so we can error if private keys are disabled if (keys.size() > 0 && pwallet->IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled when private keys are disabled"); } double total = (double)(keys.size() + scripts.size()); double progress = 0; for (const auto& key_tuple : keys) { pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false); const CKey& key = std::get<0>(key_tuple); int64_t time = std::get<1>(key_tuple); bool has_label = std::get<2>(key_tuple); std::string label = std::get<3>(key_tuple); CPubKey pubkey = key.GetPubKey(); CHECK_NONFATAL(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); pwallet->WalletLogPrintf("Importing %s...\n", EncodeDestination(PKHash(keyid))); if (!pwallet->ImportPrivKeys({{keyid, key}}, time)) { pwallet->WalletLogPrintf("Error importing key for %s\n", EncodeDestination(PKHash(keyid))); fGood = false; continue; } if (has_label) pwallet->SetAddressBook(PKHash(keyid), label, "receive"); nTimeBegin = std::min(nTimeBegin, time); progress++; } for (const auto& script_pair : scripts) { pwallet->chain().showProgress("", std::max(50, std::min(75, (int)((progress / total) * 100) + 50)), false); const CScript& script = script_pair.first; int64_t time = script_pair.second; if (!pwallet->ImportScripts({script}, time)) { pwallet->WalletLogPrintf("Error importing script %s\n", HexStr(script)); fGood = false; continue; } if (time > 0) { nTimeBegin = std::min(nTimeBegin, time); } progress++; } pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI } pwallet->chain().showProgress("", 100, false); // hide progress dialog in GUI RescanWallet(*pwallet, reserver, nTimeBegin, false /* update */); pwallet->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet"); return NullUniValue; }, }; } RPCHelpMan dumpprivkey() { return RPCHelpMan{"dumpprivkey", "\nReveals the private key corresponding to 'address'.\n" "Then the importprivkey can be used with this output\n", { {"address", RPCArg::Type::STR, RPCArg::Optional::NO, "The bitcoin address for the private key"}, }, RPCResult{ RPCResult::Type::STR, "key", "The private key" }, RPCExamples{ HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(*pwallet); LOCK2(pwallet->cs_wallet, spk_man.cs_KeyStore); EnsureWalletIsUnlocked(*pwallet); std::string strAddress = request.params[0].get_str(); CTxDestination dest = DecodeDestination(strAddress); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); } auto keyid = GetKeyForDestination(spk_man, dest); if (keyid.IsNull()) { throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); } CKey vchSecret; if (!spk_man.GetKey(keyid, vchSecret)) { throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); } return EncodeSecret(vchSecret); }, }; } RPCHelpMan dumpwallet() { return RPCHelpMan{"dumpwallet", "\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n" "Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n" "Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n" "only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n", { {"filename", RPCArg::Type::STR, RPCArg::Optional::NO, "The filename with path (absolute path recommended)"}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "filename", "The filename with full absolute path"}, } }, RPCExamples{ HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; const CWallet& wallet = *pwallet; const LegacyScriptPubKeyMan& spk_man = EnsureConstLegacyScriptPubKeyMan(wallet); // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); LOCK(wallet.cs_wallet); EnsureWalletIsUnlocked(wallet); fs::path filepath = fs::u8path(request.params[0].get_str()); filepath = fs::absolute(filepath); /* Prevent arbitrary files from being overwritten. There have been reports * that users have overwritten wallet files this way: * https://github.com/bitcoin/bitcoin/issues/9934 * It may also avoid other security issues. */ if (fs::exists(filepath)) { throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.u8string() + " already exists. If you are sure this is what you want, move it out of the way first"); } std::ofstream file; file.open(filepath); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; wallet.GetKeyBirthTimes(mapKeyBirth); int64_t block_time = 0; CHECK_NONFATAL(wallet.chain().findBlock(wallet.GetLastBlockHash(), FoundBlock().time(block_time))); // Note: To avoid a lock order issue, access to cs_main must be locked before cs_KeyStore. // So we do the two things in this function that lock cs_main first: GetKeyBirthTimes, and findBlock. LOCK(spk_man.cs_KeyStore); const std::map<CKeyID, int64_t>& mapKeyPool = spk_man.GetAllReserveKeys(); std::set<CScriptID> scripts = spk_man.GetCScripts(); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (const auto& entry : mapKeyBirth) { vKeyBirth.push_back(std::make_pair(entry.second, entry.first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by %s %s\n", PACKAGE_NAME, FormatFullVersion()); file << strprintf("# * Created on %s\n", FormatISO8601DateTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", wallet.GetLastBlockHeight(), wallet.GetLastBlockHash().ToString()); file << strprintf("# mined on %s\n", FormatISO8601DateTime(block_time)); file << "\n"; // add the base58check encoded extended master if the wallet uses HD CKeyID seed_id = spk_man.GetHDChain().seed_id; if (!seed_id.IsNull()) { CKey seed; if (spk_man.GetKey(seed_id, seed)) { CExtKey masterKey; masterKey.SetSeed(seed); file << "# extended private masterkey: " << EncodeExtKey(masterKey) << "\n\n"; } } for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID &keyid = it->second; std::string strTime = FormatISO8601DateTime(it->first); std::string strAddr; std::string strLabel; CKey key; if (spk_man.GetKey(keyid, key)) { CKeyMetadata metadata; const auto it{spk_man.mapKeyMetadata.find(keyid)}; if (it != spk_man.mapKeyMetadata.end()) metadata = it->second; file << strprintf("%s %s ", EncodeSecret(key), strTime); if (GetWalletAddressesForKey(&spk_man, wallet, keyid, strAddr, strLabel)) { file << strprintf("label=%s", strLabel); } else if (keyid == seed_id) { file << "hdseed=1"; } else if (mapKeyPool.count(keyid)) { file << "reserve=1"; } else if (metadata.hdKeypath == "s") { file << "inactivehdseed=1"; } else { file << "change=1"; } file << strprintf(" # addr=%s%s\n", strAddr, (metadata.has_key_origin ? " hdkeypath="+WriteHDKeypath(metadata.key_origin.path) : "")); } } file << "\n"; for (const CScriptID &scriptid : scripts) { CScript script; std::string create_time = "0"; std::string address = EncodeDestination(ScriptHash(scriptid)); // get birth times for scripts with metadata auto it = spk_man.m_script_metadata.find(scriptid); if (it != spk_man.m_script_metadata.end()) { create_time = FormatISO8601DateTime(it->second.nCreateTime); } if(spk_man.GetCScript(scriptid, script)) { file << strprintf("%s %s script=1", HexStr(script), create_time); file << strprintf(" # addr=%s\n", address); } } file << "\n"; file << "# End of dump\n"; file.close(); UniValue reply(UniValue::VOBJ); reply.pushKV("filename", filepath.u8string()); return reply; }, }; } struct ImportData { // Input data std::unique_ptr<CScript> redeemscript; //!< Provided redeemScript; will be moved to `import_scripts` if relevant. std::unique_ptr<CScript> witnessscript; //!< Provided witnessScript; will be moved to `import_scripts` if relevant. // Output data std::set<CScript> import_scripts; std::map<CKeyID, bool> used_keys; //!< Import these private keys if available (the value indicates whether if the key is required for solvability) std::map<CKeyID, std::pair<CPubKey, KeyOriginInfo>> key_origins; }; enum class ScriptContext { TOP, //!< Top-level scriptPubKey P2SH, //!< P2SH redeemScript WITNESS_V0, //!< P2WSH witnessScript }; // Analyse the provided scriptPubKey, determining which keys and which redeem scripts from the ImportData struct are needed to spend it, and mark them as used. // Returns an error string, or the empty string for success. static std::string RecurseImportData(const CScript& script, ImportData& import_data, const ScriptContext script_ctx) { // Use Solver to obtain script type and parsed pubkeys or hashes: std::vector<std::vector<unsigned char>> solverdata; TxoutType script_type = Solver(script, solverdata); switch (script_type) { case TxoutType::PUBKEY: { CPubKey pubkey(solverdata[0]); import_data.used_keys.emplace(pubkey.GetID(), false); return ""; } case TxoutType::PUBKEYHASH: { CKeyID id = CKeyID(uint160(solverdata[0])); import_data.used_keys[id] = true; return ""; } case TxoutType::SCRIPTHASH: { if (script_ctx == ScriptContext::P2SH) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside another P2SH"); if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2SH inside a P2WSH"); CHECK_NONFATAL(script_ctx == ScriptContext::TOP); CScriptID id = CScriptID(uint160(solverdata[0])); auto subscript = std::move(import_data.redeemscript); // Remove redeemscript from import_data to check for superfluous script later. if (!subscript) return "missing redeemscript"; if (CScriptID(*subscript) != id) return "redeemScript does not match the scriptPubKey"; import_data.import_scripts.emplace(*subscript); return RecurseImportData(*subscript, import_data, ScriptContext::P2SH); } case TxoutType::MULTISIG: { for (size_t i = 1; i + 1< solverdata.size(); ++i) { CPubKey pubkey(solverdata[i]); import_data.used_keys.emplace(pubkey.GetID(), false); } return ""; } case TxoutType::WITNESS_V0_SCRIPTHASH: { if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WSH inside another P2WSH"); uint256 fullid(solverdata[0]); CScriptID id; CRIPEMD160().Write(fullid.begin(), fullid.size()).Finalize(id.begin()); auto subscript = std::move(import_data.witnessscript); // Remove redeemscript from import_data to check for superfluous script later. if (!subscript) return "missing witnessscript"; if (CScriptID(*subscript) != id) return "witnessScript does not match the scriptPubKey or redeemScript"; if (script_ctx == ScriptContext::TOP) { import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WSH requires the TOP script imported (see script/ismine.cpp) } import_data.import_scripts.emplace(*subscript); return RecurseImportData(*subscript, import_data, ScriptContext::WITNESS_V0); } case TxoutType::WITNESS_V0_KEYHASH: { if (script_ctx == ScriptContext::WITNESS_V0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Trying to nest P2WPKH inside P2WSH"); CKeyID id = CKeyID(uint160(solverdata[0])); import_data.used_keys[id] = true; if (script_ctx == ScriptContext::TOP) { import_data.import_scripts.emplace(script); // Special rule for IsMine: native P2WPKH requires the TOP script imported (see script/ismine.cpp) } return ""; } case TxoutType::NULL_DATA: return "unspendable script"; case TxoutType::NONSTANDARD: case TxoutType::WITNESS_UNKNOWN: case TxoutType::WITNESS_V1_TAPROOT: return "unrecognized script"; } // no default case, so the compiler can warn about missing cases NONFATAL_UNREACHABLE(); } static UniValue ProcessImportLegacy(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys) { UniValue warnings(UniValue::VARR); // First ensure scriptPubKey has either a script or JSON with "address" string const UniValue& scriptPubKey = data["scriptPubKey"]; bool isScript = scriptPubKey.getType() == UniValue::VSTR; if (!isScript && !(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address"))) { throw JSONRPCError(RPC_INVALID_PARAMETER, "scriptPubKey must be string with script or JSON with address string"); } const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str(); // Optional fields. const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : ""; const std::string& witness_script_hex = data.exists("witnessscript") ? data["witnessscript"].get_str() : ""; const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue(); const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false; if (data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for a non-descriptor import"); } // Generate the script and destination for the scriptPubKey provided CScript script; if (!isScript) { CTxDestination dest = DecodeDestination(output); if (!IsValidDestination(dest)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address \"" + output + "\""); } if (OutputTypeFromDestination(dest) == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m addresses cannot be imported into legacy wallets"); } script = GetScriptForDestination(dest); } else { if (!IsHex(output)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey \"" + output + "\""); } std::vector<unsigned char> vData(ParseHex(output)); script = CScript(vData.begin(), vData.end()); CTxDestination dest; if (!ExtractDestination(script, dest) && !internal) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set to true for nonstandard scriptPubKey imports."); } } script_pub_keys.emplace(script); // Parse all arguments if (strRedeemScript.size()) { if (!IsHex(strRedeemScript)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script \"" + strRedeemScript + "\": must be hex string"); } auto parsed_redeemscript = ParseHex(strRedeemScript); import_data.redeemscript = std::make_unique<CScript>(parsed_redeemscript.begin(), parsed_redeemscript.end()); } if (witness_script_hex.size()) { if (!IsHex(witness_script_hex)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid witness script \"" + witness_script_hex + "\": must be hex string"); } auto parsed_witnessscript = ParseHex(witness_script_hex); import_data.witnessscript = std::make_unique<CScript>(parsed_witnessscript.begin(), parsed_witnessscript.end()); } for (size_t i = 0; i < pubKeys.size(); ++i) { const auto& str = pubKeys[i].get_str(); if (!IsHex(str)) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" must be a hex string"); } auto parsed_pubkey = ParseHex(str); CPubKey pubkey(parsed_pubkey); if (!pubkey.IsFullyValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey \"" + str + "\" is not a valid public key"); } pubkey_map.emplace(pubkey.GetID(), pubkey); ordered_pubkeys.push_back(pubkey.GetID()); } for (size_t i = 0; i < keys.size(); ++i) { const auto& str = keys[i].get_str(); CKey key = DecodeSecret(str); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubkey = key.GetPubKey(); CKeyID id = pubkey.GetID(); if (pubkey_map.count(id)) { pubkey_map.erase(id); } privkey_map.emplace(id, key); } // Verify and process input data have_solving_data = import_data.redeemscript || import_data.witnessscript || pubkey_map.size() || privkey_map.size(); if (have_solving_data) { // Match up data in import_data with the scriptPubKey in script. auto error = RecurseImportData(script, import_data, ScriptContext::TOP); // Verify whether the watchonly option corresponds to the availability of private keys. bool spendable = std::all_of(import_data.used_keys.begin(), import_data.used_keys.end(), [&](const std::pair<CKeyID, bool>& used_key){ return privkey_map.count(used_key.first) > 0; }); if (!watchOnly && !spendable) { warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."); } if (watchOnly && spendable) { warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."); } // Check that all required keys for solvability are provided. if (error.empty()) { for (const auto& require_key : import_data.used_keys) { if (!require_key.second) continue; // Not a required key if (pubkey_map.count(require_key.first) == 0 && privkey_map.count(require_key.first) == 0) { error = "some required keys are missing"; } } } if (!error.empty()) { warnings.push_back("Importing as non-solvable: " + error + ". If this is intentional, don't provide any keys, pubkeys, witnessscript, or redeemscript."); import_data = ImportData(); pubkey_map.clear(); privkey_map.clear(); have_solving_data = false; } else { // RecurseImportData() removes any relevant redeemscript/witnessscript from import_data, so we can use that to discover if a superfluous one was provided. if (import_data.redeemscript) warnings.push_back("Ignoring redeemscript as this is not a P2SH script."); if (import_data.witnessscript) warnings.push_back("Ignoring witnessscript as this is not a (P2SH-)P2WSH script."); for (auto it = privkey_map.begin(); it != privkey_map.end(); ) { auto oldit = it++; if (import_data.used_keys.count(oldit->first) == 0) { warnings.push_back("Ignoring irrelevant private key."); privkey_map.erase(oldit); } } for (auto it = pubkey_map.begin(); it != pubkey_map.end(); ) { auto oldit = it++; auto key_data_it = import_data.used_keys.find(oldit->first); if (key_data_it == import_data.used_keys.end() || !key_data_it->second) { warnings.push_back("Ignoring public key \"" + HexStr(oldit->first) + "\" as it doesn't appear inside P2PKH or P2WPKH."); pubkey_map.erase(oldit); } } } } return warnings; } static UniValue ProcessImportDescriptor(ImportData& import_data, std::map<CKeyID, CPubKey>& pubkey_map, std::map<CKeyID, CKey>& privkey_map, std::set<CScript>& script_pub_keys, bool& have_solving_data, const UniValue& data, std::vector<CKeyID>& ordered_pubkeys) { UniValue warnings(UniValue::VARR); const std::string& descriptor = data["desc"].get_str(); FlatSigningProvider keys; std::string error; auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true); if (!parsed_desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } if (parsed_desc->GetOutputType() == OutputType::BECH32M) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Bech32m descriptors cannot be imported into legacy wallets"); } have_solving_data = parsed_desc->IsSolvable(); const bool watch_only = data.exists("watchonly") ? data["watchonly"].get_bool() : false; int64_t range_start = 0, range_end = 0; if (!parsed_desc->IsRange() && data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } else if (parsed_desc->IsRange()) { if (!data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor is ranged, please specify the range"); } std::tie(range_start, range_end) = ParseDescriptorRange(data["range"]); } const UniValue& priv_keys = data.exists("keys") ? data["keys"].get_array() : UniValue(); // Expand all descriptors to get public keys and scripts, and private keys if available. for (int i = range_start; i <= range_end; ++i) { FlatSigningProvider out_keys; std::vector<CScript> scripts_temp; parsed_desc->Expand(i, keys, scripts_temp, out_keys); std::copy(scripts_temp.begin(), scripts_temp.end(), std::inserter(script_pub_keys, script_pub_keys.end())); for (const auto& key_pair : out_keys.pubkeys) { ordered_pubkeys.push_back(key_pair.first); } for (const auto& x : out_keys.scripts) { import_data.import_scripts.emplace(x.second); } parsed_desc->ExpandPrivate(i, keys, out_keys); std::copy(out_keys.pubkeys.begin(), out_keys.pubkeys.end(), std::inserter(pubkey_map, pubkey_map.end())); std::copy(out_keys.keys.begin(), out_keys.keys.end(), std::inserter(privkey_map, privkey_map.end())); import_data.key_origins.insert(out_keys.origins.begin(), out_keys.origins.end()); } for (size_t i = 0; i < priv_keys.size(); ++i) { const auto& str = priv_keys[i].get_str(); CKey key = DecodeSecret(str); if (!key.IsValid()) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); } CPubKey pubkey = key.GetPubKey(); CKeyID id = pubkey.GetID(); // Check if this private key corresponds to a public key from the descriptor if (!pubkey_map.count(id)) { warnings.push_back("Ignoring irrelevant private key."); } else { privkey_map.emplace(id, key); } } // Check if all the public keys have corresponding private keys in the import for spendability. // This does not take into account threshold multisigs which could be spendable without all keys. // Thus, threshold multisigs without all keys will be considered not spendable here, even if they are, // perhaps triggering a false warning message. This is consistent with the current wallet IsMine check. bool spendable = std::all_of(pubkey_map.begin(), pubkey_map.end(), [&](const std::pair<CKeyID, CPubKey>& used_key) { return privkey_map.count(used_key.first) > 0; }) && std::all_of(import_data.key_origins.begin(), import_data.key_origins.end(), [&](const std::pair<CKeyID, std::pair<CPubKey, KeyOriginInfo>>& entry) { return privkey_map.count(entry.first) > 0; }); if (!watch_only && !spendable) { warnings.push_back("Some private keys are missing, outputs will be considered watchonly. If this is intentional, specify the watchonly flag."); } if (watch_only && spendable) { warnings.push_back("All private keys are provided, outputs will be considered spendable. If this is intentional, do not specify the watchonly flag."); } return warnings; } static UniValue ProcessImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { UniValue warnings(UniValue::VARR); UniValue result(UniValue::VOBJ); try { const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; // Internal addresses should not have a label if (internal && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label"); } const std::string& label = data.exists("label") ? data["label"].get_str() : ""; const bool add_keypool = data.exists("keypool") ? data["keypool"].get_bool() : false; // Add to keypool only works with privkeys disabled if (add_keypool && !wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Keys can only be imported to the keypool when private keys are disabled"); } ImportData import_data; std::map<CKeyID, CPubKey> pubkey_map; std::map<CKeyID, CKey> privkey_map; std::set<CScript> script_pub_keys; std::vector<CKeyID> ordered_pubkeys; bool have_solving_data; if (data.exists("scriptPubKey") && data.exists("desc")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Both a descriptor and a scriptPubKey should not be provided."); } else if (data.exists("scriptPubKey")) { warnings = ProcessImportLegacy(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys); } else if (data.exists("desc")) { warnings = ProcessImportDescriptor(import_data, pubkey_map, privkey_map, script_pub_keys, have_solving_data, data, ordered_pubkeys); } else { throw JSONRPCError(RPC_INVALID_PARAMETER, "Either a descriptor or scriptPubKey must be provided."); } // If private keys are disabled, abort if private keys are being imported if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !privkey_map.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } // Check whether we have any work to do for (const CScript& script : script_pub_keys) { if (wallet.IsMine(script) & ISMINE_SPENDABLE) { throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script (\"" + HexStr(script) + "\")"); } } // All good, time to import wallet.MarkDirty(); if (!wallet.ImportScripts(import_data.import_scripts, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding script to wallet"); } if (!wallet.ImportPrivKeys(privkey_map, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); } if (!wallet.ImportPubKeys(ordered_pubkeys, pubkey_map, import_data.key_origins, add_keypool, internal, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } if (!wallet.ImportScriptPubKeys(label, script_pub_keys, have_solving_data, !internal, timestamp)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); } result.pushKV("success", UniValue(true)); } catch (const UniValue& e) { result.pushKV("success", UniValue(false)); result.pushKV("error", e); } catch (...) { result.pushKV("success", UniValue(false)); result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields")); } if (warnings.size()) result.pushKV("warnings", warnings); return result; } static int64_t GetImportTimestamp(const UniValue& data, int64_t now) { if (data.exists("timestamp")) { const UniValue& timestamp = data["timestamp"]; if (timestamp.isNum()) { return timestamp.get_int64(); } else if (timestamp.isStr() && timestamp.get_str() == "now") { return now; } throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type()))); } throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key"); } RPCHelpMan importmulti() { return RPCHelpMan{"importmulti", "\nImport addresses/scripts (with private or public keys, redeem script (P2SH)), optionally rescanning the blockchain from the earliest creation time of the imported scripts. Requires a new wallet backup.\n" "If an address/script is imported without all of the private keys required to spend from that address, it will be watchonly. The 'watchonly' option must be set to true in this case or a warning will be returned.\n" "Conversely, if all the private keys are provided and the address/script is spendable, the watchonly option must be set to false, or a warning will be returned.\n" "\nNote: This call can take over an hour to complete if rescan is true, during that time, other rpc calls\n" "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n" "Note: Use \"getwalletinfo\" to query the scanning progress.\n", { {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"desc", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Descriptor to import. If using descriptor, do not also provide address/scriptPubKey, scripts, or pubkeys"}, {"scriptPubKey", RPCArg::Type::STR, RPCArg::Optional::NO, "Type of scriptPubKey (string for script, json for address). Should not be provided if using a descriptor", /*oneline_description=*/"", {"\"<script>\" | { \"address\":\"<address>\" }", "string / json"} }, {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Creation time of the key expressed in " + UNIX_EPOCH_TIME + ",\n" " or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n" " key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n" " \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n" " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n" " creation time of all keys being imported by the importmulti call will be scanned.", /*oneline_description=*/"", {"timestamp | \"now\"", "integer / string"} }, {"redeemscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH or P2SH-P2WSH address/scriptPubKey"}, {"witnessscript", RPCArg::Type::STR, RPCArg::Optional::OMITTED, "Allowed only if the scriptPubKey is a P2SH-P2WSH or P2WSH address/scriptPubKey"}, {"pubkeys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving pubkeys to import. They must occur in P2PKH or P2WPKH scripts. They are not required when the private key is also provided (see the \"keys\" argument).", { {"pubKey", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""}, } }, {"keys", RPCArg::Type::ARR, RPCArg::Default{UniValue::VARR}, "Array of strings giving private keys to import. The corresponding public keys must occur in the output or redeemscript.", { {"key", RPCArg::Type::STR, RPCArg::Optional::OMITTED, ""}, } }, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"}, {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be treated as not incoming payments (also known as change)"}, {"watchonly", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether matching outputs should be considered watchonly."}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false"}, {"keypool", RPCArg::Type::BOOL, RPCArg::Default{false}, "Stating whether imported public keys should be added to the keypool for when users request new addresses. Only allowed when wallet private keys are disabled"}, }, }, }, "\"requests\""}, {"options", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED_NAMED_ARG, "", { {"rescan", RPCArg::Type::BOOL, RPCArg::Default{true}, "Stating if should rescan the blockchain after all imports"}, }, "\"options\""}, }, RPCResult{ RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "success", ""}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "", { {RPCResult::Type::STR, "", ""}, }}, {RPCResult::Type::OBJ, "error", /*optional=*/true, "", { {RPCResult::Type::ELISION, "", "JSONRPC error"}, }}, }}, } }, RPCExamples{ HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, " "{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") }, [&](const RPCHelpMan& self, const JSONRPCRequest& mainRequest) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(mainRequest); if (!pwallet) return NullUniValue; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ}); EnsureLegacyScriptPubKeyMan(*pwallet, true); const UniValue& requests = mainRequest.params[0]; //Default options bool fRescan = true; if (!mainRequest.params[1].isNull()) { const UniValue& options = mainRequest.params[1]; if (options.exists("rescan")) { fRescan = options["rescan"].get_bool(); } } WalletRescanReserver reserver(*pwallet); if (fRescan && !reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } int64_t now = 0; bool fRunScan = false; int64_t nLowestTimestamp = 0; UniValue response(UniValue::VARR); { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); // Verify all timestamps are present before importing any keys. CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(nLowestTimestamp).mtpTime(now))); for (const UniValue& data : requests.getValues()) { GetImportTimestamp(data, now); } const int64_t minimumTimestamp = 1; for (const UniValue& data : requests.getValues()) { const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp); const UniValue result = ProcessImport(*pwallet, data, timestamp); response.push_back(result); if (!fRescan) { continue; } // If at least one request was successful then allow rescan. if (result["success"].get_bool()) { fRunScan = true; } // Get the lowest timestamp. if (timestamp < nLowestTimestamp) { nLowestTimestamp = timestamp; } } } if (fRescan && fRunScan && requests.size()) { int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, true /* update */); { LOCK(pwallet->cs_wallet); pwallet->ReacceptWalletTransactions(); } if (pwallet->IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } if (scannedTime > nLowestTimestamp) { std::vector<UniValue> results = response.getValues(); response.clear(); response.setArray(); size_t i = 0; for (const UniValue& request : requests.getValues()) { // If key creation date is within the successfully scanned // range, or if the import result already has an error set, let // the result stand unmodified. Otherwise replace the result // with an error message. if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) { response.push_back(results.at(i)); } else { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV( "error", JSONRPCError( RPC_MISC_ERROR, strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a " "block from time %d, which is after or within %d seconds of key creation, and " "could contain transactions pertaining to the key. As a result, transactions " "and coins using this key may not appear in the wallet. This error could be " "caused by pruning or data corruption (see bitcoind log for details) and could " "be dealt with by downloading and rescanning the relevant blocks (see -reindex " "option and rescanblockchain RPC).", GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW))); response.push_back(std::move(result)); } ++i; } } } return response; }, }; } static UniValue ProcessDescriptorImport(CWallet& wallet, const UniValue& data, const int64_t timestamp) EXCLUSIVE_LOCKS_REQUIRED(wallet.cs_wallet) { UniValue warnings(UniValue::VARR); UniValue result(UniValue::VOBJ); try { if (!data.exists("desc")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Descriptor not found."); } const std::string& descriptor = data["desc"].get_str(); const bool active = data.exists("active") ? data["active"].get_bool() : false; const bool internal = data.exists("internal") ? data["internal"].get_bool() : false; const std::string& label = data.exists("label") ? data["label"].get_str() : ""; // Parse descriptor string FlatSigningProvider keys; std::string error; auto parsed_desc = Parse(descriptor, keys, error, /* require_checksum = */ true); if (!parsed_desc) { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, error); } // Range check int64_t range_start = 0, range_end = 1, next_index = 0; if (!parsed_desc->IsRange() && data.exists("range")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Range should not be specified for an un-ranged descriptor"); } else if (parsed_desc->IsRange()) { if (data.exists("range")) { auto range = ParseDescriptorRange(data["range"]); range_start = range.first; range_end = range.second + 1; // Specified range end is inclusive, but we need range end as exclusive } else { warnings.push_back("Range not given, using default keypool range"); range_start = 0; range_end = gArgs.GetIntArg("-keypool", DEFAULT_KEYPOOL_SIZE); } next_index = range_start; if (data.exists("next_index")) { next_index = data["next_index"].get_int64(); // bound checks if (next_index < range_start || next_index >= range_end) { throw JSONRPCError(RPC_INVALID_PARAMETER, "next_index is out of range"); } } } // Active descriptors must be ranged if (active && !parsed_desc->IsRange()) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Active descriptors must be ranged"); } // Ranged descriptors should not have a label if (data.exists("range") && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Ranged descriptors should not have a label"); } // Internal addresses should not have a label either if (internal && data.exists("label")) { throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal addresses should not have a label"); } // Combo descriptor check if (active && !parsed_desc->IsSingleType()) { throw JSONRPCError(RPC_WALLET_ERROR, "Combo descriptors cannot be set to active"); } // If the wallet disabled private keys, abort if private keys exist if (wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS) && !keys.keys.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import private keys to a wallet with private keys disabled"); } // Need to ExpandPrivate to check if private keys are available for all pubkeys FlatSigningProvider expand_keys; std::vector<CScript> scripts; if (!parsed_desc->Expand(0, keys, scripts, expand_keys)) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot expand descriptor. Probably because of hardened derivations without private keys provided"); } parsed_desc->ExpandPrivate(0, keys, expand_keys); // Check if all private keys are provided bool have_all_privkeys = !expand_keys.keys.empty(); for (const auto& entry : expand_keys.origins) { const CKeyID& key_id = entry.first; CKey key; if (!expand_keys.GetKey(key_id, key)) { have_all_privkeys = false; break; } } // If private keys are enabled, check some things. if (!wallet.IsWalletFlagSet(WALLET_FLAG_DISABLE_PRIVATE_KEYS)) { if (keys.keys.empty()) { throw JSONRPCError(RPC_WALLET_ERROR, "Cannot import descriptor without private keys to a wallet with private keys enabled"); } if (!have_all_privkeys) { warnings.push_back("Not all private keys provided. Some wallet functionality may return unexpected errors"); } } WalletDescriptor w_desc(std::move(parsed_desc), timestamp, range_start, range_end, next_index); // Check if the wallet already contains the descriptor auto existing_spk_manager = wallet.GetDescriptorScriptPubKeyMan(w_desc); if (existing_spk_manager) { if (!existing_spk_manager->CanUpdateToWalletDescriptor(w_desc, error)) { throw JSONRPCError(RPC_INVALID_PARAMETER, error); } } // Add descriptor to the wallet auto spk_manager = wallet.AddWalletDescriptor(w_desc, keys, label, internal); if (spk_manager == nullptr) { throw JSONRPCError(RPC_WALLET_ERROR, strprintf("Could not add descriptor '%s'", descriptor)); } // Set descriptor as active if necessary if (active) { if (!w_desc.descriptor->GetOutputType()) { warnings.push_back("Unknown output type, cannot set descriptor to active."); } else { wallet.AddActiveScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal); } } else { if (w_desc.descriptor->GetOutputType()) { wallet.DeactivateScriptPubKeyMan(spk_manager->GetID(), *w_desc.descriptor->GetOutputType(), internal); } } result.pushKV("success", UniValue(true)); } catch (const UniValue& e) { result.pushKV("success", UniValue(false)); result.pushKV("error", e); } if (warnings.size()) result.pushKV("warnings", warnings); return result; } RPCHelpMan importdescriptors() { return RPCHelpMan{"importdescriptors", "\nImport descriptors. This will trigger a rescan of the blockchain based on the earliest timestamp of all descriptors being imported. Requires a new wallet backup.\n" "\nNote: This call can take over an hour to complete if using an early timestamp; during that time, other rpc calls\n" "may report that the imported keys, addresses or scripts exist but related transactions are still missing.\n", { {"requests", RPCArg::Type::ARR, RPCArg::Optional::NO, "Data to be imported", { {"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "", { {"desc", RPCArg::Type::STR, RPCArg::Optional::NO, "Descriptor to import."}, {"active", RPCArg::Type::BOOL, RPCArg::Default{false}, "Set this descriptor to be the active descriptor for the corresponding output type/externality"}, {"range", RPCArg::Type::RANGE, RPCArg::Optional::OMITTED, "If a ranged descriptor is used, this specifies the end or the range (in the form [begin,end]) to import"}, {"next_index", RPCArg::Type::NUM, RPCArg::Optional::OMITTED, "If a ranged descriptor is set to active, this specifies the next index to generate addresses from"}, {"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "Time from which to start rescanning the blockchain for this descriptor, in " + UNIX_EPOCH_TIME + "\n" " Use the string \"now\" to substitute the current synced blockchain time.\n" " \"now\" can be specified to bypass scanning, for outputs which are known to never have been used, and\n" " 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest timestamp\n" " of all descriptors being imported will be scanned.", /*oneline_description=*/"", {"timestamp | \"now\"", "integer / string"} }, {"internal", RPCArg::Type::BOOL, RPCArg::Default{false}, "Whether matching outputs should be treated as not incoming payments (e.g. change)"}, {"label", RPCArg::Type::STR, RPCArg::Default{""}, "Label to assign to the address, only allowed with internal=false. Disabled for ranged descriptors"}, }, }, }, "\"requests\""}, }, RPCResult{ RPCResult::Type::ARR, "", "Response is an array with the same size as the input that has the execution result", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::BOOL, "success", ""}, {RPCResult::Type::ARR, "warnings", /*optional=*/true, "", { {RPCResult::Type::STR, "", ""}, }}, {RPCResult::Type::OBJ, "error", /*optional=*/true, "", { {RPCResult::Type::ELISION, "", "JSONRPC error"}, }}, }}, } }, RPCExamples{ HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"internal\": true }, " "{ \"desc\": \"<my desccriptor 2>\", \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") + HelpExampleCli("importdescriptors", "'[{ \"desc\": \"<my descriptor>\", \"timestamp\":1455191478, \"active\": true, \"range\": [0,100], \"label\": \"<my bech32 wallet>\" }]'") }, [&](const RPCHelpMan& self, const JSONRPCRequest& main_request) -> UniValue { std::shared_ptr<CWallet> const pwallet = GetWalletForJSONRPCRequest(main_request); if (!pwallet) return NullUniValue; CWallet& wallet{*pwallet}; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now wallet.BlockUntilSyncedToCurrentChain(); // Make sure wallet is a descriptor wallet if (!pwallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) { throw JSONRPCError(RPC_WALLET_ERROR, "importdescriptors is not available for non-descriptor wallets"); } RPCTypeCheck(main_request.params, {UniValue::VARR, UniValue::VOBJ}); WalletRescanReserver reserver(*pwallet); if (!reserver.reserve()) { throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait."); } const UniValue& requests = main_request.params[0]; const int64_t minimum_timestamp = 1; int64_t now = 0; int64_t lowest_timestamp = 0; bool rescan = false; UniValue response(UniValue::VARR); { LOCK(pwallet->cs_wallet); EnsureWalletIsUnlocked(*pwallet); CHECK_NONFATAL(pwallet->chain().findBlock(pwallet->GetLastBlockHash(), FoundBlock().time(lowest_timestamp).mtpTime(now))); // Get all timestamps and extract the lowest timestamp for (const UniValue& request : requests.getValues()) { // This throws an error if "timestamp" doesn't exist const int64_t timestamp = std::max(GetImportTimestamp(request, now), minimum_timestamp); const UniValue result = ProcessDescriptorImport(*pwallet, request, timestamp); response.push_back(result); if (lowest_timestamp > timestamp ) { lowest_timestamp = timestamp; } // If we know the chain tip, and at least one request was successful then allow rescan if (!rescan && result["success"].get_bool()) { rescan = true; } } pwallet->ConnectScriptPubKeyManNotifiers(); } // Rescan the blockchain using the lowest timestamp if (rescan) { int64_t scanned_time = pwallet->RescanFromTime(lowest_timestamp, reserver, true /* update */); { LOCK(pwallet->cs_wallet); pwallet->ReacceptWalletTransactions(); } if (pwallet->IsAbortingRescan()) { throw JSONRPCError(RPC_MISC_ERROR, "Rescan aborted by user."); } if (scanned_time > lowest_timestamp) { std::vector<UniValue> results = response.getValues(); response.clear(); response.setArray(); // Compose the response for (unsigned int i = 0; i < requests.size(); ++i) { const UniValue& request = requests.getValues().at(i); // If the descriptor timestamp is within the successfully scanned // range, or if the import result already has an error set, let // the result stand unmodified. Otherwise replace the result // with an error message. if (scanned_time <= GetImportTimestamp(request, now) || results.at(i).exists("error")) { response.push_back(results.at(i)); } else { UniValue result = UniValue(UniValue::VOBJ); result.pushKV("success", UniValue(false)); result.pushKV( "error", JSONRPCError( RPC_MISC_ERROR, strprintf("Rescan failed for descriptor with timestamp %d. There was an error reading a " "block from time %d, which is after or within %d seconds of key creation, and " "could contain transactions pertaining to the desc. As a result, transactions " "and coins using this desc may not appear in the wallet. This error could be " "caused by pruning or data corruption (see bitcoind log for details) and could " "be dealt with by downloading and rescanning the relevant blocks (see -reindex " "option and rescanblockchain RPC).", GetImportTimestamp(request, now), scanned_time - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW))); response.push_back(std::move(result)); } } } } return response; }, }; } RPCHelpMan listdescriptors() { return RPCHelpMan{ "listdescriptors", "\nList descriptors imported into a descriptor-enabled wallet.\n", { {"private", RPCArg::Type::BOOL, RPCArg::Default{false}, "Show private descriptors."} }, RPCResult{RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "wallet_name", "Name of wallet this operation was performed on"}, {RPCResult::Type::ARR, "descriptors", "Array of descriptor objects", { {RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "desc", "Descriptor string representation"}, {RPCResult::Type::NUM, "timestamp", "The creation time of the descriptor"}, {RPCResult::Type::BOOL, "active", "Whether this descriptor is currently used to generate new addresses"}, {RPCResult::Type::BOOL, "internal", /*optional=*/true, "True if this descriptor is used to generate change addresses. False if this descriptor is used to generate receiving addresses; defined only for active descriptors"}, {RPCResult::Type::ARR_FIXED, "range", /*optional=*/true, "Defined only for ranged descriptors", { {RPCResult::Type::NUM, "", "Range start inclusive"}, {RPCResult::Type::NUM, "", "Range end inclusive"}, }}, {RPCResult::Type::NUM, "next", /*optional=*/true, "The next index to generate addresses from; defined only for ranged descriptors"}, }}, }} }}, RPCExamples{ HelpExampleCli("listdescriptors", "") + HelpExampleRpc("listdescriptors", "") + HelpExampleCli("listdescriptors", "true") + HelpExampleRpc("listdescriptors", "true") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> wallet = GetWalletForJSONRPCRequest(request); if (!wallet) return NullUniValue; if (!wallet->IsWalletFlagSet(WALLET_FLAG_DESCRIPTORS)) { throw JSONRPCError(RPC_WALLET_ERROR, "listdescriptors is not available for non-descriptor wallets"); } const bool priv = !request.params[0].isNull() && request.params[0].get_bool(); if (priv) { EnsureWalletIsUnlocked(*wallet); } LOCK(wallet->cs_wallet); UniValue descriptors(UniValue::VARR); const auto active_spk_mans = wallet->GetActiveScriptPubKeyMans(); for (const auto& spk_man : wallet->GetAllScriptPubKeyMans()) { const auto desc_spk_man = dynamic_cast<DescriptorScriptPubKeyMan*>(spk_man); if (!desc_spk_man) { throw JSONRPCError(RPC_WALLET_ERROR, "Unexpected ScriptPubKey manager type."); } UniValue spk(UniValue::VOBJ); LOCK(desc_spk_man->cs_desc_man); const auto& wallet_descriptor = desc_spk_man->GetWalletDescriptor(); std::string descriptor; if (!desc_spk_man->GetDescriptorString(descriptor, priv)) { throw JSONRPCError(RPC_WALLET_ERROR, "Can't get descriptor string."); } spk.pushKV("desc", descriptor); spk.pushKV("timestamp", wallet_descriptor.creation_time); spk.pushKV("active", active_spk_mans.count(desc_spk_man) != 0); const auto internal = wallet->IsInternalScriptPubKeyMan(desc_spk_man); if (internal.has_value()) { spk.pushKV("internal", *internal); } if (wallet_descriptor.descriptor->IsRange()) { UniValue range(UniValue::VARR); range.push_back(wallet_descriptor.range_start); range.push_back(wallet_descriptor.range_end - 1); spk.pushKV("range", range); spk.pushKV("next", wallet_descriptor.next_index); } descriptors.push_back(spk); } UniValue response(UniValue::VOBJ); response.pushKV("wallet_name", wallet->GetName()); response.pushKV("descriptors", descriptors); return response; }, }; } RPCHelpMan backupwallet() { return RPCHelpMan{"backupwallet", "\nSafely copies current wallet file to destination, which can be a directory or a path with filename.\n", { {"destination", RPCArg::Type::STR, RPCArg::Optional::NO, "The destination directory or file"}, }, RPCResult{RPCResult::Type::NONE, "", ""}, RPCExamples{ HelpExampleCli("backupwallet", "\"backup.dat\"") + HelpExampleRpc("backupwallet", "\"backup.dat\"") }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { const std::shared_ptr<const CWallet> pwallet = GetWalletForJSONRPCRequest(request); if (!pwallet) return NullUniValue; // Make sure the results are valid at least up to the most recent block // the user could have gotten from another RPC command prior to now pwallet->BlockUntilSyncedToCurrentChain(); LOCK(pwallet->cs_wallet); std::string strDest = request.params[0].get_str(); if (!pwallet->BackupWallet(strDest)) { throw JSONRPCError(RPC_WALLET_ERROR, "Error: Wallet backup failed!"); } return NullUniValue; }, }; } RPCHelpMan restorewallet() { return RPCHelpMan{ "restorewallet", "\nRestore and loads a wallet from backup.\n", { {"wallet_name", RPCArg::Type::STR, RPCArg::Optional::NO, "The name that will be applied to the restored wallet"}, {"backup_file", RPCArg::Type::STR, RPCArg::Optional::NO, "The backup file that will be used to restore the wallet."}, {"load_on_startup", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED_NAMED_ARG, "Save wallet name to persistent settings and load on startup. True to add wallet to startup list, false to remove, null to leave unchanged."}, }, RPCResult{ RPCResult::Type::OBJ, "", "", { {RPCResult::Type::STR, "name", "The wallet name if restored successfully."}, {RPCResult::Type::STR, "warning", "Warning message if wallet was not loaded cleanly."}, } }, RPCExamples{ HelpExampleCli("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"") + HelpExampleRpc("restorewallet", "\"testwallet\" \"home\\backups\\backup-file.bak\"") + HelpExampleCliNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}}) + HelpExampleRpcNamed("restorewallet", {{"wallet_name", "testwallet"}, {"backup_file", "home\\backups\\backup-file.bak\""}, {"load_on_startup", true}}) }, [&](const RPCHelpMan& self, const JSONRPCRequest& request) -> UniValue { WalletContext& context = EnsureWalletContext(request.context); auto backup_file = fs::u8path(request.params[1].get_str()); std::string wallet_name = request.params[0].get_str(); std::optional<bool> load_on_start = request.params[2].isNull() ? std::nullopt : std::optional<bool>(request.params[2].get_bool()); DatabaseStatus status; bilingual_str error; std::vector<bilingual_str> warnings; const std::shared_ptr<CWallet> wallet = RestoreWallet(context, backup_file, wallet_name, load_on_start, status, error, warnings); HandleWalletError(wallet, status, error); UniValue obj(UniValue::VOBJ); obj.pushKV("name", wallet->GetName()); obj.pushKV("warning", Join(warnings, Untranslated("\n")).original); return obj; }, }; } } // namespace wallet
mit
tsteinholz/SR-Gaming
Libraries/allegro5-5.1/src/bitmap_draw.c
2
7253
/* ______ ___ ___ * /\ _ \ /\_ \ /\_ \ * \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___ * \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\ * \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \ * \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/ * \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/ * /\____/ * \_/__/ * * Bitmap drawing routines. * * See LICENSE.txt for copyright information. */ #include "allegro5/allegro.h" #include "allegro5/internal/aintern_bitmap.h" #include "allegro5/internal/aintern_display.h" #include "allegro5/internal/aintern_memblit.h" #include "allegro5/internal/aintern_pixels.h" static ALLEGRO_COLOR solid_white = {1, 1, 1, 1}; static void _bitmap_drawer(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, int flags) { ALLEGRO_BITMAP *dest = al_get_target_bitmap(); ALLEGRO_DISPLAY *display = _al_get_bitmap_display(dest); ASSERT(bitmap->parent == NULL); ASSERT(!(flags & (ALLEGRO_FLIP_HORIZONTAL | ALLEGRO_FLIP_VERTICAL))); ASSERT(bitmap != dest && bitmap != dest->parent); /* If destination is memory, do a memory blit */ if (al_get_bitmap_flags(dest) & ALLEGRO_MEMORY_BITMAP || _al_pixel_format_is_compressed(al_get_bitmap_format(dest))) { _al_draw_bitmap_region_memory(bitmap, tint, sx, sy, sw, sh, 0, 0, flags); } else { /* if source is memory or incompatible */ if ((al_get_bitmap_flags(bitmap) & ALLEGRO_MEMORY_BITMAP) || (!al_is_compatible_bitmap(bitmap))) { if (display && display->vt->draw_memory_bitmap_region) { display->vt->draw_memory_bitmap_region(display, bitmap, sx, sy, sw, sh, flags); } else { _al_draw_bitmap_region_memory(bitmap, tint, sx, sy, sw, sh, 0, 0, flags); } } else { /* Compatible display bitmap, use full acceleration */ bitmap->vt->draw_bitmap_region(bitmap, tint, sx, sy, sw, sh, flags); } } } static void _draw_tinted_rotated_scaled_bitmap_region(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float cx, float cy, float angle, float xscale, float yscale, float sx, float sy, float sw, float sh, float dx, float dy, int flags) { ALLEGRO_TRANSFORM backup; ALLEGRO_TRANSFORM t; ALLEGRO_BITMAP *parent = bitmap; float const orig_sw = sw; float const orig_sh = sh; ASSERT(bitmap); al_copy_transform(&backup, al_get_current_transform()); al_identity_transform(&t); if (bitmap->parent) { parent = bitmap->parent; sx += bitmap->xofs; sy += bitmap->yofs; } if (sx < 0) { sw += sx; al_translate_transform(&t, -sx, 0); sx = 0; } if (sy < 0) { sh += sy; al_translate_transform(&t, 0, -sy); sy = 0; } if (sx + sw > parent->w) sw = parent->w - sx; if (sy + sh > parent->h) sh = parent->h - sy; if (flags & ALLEGRO_FLIP_HORIZONTAL) { al_scale_transform(&t, -1, 1); al_translate_transform(&t, orig_sw, 0); flags &= ~ALLEGRO_FLIP_HORIZONTAL; } if (flags & ALLEGRO_FLIP_VERTICAL) { al_scale_transform(&t, 1, -1); al_translate_transform(&t, 0, orig_sh); flags &= ~ALLEGRO_FLIP_VERTICAL; } al_translate_transform(&t, -cx, -cy); al_scale_transform(&t, xscale, yscale); al_rotate_transform(&t, angle); al_translate_transform(&t, dx, dy); al_compose_transform(&t, &backup); al_use_transform(&t); _bitmap_drawer(parent, tint, sx, sy, sw, sh, flags); al_use_transform(&backup); } /* Function: al_draw_tinted_bitmap_region */ void al_draw_tinted_bitmap_region(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, int flags) { _draw_tinted_rotated_scaled_bitmap_region(bitmap, tint, 0, 0, 0, 1, 1, sx, sy, sw, sh, dx, dy, flags); } /* Function: al_draw_tinted_bitmap */ void al_draw_tinted_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float dx, float dy, int flags) { ASSERT(bitmap); al_draw_tinted_bitmap_region(bitmap, tint, 0, 0, bitmap->w, bitmap->h, dx, dy, flags); } /* Function: al_draw_bitmap */ void al_draw_bitmap(ALLEGRO_BITMAP *bitmap, float dx, float dy, int flags) { al_draw_tinted_bitmap(bitmap, solid_white, dx, dy, flags); } /* Function: al_draw_bitmap_region */ void al_draw_bitmap_region(ALLEGRO_BITMAP *bitmap, float sx, float sy, float sw, float sh, float dx, float dy, int flags) { al_draw_tinted_bitmap_region(bitmap, solid_white, sx, sy, sw, sh, dx, dy, flags); } /* Function: al_draw_tinted_scaled_bitmap */ void al_draw_tinted_scaled_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags) { _draw_tinted_rotated_scaled_bitmap_region(bitmap, tint, 0, 0, 0, dw / sw, dh / sh, sx, sy, sw, sh, dx, dy, flags); } /* Function: al_draw_scaled_bitmap */ void al_draw_scaled_bitmap(ALLEGRO_BITMAP *bitmap, float sx, float sy, float sw, float sh, float dx, float dy, float dw, float dh, int flags) { al_draw_tinted_scaled_bitmap(bitmap, solid_white, sx, sy, sw, sh, dx, dy, dw, dh, flags); } /* Function: al_draw_tinted_rotated_bitmap * * angle is specified in radians and moves clockwise * on the screen. */ void al_draw_tinted_rotated_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float angle, int flags) { al_draw_tinted_scaled_rotated_bitmap(bitmap, tint, cx, cy, dx, dy, 1, 1, angle, flags); } /* Function: al_draw_rotated_bitmap */ void al_draw_rotated_bitmap(ALLEGRO_BITMAP *bitmap, float cx, float cy, float dx, float dy, float angle, int flags) { al_draw_tinted_rotated_bitmap(bitmap, solid_white, cx, cy, dx, dy, angle, flags); } /* Function: al_draw_tinted_scaled_rotated_bitmap */ void al_draw_tinted_scaled_rotated_bitmap(ALLEGRO_BITMAP *bitmap, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) { _draw_tinted_rotated_scaled_bitmap_region(bitmap, tint, cx, cy, angle, xscale, yscale, 0, 0, bitmap->w, bitmap->h, dx, dy, flags); } /* Function: al_draw_tinted_scaled_rotated_bitmap_region */ void al_draw_tinted_scaled_rotated_bitmap_region(ALLEGRO_BITMAP *bitmap, float sx, float sy, float sw, float sh, ALLEGRO_COLOR tint, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) { _draw_tinted_rotated_scaled_bitmap_region(bitmap, tint, cx, cy, angle, xscale, yscale, sx, sy, sw, sh, dx, dy, flags); } /* Function: al_draw_scaled_rotated_bitmap */ void al_draw_scaled_rotated_bitmap(ALLEGRO_BITMAP *bitmap, float cx, float cy, float dx, float dy, float xscale, float yscale, float angle, int flags) { al_draw_tinted_scaled_rotated_bitmap(bitmap, solid_white, cx, cy, dx, dy, xscale, yscale, angle, flags); } /* vim: set ts=8 sts=3 sw=3 et: */
mit
rcrowder/Burt
cmucam3_r556/cc3/hal/lpc2106-cmucam3/syscalls.c
2
7698
/* * Copyright 2006-2007 Anthony Rowe and Adam Goode * * 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 <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/stat.h> #include <sys/unistd.h> #include <sys/time.h> #include <sys/times.h> #include "LPC2100.h" #include "devices.h" //#include "serial.h" #include <errno.h> #undef errno extern int errno; // register char *stack_ptr asm ("sp"); // The above line can be used to check the stack pointer // uart0_write_hex(stack_ptr); /* prototypes */ int _write (int file, const char *ptr, int len); int _read (int file, char *ptr, int len); int kill(int pid, int sig); void _exit(int status); void abort(void); int _close(int file); _off_t _lseek(int file, _off_t offset, int dir); int _fstat(int file, struct stat *st); int _isatty (int file); int _system(const char *s); int _link(char *old, char *new); int _open(const char *name, int flags, int mode); int _rename(char *oldpath, char *newpath); int _gettimeofday (struct timeval *tp, struct timezone *tzp); int _kill(int pid, int sig); int _getpid(void); int _times(struct tms *buf); int _unlink(char *name); int _raise(int sig); void *_sbrk(int nbytes); /* implementation */ int _write (int file, const char *ptr, int len) { _cc3_device_driver_t *dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->write(_cc3_get_internal_file_number(file), ptr, len); } int _read (int file, char *ptr, int len) { _cc3_device_driver_t *dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->read(_cc3_get_internal_file_number(file), ptr, len); } int kill(int pid __attribute__((unused)), int sig __attribute__((unused))) { errno = EINVAL; return(-1); } void _exit(int status __attribute__((unused))) { // XXX: should call cc3_power_down while(1); } void abort(void) { _exit(1); } int _close(int file) { _cc3_device_driver_t *dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->close(_cc3_get_internal_file_number(file)); } _off_t _lseek(int file, _off_t offset, int dir) { _cc3_device_driver_t * dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->lseek(_cc3_get_internal_file_number(file), offset, dir); } int _fstat(int file, struct stat *st) { _cc3_device_driver_t * dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->fstat(_cc3_get_internal_file_number(file), st); } int _isatty (int file) { _cc3_device_driver_t * dev = _cc3_get_driver_for_file_number(file); if (dev == NULL) { errno = EBADF; return -1; } return dev->is_tty ? 1 : 0; } int _system(const char *s) { if (s == NULL) { return 0; /* no shell */ } else { errno = EINVAL; return -1; } } int _link(char *old __attribute__((unused)), char *new __attribute__((unused))) { // we do not support hard links errno = EPERM; return -1; } static void normalize_filename(char *name) { // make all caps, and change '\' to '/' int i = 0; char c; while ((c = name[i]) != '\0') { if (c == '\\' ) { name[i] = '/'; } else { name[i] = toupper(c); } i++; } } int _open(const char *name, int flags, int mode) { int result = -1; char *norm = strdup(name); _cc3_device_driver_t *dev; if (norm == NULL) { return result; } normalize_filename(norm); dev = _cc3_get_driver_for_name(norm); if (dev == NULL) { errno = ENOENT; result = -1; } else { result = _cc3_make_file_number(dev, dev->open(name, flags, mode)); } free(norm); return result; } int _rename(char *oldpath, char *newpath) { int result = -1; char *n_oldpath; char *n_newpath; _cc3_device_driver_t *dev1; _cc3_device_driver_t *dev2; // normalize paths n_oldpath = strdup(oldpath); if (n_oldpath == NULL) { return -1; } n_newpath = strdup(newpath); if (n_newpath == NULL) { free(n_oldpath); return -1; } normalize_filename(n_oldpath); normalize_filename(n_newpath); // get the device drivers for the paths dev1 = _cc3_get_driver_for_name(n_oldpath); dev2 = _cc3_get_driver_for_name(n_newpath); if (dev1 != dev2) { // make sure the devices are the same errno = EXDEV; } else if (dev1 == NULL || dev2 == NULL) { // make sure the drivers exist errno = ENOENT; } else { // pass it down result = dev1->rename(n_oldpath, n_newpath); } // done free(n_oldpath); free(n_newpath); return result; } int _gettimeofday (struct timeval *tp __attribute__((unused)), struct timezone *tzp __attribute__((unused))) { return -1; } int _kill(int pid __attribute__((unused)), int sig __attribute__((unused))) { errno = EINVAL; return -1; } int _getpid() { return 1; } int _times(struct tms *buf) { clock_t ticks = REG(TIMER0_TC) / (1000 / CLOCKS_PER_SEC); // REG in milliseconds buf->tms_utime = ticks; buf->tms_stime = 0; buf->tms_cutime = 0; buf->tms_cstime = 0; return ticks; } int _unlink(char *name) { int result = -1; char *norm = strdup(name); _cc3_device_driver_t *dev; if (norm == NULL) { return -1; } // normalize normalize_filename(norm); // get device dev = _cc3_get_driver_for_name(norm); if (dev != NULL) { result = dev->unlink(name); } else { errno = ENOENT; } free(norm); return result; } int _raise(int sig __attribute__((unused))) { return 1; } /* exciting memory management! */ extern char _end[]; /* end is set in the linker command */ /* file and is the end of statically */ /* allocated data (thus start of heap). */ extern char _heap_end[]; /* heap_end is also set in the linker */ /* and represents the physical end of */ /* ram (and the ultimate limit of the */ /* heap). */ static void *heap_ptr; /* Points to current end of the heap. */ void *_sbrk(int nbytes) { char *base; /* errno should be set to ENOMEM on error */ //uart0_write("in _sbrk\r\n"); //uart0_write(" nbytes = "); //uart0_write_hex((unsigned int) nbytes); //uart0_write(" heap_ptr = "); //uart0_write_hex((unsigned int) heap_ptr); if (!heap_ptr) { /* Initialize if first time through. */ heap_ptr = _end; } //uart0_write(" heap_ptr = "); //uart0_write_hex((unsigned int) heap_ptr); base = heap_ptr; /* Point to end of heap. */ //uart0_write(" base = "); //uart0_write_hex((unsigned int) base); if (base + nbytes >= (char *) _heap_end) { //uart0_write(" ENOMEM!\r\n"); errno = ENOMEM; return (void *) -1; } heap_ptr = (char *)heap_ptr + nbytes; /* Increase heap */ //uart0_write(" heap_ptr = "); //uart0_write_hex((unsigned int) heap_ptr); //uart0_write(" returning\r\n"); return base; /* Return pointer to start of new heap area. */ }
mit
Siv3D/OpenSiv3D
Siv3D/src/ThirdParty/Oniguruma/iso8859_14.c
2
8847
/********************************************************************** iso8859_14.c - Oniguruma (regular expression library) **********************************************************************/ /*- * Copyright (c) 2002-2019 K.Kosako * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "regenc.h" #define ENC_ISO_8859_14_TO_LOWER_CASE(c) EncISO_8859_14_ToLowerCaseTable[c] #define ENC_IS_ISO_8859_14_CTYPE(code,ctype) \ ((EncISO_8859_14_CtypeTable[code] & CTYPE_TO_BIT(ctype)) != 0) static const UChar EncISO_8859_14_ToLowerCaseTable[256] = { '\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007', '\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017', '\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027', '\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037', '\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047', '\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057', '\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067', '\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077', '\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137', '\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147', '\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157', '\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167', '\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177', '\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207', '\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217', '\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227', '\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237', '\240', '\242', '\242', '\243', '\245', '\245', '\253', '\247', '\270', '\251', '\272', '\253', '\274', '\255', '\256', '\377', '\261', '\261', '\263', '\263', '\265', '\265', '\266', '\271', '\270', '\271', '\272', '\277', '\274', '\276', '\276', '\277', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\337', '\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347', '\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357', '\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367', '\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377' }; static const unsigned short EncISO_8859_14_CtypeTable[256] = { 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x420c, 0x4209, 0x4208, 0x4208, 0x4208, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4008, 0x4284, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x78b0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x7ca2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x74a2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x51a0, 0x41a0, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x78e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x70e2, 0x41a0, 0x41a0, 0x41a0, 0x41a0, 0x4008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0008, 0x0284, 0x34a2, 0x30e2, 0x00a0, 0x34a2, 0x30e2, 0x34a2, 0x00a0, 0x34a2, 0x00a0, 0x34a2, 0x30e2, 0x34a2, 0x01a0, 0x00a0, 0x34a2, 0x34a2, 0x30e2, 0x34a2, 0x30e2, 0x34a2, 0x30e2, 0x00a0, 0x34a2, 0x30e2, 0x30e2, 0x30e2, 0x34a2, 0x30e2, 0x34a2, 0x30e2, 0x30e2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x34a2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2, 0x30e2 }; static int mbc_case_fold(OnigCaseFoldType flag, const UChar** pp, const UChar* end ARG_UNUSED, UChar* lower) { const UChar* p = *pp; if (*p == 0xdf && (flag & INTERNAL_ONIGENC_CASE_FOLD_MULTI_CHAR) != 0) { *lower++ = 's'; *lower = 's'; (*pp)++; return 2; } *lower = ENC_ISO_8859_14_TO_LOWER_CASE(*p); (*pp)++; return 1; /* return byte length of converted char to lower */ } static int is_code_ctype(OnigCodePoint code, unsigned int ctype) { if (code < 256) return ENC_IS_ISO_8859_14_CTYPE(code, ctype); else return FALSE; } static const OnigPairCaseFoldCodes CaseFoldMap[] = { { 0xa1, 0xa2 }, { 0xa4, 0xa5 }, { 0xa6, 0xab }, { 0xa8, 0xb8 }, { 0xaa, 0xba }, { 0xac, 0xbc }, { 0xaf, 0xff }, { 0xb0, 0xb1 }, { 0xb2, 0xb3 }, { 0xb4, 0xb5 }, { 0xb7, 0xb9 }, { 0xbb, 0xbf }, { 0xbd, 0xbe }, { 0xc0, 0xe0 }, { 0xc1, 0xe1 }, { 0xc2, 0xe2 }, { 0xc3, 0xe3 }, { 0xc4, 0xe4 }, { 0xc5, 0xe5 }, { 0xc6, 0xe6 }, { 0xc7, 0xe7 }, { 0xc8, 0xe8 }, { 0xc9, 0xe9 }, { 0xca, 0xea }, { 0xcb, 0xeb }, { 0xcc, 0xec }, { 0xcd, 0xed }, { 0xce, 0xee }, { 0xcf, 0xef }, { 0xd0, 0xf0 }, { 0xd1, 0xf1 }, { 0xd2, 0xf2 }, { 0xd3, 0xf3 }, { 0xd4, 0xf4 }, { 0xd5, 0xf5 }, { 0xd6, 0xf6 }, { 0xd7, 0xf7 }, { 0xd8, 0xf8 }, { 0xd9, 0xf9 }, { 0xda, 0xfa }, { 0xdb, 0xfb }, { 0xdc, 0xfc }, { 0xdd, 0xfd }, { 0xde, 0xfe } }; static int apply_all_case_fold(OnigCaseFoldType flag, OnigApplyAllCaseFoldFunc f, void* arg) { return onigenc_apply_all_case_fold_with_map( sizeof(CaseFoldMap)/sizeof(OnigPairCaseFoldCodes), CaseFoldMap, 1, flag, f, arg); } static int get_case_fold_codes_by_str(OnigCaseFoldType flag, const OnigUChar* p, const OnigUChar* end, OnigCaseFoldCodeItem items[]) { return onigenc_get_case_fold_codes_by_str_with_map( sizeof(CaseFoldMap)/sizeof(OnigPairCaseFoldCodes), CaseFoldMap, 1, flag, p, end, items); } OnigEncodingType OnigEncodingISO_8859_14 = { onigenc_single_byte_mbc_enc_len, "ISO-8859-14", /* name */ 1, /* max enc length */ 1, /* min enc length */ onigenc_is_mbc_newline_0x0a, onigenc_single_byte_mbc_to_code, onigenc_single_byte_code_to_mbclen, onigenc_single_byte_code_to_mbc, mbc_case_fold, apply_all_case_fold, get_case_fold_codes_by_str, onigenc_minimum_property_name_to_ctype, is_code_ctype, onigenc_not_support_get_ctype_code_range, onigenc_single_byte_left_adjust_char_head, onigenc_always_true_is_allowed_reverse_match, NULL, /* init */ NULL, /* is_initialized */ onigenc_always_true_is_valid_mbc_string, ENC_FLAG_ASCII_COMPATIBLE|ENC_FLAG_SKIP_OFFSET_1, 0, 0 };
mit
maurer/tiamat
samples/Juliet/testcases/CWE415_Double_Free/s02/CWE415_Double_Free__new_delete_wchar_t_22b.cpp
2
2417
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE415_Double_Free__new_delete_wchar_t_22b.cpp Label Definition File: CWE415_Double_Free__new_delete.label.xml Template File: sources-sinks-22b.tmpl.cpp */ /* * @description * CWE: 415 Double Free * BadSource: Allocate data using new and Deallocae data using delete * GoodSource: Allocate data using new * Sinks: * GoodSink: do nothing * BadSink : Deallocate data using delete * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE415_Double_Free__new_delete_wchar_t_22 { #ifndef OMITBAD /* The global variable below is used to drive control flow in the sink function. Since it is in a C++ namespace, it doesn't need a globally unique name. */ extern int badGlobal; void badSink(wchar_t * data) { if(badGlobal) { /* POTENTIAL FLAW: Possibly deleting memory twice */ delete data; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the sink functions. Since they are in a C++ namespace, they don't need globally unique names. */ extern int goodB2G1Global; extern int goodB2G2Global; extern int goodG2B1Global; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ void goodB2G1Sink(wchar_t * data) { if(goodB2G1Global) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* do nothing */ /* FIX: Don't attempt to delete the memory */ ; /* empty statement needed for some flow variants */ } } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ void goodB2G2Sink(wchar_t * data) { if(goodB2G2Global) { /* do nothing */ /* FIX: Don't attempt to delete the memory */ ; /* empty statement needed for some flow variants */ } } /* goodG2B1() - use goodsource and badsink */ void goodG2B1Sink(wchar_t * data) { if(goodG2B1Global) { /* POTENTIAL FLAW: Possibly deleting memory twice */ delete data; } } #endif /* OMITGOOD */ } /* close namespace */
mit
OpenWise/wiseup-arduino
libraries/DallasTemperature/DallasTemperature.cpp
2
22993
// This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // Version 3.7.2 modified on Dec 6, 2011 to support Arduino 1.0 // See Includes... // Modified by Jordan Hochenbaum #include "DallasTemperature.h" #if ARDUINO >= 100 #include "Arduino.h" #else extern "C" { #include "WConstants.h" } #endif DallasTemperature::DallasTemperature(OneWire* _oneWire) #if REQUIRESALARMS : _AlarmHandler(&defaultAlarmHandler) #endif { _wire = _oneWire; devices = 0; parasite = false; bitResolution = 9; waitForConversion = true; checkForConversion = true; } // initialise the bus void DallasTemperature::begin(void) { DeviceAddress deviceAddress; _wire->reset_search(); devices = 0; // Reset the number of devices when we enumerate wire devices while (_wire->search(deviceAddress)) { if (validAddress(deviceAddress)) { if (!parasite && readPowerSupply(deviceAddress)) parasite = true; ScratchPad scratchPad; readScratchPad(deviceAddress, scratchPad); bitResolution = max(bitResolution, getResolution(deviceAddress)); devices++; } } } // returns the number of devices found on the bus uint8_t DallasTemperature::getDeviceCount(void) { return devices; } // returns true if address is valid bool DallasTemperature::validAddress(const uint8_t* deviceAddress) { return (_wire->crc8((uint8_t *)deviceAddress, 7) == deviceAddress[7]); } // finds an address at a given index on the bus // returns true if the device was found bool DallasTemperature::getAddress(uint8_t* deviceAddress, uint8_t index) { uint8_t depth = 0; _wire->reset_search(); while (depth <= index && _wire->search(deviceAddress)) { if (depth == index && validAddress(deviceAddress)) return true; depth++; } return false; } // attempt to determine if the device at the given address is connected to the bus bool DallasTemperature::isConnected(const uint8_t* deviceAddress) { ScratchPad scratchPad; return isConnected(deviceAddress, scratchPad); } // attempt to determine if the device at the given address is connected to the bus // also allows for updating the read scratchpad bool DallasTemperature::isConnected(const uint8_t* deviceAddress, uint8_t* scratchPad) { readScratchPad(deviceAddress, scratchPad); return (_wire->crc8(scratchPad, 8) == scratchPad[SCRATCHPAD_CRC]); } // read device's scratch pad void DallasTemperature::readScratchPad(const uint8_t* deviceAddress, uint8_t* scratchPad) { // send the command _wire->reset(); _wire->select((uint8_t *)deviceAddress); _wire->write(READSCRATCH); // TODO => collect all comments & use simple loop // byte 0: temperature LSB // byte 1: temperature MSB // byte 2: high alarm temp // byte 3: low alarm temp // byte 4: DS18S20: store for crc // DS18B20 & DS1822: configuration register // byte 5: internal use & crc // byte 6: DS18S20: COUNT_REMAIN // DS18B20 & DS1822: store for crc // byte 7: DS18S20: COUNT_PER_C // DS18B20 & DS1822: store for crc // byte 8: SCRATCHPAD_CRC // // for(int i=0; i<9; i++) // { // scratchPad[i] = _wire->read(); // } // read the response // byte 0: temperature LSB scratchPad[TEMP_LSB] = _wire->read(); // byte 1: temperature MSB scratchPad[TEMP_MSB] = _wire->read(); // byte 2: high alarm temp scratchPad[HIGH_ALARM_TEMP] = _wire->read(); // byte 3: low alarm temp scratchPad[LOW_ALARM_TEMP] = _wire->read(); // byte 4: // DS18S20: store for crc // DS18B20 & DS1822: configuration register scratchPad[CONFIGURATION] = _wire->read(); // byte 5: // internal use & crc scratchPad[INTERNAL_BYTE] = _wire->read(); // byte 6: // DS18S20: COUNT_REMAIN // DS18B20 & DS1822: store for crc scratchPad[COUNT_REMAIN] = _wire->read(); // byte 7: // DS18S20: COUNT_PER_C // DS18B20 & DS1822: store for crc scratchPad[COUNT_PER_C] = _wire->read(); // byte 8: // SCTRACHPAD_CRC scratchPad[SCRATCHPAD_CRC] = _wire->read(); _wire->reset(); } // writes device's scratch pad void DallasTemperature::writeScratchPad(const uint8_t* deviceAddress, const uint8_t* scratchPad) { _wire->reset(); _wire->select((uint8_t *)deviceAddress); _wire->write(WRITESCRATCH); _wire->write(scratchPad[HIGH_ALARM_TEMP]); // high alarm temp _wire->write(scratchPad[LOW_ALARM_TEMP]); // low alarm temp // DS1820 and DS18S20 have no configuration register if (deviceAddress[0] != DS18S20MODEL) _wire->write(scratchPad[CONFIGURATION]); // configuration _wire->reset(); _wire->select((uint8_t *)deviceAddress); //<--this line was missing // save the newly written values to eeprom _wire->write(COPYSCRATCH, parasite); delay(20); // <--- added 20ms delay to allow 10ms long EEPROM write operation (as specified by datasheet) if (parasite) delay(10); // 10ms delay _wire->reset(); } // reads the device's power requirements bool DallasTemperature::readPowerSupply(const uint8_t* deviceAddress) { bool ret = false; _wire->reset(); _wire->select((uint8_t *)deviceAddress); _wire->write(READPOWERSUPPLY); if (_wire->read_bit() == 0) ret = true; _wire->reset(); return ret; } // set resolution of all devices to 9, 10, 11, or 12 bits // if new resolution is out of range, it is constrained. void DallasTemperature::setResolution(uint8_t newResolution) { bitResolution = constrain(newResolution, 9, 12); DeviceAddress deviceAddress; for (int i=0; i<devices; i++) { getAddress(deviceAddress, i); setResolution(deviceAddress, bitResolution); } } // set resolution of a device to 9, 10, 11, or 12 bits // if new resolution is out of range, 9 bits is used. bool DallasTemperature::setResolution(const uint8_t* deviceAddress, uint8_t newResolution) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { // DS1820 and DS18S20 have no resolution configuration register if (deviceAddress[0] != DS18S20MODEL) { switch (newResolution) { case 12: scratchPad[CONFIGURATION] = TEMP_12_BIT; break; case 11: scratchPad[CONFIGURATION] = TEMP_11_BIT; break; case 10: scratchPad[CONFIGURATION] = TEMP_10_BIT; break; case 9: default: scratchPad[CONFIGURATION] = TEMP_9_BIT; break; } writeScratchPad(deviceAddress, scratchPad); } return true; // new value set } return false; } // returns the global resolution uint8_t DallasTemperature::getResolution() { return bitResolution; } // returns the current resolution of the device, 9-12 // returns 0 if device not found uint8_t DallasTemperature::getResolution(const uint8_t* deviceAddress) { // DS1820 and DS18S20 have no resolution configuration register if (deviceAddress[0] == DS18S20MODEL) return 12; ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { switch (scratchPad[CONFIGURATION]) { case TEMP_12_BIT: return 12; case TEMP_11_BIT: return 11; case TEMP_10_BIT: return 10; case TEMP_9_BIT: return 9; } } return 0; } // sets the value of the waitForConversion flag // TRUE : function requestTemperature() etc returns when conversion is ready // FALSE: function requestTemperature() etc returns immediately (USE WITH CARE!!) // (1) programmer has to check if the needed delay has passed // (2) but the application can do meaningful things in that time void DallasTemperature::setWaitForConversion(bool flag) { waitForConversion = flag; } // gets the value of the waitForConversion flag bool DallasTemperature::getWaitForConversion() { return waitForConversion; } // sets the value of the checkForConversion flag // TRUE : function requestTemperature() etc will 'listen' to an IC to determine whether a conversion is complete // FALSE: function requestTemperature() etc will wait a set time (worst case scenario) for a conversion to complete void DallasTemperature::setCheckForConversion(bool flag) { checkForConversion = flag; } // gets the value of the waitForConversion flag bool DallasTemperature::getCheckForConversion() { return checkForConversion; } bool DallasTemperature::isConversionAvailable(const uint8_t* deviceAddress) { // Check if the clock has been raised indicating the conversion is complete ScratchPad scratchPad; readScratchPad(deviceAddress, scratchPad); return scratchPad[0]; } // sends command for all devices on the bus to perform a temperature conversion void DallasTemperature::requestTemperatures() { _wire->reset(); _wire->skip(); _wire->write(STARTCONVO, parasite); // ASYNC mode? if (!waitForConversion) return; blockTillConversionComplete(bitResolution, NULL); } // sends command for one device to perform a temperature by address // returns FALSE if device is disconnected // returns TRUE otherwise bool DallasTemperature::requestTemperaturesByAddress(const uint8_t* deviceAddress) { _wire->reset(); _wire->select((uint8_t *)deviceAddress); _wire->write(STARTCONVO, parasite); // check device ScratchPad scratchPad; if (!isConnected(deviceAddress, scratchPad)) return false; // ASYNC mode? if (!waitForConversion) return true; blockTillConversionComplete(getResolution(deviceAddress), deviceAddress); return true; } // returns number of milliseconds to wait till conversion is complete (based on IC datasheet) int16_t DallasTemperature::millisToWaitForConversion(uint8_t bitResolution) { switch (bitResolution) { case 9: return 94; case 10: return 188; case 11: return 375; default: return 750; } } // Continue to check if the IC has responded with a temperature void DallasTemperature::blockTillConversionComplete(uint8_t bitResolution, const uint8_t* deviceAddress) { int delms = millisToWaitForConversion(bitResolution); if (deviceAddress != NULL && checkForConversion && !parasite) { unsigned long timend = millis() + delms; while(!isConversionAvailable(deviceAddress) && (millis() < timend)); } else { delay(delms); } } // sends command for one device to perform a temp conversion by index bool DallasTemperature::requestTemperaturesByIndex(uint8_t deviceIndex) { DeviceAddress deviceAddress; getAddress(deviceAddress, deviceIndex); return requestTemperaturesByAddress(deviceAddress); } // Fetch temperature for device index float DallasTemperature::getTempCByIndex(uint8_t deviceIndex) { DeviceAddress deviceAddress; if (!getAddress(deviceAddress, deviceIndex)) return DEVICE_DISCONNECTED_C; return getTempC((uint8_t*)deviceAddress); } // Fetch temperature for device index float DallasTemperature::getTempFByIndex(uint8_t deviceIndex) { DeviceAddress deviceAddress; if (!getAddress(deviceAddress, deviceIndex)) return DEVICE_DISCONNECTED_F; return getTempF((uint8_t*)deviceAddress); } // reads scratchpad and returns fixed-point temperature, scaling factor 2^-7 int16_t DallasTemperature::calculateTemperature(const uint8_t* deviceAddress, uint8_t* scratchPad) { int16_t fpTemperature = (((int16_t) scratchPad[TEMP_MSB]) << 11) | (((int16_t) scratchPad[TEMP_LSB]) << 3); /* DS1820 and DS18S20 have a 9-bit temperature register. Resolutions greater than 9-bit can be calculated using the data from the temperature, and COUNT REMAIN and COUNT PER °C registers in the scratchpad. The resolution of the calculation depends on the model. While the COUNT PER °C register is hard-wired to 16 (10h) in a DS18S20, it changes with temperature in DS1820. After reading the scratchpad, the TEMP_READ value is obtained by truncating the 0.5°C bit (bit 0) from the temperature data. The extended resolution temperature can then be calculated using the following equation: COUNT_PER_C - COUNT_REMAIN TEMPERATURE = TEMP_READ - 0.25 + -------------------------- COUNT_PER_C Hagai Shatz simplified this to integer arithmetic for a 12 bits value for a DS18S20, and James Cameron added legacy DS1820 support. See - http://myarduinotoy.blogspot.co.uk/2013/02/12bit-result-from-ds18s20.html */ if (deviceAddress[0] == DS18S20MODEL) fpTemperature = ((fpTemperature & 0xfff0) << 3) - 16 + ( ((scratchPad[COUNT_PER_C] - scratchPad[COUNT_REMAIN]) << 7) / scratchPad[COUNT_PER_C] ); return fpTemperature; } // returns temperature in 1/128 degrees C or DEVICE_DISCONNECTED_RAW if the // device's scratch pad cannot be read successfully. // the numeric value of DEVICE_DISCONNECTED_RAW is defined in // DallasTemperature.h. It is a large negative number outside the // operating range of the device int16_t DallasTemperature::getTemp(const uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return calculateTemperature(deviceAddress, scratchPad); return DEVICE_DISCONNECTED_RAW; } // returns temperature in degrees C or DEVICE_DISCONNECTED_C if the // device's scratch pad cannot be read successfully. // the numeric value of DEVICE_DISCONNECTED_C is defined in // DallasTemperature.h. It is a large negative number outside the // operating range of the device float DallasTemperature::getTempC(const uint8_t* deviceAddress) { return rawToCelsius(getTemp(deviceAddress)); } // returns temperature in degrees F or DEVICE_DISCONNECTED_F if the // device's scratch pad cannot be read successfully. // the numeric value of DEVICE_DISCONNECTED_F is defined in // DallasTemperature.h. It is a large negative number outside the // operating range of the device float DallasTemperature::getTempF(const uint8_t* deviceAddress) { return rawToFahrenheit(getTemp(deviceAddress)); } // returns true if the bus requires parasite power bool DallasTemperature::isParasitePowerMode(void) { return parasite; } #if REQUIRESALARMS /* ALARMS: TH and TL Register Format BIT 7 BIT 6 BIT 5 BIT 4 BIT 3 BIT 2 BIT 1 BIT 0 S 2^6 2^5 2^4 2^3 2^2 2^1 2^0 Only bits 11 through 4 of the temperature register are used in the TH and TL comparison since TH and TL are 8-bit registers. If the measured temperature is lower than or equal to TL or higher than or equal to TH, an alarm condition exists and an alarm flag is set inside the DS18B20. This flag is updated after every temperature measurement; therefore, if the alarm condition goes away, the flag will be turned off after the next temperature conversion. */ // sets the high alarm temperature for a device in degrees Celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C void DallasTemperature::setHighAlarmTemp(const uint8_t* deviceAddress, char celsius) { // make sure the alarm temperature is within the device's range if (celsius > 125) celsius = 125; else if (celsius < -55) celsius = -55; ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { scratchPad[HIGH_ALARM_TEMP] = (uint8_t)celsius; writeScratchPad(deviceAddress, scratchPad); } } // sets the low alarm temperature for a device in degrees Celsius // accepts a float, but the alarm resolution will ignore anything // after a decimal point. valid range is -55C - 125C void DallasTemperature::setLowAlarmTemp(const uint8_t* deviceAddress, char celsius) { // make sure the alarm temperature is within the device's range if (celsius > 125) celsius = 125; else if (celsius < -55) celsius = -55; ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { scratchPad[LOW_ALARM_TEMP] = (uint8_t)celsius; writeScratchPad(deviceAddress, scratchPad); } } // returns a char with the current high alarm temperature or // DEVICE_DISCONNECTED for an address char DallasTemperature::getHighAlarmTemp(const uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[HIGH_ALARM_TEMP]; return DEVICE_DISCONNECTED_C; } // returns a char with the current low alarm temperature or // DEVICE_DISCONNECTED for an address char DallasTemperature::getLowAlarmTemp(const uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) return (char)scratchPad[LOW_ALARM_TEMP]; return DEVICE_DISCONNECTED_C; } // resets internal variables used for the alarm search void DallasTemperature::resetAlarmSearch() { alarmSearchJunction = -1; alarmSearchExhausted = 0; for(uint8_t i = 0; i < 7; i++) alarmSearchAddress[i] = 0; } // This is a modified version of the OneWire::search method. // // Also added the OneWire search fix documented here: // http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 // // Perform an alarm search. If this function returns a '1' then it has // enumerated the next device and you may retrieve the ROM from the // OneWire::address variable. If there are no devices, no further // devices, or something horrible happens in the middle of the // enumeration then a 0 is returned. If a new device is found then // its address is copied to newAddr. Use // DallasTemperature::resetAlarmSearch() to start over. bool DallasTemperature::alarmSearch(uint8_t* newAddr) { uint8_t i; char lastJunction = -1; uint8_t done = 1; if (alarmSearchExhausted) return false; if (!_wire->reset()) return false; // send the alarm search command _wire->write(0xEC, 0); for(i = 0; i < 64; i++) { uint8_t a = _wire->read_bit( ); uint8_t nota = _wire->read_bit( ); uint8_t ibyte = i / 8; uint8_t ibit = 1 << (i & 7); // I don't think this should happen, this means nothing responded, but maybe if // something vanishes during the search it will come up. if (a && nota) return false; if (!a && !nota) { if (i == alarmSearchJunction) { // this is our time to decide differently, we went zero last time, go one. a = 1; alarmSearchJunction = lastJunction; } else if (i < alarmSearchJunction) { // take whatever we took last time, look in address if (alarmSearchAddress[ibyte] & ibit) a = 1; else { // Only 0s count as pending junctions, we've already exhausted the 0 side of 1s a = 0; done = 0; lastJunction = i; } } else { // we are blazing new tree, take the 0 a = 0; alarmSearchJunction = i; done = 0; } // OneWire search fix // See: http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295 } if (a) alarmSearchAddress[ibyte] |= ibit; else alarmSearchAddress[ibyte] &= ~ibit; _wire->write_bit(a); } if (done) alarmSearchExhausted = 1; for (i = 0; i < 8; i++) newAddr[i] = alarmSearchAddress[i]; return true; } // returns true if device address might have an alarm condition // (only an alarm search can verify this) bool DallasTemperature::hasAlarm(const uint8_t* deviceAddress) { ScratchPad scratchPad; if (isConnected(deviceAddress, scratchPad)) { char temp = calculateTemperature(deviceAddress, scratchPad) >> 7; // check low alarm if (temp <= (char)scratchPad[LOW_ALARM_TEMP]) return true; // check high alarm if (temp >= (char)scratchPad[HIGH_ALARM_TEMP]) return true; } // no alarm return false; } // returns true if any device is reporting an alarm condition on the bus bool DallasTemperature::hasAlarm(void) { DeviceAddress deviceAddress; resetAlarmSearch(); return alarmSearch(deviceAddress); } // runs the alarm handler for all devices returned by alarmSearch() void DallasTemperature::processAlarms(void) { resetAlarmSearch(); DeviceAddress alarmAddr; while (alarmSearch(alarmAddr)) { if (validAddress(alarmAddr)) _AlarmHandler(alarmAddr); } } // sets the alarm handler void DallasTemperature::setAlarmHandler(AlarmHandler *handler) { _AlarmHandler = handler; } // The default alarm handler void DallasTemperature::defaultAlarmHandler(const uint8_t* deviceAddress) { } #endif // Convert float Celsius to Fahrenheit float DallasTemperature::toFahrenheit(float celsius) { return (celsius * 1.8) + 32; } // Convert float Fahrenheit to Celsius float DallasTemperature::toCelsius(float fahrenheit) { return (fahrenheit - 32) * 0.555555556; } // convert from raw to Celsius float DallasTemperature::rawToCelsius(int16_t raw) { if (raw <= DEVICE_DISCONNECTED_RAW) return DEVICE_DISCONNECTED_C; // C = RAW/128 return (float)raw * 0.0078125; } // convert from raw to Fahrenheit float DallasTemperature::rawToFahrenheit(int16_t raw) { if (raw <= DEVICE_DISCONNECTED_RAW) return DEVICE_DISCONNECTED_F; // C = RAW/128 // F = (C*1.8)+32 = (RAW/128*1.8)+32 = (RAW*0.0140625)+32 return ((float)raw * 0.0140625) + 32; } #if REQUIRESNEW // MnetCS - Allocates memory for DallasTemperature. Allows us to instance a new object void* DallasTemperature::operator new(unsigned int size) // Implicit NSS obj size { void * p; // void pointer p = malloc(size); // Allocate memory memset((DallasTemperature*)p,0,size); // Initialise memory //!!! CANT EXPLICITLY CALL CONSTRUCTOR - workaround by using an init() methodR - workaround by using an init() method return (DallasTemperature*) p; // Cast blank region to NSS pointer } // MnetCS 2009 - Free the memory used by this instance void DallasTemperature::operator delete(void* p) { DallasTemperature* pNss = (DallasTemperature*) p; // Cast to NSS pointer pNss->~DallasTemperature(); // Destruct the object free(p); // Free the memory } #endif
mit
jicailiu/xbox-live-api
Tests/CTestApp/Xbox/XSAPI/Main.cpp
2
2768
// // Main.cpp // #include "pch.h" #include "Game.h" using namespace winrt::Windows::ApplicationModel; using namespace winrt::Windows::ApplicationModel::Core; using namespace winrt::Windows::ApplicationModel::Activation; using namespace winrt::Windows::UI::Core; using namespace winrt::Windows::Foundation; using namespace DirectX; class ViewProvider final : public winrt::implements<ViewProvider, IFrameworkView> { public: ViewProvider() : m_exit(false) { } // IFrameworkView methods void Initialize(CoreApplicationView const & applicationView) { applicationView.Activated({ this, &ViewProvider::OnActivated }); CoreApplication::Suspending({ this, &ViewProvider::OnSuspending }); CoreApplication::Resuming({ this, &ViewProvider::OnResuming }); CoreApplication::DisableKinectGpuReservation(true); m_game = std::make_unique<Game>(); } void Uninitialize() { m_game.reset(); } void SetWindow(CoreWindow const & window) { window.Closed({ this, &ViewProvider::OnWindowClosed }); ::IUnknown* windowPtr = winrt::get_abi(window); m_game->Initialize(windowPtr); } void Load(winrt::hstring const & /*entryPoint*/) { } void Run() { while (!m_exit) { m_game->Tick(); CoreWindow::GetForCurrentThread().Dispatcher().ProcessEvents(CoreProcessEventsOption::ProcessAllIfPresent); } } protected: // Event handlers void OnActivated(CoreApplicationView const & /*applicationView*/, IActivatedEventArgs const & /*args*/) { CoreWindow::GetForCurrentThread().Activate(); } void OnSuspending(IInspectable const & /*sender*/, SuspendingEventArgs const & args) { auto deferral = args.SuspendingOperation().GetDeferral(); std::async(std::launch::async, [this, deferral]() { m_game->OnSuspending(); deferral.Complete(); }); } void OnResuming(IInspectable const & /*sender*/, IInspectable const & /*args*/) { m_game->OnResuming(); } void OnWindowClosed(CoreWindow const & /*sender*/, CoreWindowEventArgs const & /*args*/) { m_exit = true; } private: bool m_exit; std::unique_ptr<Game> m_game; }; class ViewProviderFactory final : public winrt::implements<ViewProviderFactory, IFrameworkViewSource> { public: IFrameworkView CreateView() { return winrt::make<ViewProvider>(); } }; // Entry point int WINAPIV WinMain() { winrt::init_apartment(); ViewProviderFactory viewProviderFactory; CoreApplication::Run(viewProviderFactory); winrt::uninit_apartment(); return 0; }
mit
ruar18/competitive-programming
dmoj/dmopc/14c1p5-surprise-teleport.cpp
2
1246
#include <bits/stdc++.h> using namespace std; int r, c, x, y, sx, sy, ox, oy, t, dist[1001][1001], d[4][2]={{0,1},{0,-1},{1,0},{-1,0}}, mindist=123456789; queue<int> q; char grid[1001][1001]; int main(){ memset(dist,-1,sizeof(dist)); scanf("%d%d%d%d%d%d", &r, &c, &sx, &sy, &ox, &oy); if(sx==ox && sy==oy){ printf("0"); return 0; } q.push(sx); q.push(sy); dist[sx][sy]=0; for(int i =0; i <r;i++){ for(int j=0;j<c;j++){ scanf(" %c", &grid[i][j]); } } scanf("%d", &t); for(int i = 0;i<t;i++){ scanf("%d%d", &x, &y); if(x==sx && y==sy) mindist=0; grid[x][y]='t'; } grid[ox][oy]='e'; while(!q.empty()){ int cx=q.front(); q.pop(); int cy=q.front(); q.pop(); for(int k=0;k<4;k++){ int nx=cx+d[k][0], ny=cy+d[k][1]; if(nx>=0 && nx<r && ny>=0 && ny<c && grid[nx][ny]!='X' && dist[nx][ny]==-1){ dist[nx][ny] = dist[cx][cy]+1; if(grid[nx][ny]=='e'){printf("%d", max(dist[nx][ny]-mindist, 0)); return 0;} if(grid[nx][ny]=='t' && mindist==123456789) mindist=dist[nx][ny]; q.push(nx); q.push(ny); } } } return 0; }
mit
FlyingGraysons/Fido
src/Simulator/Simlink.cpp
2
9379
#include "../../include/Simulator/Simlink.h" #define _USE_MATH_DEFINES #include <SFML/Audio.hpp> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <iostream> #include <ctime> #include <math.h> #include <functional> Simlink::Simlink() : emitter(20), robot(850, 250, 50, 40), line(sf::Vector2f(0, 0), sf::Vector2f(1000, 1000)), ball(15, 100) { irVal = motors.motorOne = motors.motorTwo = 0; micVal = 30; visVal = batVal = 50; tempVal = 50; imu.accel.xComp = imu.accel.yComp = imu.accel.zComp = 0; imu.compass.xComp = imu.compass.yComp = imu.compass.zComp = 0; imu.gyro.xComp = imu.gyro.yComp = imu.gyro.zComp = 0; click = false; keepWindowsOpen = true; ball.setFillColor(sf::Color::Red); ball.setOutlineThickness(-3); ball.setOutlineColor(sf::Color::Black); ball.setOrigin(15,15); ball.setPosition(840, 100); mainWindowThread = std::thread(&Simlink::mainWindowHandler, this); } Simlink::~Simlink() { closeWindow(); } void Simlink::closeWindow() { keepWindowsOpen = false; if(mainWindowThread.joinable() == true) mainWindowThread.join(); } void Simlink::mainWindowHandler() { sf::ContextSettings settings; settings.antialiasingLevel = 8; // Initialize main window mainWindow.create(sf::VideoMode(1200, 900), "Fido Simulator", sf::Style::Default, settings); sf::Texture texture; if (!texture.loadFromFile("resources/background.png")) { exit(EXIT_FAILURE); } background = sf::Sprite(texture); sf::Font font; if (!font.loadFromFile("resources/sansation.ttf")) { exit(EXIT_FAILURE); } sf::Text text("Hello SFML", font, 50); text.setColor(sf::Color::Black); while (keepWindowsOpen == true) { updateMainWindow(); } mainWindow.close(); } void Simlink::updateMainWindow() { if (mainWindow.isOpen() == false) return; sf::Event event; while (mainWindow.pollEvent(event)) { switch (event.type) { case sf::Event::Closed: mainWindow.close(); break; case sf::Event::KeyPressed: if (event.key.code == sf::Keyboard::Escape) mainWindow.close(); break; case sf::Event::MouseButtonPressed: if (event.mouseButton.button == sf::Mouse::Left) { click = true; cx = event.mouseButton.x; cy = event.mouseButton.y; } break; case sf::Event::MouseButtonReleased: if (event.mouseButton.button == sf::Mouse::Left) click = false; break; case sf::Event::MouseMoved: if (click) { cx = event.mouseMove.x; cy = event.mouseMove.y; } break; default: break; } } if (click) { if (cx > 160 && cx < 220 && cy > 20 && cy < 280) imu.accel.xComp = -((cy - 20) - 130) / 1.28; else if (cx > 270 && cx < 330 && cy > 20 && cy < 280) imu.accel.yComp = -((cy - 20) - 130) / 1.28; else if (cx > 380 && cx < 440 && cy > 20 && cy < 280) imu.accel.zComp = -((cy - 20) - 130) / 1.28; if (cx > 160 && cx < 220 && cy > 320 && cy < 580) imu.gyro.xComp = -((cy - 320) - 130) / 1.28; else if (cx > 270 && cx < 330 && cy > 320 && cy < 580) imu.gyro.yComp = -((cy - 320) - 130) / 1.28; else if (cx > 380 && cx < 440 && cy > 320 && cy < 580) imu.gyro.zComp = -((cy - 320) - 130) / 1.28; if (cx > 160 && cx < 220 && cy > 620 && cy < 880) imu.compass.xComp = -((cy - 620) - 130) / 1.28; else if (cx > 270 && cx < 330 && cy > 620 && cy < 880) imu.compass.yComp = -((cy - 620) - 130) / 1.28; else if (cx > 380 && cx < 440 && cy > 620 && cy < 880) imu.compass.zComp = -((cy - 620) - 130) / 1.28; if (cx > 780 && cx < 850 && cy > 620 && cy < 880) batVal = (int)((880 - cy) / 2.6); else if (cx > 890 && cx < 960 && cy > 620 && cy < 880) irVal = (int)((880 - cy) / 2.6); else if (cx > 1000 && cx < 1070 && cy > 620 && cy < 880) visVal = (int)((880 - cy) / 2.6); else if (cx > 1110 && cx < 1180 && cy > 620 && cy < 880) micVal = (int)((880 - cy) / 2.6); else if (cx > 500 && cx < 700 && cy > 800 && cy < 880) tempVal = (int)((cx - 500) / 2); } sf::CircleShape ledCirc(40); ledCirc.setFillColor(sf::Color(led.r, led.g, led.b)); ledCirc.setPosition(675, 625); ledCirc.setOutlineThickness(5); ledCirc.setOutlineColor(sf::Color(0, 0, 0)); sf::RectangleShape slide(sf::Vector2f(40, 30)); slide.setFillColor(sf::Color(0, 0, 0)); mainWindow.clear(); mainWindow.draw(background); mainWindow.draw(ledCirc); slide.setPosition(170, 133 - imu.accel.xComp*1.2); mainWindow.draw(slide); slide.setPosition(280, 133 - imu.accel.yComp*1.2); mainWindow.draw(slide); slide.setPosition(390, 133 - imu.accel.zComp*1.2); mainWindow.draw(slide); slide.setPosition(168, 435 - imu.gyro.xComp*1.2); mainWindow.draw(slide); slide.setPosition(278, 435 - imu.gyro.yComp*1.2); mainWindow.draw(slide); slide.setPosition(388, 435 - imu.gyro.zComp*1.2); mainWindow.draw(slide); slide.setPosition(166, 732 - imu.compass.xComp*1.2); mainWindow.draw(slide); slide.setPosition(276, 732 - imu.compass.yComp*1.2); mainWindow.draw(slide); slide.setPosition(386, 732 - imu.compass.zComp*1.2); mainWindow.draw(slide); slide.setPosition(797, 858 - batVal*2.5); mainWindow.draw(slide); slide.setPosition(906, 858 - irVal*2.5); mainWindow.draw(slide); slide.setPosition(1016, 858 - visVal*2.5); mainWindow.draw(slide); slide.setPosition(1126, 858 - micVal*2.5); mainWindow.draw(slide); sf::RectangleShape horizontalSlide(sf::Vector2f(30, 40)); horizontalSlide.setFillColor(sf::Color(0, 0, 0)); horizontalSlide.setPosition(500 + tempVal * 2, 835); mainWindow.draw(horizontalSlide); /// Kinematics if (sf::Mouse::isButtonPressed(sf::Mouse::Right)) { sf::Vector2i mousePosition = sf::Mouse::getPosition(mainWindow); if(mousePosition.x > 496 + emitter.getRadius() && mousePosition.x < 1200 - emitter.getRadius() && mousePosition.y > 0 + emitter.getRadius() && mousePosition.y < 595 - emitter.getRadius()) emitter.set(sf::Mouse::getPosition(mainWindow)); } else if (sf::Keyboard::isKeyPressed(sf::Keyboard::P)) { emitter.bye(); } mainWindow.draw(robot); mainWindow.draw(emitter); //mainWindow.draw(line); //mainWindow.draw(ball); mainWindow.display(); sf::sleep(sf::milliseconds(25)); } TDVect Simlink::getAccel() { return imu.accel; } TDVect Simlink::getGyro() { return imu.gyro; } TDVect Simlink::getCompass() { TDVect emitSense = emitter.sense(robot, 50); imu.compass = { emitSense.xComp / 6.4, emitSense.yComp / 6.4, emitSense.zComp / 6.4 }; return imu.compass; } bool Simlink::isLeftOfLine() { return line.isLeft(robot.getPosition()); } double Simlink::distanceFromLine() { return line.distance(robot.getPosition()); } void Simlink::getBallDisplacement(double *x, double *z) { double lineLength = 100; double rotationX = robot.getRotation() * M_PI / 180.0; Line xLine = Line(robot.getPosition(), robot.getPosition() + sf::Vector2f(cos(rotationX)*lineLength, sin(rotationX)*lineLength)); *x = xLine.distance(ball.getPosition()); if(!xLine.isLeft(ball.getPosition())) *x *= -1; double rotationZ = (robot.getRotation() - 90) * M_PI / 180.0; Line zLine = Line(robot.getPosition(), robot.getPosition() + sf::Vector2f(cos(rotationZ)*lineLength, sin(rotationZ)*lineLength)); *z = zLine.distance(ball.getPosition()); if(zLine.isLeft(ball.getPosition())) *z *= -1; std::cout << *x << " " << *z << "\n"; std::cout.flush(); } int Simlink::getMicrophone() { return micVal; } int Simlink::getIR() { return irVal; } int Simlink::getVis() { return visVal; } int Simlink::getBattery() { return batVal; } void Simlink::setLED(int r, int g, int b, int i) { led.r = r * i/100; led.g = g * i/100; led.b = b * i/100; } void Simlink::setMotors(int motorOne, int motorTwo, double speed, double deltaTime) { motors.motorOne = motorOne; motors.motorTwo = motorTwo; sf::Vector2f previousRobotPosition = robot.getPosition(); robot.go(motors.motorOne, motors.motorTwo, speed, deltaTime); sf::Vector2f newRobotPosition = robot.getPosition(); if (newRobotPosition.x < 500 + robot.getGlobalBounds().height / 2 || newRobotPosition.x > 1200 - robot.getGlobalBounds().height / 2 || newRobotPosition.y < 0 + robot.getGlobalBounds().height / 2 || newRobotPosition.y > 595 - robot.getGlobalBounds().height / 2) { robot.setPosition(previousRobotPosition); } } void Simlink::chirp(int volume, int frequency) { piezo.frequency = frequency; piezo.volume = volume; int endTime = 200 + clock(); while(clock() != endTime); piezo.volume = 0; } int Simlink::getTemperature() { return tempVal; } void Simlink::placeRobotInRandomPosition() { double randX = (((double)rand() / (double)RAND_MAX) * (1150 - 550)) + 550; double randY = ((double)rand() / (double)RAND_MAX) * (530 - 50) + 50; robot.setPosition(randX, randY); } void Simlink::placeEmitterInRandomPosition() { double randX = ((double)rand() / (double)RAND_MAX) * (1150 - 550) + 550; double randY = ((double)rand() / (double)RAND_MAX) * (530 - 50) + 50; emitter.set(sf::Vector2i((int)randX, (int)randY)); } double Simlink::getDistanceOfRobotFromEmitter() { double difX = emitter.getPosition().x - robot.getPosition().x; double difY = emitter.getPosition().y - robot.getPosition().y; return sqrt(pow(difX, 2) + pow(difY, 2)); } void Simlink::getRobotDisplacementFromEmitter(double *x, double *y) { *x = emitter.getPosition().x - robot.getPosition().x; *y = emitter.getPosition().y - robot.getPosition().y; } void Simlink::placeLine(sf::Vector2f p1, sf::Vector2f p2) { line = Line(p1, p2); }
mit
jjuiddong/Point-Cloud
Src/Sample/Graphic/base/indexbuffer.cpp
2
1332
#include "stdafx.h" #include "indexbuffer.h" using namespace graphic; cIndexBuffer::cIndexBuffer() : m_pIdxBuff(NULL) , m_faceCount(0) { } cIndexBuffer::~cIndexBuffer() { Clear(); } bool cIndexBuffer::Create(cRenderer &renderer, int faceCount) { SAFE_RELEASE(m_pIdxBuff); if (FAILED(renderer.GetDevice()->CreateIndexBuffer(faceCount*3*sizeof(WORD), D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &m_pIdxBuff, NULL))) { return false; } m_faceCount = faceCount; return true; } void* cIndexBuffer::Lock() { RETV(!m_pIdxBuff, NULL); WORD *indices = NULL; m_pIdxBuff->Lock(0, 0, (void**)&indices, 0); return indices; } void cIndexBuffer::Unlock() { m_pIdxBuff->Unlock(); } void cIndexBuffer::Bind(cRenderer &renderer) const { renderer.GetDevice()->SetIndices(m_pIdxBuff); } void cIndexBuffer::Clear() { m_faceCount = 0; SAFE_RELEASE(m_pIdxBuff); } //cIndexBuffer& cIndexBuffer::operator=(cIndexBuffer &rhs) void cIndexBuffer::Set(cRenderer &renderer, cIndexBuffer &rhs) { if (this != &rhs) { m_faceCount = rhs.m_faceCount; if (Create(renderer, rhs.m_faceCount)) { if (BYTE* dest = (BYTE*)Lock()) { if (BYTE *src = (BYTE*)rhs.Lock()) { memcpy(dest, src, rhs.m_faceCount*3*sizeof(WORD)); rhs.Unlock(); } Unlock(); } } } //return *this; }
mit
TrickyCoin/trickycoin
src/qt/rpcconsole.cpp
2
14509
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the TrickyCoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
mit
SCOREC/nektar
solvers/CardiacEPSolver/CellModels/Winslow99.cpp
2
92048
/////////////////////////////////////////////////////////////////////////////// // // File Winslow99.cpp // // For more information, please see: http://www.nektar.info // // The MIT License // // Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA), // Department of Aeronautics, Imperial College London (UK), and Scientific // Computing and Imaging Institute, University of Utah (USA). // // License for the specific language governing rights and limitations under // 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. // // Description: Winslow 1999 cell model // /////////////////////////////////////////////////////////////////////////////// #include <iostream> #include <string> //#include <LibUtilities/BasicUtils/Vmath.hpp> #include <CardiacEPSolver/CellModels/Winslow99.h> namespace Nektar { std::string Winslow99::className = GetCellModelFactory().RegisterCreatorFunction( "Winslow99", Winslow99::create, "Winslow 1999 cell model."); /** * */ Winslow99::Winslow99( const LibUtilities::SessionReaderSharedPtr& pSession, const MultiRegions::ExpListSharedPtr& pField): CellModel(pSession, pField) { m_nvar = 33; m_gates.push_back(1); m_gates.push_back(2); m_gates.push_back(3); m_gates.push_back(4); m_gates.push_back(5); m_gates.push_back(6); m_gates.push_back(7); m_concentrations.push_back(8); m_concentrations.push_back(9); m_concentrations.push_back(10); m_concentrations.push_back(11); m_concentrations.push_back(12); m_concentrations.push_back(13); m_concentrations.push_back(14); m_concentrations.push_back(15); m_concentrations.push_back(16); m_concentrations.push_back(17); m_concentrations.push_back(18); m_concentrations.push_back(19); m_gates.push_back(20); m_concentrations.push_back(21); m_concentrations.push_back(22); m_concentrations.push_back(23); m_concentrations.push_back(24); m_concentrations.push_back(25); m_concentrations.push_back(26); m_concentrations.push_back(27); m_concentrations.push_back(28); m_concentrations.push_back(29); m_concentrations.push_back(30); m_concentrations.push_back(31); m_concentrations.push_back(32); } void Winslow99::v_Update( const Array<OneD, const Array<OneD, NekDouble> >&inarray, Array<OneD, Array<OneD, NekDouble> >&outarray, const NekDouble time) { int nq = m_nq; for (unsigned int i = 0; i < nq; ++i) { // Inputs: // Time units: millisecond NekDouble var_chaste_interface__membrane__V = inarray[0][i]; // Units: millivolt; Initial value: -96.1638 NekDouble var_chaste_interface__fast_sodium_current_m_gate__m = inarray[1][i]; // Units: dimensionless; Initial value: 0.0328302 NekDouble var_chaste_interface__fast_sodium_current_h_gate__h = inarray[2][i]; // Units: dimensionless; Initial value: 0.988354 NekDouble var_chaste_interface__fast_sodium_current_j_gate__j = inarray[3][i]; // Units: dimensionless; Initial value: 0.99254 NekDouble var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr = inarray[4][i]; // Units: dimensionless; Initial value: 0.51 NekDouble var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks = inarray[5][i]; // Units: dimensionless; Initial value: 0.264 NekDouble var_chaste_interface__transient_outward_potassium_current_X_to1_gate__X_to1 = inarray[6][i]; // Units: dimensionless; Initial value: 2.63 NekDouble var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__Y_to1 = inarray[7][i]; // Units: dimensionless; Initial value: 0.99 NekDouble var_chaste_interface__L_type_Ca_current__O = inarray[8][i]; // Units: dimensionless; Initial value: 9.84546e-21 NekDouble var_chaste_interface__L_type_Ca_current__O_Ca = inarray[9][i]; // Units: dimensionless; Initial value: 0 NekDouble var_chaste_interface__L_type_Ca_current__C0 = inarray[10][i]; // Units: dimensionless; Initial value: 0.997208 NekDouble var_chaste_interface__L_type_Ca_current__C1 = inarray[11][i]; // Units: dimensionless; Initial value: 6.38897e-5 NekDouble var_chaste_interface__L_type_Ca_current__C2 = inarray[12][i]; // Units: dimensionless; Initial value: 1.535e-9 NekDouble var_chaste_interface__L_type_Ca_current__C3 = inarray[13][i]; // Units: dimensionless; Initial value: 1.63909e-14 NekDouble var_chaste_interface__L_type_Ca_current__C4 = inarray[14][i]; // Units: dimensionless; Initial value: 6.56337e-20 NekDouble var_chaste_interface__L_type_Ca_current__C_Ca0 = inarray[15][i]; // Units: dimensionless; Initial value: 0.00272826 NekDouble var_chaste_interface__L_type_Ca_current__C_Ca1 = inarray[16][i]; // Units: dimensionless; Initial value: 6.99215e-7 NekDouble var_chaste_interface__L_type_Ca_current__C_Ca2 = inarray[17][i]; // Units: dimensionless; Initial value: 6.71989e-11 NekDouble var_chaste_interface__L_type_Ca_current__C_Ca3 = inarray[18][i]; // Units: dimensionless; Initial value: 2.87031e-15 NekDouble var_chaste_interface__L_type_Ca_current__C_Ca4 = inarray[19][i]; // Units: dimensionless; Initial value: 4.59752e-20 NekDouble var_chaste_interface__L_type_Ca_current_y_gate__y = inarray[20][i]; // Units: dimensionless; Initial value: 0.798 NekDouble var_chaste_interface__RyR_channel__P_O1 = inarray[21][i]; // Units: dimensionless; Initial value: 0 NekDouble var_chaste_interface__RyR_channel__P_O2 = inarray[22][i]; // Units: dimensionless; Initial value: 0 NekDouble var_chaste_interface__RyR_channel__P_C1 = inarray[23][i]; // Units: dimensionless; Initial value: 0.47 NekDouble var_chaste_interface__RyR_channel__P_C2 = inarray[24][i]; // Units: dimensionless; Initial value: 0.53 NekDouble var_chaste_interface__intracellular_Ca_fluxes__HTRPNCa = inarray[25][i]; // Units: millimolar; Initial value: 0.98 NekDouble var_chaste_interface__intracellular_Ca_fluxes__LTRPNCa = inarray[26][i]; // Units: millimolar; Initial value: 0.078 NekDouble var_chaste_interface__intracellular_ion_concentrations__Nai = inarray[27][i]; // Units: millimolar; Initial value: 10 NekDouble var_chaste_interface__intracellular_ion_concentrations__Cai = inarray[28][i]; // Units: millimolar; Initial value: 0.00008 NekDouble var_chaste_interface__intracellular_ion_concentrations__Ki = inarray[29][i]; // Units: millimolar; Initial value: 157.8 NekDouble var_chaste_interface__intracellular_ion_concentrations__Ca_ss = inarray[30][i]; // Units: millimolar; Initial value: 0.00011 NekDouble var_chaste_interface__intracellular_ion_concentrations__Ca_JSR = inarray[31][i]; // Units: millimolar; Initial value: 0.257 NekDouble var_chaste_interface__intracellular_ion_concentrations__Ca_NSR = inarray[32][i]; // Units: millimolar; Initial value: 0.257 // Mathematics NekDouble d_dt_chaste_interface__membrane__V; const NekDouble var_membrane__R = 8.314472; // joule_per_mole_kelvin const NekDouble var_membrane__T = 310.0; // kelvin const NekDouble var_membrane__F = 96.4853415; // coulomb_per_millimole const NekDouble var_fast_sodium_current__j = var_chaste_interface__fast_sodium_current_j_gate__j; // dimensionless const NekDouble var_fast_sodium_current__h = var_chaste_interface__fast_sodium_current_h_gate__h; // dimensionless const NekDouble var_fast_sodium_current__g_Na = 12.8; // milliS_per_microF const NekDouble var_fast_sodium_current__m = var_chaste_interface__fast_sodium_current_m_gate__m; // dimensionless const NekDouble var_fast_sodium_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_fast_sodium_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_fast_sodium_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_standard_ionic_concentrations__Nao = 138.0; // millimolar const NekDouble var_fast_sodium_current__Nao = var_standard_ionic_concentrations__Nao; // millimolar const NekDouble var_fast_sodium_current__Nai = var_chaste_interface__intracellular_ion_concentrations__Nai; // millimolar const NekDouble var_fast_sodium_current__T = var_membrane__T; // kelvin const NekDouble var_fast_sodium_current__E_Na = ((var_fast_sodium_current__R * var_fast_sodium_current__T) / var_fast_sodium_current__F) * log(var_fast_sodium_current__Nao / var_fast_sodium_current__Nai); // millivolt const NekDouble var_fast_sodium_current__i_Na = var_fast_sodium_current__g_Na * pow(var_fast_sodium_current__m, 3.0) * var_fast_sodium_current__h * var_fast_sodium_current__j * (var_fast_sodium_current__V - var_fast_sodium_current__E_Na); // microA_per_microF const NekDouble var_L_type_Ca_current__O = var_chaste_interface__L_type_Ca_current__O; // dimensionless const NekDouble var_L_type_Ca_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_L_type_Ca_current__P_Ca = 0.0003125; // cm_per_second const NekDouble var_standard_ionic_concentrations__Cao = 2.0; // millimolar const NekDouble var_L_type_Ca_current__Cao = var_standard_ionic_concentrations__Cao; // millimolar const NekDouble var_L_type_Ca_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_L_type_Ca_current__T = var_membrane__T; // kelvin const NekDouble var_L_type_Ca_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_L_type_Ca_current__i_Ca_max = ((((var_L_type_Ca_current__P_Ca / (1.0 * 1.0)) * 4.0 * var_L_type_Ca_current__V * pow(var_L_type_Ca_current__F, 2.0) * 1000.0) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T)) * ((0.001 * exp((2.0 * var_L_type_Ca_current__V * var_L_type_Ca_current__F) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T))) - (0.341 * var_L_type_Ca_current__Cao))) / (exp((2.0 * var_L_type_Ca_current__V * var_L_type_Ca_current__F) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T)) - 1.0); // microA_per_microF const NekDouble var_L_type_Ca_current__y = var_chaste_interface__L_type_Ca_current_y_gate__y; // dimensionless const NekDouble var_L_type_Ca_current__O_Ca = var_chaste_interface__L_type_Ca_current__O_Ca; // dimensionless const NekDouble var_L_type_Ca_current__i_Ca = var_L_type_Ca_current__i_Ca_max * var_L_type_Ca_current__y * (var_L_type_Ca_current__O + var_L_type_Ca_current__O_Ca); // microA_per_microF const NekDouble var_L_type_Ca_current__P_K = 5.79e-07; // cm_per_second const NekDouble var_L_type_Ca_current__i_Ca_half = -0.265; // microA_per_microF const NekDouble var_L_type_Ca_current__p_prime_k = var_L_type_Ca_current__P_K / (1.0 + (var_L_type_Ca_current__i_Ca_max / var_L_type_Ca_current__i_Ca_half)); // cm_per_second const NekDouble var_standard_ionic_concentrations__Ko = 4.0; // millimolar const NekDouble var_L_type_Ca_current__Ko = var_standard_ionic_concentrations__Ko; // millimolar const NekDouble var_L_type_Ca_current__Ki = var_chaste_interface__intracellular_ion_concentrations__Ki; // millimolar const NekDouble var_L_type_Ca_current__i_Ca_K = ((((var_L_type_Ca_current__p_prime_k / (1.0 * 1.0)) * var_L_type_Ca_current__y * (var_L_type_Ca_current__O + var_L_type_Ca_current__O_Ca) * var_L_type_Ca_current__V * pow(var_L_type_Ca_current__F, 2.0)) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T)) * ((var_L_type_Ca_current__Ki * exp((var_L_type_Ca_current__V * var_L_type_Ca_current__F) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T))) - var_L_type_Ca_current__Ko)) / (exp((var_L_type_Ca_current__V * var_L_type_Ca_current__F) / (var_L_type_Ca_current__R * var_L_type_Ca_current__T)) - 1.0); // microA_per_microF const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__Ko = var_standard_ionic_concentrations__Ko; // millimolar const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__f_Ko = sqrt(var_rapid_activating_delayed_rectifiyer_K_current__Ko / 4.0); // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__Ki = var_chaste_interface__intracellular_ion_concentrations__Ki; // millimolar const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__T = var_membrane__T; // kelvin const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__E_K = ((var_rapid_activating_delayed_rectifiyer_K_current__R * var_rapid_activating_delayed_rectifiyer_K_current__T) / var_rapid_activating_delayed_rectifiyer_K_current__F) * log(var_rapid_activating_delayed_rectifiyer_K_current__Ko / var_rapid_activating_delayed_rectifiyer_K_current__Ki); // millivolt const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__R_V = 1.0 / (1.0 + (1.4945 * exp(0.0446 * var_rapid_activating_delayed_rectifiyer_K_current__V))); // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__X_kr = var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr; // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__g_Kr = 0.0034; // milliS_per_microF const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__i_Kr = var_rapid_activating_delayed_rectifiyer_K_current__g_Kr * var_rapid_activating_delayed_rectifiyer_K_current__f_Ko * var_rapid_activating_delayed_rectifiyer_K_current__R_V * var_rapid_activating_delayed_rectifiyer_K_current__X_kr * (var_rapid_activating_delayed_rectifiyer_K_current__V - var_rapid_activating_delayed_rectifiyer_K_current__E_K); // microA_per_microF const NekDouble var_slow_activating_delayed_rectifiyer_K_current__g_Ks = 0.0027134; // milliS_per_microF const NekDouble var_slow_activating_delayed_rectifiyer_K_current__Ko = var_standard_ionic_concentrations__Ko; // millimolar const NekDouble var_slow_activating_delayed_rectifiyer_K_current__Nao = var_standard_ionic_concentrations__Nao; // millimolar const NekDouble var_slow_activating_delayed_rectifiyer_K_current__Ki = var_chaste_interface__intracellular_ion_concentrations__Ki; // millimolar const NekDouble var_slow_activating_delayed_rectifiyer_K_current__Nai = var_chaste_interface__intracellular_ion_concentrations__Nai; // millimolar const NekDouble var_slow_activating_delayed_rectifiyer_K_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_slow_activating_delayed_rectifiyer_K_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_slow_activating_delayed_rectifiyer_K_current__T = var_membrane__T; // kelvin const NekDouble var_slow_activating_delayed_rectifiyer_K_current__E_Ks = ((var_slow_activating_delayed_rectifiyer_K_current__R * var_slow_activating_delayed_rectifiyer_K_current__T) / var_slow_activating_delayed_rectifiyer_K_current__F) * log((var_slow_activating_delayed_rectifiyer_K_current__Ko + (0.01833 * var_slow_activating_delayed_rectifiyer_K_current__Nao)) / (var_slow_activating_delayed_rectifiyer_K_current__Ki + (0.01833 * var_slow_activating_delayed_rectifiyer_K_current__Nai))); // millivolt const NekDouble var_slow_activating_delayed_rectifiyer_K_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_slow_activating_delayed_rectifiyer_K_current__X_ks = var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks; // dimensionless const NekDouble var_slow_activating_delayed_rectifiyer_K_current__i_Ks = var_slow_activating_delayed_rectifiyer_K_current__g_Ks * pow(var_slow_activating_delayed_rectifiyer_K_current__X_ks, 2.0) * (var_slow_activating_delayed_rectifiyer_K_current__V - var_slow_activating_delayed_rectifiyer_K_current__E_Ks); // microA_per_microF const NekDouble var_transient_outward_potassium_current__X_to1 = var_chaste_interface__transient_outward_potassium_current_X_to1_gate__X_to1; // dimensionless const NekDouble var_transient_outward_potassium_current__Y_to1 = var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__Y_to1; // dimensionless const NekDouble var_transient_outward_potassium_current__g_to1 = 0.23815; // milliS_per_microF const NekDouble var_transient_outward_potassium_current__E_K = var_rapid_activating_delayed_rectifiyer_K_current__E_K; // millivolt const NekDouble var_transient_outward_potassium_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_transient_outward_potassium_current__i_to1 = var_transient_outward_potassium_current__g_to1 * var_transient_outward_potassium_current__X_to1 * var_transient_outward_potassium_current__Y_to1 * (var_transient_outward_potassium_current__V - var_transient_outward_potassium_current__E_K); // microA_per_microF const NekDouble var_time_independent_potassium_current__Ko = var_standard_ionic_concentrations__Ko; // millimolar const NekDouble var_time_independent_potassium_current__E_K = var_rapid_activating_delayed_rectifiyer_K_current__E_K; // millivolt const NekDouble var_time_independent_potassium_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_time_independent_potassium_current_K1_gate__F = var_time_independent_potassium_current__F; // coulomb_per_millimole const NekDouble var_time_independent_potassium_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_time_independent_potassium_current_K1_gate__V = var_time_independent_potassium_current__V; // millivolt const NekDouble var_time_independent_potassium_current__T = var_membrane__T; // kelvin const NekDouble var_time_independent_potassium_current_K1_gate__T = var_time_independent_potassium_current__T; // kelvin const NekDouble var_time_independent_potassium_current_K1_gate__E_K = var_time_independent_potassium_current__E_K; // millivolt const NekDouble var_time_independent_potassium_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_time_independent_potassium_current_K1_gate__R = var_time_independent_potassium_current__R; // joule_per_mole_kelvin const NekDouble var_time_independent_potassium_current_K1_gate__K1_infinity_V = 1.0 / (2.0 + exp(((1.5 * var_time_independent_potassium_current_K1_gate__F) / (var_time_independent_potassium_current_K1_gate__R * var_time_independent_potassium_current_K1_gate__T)) * (var_time_independent_potassium_current_K1_gate__V - var_time_independent_potassium_current_K1_gate__E_K))); // dimensionless const NekDouble var_time_independent_potassium_current__K1_infinity_V = var_time_independent_potassium_current_K1_gate__K1_infinity_V; // dimensionless const NekDouble var_time_independent_potassium_current__g_K1 = 2.8; // milliS_per_microF const NekDouble var_time_independent_potassium_current__K_mK1 = 13.0; // millimolar const NekDouble var_time_independent_potassium_current__i_K1 = ((var_time_independent_potassium_current__g_K1 * var_time_independent_potassium_current__K1_infinity_V * var_time_independent_potassium_current__Ko) / (var_time_independent_potassium_current__Ko + var_time_independent_potassium_current__K_mK1)) * (var_time_independent_potassium_current__V - var_time_independent_potassium_current__E_K); // microA_per_microF const NekDouble var_plateau_potassium_current__g_Kp = 0.002216; // milliS_per_microF const NekDouble var_plateau_potassium_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_plateau_potassium_current_Kp_gate__V = var_plateau_potassium_current__V; // millivolt const NekDouble var_plateau_potassium_current_Kp_gate__Kp_V = 1.0 / (1.0 + exp((7.488 - var_plateau_potassium_current_Kp_gate__V) / 5.98)); // dimensionless const NekDouble var_plateau_potassium_current__Kp_V = var_plateau_potassium_current_Kp_gate__Kp_V; // dimensionless const NekDouble var_plateau_potassium_current__E_K = var_rapid_activating_delayed_rectifiyer_K_current__E_K; // millivolt const NekDouble var_plateau_potassium_current__i_Kp = var_plateau_potassium_current__g_Kp * var_plateau_potassium_current__Kp_V * (var_plateau_potassium_current__V - var_plateau_potassium_current__E_K); // microA_per_microF const NekDouble var_Na_Ca_exchanger__Nao = var_standard_ionic_concentrations__Nao; // millimolar const NekDouble var_Na_Ca_exchanger__K_sat = 0.2; // dimensionless const NekDouble var_Na_Ca_exchanger__K_mNa = 87.5; // millimolar const NekDouble var_Na_Ca_exchanger__Nai = var_chaste_interface__intracellular_ion_concentrations__Nai; // millimolar const NekDouble var_Na_Ca_exchanger__K_NaCa = 0.3; // microA_per_microF const NekDouble var_Na_Ca_exchanger__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_Na_Ca_exchanger__T = var_membrane__T; // kelvin const NekDouble var_Na_Ca_exchanger__Cao = var_standard_ionic_concentrations__Cao; // millimolar const NekDouble var_Na_Ca_exchanger__eta = 0.35; // dimensionless const NekDouble var_Na_Ca_exchanger__K_mCa = 1.38; // millimolar const NekDouble var_Na_Ca_exchanger__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_Na_Ca_exchanger__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_Na_Ca_exchanger__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_Na_Ca_exchanger__i_NaCa = ((var_Na_Ca_exchanger__K_NaCa * 5000.0) / ((pow(var_Na_Ca_exchanger__K_mNa, 3.0) + pow(var_Na_Ca_exchanger__Nao, 3.0)) * (var_Na_Ca_exchanger__K_mCa + var_Na_Ca_exchanger__Cao) * (1.0 + (var_Na_Ca_exchanger__K_sat * exp(((var_Na_Ca_exchanger__eta - 1.0) * var_Na_Ca_exchanger__V * var_Na_Ca_exchanger__F) / (var_Na_Ca_exchanger__R * var_Na_Ca_exchanger__T)))))) * ((exp((var_Na_Ca_exchanger__eta * var_Na_Ca_exchanger__V * var_Na_Ca_exchanger__F) / (var_Na_Ca_exchanger__R * var_Na_Ca_exchanger__T)) * pow(var_Na_Ca_exchanger__Nai, 3.0) * var_Na_Ca_exchanger__Cao) - (exp(((var_Na_Ca_exchanger__eta - 1.0) * var_Na_Ca_exchanger__V * var_Na_Ca_exchanger__F) / (var_Na_Ca_exchanger__R * var_Na_Ca_exchanger__T)) * pow(var_Na_Ca_exchanger__Nao, 3.0) * var_Na_Ca_exchanger__Cai)); // microA_per_microF const NekDouble var_sodium_potassium_pump__Ko = var_standard_ionic_concentrations__Ko; // millimolar const NekDouble var_sodium_potassium_pump__K_mNai = 10.0; // millimolar const NekDouble var_sodium_potassium_pump__Nai = var_chaste_interface__intracellular_ion_concentrations__Nai; // millimolar const NekDouble var_sodium_potassium_pump__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_sodium_potassium_pump__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_sodium_potassium_pump__T = var_membrane__T; // kelvin const NekDouble var_sodium_potassium_pump__Nao = var_standard_ionic_concentrations__Nao; // millimolar const NekDouble var_sodium_potassium_pump__sigma = (1.0 / 7.0) * (exp(var_sodium_potassium_pump__Nao / 67.3) - 1.0); // dimensionless const NekDouble var_sodium_potassium_pump__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_sodium_potassium_pump__f_NaK = 1.0 / (1.0 + (0.1245 * exp(((-0.1) * var_sodium_potassium_pump__V * var_sodium_potassium_pump__F) / (var_sodium_potassium_pump__R * var_sodium_potassium_pump__T))) + (0.0365 * var_sodium_potassium_pump__sigma * exp(((-var_sodium_potassium_pump__V) * var_sodium_potassium_pump__F) / (var_sodium_potassium_pump__R * var_sodium_potassium_pump__T)))); // dimensionless const NekDouble var_sodium_potassium_pump__I_NaK = 0.693; // microA_per_microF const NekDouble var_sodium_potassium_pump__K_mKo = 1.5; // millimolar const NekDouble var_sodium_potassium_pump__i_NaK = (((var_sodium_potassium_pump__I_NaK * var_sodium_potassium_pump__f_NaK) / (1.0 + pow(var_sodium_potassium_pump__K_mNai / var_sodium_potassium_pump__Nai, 1.5))) * var_sodium_potassium_pump__Ko) / (var_sodium_potassium_pump__Ko + var_sodium_potassium_pump__K_mKo); // microA_per_microF const NekDouble var_sarcolemmal_calcium_pump__I_pCa = 0.05; // microA_per_microF const NekDouble var_sarcolemmal_calcium_pump__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_sarcolemmal_calcium_pump__K_mpCa = 5e-05; // millimolar const NekDouble var_sarcolemmal_calcium_pump__i_p_Ca = (var_sarcolemmal_calcium_pump__I_pCa * var_sarcolemmal_calcium_pump__Cai) / (var_sarcolemmal_calcium_pump__K_mpCa + var_sarcolemmal_calcium_pump__Cai); // microA_per_microF const NekDouble var_calcium_background_current__R = var_membrane__R; // joule_per_mole_kelvin const NekDouble var_calcium_background_current__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_calcium_background_current__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_calcium_background_current__T = var_membrane__T; // kelvin const NekDouble var_calcium_background_current__Cao = var_standard_ionic_concentrations__Cao; // millimolar const NekDouble var_calcium_background_current__E_Ca = ((var_calcium_background_current__R * var_calcium_background_current__T) / (2.0 * var_calcium_background_current__F)) * log(var_calcium_background_current__Cao / var_calcium_background_current__Cai); // millivolt const NekDouble var_calcium_background_current__g_Cab = 0.0003842; // milliS_per_microF const NekDouble var_calcium_background_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_calcium_background_current__i_Ca_b = var_calcium_background_current__g_Cab * (var_calcium_background_current__V - var_calcium_background_current__E_Ca); // microA_per_microF const NekDouble var_sodium_background_current__g_Nab = 0.0031; // milliS_per_microF const NekDouble var_sodium_background_current__V = var_chaste_interface__membrane__V; // millivolt const NekDouble var_sodium_background_current__E_Na = var_fast_sodium_current__E_Na; // millivolt const NekDouble var_sodium_background_current__i_Na_b = var_sodium_background_current__g_Nab * (var_sodium_background_current__V - var_sodium_background_current__E_Na); // microA_per_microF const NekDouble var_fast_sodium_current_m_gate__V = var_fast_sodium_current__V; // millivolt const NekDouble var_fast_sodium_current_m_gate__beta_m = 80.0 * exp((-var_fast_sodium_current_m_gate__V) / 11.0); // per_second const NekDouble var_fast_sodium_current_m_gate__E0_m = var_fast_sodium_current_m_gate__V + 47.13; // millivolt const NekDouble var_fast_sodium_current_m_gate__alpha_m = (fabs(var_fast_sodium_current_m_gate__E0_m) < 1e-05) ? (1000.0 / (0.1 - (0.005 * var_fast_sodium_current_m_gate__E0_m))) : ((320.0 * var_fast_sodium_current_m_gate__E0_m) / (1.0 - exp((-0.1) * var_fast_sodium_current_m_gate__E0_m))); // per_second const NekDouble var_fast_sodium_current_m_gate__m = var_fast_sodium_current__m; // dimensionless const NekDouble var_fast_sodium_current_m_gate__d_m_d_environment__time = (var_fast_sodium_current_m_gate__V >= (-90.0)) ? ((var_fast_sodium_current_m_gate__alpha_m * (1.0 - var_fast_sodium_current_m_gate__m)) - (var_fast_sodium_current_m_gate__beta_m * var_fast_sodium_current_m_gate__m)) : 0.0; // per_second const NekDouble var_fast_sodium_current__fast_sodium_current_m_gate__d_m_d_environment__time = var_fast_sodium_current_m_gate__d_m_d_environment__time; // per_second const NekDouble var_fast_sodium_current_h_gate__V = var_fast_sodium_current__V; // millivolt const NekDouble var_fast_sodium_current_h_gate__beta_h = (var_fast_sodium_current_h_gate__V < (-40.0)) ? ((3560.0 * exp(0.079 * var_fast_sodium_current_h_gate__V)) + (310000.0 * exp(0.35 * var_fast_sodium_current_h_gate__V))) : (1000.0 / (0.13 * (1.0 + exp((var_fast_sodium_current_h_gate__V + 10.66) / (-11.1))))); // per_second const NekDouble var_fast_sodium_current_h_gate__alpha_h = (var_fast_sodium_current_h_gate__V < (-40.0)) ? (135.0 * exp((80.0 + var_fast_sodium_current_h_gate__V) / (-6.8))) : 0.0; // per_second const NekDouble var_fast_sodium_current_h_gate__h = var_fast_sodium_current__h; // dimensionless const NekDouble var_fast_sodium_current_h_gate__d_h_d_environment__time = (var_fast_sodium_current_h_gate__alpha_h * (1.0 - var_fast_sodium_current_h_gate__h)) - (var_fast_sodium_current_h_gate__beta_h * var_fast_sodium_current_h_gate__h); // per_second const NekDouble var_fast_sodium_current__fast_sodium_current_h_gate__d_h_d_environment__time = var_fast_sodium_current_h_gate__d_h_d_environment__time; // per_second const NekDouble var_fast_sodium_current_j_gate__V = var_fast_sodium_current__V; // millivolt const NekDouble var_fast_sodium_current_j_gate__alpha_j = (var_fast_sodium_current_j_gate__V < (-40.0)) ? ((1000.0 * (-((127140.0 * exp(0.2444 * var_fast_sodium_current_j_gate__V)) + (3.474e-05 * exp((-0.04391) * var_fast_sodium_current_j_gate__V)))) * (var_fast_sodium_current_j_gate__V + 37.78)) / (1.0 + exp(0.311 * (var_fast_sodium_current_j_gate__V + 79.23)))) : 0.0; // per_second const NekDouble var_fast_sodium_current_j_gate__beta_j = (var_fast_sodium_current_j_gate__V < (-40.0)) ? ((121.2 * exp((-0.01052) * var_fast_sodium_current_j_gate__V)) / (1.0 + exp((-0.1378) * (var_fast_sodium_current_j_gate__V + 40.14)))) : ((300.0 * exp((-2.535e-07) * var_fast_sodium_current_j_gate__V)) / (1.0 + exp((-0.1) * (var_fast_sodium_current_j_gate__V + 32.0)))); // per_second const NekDouble var_fast_sodium_current_j_gate__j = var_fast_sodium_current__j; // dimensionless const NekDouble var_fast_sodium_current_j_gate__d_j_d_environment__time = (var_fast_sodium_current_j_gate__alpha_j * (1.0 - var_fast_sodium_current_j_gate__j)) - (var_fast_sodium_current_j_gate__beta_j * var_fast_sodium_current_j_gate__j); // per_second const NekDouble var_fast_sodium_current__fast_sodium_current_j_gate__d_j_d_environment__time = var_fast_sodium_current_j_gate__d_j_d_environment__time; // per_second const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__tau_factor = 1.0; // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__V = var_rapid_activating_delayed_rectifiyer_K_current__V; // millivolt const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K21 = exp((-7.677) - (0.0128 * var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__V)); // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K12 = exp((-5.495) + (0.1691 * var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__V)); // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__tau_X_kr = (0.001 / (var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K12 + var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K21)) + (var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__tau_factor * 0.027); // second const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr = var_rapid_activating_delayed_rectifiyer_K_current__X_kr; // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr_inf = var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K12 / (var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K12 + var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__K21); // dimensionless const NekDouble var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time = (var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr_inf - var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr) / var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__tau_X_kr; // per_second const NekDouble var_rapid_activating_delayed_rectifiyer_K_current__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time = var_rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time; // per_second const NekDouble var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V = var_slow_activating_delayed_rectifiyer_K_current__V; // millivolt const NekDouble var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__tau_X_ks = 0.001 / (((7.19e-05 * (var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V - 10.0)) / (1.0 - exp((-0.148) * (var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V - 10.0)))) + ((0.000131 * (var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V - 10.0)) / (exp(0.0687 * (var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V - 10.0)) - 1.0))); // second const NekDouble var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks_infinity = 1.0 / (1.0 + exp((-(var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__V - 24.7)) / 13.6)); // dimensionless const NekDouble var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks = var_slow_activating_delayed_rectifiyer_K_current__X_ks; // dimensionless const NekDouble var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time = (var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks_infinity - var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks) / var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__tau_X_ks; // per_second const NekDouble var_slow_activating_delayed_rectifiyer_K_current__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time = var_slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time; // per_second const NekDouble var_transient_outward_potassium_current_X_to1_gate__V = var_transient_outward_potassium_current__V; // millivolt const NekDouble var_transient_outward_potassium_current_X_to1_gate__alpha_X_to1 = 45.16 * exp(0.03577 * var_transient_outward_potassium_current_X_to1_gate__V); // per_second const NekDouble var_transient_outward_potassium_current_X_to1_gate__X_to1 = var_transient_outward_potassium_current__X_to1; // dimensionless const NekDouble var_transient_outward_potassium_current_X_to1_gate__beta_X_to1 = 98.9 * exp((-0.06237) * var_transient_outward_potassium_current_X_to1_gate__V); // per_second const NekDouble var_transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time = (var_transient_outward_potassium_current_X_to1_gate__alpha_X_to1 * (1.0 - var_transient_outward_potassium_current_X_to1_gate__X_to1)) - (var_transient_outward_potassium_current_X_to1_gate__beta_X_to1 * var_transient_outward_potassium_current_X_to1_gate__X_to1); // per_second const NekDouble var_transient_outward_potassium_current__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time = var_transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time; // per_second const NekDouble var_transient_outward_potassium_current_Y_to1_gate__V = var_transient_outward_potassium_current__V; // millivolt const NekDouble var_transient_outward_potassium_current_Y_to1_gate__alpha_Y_to1 = (5.415 * exp((-(var_transient_outward_potassium_current_Y_to1_gate__V + 33.5)) / 5.0)) / (1.0 + (0.051335 * exp((-(var_transient_outward_potassium_current_Y_to1_gate__V + 33.5)) / 5.0))); // per_second const NekDouble var_transient_outward_potassium_current_Y_to1_gate__Y_to1 = var_transient_outward_potassium_current__Y_to1; // dimensionless const NekDouble var_transient_outward_potassium_current_Y_to1_gate__beta_Y_to1 = (5.415 * exp((var_transient_outward_potassium_current_Y_to1_gate__V + 33.5) / 5.0)) / (1.0 + (0.051335 * exp((var_transient_outward_potassium_current_Y_to1_gate__V + 33.5) / 5.0))); // per_second const NekDouble var_transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time = (var_transient_outward_potassium_current_Y_to1_gate__alpha_Y_to1 * (1.0 - var_transient_outward_potassium_current_Y_to1_gate__Y_to1)) - (var_transient_outward_potassium_current_Y_to1_gate__beta_Y_to1 * var_transient_outward_potassium_current_Y_to1_gate__Y_to1); // per_second const NekDouble var_transient_outward_potassium_current__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time = var_transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time; // per_second const NekDouble var_L_type_Ca_current__alpha = 400.0 * exp((var_L_type_Ca_current__V + 2.0) / 10.0); // per_second const NekDouble var_L_type_Ca_current__beta = 50.0 * exp((-(var_L_type_Ca_current__V + 2.0)) / 13.0); // per_second const NekDouble var_L_type_Ca_current__Ca_ss = var_chaste_interface__intracellular_ion_concentrations__Ca_ss; // millimolar const NekDouble var_L_type_Ca_current__gamma = (103.75 * var_L_type_Ca_current__Ca_ss) / 1.0; // per_second const NekDouble var_L_type_Ca_current__a = 2.0; // dimensionless const NekDouble var_L_type_Ca_current__alpha_a = var_L_type_Ca_current__alpha * var_L_type_Ca_current__a; // per_second const NekDouble var_L_type_Ca_current__b = 2.0; // dimensionless const NekDouble var_L_type_Ca_current__beta_b = var_L_type_Ca_current__beta / var_L_type_Ca_current__b; // per_second const NekDouble var_L_type_Ca_current__g = 2000.0; // per_second const NekDouble var_L_type_Ca_current__f = 300.0; // per_second const NekDouble var_L_type_Ca_current__gprime = 7000.0; // per_second const NekDouble var_L_type_Ca_current__fprime = 7.0; // per_second const NekDouble var_L_type_Ca_current__omega = 10.0; // per_second const NekDouble var_L_type_Ca_current__C0 = var_chaste_interface__L_type_Ca_current__C0; // dimensionless const NekDouble var_L_type_Ca_current__C1 = var_chaste_interface__L_type_Ca_current__C1; // dimensionless const NekDouble var_L_type_Ca_current__C2 = var_chaste_interface__L_type_Ca_current__C2; // dimensionless const NekDouble var_L_type_Ca_current__C3 = var_chaste_interface__L_type_Ca_current__C3; // dimensionless const NekDouble var_L_type_Ca_current__C4 = var_chaste_interface__L_type_Ca_current__C4; // dimensionless const NekDouble var_L_type_Ca_current__C_Ca0 = var_chaste_interface__L_type_Ca_current__C_Ca0; // dimensionless const NekDouble var_L_type_Ca_current__C_Ca1 = var_chaste_interface__L_type_Ca_current__C_Ca1; // dimensionless const NekDouble var_L_type_Ca_current__C_Ca2 = var_chaste_interface__L_type_Ca_current__C_Ca2; // dimensionless const NekDouble var_L_type_Ca_current__C_Ca3 = var_chaste_interface__L_type_Ca_current__C_Ca3; // dimensionless const NekDouble var_L_type_Ca_current__C_Ca4 = var_chaste_interface__L_type_Ca_current__C_Ca4; // dimensionless const NekDouble var_L_type_Ca_current__d_O_d_environment__time = (var_L_type_Ca_current__f * var_L_type_Ca_current__C4) - (var_L_type_Ca_current__g * var_L_type_Ca_current__O); // per_second const NekDouble var_L_type_Ca_current__d_O_Ca_d_environment__time = (var_L_type_Ca_current__fprime * var_L_type_Ca_current__C_Ca4) - (var_L_type_Ca_current__gprime * var_L_type_Ca_current__O_Ca); // per_second const NekDouble var_L_type_Ca_current__d_C0_d_environment__time = ((var_L_type_Ca_current__beta * var_L_type_Ca_current__C1) + (var_L_type_Ca_current__omega * var_L_type_Ca_current__C_Ca0)) - (((4.0 * var_L_type_Ca_current__alpha) + var_L_type_Ca_current__gamma) * var_L_type_Ca_current__C0); // per_second const NekDouble var_L_type_Ca_current__d_C1_d_environment__time = ((4.0 * var_L_type_Ca_current__alpha * var_L_type_Ca_current__C0) + (2.0 * var_L_type_Ca_current__beta * var_L_type_Ca_current__C2) + ((var_L_type_Ca_current__omega / var_L_type_Ca_current__b) * var_L_type_Ca_current__C_Ca1)) - ((var_L_type_Ca_current__beta + (3.0 * var_L_type_Ca_current__alpha) + (var_L_type_Ca_current__gamma * var_L_type_Ca_current__a)) * var_L_type_Ca_current__C1); // per_second const NekDouble var_L_type_Ca_current__d_C2_d_environment__time = ((3.0 * var_L_type_Ca_current__alpha * var_L_type_Ca_current__C1) + (3.0 * var_L_type_Ca_current__beta * var_L_type_Ca_current__C3) + ((var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 2.0)) * var_L_type_Ca_current__C_Ca2)) - (((var_L_type_Ca_current__beta * 2.0) + (2.0 * var_L_type_Ca_current__alpha) + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 2.0))) * var_L_type_Ca_current__C2); // per_second const NekDouble var_L_type_Ca_current__d_C3_d_environment__time = ((2.0 * var_L_type_Ca_current__alpha * var_L_type_Ca_current__C2) + (4.0 * var_L_type_Ca_current__beta * var_L_type_Ca_current__C4) + ((var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 3.0)) * var_L_type_Ca_current__C_Ca3)) - (((var_L_type_Ca_current__beta * 3.0) + var_L_type_Ca_current__alpha + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 3.0))) * var_L_type_Ca_current__C3); // per_second const NekDouble var_L_type_Ca_current__d_C4_d_environment__time = ((var_L_type_Ca_current__alpha * var_L_type_Ca_current__C3) + (var_L_type_Ca_current__g * var_L_type_Ca_current__O) + ((var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 4.0)) * var_L_type_Ca_current__C_Ca4)) - (((var_L_type_Ca_current__beta * 4.0) + var_L_type_Ca_current__f + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 4.0))) * var_L_type_Ca_current__C4); // per_second const NekDouble var_L_type_Ca_current__d_C_Ca0_d_environment__time = ((var_L_type_Ca_current__beta_b * var_L_type_Ca_current__C_Ca1) + (var_L_type_Ca_current__gamma * var_L_type_Ca_current__C0)) - (((4.0 * var_L_type_Ca_current__alpha_a) + var_L_type_Ca_current__omega) * var_L_type_Ca_current__C_Ca0); // per_second const NekDouble var_L_type_Ca_current__d_C_Ca1_d_environment__time = ((4.0 * var_L_type_Ca_current__alpha_a * var_L_type_Ca_current__C_Ca0) + (2.0 * var_L_type_Ca_current__beta_b * var_L_type_Ca_current__C_Ca2) + (var_L_type_Ca_current__gamma * var_L_type_Ca_current__a * var_L_type_Ca_current__C1)) - ((var_L_type_Ca_current__beta_b + (3.0 * var_L_type_Ca_current__alpha_a) + (var_L_type_Ca_current__omega / var_L_type_Ca_current__b)) * var_L_type_Ca_current__C_Ca1); // per_second const NekDouble var_L_type_Ca_current__d_C_Ca2_d_environment__time = ((3.0 * var_L_type_Ca_current__alpha_a * var_L_type_Ca_current__C_Ca1) + (3.0 * var_L_type_Ca_current__beta_b * var_L_type_Ca_current__C_Ca3) + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 2.0) * var_L_type_Ca_current__C2)) - (((var_L_type_Ca_current__beta_b * 2.0) + (2.0 * var_L_type_Ca_current__alpha_a) + (var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 2.0))) * var_L_type_Ca_current__C_Ca2); // per_second const NekDouble var_L_type_Ca_current__d_C_Ca3_d_environment__time = ((2.0 * var_L_type_Ca_current__alpha_a * var_L_type_Ca_current__C_Ca2) + (4.0 * var_L_type_Ca_current__beta_b * var_L_type_Ca_current__C_Ca4) + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 3.0) * var_L_type_Ca_current__C3)) - (((var_L_type_Ca_current__beta_b * 3.0) + var_L_type_Ca_current__alpha_a + (var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 3.0))) * var_L_type_Ca_current__C_Ca3); // per_second const NekDouble var_L_type_Ca_current__d_C_Ca4_d_environment__time = ((var_L_type_Ca_current__alpha_a * var_L_type_Ca_current__C_Ca3) + (var_L_type_Ca_current__gprime * var_L_type_Ca_current__O_Ca) + (var_L_type_Ca_current__gamma * pow(var_L_type_Ca_current__a, 4.0) * var_L_type_Ca_current__C4)) - (((var_L_type_Ca_current__beta_b * 4.0) + var_L_type_Ca_current__fprime + (var_L_type_Ca_current__omega / pow(var_L_type_Ca_current__b, 4.0))) * var_L_type_Ca_current__C_Ca4); // per_second const NekDouble var_L_type_Ca_current_y_gate__y = var_L_type_Ca_current__y; // dimensionless const NekDouble var_L_type_Ca_current_y_gate__V = var_L_type_Ca_current__V; // millivolt const NekDouble var_L_type_Ca_current_y_gate__y_infinity = (0.8 / (1.0 + exp((var_L_type_Ca_current_y_gate__V + 12.5) / 5.0))) + 0.2; // dimensionless const NekDouble var_L_type_Ca_current_y_gate__tau_y = (20.0 + (600.0 / (1.0 + exp((var_L_type_Ca_current_y_gate__V + 20.0) / 9.5)))) / 1000.0; // second const NekDouble var_L_type_Ca_current_y_gate__d_y_d_environment__time = (var_L_type_Ca_current_y_gate__y_infinity - var_L_type_Ca_current_y_gate__y) / var_L_type_Ca_current_y_gate__tau_y; // per_second const NekDouble var_L_type_Ca_current__L_type_Ca_current_y_gate__d_y_d_environment__time = var_L_type_Ca_current_y_gate__d_y_d_environment__time; // per_second const NekDouble var_RyR_channel__P_O2 = var_chaste_interface__RyR_channel__P_O2; // dimensionless const NekDouble var_RyR_channel__Ca_ss = var_chaste_interface__intracellular_ion_concentrations__Ca_ss; // millimolar const NekDouble var_RyR_channel__P_O1 = var_chaste_interface__RyR_channel__P_O1; // dimensionless const NekDouble var_RyR_channel__v1 = 1800.0; // per_second const NekDouble var_RyR_channel__Ca_JSR = var_chaste_interface__intracellular_ion_concentrations__Ca_JSR; // millimolar const NekDouble var_RyR_channel__J_rel = var_RyR_channel__v1 * (var_RyR_channel__P_O1 + var_RyR_channel__P_O2) * (var_RyR_channel__Ca_JSR - var_RyR_channel__Ca_ss); // millimolar_per_second const NekDouble var_RyR_channel__k_a_plus = 1.215e+13; // millimolar4_per_second const NekDouble var_RyR_channel__k_a_minus = 576.0; // per_second const NekDouble var_RyR_channel__k_b_plus = 4050000000.0; // millimolar3_per_second const NekDouble var_RyR_channel__k_b_minus = 1930.0; // per_second const NekDouble var_RyR_channel__k_c_plus = 100.0; // per_second const NekDouble var_RyR_channel__k_c_minus = 0.8; // per_second const NekDouble var_RyR_channel__P_C1 = var_chaste_interface__RyR_channel__P_C1; // dimensionless const NekDouble var_RyR_channel__P_C2 = var_chaste_interface__RyR_channel__P_C2; // dimensionless const NekDouble var_RyR_channel__n = 4.0; // dimensionless const NekDouble var_RyR_channel__m = 3.0; // dimensionless const NekDouble var_RyR_channel__d_P_O1_d_environment__time = ((var_RyR_channel__k_a_plus * pow(var_RyR_channel__Ca_ss, var_RyR_channel__n) * var_RyR_channel__P_C1) - ((var_RyR_channel__k_a_minus * var_RyR_channel__P_O1) + (var_RyR_channel__k_b_plus * pow(var_RyR_channel__Ca_ss, var_RyR_channel__m) * var_RyR_channel__P_O1) + (var_RyR_channel__k_c_plus * var_RyR_channel__P_O1))) + (var_RyR_channel__k_b_minus * var_RyR_channel__P_O2) + (var_RyR_channel__k_c_minus * var_RyR_channel__P_C2); // per_second const NekDouble var_RyR_channel__d_P_O2_d_environment__time = (var_RyR_channel__k_b_plus * pow(var_RyR_channel__Ca_ss, var_RyR_channel__m) * var_RyR_channel__P_O1) - (var_RyR_channel__k_b_minus * var_RyR_channel__P_O2); // per_second const NekDouble var_RyR_channel__d_P_C1_d_environment__time = ((-var_RyR_channel__k_a_plus) * pow(var_RyR_channel__Ca_ss, var_RyR_channel__n) * var_RyR_channel__P_C1) + (var_RyR_channel__k_a_minus * var_RyR_channel__P_O1); // per_second const NekDouble var_RyR_channel__d_P_C2_d_environment__time = (var_RyR_channel__k_c_plus * var_RyR_channel__P_O1) - (var_RyR_channel__k_c_minus * var_RyR_channel__P_C2); // per_second const NekDouble var_SERCA2a_pump__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_SERCA2a_pump__N_fb = 1.2; // dimensionless const NekDouble var_SERCA2a_pump__K_fb = 0.000168; // millimolar const NekDouble var_SERCA2a_pump__fb = pow(var_SERCA2a_pump__Cai / var_SERCA2a_pump__K_fb, var_SERCA2a_pump__N_fb); // dimensionless const NekDouble var_SERCA2a_pump__Vmaxf = 0.0813; // millimolar_per_second const NekDouble var_SERCA2a_pump__K_SR = 1.0; // dimensionless const NekDouble var_SERCA2a_pump__Ca_NSR = var_chaste_interface__intracellular_ion_concentrations__Ca_NSR; // millimolar const NekDouble var_SERCA2a_pump__K_rb = 3.29; // millimolar const NekDouble var_SERCA2a_pump__N_rb = 1.0; // dimensionless const NekDouble var_SERCA2a_pump__rb = pow(var_SERCA2a_pump__Ca_NSR / var_SERCA2a_pump__K_rb, var_SERCA2a_pump__N_rb); // dimensionless const NekDouble var_SERCA2a_pump__Vmaxr = 0.318; // millimolar_per_second const NekDouble var_SERCA2a_pump__J_up = (var_SERCA2a_pump__K_SR * ((var_SERCA2a_pump__Vmaxf * var_SERCA2a_pump__fb) - (var_SERCA2a_pump__Vmaxr * var_SERCA2a_pump__rb))) / (1.0 + var_SERCA2a_pump__fb + var_SERCA2a_pump__rb); // millimolar_per_second const NekDouble var_intracellular_Ca_fluxes__Ca_NSR = var_chaste_interface__intracellular_ion_concentrations__Ca_NSR; // millimolar const NekDouble var_intracellular_Ca_fluxes__Ca_JSR = var_chaste_interface__intracellular_ion_concentrations__Ca_JSR; // millimolar const NekDouble var_intracellular_Ca_fluxes__tau_tr = 0.0005747; // second const NekDouble var_intracellular_Ca_fluxes__J_tr = (var_intracellular_Ca_fluxes__Ca_NSR - var_intracellular_Ca_fluxes__Ca_JSR) / var_intracellular_Ca_fluxes__tau_tr; // millimolar_per_second const NekDouble var_intracellular_Ca_fluxes__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_intracellular_Ca_fluxes__tau_xfer = 0.0267; // second const NekDouble var_intracellular_Ca_fluxes__Ca_ss = var_chaste_interface__intracellular_ion_concentrations__Ca_ss; // millimolar const NekDouble var_intracellular_Ca_fluxes__J_xfer = (var_intracellular_Ca_fluxes__Ca_ss - var_intracellular_Ca_fluxes__Cai) / var_intracellular_Ca_fluxes__tau_xfer; // millimolar_per_second const NekDouble var_intracellular_Ca_fluxes__k_htrpn_minus = 0.066; // per_second const NekDouble var_intracellular_Ca_fluxes__k_htrpn_plus = 20000.0; // per_millimolar_second const NekDouble var_intracellular_Ca_fluxes__HTRPNCa = var_chaste_interface__intracellular_Ca_fluxes__HTRPNCa; // millimolar const NekDouble var_intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time = (var_intracellular_Ca_fluxes__k_htrpn_plus * var_intracellular_Ca_fluxes__Cai * (1.0 - var_intracellular_Ca_fluxes__HTRPNCa)) - (var_intracellular_Ca_fluxes__k_htrpn_minus * var_intracellular_Ca_fluxes__HTRPNCa); // 'millimole per litre per second' const NekDouble var_intracellular_Ca_fluxes__J_HTRPNCa = var_intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time; // millimolar_per_second const NekDouble var_intracellular_Ca_fluxes__LTRPN_tot = 0.07; // dimensionless const NekDouble var_intracellular_Ca_fluxes__LTRPNCa = var_chaste_interface__intracellular_Ca_fluxes__LTRPNCa; // millimolar const NekDouble var_intracellular_Ca_fluxes__k_ltrpn_minus = 40.0; // per_second const NekDouble var_intracellular_Ca_fluxes__k_ltrpn_plus = 40000.0; // per_millimolar_second const NekDouble var_intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time = (var_intracellular_Ca_fluxes__k_ltrpn_plus * var_intracellular_Ca_fluxes__Cai * (1.0 - var_intracellular_Ca_fluxes__LTRPNCa)) - (var_intracellular_Ca_fluxes__k_ltrpn_minus * var_intracellular_Ca_fluxes__LTRPNCa); // 'millimole per litre per second' const NekDouble var_intracellular_Ca_fluxes__J_LTRPNCa = var_intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time; // millimolar_per_second const NekDouble var_intracellular_Ca_fluxes__HTRPN_tot = 0.14; // dimensionless const NekDouble var_intracellular_Ca_fluxes__J_trpn = (var_intracellular_Ca_fluxes__HTRPN_tot * var_intracellular_Ca_fluxes__J_HTRPNCa) + (var_intracellular_Ca_fluxes__LTRPN_tot * var_intracellular_Ca_fluxes__J_LTRPNCa); // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__Cai = var_chaste_interface__intracellular_ion_concentrations__Cai; // millimolar const NekDouble var_intracellular_ion_concentrations__Ca_ss = var_chaste_interface__intracellular_ion_concentrations__Ca_ss; // millimolar const NekDouble var_intracellular_ion_concentrations__Ca_JSR = var_chaste_interface__intracellular_ion_concentrations__Ca_JSR; // millimolar const NekDouble var_intracellular_ion_concentrations__A_cap = 0.0001534; // cm2 const NekDouble var_intracellular_ion_concentrations__V_myo = 2.584e-05; // micro_litre const NekDouble var_intracellular_ion_concentrations__V_JSR = 1.6e-07; // micro_litre const NekDouble var_intracellular_ion_concentrations__V_NSR = 2.1e-06; // micro_litre const NekDouble var_intracellular_ion_concentrations__V_SS = 1.2e-09; // micro_litre const NekDouble var_intracellular_ion_concentrations__K_mCMDN = 0.00238; // millimolar const NekDouble var_intracellular_ion_concentrations__K_mEGTA = 0.00015; // millimolar const NekDouble var_intracellular_ion_concentrations__K_mCSQN = 0.8; // millimolar const NekDouble var_intracellular_ion_concentrations__CMDN_tot = 0.05; // millimolar const NekDouble var_intracellular_ion_concentrations__EGTA_tot = 0.0; // millimolar const NekDouble var_intracellular_ion_concentrations__CSQN_tot = 15.0; // millimolar const NekDouble var_intracellular_ion_concentrations__beta_i = 1.0 / (1.0 + ((var_intracellular_ion_concentrations__CMDN_tot * var_intracellular_ion_concentrations__K_mCMDN) / pow(var_intracellular_ion_concentrations__K_mCMDN + var_intracellular_ion_concentrations__Cai, 2.0)) + ((var_intracellular_ion_concentrations__EGTA_tot * var_intracellular_ion_concentrations__K_mEGTA) / pow(var_intracellular_ion_concentrations__K_mEGTA + var_intracellular_ion_concentrations__Cai, 2.0))); // dimensionless const NekDouble var_intracellular_ion_concentrations__beta_SS = 1.0 / (1.0 + ((var_intracellular_ion_concentrations__CMDN_tot * var_intracellular_ion_concentrations__K_mCMDN) / pow(var_intracellular_ion_concentrations__K_mCMDN + var_intracellular_ion_concentrations__Ca_ss, 2.0)) + ((var_intracellular_ion_concentrations__EGTA_tot * var_intracellular_ion_concentrations__K_mEGTA) / pow(var_intracellular_ion_concentrations__K_mEGTA + var_intracellular_ion_concentrations__Ca_ss, 2.0))); // dimensionless const NekDouble var_intracellular_ion_concentrations__beta_JSR = 1.0 / (1.0 + ((var_intracellular_ion_concentrations__CSQN_tot * var_intracellular_ion_concentrations__K_mCSQN) / pow(var_intracellular_ion_concentrations__K_mCSQN + var_intracellular_ion_concentrations__Ca_JSR, 2.0))); // dimensionless const NekDouble var_intracellular_ion_concentrations__F = var_membrane__F; // coulomb_per_millimole const NekDouble var_intracellular_ion_concentrations__i_Na = var_fast_sodium_current__i_Na; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Ca = var_L_type_Ca_current__i_Ca; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Na_b = var_sodium_background_current__i_Na_b; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_NaCa = var_Na_Ca_exchanger__i_NaCa; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_NaK = var_sodium_potassium_pump__i_NaK; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Ca_K = var_L_type_Ca_current__i_Ca_K; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Kr = var_rapid_activating_delayed_rectifiyer_K_current__i_Kr; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Ks = var_slow_activating_delayed_rectifiyer_K_current__i_Ks; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_K1 = var_time_independent_potassium_current__i_K1; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Kp = var_plateau_potassium_current__i_Kp; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_to1 = var_transient_outward_potassium_current__i_to1; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_p_Ca = var_sarcolemmal_calcium_pump__i_p_Ca; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__i_Ca_b = var_calcium_background_current__i_Ca_b; // microA_per_microF const NekDouble var_intracellular_ion_concentrations__J_up = var_SERCA2a_pump__J_up; // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__J_rel = var_RyR_channel__J_rel; // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__J_xfer = var_intracellular_Ca_fluxes__J_xfer; // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__J_trpn = var_intracellular_Ca_fluxes__J_trpn; // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__J_tr = var_intracellular_Ca_fluxes__J_tr; // millimolar_per_second const NekDouble var_intracellular_ion_concentrations__d_Nai_d_environment__time = ((-0.0) * (var_intracellular_ion_concentrations__i_Na + var_intracellular_ion_concentrations__i_Na_b + (var_intracellular_ion_concentrations__i_NaCa * 3.0) + (var_intracellular_ion_concentrations__i_NaK * 3.0)) * var_intracellular_ion_concentrations__A_cap * 1.0) / (var_intracellular_ion_concentrations__V_myo * var_intracellular_ion_concentrations__F); // 'millimole per litre per second' const NekDouble var_intracellular_ion_concentrations__d_Cai_d_environment__time = var_intracellular_ion_concentrations__beta_i * ((var_intracellular_ion_concentrations__J_xfer - (var_intracellular_ion_concentrations__J_up + var_intracellular_ion_concentrations__J_trpn)) + ((((2.0 * var_intracellular_ion_concentrations__i_NaCa) - (var_intracellular_ion_concentrations__i_p_Ca + var_intracellular_ion_concentrations__i_Ca_b)) * var_intracellular_ion_concentrations__A_cap * 1.0) / (2.0 * var_intracellular_ion_concentrations__V_myo * var_intracellular_ion_concentrations__F))); // 'millimole per litre per second' const NekDouble var_intracellular_ion_concentrations__d_Ki_d_environment__time = ((-0.0) * (var_intracellular_ion_concentrations__i_Ca_K + var_intracellular_ion_concentrations__i_Kr + var_intracellular_ion_concentrations__i_Ks + var_intracellular_ion_concentrations__i_K1 + var_intracellular_ion_concentrations__i_Kp + var_intracellular_ion_concentrations__i_to1 + (var_intracellular_ion_concentrations__i_NaK * (-2.0))) * var_intracellular_ion_concentrations__A_cap * 1.0) / (var_intracellular_ion_concentrations__V_myo * var_intracellular_ion_concentrations__F); // 'millimole per litre per second' const NekDouble var_intracellular_ion_concentrations__d_Ca_ss_d_environment__time = var_intracellular_ion_concentrations__beta_SS * ((((var_intracellular_ion_concentrations__J_rel * var_intracellular_ion_concentrations__V_JSR) / var_intracellular_ion_concentrations__V_SS) - ((var_intracellular_ion_concentrations__J_xfer * var_intracellular_ion_concentrations__V_myo) / var_intracellular_ion_concentrations__V_SS)) - ((var_intracellular_ion_concentrations__i_Ca * var_intracellular_ion_concentrations__A_cap * 1.0) / (2.0 * var_intracellular_ion_concentrations__V_SS * var_intracellular_ion_concentrations__F))); // 'millimole per litre per second' const NekDouble var_intracellular_ion_concentrations__d_Ca_JSR_d_environment__time = var_intracellular_ion_concentrations__beta_JSR * (var_intracellular_ion_concentrations__J_tr - var_intracellular_ion_concentrations__J_rel); // 'millimole per litre per second' const NekDouble var_intracellular_ion_concentrations__d_Ca_NSR_d_environment__time = ((var_intracellular_ion_concentrations__J_up * var_intracellular_ion_concentrations__V_myo) / var_intracellular_ion_concentrations__V_NSR) - ((var_intracellular_ion_concentrations__J_tr * var_intracellular_ion_concentrations__V_JSR) / var_intracellular_ion_concentrations__V_NSR); // 'millimole per litre per second' const NekDouble var_chaste_interface__fast_sodium_current_m_gate__d_m_d_environment__time_converter = var_fast_sodium_current__fast_sodium_current_m_gate__d_m_d_environment__time; // per_second const NekDouble var_chaste_interface__fast_sodium_current_m_gate__d_m_d_environment__time = 0.001 * var_chaste_interface__fast_sodium_current_m_gate__d_m_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__fast_sodium_current_h_gate__d_h_d_environment__time_converter = var_fast_sodium_current__fast_sodium_current_h_gate__d_h_d_environment__time; // per_second const NekDouble var_chaste_interface__fast_sodium_current_h_gate__d_h_d_environment__time = 0.001 * var_chaste_interface__fast_sodium_current_h_gate__d_h_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__fast_sodium_current_j_gate__d_j_d_environment__time_converter = var_fast_sodium_current__fast_sodium_current_j_gate__d_j_d_environment__time; // per_second const NekDouble var_chaste_interface__fast_sodium_current_j_gate__d_j_d_environment__time = 0.001 * var_chaste_interface__fast_sodium_current_j_gate__d_j_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time_converter = var_rapid_activating_delayed_rectifiyer_K_current__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time; // per_second const NekDouble var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time = 0.001 * var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time_converter = var_slow_activating_delayed_rectifiyer_K_current__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time; // per_second const NekDouble var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time = 0.001 * var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time_converter = var_transient_outward_potassium_current__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time; // per_second const NekDouble var_chaste_interface__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time = 0.001 * var_chaste_interface__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time_converter = var_transient_outward_potassium_current__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time; // per_second const NekDouble var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time = 0.001 * var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_O_d_environment__time_converter = var_L_type_Ca_current__d_O_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_O_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_O_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_O_Ca_d_environment__time_converter = var_L_type_Ca_current__d_O_Ca_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_O_Ca_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_O_Ca_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C0_d_environment__time_converter = var_L_type_Ca_current__d_C0_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C0_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C0_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C1_d_environment__time_converter = var_L_type_Ca_current__d_C1_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C1_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C2_d_environment__time_converter = var_L_type_Ca_current__d_C2_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C2_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C2_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C3_d_environment__time_converter = var_L_type_Ca_current__d_C3_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C3_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C3_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C4_d_environment__time_converter = var_L_type_Ca_current__d_C4_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C4_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C4_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca0_d_environment__time_converter = var_L_type_Ca_current__d_C_Ca0_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca0_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C_Ca0_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca1_d_environment__time_converter = var_L_type_Ca_current__d_C_Ca1_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca1_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C_Ca1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca2_d_environment__time_converter = var_L_type_Ca_current__d_C_Ca2_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca2_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C_Ca2_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca3_d_environment__time_converter = var_L_type_Ca_current__d_C_Ca3_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca3_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C_Ca3_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca4_d_environment__time_converter = var_L_type_Ca_current__d_C_Ca4_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current__d_C_Ca4_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current__d_C_Ca4_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__L_type_Ca_current_y_gate__d_y_d_environment__time_converter = var_L_type_Ca_current__L_type_Ca_current_y_gate__d_y_d_environment__time; // per_second const NekDouble var_chaste_interface__L_type_Ca_current_y_gate__d_y_d_environment__time = 0.001 * var_chaste_interface__L_type_Ca_current_y_gate__d_y_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__RyR_channel__d_P_O1_d_environment__time_converter = var_RyR_channel__d_P_O1_d_environment__time; // per_second const NekDouble var_chaste_interface__RyR_channel__d_P_O1_d_environment__time = 0.001 * var_chaste_interface__RyR_channel__d_P_O1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__RyR_channel__d_P_O2_d_environment__time_converter = var_RyR_channel__d_P_O2_d_environment__time; // per_second const NekDouble var_chaste_interface__RyR_channel__d_P_O2_d_environment__time = 0.001 * var_chaste_interface__RyR_channel__d_P_O2_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__RyR_channel__d_P_C1_d_environment__time_converter = var_RyR_channel__d_P_C1_d_environment__time; // per_second const NekDouble var_chaste_interface__RyR_channel__d_P_C1_d_environment__time = 0.001 * var_chaste_interface__RyR_channel__d_P_C1_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__RyR_channel__d_P_C2_d_environment__time_converter = var_RyR_channel__d_P_C2_d_environment__time; // per_second const NekDouble var_chaste_interface__RyR_channel__d_P_C2_d_environment__time = 0.001 * var_chaste_interface__RyR_channel__d_P_C2_d_environment__time_converter; // 'per millisecond' const NekDouble var_chaste_interface__intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time_converter = var_intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time; // ___units_89 const NekDouble var_chaste_interface__intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time = 0.001 * var_chaste_interface__intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time_converter = var_intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time = 0.001 * var_chaste_interface__intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Nai_d_environment__time_converter = var_intracellular_ion_concentrations__d_Nai_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Nai_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Nai_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Cai_d_environment__time_converter = var_intracellular_ion_concentrations__d_Cai_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Cai_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Cai_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ki_d_environment__time_converter = var_intracellular_ion_concentrations__d_Ki_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ki_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Ki_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_ss_d_environment__time_converter = var_intracellular_ion_concentrations__d_Ca_ss_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_ss_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Ca_ss_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_JSR_d_environment__time_converter = var_intracellular_ion_concentrations__d_Ca_JSR_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_JSR_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Ca_JSR_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_NSR_d_environment__time_converter = var_intracellular_ion_concentrations__d_Ca_NSR_d_environment__time; // millimole_per_litre_per_second const NekDouble var_chaste_interface__intracellular_ion_concentrations__d_Ca_NSR_d_environment__time = 0.001 * var_chaste_interface__intracellular_ion_concentrations__d_Ca_NSR_d_environment__time_converter; // 'millimolar per millisecond' const NekDouble d_dt_chaste_interface__fast_sodium_current_m_gate__m = var_chaste_interface__fast_sodium_current_m_gate__d_m_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__fast_sodium_current_h_gate__h = var_chaste_interface__fast_sodium_current_h_gate__d_h_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__fast_sodium_current_j_gate__j = var_chaste_interface__fast_sodium_current_j_gate__d_j_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr = var_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__d_X_kr_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks = var_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__d_X_ks_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__transient_outward_potassium_current_X_to1_gate__X_to1 = var_chaste_interface__transient_outward_potassium_current_X_to1_gate__d_X_to1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__transient_outward_potassium_current_Y_to1_gate__Y_to1 = var_chaste_interface__transient_outward_potassium_current_Y_to1_gate__d_Y_to1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__O = var_chaste_interface__L_type_Ca_current__d_O_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__O_Ca = var_chaste_interface__L_type_Ca_current__d_O_Ca_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C0 = var_chaste_interface__L_type_Ca_current__d_C0_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C1 = var_chaste_interface__L_type_Ca_current__d_C1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C2 = var_chaste_interface__L_type_Ca_current__d_C2_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C3 = var_chaste_interface__L_type_Ca_current__d_C3_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C4 = var_chaste_interface__L_type_Ca_current__d_C4_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C_Ca0 = var_chaste_interface__L_type_Ca_current__d_C_Ca0_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C_Ca1 = var_chaste_interface__L_type_Ca_current__d_C_Ca1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C_Ca2 = var_chaste_interface__L_type_Ca_current__d_C_Ca2_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C_Ca3 = var_chaste_interface__L_type_Ca_current__d_C_Ca3_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current__C_Ca4 = var_chaste_interface__L_type_Ca_current__d_C_Ca4_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__L_type_Ca_current_y_gate__y = var_chaste_interface__L_type_Ca_current_y_gate__d_y_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__RyR_channel__P_O1 = var_chaste_interface__RyR_channel__d_P_O1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__RyR_channel__P_O2 = var_chaste_interface__RyR_channel__d_P_O2_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__RyR_channel__P_C1 = var_chaste_interface__RyR_channel__d_P_C1_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__RyR_channel__P_C2 = var_chaste_interface__RyR_channel__d_P_C2_d_environment__time; // 'per millisecond' const NekDouble d_dt_chaste_interface__intracellular_Ca_fluxes__HTRPNCa = var_chaste_interface__intracellular_Ca_fluxes__d_HTRPNCa_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_Ca_fluxes__LTRPNCa = var_chaste_interface__intracellular_Ca_fluxes__d_LTRPNCa_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Nai = var_chaste_interface__intracellular_ion_concentrations__d_Nai_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Cai = var_chaste_interface__intracellular_ion_concentrations__d_Cai_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Ki = var_chaste_interface__intracellular_ion_concentrations__d_Ki_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Ca_ss = var_chaste_interface__intracellular_ion_concentrations__d_Ca_ss_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Ca_JSR = var_chaste_interface__intracellular_ion_concentrations__d_Ca_JSR_d_environment__time; // 'millimole per litre per millisecond' const NekDouble d_dt_chaste_interface__intracellular_ion_concentrations__Ca_NSR = var_chaste_interface__intracellular_ion_concentrations__d_Ca_NSR_d_environment__time; // 'millimole per litre per millisecond' const NekDouble var_membrane__C_sc = 0.001; // microF_per_cm2 const NekDouble var_membrane__i_Na = var_fast_sodium_current__i_Na; // microA_per_microF const NekDouble var_membrane__i_Ca = var_L_type_Ca_current__i_Ca; // microA_per_microF const NekDouble var_membrane__i_Ca_K = var_L_type_Ca_current__i_Ca_K; // microA_per_microF const NekDouble var_membrane__i_Kr = var_rapid_activating_delayed_rectifiyer_K_current__i_Kr; // microA_per_microF const NekDouble var_membrane__i_Ks = var_slow_activating_delayed_rectifiyer_K_current__i_Ks; // microA_per_microF const NekDouble var_membrane__i_to1 = var_transient_outward_potassium_current__i_to1; // microA_per_microF const NekDouble var_membrane__i_K1 = var_time_independent_potassium_current__i_K1; // microA_per_microF const NekDouble var_membrane__i_Kp = var_plateau_potassium_current__i_Kp; // microA_per_microF const NekDouble var_membrane__i_NaCa = var_Na_Ca_exchanger__i_NaCa; // microA_per_microF const NekDouble var_membrane__i_NaK = var_sodium_potassium_pump__i_NaK; // microA_per_microF const NekDouble var_membrane__i_p_Ca = var_sarcolemmal_calcium_pump__i_p_Ca; // microA_per_microF const NekDouble var_membrane__i_Ca_b = var_calcium_background_current__i_Ca_b; // microA_per_microF const NekDouble var_membrane__i_Na_b = var_sodium_background_current__i_Na_b; // microA_per_microF const NekDouble var_chaste_interface__membrane__i_Stim = 0.0; const NekDouble var_membrane__i_Stim_converter = var_chaste_interface__membrane__i_Stim; // uA_per_cm2 const NekDouble var_membrane__chaste_interface__chaste_membrane_capacitance = 1.0; // uF_per_cm2 const NekDouble var_membrane__i_Stim = var_membrane__i_Stim_converter / var_membrane__chaste_interface__chaste_membrane_capacitance; // microA_per_microF const NekDouble var_membrane__d_V_d_environment__time = ((-1.0) * 1.0 * (var_membrane__i_Na + var_membrane__i_Ca + var_membrane__i_Ca_K + var_membrane__i_Kr + var_membrane__i_Ks + var_membrane__i_to1 + var_membrane__i_K1 + var_membrane__i_Kp + var_membrane__i_NaCa + var_membrane__i_NaK + var_membrane__i_p_Ca + var_membrane__i_Na_b + var_membrane__i_Ca_b + var_membrane__i_Stim)) / var_membrane__C_sc; // 'millivolt per second' const NekDouble var_chaste_interface__membrane__d_V_d_environment__time_converter = var_membrane__d_V_d_environment__time; // ___units_1 const NekDouble var_chaste_interface__membrane__d_V_d_environment__time = 0.001 * var_chaste_interface__membrane__d_V_d_environment__time_converter; // 'millivolt per millisecond' d_dt_chaste_interface__membrane__V = var_chaste_interface__membrane__d_V_d_environment__time; // 'millivolt per millisecond' outarray[0][i] = d_dt_chaste_interface__membrane__V; outarray[1][i] = d_dt_chaste_interface__fast_sodium_current_m_gate__m; outarray[2][i] = d_dt_chaste_interface__fast_sodium_current_h_gate__h; outarray[3][i] = d_dt_chaste_interface__fast_sodium_current_j_gate__j; outarray[4][i] = d_dt_chaste_interface__rapid_activating_delayed_rectifiyer_K_current_X_kr_gate__X_kr; outarray[5][i] = d_dt_chaste_interface__slow_activating_delayed_rectifiyer_K_current_X_ks_gate__X_ks; outarray[6][i] = d_dt_chaste_interface__transient_outward_potassium_current_X_to1_gate__X_to1; outarray[7][i] = d_dt_chaste_interface__transient_outward_potassium_current_Y_to1_gate__Y_to1; outarray[8][i] = d_dt_chaste_interface__L_type_Ca_current__O; outarray[9][i] = d_dt_chaste_interface__L_type_Ca_current__O_Ca; outarray[10][i] = d_dt_chaste_interface__L_type_Ca_current__C0; outarray[11][i] = d_dt_chaste_interface__L_type_Ca_current__C1; outarray[12][i] = d_dt_chaste_interface__L_type_Ca_current__C2; outarray[13][i] = d_dt_chaste_interface__L_type_Ca_current__C3; outarray[14][i] = d_dt_chaste_interface__L_type_Ca_current__C4; outarray[15][i] = d_dt_chaste_interface__L_type_Ca_current__C_Ca0; outarray[16][i] = d_dt_chaste_interface__L_type_Ca_current__C_Ca1; outarray[17][i] = d_dt_chaste_interface__L_type_Ca_current__C_Ca2; outarray[18][i] = d_dt_chaste_interface__L_type_Ca_current__C_Ca3; outarray[19][i] = d_dt_chaste_interface__L_type_Ca_current__C_Ca4; outarray[20][i] = d_dt_chaste_interface__L_type_Ca_current_y_gate__y; outarray[21][i] = d_dt_chaste_interface__RyR_channel__P_O1; outarray[22][i] = d_dt_chaste_interface__RyR_channel__P_O2; outarray[23][i] = d_dt_chaste_interface__RyR_channel__P_C1; outarray[24][i] = d_dt_chaste_interface__RyR_channel__P_C2; outarray[25][i] = d_dt_chaste_interface__intracellular_Ca_fluxes__HTRPNCa; outarray[26][i] = d_dt_chaste_interface__intracellular_Ca_fluxes__LTRPNCa; outarray[27][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Nai; outarray[28][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Cai; outarray[29][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Ki; outarray[30][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Ca_ss; outarray[31][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Ca_JSR; outarray[32][i] = d_dt_chaste_interface__intracellular_ion_concentrations__Ca_NSR; } } /** * */ void Winslow99::v_GenerateSummary(SummaryList& s) { SolverUtils::AddSummaryItem(s, "Cell model", "Winslow99"); } /** * */ void Winslow99::v_SetInitialConditions() { Vmath::Fill(m_nq, -96.1638, m_cellSol[0], 1); Vmath::Fill(m_nq, 0.0328302, m_cellSol[1], 1); Vmath::Fill(m_nq, 0.988354, m_cellSol[2], 1); Vmath::Fill(m_nq, 0.99254, m_cellSol[3], 1); Vmath::Fill(m_nq, 0.51, m_cellSol[4], 1); Vmath::Fill(m_nq, 0.264, m_cellSol[5], 1); Vmath::Fill(m_nq, 2.63, m_cellSol[6], 1); Vmath::Fill(m_nq, 0.99, m_cellSol[7], 1); Vmath::Fill(m_nq, 9.84546e-21, m_cellSol[8], 1); Vmath::Fill(m_nq, 0.0, m_cellSol[9], 1); Vmath::Fill(m_nq, 0.997208, m_cellSol[10], 1); Vmath::Fill(m_nq, 6.38897e-5, m_cellSol[11], 1); Vmath::Fill(m_nq, 1.535e-9, m_cellSol[12], 1); Vmath::Fill(m_nq, 1.63909e-14, m_cellSol[13], 1); Vmath::Fill(m_nq, 6.56337e-20, m_cellSol[14], 1); Vmath::Fill(m_nq, 0.00272826, m_cellSol[15], 1); Vmath::Fill(m_nq, 6.99215e-7, m_cellSol[16], 1); Vmath::Fill(m_nq, 6.71989e-11, m_cellSol[17], 1); Vmath::Fill(m_nq, 2.87031e-15, m_cellSol[18], 1); Vmath::Fill(m_nq, 4.59752e-20, m_cellSol[19], 1); Vmath::Fill(m_nq, 0.798, m_cellSol[20], 1); Vmath::Fill(m_nq, 0.0, m_cellSol[21], 1); Vmath::Fill(m_nq, 0.0, m_cellSol[22], 1); Vmath::Fill(m_nq, 0.47, m_cellSol[23], 1); Vmath::Fill(m_nq, 0.53, m_cellSol[24], 1); Vmath::Fill(m_nq, 0.98, m_cellSol[25], 1); Vmath::Fill(m_nq, 0.078, m_cellSol[26], 1); Vmath::Fill(m_nq, 10.0, m_cellSol[27], 1); Vmath::Fill(m_nq, 0.00008, m_cellSol[28], 1); Vmath::Fill(m_nq, 157.8, m_cellSol[29], 1); Vmath::Fill(m_nq, 0.00011, m_cellSol[30], 1); Vmath::Fill(m_nq, 0.257, m_cellSol[31], 1); Vmath::Fill(m_nq, 0.257, m_cellSol[32], 1); } }
mit
RippeR37/GLUL
src/GLUL/Input/Mouse.cpp
3
2612
#include <GLUL/Window.h> #include <GLUL/Input/Mouse.h> #include <GL/glew.h> #include <GLFW/glfw3.h> namespace GLUL { namespace Input { void Mouse::setMode(CursorMode cursorMode) { setMode(cursorMode, GLUL::Windows::Active()); } void Mouse::setMode(CursorMode cursorMode, GLUL::Window* window) { if(window) { int libMode = GLFW_CURSOR_NORMAL; switch(cursorMode) { case CursorMode::Normal: libMode = GLFW_CURSOR_NORMAL; break; case CursorMode::Hidden: libMode = GLFW_CURSOR_HIDDEN; break; case CursorMode::Disabled: libMode = GLFW_CURSOR_DISABLED; break; default: break; } glfwSetInputMode(window->getHandle(), GLFW_CURSOR, libMode); } } Input::Action Mouse::getState(MouseButton mouseButton) { return getState(mouseButton, GLUL::Windows::Active()); } Input::Action Mouse::getState(MouseButton mouseButton, GLUL::Window* window) { Input::Action result = Input::Action::Release; if(window) { int libButton = GLFW_MOUSE_BUTTON_LEFT; switch(mouseButton) { case MouseButton::Left: libButton = GLFW_MOUSE_BUTTON_LEFT; break; case MouseButton::Right: libButton = GLFW_MOUSE_BUTTON_RIGHT; break; case MouseButton::Middle: libButton = GLFW_MOUSE_BUTTON_MIDDLE; break; default: break; } int libResult = glfwGetMouseButton(window->getHandle(), libButton); switch(libResult) { case GLFW_PRESS: result = Input::Action::Press; break; case GLFW_REPEAT: result = Input::Action::Repeat; break; case GLFW_RELEASE: result = Input::Action::Release; break; default: break; } } return result; } glm::vec2 Mouse::getPosition() { return getPosition(GLUL::Windows::Active()); } glm::vec2 Mouse::getPosition(GLUL::Window* window) { glm::vec2 result = glm::vec2(0.0f, 0.0f); glm::dvec2 libResult; if(window) { glfwGetCursorPos(window->getHandle(), &libResult.x, &libResult.y); result = libResult; } return result; } } }
mit
rbaghdadi/ISIR
benchmarks/halide/wrapper_ticket.cpp
3
1567
#include "wrapper_ticket.h" #include "Halide.h" #include "halide_image_io.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <tiramisu/utils.h> #define N 1024 #define NB_TESTS 60 #define CHECK_CORRECTNESS 1 int main(int, char**) { std::vector<std::chrono::duration<double,std::milli>> duration_vector_1; std::vector<std::chrono::duration<double,std::milli>> duration_vector_2; Halide::Buffer<uint8_t> output1(N, N); Halide::Buffer<int> output2(N, N); init_buffer(output1, (uint8_t) 0); init_buffer(output2, (int) 0); //Warm up ticket_tiramisu(output1.raw_buffer()); ticket_ref(output2.raw_buffer()); // Tiramisu for (int i=0; i<NB_TESTS; i++) { auto start1 = std::chrono::high_resolution_clock::now(); ticket_tiramisu(output1.raw_buffer()); auto end1 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration1 = end1 - start1; duration_vector_1.push_back(duration1); } // Reference for (int i=0; i<NB_TESTS; i++) { auto start2 = std::chrono::high_resolution_clock::now(); ticket_ref(output2.raw_buffer()); auto end2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double,std::milli> duration2 = end2 - start2; duration_vector_2.push_back(duration2); } print_time("performance_CPU.csv", "edge", {"Tiramisu", "Halide"}, {median(duration_vector_1), median(duration_vector_2)}); return 0; }
mit
FinanceChainFoundation/FinChain-core
tests/tests/wallet_tests.cpp
3
2867
/* * Copyright (c) 2017 Cryptonomex, Inc., and contributors. * * The MIT License * * 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 <boost/test/unit_test.hpp> #include <graphene/app/database_api.hpp> #include <graphene/wallet/wallet.hpp> #include <iostream> #include "../common/database_fixture.hpp" using namespace graphene::chain; using namespace graphene::chain::test; using namespace graphene::wallet; BOOST_FIXTURE_TEST_SUITE(wallet_tests, database_fixture) /*** * Check the basic behavior of deriving potential owner keys from a brain key */ BOOST_AUTO_TEST_CASE(derive_owner_keys_from_brain_key) { try { /*** * Act */ int nbr_keys_desired = 3; vector<brain_key_info> derived_keys = graphene::wallet::utility::derive_owner_keys_from_brain_key("SOME WORDS GO HERE", nbr_keys_desired); /*** * Assert: Check the number of derived keys */ BOOST_CHECK_EQUAL(nbr_keys_desired, derived_keys.size()); /*** * Assert: Check that each derived key is unique */ set<string> set_derived_public_keys; for (auto info : derived_keys) { string description = (string) info.pub_key; set_derived_public_keys.emplace(description); } BOOST_CHECK_EQUAL(nbr_keys_desired, set_derived_public_keys.size()); /*** * Assert: Check whether every public key begins with the expected prefix */ string expected_prefix = GRAPHENE_ADDRESS_PREFIX; for (auto info : derived_keys) { string description = (string) info.pub_key; BOOST_CHECK_EQUAL(0, description.find(expected_prefix)); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
mit
cginternals/libzeug
source/tests/reflectionzeug-test/propertyInstanciationTests/PropertyInstanciationInt16_TArray_test.cpp
3
8708
#include <gmock/gmock.h> #include <reflectionzeug/property/Property.h> #include "../MyObject.h" using namespace reflectionzeug; using std::string; class PropertyInstanceInt16_TArray_test : public testing::Test { public: PropertyInstanceInt16_TArray_test() { } protected: }; namespace { int16_t staticGetter(size_t) { return int16_t(); } void staticSetter(size_t, int16_t /*value*/) { } } // Propterty instanciaton (read/write) TEST_F(PropertyInstanceInt16_TArray_test, instanciatePropertyWith_String_LambdaGetter_LambdaSetter) { auto get = [] (size_t) {return int16_t();}; auto set = [] (size_t, const int16_t & /*val*/) {}; auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", get, set); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciatePropertyWith_String_StaticGetter_StaticSetter) { auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", &staticGetter, &staticSetter); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciatePropertyWith_String_Object_ConstGetterConst_SetterConst) { auto obj = new MyObject<int16_t>; auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", obj, &MyObject<int16_t>::arrayConstgetterconst, &MyObject<int16_t>::arraySetterconst); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciatePropertyWith_String_Object_GetterConst_SetterConst) { auto obj = new MyObject<int16_t>; auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", obj, &MyObject<int16_t>::arrayGetterconst, &MyObject<int16_t>::arraySetterconst); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciatePropertyWith_String_Object_GetterConst_Setter) { auto obj = new MyObject<int16_t>; auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", obj, &MyObject<int16_t>::arrayGetterconst, &MyObject<int16_t>::arraySetter); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } // Propterty instanciaton (read only) TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstPropertyWith_String_LambdaGetter) { auto get = [] (size_t) {return int16_t();}; auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", get); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstPropertyWith_String_StaticGetter) { auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", &staticGetter); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstPropertyWith_String_Object_ConstGetterConst) { auto obj = new MyObject<int16_t>; auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", obj, &MyObject<int16_t>::arrayConstgetterconst); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstPropertyWith_String_Object_GetterConst) { auto obj = new MyObject<int16_t>; auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", obj, &MyObject<int16_t>::arrayGetterconst); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } // Propterty instanciaton with Accessor (read/write) TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String) { auto accessor = new ArrayAccessorValue<int16_t, 1>(); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_Value) { auto accessor = new ArrayAccessorValue<int16_t, 1>(std::array<int16_t, 1>()); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_LambdaGetter_LambdaSetter) { auto get = [] (size_t) {return int16_t();}; auto set = [] (size_t, const int16_t & /*val*/) {}; auto accessor = new ArrayAccessorGetSet<int16_t, 1>(get, set); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_StaticGetter_StaticSetter) { auto accessor = new ArrayAccessorGetSet<int16_t, 1>(&staticGetter, &staticSetter); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_Object_ConstGetterConst_SetterConst) { auto obj = new MyObject<int16_t>; auto accessor = new ArrayAccessorGetSet<int16_t, 1>(obj, &MyObject<int16_t>::arrayConstgetterconst, &MyObject<int16_t>::arraySetterconst); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_Object_GetterConst_SetterConst) { auto obj = new MyObject<int16_t>; auto accessor = new ArrayAccessorGetSet<int16_t, 1>(obj, &MyObject<int16_t>::arrayGetterconst, &MyObject<int16_t>::arraySetterconst); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateAccessorWith_String_Object_GetterConst_Setter) { auto obj = new MyObject<int16_t>; auto accessor = new ArrayAccessorGetSet<int16_t, 1>(obj, &MyObject<int16_t>::arrayGetterconst, &MyObject<int16_t>::arraySetter); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } // Propterty instanciaton with Accessor (read only) TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String) { auto accessor = new ArrayAccessorValue<const int16_t, 1>(); auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String_Value) { auto accessor = new ArrayAccessorValue<const int16_t, 1>(std::array<int16_t, 1>()); auto prop = new PropertyArray<int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String_LambdaGetter) { auto get = [] (size_t) {return int16_t();}; auto accessor = new ArrayAccessorGetSet<const int16_t, 1>(get); auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String_StaticGetter) { auto accessor = new ArrayAccessorGetSet<const int16_t, 1>(&staticGetter); auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String_Object_ConstGetterConst) { auto obj = new MyObject<int16_t>; auto accessor = new ArrayAccessorGetSet<const int16_t, 1>(obj, &MyObject<int16_t>::arrayConstgetterconst); auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; } TEST_F(PropertyInstanceInt16_TArray_test, instanciateConstAccessorWith_String_Object_GetterConst) { auto obj = new MyObject<int16_t>; auto accessor = new ArrayAccessorGetSet<const int16_t, 1>(obj, &MyObject<int16_t>::arrayGetterconst); auto prop = new PropertyArray<const int16_t, 1>("int16_tProperty", accessor); ASSERT_EQ(typeid(std::array<int16_t, 1>), prop->type()); delete prop; delete obj; }
mit
mikedlowis-prototypes/acc
source/oocontext.cpp
3
1755
/* oocontext.cpp ** strophe XMPP client library -- C++ context implementation ** ** Copyright (C) 2005-2009 Collecta, Inc. ** ** This software is provided AS-IS with no warranty, either express ** or implied. ** ** This program is dual licensed under the MIT and GPLv3 licenses. */ #include <stdlib.h> #include "strophe.h" #include "strophepp.h" XMPP::Context::Context() { m_mem.alloc = callAlloc; m_mem.realloc = callRealloc; m_mem.free = callFree; m_mem.userdata = (void *)this; m_log.handler = callLog; m_log.userdata = (void *)this; m_ctx = ::xmpp_ctx_new(&m_mem, &m_log); } XMPP::Context::~Context() { ::xmpp_ctx_free(m_ctx); } void *XMPP::Context::alloc(const size_t size) { return ::malloc(size); } void *XMPP::Context::realloc(void *p, const size_t size) { return ::realloc(p, size); } void XMPP::Context::free(void *p) { ::free(p); } void XMPP::Context::log(const xmpp_log_level_t level, const char * const area, const char * const msg) { /* do nothing by default */ } xmpp_ctx_t *XMPP::Context::getContext() { return m_ctx; } void *XMPP::Context::callAlloc(const size_t size, void * const userdata) { return reinterpret_cast<Context *>(userdata)->alloc(size); } void *XMPP::Context::callRealloc(void *p, const size_t size, void * const userdata) { return reinterpret_cast<Context *>(userdata)->realloc(p, size); } void XMPP::Context::callFree(void *p, void * const userdata) { reinterpret_cast<Context *>(userdata)->free(p); } void XMPP::Context::callLog(void * const userdata, const xmpp_log_level_t level, const char * const area, const char * const msg) { reinterpret_cast<Context *>(userdata)->log(level, area, msg); }
mit
tipographo/tipographo.github.io
node_modules/grpc/deps/grpc/third_party/boringssl/crypto/fipsmodule/ec/p256-64.c
3
51073
/* Copyright (c) 2015, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ // A 64-bit implementation of the NIST P-256 elliptic curve point // multiplication // // OpenSSL integration was taken from Emilia Kasper's work in ecp_nistp224.c. // Otherwise based on Emilia's P224 work, which was inspired by my curve25519 // work which got its smarts from Daniel J. Bernstein's work on the same. #include <openssl/base.h> #if defined(OPENSSL_64_BIT) && !defined(OPENSSL_WINDOWS) #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/err.h> #include <openssl/mem.h> #include <string.h> #include "../delocate.h" #include "../../internal.h" #include "internal.h" // The underlying field. P256 operates over GF(2^256-2^224+2^192+2^96-1). We // can serialise an element of this field into 32 bytes. We call this an // felem_bytearray. typedef uint8_t felem_bytearray[32]; // The representation of field elements. // ------------------------------------ // // We represent field elements with either four 128-bit values, eight 128-bit // values, or four 64-bit values. The field element represented is: // v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + v[3]*2^192 (mod p) // or: // v[0]*2^0 + v[1]*2^64 + v[2]*2^128 + ... + v[8]*2^512 (mod p) // // 128-bit values are called 'limbs'. Since the limbs are spaced only 64 bits // apart, but are 128-bits wide, the most significant bits of each limb overlap // with the least significant bits of the next. // // A field element with four limbs is an 'felem'. One with eight limbs is a // 'longfelem' // // A field element with four, 64-bit values is called a 'smallfelem'. Small // values are used as intermediate values before multiplication. #define NLIMBS 4 typedef uint128_t limb; typedef limb felem[NLIMBS]; typedef limb longfelem[NLIMBS * 2]; typedef uint64_t smallfelem[NLIMBS]; // This is the value of the prime as four 64-bit words, little-endian. static const uint64_t kPrime[4] = {0xfffffffffffffffful, 0xffffffff, 0, 0xffffffff00000001ul}; static const uint64_t bottom63bits = 0x7ffffffffffffffful; static uint64_t load_u64(const uint8_t in[8]) { uint64_t ret; OPENSSL_memcpy(&ret, in, sizeof(ret)); return ret; } static void store_u64(uint8_t out[8], uint64_t in) { OPENSSL_memcpy(out, &in, sizeof(in)); } // bin32_to_felem takes a little-endian byte array and converts it into felem // form. This assumes that the CPU is little-endian. static void bin32_to_felem(felem out, const uint8_t in[32]) { out[0] = load_u64(&in[0]); out[1] = load_u64(&in[8]); out[2] = load_u64(&in[16]); out[3] = load_u64(&in[24]); } // smallfelem_to_bin32 takes a smallfelem and serialises into a little endian, // 32 byte array. This assumes that the CPU is little-endian. static void smallfelem_to_bin32(uint8_t out[32], const smallfelem in) { store_u64(&out[0], in[0]); store_u64(&out[8], in[1]); store_u64(&out[16], in[2]); store_u64(&out[24], in[3]); } // To preserve endianness when using BN_bn2bin and BN_bin2bn. static void flip_endian(uint8_t *out, const uint8_t *in, size_t len) { for (size_t i = 0; i < len; ++i) { out[i] = in[len - 1 - i]; } } // BN_to_felem converts an OpenSSL BIGNUM into an felem. static int BN_to_felem(felem out, const BIGNUM *bn) { if (BN_is_negative(bn)) { OPENSSL_PUT_ERROR(EC, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } felem_bytearray b_out; // BN_bn2bin eats leading zeroes OPENSSL_memset(b_out, 0, sizeof(b_out)); size_t num_bytes = BN_num_bytes(bn); if (num_bytes > sizeof(b_out)) { OPENSSL_PUT_ERROR(EC, EC_R_BIGNUM_OUT_OF_RANGE); return 0; } felem_bytearray b_in; num_bytes = BN_bn2bin(bn, b_in); flip_endian(b_out, b_in, num_bytes); bin32_to_felem(out, b_out); return 1; } // felem_to_BN converts an felem into an OpenSSL BIGNUM. static BIGNUM *smallfelem_to_BN(BIGNUM *out, const smallfelem in) { felem_bytearray b_in, b_out; smallfelem_to_bin32(b_in, in); flip_endian(b_out, b_in, sizeof(b_out)); return BN_bin2bn(b_out, sizeof(b_out), out); } // Field operations. static void felem_assign(felem out, const felem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } // felem_sum sets out = out + in. static void felem_sum(felem out, const felem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } // felem_small_sum sets out = out + in. static void felem_small_sum(felem out, const smallfelem in) { out[0] += in[0]; out[1] += in[1]; out[2] += in[2]; out[3] += in[3]; } // felem_scalar sets out = out * scalar static void felem_scalar(felem out, const uint64_t scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; } // longfelem_scalar sets out = out * scalar static void longfelem_scalar(longfelem out, const uint64_t scalar) { out[0] *= scalar; out[1] *= scalar; out[2] *= scalar; out[3] *= scalar; out[4] *= scalar; out[5] *= scalar; out[6] *= scalar; out[7] *= scalar; } #define two105m41m9 ((((limb)1) << 105) - (((limb)1) << 41) - (((limb)1) << 9)) #define two105 (((limb)1) << 105) #define two105m41p9 ((((limb)1) << 105) - (((limb)1) << 41) + (((limb)1) << 9)) // zero105 is 0 mod p static const felem zero105 = {two105m41m9, two105, two105m41p9, two105m41p9}; // smallfelem_neg sets |out| to |-small| // On exit: // out[i] < out[i] + 2^105 static void smallfelem_neg(felem out, const smallfelem small) { // In order to prevent underflow, we subtract from 0 mod p. out[0] = zero105[0] - small[0]; out[1] = zero105[1] - small[1]; out[2] = zero105[2] - small[2]; out[3] = zero105[3] - small[3]; } // felem_diff subtracts |in| from |out| // On entry: // in[i] < 2^104 // On exit: // out[i] < out[i] + 2^105. static void felem_diff(felem out, const felem in) { // In order to prevent underflow, we add 0 mod p before subtracting. out[0] += zero105[0]; out[1] += zero105[1]; out[2] += zero105[2]; out[3] += zero105[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } #define two107m43m11 \ ((((limb)1) << 107) - (((limb)1) << 43) - (((limb)1) << 11)) #define two107 (((limb)1) << 107) #define two107m43p11 \ ((((limb)1) << 107) - (((limb)1) << 43) + (((limb)1) << 11)) // zero107 is 0 mod p static const felem zero107 = {two107m43m11, two107, two107m43p11, two107m43p11}; // An alternative felem_diff for larger inputs |in| // felem_diff_zero107 subtracts |in| from |out| // On entry: // in[i] < 2^106 // On exit: // out[i] < out[i] + 2^107. static void felem_diff_zero107(felem out, const felem in) { // In order to prevent underflow, we add 0 mod p before subtracting. out[0] += zero107[0]; out[1] += zero107[1]; out[2] += zero107[2]; out[3] += zero107[3]; out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; } // longfelem_diff subtracts |in| from |out| // On entry: // in[i] < 7*2^67 // On exit: // out[i] < out[i] + 2^70 + 2^40. static void longfelem_diff(longfelem out, const longfelem in) { static const limb two70m8p6 = (((limb)1) << 70) - (((limb)1) << 8) + (((limb)1) << 6); static const limb two70p40 = (((limb)1) << 70) + (((limb)1) << 40); static const limb two70 = (((limb)1) << 70); static const limb two70m40m38p6 = (((limb)1) << 70) - (((limb)1) << 40) - (((limb)1) << 38) + (((limb)1) << 6); static const limb two70m6 = (((limb)1) << 70) - (((limb)1) << 6); // add 0 mod p to avoid underflow out[0] += two70m8p6; out[1] += two70p40; out[2] += two70; out[3] += two70m40m38p6; out[4] += two70m6; out[5] += two70m6; out[6] += two70m6; out[7] += two70m6; // in[i] < 7*2^67 < 2^70 - 2^40 - 2^38 + 2^6 out[0] -= in[0]; out[1] -= in[1]; out[2] -= in[2]; out[3] -= in[3]; out[4] -= in[4]; out[5] -= in[5]; out[6] -= in[6]; out[7] -= in[7]; } #define two64m0 ((((limb)1) << 64) - 1) #define two110p32m0 ((((limb)1) << 110) + (((limb)1) << 32) - 1) #define two64m46 ((((limb)1) << 64) - (((limb)1) << 46)) #define two64m32 ((((limb)1) << 64) - (((limb)1) << 32)) // zero110 is 0 mod p. static const felem zero110 = {two64m0, two110p32m0, two64m46, two64m32}; // felem_shrink converts an felem into a smallfelem. The result isn't quite // minimal as the value may be greater than p. // // On entry: // in[i] < 2^109 // On exit: // out[i] < 2^64. static void felem_shrink(smallfelem out, const felem in) { felem tmp; uint64_t a, b, mask; int64_t high, low; static const uint64_t kPrime3Test = 0x7fffffff00000001ul; // 2^63 - 2^32 + 1 // Carry 2->3 tmp[3] = zero110[3] + in[3] + ((uint64_t)(in[2] >> 64)); // tmp[3] < 2^110 tmp[2] = zero110[2] + (uint64_t)in[2]; tmp[0] = zero110[0] + in[0]; tmp[1] = zero110[1] + in[1]; // tmp[0] < 2**110, tmp[1] < 2^111, tmp[2] < 2**65 // We perform two partial reductions where we eliminate the high-word of // tmp[3]. We don't update the other words till the end. a = tmp[3] >> 64; // a < 2^46 tmp[3] = (uint64_t)tmp[3]; tmp[3] -= a; tmp[3] += ((limb)a) << 32; // tmp[3] < 2^79 b = a; a = tmp[3] >> 64; // a < 2^15 b += a; // b < 2^46 + 2^15 < 2^47 tmp[3] = (uint64_t)tmp[3]; tmp[3] -= a; tmp[3] += ((limb)a) << 32; // tmp[3] < 2^64 + 2^47 // This adjusts the other two words to complete the two partial // reductions. tmp[0] += b; tmp[1] -= (((limb)b) << 32); // In order to make space in tmp[3] for the carry from 2 -> 3, we // conditionally subtract kPrime if tmp[3] is large enough. high = tmp[3] >> 64; // As tmp[3] < 2^65, high is either 1 or 0 high = ~(high - 1); // high is: // all ones if the high word of tmp[3] is 1 // all zeros if the high word of tmp[3] if 0 low = tmp[3]; mask = low >> 63; // mask is: // all ones if the MSB of low is 1 // all zeros if the MSB of low if 0 low &= bottom63bits; low -= kPrime3Test; // if low was greater than kPrime3Test then the MSB is zero low = ~low; low >>= 63; // low is: // all ones if low was > kPrime3Test // all zeros if low was <= kPrime3Test mask = (mask & low) | high; tmp[0] -= mask & kPrime[0]; tmp[1] -= mask & kPrime[1]; // kPrime[2] is zero, so omitted tmp[3] -= mask & kPrime[3]; // tmp[3] < 2**64 - 2**32 + 1 tmp[1] += ((uint64_t)(tmp[0] >> 64)); tmp[0] = (uint64_t)tmp[0]; tmp[2] += ((uint64_t)(tmp[1] >> 64)); tmp[1] = (uint64_t)tmp[1]; tmp[3] += ((uint64_t)(tmp[2] >> 64)); tmp[2] = (uint64_t)tmp[2]; // tmp[i] < 2^64 out[0] = tmp[0]; out[1] = tmp[1]; out[2] = tmp[2]; out[3] = tmp[3]; } // smallfelem_expand converts a smallfelem to an felem static void smallfelem_expand(felem out, const smallfelem in) { out[0] = in[0]; out[1] = in[1]; out[2] = in[2]; out[3] = in[3]; } // smallfelem_square sets |out| = |small|^2 // On entry: // small[i] < 2^64 // On exit: // out[i] < 7 * 2^64 < 2^67 static void smallfelem_square(longfelem out, const smallfelem small) { limb a; uint64_t high, low; a = ((uint128_t)small[0]) * small[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t)small[0]) * small[1]; low = a; high = a >> 64; out[1] += low; out[1] += low; out[2] = high; a = ((uint128_t)small[0]) * small[2]; low = a; high = a >> 64; out[2] += low; out[2] *= 2; out[3] = high; a = ((uint128_t)small[0]) * small[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t)small[1]) * small[2]; low = a; high = a >> 64; out[3] += low; out[3] *= 2; out[4] += high; a = ((uint128_t)small[1]) * small[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t)small[1]) * small[3]; low = a; high = a >> 64; out[4] += low; out[4] *= 2; out[5] = high; a = ((uint128_t)small[2]) * small[3]; low = a; high = a >> 64; out[5] += low; out[5] *= 2; out[6] = high; out[6] += high; a = ((uint128_t)small[2]) * small[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t)small[3]) * small[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } //felem_square sets |out| = |in|^2 // On entry: // in[i] < 2^109 // On exit: // out[i] < 7 * 2^64 < 2^67. static void felem_square(longfelem out, const felem in) { uint64_t small[4]; felem_shrink(small, in); smallfelem_square(out, small); } // smallfelem_mul sets |out| = |small1| * |small2| // On entry: // small1[i] < 2^64 // small2[i] < 2^64 // On exit: // out[i] < 7 * 2^64 < 2^67. static void smallfelem_mul(longfelem out, const smallfelem small1, const smallfelem small2) { limb a; uint64_t high, low; a = ((uint128_t)small1[0]) * small2[0]; low = a; high = a >> 64; out[0] = low; out[1] = high; a = ((uint128_t)small1[0]) * small2[1]; low = a; high = a >> 64; out[1] += low; out[2] = high; a = ((uint128_t)small1[1]) * small2[0]; low = a; high = a >> 64; out[1] += low; out[2] += high; a = ((uint128_t)small1[0]) * small2[2]; low = a; high = a >> 64; out[2] += low; out[3] = high; a = ((uint128_t)small1[1]) * small2[1]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t)small1[2]) * small2[0]; low = a; high = a >> 64; out[2] += low; out[3] += high; a = ((uint128_t)small1[0]) * small2[3]; low = a; high = a >> 64; out[3] += low; out[4] = high; a = ((uint128_t)small1[1]) * small2[2]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t)small1[2]) * small2[1]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t)small1[3]) * small2[0]; low = a; high = a >> 64; out[3] += low; out[4] += high; a = ((uint128_t)small1[1]) * small2[3]; low = a; high = a >> 64; out[4] += low; out[5] = high; a = ((uint128_t)small1[2]) * small2[2]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t)small1[3]) * small2[1]; low = a; high = a >> 64; out[4] += low; out[5] += high; a = ((uint128_t)small1[2]) * small2[3]; low = a; high = a >> 64; out[5] += low; out[6] = high; a = ((uint128_t)small1[3]) * small2[2]; low = a; high = a >> 64; out[5] += low; out[6] += high; a = ((uint128_t)small1[3]) * small2[3]; low = a; high = a >> 64; out[6] += low; out[7] = high; } // felem_mul sets |out| = |in1| * |in2| // On entry: // in1[i] < 2^109 // in2[i] < 2^109 // On exit: // out[i] < 7 * 2^64 < 2^67 static void felem_mul(longfelem out, const felem in1, const felem in2) { smallfelem small1, small2; felem_shrink(small1, in1); felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } // felem_small_mul sets |out| = |small1| * |in2| // On entry: // small1[i] < 2^64 // in2[i] < 2^109 // On exit: // out[i] < 7 * 2^64 < 2^67 static void felem_small_mul(longfelem out, const smallfelem small1, const felem in2) { smallfelem small2; felem_shrink(small2, in2); smallfelem_mul(out, small1, small2); } #define two100m36m4 ((((limb)1) << 100) - (((limb)1) << 36) - (((limb)1) << 4)) #define two100 (((limb)1) << 100) #define two100m36p4 ((((limb)1) << 100) - (((limb)1) << 36) + (((limb)1) << 4)) // zero100 is 0 mod p static const felem zero100 = {two100m36m4, two100, two100m36p4, two100m36p4}; // Internal function for the different flavours of felem_reduce. // felem_reduce_ reduces the higher coefficients in[4]-in[7]. // On entry: // out[0] >= in[6] + 2^32*in[6] + in[7] + 2^32*in[7] // out[1] >= in[7] + 2^32*in[4] // out[2] >= in[5] + 2^32*in[5] // out[3] >= in[4] + 2^32*in[5] + 2^32*in[6] // On exit: // out[0] <= out[0] + in[4] + 2^32*in[5] // out[1] <= out[1] + in[5] + 2^33*in[6] // out[2] <= out[2] + in[7] + 2*in[6] + 2^33*in[7] // out[3] <= out[3] + 2^32*in[4] + 3*in[7] static void felem_reduce_(felem out, const longfelem in) { int128_t c; // combine common terms from below c = in[4] + (in[5] << 32); out[0] += c; out[3] -= c; c = in[5] - in[7]; out[1] += c; out[2] -= c; // the remaining terms // 256: [(0,1),(96,-1),(192,-1),(224,1)] out[1] -= (in[4] << 32); out[3] += (in[4] << 32); // 320: [(32,1),(64,1),(128,-1),(160,-1),(224,-1)] out[2] -= (in[5] << 32); // 384: [(0,-1),(32,-1),(96,2),(128,2),(224,-1)] out[0] -= in[6]; out[0] -= (in[6] << 32); out[1] += (in[6] << 33); out[2] += (in[6] * 2); out[3] -= (in[6] << 32); // 448: [(0,-1),(32,-1),(64,-1),(128,1),(160,2),(192,3)] out[0] -= in[7]; out[0] -= (in[7] << 32); out[2] += (in[7] << 33); out[3] += (in[7] * 3); } // felem_reduce converts a longfelem into an felem. // To be called directly after felem_square or felem_mul. // On entry: // in[0] < 2^64, in[1] < 3*2^64, in[2] < 5*2^64, in[3] < 7*2^64 // in[4] < 7*2^64, in[5] < 5*2^64, in[6] < 3*2^64, in[7] < 2*64 // On exit: // out[i] < 2^101 static void felem_reduce(felem out, const longfelem in) { out[0] = zero100[0] + in[0]; out[1] = zero100[1] + in[1]; out[2] = zero100[2] + in[2]; out[3] = zero100[3] + in[3]; felem_reduce_(out, in); // out[0] > 2^100 - 2^36 - 2^4 - 3*2^64 - 3*2^96 - 2^64 - 2^96 > 0 // out[1] > 2^100 - 2^64 - 7*2^96 > 0 // out[2] > 2^100 - 2^36 + 2^4 - 5*2^64 - 5*2^96 > 0 // out[3] > 2^100 - 2^36 + 2^4 - 7*2^64 - 5*2^96 - 3*2^96 > 0 // // out[0] < 2^100 + 2^64 + 7*2^64 + 5*2^96 < 2^101 // out[1] < 2^100 + 3*2^64 + 5*2^64 + 3*2^97 < 2^101 // out[2] < 2^100 + 5*2^64 + 2^64 + 3*2^65 + 2^97 < 2^101 // out[3] < 2^100 + 7*2^64 + 7*2^96 + 3*2^64 < 2^101 } // felem_reduce_zero105 converts a larger longfelem into an felem. // On entry: // in[0] < 2^71 // On exit: // out[i] < 2^106 static void felem_reduce_zero105(felem out, const longfelem in) { out[0] = zero105[0] + in[0]; out[1] = zero105[1] + in[1]; out[2] = zero105[2] + in[2]; out[3] = zero105[3] + in[3]; felem_reduce_(out, in); // out[0] > 2^105 - 2^41 - 2^9 - 2^71 - 2^103 - 2^71 - 2^103 > 0 // out[1] > 2^105 - 2^71 - 2^103 > 0 // out[2] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 > 0 // out[3] > 2^105 - 2^41 + 2^9 - 2^71 - 2^103 - 2^103 > 0 // // out[0] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 // out[1] < 2^105 + 2^71 + 2^71 + 2^103 < 2^106 // out[2] < 2^105 + 2^71 + 2^71 + 2^71 + 2^103 < 2^106 // out[3] < 2^105 + 2^71 + 2^103 + 2^71 < 2^106 } // subtract_u64 sets *result = *result - v and *carry to one if the // subtraction underflowed. static void subtract_u64(uint64_t *result, uint64_t *carry, uint64_t v) { uint128_t r = *result; r -= v; *carry = (r >> 64) & 1; *result = (uint64_t)r; } // felem_contract converts |in| to its unique, minimal representation. On // entry: in[i] < 2^109. static void felem_contract(smallfelem out, const felem in) { uint64_t all_equal_so_far = 0, result = 0; felem_shrink(out, in); // small is minimal except that the value might be > p all_equal_so_far--; // We are doing a constant time test if out >= kPrime. We need to compare // each uint64_t, from most-significant to least significant. For each one, if // all words so far have been equal (m is all ones) then a non-equal // result is the answer. Otherwise we continue. for (size_t i = 3; i < 4; i--) { uint64_t equal; uint128_t a = ((uint128_t)kPrime[i]) - out[i]; // if out[i] > kPrime[i] then a will underflow and the high 64-bits // will all be set. result |= all_equal_so_far & ((uint64_t)(a >> 64)); // if kPrime[i] == out[i] then |equal| will be all zeros and the // decrement will make it all ones. equal = kPrime[i] ^ out[i]; equal--; equal &= equal << 32; equal &= equal << 16; equal &= equal << 8; equal &= equal << 4; equal &= equal << 2; equal &= equal << 1; equal = ((int64_t)equal) >> 63; all_equal_so_far &= equal; } // if all_equal_so_far is still all ones then the two values are equal // and so out >= kPrime is true. result |= all_equal_so_far; // if out >= kPrime then we subtract kPrime. uint64_t carry; subtract_u64(&out[0], &carry, result & kPrime[0]); subtract_u64(&out[1], &carry, carry); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[1], &carry, result & kPrime[1]); subtract_u64(&out[2], &carry, carry); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[2], &carry, result & kPrime[2]); subtract_u64(&out[3], &carry, carry); subtract_u64(&out[3], &carry, result & kPrime[3]); } // felem_is_zero returns a limb with all bits set if |in| == 0 (mod p) and 0 // otherwise. // On entry: // small[i] < 2^64 static limb smallfelem_is_zero(const smallfelem small) { limb result; uint64_t is_p; uint64_t is_zero = small[0] | small[1] | small[2] | small[3]; is_zero--; is_zero &= is_zero << 32; is_zero &= is_zero << 16; is_zero &= is_zero << 8; is_zero &= is_zero << 4; is_zero &= is_zero << 2; is_zero &= is_zero << 1; is_zero = ((int64_t)is_zero) >> 63; is_p = (small[0] ^ kPrime[0]) | (small[1] ^ kPrime[1]) | (small[2] ^ kPrime[2]) | (small[3] ^ kPrime[3]); is_p--; is_p &= is_p << 32; is_p &= is_p << 16; is_p &= is_p << 8; is_p &= is_p << 4; is_p &= is_p << 2; is_p &= is_p << 1; is_p = ((int64_t)is_p) >> 63; is_zero |= is_p; result = is_zero; result |= ((limb)is_zero) << 64; return result; } // felem_inv calculates |out| = |in|^{-1} // // Based on Fermat's Little Theorem: // a^p = a (mod p) // a^{p-1} = 1 (mod p) // a^{p-2} = a^{-1} (mod p) static void felem_inv(felem out, const felem in) { felem ftmp, ftmp2; // each e_I will hold |in|^{2^I - 1} felem e2, e4, e8, e16, e32, e64; longfelem tmp; felem_square(tmp, in); felem_reduce(ftmp, tmp); // 2^1 felem_mul(tmp, in, ftmp); felem_reduce(ftmp, tmp); // 2^2 - 2^0 felem_assign(e2, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^3 - 2^1 felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^4 - 2^2 felem_mul(tmp, ftmp, e2); felem_reduce(ftmp, tmp); // 2^4 - 2^0 felem_assign(e4, ftmp); felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^5 - 2^1 felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^6 - 2^2 felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^7 - 2^3 felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // 2^8 - 2^4 felem_mul(tmp, ftmp, e4); felem_reduce(ftmp, tmp); // 2^8 - 2^0 felem_assign(e8, ftmp); for (size_t i = 0; i < 8; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } // 2^16 - 2^8 felem_mul(tmp, ftmp, e8); felem_reduce(ftmp, tmp); // 2^16 - 2^0 felem_assign(e16, ftmp); for (size_t i = 0; i < 16; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } // 2^32 - 2^16 felem_mul(tmp, ftmp, e16); felem_reduce(ftmp, tmp); // 2^32 - 2^0 felem_assign(e32, ftmp); for (size_t i = 0; i < 32; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } // 2^64 - 2^32 felem_assign(e64, ftmp); felem_mul(tmp, ftmp, in); felem_reduce(ftmp, tmp); // 2^64 - 2^32 + 2^0 for (size_t i = 0; i < 192; i++) { felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); } // 2^256 - 2^224 + 2^192 felem_mul(tmp, e64, e32); felem_reduce(ftmp2, tmp); // 2^64 - 2^0 for (size_t i = 0; i < 16; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } // 2^80 - 2^16 felem_mul(tmp, ftmp2, e16); felem_reduce(ftmp2, tmp); // 2^80 - 2^0 for (size_t i = 0; i < 8; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } // 2^88 - 2^8 felem_mul(tmp, ftmp2, e8); felem_reduce(ftmp2, tmp); // 2^88 - 2^0 for (size_t i = 0; i < 4; i++) { felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); } // 2^92 - 2^4 felem_mul(tmp, ftmp2, e4); felem_reduce(ftmp2, tmp); // 2^92 - 2^0 felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); // 2^93 - 2^1 felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); // 2^94 - 2^2 felem_mul(tmp, ftmp2, e2); felem_reduce(ftmp2, tmp); // 2^94 - 2^0 felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); // 2^95 - 2^1 felem_square(tmp, ftmp2); felem_reduce(ftmp2, tmp); // 2^96 - 2^2 felem_mul(tmp, ftmp2, in); felem_reduce(ftmp2, tmp); // 2^96 - 3 felem_mul(tmp, ftmp2, ftmp); felem_reduce(out, tmp); // 2^256 - 2^224 + 2^192 + 2^96 - 3 } // Group operations // ---------------- // // Building on top of the field operations we have the operations on the // elliptic curve group itself. Points on the curve are represented in Jacobian // coordinates. // point_double calculates 2*(x_in, y_in, z_in) // // The method is taken from: // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b // // Outputs can equal corresponding inputs, i.e., x_out == x_in is allowed. // while x_out == y_in is not (maybe this works, but it's not tested). static void point_double(felem x_out, felem y_out, felem z_out, const felem x_in, const felem y_in, const felem z_in) { longfelem tmp, tmp2; felem delta, gamma, beta, alpha, ftmp, ftmp2; smallfelem small1, small2; felem_assign(ftmp, x_in); // ftmp[i] < 2^106 felem_assign(ftmp2, x_in); // ftmp2[i] < 2^106 // delta = z^2 felem_square(tmp, z_in); felem_reduce(delta, tmp); // delta[i] < 2^101 // gamma = y^2 felem_square(tmp, y_in); felem_reduce(gamma, tmp); // gamma[i] < 2^101 felem_shrink(small1, gamma); // beta = x*gamma felem_small_mul(tmp, small1, x_in); felem_reduce(beta, tmp); // beta[i] < 2^101 // alpha = 3*(x-delta)*(x+delta) felem_diff(ftmp, delta); // ftmp[i] < 2^105 + 2^106 < 2^107 felem_sum(ftmp2, delta); // ftmp2[i] < 2^105 + 2^106 < 2^107 felem_scalar(ftmp2, 3); // ftmp2[i] < 3 * 2^107 < 2^109 felem_mul(tmp, ftmp, ftmp2); felem_reduce(alpha, tmp); // alpha[i] < 2^101 felem_shrink(small2, alpha); // x' = alpha^2 - 8*beta smallfelem_square(tmp, small2); felem_reduce(x_out, tmp); felem_assign(ftmp, beta); felem_scalar(ftmp, 8); // ftmp[i] < 8 * 2^101 = 2^104 felem_diff(x_out, ftmp); // x_out[i] < 2^105 + 2^101 < 2^106 // z' = (y + z)^2 - gamma - delta felem_sum(delta, gamma); // delta[i] < 2^101 + 2^101 = 2^102 felem_assign(ftmp, y_in); felem_sum(ftmp, z_in); // ftmp[i] < 2^106 + 2^106 = 2^107 felem_square(tmp, ftmp); felem_reduce(z_out, tmp); felem_diff(z_out, delta); // z_out[i] < 2^105 + 2^101 < 2^106 // y' = alpha*(4*beta - x') - 8*gamma^2 felem_scalar(beta, 4); // beta[i] < 4 * 2^101 = 2^103 felem_diff_zero107(beta, x_out); // beta[i] < 2^107 + 2^103 < 2^108 felem_small_mul(tmp, small2, beta); // tmp[i] < 7 * 2^64 < 2^67 smallfelem_square(tmp2, small1); // tmp2[i] < 7 * 2^64 longfelem_scalar(tmp2, 8); // tmp2[i] < 8 * 7 * 2^64 = 7 * 2^67 longfelem_diff(tmp, tmp2); // tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 felem_reduce_zero105(y_out, tmp); // y_out[i] < 2^106 } // point_double_small is the same as point_double, except that it operates on // smallfelems. static void point_double_small(smallfelem x_out, smallfelem y_out, smallfelem z_out, const smallfelem x_in, const smallfelem y_in, const smallfelem z_in) { felem felem_x_out, felem_y_out, felem_z_out; felem felem_x_in, felem_y_in, felem_z_in; smallfelem_expand(felem_x_in, x_in); smallfelem_expand(felem_y_in, y_in); smallfelem_expand(felem_z_in, z_in); point_double(felem_x_out, felem_y_out, felem_z_out, felem_x_in, felem_y_in, felem_z_in); felem_shrink(x_out, felem_x_out); felem_shrink(y_out, felem_y_out); felem_shrink(z_out, felem_z_out); } // p256_copy_conditional copies in to out iff mask is all ones. static void p256_copy_conditional(felem out, const felem in, limb mask) { for (size_t i = 0; i < NLIMBS; ++i) { const limb tmp = mask & (in[i] ^ out[i]); out[i] ^= tmp; } } // copy_small_conditional copies in to out iff mask is all ones. static void copy_small_conditional(felem out, const smallfelem in, limb mask) { const uint64_t mask64 = mask; for (size_t i = 0; i < NLIMBS; ++i) { out[i] = ((limb)(in[i] & mask64)) | (out[i] & ~mask); } } // point_add calcuates (x1, y1, z1) + (x2, y2, z2) // // The method is taken from: // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl, // adapted for mixed addition (z2 = 1, or z2 = 0 for the point at infinity). // // This function includes a branch for checking whether the two input points // are equal, (while not equal to the point at infinity). This case never // happens during single point multiplication, so there is no timing leak for // ECDH or ECDSA signing. static void point_add(felem x3, felem y3, felem z3, const felem x1, const felem y1, const felem z1, const int mixed, const smallfelem x2, const smallfelem y2, const smallfelem z2) { felem ftmp, ftmp2, ftmp3, ftmp4, ftmp5, ftmp6, x_out, y_out, z_out; longfelem tmp, tmp2; smallfelem small1, small2, small3, small4, small5; limb x_equal, y_equal, z1_is_zero, z2_is_zero; felem_shrink(small3, z1); z1_is_zero = smallfelem_is_zero(small3); z2_is_zero = smallfelem_is_zero(z2); // ftmp = z1z1 = z1**2 smallfelem_square(tmp, small3); felem_reduce(ftmp, tmp); // ftmp[i] < 2^101 felem_shrink(small1, ftmp); if (!mixed) { // ftmp2 = z2z2 = z2**2 smallfelem_square(tmp, z2); felem_reduce(ftmp2, tmp); // ftmp2[i] < 2^101 felem_shrink(small2, ftmp2); felem_shrink(small5, x1); // u1 = ftmp3 = x1*z2z2 smallfelem_mul(tmp, small5, small2); felem_reduce(ftmp3, tmp); // ftmp3[i] < 2^101 // ftmp5 = z1 + z2 felem_assign(ftmp5, z1); felem_small_sum(ftmp5, z2); // ftmp5[i] < 2^107 // ftmp5 = (z1 + z2)**2 - (z1z1 + z2z2) = 2z1z2 felem_square(tmp, ftmp5); felem_reduce(ftmp5, tmp); // ftmp2 = z2z2 + z1z1 felem_sum(ftmp2, ftmp); // ftmp2[i] < 2^101 + 2^101 = 2^102 felem_diff(ftmp5, ftmp2); // ftmp5[i] < 2^105 + 2^101 < 2^106 // ftmp2 = z2 * z2z2 smallfelem_mul(tmp, small2, z2); felem_reduce(ftmp2, tmp); // s1 = ftmp2 = y1 * z2**3 felem_mul(tmp, y1, ftmp2); felem_reduce(ftmp6, tmp); // ftmp6[i] < 2^101 } else { // We'll assume z2 = 1 (special case z2 = 0 is handled later). // u1 = ftmp3 = x1*z2z2 felem_assign(ftmp3, x1); // ftmp3[i] < 2^106 // ftmp5 = 2z1z2 felem_assign(ftmp5, z1); felem_scalar(ftmp5, 2); // ftmp5[i] < 2*2^106 = 2^107 // s1 = ftmp2 = y1 * z2**3 felem_assign(ftmp6, y1); // ftmp6[i] < 2^106 } // u2 = x2*z1z1 smallfelem_mul(tmp, x2, small1); felem_reduce(ftmp4, tmp); // h = ftmp4 = u2 - u1 felem_diff_zero107(ftmp4, ftmp3); // ftmp4[i] < 2^107 + 2^101 < 2^108 felem_shrink(small4, ftmp4); x_equal = smallfelem_is_zero(small4); // z_out = ftmp5 * h felem_small_mul(tmp, small4, ftmp5); felem_reduce(z_out, tmp); // z_out[i] < 2^101 // ftmp = z1 * z1z1 smallfelem_mul(tmp, small1, small3); felem_reduce(ftmp, tmp); // s2 = tmp = y2 * z1**3 felem_small_mul(tmp, y2, ftmp); felem_reduce(ftmp5, tmp); // r = ftmp5 = (s2 - s1)*2 felem_diff_zero107(ftmp5, ftmp6); // ftmp5[i] < 2^107 + 2^107 = 2^108 felem_scalar(ftmp5, 2); // ftmp5[i] < 2^109 felem_shrink(small1, ftmp5); y_equal = smallfelem_is_zero(small1); if (x_equal && y_equal && !z1_is_zero && !z2_is_zero) { point_double(x3, y3, z3, x1, y1, z1); return; } // I = ftmp = (2h)**2 felem_assign(ftmp, ftmp4); felem_scalar(ftmp, 2); // ftmp[i] < 2*2^108 = 2^109 felem_square(tmp, ftmp); felem_reduce(ftmp, tmp); // J = ftmp2 = h * I felem_mul(tmp, ftmp4, ftmp); felem_reduce(ftmp2, tmp); // V = ftmp4 = U1 * I felem_mul(tmp, ftmp3, ftmp); felem_reduce(ftmp4, tmp); // x_out = r**2 - J - 2V smallfelem_square(tmp, small1); felem_reduce(x_out, tmp); felem_assign(ftmp3, ftmp4); felem_scalar(ftmp4, 2); felem_sum(ftmp4, ftmp2); // ftmp4[i] < 2*2^101 + 2^101 < 2^103 felem_diff(x_out, ftmp4); // x_out[i] < 2^105 + 2^101 // y_out = r(V-x_out) - 2 * s1 * J felem_diff_zero107(ftmp3, x_out); // ftmp3[i] < 2^107 + 2^101 < 2^108 felem_small_mul(tmp, small1, ftmp3); felem_mul(tmp2, ftmp6, ftmp2); longfelem_scalar(tmp2, 2); // tmp2[i] < 2*2^67 = 2^68 longfelem_diff(tmp, tmp2); // tmp[i] < 2^67 + 2^70 + 2^40 < 2^71 felem_reduce_zero105(y_out, tmp); // y_out[i] < 2^106 copy_small_conditional(x_out, x2, z1_is_zero); p256_copy_conditional(x_out, x1, z2_is_zero); copy_small_conditional(y_out, y2, z1_is_zero); p256_copy_conditional(y_out, y1, z2_is_zero); copy_small_conditional(z_out, z2, z1_is_zero); p256_copy_conditional(z_out, z1, z2_is_zero); felem_assign(x3, x_out); felem_assign(y3, y_out); felem_assign(z3, z_out); } // point_add_small is the same as point_add, except that it operates on // smallfelems. static void point_add_small(smallfelem x3, smallfelem y3, smallfelem z3, smallfelem x1, smallfelem y1, smallfelem z1, smallfelem x2, smallfelem y2, smallfelem z2) { felem felem_x3, felem_y3, felem_z3; felem felem_x1, felem_y1, felem_z1; smallfelem_expand(felem_x1, x1); smallfelem_expand(felem_y1, y1); smallfelem_expand(felem_z1, z1); point_add(felem_x3, felem_y3, felem_z3, felem_x1, felem_y1, felem_z1, 0, x2, y2, z2); felem_shrink(x3, felem_x3); felem_shrink(y3, felem_y3); felem_shrink(z3, felem_z3); } // Base point pre computation // -------------------------- // // Two different sorts of precomputed tables are used in the following code. // Each contain various points on the curve, where each point is three field // elements (x, y, z). // // For the base point table, z is usually 1 (0 for the point at infinity). // This table has 2 * 16 elements, starting with the following: // index | bits | point // ------+---------+------------------------------ // 0 | 0 0 0 0 | 0G // 1 | 0 0 0 1 | 1G // 2 | 0 0 1 0 | 2^64G // 3 | 0 0 1 1 | (2^64 + 1)G // 4 | 0 1 0 0 | 2^128G // 5 | 0 1 0 1 | (2^128 + 1)G // 6 | 0 1 1 0 | (2^128 + 2^64)G // 7 | 0 1 1 1 | (2^128 + 2^64 + 1)G // 8 | 1 0 0 0 | 2^192G // 9 | 1 0 0 1 | (2^192 + 1)G // 10 | 1 0 1 0 | (2^192 + 2^64)G // 11 | 1 0 1 1 | (2^192 + 2^64 + 1)G // 12 | 1 1 0 0 | (2^192 + 2^128)G // 13 | 1 1 0 1 | (2^192 + 2^128 + 1)G // 14 | 1 1 1 0 | (2^192 + 2^128 + 2^64)G // 15 | 1 1 1 1 | (2^192 + 2^128 + 2^64 + 1)G // followed by a copy of this with each element multiplied by 2^32. // // The reason for this is so that we can clock bits into four different // locations when doing simple scalar multiplies against the base point, // and then another four locations using the second 16 elements. // // Tables for other points have table[i] = iG for i in 0 .. 16. // g_pre_comp is the table of precomputed base points static const smallfelem g_pre_comp[2][16][3] = { {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0xf4a13945d898c296, 0x77037d812deb33a0, 0xf8bce6e563a440f2, 0x6b17d1f2e12c4247}, {0xcbb6406837bf51f5, 0x2bce33576b315ece, 0x8ee7eb4a7c0f9e16, 0x4fe342e2fe1a7f9b}, {1, 0, 0, 0}}, {{0x90e75cb48e14db63, 0x29493baaad651f7e, 0x8492592e326e25de, 0x0fa822bc2811aaa5}, {0xe41124545f462ee7, 0x34b1a65050fe82f5, 0x6f4ad4bcb3df188b, 0xbff44ae8f5dba80d}, {1, 0, 0, 0}}, {{0x93391ce2097992af, 0xe96c98fd0d35f1fa, 0xb257c0de95e02789, 0x300a4bbc89d6726f}, {0xaa54a291c08127a0, 0x5bb1eeada9d806a5, 0x7f1ddb25ff1e3c6f, 0x72aac7e0d09b4644}, {1, 0, 0, 0}}, {{0x57c84fc9d789bd85, 0xfc35ff7dc297eac3, 0xfb982fd588c6766e, 0x447d739beedb5e67}, {0x0c7e33c972e25b32, 0x3d349b95a7fae500, 0xe12e9d953a4aaff7, 0x2d4825ab834131ee}, {1, 0, 0, 0}}, {{0x13949c932a1d367f, 0xef7fbd2b1a0a11b7, 0xddc6068bb91dfc60, 0xef9519328a9c72ff}, {0x196035a77376d8a8, 0x23183b0895ca1740, 0xc1ee9807022c219c, 0x611e9fc37dbb2c9b}, {1, 0, 0, 0}}, {{0xcae2b1920b57f4bc, 0x2936df5ec6c9bc36, 0x7dea6482e11238bf, 0x550663797b51f5d8}, {0x44ffe216348a964c, 0x9fb3d576dbdefbe1, 0x0afa40018d9d50e5, 0x157164848aecb851}, {1, 0, 0, 0}}, {{0xe48ecafffc5cde01, 0x7ccd84e70d715f26, 0xa2e8f483f43e4391, 0xeb5d7745b21141ea}, {0xcac917e2731a3479, 0x85f22cfe2844b645, 0x0990e6a158006cee, 0xeafd72ebdbecc17b}, {1, 0, 0, 0}}, {{0x6cf20ffb313728be, 0x96439591a3c6b94a, 0x2736ff8344315fc5, 0xa6d39677a7849276}, {0xf2bab833c357f5f4, 0x824a920c2284059b, 0x66b8babd2d27ecdf, 0x674f84749b0b8816}, {1, 0, 0, 0}}, {{0x2df48c04677c8a3e, 0x74e02f080203a56b, 0x31855f7db8c7fedb, 0x4e769e7672c9ddad}, {0xa4c36165b824bbb0, 0xfb9ae16f3b9122a5, 0x1ec0057206947281, 0x42b99082de830663}, {1, 0, 0, 0}}, {{0x6ef95150dda868b9, 0xd1f89e799c0ce131, 0x7fdc1ca008a1c478, 0x78878ef61c6ce04d}, {0x9c62b9121fe0d976, 0x6ace570ebde08d4f, 0xde53142c12309def, 0xb6cb3f5d7b72c321}, {1, 0, 0, 0}}, {{0x7f991ed2c31a3573, 0x5b82dd5bd54fb496, 0x595c5220812ffcae, 0x0c88bc4d716b1287}, {0x3a57bf635f48aca8, 0x7c8181f4df2564f3, 0x18d1b5b39c04e6aa, 0xdd5ddea3f3901dc6}, {1, 0, 0, 0}}, {{0xe96a79fb3e72ad0c, 0x43a0a28c42ba792f, 0xefe0a423083e49f3, 0x68f344af6b317466}, {0xcdfe17db3fb24d4a, 0x668bfc2271f5c626, 0x604ed93c24d67ff3, 0x31b9c405f8540a20}, {1, 0, 0, 0}}, {{0xd36b4789a2582e7f, 0x0d1a10144ec39c28, 0x663c62c3edbad7a0, 0x4052bf4b6f461db9}, {0x235a27c3188d25eb, 0xe724f33999bfcc5b, 0x862be6bd71d70cc8, 0xfecf4d5190b0fc61}, {1, 0, 0, 0}}, {{0x74346c10a1d4cfac, 0xafdf5cc08526a7a4, 0x123202a8f62bff7a, 0x1eddbae2c802e41a}, {0x8fa0af2dd603f844, 0x36e06b7e4c701917, 0x0c45f45273db33a0, 0x43104d86560ebcfc}, {1, 0, 0, 0}}, {{0x9615b5110d1d78e5, 0x66b0de3225c4744b, 0x0a4a46fb6aaf363a, 0xb48e26b484f7a21c}, {0x06ebb0f621a01b2d, 0xc004e4048b7b0f98, 0x64131bcdfed6f668, 0xfac015404d4d3dab}, {1, 0, 0, 0}}}, {{{0, 0, 0, 0}, {0, 0, 0, 0}, {0, 0, 0, 0}}, {{0x3a5a9e22185a5943, 0x1ab919365c65dfb6, 0x21656b32262c71da, 0x7fe36b40af22af89}, {0xd50d152c699ca101, 0x74b3d5867b8af212, 0x9f09f40407dca6f1, 0xe697d45825b63624}, {1, 0, 0, 0}}, {{0xa84aa9397512218e, 0xe9a521b074ca0141, 0x57880b3a18a2e902, 0x4a5b506612a677a6}, {0x0beada7a4c4f3840, 0x626db15419e26d9d, 0xc42604fbe1627d40, 0xeb13461ceac089f1}, {1, 0, 0, 0}}, {{0xf9faed0927a43281, 0x5e52c4144103ecbc, 0xc342967aa815c857, 0x0781b8291c6a220a}, {0x5a8343ceeac55f80, 0x88f80eeee54a05e3, 0x97b2a14f12916434, 0x690cde8df0151593}, {1, 0, 0, 0}}, {{0xaee9c75df7f82f2a, 0x9e4c35874afdf43a, 0xf5622df437371326, 0x8a535f566ec73617}, {0xc5f9a0ac223094b7, 0xcde533864c8c7669, 0x37e02819085a92bf, 0x0455c08468b08bd7}, {1, 0, 0, 0}}, {{0x0c0a6e2c9477b5d9, 0xf9a4bf62876dc444, 0x5050a949b6cdc279, 0x06bada7ab77f8276}, {0xc8b4aed1ea48dac9, 0xdebd8a4b7ea1070f, 0x427d49101366eb70, 0x5b476dfd0e6cb18a}, {1, 0, 0, 0}}, {{0x7c5c3e44278c340a, 0x4d54606812d66f3b, 0x29a751b1ae23c5d8, 0x3e29864e8a2ec908}, {0x142d2a6626dbb850, 0xad1744c4765bd780, 0x1f150e68e322d1ed, 0x239b90ea3dc31e7e}, {1, 0, 0, 0}}, {{0x78c416527a53322a, 0x305dde6709776f8e, 0xdbcab759f8862ed4, 0x820f4dd949f72ff7}, {0x6cc544a62b5debd4, 0x75be5d937b4e8cc4, 0x1b481b1b215c14d3, 0x140406ec783a05ec}, {1, 0, 0, 0}}, {{0x6a703f10e895df07, 0xfd75f3fa01876bd8, 0xeb5b06e70ce08ffe, 0x68f6b8542783dfee}, {0x90c76f8a78712655, 0xcf5293d2f310bf7f, 0xfbc8044dfda45028, 0xcbe1feba92e40ce6}, {1, 0, 0, 0}}, {{0xe998ceea4396e4c1, 0xfc82ef0b6acea274, 0x230f729f2250e927, 0xd0b2f94d2f420109}, {0x4305adddb38d4966, 0x10b838f8624c3b45, 0x7db2636658954e7a, 0x971459828b0719e5}, {1, 0, 0, 0}}, {{0x4bd6b72623369fc9, 0x57f2929e53d0b876, 0xc2d5cba4f2340687, 0x961610004a866aba}, {0x49997bcd2e407a5e, 0x69ab197d92ddcb24, 0x2cf1f2438fe5131c, 0x7acb9fadcee75e44}, {1, 0, 0, 0}}, {{0x254e839423d2d4c0, 0xf57f0c917aea685b, 0xa60d880f6f75aaea, 0x24eb9acca333bf5b}, {0xe3de4ccb1cda5dea, 0xfeef9341c51a6b4f, 0x743125f88bac4c4d, 0x69f891c5acd079cc}, {1, 0, 0, 0}}, {{0xeee44b35702476b5, 0x7ed031a0e45c2258, 0xb422d1e7bd6f8514, 0xe51f547c5972a107}, {0xa25bcd6fc9cf343d, 0x8ca922ee097c184e, 0xa62f98b3a9fe9a06, 0x1c309a2b25bb1387}, {1, 0, 0, 0}}, {{0x9295dbeb1967c459, 0xb00148833472c98e, 0xc504977708011828, 0x20b87b8aa2c4e503}, {0x3063175de057c277, 0x1bd539338fe582dd, 0x0d11adef5f69a044, 0xf5c6fa49919776be}, {1, 0, 0, 0}}, {{0x8c944e760fd59e11, 0x3876cba1102fad5f, 0xa454c3fad83faa56, 0x1ed7d1b9332010b9}, {0xa1011a270024b889, 0x05e4d0dcac0cd344, 0x52b520f0eb6a2a24, 0x3a2b03f03217257a}, {1, 0, 0, 0}}, {{0xf20fc2afdf1d043d, 0xf330240db58d5a62, 0xfc7d229ca0058c3b, 0x15fee545c78dd9f6}, {0x501e82885bc98cda, 0x41ef80e5d046ac04, 0x557d9f49461210fb, 0x4ab5b6b2b8753f81}, {1, 0, 0, 0}}}}; // select_point selects the |idx|th point from a precomputation table and // copies it to out. static void select_point(const uint64_t idx, size_t size, const smallfelem pre_comp[/*size*/][3], smallfelem out[3]) { uint64_t *outlimbs = &out[0][0]; OPENSSL_memset(outlimbs, 0, 3 * sizeof(smallfelem)); for (size_t i = 0; i < size; i++) { const uint64_t *inlimbs = (const uint64_t *)&pre_comp[i][0][0]; uint64_t mask = i ^ idx; mask |= mask >> 4; mask |= mask >> 2; mask |= mask >> 1; mask &= 1; mask--; for (size_t j = 0; j < NLIMBS * 3; j++) { outlimbs[j] |= inlimbs[j] & mask; } } } // get_bit returns the |i|th bit in |in| static char get_bit(const felem_bytearray in, int i) { if (i < 0 || i >= 256) { return 0; } return (in[i >> 3] >> (i & 7)) & 1; } // Interleaved point multiplication using precomputed point multiples: The // small point multiples 0*P, 1*P, ..., 17*P are in p_pre_comp, the scalar // in p_scalar, if non-NULL. If g_scalar is non-NULL, we also add this multiple // of the generator, using certain (large) precomputed multiples in g_pre_comp. // Output point (X, Y, Z) is stored in x_out, y_out, z_out. static void batch_mul(felem x_out, felem y_out, felem z_out, const uint8_t *p_scalar, const uint8_t *g_scalar, const smallfelem p_pre_comp[17][3]) { felem nq[3], ftmp; smallfelem tmp[3]; uint64_t bits; uint8_t sign, digit; // set nq to the point at infinity OPENSSL_memset(nq, 0, 3 * sizeof(felem)); // Loop over both scalars msb-to-lsb, interleaving additions of multiples // of the generator (two in each of the last 32 rounds) and additions of p // (every 5th round). int skip = 1; // save two point operations in the first round size_t i = p_scalar != NULL ? 255 : 31; for (;;) { // double if (!skip) { point_double(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2]); } // add multiples of the generator if (g_scalar != NULL && i <= 31) { // first, look 32 bits upwards bits = get_bit(g_scalar, i + 224) << 3; bits |= get_bit(g_scalar, i + 160) << 2; bits |= get_bit(g_scalar, i + 96) << 1; bits |= get_bit(g_scalar, i + 32); // select the point to add, in constant time select_point(bits, 16, g_pre_comp[1], tmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } // second, look at the current position bits = get_bit(g_scalar, i + 192) << 3; bits |= get_bit(g_scalar, i + 128) << 2; bits |= get_bit(g_scalar, i + 64) << 1; bits |= get_bit(g_scalar, i); // select the point to add, in constant time select_point(bits, 16, g_pre_comp[0], tmp); point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 1 /* mixed */, tmp[0], tmp[1], tmp[2]); } // do other additions every 5 doublings if (p_scalar != NULL && i % 5 == 0) { bits = get_bit(p_scalar, i + 4) << 5; bits |= get_bit(p_scalar, i + 3) << 4; bits |= get_bit(p_scalar, i + 2) << 3; bits |= get_bit(p_scalar, i + 1) << 2; bits |= get_bit(p_scalar, i) << 1; bits |= get_bit(p_scalar, i - 1); ec_GFp_nistp_recode_scalar_bits(&sign, &digit, bits); // select the point to add or subtract, in constant time. select_point(digit, 17, p_pre_comp, tmp); smallfelem_neg(ftmp, tmp[1]); // (X, -Y, Z) is the negative // point copy_small_conditional(ftmp, tmp[1], (((limb)sign) - 1)); felem_contract(tmp[1], ftmp); if (!skip) { point_add(nq[0], nq[1], nq[2], nq[0], nq[1], nq[2], 0 /* mixed */, tmp[0], tmp[1], tmp[2]); } else { smallfelem_expand(nq[0], tmp[0]); smallfelem_expand(nq[1], tmp[1]); smallfelem_expand(nq[2], tmp[2]); skip = 0; } } if (i == 0) { break; } --i; } felem_assign(x_out, nq[0]); felem_assign(y_out, nq[1]); felem_assign(z_out, nq[2]); } // OPENSSL EC_METHOD FUNCTIONS // Takes the Jacobian coordinates (X, Y, Z) of a point and returns (X', Y') = // (X/Z^2, Y/Z^3). static int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *point, BIGNUM *x, BIGNUM *y, BN_CTX *ctx) { felem z1, z2, x_in, y_in; smallfelem x_out, y_out; longfelem tmp; if (EC_POINT_is_at_infinity(group, point)) { OPENSSL_PUT_ERROR(EC, EC_R_POINT_AT_INFINITY); return 0; } if (!BN_to_felem(x_in, &point->X) || !BN_to_felem(y_in, &point->Y) || !BN_to_felem(z1, &point->Z)) { return 0; } felem_inv(z2, z1); felem_square(tmp, z2); felem_reduce(z1, tmp); if (x != NULL) { felem_mul(tmp, x_in, z1); felem_reduce(x_in, tmp); felem_contract(x_out, x_in); if (!smallfelem_to_BN(x, x_out)) { OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB); return 0; } } if (y != NULL) { felem_mul(tmp, z1, z2); felem_reduce(z1, tmp); felem_mul(tmp, y_in, z1); felem_reduce(y_in, tmp); felem_contract(y_out, y_in); if (!smallfelem_to_BN(y, y_out)) { OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB); return 0; } } return 1; } static int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r, const EC_SCALAR *g_scalar, const EC_POINT *p, const EC_SCALAR *p_scalar, BN_CTX *ctx) { int ret = 0; BN_CTX *new_ctx = NULL; BIGNUM *x, *y, *z, *tmp_scalar; smallfelem p_pre_comp[17][3]; smallfelem x_in, y_in, z_in; felem x_out, y_out, z_out; if (ctx == NULL) { ctx = new_ctx = BN_CTX_new(); if (ctx == NULL) { return 0; } } BN_CTX_start(ctx); if ((x = BN_CTX_get(ctx)) == NULL || (y = BN_CTX_get(ctx)) == NULL || (z = BN_CTX_get(ctx)) == NULL || (tmp_scalar = BN_CTX_get(ctx)) == NULL) { goto err; } if (p != NULL && p_scalar != NULL) { // We treat NULL scalars as 0, and NULL points as points at infinity, i.e., // they contribute nothing to the linear combination. OPENSSL_memset(&p_pre_comp, 0, sizeof(p_pre_comp)); // Precompute multiples. if (!BN_to_felem(x_out, &p->X) || !BN_to_felem(y_out, &p->Y) || !BN_to_felem(z_out, &p->Z)) { goto err; } felem_shrink(p_pre_comp[1][0], x_out); felem_shrink(p_pre_comp[1][1], y_out); felem_shrink(p_pre_comp[1][2], z_out); for (size_t j = 2; j <= 16; ++j) { if (j & 1) { point_add_small(p_pre_comp[j][0], p_pre_comp[j][1], p_pre_comp[j][2], p_pre_comp[1][0], p_pre_comp[1][1], p_pre_comp[1][2], p_pre_comp[j - 1][0], p_pre_comp[j - 1][1], p_pre_comp[j - 1][2]); } else { point_double_small(p_pre_comp[j][0], p_pre_comp[j][1], p_pre_comp[j][2], p_pre_comp[j / 2][0], p_pre_comp[j / 2][1], p_pre_comp[j / 2][2]); } } } batch_mul(x_out, y_out, z_out, (p != NULL && p_scalar != NULL) ? p_scalar->bytes : NULL, g_scalar != NULL ? g_scalar->bytes : NULL, (const smallfelem(*)[3]) & p_pre_comp); // reduce the output to its unique minimal representation felem_contract(x_in, x_out); felem_contract(y_in, y_out); felem_contract(z_in, z_out); if (!smallfelem_to_BN(x, x_in) || !smallfelem_to_BN(y, y_in) || !smallfelem_to_BN(z, z_in)) { OPENSSL_PUT_ERROR(EC, ERR_R_BN_LIB); goto err; } ret = ec_point_set_Jprojective_coordinates_GFp(group, r, x, y, z, ctx); err: BN_CTX_end(ctx); BN_CTX_free(new_ctx); return ret; } DEFINE_METHOD_FUNCTION(EC_METHOD, EC_GFp_nistp256_method) { out->group_init = ec_GFp_simple_group_init; out->group_finish = ec_GFp_simple_group_finish; out->group_set_curve = ec_GFp_simple_group_set_curve; out->point_get_affine_coordinates = ec_GFp_nistp256_point_get_affine_coordinates; out->mul = ec_GFp_nistp256_points_mul; out->field_mul = ec_GFp_simple_field_mul; out->field_sqr = ec_GFp_simple_field_sqr; out->field_encode = NULL; out->field_decode = NULL; }; #endif // 64_BIT && !WINDOWS
mit
stefangordon/AzureIoT
src/sdk/agenttypesystem.c
3
163430
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include <stdlib.h> #ifdef _CRTDBG_MAP_ALLOC #include <crtdbg.h> #endif #include "gballoc.h" #include "agenttypesystem.h" #include <inttypes.h> #ifdef _MSC_VER #pragma warning(disable: 4756) /* Known warning for INFINITY */ #endif #include <stddef.h> #include <float.h> #include <math.h> #include <limits.h> /*if ULLONG_MAX is defined by limits.h for whatever reasons... */ #ifndef ULLONG_MAX #define ULLONG_MAX 18446744073709551615 #endif #include "crt_abstractions.h" #include "jsonencoder.h" #include "multitree.h" #include "iot_logging.h" #define NaN_STRING "NaN" #define MINUSINF_STRING "-INF" #define PLUSINF_STRING "INF" #ifndef _HUGE_ENUF #define _HUGE_ENUF 1e+300 /* _HUGE_ENUF*_HUGE_ENUF must overflow */ #endif /* _HUGE_ENUF */ #ifndef INFINITY #define INFINITY ((float)(_HUGE_ENUF * _HUGE_ENUF)) /* causes warning C4756: overflow in constant arithmetic (by design) */ #endif /* INFINITY */ #ifndef NAN #define NAN ((float)(INFINITY * 0.0F)) #endif /* NAN */ #define GUID_STRING_LENGTH 38 // This is an artificial upper limit on floating point string length // (e.g. the size of the string when printing %f). It is set to twice the // maximum decimal precision plus 2. 1 for the decimal point and 1 for a // sign (+/-) // Unfortunately it is quite possible to print a float larger than this. // An example of this would be printf("%.*f", MAX_FLOATING_POINT_STRING_LENGTH, 1.3); // But currently no explicit requests for this exist in the file nor are // any expected to reasonably occur when being used (numbers that hit // this limit would be experiencing significant precision loss in storage anyway. #define MAX_FLOATING_POINT_STRING_LENGTH (DECIMAL_DIG *2 + 2) // This maximum length is 11 for 32 bit integers (including the sign) // optionally increase to 21 if longs are 64 bit #define MAX_LONG_STRING_LENGTH ( 11 + (10 * (sizeof(long)/ 8))) // This is the maximum length for the largest 64 bit number (signed) #define MAX_ULONG_LONG_STRING_LENGTH 20 DEFINE_ENUM_STRINGS(AGENT_DATA_TYPES_RESULT, AGENT_DATA_TYPES_RESULT_VALUES); static int ValidateDate(int year, int month, int day); static int NoCloneFunction(void** destination, const void* source) { *destination = (void*)source; return 0; } static void NoFreeFunction(void* value) { (void)value; } static const char base64char[64] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_' }; static const char base64b16[16] = { 'A', 'E', 'I', 'M', 'Q', 'U', 'Y', 'c', 'g', 'k', 'o', 's', 'w', '0', '4', '8' }; static const char base64b8[4] = { 'A' , 'Q' , 'g' , 'w' }; #define IS_DIGIT(a) (('0'<=(a)) &&((a)<='9')) /*creates an AGENT_DATA_TYPE containing a EDM_BOOLEAN from a int*/ AGENT_DATA_TYPES_RESULT Create_EDM_BOOLEAN_from_int(AGENT_DATA_TYPE* agentData, int v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[All the Create_... functions shall check their parameters for validity.When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned]*/ if(agentData==NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_031:[ Creates a AGENT_DATA_TYPE representing an EDM_BOOLEAN.]*/ agentData->type = EDM_BOOLEAN_TYPE; agentData->value.edmBoolean.value = (v)?(EDM_TRUE):(EDM_FALSE); result = AGENT_DATA_TYPES_OK; } return result; } /*creates an AGENT_DATA_TYPE containing a UINT8*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_UINT8(AGENT_DATA_TYPE* agentData, uint8_t v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_BYTE_TYPE; agentData->value.edmByte.value = v; result = AGENT_DATA_TYPES_OK; } return result; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_091:[Creates an AGENT_DATA_TYPE containing an Edm.DateTimeOffset from an EDM_DATE_TIME_OFFSET.]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_EDM_DATE_TIME_OFFSET(AGENT_DATA_TYPE* agentData, EDM_DATE_TIME_OFFSET v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ]*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (ValidateDate(v.dateTime.tm_year+1900, v.dateTime.tm_mon +1 , v.dateTime.tm_mday) != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_092:[ The structure shall be validated to be conforming to OData specifications (odata-abnf-construction-rules, 2013), and if found invalid, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; } else if ( (v.dateTime.tm_hour > 23) || (v.dateTime.tm_hour < 0) || (v.dateTime.tm_min > 59) || (v.dateTime.tm_min < 0) || (v.dateTime.tm_sec > 59) || (v.dateTime.tm_sec < 0) ) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_092:[ The structure shall be validated, and if found invalid, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; } else if ((v.hasFractionalSecond) && (v.fractionalSecond > 999999999999)) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_092:[ The structure shall be validated to be conforming to OData specifications (odata-abnf-construction-rules, 2013), and if found invalid, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; } else if ( (v.hasTimeZone) && ( (v.timeZoneHour<-23) || (v.timeZoneHour>23) || (v.timeZoneMinute>59) ) ) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_092:[ The structure shall be validated to be conforming to OData specifications (odata-abnf-construction-rules, 2013), and if found invalid, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; } else { agentData->type = EDM_DATE_TIME_OFFSET_TYPE; agentData->value.edmDateTimeOffset = v; result = AGENT_DATA_TYPES_OK; } return result; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_094:[ Creates and AGENT_DATA_TYPE containing a EDM_GUID from an EDM_GUID]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_EDM_GUID(AGENT_DATA_TYPE* agentData, EDM_GUID v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the functions shall check their parameters for validity. When an invalid parameter is detected, the value AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("result = %s \r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_094:[ Creates and AGENT_DATA_TYPE containing a EDM_GUID from an EDM_GUID]*/ agentData->type = EDM_GUID_TYPE; memmove(agentData->value.edmGuid.GUID, v.GUID, 16); result = AGENT_DATA_TYPES_OK; } return result; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_098:[ Creates an AGENT_DATA_TYPE containing a EDM_BINARY from a EDM_BINARY.]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_EDM_BINARY(AGENT_DATA_TYPE* agentData, EDM_BINARY v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the functions shall check their parameters for validity. When an invalid parameter is detected, the value AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("result = %s\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_098:[ Creates an AGENT_DATA_TYPE containing a EDM_BINARY from a EDM_BINARY.]*/ if (v.data == NULL) { if (v.size != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("result = %s \r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_BINARY_TYPE; agentData->value.edmBinary.size = 0; agentData->value.edmBinary.data = NULL; result = AGENT_DATA_TYPES_OK; } } else { if (v.size != 0) { /*make a copy*/ if ((agentData->value.edmBinary.data = (unsigned char*)malloc(v.size)) == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("result = %s\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { memcpy(agentData->value.edmBinary.data, v.data, v.size); agentData->type = EDM_BINARY_TYPE; agentData->value.edmBinary.size = v.size; result = AGENT_DATA_TYPES_OK; } } else { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("result = %s\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } } } return result; } /*scans sign, if any*/ /*if no sign, then it will set *sign to = +1*/ /*if sign, then it will set *sign to = +/-1*/ static void scanOptionalSign(const char* source, size_t sourceSize, size_t* position, int* sign) { if (*position < sourceSize) { if (source[*position] == '-') { *sign = -1; (*position)++; } else if (source[*position] == '+') { *sign = +1; (*position)++; } else { *sign = +1; } } } /*scans a minus sign, if any*/ /*if no sign, then it will set *sign to = +1*/ /*if sign, then it will set *sign to = +/-1*/ static void scanOptionalMinusSign(const char* source, size_t sourceSize, size_t* position, int* sign) { if (*position < sourceSize) { if (source[*position] == '-') { *sign = -1; (*position)++; } else { *sign = +1; } } } /*this function alawys returns 0 if it processed 1 digit*/ /*return 1 when error (such as wrong parameters)*/ static int scanMandatoryOneDigit(const char* source, size_t sourceSize, size_t* position) { int result; if (*position < sourceSize) { if (IS_DIGIT(source[*position])) { (*position)++; result = 0; } else { result = 1; } } else { result = 1; } return result; } /*scans digits, if any*/ static void scanOptionalNDigits(const char* source, size_t sourceSize, size_t* position) { while (*position < sourceSize) { if (IS_DIGIT(source[*position])) { (*position)++; } else { break; } } } /*from the string pointed to by source, having the size sourceSize, starting at initial position *position*/ /*this function will attempt to read a decimal number having an optional sign(+/-) followed by precisely N digits */ /*will return 0 if in the string there was a number and that number has been read in the *value parameter*/ /*will update position parameter to reflect the first character not belonging to the number*/ static int scanAndReadNDigitsInt(const char* source, size_t sourceSize, size_t* position, int *value, size_t N) { N++; *value = 0; while ((*position < sourceSize) && (N > 0)) { if (IS_DIGIT(source[*position])) { *value *= 10; *value += (source[*position] - '0'); (*position)++; } else { break; } N--; } return N != 1; } /*this function alawys returns 0 if it found a dot followed by at least digit*/ /*return 1 when error (such as wrong parameters)*/ static int scanOptionalDotAndDigits(const char* source, size_t sourceSize, size_t* position) { int result = 0; if (*position < sourceSize) { if (source[*position] == '.') { (*position)++; if (scanMandatoryOneDigit(source, sourceSize, position) != 0) { /* not a digit following the dot... */ result = 1; } else { scanOptionalNDigits(source, sourceSize, position); } } else { /*not a dot, don't care*/ } } return result; } static int scanMandatory1CapitalHexDigit(const char* source, uint8_t* value) { int result = 0; if (('0' <= source[0]) && (source[0] <= '9')) { *value = (source[0] - '0'); } else if (('A' <= source[0]) && (source[0] <= 'F')) { *value = (source[0] - 'A'+10); } else { result = 1; } return result; } /*this function alawys returns 0 if it found 2 hex digits, also updates the *value parameter*/ /*return 1 when error (such as wrong parameters)*/ static int scanMandatory2CapitalHexDigits(const char* source, uint8_t* value) { int result; uint8_t temp; if (scanMandatory1CapitalHexDigit(source, &temp) == 0) { *value = temp*16; if (scanMandatory1CapitalHexDigit(source + 1, &temp) == 0) { *value += temp; result = 0; } else { result = 1; } } else { result = 2; } return result; } static int ValidateDecimal(const char* v, size_t vlen) { int result; int sign = 0; size_t validatePosition = 0; scanOptionalSign(v, vlen, &validatePosition, &sign); if (scanMandatoryOneDigit(v, vlen, &validatePosition) != 0) { result = 1; } else { scanOptionalNDigits(v, vlen, &validatePosition); if (scanOptionalDotAndDigits(v, vlen, &validatePosition) != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_067:[ If the string indicated by the parameter v does not match exactly an ODATA string representation, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } else if (validatePosition != vlen) /*Trailing wrong characters*/ { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_067:[ If the string indicated by the parameter v does not match exactly an ODATA string representation, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } else { result = 0; } } return result; } /*return 0 if everything went ok*/ /*takes 1 base64char and returns its value*/ static int base64toValue(char base64charSource, unsigned char* value) { int result; if (('A' <= base64charSource) && (base64charSource <= 'Z')) { *value = base64charSource - 'A'; result = 0; } else if (('a' <= base64charSource) && (base64charSource <= 'z')) { *value = ('Z' - 'A') +1+ (base64charSource - 'a'); result = 0; } else if (('0' <= base64charSource) && (base64charSource <= '9')) { *value = ('Z' - 'A') +1+('z'-'a')+1 +(base64charSource - '0'); result = 0; } else if ('-' == base64charSource) { *value = 62; result = 0; } else if ('_' == base64charSource) { *value = 63; result = 0; } else { result = 1; } return result; } /*returns 0 if everything went ok*/ /*scans 4 base64 characters and returns 3 usual bytes*/ static int scan4base64char(const char* source, size_t sourceSize, unsigned char *destination0, unsigned char* destination1, unsigned char* destination2) { int result; if (sourceSize < 4) { result = 1; } else { unsigned char b0, b1, b2, b3; if ( (base64toValue(source[0], &b0) == 0) && (base64toValue(source[1], &b1) == 0) && (base64toValue(source[2], &b2) == 0) && (base64toValue(source[3], &b3) == 0) ) { *destination0 = (b0 << 2) | ((b1 & 0x30) >> 4); *destination1 = ((b1 & 0x0F)<<4) | ((b2 & 0x3C) >>2 ); *destination2 = ((b2 & 0x03) << 6) | (b3); result = 0; } else { result = 2; } } return result; } /*return 0 if the character is one of ( 'A' / 'E' / 'I' / 'M' / 'Q' / 'U' / 'Y' / 'c' / 'g' / 'k' / 'o' / 's' / 'w' / '0' / '4' / '8' )*/ static int base64b16toValue(unsigned char source, unsigned char* destination) { unsigned char i; for (i = 0; i <= 15; i++) { if (base64b16[i] == source) { *destination = i; return 0; } } return 1; } /*return 0 if the character is one of ( 'A' / 'Q' / 'g' / 'w' )*/ static int base64b8toValue(unsigned char source, unsigned char* destination) { unsigned char i; for (i = 0; i <= 3; i++) { if (base64b8[i] == source) { *destination = i; return 0; } } return 1; } /*returns 0 if everything went ok*/ /*scans 2 base64 characters + 1 special + 1 optional = and returns 2 usual bytes*/ int scanbase64b16(const char* source, size_t sourceSize, size_t *consumed, unsigned char* destination0, unsigned char* destination1) { int result; if (sourceSize < 3) { result = 1; } else { unsigned char c0, c1, c2; *consumed = 0; if ( (base64toValue(source[0], &c0) == 0) && (base64toValue(source[1], &c1) == 0) && (base64b16toValue(source[2], &c2) == 0) ) { *consumed = 3 + ((sourceSize>=3)&&(source[3] == '=')); /*== produce 1 or 0 ( in C )*/ *destination0 = (c0 << 2) | ((c1 & 0x30) >> 4); *destination1 = ((c1 &0x0F) <<4) | c2; result = 0; } else { result = 2; } } return result; } /*return 0 if everything is ok*/ /*Reads base64b8 = base64char ( 'A' / 'Q' / 'g' / 'w' ) [ "==" ]*/ int scanbase64b8(const char* source, size_t sourceSize, size_t *consumed, unsigned char* destination0) { int result; if (sourceSize < 2) { result = 1; } else { unsigned char c0, c1; if ( (base64toValue(source[0], &c0) == 0) && (base64b8toValue(source[1], &c1) == 0) ) { *consumed = 2 + (((sourceSize>=4) && (source[2] == '=') && (source[3] == '='))?2:0); /*== produce 1 or 0 ( in C )*/ *destination0 = (c0 << 2) | (c1 & 3); result = 0; } else { result = 2; } } return result; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_039:[ Creates an AGENT_DATA_TYPE containing an EDM_DECIMAL from a null-terminated string.]*/ AGENT_DATA_TYPES_RESULT Create_EDM_DECIMAL_from_charz(AGENT_DATA_TYPE* agentData, const char* v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (v == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t vlen = strlen(v); /*validate that v has the form [SIGN] 1*DIGIT ["." 1*DIGIT]*/ if (vlen == 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_067:[ If the string indicated by the parameter v does not match exactly an ODATA string representation, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (ValidateDecimal(v, vlen) != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_067:[ If the string indicated by the parameter v does not match exactly an ODATA string representation, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if ((agentData->value.edmDecimal.value = STRING_construct(v)) == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_DECIMAL_TYPE; result = AGENT_DATA_TYPES_OK; } } } return result; } /*create an AGENT_DATA_TYPE containing an EDM_DOUBLE from a double*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_DOUBLE(AGENT_DATA_TYPE* agentData, double v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[All the Create_... functions shall check their parameters for validity.When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned]*/ if(agentData==NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_041:[Creates an AGENT_DATA_TYPE containing an EDM_DOUBLE from double]*/ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_042:[Values of NaN, -INF, +INF are accepted]*/ agentData->type = EDM_DOUBLE_TYPE; agentData->value.edmDouble.value = v; result = AGENT_DATA_TYPES_OK; } return result; } /*create an AGENT_DATA_TYPE from INT16_T*/ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_043:[ Creates an AGENT_DATA_TYPE containing an EDM_INT16 from int16_t]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_SINT16(AGENT_DATA_TYPE* agentData, int16_t v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_INT16_TYPE; agentData->value.edmInt16.value = v; result = AGENT_DATA_TYPES_OK; } return result; } /*create an AGENT_DATA_TYPE from INT32_T*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_SINT32(AGENT_DATA_TYPE* agentData, int32_t v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_INT32_TYPE; agentData->value.edmInt32.value = v; result = AGENT_DATA_TYPES_OK; } return result; } /*create an AGENT_DATA_TYPE from INT64_T*/ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_045:[ Creates an AGENT_DATA_TYPE containing an EDM_INT64 from int64_t]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_SINT64(AGENT_DATA_TYPE* agentData, int64_t v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_INT64_TYPE; agentData->value.edmInt64.value = v; result = AGENT_DATA_TYPES_OK; } return result; } /*create an AGENT_DATA_TYPE from int8_t*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_SINT8(AGENT_DATA_TYPE* agentData, int8_t v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_SBYTE_TYPE; agentData->value.edmSbyte.value = v; result = AGENT_DATA_TYPES_OK; } return result; } static int ValidateDate(int year, int month, int day) { int result; if ((year <= -10000) || (year >= 10000)) { result = 1; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[ If year-month-date does not indicate a valid day (for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ if (day <= 0) { result = 1; } else { /*the following data will be validated...*/ /*leap years are those that can be divided by 4. But if the year can be divided by 100, it is not leap. But if they year can be divided by 400 it is leap*/ if ( (month == 1) || /*these months have always 31 days*/ (month == 3) || (month == 5) || (month == 7) || (month == 8) || (month == 10) || (month == 12) ) { if (day <= 31) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } else if ( (month == 4) || (month == 6) || (month == 9) || (month == 11) ) { if (day <= 30) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = -1; } } else if (month == 2)/*february*/ { if ((year % 400) == 0) { /*these are leap years, suchs as 2000*/ if (day <= 29) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } else if ((year % 100) == 0) { /*non-leap year, such as 1900*/ if (day <= 28) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } else if ((year % 4) == 0) { /*these are leap years, such as 2104*/ if (day <= 29) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } else { /*certainly not a leap year*/ if (day <= 28) { result = 0; } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_070:[If year - month - date does not indicate a valid day(for example 31 Feb 2013), then AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ result = 1; } } } return result; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_069:[ Creates an AGENT_DATA_TYPE containing an EDM_DATE from a year, a month and a day of the month.]*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_date(AGENT_DATA_TYPE* agentData, int16_t year, uint8_t month, uint8_t day) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*ODATA-ABNF: year = [ "-" ] ( "0" 3DIGIT / oneToNine 3*DIGIT )*/ else if (ValidateDate(year, month, day) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_069:[ Creates an AGENT_DATA_TYPE containing an EDM_DATE from a year, a month and a day of the month.]*/ agentData->type = EDM_DATE_TYPE; agentData->value.edmDate.year = year; agentData->value.edmDate.month = month; agentData->value.edmDate.day = day; result = AGENT_DATA_TYPES_OK; } return result; } /*create an AGENT_DATA_TYPE from SINGLE*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_FLOAT(AGENT_DATA_TYPE* agentData, float v) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[All the Create_... functions shall check their parameters for validity.When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned]*/ if(agentData==NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_SINGLE_TYPE; agentData->value.edmSingle.value = v; result = AGENT_DATA_TYPES_OK; } return result; } const char hexToASCII[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; /*create an AGENT_DATA_TYPE from ANSI zero terminated string*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_charz(AGENT_DATA_TYPE* agentData, const char* v) { AGENT_DATA_TYPES_RESULT result = AGENT_DATA_TYPES_OK; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (v == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_049:[ Creates an AGENT_DATA_TYPE containing an EDM_STRING from an ASCII zero terminated string.]*/ agentData->type = EDM_STRING_TYPE; if (mallocAndStrcpy_s(&agentData->value.edmString.chars, v) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->value.edmString.length = strlen(agentData->value.edmString.chars); result = AGENT_DATA_TYPES_OK; } } return result; } /*create an AGENT_DATA_TYPE from ANSI zero terminated string (without quotes) */ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_charz_no_quotes(AGENT_DATA_TYPE* agentData, const char* v) { AGENT_DATA_TYPES_RESULT result = AGENT_DATA_TYPES_OK; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the Create_... functions shall check their parameters for validity. When an invalid parameter is detected, a code of AGENT_DATA_TYPES_INVALID_ARG shall be returned ].*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (v == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /* Codes_SRS_AGENT_TYPE_SYSTEM_01_001: [Creates an AGENT_DATA_TYPE containing an EDM_STRING from an ASCII zero terminated string.] */ agentData->type = EDM_STRING_NO_QUOTES_TYPE; if (mallocAndStrcpy_s(&agentData->value.edmStringNoQuotes.chars, v) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->value.edmStringNoQuotes.length = strlen(agentData->value.edmStringNoQuotes.chars); result = AGENT_DATA_TYPES_OK; } } return result; } void Destroy_AGENT_DATA_TYPE(AGENT_DATA_TYPE* agentData) { if(agentData==NULL) { LogError("agentData was NULL.\r\n"); } else { switch(agentData->type) { default: { LogError("invalid agentData\r\n"); break; } case(EDM_NO_TYPE): { LogError("invalid agentData\r\n"); break; } case(EDM_BINARY_TYPE): { /*destroying means maybe deallocating some memory*/ free(agentData->value.edmBinary.data); /* If ptr is a null pointer, no action occurs*/ agentData->value.edmBinary.data = NULL; break; } case(EDM_BOOLEAN_TYPE): { /*nothing to do*/ break; } case(EDM_BYTE_TYPE): { /*nothing to do*/ break; } case(EDM_DATE_TYPE): { /*nothing to do*/ break; } case(EDM_DATE_TIME_OFFSET_TYPE): { /*nothing to do*/ break; } case(EDM_DECIMAL_TYPE): { STRING_delete(agentData->value.edmDecimal.value); agentData->value.edmDecimal.value = NULL; break; } case(EDM_DURATION_TYPE): { LogError("EDM_DURATION_TYPE not implemented\r\n"); break; } case(EDM_GUID_TYPE): { /*nothing to do*/ break; } case(EDM_INT16_TYPE): { /*nothing to do*/ break; } case(EDM_INT32_TYPE): { /*nothing to do*/ break; } case(EDM_INT64_TYPE): { /*nothing to do*/ break; } case(EDM_SBYTE_TYPE): { /*nothing to do*/ break; } case(EDM_STREAM): { LogError("EDM_STREAM not implemented\r\n"); break; } case(EDM_STRING_TYPE): { if (agentData->value.edmString.chars != NULL) { free(agentData->value.edmString.chars); agentData->value.edmString.chars = NULL; } break; } case(EDM_STRING_NO_QUOTES_TYPE) : { if (agentData->value.edmStringNoQuotes.chars != NULL) { free(agentData->value.edmStringNoQuotes.chars); agentData->value.edmStringNoQuotes.chars = NULL; } break; } case(EDM_TIME_OF_DAY_TYPE) : { LogError("EDM_TIME_OF_DAY_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_TYPE): { LogError("EDM_GEOGRAPHY_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_POINT_TYPE): { LogError("EDM_GEOGRAPHY_POINT_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_LINE_STRING_TYPE): { LogError("EDM_GEOGRAPHY_LINE_STRING_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_POLYGON_TYPE): { LogError("EDM_GEOGRAPHY_POLYGON_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_MULTI_POINT_TYPE): { LogError("EDM_GEOGRAPHY_MULTI_POINT_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_MULTI_LINE_STRING_TYPE): { LogError("EDM_GEOGRAPHY_MULTI_LINE_STRING_TYPE not implemented\r\n"); break; } case(EDM_GEOGRAPHY_MULTI_POLYGON_TYPE): { LogError("EDM_GEOGRAPHY_MULTI_POLYGON_TYPE\r\n"); break; } case(EDM_GEOGRAPHY_COLLECTION_TYPE): { LogError("EDM_GEOGRAPHY_COLLECTION_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_TYPE): { LogError("EDM_GEOMETRY_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_POINT_TYPE): { LogError("EDM_GEOMETRY_POINT_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_LINE_STRING_TYPE): { LogError("EDM_GEOMETRY_LINE_STRING_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_POLYGON_TYPE): { LogError("EDM_GEOMETRY_POLYGON_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_MULTI_POINT_TYPE): { LogError("EDM_GEOMETRY_MULTI_POINT_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_MULTI_LINE_STRING_TYPE): { LogError("EDM_GEOMETRY_MULTI_LINE_STRING_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_MULTI_POLYGON_TYPE): { LogError("EDM_GEOMETRY_MULTI_POLYGON_TYPE not implemented\r\n"); break; } case(EDM_GEOMETRY_COLLECTION_TYPE): { LogError("EDM_GEOMETRY_COLLECTION_TYPE not implemented\r\n"); break; } case(EDM_SINGLE_TYPE): { break; } case(EDM_DOUBLE_TYPE): { break; } case (EDM_COMPLEX_TYPE_TYPE): { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_050:[Destroy_AGENT_DATA_TYPE shall deallocate all allocated resources used to represent the type.]*/ size_t i; for (i = 0; i < agentData->value.edmComplexType.nMembers; i++) { free((void*)(agentData->value.edmComplexType.fields[i].fieldName)); agentData->value.edmComplexType.fields[i].fieldName = NULL; Destroy_AGENT_DATA_TYPE(agentData->value.edmComplexType.fields[i].value); free(agentData->value.edmComplexType.fields[i].value); agentData->value.edmComplexType.fields[i].value = NULL; } free(agentData->value.edmComplexType.fields); break; } } agentData->type = EDM_NO_TYPE; /*mark as detroyed*/ } } static char hexDigitToChar(uint8_t hexDigit) { if (hexDigit < 10) return '0' + hexDigit; else return ('A' - 10) + hexDigit; } AGENT_DATA_TYPES_RESULT AgentDataTypes_ToString(STRING_HANDLE destination, const AGENT_DATA_TYPE* value) { AGENT_DATA_TYPES_RESULT result; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_015:[If destination parameter is NULL, AgentDataTypes_ToString shall return AGENT_DATA_TYPES_INVALID_ARG.]*/ if(destination == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_053:[ If value is NULL or has been destroyed or otherwise doesn't contain valid data, AGENT_DATA_TYPES_INVALID_ARG shall be returned.]*/ else if (value == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { switch(value->type) { default: { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_NULL_TYPE) : { /*SRS_AGENT_TYPE_SYSTEM_99_101:[ EDM_NULL_TYPE shall return the unquoted string null.]*/ if (STRING_concat(destination, "null") != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_014:[ All functions shall return AGENT_DATA_TYPES_OK when the processing is successful.]*/ result = AGENT_DATA_TYPES_OK; } break; } case(EDM_BOOLEAN_TYPE) : { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_017:[EDM_BOOLEAN:as in(odata - abnf - construction - rules, 2013), booleanValue = "true" / "false"]*/ if (value->value.edmBoolean.value == EDM_TRUE) { /*SRS_AGENT_TYPE_SYSTEM_99_030:[If v is different than 0 then the AGENT_DATA_TYPE shall have the value "true".]*/ if (STRING_concat(destination, "true") != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_014:[ All functions shall return AGENT_DATA_TYPES_OK when the processing is successful.]*/ result = AGENT_DATA_TYPES_OK; } } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_017:[EDM_BOOLEAN:as in(odata - abnf - construction - rules, 2013), booleanValue = "true" / "false"]*/ else if (value->value.edmBoolean.value == EDM_FALSE) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_029:[ If v 0 then the AGENT_DATA_TYPE shall have the value "false" Boolean.]*/ if (STRING_concat(destination, "false") != 0) { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_014:[ All functions shall return AGENT_DATA_TYPES_OK when the processing is successful.]*/ result = AGENT_DATA_TYPES_OK; } } else { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_053:[ If value contains invalid data, AgentDataTypes_ToString shall return AGENT_DATA_TYPES_INVALID_ARG.]*/ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } break; } case(EDM_BYTE_TYPE) : { char tempbuffer2[4]; /*because bytes can at most be 255 and that is 3 characters + 1 for '\0'*/ size_t pos = 0; if (value->value.edmByte.value >= 100) tempbuffer2[pos++] = '0' + (value->value.edmByte.value / 100); if (value->value.edmByte.value >= 10) tempbuffer2[pos++] = '0' + (value->value.edmByte.value % 100) / 10; tempbuffer2[pos++] = '0' + (value->value.edmByte.value % 10); tempbuffer2[pos++] = '\0'; if (STRING_concat(destination, tempbuffer2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case(EDM_DATE_TYPE) : { size_t pos = 0; char tempBuffer2[1 + 5 + 1 + 2 + 1 + 2 + 1+1]; int16_t year = value->value.edmDate.year; tempBuffer2[pos++] = '\"'; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_068:[ EDM_DATE: dateValue = year "-" month "-" day.]*/ if (year < 0) { tempBuffer2[pos++] = '-'; year = -year; } tempBuffer2[pos++] = '0' + (char)(year / 1000); tempBuffer2[pos++] = '0' + (char)((year % 1000) / 100); tempBuffer2[pos++] = '0' + (char)((year % 100) / 10); tempBuffer2[pos++] = '0' + (char)(year % 10); tempBuffer2[pos++] = '-'; tempBuffer2[pos++] = '0' + value->value.edmDate.month / 10; tempBuffer2[pos++] = '0' + value->value.edmDate.month % 10; tempBuffer2[pos++] = '-'; tempBuffer2[pos++] = '0' + value->value.edmDate.day / 10; tempBuffer2[pos++] = '0' + value->value.edmDate.day % 10; tempBuffer2[pos++] = '\"'; tempBuffer2[pos++] = '\0'; if (STRING_concat(destination, tempBuffer2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_DATE_TIME_OFFSET_TYPE): { /*Codes_SRS_AGENT_TYPE_SYSTEM_99_019:[ EDM_DATETIMEOFFSET: dateTimeOffsetValue = year "-" month "-" day "T" hour ":" minute [ ":" second [ "." fractionalSeconds ] ] ( "Z" / sign hour ":" minute )]*/ /*from ABNF seems like these numbers HAVE to be padded with zeroes*/ if (value->value.edmDateTimeOffset.hasTimeZone) { if (value->value.edmDateTimeOffset.hasFractionalSecond) { size_t tempBufferSize = 1 + // \" MAX_LONG_STRING_LENGTH + // %.4d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // T MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // . MAX_ULONG_LONG_STRING_LENGTH + // %.12llu 1 + MAX_LONG_STRING_LENGTH + // %+.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + //\" 1; // " (terminating NULL); char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "\"%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.12llu%+.2d:%.2d\"", /*+ in printf forces the sign to appear*/ value->value.edmDateTimeOffset.dateTime.tm_year+1900, value->value.edmDateTimeOffset.dateTime.tm_mon+1, value->value.edmDateTimeOffset.dateTime.tm_mday, value->value.edmDateTimeOffset.dateTime.tm_hour, value->value.edmDateTimeOffset.dateTime.tm_min, value->value.edmDateTimeOffset.dateTime.tm_sec, value->value.edmDateTimeOffset.fractionalSecond, value->value.edmDateTimeOffset.timeZoneHour, value->value.edmDateTimeOffset.timeZoneMinute) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } // Clean up temp buffer if allocated free(tempBuffer); } } else { size_t tempBufferSize = 1 + // \" MAX_LONG_STRING_LENGTH + // %.4d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // T MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + MAX_LONG_STRING_LENGTH + // %+.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // \" 1; // " terminating NULL char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "\"%.4d-%.2d-%.2dT%.2d:%.2d:%.2d%+.2d:%.2d\"", /*+ in printf forces the sign to appear*/ value->value.edmDateTimeOffset.dateTime.tm_year + 1900, value->value.edmDateTimeOffset.dateTime.tm_mon+1, value->value.edmDateTimeOffset.dateTime.tm_mday, value->value.edmDateTimeOffset.dateTime.tm_hour, value->value.edmDateTimeOffset.dateTime.tm_min, value->value.edmDateTimeOffset.dateTime.tm_sec, value->value.edmDateTimeOffset.timeZoneHour, value->value.edmDateTimeOffset.timeZoneMinute) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } // Clean up temp buffer if allocated free(tempBuffer); } } } else { if (value->value.edmDateTimeOffset.hasFractionalSecond) { size_t tempBufferSize = 1 + //\" MAX_LONG_STRING_LENGTH + // %.4d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // T MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // . MAX_ULONG_LONG_STRING_LENGTH + // %.12llu 1 + // Z 1 + // \" 1; // " (terminating NULL) char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "\"%.4d-%.2d-%.2dT%.2d:%.2d:%.2d.%.12lluZ\"", /*+ in printf forces the sign to appear*/ value->value.edmDateTimeOffset.dateTime.tm_year + 1900, value->value.edmDateTimeOffset.dateTime.tm_mon+1, value->value.edmDateTimeOffset.dateTime.tm_mday, value->value.edmDateTimeOffset.dateTime.tm_hour, value->value.edmDateTimeOffset.dateTime.tm_min, value->value.edmDateTimeOffset.dateTime.tm_sec, value->value.edmDateTimeOffset.fractionalSecond) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(tempBuffer); } } else { size_t tempBufferSize = 1 + // \" MAX_LONG_STRING_LENGTH + // %.4d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // - MAX_LONG_STRING_LENGTH + // %.2d 1 + // T MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // : MAX_LONG_STRING_LENGTH + // %.2d 1 + // Z 1 + // \" 1; // " (terminating null); char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "\"%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ\"", value->value.edmDateTimeOffset.dateTime.tm_year + 1900, value->value.edmDateTimeOffset.dateTime.tm_mon+1, value->value.edmDateTimeOffset.dateTime.tm_mday, value->value.edmDateTimeOffset.dateTime.tm_hour, value->value.edmDateTimeOffset.dateTime.tm_min, value->value.edmDateTimeOffset.dateTime.tm_sec) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(tempBuffer); } } } break; } case(EDM_DECIMAL_TYPE) : { if (STRING_concat_with_STRING(destination, value->value.edmDecimal.value) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_INT16_TYPE) : { /*-32768 to +32767*/ char buffertemp2[7]; /*because 5 digits and sign and '\0'*/ uint16_t positiveValue; size_t pos = 0; uint16_t rank = (uint16_t)10000; bool foundFirstDigit = false; if (value->value.edmInt16.value < 0) { buffertemp2[pos++] = '-'; positiveValue = -value->value.edmInt16.value; } else { positiveValue = value->value.edmInt16.value; } while (rank >= 10) { if ((foundFirstDigit == true) || (positiveValue / rank) > 0) { buffertemp2[pos++] = '0' + (char)(positiveValue / rank); foundFirstDigit = true; } positiveValue %= rank; rank /= 10; } buffertemp2[pos++] = '0' + (char)(positiveValue); buffertemp2[pos++] = '\0'; if (STRING_concat(destination, buffertemp2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_INT32_TYPE) : { /*-2147483648 to +2147483647*/ char buffertemp2[12]; /*because 10 digits and sign and '\0'*/ uint32_t positiveValue; size_t pos = 0; uint32_t rank = 1000000000UL; bool foundFirstDigit = false; if (value->value.edmInt32.value < 0) { buffertemp2[pos++] = '-'; positiveValue = - value->value.edmInt32.value; } else { positiveValue = value->value.edmInt32.value; } while (rank >= 10) { if ((foundFirstDigit == true) || (positiveValue / rank) > 0) { buffertemp2[pos++] = '0' + (char)(positiveValue / rank); foundFirstDigit = true; } positiveValue %= rank; rank /= 10; } buffertemp2[pos++] = '0' + (char)(positiveValue); buffertemp2[pos++] = '\0'; if (STRING_concat(destination, buffertemp2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_INT64_TYPE): { char buffertemp2[21]; /*because 19 digits and sign and '\0'*/ uint64_t positiveValue; size_t pos = 0; uint64_t rank = 10000000000000000000ULL; bool foundFirstDigit = false; if (value->value.edmInt64.value < 0) { buffertemp2[pos++] = '-'; positiveValue = -value->value.edmInt64.value; } else { positiveValue = value->value.edmInt64.value; } while (rank >= 10) { if ((foundFirstDigit == true) || (positiveValue / rank) > 0) { buffertemp2[pos++] = '0' + (char)(positiveValue / rank); foundFirstDigit = true; } positiveValue %= rank; rank /= 10; } buffertemp2[pos++] = '0' + (char)(positiveValue); buffertemp2[pos++] = '\0'; if (STRING_concat(destination, buffertemp2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_SBYTE_TYPE) : { char tempbuffer2[5]; /* because '-' and 3 characters for 127 let's say and '\0'*/ int absValue = value->value.edmSbyte.value; size_t pos=0; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_026:[ EDM_SBYTE: sbyteValue = [ sign ] 1*3DIGIT ; numbers in the range from -128 to 127]*/ if (value->value.edmSbyte.value < 0) { tempbuffer2[pos++] = '-'; absValue = -absValue; } if (absValue >= 100 ) tempbuffer2[pos++] = '0' + (char)(absValue / 100); if (absValue >=10) tempbuffer2[pos++] = '0' + (absValue % 100) / 10; tempbuffer2[pos++] = '0' + (absValue % 10); tempbuffer2[pos++] = '\0'; if (STRING_concat(destination, tempbuffer2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case (EDM_STRING_TYPE): { size_t i; size_t nControlCharacters = 0; /*counts how many characters are to be expanded from 1 character to \uxxxx (6 characters)*/ size_t nEscapeCharacters = 0; size_t vlen = value->value.edmString.length; char* v = value->value.edmString.chars; for (i = 0; i < vlen; i++) { if ((unsigned char)v[i] >= 128) /*this be a UNICODE character begin*/ { break; } else { if (v[i] <= 0x1F) { nControlCharacters++; } else if ( (v[i] == '"') || (v[i] == '\\') || (v[i] == '/') ) { nEscapeCharacters++; } } } if (i < vlen) { result = AGENT_DATA_TYPES_INVALID_ARG; /*don't handle those who do not copy bit by bit to UTF8*/ LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*forward parse the string to scan for " and for \ that in JSON are \" respectively \\*/ size_t tempBufferSize = vlen + 5 * nControlCharacters + nEscapeCharacters + 3 + 1; char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t w = 0; tempBuffer[w++] = '"'; for (i = 0; i < vlen; i++) { if (v[i] <= 0x1F) { tempBuffer[w++] = '\\'; tempBuffer[w++] = 'u'; tempBuffer[w++] = '0'; tempBuffer[w++] = '0'; tempBuffer[w++] = hexToASCII[(v[i] & 0xF0) >> 4]; /*high nibble*/ tempBuffer[w++] = hexToASCII[v[i] & 0x0F]; /*lowNibble nibble*/ } else if (v[i] == '"') { tempBuffer[w++] = '\\'; tempBuffer[w++] = '"'; } else if (v[i] == '\\') { tempBuffer[w++] = '\\'; tempBuffer[w++] = '\\'; } else if (v[i] == '/') { tempBuffer[w++] = '\\'; tempBuffer[w++] = '/'; } else { tempBuffer[w++] = v[i]; } } #ifdef _MSC_VER #pragma warning(suppress: 6386) /* The test Create_AGENT_DATA_TYPE_from_charz_With_2_Slashes_Succeeds verifies that Code Analysis is wrong here */ #endif tempBuffer[w] = '"'; /*zero terminating it*/ tempBuffer[vlen + 5 * nControlCharacters + nEscapeCharacters + 3 - 1] = '\0'; if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(tempBuffer); } } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_01_003: [EDM_STRING_no_quotes: the string is copied as given when the AGENT_DATA_TYPE was created.] */ case (EDM_STRING_NO_QUOTES_TYPE) : { /* this is a special case where we just want to copy/paste the contents, no encoding, no quotes */ /* Codes_SRS_AGENT_TYPE_SYSTEM_01_002: [When serialized, this type is not enclosed with quotes.] */ if (STRING_concat(destination, value->value.edmStringNoQuotes.chars) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } #ifndef NO_FLOATS case(EDM_SINGLE_TYPE): { /*C89 standard says: When a float is promoted to double or long double, or a double is promoted to long double, its value is unchanged*/ /*I read that as : when a float is NaN or Inf, it will stay NaN or INF in double representation*/ /*The sprintf function returns the number of characters written in the array, not counting the terminating null character.*/ if(ISNAN(value->value.edmSingle.value)) { if (STRING_concat(destination, NaN_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } else if (ISNEGATIVEINFINITY(value->value.edmSingle.value)) { if (STRING_concat(destination, MINUSINF_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } else if (ISPOSITIVEINFINITY(value->value.edmSingle.value)) { if (STRING_concat(destination, PLUSINF_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } else { size_t tempBufferSize = MAX_FLOATING_POINT_STRING_LENGTH; char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "%.*f", FLT_DIG, (double)(value->value.edmSingle.value)) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(tempBuffer); } } break; } case(EDM_DOUBLE_TYPE): { /*The sprintf function returns the number of characters written in the array, not counting the terminating null character.*/ /*OData-ABNF says these can be used: nanInfinity = 'NaN' / '-INF' / 'INF'*/ /*C90 doesn't declare a NaN or Inf in the standard, however, values might be NaN or Inf...*/ /*C99 ... does*/ /*C11 is same as C99*/ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_022:[ EDM_DOUBLE: doubleValue = decimalValue [ "e" [SIGN] 1*DIGIT ] / nanInfinity ; IEEE 754 binary64 floating-point number (15-17 decimal digits). The representation shall use DBL_DIG C #define*/ if(ISNAN(value->value.edmDouble.value)) { if (STRING_concat(destination, NaN_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_022:[ EDM_DOUBLE: doubleValue = decimalValue [ "e" [SIGN] 1*DIGIT ] / nanInfinity ; IEEE 754 binary64 floating-point number (15-17 decimal digits). The representation shall use DBL_DIG C #define*/ else if (ISNEGATIVEINFINITY(value->value.edmDouble.value)) { if (STRING_concat(destination, MINUSINF_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_022:[ EDM_DOUBLE: doubleValue = decimalValue [ "e" [SIGN] 1*DIGIT ] / nanInfinity ; IEEE 754 binary64 floating-point number (15-17 decimal digits). The representation shall use DBL_DIG C #define*/ else if (ISPOSITIVEINFINITY(value->value.edmDouble.value)) { if (STRING_concat(destination, PLUSINF_STRING) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_022:[ EDM_DOUBLE: doubleValue = decimalValue [ "e" [SIGN] 1*DIGIT ] / nanInfinity ; IEEE 754 binary64 floating-point number (15-17 decimal digits). The representation shall use DBL_DIG C #define*/ else { size_t tempBufferSize = DECIMAL_DIG * 2; char* tempBuffer = (char*)malloc(tempBufferSize); if (tempBuffer == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (sprintf_s(tempBuffer, tempBufferSize, "%.*f", DBL_DIG, value->value.edmDouble.value) < 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (STRING_concat(destination, tempBuffer) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(tempBuffer); } } break; } #endif case(EDM_COMPLEX_TYPE_TYPE) : { /*to produce an EDM_COMPLEX_TYPE is a recursive process*/ /*uses JSON encoder*/ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_062:[ If the AGENT_DATA_TYPE represents a "complex type", then the JSON marshaller shall produce the following JSON value:[...]*/ MULTITREE_HANDLE treeHandle; result = AGENT_DATA_TYPES_OK; /*SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ treeHandle = MultiTree_Create(NoCloneFunction, NoFreeFunction); if (treeHandle == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t i; for (i = 0; i < value->value.edmComplexType.nMembers; i++) { if (MultiTree_AddLeaf(treeHandle, value->value.edmComplexType.fields[i].fieldName, value->value.edmComplexType.fields[i].value) != MULTITREE_OK) { /*SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*all is fine*/ } } if (result == AGENT_DATA_TYPES_OK) { /*SRS_AGENT_TYPE_SYSTEM_99_016:[ When the value cannot be converted to a string AgentDataTypes_ToString shall return AGENT_DATA_TYPES_ERROR.]*/ if (JSONEncoder_EncodeTree(treeHandle, destination, (JSON_ENCODER_TOSTRING_FUNC)AgentDataTypes_ToString) != JSON_ENCODER_OK) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /*all is fine*/ } } MultiTree_Destroy(treeHandle); } break; } case EDM_GUID_TYPE: { char tempBuffer2[1 + 8 + 1 + 4 + 1 + 4 + 1 + 4 + 1 + 12 + 1+ 1]; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_093:[ EDM_GUID: 8HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 4HEXDIG "-" 12HEXDIG]*/ tempBuffer2[0] = '\"'; tempBuffer2[1] = hexDigitToChar(value->value.edmGuid.GUID[0] / 16); tempBuffer2[2] = hexDigitToChar(value->value.edmGuid.GUID[0] % 16); tempBuffer2[3] = hexDigitToChar(value->value.edmGuid.GUID[1] / 16); tempBuffer2[4] = hexDigitToChar(value->value.edmGuid.GUID[1] % 16); tempBuffer2[5] = hexDigitToChar(value->value.edmGuid.GUID[2] / 16); tempBuffer2[6] = hexDigitToChar(value->value.edmGuid.GUID[2] % 16); tempBuffer2[7] = hexDigitToChar(value->value.edmGuid.GUID[3] / 16); tempBuffer2[8] = hexDigitToChar(value->value.edmGuid.GUID[3] % 16); tempBuffer2[9] = '-'; tempBuffer2[10] = hexDigitToChar(value->value.edmGuid.GUID[4] / 16); tempBuffer2[11] = hexDigitToChar(value->value.edmGuid.GUID[4] % 16); tempBuffer2[12] = hexDigitToChar(value->value.edmGuid.GUID[5] / 16); tempBuffer2[13] = hexDigitToChar(value->value.edmGuid.GUID[5] % 16); tempBuffer2[14] = '-'; tempBuffer2[15] = hexDigitToChar(value->value.edmGuid.GUID[6] / 16); tempBuffer2[16] = hexDigitToChar(value->value.edmGuid.GUID[6] % 16); tempBuffer2[17] = hexDigitToChar(value->value.edmGuid.GUID[7] / 16); tempBuffer2[18] = hexDigitToChar(value->value.edmGuid.GUID[7] % 16); tempBuffer2[19] = '-'; tempBuffer2[20] = hexDigitToChar(value->value.edmGuid.GUID[8] / 16); tempBuffer2[21] = hexDigitToChar(value->value.edmGuid.GUID[8] % 16); tempBuffer2[22] = hexDigitToChar(value->value.edmGuid.GUID[9] / 16); tempBuffer2[23] = hexDigitToChar(value->value.edmGuid.GUID[9] % 16); tempBuffer2[24] = '-'; tempBuffer2[25] = hexDigitToChar(value->value.edmGuid.GUID[10] / 16); tempBuffer2[26] = hexDigitToChar(value->value.edmGuid.GUID[10] % 16); tempBuffer2[27] = hexDigitToChar(value->value.edmGuid.GUID[11] / 16); tempBuffer2[28] = hexDigitToChar(value->value.edmGuid.GUID[11] % 16); tempBuffer2[29] = hexDigitToChar(value->value.edmGuid.GUID[12] / 16); tempBuffer2[30] = hexDigitToChar(value->value.edmGuid.GUID[12] % 16); tempBuffer2[31] = hexDigitToChar(value->value.edmGuid.GUID[13] / 16); tempBuffer2[32] = hexDigitToChar(value->value.edmGuid.GUID[13] % 16); tempBuffer2[33] = hexDigitToChar(value->value.edmGuid.GUID[14] / 16); tempBuffer2[34] = hexDigitToChar(value->value.edmGuid.GUID[14] % 16); tempBuffer2[35] = hexDigitToChar(value->value.edmGuid.GUID[15] / 16); tempBuffer2[36] = hexDigitToChar(value->value.edmGuid.GUID[15] % 16); tempBuffer2[37] = '\"'; tempBuffer2[38] = '\0'; if (STRING_concat(destination, tempBuffer2) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } break; } case EDM_BINARY_TYPE: { size_t currentPosition = 0; char* temp; /*binary types */ /*Codes_SRS_AGENT_TYPE_SYSTEM_99_099:[EDM_BINARY:= *(4base64char)[base64b16 / base64b8]]*/ /*the following will happen*/ /*1. the "data" of the binary shall be "eaten" 3 characters at a time and produce 4 base64 encoded characters for as long as there are more than 3 characters still to process*/ /*2. the remaining characters (1 or 2) shall be encoded.*/ /*there's a level of assumption that 'a' corresponds to 0b000000 and that '_' corresponds to 0b111111*/ /*the encoding will use the optional [=] or [==] at the end of the encoded string, so that other less standard aware libraries can do their work*/ /*these are the bits of the 3 normal bytes to be encoded*/ size_t neededSize = 2; /*2 because starting and ending quotes */ neededSize += (value->value.edmBinary.size == 0) ? (0) : ((((value->value.edmBinary.size-1) / 3) + 1) * 4); neededSize += 1; /*+1 because \0 at the end of the string*/ if ((temp = (char*)malloc(neededSize))==NULL) { result = AGENT_DATA_TYPES_ERROR; } else { /*b0 b1(+1) b2(+2) 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 |----c1---| |----c2---| |----c3---| |----c4---| */ size_t destinationPointer = 0; temp[destinationPointer++] = '"'; while (value->value.edmBinary.size - currentPosition >= 3) { char c1 = base64char[value->value.edmBinary.data[currentPosition] >> 2]; char c2 = base64char[ ((value->value.edmBinary.data[currentPosition] & 3) << 4) | (value->value.edmBinary.data[currentPosition + 1] >> 4) ]; char c3 = base64char[ ((value->value.edmBinary.data[currentPosition + 1] & 0x0F) << 2) | ((value->value.edmBinary.data[currentPosition + 2] >> 6) & 3) ]; char c4 = base64char[ value->value.edmBinary.data[currentPosition + 2] & 0x3F ]; currentPosition += 3; temp[destinationPointer++] = c1; temp[destinationPointer++] = c2; temp[destinationPointer++] = c3; temp[destinationPointer++] = c4; } if (value->value.edmBinary.size - currentPosition == 2) { char c1 = base64char[value->value.edmBinary.data[currentPosition] >> 2]; char c2 = base64char[ ((value->value.edmBinary.data[currentPosition] & 0x03) << 4) | (value->value.edmBinary.data[currentPosition + 1] >> 4) ]; char c3 = base64b16[value->value.edmBinary.data[currentPosition + 1] & 0x0F]; temp[destinationPointer++] = c1; temp[destinationPointer++] = c2; temp[destinationPointer++] = c3; temp[destinationPointer++] = '='; } else if (value->value.edmBinary.size - currentPosition == 1) { char c1 = base64char[value->value.edmBinary.data[currentPosition] >> 2]; char c2 = base64b8[value->value.edmBinary.data[currentPosition] & 0x03]; temp[destinationPointer++] = c1; temp[destinationPointer++] = c2; temp[destinationPointer++] = '='; temp[destinationPointer++] = '='; } /*closing quote*/ temp[destinationPointer++] = '"'; /*null terminating the string*/ temp[destinationPointer] = '\0'; if (STRING_concat(destination, temp) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } free(temp); } break; } } } return result; } /*return 0 if all names are different than NULL*/ static int isOneNameNULL(size_t nMemberNames, const char* const * memberNames) { size_t i; int result = 0; for (i = 0; i < nMemberNames; i++) { if (memberNames[i] == NULL) { result = 1; break; } } return result; } /*return 0 if all names are different than NULL*/ static int areThereTwoSameNames(size_t nMemberNames, const char* const * memberNames) { size_t i, j; int result = 0; for (i = 0; i < nMemberNames-1; i++) { for (j = i + 1; j < nMemberNames; j++) { if (strcmp(memberNames[i], memberNames[j]) == 0) { result = 1; goto out; } } } out: return result; } static void DestroyHalfBakedComplexType(AGENT_DATA_TYPE* agentData) { size_t i; if (agentData != NULL) { if (agentData->type == EDM_COMPLEX_TYPE_TYPE) { if (agentData->value.edmComplexType.fields != NULL) { for (i = 0; i < agentData->value.edmComplexType.nMembers; i++) { if (agentData->value.edmComplexType.fields[i].fieldName != NULL) { free((void*)(agentData->value.edmComplexType.fields[i].fieldName)); agentData->value.edmComplexType.fields[i].fieldName = NULL; } if (agentData->value.edmComplexType.fields[i].value != NULL) { Destroy_AGENT_DATA_TYPE(agentData->value.edmComplexType.fields[i].value); free(agentData->value.edmComplexType.fields[i].value); agentData->value.edmComplexType.fields[i].value = NULL; } } free(agentData->value.edmComplexType.fields); agentData->value.edmComplexType.fields = NULL; } agentData->type = EDM_NO_TYPE; } } } /* Creates an object of AGENT_DATA_TYPE_TYPE EDM_NULL_TYPE*/ AGENT_DATA_TYPES_RESULT Create_NULL_AGENT_DATA_TYPE(AGENT_DATA_TYPE* agentData) { AGENT_DATA_TYPES_RESULT result; if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_NULL_TYPE; result = AGENT_DATA_TYPES_OK; } return result; } /*creates a copy of the AGENT_DATA_TYPE*/ AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_AGENT_DATA_TYPE(AGENT_DATA_TYPE* dest, const AGENT_DATA_TYPE* src) { AGENT_DATA_TYPES_RESULT result; size_t i; if ((dest == NULL) || (src == NULL)) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { switch (src->type) { default: { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_NO_TYPE) : case(EDM_NULL_TYPE) : { dest->type = src->type; result = AGENT_DATA_TYPES_OK; break; } case(EDM_BOOLEAN_TYPE) : { dest->type = src->type; dest->value.edmBoolean= src->value.edmBoolean; result = AGENT_DATA_TYPES_OK; break; } case(EDM_BYTE_TYPE) : { dest->type = src->type; dest->value.edmByte= src->value.edmByte; result = AGENT_DATA_TYPES_OK; break; } case(EDM_DATE_TYPE) : { dest->type = src->type; dest->value.edmDate = src->value.edmDate; result = AGENT_DATA_TYPES_OK; break; } case(EDM_DATE_TIME_OFFSET_TYPE) : { dest->type = src->type; dest->value.edmDateTimeOffset = src->value.edmDateTimeOffset; result = AGENT_DATA_TYPES_OK; break; } case(EDM_DECIMAL_TYPE) : { if ((dest->value.edmDecimal.value = STRING_clone(src->value.edmDecimal.value)) == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { dest->type = src->type; result = AGENT_DATA_TYPES_OK; /*all is fine*/ } break; } case(EDM_DOUBLE_TYPE) : { dest->type = src->type; dest->value.edmDouble = src->value.edmDouble; result = AGENT_DATA_TYPES_OK; break; } case(EDM_DURATION_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GUID_TYPE) : { dest->type = src->type; dest->value.edmGuid = src->value.edmGuid; result = AGENT_DATA_TYPES_OK; break; } case EDM_BINARY_TYPE: { if (src->value.edmBinary.size == 0) { dest->value.edmBinary.size = 0; dest->value.edmBinary.data = NULL; dest->type = EDM_BINARY_TYPE; result = AGENT_DATA_TYPES_OK; } else { if ((dest->value.edmBinary.data = (unsigned char*)malloc(src->value.edmBinary.size)) == NULL) { result = AGENT_DATA_TYPES_ERROR; } else { dest->value.edmBinary.size = src->value.edmBinary.size; memcpy(dest->value.edmBinary.data, src->value.edmBinary.data, src->value.edmBinary.size); dest->type = EDM_BINARY_TYPE; result = AGENT_DATA_TYPES_OK; } } break; } case(EDM_INT16_TYPE) : { dest->type = src->type; dest->value.edmInt16 = src->value.edmInt16; result = AGENT_DATA_TYPES_OK; break; } case(EDM_INT32_TYPE) : { dest->type = src->type; dest->value.edmInt32 = src->value.edmInt32; result = AGENT_DATA_TYPES_OK; break; } case(EDM_INT64_TYPE) : { dest->type = src->type; dest->value.edmInt64 = src->value.edmInt64; result = AGENT_DATA_TYPES_OK; break; } case(EDM_SBYTE_TYPE) : { dest->type = src->type; dest->value.edmSbyte = src->value.edmSbyte; result = AGENT_DATA_TYPES_OK; break; } case(EDM_SINGLE_TYPE) : { dest->type = src->type; dest->value.edmSingle = src->value.edmSingle; result = AGENT_DATA_TYPES_OK; break; } case(EDM_STREAM) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } /*not supported, because what is stream?*/ case(EDM_STRING_TYPE) : { dest->type = src->type; dest->value.edmString.length = src->value.edmString.length; if (mallocAndStrcpy_s((char**)&(dest->value.edmString.chars), (char*)src->value.edmString.chars) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; /*all is fine*/ } break; } case(EDM_STRING_NO_QUOTES_TYPE) : { dest->type = src->type; dest->value.edmStringNoQuotes.length = src->value.edmStringNoQuotes.length; if (mallocAndStrcpy_s((char**)&(dest->value.edmStringNoQuotes.chars), (char*)src->value.edmStringNoQuotes.chars) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; /*all is fine*/ } break; } case(EDM_TIME_OF_DAY_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } /*not supported because what is "abstract base type"*/ case(EDM_GEOGRAPHY_POINT_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_LINE_STRING_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_POLYGON_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_MULTI_POINT_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_MULTI_LINE_STRING_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_MULTI_POLYGON_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOGRAPHY_COLLECTION_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } /*not supported because what is "abstract base type"*/ case(EDM_GEOMETRY_POINT_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_LINE_STRING_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_POLYGON_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_MULTI_POINT_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_MULTI_LINE_STRING_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_MULTI_POLYGON_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_GEOMETRY_COLLECTION_TYPE) : { result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } case(EDM_COMPLEX_TYPE_TYPE) : { result = AGENT_DATA_TYPES_OK; /*copying a COMPLEX_TYPE means to copy all its member names and all its fields*/ dest->type = src->type; if (src->value.edmComplexType.nMembers == 0) { /*error*/ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { dest->value.edmComplexType.nMembers = src->value.edmComplexType.nMembers; dest->value.edmComplexType.fields = (COMPLEX_TYPE_FIELD_TYPE*)malloc(dest->value.edmComplexType.nMembers * sizeof(COMPLEX_TYPE_FIELD_TYPE)); if (dest->value.edmComplexType.fields == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { for (i = 0; i < dest->value.edmComplexType.nMembers; i++) { dest->value.edmComplexType.fields[i].fieldName = NULL; dest->value.edmComplexType.fields[i].value = NULL; } for (i = 0; i < dest->value.edmComplexType.nMembers; i++) { /*copy the name of this field*/ if (mallocAndStrcpy_s((char**)(&(dest->value.edmComplexType.fields[i].fieldName)), src->value.edmComplexType.fields[i].fieldName) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*field name copied success*/ /*field value copy follows*/ dest->value.edmComplexType.fields[i].value = (AGENT_DATA_TYPE*)malloc(sizeof(AGENT_DATA_TYPE)); if (dest->value.edmComplexType.fields[i].value == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { if (Create_AGENT_DATA_TYPE_from_AGENT_DATA_TYPE(dest->value.edmComplexType.fields[i].value, src->value.edmComplexType.fields[i].value) != AGENT_DATA_TYPES_OK) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*all is fine*/ } } } } if (result != AGENT_DATA_TYPES_OK) { /*unbuild*/ DestroyHalfBakedComplexType(dest); } } } break; } /*ANY CHANGE (?!) here must be reflected in the tool providing the binary file (XML2BINARY) */ } if (result != AGENT_DATA_TYPES_OK) { dest->type = EDM_NO_TYPE; } } return result; } AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_MemberPointers(AGENT_DATA_TYPE* agentData, const char* typeName, size_t nMembers, const char* const * memberNames, const AGENT_DATA_TYPE** memberPointerValues) { AGENT_DATA_TYPES_RESULT result; /* Codes_SRS_AGENT_TYPE_SYSTEM_99_109:[ AGENT_DATA_TYPES_INVALID_ARG shall be returned if memberPointerValues parameter is NULL.] */ if (memberPointerValues == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result: AGENT_DATA_TYPES_INVALID_ARG)\r\n"); } else { AGENT_DATA_TYPE* values = (AGENT_DATA_TYPE*)malloc(nMembers* sizeof(AGENT_DATA_TYPE)); if (values == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t i; for (i = 0; i < nMembers; i++) { if (Create_AGENT_DATA_TYPE_from_AGENT_DATA_TYPE(values + i, memberPointerValues[i]) != AGENT_DATA_TYPES_OK) { size_t j; for (j = 0; j < i; j++) { Destroy_AGENT_DATA_TYPE(values + j); } break; } } if (i != nMembers) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /* SRS_AGENT_TYPE_SYSTEM_99_111:[ AGENT_DATA_TYPES_OK shall be returned upon success.] */ result = Create_AGENT_DATA_TYPE_from_Members(agentData, typeName, nMembers, memberNames, values); if (result != AGENT_DATA_TYPES_OK) { LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } for (i = 0; i < nMembers; i++) { Destroy_AGENT_DATA_TYPE(&values[i]); } } free(values); } } return result; } AGENT_DATA_TYPES_RESULT Create_AGENT_DATA_TYPE_from_Members(AGENT_DATA_TYPE* agentData, const char* typeName, size_t nMembers, const char* const * memberNames, const AGENT_DATA_TYPE* memberValues) { AGENT_DATA_TYPES_RESULT result; size_t i; /*Codes_SRS_AGENT_TYPE_SYSTEM_99_013:[ All the functions shall check their parameters for validity. When an invalid parameter is detected, the value AGENT_DATA_TYPES_INVALID_ARG shall be returned ]*/ if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result: AGENT_DATA_TYPES_INVALID_ARG)\r\n"); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_055:[ If typeName is NULL, the function shall return AGENT_DATA_TYPES_INVALID_ARG .]*/ else if (typeName==NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result: AGENT_DATA_TYPES_INVALID_ARG)\r\n"); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_056:[If nMembers is 0, the function shall return AGENT_DATA_TYPES_INVALID_ARG .]*/ else if (nMembers == 0) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_057:[ If memberNames is NULL, the function shall return AGENT_DATA_TYPES_INVALID_ARG .]*/ else if (memberNames == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_058:[ If any of the memberNames[i] is NULL, the function shall return AGENT_DATA_TYPES_INVALID_ARG .]*/ else if (isOneNameNULL(nMembers, memberNames)!=0) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_059:[ If memberValues is NULL, the function shall return AGENT_DATA_TYPES_INVALID_ARG .]*/ else if (memberValues == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_063:[ If there are two memberNames with the same name, then the function shall return AGENT_DATA_TYPES_INVALID_ARG.]*/ else if (areThereTwoSameNames(nMembers, memberNames) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->value.edmComplexType.nMembers = nMembers; agentData->value.edmComplexType.fields = (COMPLEX_TYPE_FIELD_TYPE*)malloc(nMembers *sizeof(COMPLEX_TYPE_FIELD_TYPE)); if (agentData->value.edmComplexType.fields == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; /*not liking this, solution might be to use a temp variable*/ /*initialize the fields*/ for (i = 0; i < nMembers; i++) { agentData->value.edmComplexType.fields[i].fieldName = NULL; agentData->value.edmComplexType.fields[i].value = NULL; } for (i = 0; i < nMembers; i++) { /*copy the name*/ if (mallocAndStrcpy_s((char**)(&(agentData->value.edmComplexType.fields[i].fieldName)), memberNames[i]) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*field name was transferred successfully*/ /*copy the rest*/ agentData->value.edmComplexType.fields[i].value = (AGENT_DATA_TYPE*)malloc(sizeof(AGENT_DATA_TYPE)); if (agentData->value.edmComplexType.fields[i].value == NULL) { /*deallocate the name*/ free((void*)(agentData->value.edmComplexType.fields[i].fieldName)); agentData->value.edmComplexType.fields[i].fieldName = NULL; result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*copy the values*/ if (Create_AGENT_DATA_TYPE_from_AGENT_DATA_TYPE(agentData->value.edmComplexType.fields[i].value, &(memberValues[i])) != AGENT_DATA_TYPES_OK) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; } else { /*all is fine*/ } } } } } if (result != AGENT_DATA_TYPES_OK) { /*dealloc, something went bad*/ DestroyHalfBakedComplexType(agentData); } else { agentData->type = EDM_COMPLEX_TYPE_TYPE; } } return result; } #define isLeapYear(y) ((((y) % 400) == 0) || (((y)%4==0)&&(!((y)%100==0)))) const int daysInAllPreviousMonths[12] = { 0, 31, 31 + 28, 31 + 28 + 31, 31 + 28 + 31 + 30, 31 + 28 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 }; /*this function assumes a correctly filled in tm_year, tm_mon and tm_mday and will fill in tm_yday and tm_wday*/ static void fill_tm_yday_and_tm_wday(struct tm* source) { /*to fill in tm_yday the function shall add the number of days in every month, not including the current one*/ /*and then it will add the number of days in the current month*/ /*1st of Jan is day "0" in a year*/ int year = source->tm_year + 1900 + 10000; int nLeapYearsSinceYearMinus9999 = ((year - 1) / 4) - ((year - 1) / 100) + ((year - 1) / 400); source->tm_yday = (daysInAllPreviousMonths[source->tm_mon]) + (source->tm_mday - 1) + ((source->tm_mon > 1 /*1 is Feb*/) && isLeapYear(year)); source->tm_wday = ((365 * year + nLeapYearsSinceYearMinus9999) + source->tm_yday) % 7; /*day "0" is 1st jan -9999 (this is how much odata can span*/ /*the function shall count days */ } /*the following function does the same as sscanf(pos2, ":%02d", &sec)*/ /*this function only exists because of optimizing valgrind time, otherwise sscanf would be just as good*/ static int sscanf2d(const char *pos2, int* sec) { int result; size_t position = 1; if ( (pos2[0] == ':') && (scanAndReadNDigitsInt(pos2, strlen(pos2), &position, sec, 2) == 0) ) { result = 1; } else { result = 0; } return result; } /*the following function does the same as (sscanf(pos2, ".%llu", &fractionalSeconds) != 1)*/ static int sscanfllu(const char*pos2, unsigned long long* fractionalSeconds) { int result; if (pos2[0] != '.') { /*doesn't start with '.' error out*/ result = 0; } else { size_t index=1; *fractionalSeconds = 0; bool error = true; while (IS_DIGIT(pos2[index])) { if ((ULLONG_MAX - (pos2[index]-'0'))/10 < *fractionalSeconds) { /*overflow... */ error = true; break; } else { *fractionalSeconds = *fractionalSeconds * 10 + (pos2[index] - '0'); error = false; } index++; } if (error) { result = 0; /*return 0 fields converted*/ } else { result = 1; /*1 field converted*/ } } return result; } /*the below function replaces sscanf(pos2, "%03d:%02d\"", &hourOffset, &minOffset)*/ /*return 2 if success*/ static int sscanf3d2d(const char* pos2, int* hourOffset, int* minOffset) { size_t position = 0; int result; if ( (scanAndReadNDigitsInt(pos2, strlen(pos2), &position, hourOffset, 2) == 0) && (pos2 += position, pos2[0] == ':') && (scanAndReadNDigitsInt(pos2, strlen(pos2), &position, minOffset, 2) == 0) ) { result = 2; } else { result = 0; } return result; } AGENT_DATA_TYPES_RESULT CreateAgentDataType_From_String(const char* source, AGENT_DATA_TYPE_TYPE type, AGENT_DATA_TYPE* agentData) { AGENT_DATA_TYPES_RESULT result; /* Codes_SRS_AGENT_TYPE_SYSTEM_99_073:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is NULL.] */ if ((source == NULL) || /* Codes_SRS_AGENT_TYPE_SYSTEM_99_074:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if agentData is NULL.] */ (agentData == NULL)) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_071:[ CreateAgentDataType_From_String shall create an AGENT_DATA_TYPE from a char* representation of the type indicated by type parameter.] */ /* Codes_SRS_AGENT_TYPE_SYSTEM_99_072:[ The implementation for the transformation of the char* source into AGENT_DATA_TYPE shall be type specific.] */ switch (type) { default: /* Codes_SRS_AGENT_TYPE_SYSTEM_99_075:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_NOT_IMPLEMENTED if type is not a supported type.] */ result = AGENT_DATA_TYPES_NOT_IMPLEMENTED; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); break; /* Codes_SRS_AGENT_TYPE_SYSTEM_99_086:[ EDM_STRING] */ case EDM_BOOLEAN_TYPE: { if (strcmp(source, "true") == 0) { agentData->type = EDM_BOOLEAN_TYPE; agentData->value.edmBoolean.value = EDM_TRUE; result = AGENT_DATA_TYPES_OK; } else if (strcmp(source, "false") == 0) { agentData->type = EDM_BOOLEAN_TYPE; agentData->value.edmBoolean.value = EDM_FALSE; result = AGENT_DATA_TYPES_OK; } else { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } break; } case EDM_NULL_TYPE: { if (strcmp(source, "null") == 0) { agentData->type = EDM_NULL_TYPE; result = AGENT_DATA_TYPES_OK; } else { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_084:[ EDM_SBYTE] */ case EDM_SBYTE_TYPE: { int sByteValue; if ((sscanf(source, "%d", &sByteValue) != 1) || (sByteValue < -128) || (sByteValue > 127)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_SBYTE_TYPE; agentData->value.edmSbyte.value = (int8_t)sByteValue; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_077:[ EDM_BYTE] */ case EDM_BYTE_TYPE: { int byteValue; if ((sscanf(source, "%d", &byteValue) != 1) || (byteValue < 0) || (byteValue > 255)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_BYTE_TYPE; agentData->value.edmByte.value = (uint8_t)byteValue; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_081:[ EDM_INT16] */ case EDM_INT16_TYPE: { int int16Value; if ((sscanf(source, "%d", &int16Value) != 1) || (int16Value < -32768) || (int16Value > 32767)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_INT16_TYPE; agentData->value.edmInt16.value = (int16_t)int16Value; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_082:[ EDM_INT32] */ case EDM_INT32_TYPE: { int32_t int32Value; unsigned char isNegative; uint32_t uint32Value; const char* pos; size_t strLength; if (source[0] == '-') { isNegative = 1; pos = &source[1]; } else { isNegative = 0; pos = &source[0]; } strLength = strlen(source); if ((sscanf(pos, "%" SCNu32, &uint32Value) != 1) || (strLength > 11) || ((uint32Value > 2147483648UL) && isNegative) || ((uint32Value > 2147483647UL) && (!isNegative))) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (isNegative) { if (uint32Value == 2147483648UL) { int32Value = -2147483647L - 1L; } else { int32Value = -(int32_t)uint32Value; } } else { int32Value = uint32Value; } agentData->type = EDM_INT32_TYPE; agentData->value.edmInt32.value = (int32_t)int32Value; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_083:[ EDM_INT64] */ case EDM_INT64_TYPE: { long long int64Value; unsigned char isNegative; unsigned long long ullValue; const char* pos; size_t strLength; if (source[0] == '-') { isNegative = 1; pos = &source[1]; } else { isNegative = 0; pos = &source[0]; } strLength = strlen(source); if ((sscanf(pos, "%llu", &ullValue) != 1) || (strLength > 20) || ((ullValue > 9223372036854775808ULL) && isNegative) || ((ullValue > 9223372036854775807ULL) && (!isNegative))) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (isNegative) { if (ullValue == 9223372036854775808ULL) { int64Value = -9223372036854775807LL - 1LL; } else { int64Value = -(long long)ullValue; } } else { int64Value = ullValue; } agentData->type = EDM_INT64_TYPE; agentData->value.edmInt64.value = (int64_t)int64Value; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_085:[ EDM_DATE] */ case EDM_DATE_TYPE: { int year; int month; int day; size_t strLength = strlen(source); if ((strLength < 2) || (source[0] != '"') || (source[strlen(source) - 1] != '"')) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t pos = 1; int sign; scanOptionalMinusSign(source, 2, &pos, &sign); if ((scanAndReadNDigitsInt(source, strLength, &pos, &year, 4) != 0) || (source[pos++] != '-') || (scanAndReadNDigitsInt(source, strLength, &pos, &month, 2) != 0) || (source[pos++] != '-') || (scanAndReadNDigitsInt(source, strLength, &pos, &day, 2) != 0) || (Create_AGENT_DATA_TYPE_from_date(agentData, (int16_t)(sign*year), (uint8_t)month, (uint8_t)day) != AGENT_DATA_TYPES_OK)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_078:[ EDM_DATETIMEOFFSET] */ case EDM_DATE_TIME_OFFSET_TYPE: { int year; int month; int day; int hour; int min; int sec = 0; int hourOffset; int minOffset; unsigned long long fractionalSeconds = 0; size_t strLength = strlen(source); agentData->value.edmDateTimeOffset.hasFractionalSecond = 0; agentData->value.edmDateTimeOffset.hasTimeZone = 0; /* The value of tm_isdst is positive if Daylight Saving Time is in effect, zero if Daylight Saving Time is not in effect, and negative if the information is not available.*/ agentData->value.edmDateTimeOffset.dateTime.tm_isdst = -1; if ((strLength < 2) || (source[0] != '"') || (source[strlen(source) - 1] != '"')) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { size_t pos = 1; int sign; scanOptionalMinusSign(source, 2, &pos, &sign); if ((scanAndReadNDigitsInt(source, strLength, &pos, &year, 4) != 0) || (source[pos++] != '-') || (scanAndReadNDigitsInt(source, strLength, &pos, &month, 2) != 0) || (source[pos++] != '-') || (scanAndReadNDigitsInt(source, strLength, &pos, &day, 2) != 0) || (source[pos++] != 'T') || (scanAndReadNDigitsInt(source, strLength, &pos, &hour, 2) != 0) || (source[pos++] != ':') || (scanAndReadNDigitsInt(source, strLength, &pos, &min, 2) != 0)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { const char* pos2; year = year*sign; if ((pos2 = strchr(source, ':')) == NULL) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { pos2 += 3; if (*pos2 == ':') { if (sscanf2d(pos2, &sec) != 1) { pos2 = NULL; } else { pos2 += 3; } } if ((pos2 != NULL) && (*pos2 == '.')) { if (sscanfllu(pos2, &fractionalSeconds) != 1) { pos2 = NULL; } else { pos2++; agentData->value.edmDateTimeOffset.hasFractionalSecond = 1; while ((*pos2 != '\0') && (IS_DIGIT(*pos2))) { pos2++; } if (*pos2 == '\0') { pos2 = NULL; } } } if (pos2 == NULL) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { hourOffset = 0; minOffset = 0; if (sscanf(pos2, "%03d:%02d\"", &hourOffset, &minOffset) == 2) { agentData->value.edmDateTimeOffset.hasTimeZone = 1; } if ((strcmp(pos2, "Z\"") == 0) || agentData->value.edmDateTimeOffset.hasTimeZone) { if ((ValidateDate(year, month, day) != 0) || (hour < 0) || (hour > 23) || (min < 0) || (min > 59) || (sec < 0) || (sec > 59) || (fractionalSeconds > 999999999999) || (hourOffset < -23) || (hourOffset > 23) || (minOffset < 0) || (minOffset > 59)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_DATE_TIME_OFFSET_TYPE; agentData->value.edmDateTimeOffset.dateTime.tm_year= year-1900; agentData->value.edmDateTimeOffset.dateTime.tm_mon = month-1; agentData->value.edmDateTimeOffset.dateTime.tm_mday = day; agentData->value.edmDateTimeOffset.dateTime.tm_hour = hour; agentData->value.edmDateTimeOffset.dateTime.tm_min = min; agentData->value.edmDateTimeOffset.dateTime.tm_sec = sec; /*fill in tm_wday and tm_yday*/ fill_tm_yday_and_tm_wday(&agentData->value.edmDateTimeOffset.dateTime); agentData->value.edmDateTimeOffset.fractionalSecond = (uint64_t)fractionalSeconds; agentData->value.edmDateTimeOffset.timeZoneHour = (int8_t)hourOffset; agentData->value.edmDateTimeOffset.timeZoneMinute = (uint8_t)minOffset; result = AGENT_DATA_TYPES_OK; } } else { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } } } } } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_080:[ EDM_DOUBLE] */ case EDM_DOUBLE_TYPE: { if (strcmp(source, "\"NaN\"") == 0) { agentData->type = EDM_DOUBLE_TYPE; agentData->value.edmDouble.value = NAN; result = AGENT_DATA_TYPES_OK; } else if (strcmp(source, "\"INF\"") == 0) { agentData->type = EDM_DOUBLE_TYPE; agentData->value.edmDouble.value = INFINITY; result = AGENT_DATA_TYPES_OK; } else if (strcmp(source, "\"-INF\"") == 0) { agentData->type = EDM_DOUBLE_TYPE; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4056) /* Known warning for INIFNITY */ #endif agentData->value.edmDouble.value = -INFINITY; #ifdef _MSC_VER #pragma warning(pop) #endif result = AGENT_DATA_TYPES_OK; } else if (sscanf(source, "%lf", &agentData->value.edmDouble.value) != 1) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; } else { agentData->type = EDM_DOUBLE_TYPE; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_089:[EDM_SINGLE] */ case EDM_SINGLE_TYPE: { if (strcmp(source, "\"NaN\"") == 0) { agentData->type = EDM_SINGLE_TYPE; agentData->value.edmSingle.value = NAN; result = AGENT_DATA_TYPES_OK; } else if (strcmp(source, "\"INF\"") == 0) { agentData->type = EDM_SINGLE_TYPE; agentData->value.edmSingle.value = INFINITY; result = AGENT_DATA_TYPES_OK; } else if (strcmp(source, "\"-INF\"") == 0) { agentData->type = EDM_SINGLE_TYPE; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4056) /* Known warning for INIFNITY */ #endif agentData->value.edmSingle.value = -INFINITY; #ifdef _MSC_VER #pragma warning(pop) #endif result = AGENT_DATA_TYPES_OK; } else if (sscanf(source, "%f", &agentData->value.edmSingle.value) != 1) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_SINGLE_TYPE; result = AGENT_DATA_TYPES_OK; } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_079:[ EDM_DECIMAL] */ case EDM_DECIMAL_TYPE: { size_t strLength = strlen(source); if ((strLength < 2) || (source[0] != '"') || (source[strLength - 1] != '"') || (ValidateDecimal(source + 1, strLength - 2) != 0)) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_DECIMAL_TYPE; agentData->value.edmDecimal.value = STRING_construct_n(source + 1, strLength-2); if (agentData->value.edmDecimal.value == NULL) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_088:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_ERROR if any other error occurs.] */ result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { result = AGENT_DATA_TYPES_OK; } } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_99_086:[ EDM_STRING] */ case EDM_STRING_TYPE: { size_t strLength = strlen(source); if ((strLength < 2) || (source[0] != '"') || (source[strLength - 1] != '"')) { /* Codes_SRS_AGENT_TYPE_SYSTEM_99_087:[ CreateAgentDataType_From_String shall return AGENT_DATA_TYPES_INVALID_ARG if source is not a valid string for a value of type type.] */ result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { char* temp; if ((temp = (char*)malloc(strLength - 1)) == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else if (strncpy_s(temp, strLength - 1, source + 1, strLength - 2) != 0) { free(temp); result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { temp[strLength - 2] = 0; agentData->type = EDM_STRING_TYPE; agentData->value.edmString.chars = temp; agentData->value.edmString.length = strLength - 2; result = AGENT_DATA_TYPES_OK; } } break; } /* Codes_SRS_AGENT_TYPE_SYSTEM_01_004: [EDM_STRING_NO_QUOTES] */ case EDM_STRING_NO_QUOTES_TYPE: { char* temp; size_t strLength = strlen(source); if (mallocAndStrcpy_s(&temp, source) != 0) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { agentData->type = EDM_STRING_NO_QUOTES_TYPE; agentData->value.edmStringNoQuotes.chars = temp; agentData->value.edmStringNoQuotes.length = strLength; result = AGENT_DATA_TYPES_OK; } break; } /*Codes_SRS_AGENT_TYPE_SYSTEM_99_097:[ EDM_GUID]*/ case EDM_GUID_TYPE: { if (strlen(source) != GUID_STRING_LENGTH) { result = AGENT_DATA_TYPES_INVALID_ARG; } else { if (source[0] != '"') { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 1, &(agentData->value.edmGuid.GUID[0])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 3, &(agentData->value.edmGuid.GUID[1])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 5, &(agentData->value.edmGuid.GUID[2])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 7, &(agentData->value.edmGuid.GUID[3])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (source[9] != '-') { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 10, &(agentData->value.edmGuid.GUID[4])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 12, &(agentData->value.edmGuid.GUID[5])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (source[14] != '-') { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 15, &(agentData->value.edmGuid.GUID[6])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 17, &(agentData->value.edmGuid.GUID[7])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (source[19] != '-') { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 20, &(agentData->value.edmGuid.GUID[8])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 22, &(agentData->value.edmGuid.GUID[9])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (source[24] != '-') { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 25, &(agentData->value.edmGuid.GUID[10])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 27, &(agentData->value.edmGuid.GUID[11])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 29, &(agentData->value.edmGuid.GUID[12])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 31, &(agentData->value.edmGuid.GUID[13])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 33, &(agentData->value.edmGuid.GUID[14])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (scanMandatory2CapitalHexDigits(source + 35, &(agentData->value.edmGuid.GUID[15])) != 0) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (source[37] != '"') { result = AGENT_DATA_TYPES_INVALID_ARG; } else { agentData->type = EDM_GUID_TYPE; result = AGENT_DATA_TYPES_OK; } } break; } case EDM_BINARY_TYPE: { size_t sourceLength = strlen(source); if (sourceLength < 2) { result = AGENT_DATA_TYPES_INVALID_ARG; } else if (sourceLength == 2) { agentData->type = EDM_BINARY_TYPE; agentData->value.edmBinary.data = NULL; agentData->value.edmBinary.size = 0; result = AGENT_DATA_TYPES_OK; } else { size_t sourcePosition = 0; if (source[sourcePosition++] != '"') /*if it doesn't start with a quote then... */ { result = AGENT_DATA_TYPES_INVALID_ARG; } else { /*1. read groups of 4 base64 character and transfer those into groups of 3 "normal" characters. 2. read the end of the string and produce from that the ending characters*/ /*compute the amount of memory to allocate*/ agentData->value.edmBinary.size = (((sourceLength - 2) + 4) / 4) * 3; /*this is overallocation, shall be trimmed later*/ agentData->value.edmBinary.data = (unsigned char*)malloc(agentData->value.edmBinary.size); /*this is overallocation, shall be trimmed later*/ if (agentData->value.edmBinary.data == NULL) { result = AGENT_DATA_TYPES_ERROR; } else { size_t destinationPosition = 0; size_t consumed; /*read and store "solid" groups of 4 base64 chars*/ while (scan4base64char(source + sourcePosition, sourceLength - sourcePosition, agentData->value.edmBinary.data + destinationPosition, agentData->value.edmBinary.data + destinationPosition + 1, agentData->value.edmBinary.data + destinationPosition + 2) == 0) { sourcePosition += 4; destinationPosition += 3; } if (scanbase64b16(source + sourcePosition, sourceLength - sourcePosition, &consumed, agentData->value.edmBinary.data + destinationPosition, agentData->value.edmBinary.data + destinationPosition + 1) == 0) { sourcePosition += consumed; destinationPosition += 2; } else if (scanbase64b8(source + sourcePosition, sourceLength - sourcePosition, &consumed, agentData->value.edmBinary.data + destinationPosition) == 0) { sourcePosition += consumed; destinationPosition += 1; } if (source[sourcePosition++] != '"') /*if it doesn't end with " then bail out*/ { free(agentData->value.edmBinary.data); agentData->value.edmBinary.data = NULL; result = AGENT_DATA_TYPES_INVALID_ARG; } else if (sourcePosition != sourceLength) { free(agentData->value.edmBinary.data); agentData->value.edmBinary.data = NULL; result = AGENT_DATA_TYPES_INVALID_ARG; } else { /*trim the result*/ void* temp = realloc(agentData->value.edmBinary.data, destinationPosition); if (temp == NULL) /*this is extremely unlikely to happen, but whatever*/ { free(agentData->value.edmBinary.data); agentData->value.edmBinary.data = NULL; result = AGENT_DATA_TYPES_ERROR; } else { agentData->type = EDM_BINARY_TYPE; agentData->value.edmBinary.data = (unsigned char*)temp; agentData->value.edmBinary.size = destinationPosition; result = AGENT_DATA_TYPES_OK; } } } } } break; } } } return result; } // extern AGENT_DATA_TYPES_RESULT AgentDataType_GetComplexTypeField(AGENT_DATA_TYPE* agentData, size_t index, COMPLEX_TYPE_FIELD_TYPE* complexField); COMPLEX_TYPE_FIELD_TYPE* AgentDataType_GetComplexTypeField(AGENT_DATA_TYPE* agentData, size_t index) { AGENT_DATA_TYPES_RESULT result; COMPLEX_TYPE_FIELD_TYPE* complexField = NULL; if (agentData == NULL) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (agentData->type != EDM_COMPLEX_TYPE_TYPE) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { if (index >= agentData->value.edmComplexType.nMembers) { result = AGENT_DATA_TYPES_INVALID_ARG; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { complexField = (COMPLEX_TYPE_FIELD_TYPE*)malloc(sizeof(COMPLEX_TYPE_FIELD_TYPE)); if (complexField == NULL) { result = AGENT_DATA_TYPES_ERROR; LogError("(result = %s)\r\n", ENUM_TO_STRING(AGENT_DATA_TYPES_RESULT, result)); } else { *complexField = agentData->value.edmComplexType.fields[index]; result = AGENT_DATA_TYPES_OK; } } } } return complexField; }
mit
willwray/dash
src/test/bloom_tests.cpp
4
54340
// Copyright (c) 2012-2015 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 "bloom.h" #include "base58.h" #include "clientversion.h" #include "key.h" #include "merkleblock.h" #include "random.h" #include "serialize.h" #include "streams.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include "test/test_dash.h" #include <vector> #include <boost/test/unit_test.hpp> #include <boost/tuple/tuple.hpp> using namespace std; BOOST_FIXTURE_TEST_SUITE(bloom_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize) { CBloomFilter filter(3, 0.01, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")); BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!"); // One bit different in first byte BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter contains something it shouldn't!"); filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")); BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "BloomFilter doesn't contain just-inserted object (2)!"); filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")); BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "BloomFilter doesn't contain just-inserted object (3)!"); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); vector<unsigned char> vch = ParseHex("03614e9b050000000000000001"); vector<char> expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end()); BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!"); filter.clear(); BOOST_CHECK_MESSAGE( !filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter should be empty!"); } BOOST_AUTO_TEST_CASE(bloom_create_insert_serialize_with_tweak) { // Same test as bloom_create_insert_serialize, but we add a nTweak of 100 CBloomFilter filter(3, 0.01, 2147483649UL, BLOOM_UPDATE_ALL); filter.insert(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")); BOOST_CHECK_MESSAGE( filter.contains(ParseHex("99108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter doesn't contain just-inserted object!"); // One bit different in first byte BOOST_CHECK_MESSAGE(!filter.contains(ParseHex("19108ad8ed9bb6274d3980bab5a85c048f0950c8")), "BloomFilter contains something it shouldn't!"); filter.insert(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")); BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b5a2c786d9ef4658287ced5914b37a1b4aa32eee")), "BloomFilter doesn't contain just-inserted object (2)!"); filter.insert(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")); BOOST_CHECK_MESSAGE(filter.contains(ParseHex("b9300670b4c5366e95b2699e8b18bc75e5f729c5")), "BloomFilter doesn't contain just-inserted object (3)!"); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); vector<unsigned char> vch = ParseHex("03ce4299050000000100008001"); vector<char> expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end()); } BOOST_AUTO_TEST_CASE(bloom_create_insert_key) { string strSecret = string("7sQb6QHALg4XyHsJHsSNXnEHGhZfzTTUPJXJqaqK7CavQkiL9Ms"); CBitcoinSecret vchSecret; BOOST_CHECK(vchSecret.SetString(strSecret)); CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); vector<unsigned char> vchPubKey(pubkey.begin(), pubkey.end()); CBloomFilter filter(2, 0.001, 0, BLOOM_UPDATE_ALL); filter.insert(vchPubKey); uint160 hash = pubkey.GetID(); filter.insert(vector<unsigned char>(hash.begin(), hash.end())); CDataStream stream(SER_NETWORK, PROTOCOL_VERSION); filter.Serialize(stream, SER_NETWORK, PROTOCOL_VERSION); vector<unsigned char> vch = ParseHex("038fc16b080000000000000001"); vector<char> expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; BOOST_CHECK_EQUAL_COLLECTIONS(stream.begin(), stream.end(), expected.begin(), expected.end()); } BOOST_AUTO_TEST_CASE(bloom_match) { // Random real transaction (b4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b) CTransaction tx; CDataStream stream(ParseHex("01000000010b26e9b7735eb6aabdf358bab62f9816a21ba9ebdb719d5299e88607d722c190000000008b4830450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a0141046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339ffffffff021bff3d11000000001976a91404943fdd508053c75000106d3bc6e2754dbcff1988ac2f15de00000000001976a914a266436d2965547608b9e15d9032a7b9d64fa43188ac00000000"), SER_DISK, CLIENT_VERSION); stream >> tx; // and one which spends it (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00}; vector<unsigned char> vch(ch, ch + sizeof(ch) -1); CDataStream spendStream(vch, SER_DISK, CLIENT_VERSION); CTransaction spendingTx; spendStream >> spendingTx; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(uint256S("0xb4749f017444b051c44dfd2720e88f314ff94f3dd6d56d40ef65854fcd7fff6b")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match tx hash"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); // byte-reversed tx hash filter.insert(ParseHex("6bff7fcd4f8565ef406dd5d63d4ff94f318fe82027fd4dc451b04474019f74b4")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized tx hash"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("30450220070aca44506c5cef3a16ed519d7c3c39f8aab192c4e1c90d065f37b8a4af6141022100a8e160b856c2d43d27d8fba71e5aef6405b8643ac4cb7cb3c462aced7f14711a01")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input signature"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("046d11fee51b0e60666d5049a9101a72741df480b96ee26488a4d3466b95c9a40ac5eeef87e10a5cd336c19a84565f80fa6c547957b7700ff4dfbdefe76036c339")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match input pub key"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("04943fdd508053c75000106d3bc6e2754dbcff19")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address"); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(spendingTx), "Simple Bloom filter didn't add output"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("a266436d2965547608b9e15d9032a7b9d64fa431")); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match output address"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(COutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0)); BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match COutPoint"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); COutPoint prevOutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0); { vector<unsigned char> data(32 + sizeof(unsigned int)); memcpy(&data[0], prevOutPoint.hash.begin(), 32); memcpy(&data[32], &prevOutPoint.n, sizeof(unsigned int)); filter.insert(data); } BOOST_CHECK_MESSAGE(filter.IsRelevantAndUpdate(tx), "Simple Bloom filter didn't match manually serialized COutPoint"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(uint256S("00000009e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436")); BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random tx hash"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(ParseHex("0000006d2965547608b9e15d9032a7b9d64fa431")); BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched random address"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(COutPoint(uint256S("0x90c122d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 1)); BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about"); filter = CBloomFilter(10, 0.000001, 0, BLOOM_UPDATE_ALL); filter.insert(COutPoint(uint256S("0x000000d70786e899529d71dbeba91ba216982fb6ba58f3bdaab65e73b7e9260b"), 0)); BOOST_CHECK_MESSAGE(!filter.IsRelevantAndUpdate(tx), "Simple Bloom filter matched COutPoint for an output we didn't care about"); } BOOST_AUTO_TEST_CASE(merkle_block_1) { // Random real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af) // With 9 txes CBlock block; CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL); // Match the last transaction filter.insert(uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x74d681e0e03bafa802c8aa084379aa98d9fcd632ddc2ed9782b586ec87451f20")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 8); vector<uint256> vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); // Also match the 8th transaction filter.insert(uint256S("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053")); merkleBlock = CMerkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2); BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xdd1fd2a6fc16404faf339881a90adbde7f4f728691ac62e8f168809cdfae1053")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 7); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); } BOOST_AUTO_TEST_CASE(merkle_block_2) { // Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6) // With 4 txes CBlock block; CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL); // Match the first transaction filter.insert(uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); vector<uint256> vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); // Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5) // This should match the third transaction because it spends the output matched // It also matches the fourth transaction, which spends to the pubkey again filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af")); merkleBlock = CMerkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 4); BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]); BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256S("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f")); BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1); BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256S("0x6b0f8a73a56c04b519f1883e8aafda643ba61a30bd1439969df21bea5f4e27e2")); BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 2); BOOST_CHECK(merkleBlock.vMatchedTxn[3].second == uint256S("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23")); BOOST_CHECK(merkleBlock.vMatchedTxn[3].first == 3); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); } BOOST_AUTO_TEST_CASE(merkle_block_2_with_update_none) { // Random real block (000000005a4ded781e667e06ceefafb71410b511fe0d5adc3e5a27ecbec34ae6) // With 4 txes CBlock block; CDataStream stream(ParseHex("0100000075616236cc2126035fadb38deb65b9102cc2c41c09cdf29fc051906800000000fe7d5e12ef0ff901f6050211249919b1c0653771832b3a80c66cea42847f0ae1d4d26e49ffff001d00f0a4410401000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0804ffff001d029105ffffffff0100f2052a010000004341046d8709a041d34357697dfcb30a9d05900a6294078012bf3bb09c6f9b525f1d16d5503d7905db1ada9501446ea00728668fc5719aa80be2fdfc8a858a4dbdd4fbac00000000010000000255605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d28350000000049483045022100aa46504baa86df8a33b1192b1b9367b4d729dc41e389f2c04f3e5c7f0559aae702205e82253a54bf5c4f65b7428551554b2045167d6d206dfe6a2e198127d3f7df1501ffffffff55605dc6f5c3dc148b6da58442b0b2cd422be385eab2ebea4119ee9c268d2835010000004847304402202329484c35fa9d6bb32a55a70c0982f606ce0e3634b69006138683bcd12cbb6602200c28feb1e2555c3210f1dddb299738b4ff8bbe9667b68cb8764b5ac17b7adf0001ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac0000000001000000025f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028000000004847304402205d6058484157235b06028c30736c15613a28bdb768ee628094ca8b0030d4d6eb0220328789c9a2ec27ddaec0ad5ef58efded42e6ea17c2e1ce838f3d6913f5e95db601ffffffff5f9a06d3acdceb56be1bfeaa3e8a25e62d182fa24fefe899d1c17f1dad4c2028010000004a493046022100c45af050d3cea806cedd0ab22520c53ebe63b987b8954146cdca42487b84bdd6022100b9b027716a6b59e640da50a864d6dd8a0ef24c76ce62391fa3eabaf4d2886d2d01ffffffff0200e1f505000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac000000000100000002e2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b0000000048473044022016e7a727a061ea2254a6c358376aaa617ac537eb836c77d646ebda4c748aac8b0220192ce28bf9f2c06a6467e6531e27648d2b3e2e2bae85159c9242939840295ba501ffffffffe2274e5fea1bf29d963914bd301aa63b64daaf8a3e88f119b5046ca5738a0f6b010000004a493046022100b7a1a755588d4190118936e15cd217d133b0e4a53c3c15924010d5648d8925c9022100aaef031874db2114f2d869ac2de4ae53908fbfea5b2b1862e181626bb9005c9f01ffffffff0200e1f505000000004341044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45afac00180d8f000000004341046a0765b5865641ce08dd39690aade26dfbf5511430ca428a3089261361cef170e3929a68aee3d8d4848b0c5111b0a37b82b86ad559fd2a745b44d8e8d9dfdc0cac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE); // Match the first transaction filter.insert(uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0xe980fe9f792d014e73b95203dc1335c5f9ce19ac537a419e6df5b47aecb93b70")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); vector<uint256> vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); // Match an output from the second transaction (the pubkey for address 1DZTzaBHUDM7T3QvUKBz4qXMRpkg8jsfB5) // This should not match the third transaction though it spends the output matched // It will match the fourth transaction, which has another pay-to-pubkey output to the same address filter.insert(ParseHex("044a656f065871a353f216ca26cef8dde2f03e8c16202d2e8ad769f02032cb86a5eb5e56842e92e19141d60a01928f8dd2c875a390f67c1f6c94cfc617c0ea45af")); merkleBlock = CMerkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 3); BOOST_CHECK(pair == merkleBlock.vMatchedTxn[0]); BOOST_CHECK(merkleBlock.vMatchedTxn[1].second == uint256S("0x28204cad1d7fc1d199e8ef4fa22f182de6258a3eaafe1bbe56ebdcacd3069a5f")); BOOST_CHECK(merkleBlock.vMatchedTxn[1].first == 1); BOOST_CHECK(merkleBlock.vMatchedTxn[2].second == uint256S("0x3c1d7e82342158e4109df2e0b6348b6e84e403d8b4046d7007663ace63cddb23")); BOOST_CHECK(merkleBlock.vMatchedTxn[2].first == 3); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); } BOOST_AUTO_TEST_CASE(merkle_block_3_and_serialize) { // Random real block (000000000000dab0130bbcc991d3d7ae6b81aa6f50a798888dfe62337458dc45) // With one tx CBlock block; CDataStream stream(ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff08044c86041b020a02ffffffff0100f2052a01000000434104ecd3229b0571c3be876feaac0442a9f13c5a572742927af1dc623353ecf8c202225f64868137a18cdd85cbbb4c74fbccfd4f49639cf1bdc94a5672bb15ad5d4cac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL); // Match the only transaction filter.insert(uint256S("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x63194f18be0af63f2c6bc9dc0f777cbefed3d9415c4af83f3ee3a3d669c00cb5")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 0); vector<uint256> vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); CDataStream merkleStream(SER_NETWORK, PROTOCOL_VERSION); merkleStream << merkleBlock; vector<unsigned char> vch = ParseHex("0100000079cda856b143d9db2c1caff01d1aecc8630d30625d10e8b4b8b0000000000000b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f196367291b4d4c86041b8fa45d630100000001b50cc069d6a3e33e3ff84a5c41d9d3febe7c770fdcc96b2c3ff60abe184f19630101"); vector<char> expected(vch.size()); for (unsigned int i = 0; i < vch.size(); i++) expected[i] = (char)vch[i]; BOOST_CHECK_EQUAL_COLLECTIONS(expected.begin(), expected.end(), merkleStream.begin(), merkleStream.end()); } BOOST_AUTO_TEST_CASE(merkle_block_4) { // Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4) // With 7 txes CBlock block; CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_ALL); // Match the last transaction filter.insert(uint256S("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 1); pair<unsigned int, uint256> pair = merkleBlock.vMatchedTxn[0]; BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x0a2a92f0bda4727d0a13eaddf4dd9ac6b5c61a1429e6b2b818f19b15df0ac154")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 6); vector<uint256> vMatched; BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); // Also match the 4th transaction filter.insert(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041")); merkleBlock = CMerkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); BOOST_CHECK(merkleBlock.vMatchedTxn.size() == 2); BOOST_CHECK(merkleBlock.vMatchedTxn[0].second == uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041")); BOOST_CHECK(merkleBlock.vMatchedTxn[0].first == 3); BOOST_CHECK(merkleBlock.vMatchedTxn[1] == pair); BOOST_CHECK(merkleBlock.txn.ExtractMatches(vMatched) == block.hashMerkleRoot); BOOST_CHECK(vMatched.size() == merkleBlock.vMatchedTxn.size()); for (unsigned int i = 0; i < vMatched.size(); i++) BOOST_CHECK(vMatched[i] == merkleBlock.vMatchedTxn[i].second); } BOOST_AUTO_TEST_CASE(merkle_block_4_test_p2pubkey_only) { // Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4) // With 7 txes CBlock block; CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_P2PUBKEY_ONLY); // Match the generation pubkey filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91")); // ...and the output address of the 4th transaction filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); // We should match the generation outpoint BOOST_CHECK(filter.contains(COutPoint(uint256S("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0))); // ... but not the 4th transaction's output (its not pay-2-pubkey) BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0))); } BOOST_AUTO_TEST_CASE(merkle_block_4_test_update_none) { // Random real block (000000000000b731f2eef9e8c63173adfb07e41bd53eb0ef0a6b720d6cb6dea4) // With 7 txes CBlock block; CDataStream stream(ParseHex("0100000082bb869cf3a793432a66e826e05a6fc37469f8efb7421dc880670100000000007f16c5962e8bd963659c793ce370d95f093bc7e367117b3c30c1f8fdd0d9728776381b4d4c86041b554b85290701000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0136ffffffff0100f2052a01000000434104eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91ac000000000100000001bcad20a6a29827d1424f08989255120bf7f3e9e3cdaaa6bb31b0737fe048724300000000494830450220356e834b046cadc0f8ebb5a8a017b02de59c86305403dad52cd77b55af062ea10221009253cd6c119d4729b77c978e1e2aa19f5ea6e0e52b3f16e32fa608cd5bab753901ffffffff02008d380c010000001976a9142b4b8072ecbba129b6453c63e129e643207249ca88ac0065cd1d000000001976a9141b8dd13b994bcfc787b32aeadf58ccb3615cbd5488ac000000000100000003fdacf9b3eb077412e7a968d2e4f11b9a9dee312d666187ed77ee7d26af16cb0b000000008c493046022100ea1608e70911ca0de5af51ba57ad23b9a51db8d28f82c53563c56a05c20f5a87022100a8bdc8b4a8acc8634c6b420410150775eb7f2474f5615f7fccd65af30f310fbf01410465fdf49e29b06b9a1582287b6279014f834edc317695d125ef623c1cc3aaece245bd69fcad7508666e9c74a49dc9056d5fc14338ef38118dc4afae5fe2c585caffffffff309e1913634ecb50f3c4f83e96e70b2df071b497b8973a3e75429df397b5af83000000004948304502202bdb79c596a9ffc24e96f4386199aba386e9bc7b6071516e2b51dda942b3a1ed022100c53a857e76b724fc14d45311eac5019650d415c3abb5428f3aae16d8e69bec2301ffffffff2089e33491695080c9edc18a428f7d834db5b6d372df13ce2b1b0e0cbcb1e6c10000000049483045022100d4ce67c5896ee251c810ac1ff9ceccd328b497c8f553ab6e08431e7d40bad6b5022033119c0c2b7d792d31f1187779c7bd95aefd93d90a715586d73801d9b47471c601ffffffff0100714460030000001976a914c7b55141d097ea5df7a0ed330cf794376e53ec8d88ac0000000001000000045bf0e214aa4069a3e792ecee1e1bf0c1d397cde8dd08138f4b72a00681743447000000008b48304502200c45de8c4f3e2c1821f2fc878cba97b1e6f8807d94930713aa1c86a67b9bf1e40221008581abfef2e30f957815fc89978423746b2086375ca8ecf359c85c2a5b7c88ad01410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffffd669f7d7958d40fc59d2253d88e0f248e29b599c80bbcec344a83dda5f9aa72c000000008a473044022078124c8beeaa825f9e0b30bff96e564dd859432f2d0cb3b72d3d5d93d38d7e930220691d233b6c0f995be5acb03d70a7f7a65b6bc9bdd426260f38a1346669507a3601410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95fffffffff878af0d93f5229a68166cf051fd372bb7a537232946e0a46f53636b4dafdaa4000000008c493046022100c717d1714551663f69c3c5759bdbb3a0fcd3fab023abc0e522fe6440de35d8290221008d9cbe25bffc44af2b18e81c58eb37293fd7fe1c2e7b46fc37ee8c96c50ab1e201410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff27f2b668859cd7f2f894aa0fd2d9e60963bcd07c88973f425f999b8cbfd7a1e2000000008c493046022100e00847147cbf517bcc2f502f3ddc6d284358d102ed20d47a8aa788a62f0db780022100d17b2d6fa84dcaf1c95d88d7e7c30385aecf415588d749afd3ec81f6022cecd701410462bb73f76ca0994fcb8b4271e6fb7561f5c0f9ca0cf6485261c4a0dc894f4ab844c6cdfb97cd0b60ffb5018ffd6238f4d87270efb1d3ae37079b794a92d7ec95ffffffff0100c817a8040000001976a914b6efd80d99179f4f4ff6f4dd0a007d018c385d2188ac000000000100000001834537b2f1ce8ef9373a258e10545ce5a50b758df616cd4356e0032554ebd3c4000000008b483045022100e68f422dd7c34fdce11eeb4509ddae38201773dd62f284e8aa9d96f85099d0b002202243bd399ff96b649a0fad05fa759d6a882f0af8c90cf7632c2840c29070aec20141045e58067e815c2f464c6a2a15f987758374203895710c2d452442e28496ff38ba8f5fd901dc20e29e88477167fe4fc299bf818fd0d9e1632d467b2a3d9503b1aaffffffff0280d7e636030000001976a914f34c3e10eb387efe872acb614c89e78bfca7815d88ac404b4c00000000001976a914a84e272933aaf87e1715d7786c51dfaeb5b65a6f88ac00000000010000000143ac81c8e6f6ef307dfe17f3d906d999e23e0189fda838c5510d850927e03ae7000000008c4930460221009c87c344760a64cb8ae6685a3eec2c1ac1bed5b88c87de51acd0e124f266c16602210082d07c037359c3a257b5c63ebd90f5a5edf97b2ac1c434b08ca998839f346dd40141040ba7e521fa7946d12edbb1d1e95a15c34bd4398195e86433c92b431cd315f455fe30032ede69cad9d1e1ed6c3c4ec0dbfced53438c625462afb792dcb098544bffffffff0240420f00000000001976a9144676d1b820d63ec272f1900d59d43bc6463d96f888ac40420f00000000001976a914648d04341d00d7968b3405c034adc38d4d8fb9bd88ac00000000010000000248cc917501ea5c55f4a8d2009c0567c40cfe037c2e71af017d0a452ff705e3f1000000008b483045022100bf5fdc86dc5f08a5d5c8e43a8c9d5b1ed8c65562e280007b52b133021acd9acc02205e325d613e555f772802bf413d36ba807892ed1a690a77811d3033b3de226e0a01410429fa713b124484cb2bd7b5557b2c0b9df7b2b1fee61825eadc5ae6c37a9920d38bfccdc7dc3cb0c47d7b173dbc9db8d37db0a33ae487982c59c6f8606e9d1791ffffffff41ed70551dd7e841883ab8f0b16bf04176b7d1480e4f0af9f3d4c3595768d068000000008b4830450221008513ad65187b903aed1102d1d0c47688127658c51106753fed0151ce9c16b80902201432b9ebcb87bd04ceb2de66035fbbaf4bf8b00d1cfe41f1a1f7338f9ad79d210141049d4cf80125bf50be1709f718c07ad15d0fc612b7da1f5570dddc35f2a352f0f27c978b06820edca9ef982c35fda2d255afba340068c5035552368bc7200c1488ffffffff0100093d00000000001976a9148edb68822f1ad580b043c7b3df2e400f8699eb4888ac00000000"), SER_NETWORK, PROTOCOL_VERSION); stream >> block; CBloomFilter filter(10, 0.000001, 0, BLOOM_UPDATE_NONE); // Match the generation pubkey filter.insert(ParseHex("04eaafc2314def4ca98ac970241bcab022b9c1e1f4ea423a20f134c876f2c01ec0f0dd5b2e86e7168cefe0d81113c3807420ce13ad1357231a2252247d97a46a91")); // ...and the output address of the 4th transaction filter.insert(ParseHex("b6efd80d99179f4f4ff6f4dd0a007d018c385d21")); CMerkleBlock merkleBlock(block, filter); BOOST_CHECK(merkleBlock.header.GetHash() == block.GetHash()); // We shouldn't match any outpoints (UPDATE_NONE) BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x147caa76786596590baa4e98f5d9f48b86c7765e489f7a6ff3360fe5c674360b"), 0))); BOOST_CHECK(!filter.contains(COutPoint(uint256S("0x02981fa052f0481dbc5868f4fc2166035a10f27a03cfd2de67326471df5bc041"), 0))); } static std::vector<unsigned char> RandomData() { uint256 r = GetRandHash(); return std::vector<unsigned char>(r.begin(), r.end()); } BOOST_AUTO_TEST_CASE(rolling_bloom) { // last-100-entry, 1% false positive: CRollingBloomFilter rb1(100, 0.01); // Overfill: static const int DATASIZE=399; std::vector<unsigned char> data[DATASIZE]; for (int i = 0; i < DATASIZE; i++) { data[i] = RandomData(); rb1.insert(data[i]); } // Last 100 guaranteed to be remembered: for (int i = 299; i < DATASIZE; i++) { BOOST_CHECK(rb1.contains(data[i])); } // false positive rate is 1%, so we should get about 100 hits if // testing 10,000 random keys. We get worst-case false positive // behavior when the filter is as full as possible, which is // when we've inserted one minus an integer multiple of nElement*2. unsigned int nHits = 0; for (int i = 0; i < 10000; i++) { if (rb1.contains(RandomData())) ++nHits; } // Run test_dash with --log_level=message to see BOOST_TEST_MESSAGEs: BOOST_TEST_MESSAGE("RollingBloomFilter got " << nHits << " false positives (~100 expected)"); // Insanely unlikely to get a fp count outside this range: BOOST_CHECK(nHits > 25); BOOST_CHECK(nHits < 175); BOOST_CHECK(rb1.contains(data[DATASIZE-1])); rb1.reset(); BOOST_CHECK(!rb1.contains(data[DATASIZE-1])); // Now roll through data, make sure last 100 entries // are always remembered: for (int i = 0; i < DATASIZE; i++) { if (i >= 100) BOOST_CHECK(rb1.contains(data[i-100])); rb1.insert(data[i]); } // Insert 999 more random entries: for (int i = 0; i < 999; i++) { rb1.insert(RandomData()); } // Sanity check to make sure the filter isn't just filling up: nHits = 0; for (int i = 0; i < DATASIZE; i++) { if (rb1.contains(data[i])) ++nHits; } // Expect about 5 false positives, more than 100 means // something is definitely broken. BOOST_TEST_MESSAGE("RollingBloomFilter got " << nHits << " false positives (~5 expected)"); BOOST_CHECK(nHits < 100); // last-1000-entry, 0.01% false positive: CRollingBloomFilter rb2(1000, 0.001); for (int i = 0; i < DATASIZE; i++) { rb2.insert(data[i]); } // ... room for all of them: for (int i = 0; i < DATASIZE; i++) { BOOST_CHECK(rb2.contains(data[i])); } } BOOST_AUTO_TEST_SUITE_END()
mit
est77/appleseed-maya
src/appleseedmaya/idlejobqueue.cpp
4
3324
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2016-2019 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "idlejobqueue.h" // appleseed-maya headers. #include "appleseedmaya/logger.h" // Maya headers. #include "appleseedmaya/_beginmayaheaders.h" #include <maya/MEventMessage.h> #include <maya/MStatus.h> #include <maya/MString.h> #include "appleseedmaya/_endmayaheaders.h" // Standard headers. #include <cassert> #include <mutex> #include <queue> namespace { MCallbackId g_callbackId; std::queue<std::function<void ()>> g_jobQueue; std::mutex g_jobQueueMutex; static void idleCallback(void* clientData) { while (true) { std::function<void ()> job; { std::lock_guard<std::mutex> lock(g_jobQueueMutex); if (g_jobQueue.empty()) break; job = std::move(g_jobQueue.front()); g_jobQueue.pop(); } job(); } } } namespace IdleJobQueue { MStatus initialize() { g_callbackId = 0; RENDERER_LOG_INFO("Initialized idle job queue"); return MS::kSuccess; } MStatus uninitialize() { stop(); RENDERER_LOG_INFO("Uninitialized idle job queue"); return MS::kSuccess; } void start() { if (g_callbackId == 0) { RENDERER_LOG_DEBUG("Started idle job queue"); MStatus status; g_callbackId = MEventMessage::addEventCallback( "idle", &idleCallback, reinterpret_cast<void*>(0), &status); } } void stop() { if (g_callbackId != 0) { RENDERER_LOG_DEBUG("Stoped idle job queue"); MEventMessage::removeCallback(g_callbackId); g_callbackId = 0; // Perform any pending jobs. idleCallback(nullptr); assert(g_jobQueue.empty()); } } void pushJob(std::function<void ()> job) { assert(job); assert(g_callbackId != 0); std::lock_guard<std::mutex> lock(g_jobQueueMutex); g_jobQueue.push(std::move(job)); } } // IdleJobQueue
mit
tilemapjp/OSGeo.GDAL.Xamarin
gdal-1.11.0/apps/testepsg.cpp
4
7108
/****************************************************************************** * $Id: testepsg.cpp 18987 2010-03-01 19:44:06Z rouault $ * * Project: OpenGIS Simple Features Reference Implementation * Purpose: Test mainline for translating EPSG definitions into WKT. * Author: Frank Warmerdam, warmerdam@pobox.com * ****************************************************************************** * Copyright (c) 2000, Frank Warmerdam * * 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 "ogr_spatialref.h" #include "ogr_core.h" #include "cpl_conv.h" #include "cpl_string.h" #include "ogr_p.h" #include "cpl_multiproc.h" void Usage() { printf( "testepsg [-xml] [-t src_def trg_def x y z]* [def]*\n" ); printf( " -t: transform a coordinate from source GCS/PCS to target GCS/PCS\n" ); printf( "\n" ); printf( "def's on their own are translated to WKT & XML and printed.\n" ); printf( "def's may be of any user input format, a WKT def, an\n" ); printf( "EPSG:n definition or the name of a file containing WKT/XML.\n"); } int main( int nArgc, char ** papszArgv ) { OGRSpatialReference oSRS; int i; int bReportXML = FALSE; /* -------------------------------------------------------------------- */ /* Processing command line arguments. */ /* -------------------------------------------------------------------- */ nArgc = OGRGeneralCmdLineProcessor( nArgc, &papszArgv, 0 ); if( nArgc < 2 ) Usage(); for( i = 1; i < nArgc; i++ ) { if( EQUAL(papszArgv[i],"-xml") ) bReportXML = TRUE; else if( EQUAL(papszArgv[i],"-t") && i < nArgc - 4 ) { OGRSpatialReference oSourceSRS, oTargetSRS; OGRCoordinateTransformation *poCT; double x, y, z_orig, z; int nArgsUsed = 4; if( oSourceSRS.SetFromUserInput(papszArgv[i+1]) != OGRERR_NONE ) { CPLError( CE_Failure, CPLE_AppDefined, "SetFromUserInput(%s) failed.", papszArgv[i+1] ); continue; } if( oTargetSRS.SetFromUserInput(papszArgv[i+2]) != OGRERR_NONE ) { CPLError( CE_Failure, CPLE_AppDefined, "SetFromUserInput(%s) failed.", papszArgv[i+2] ); continue; } poCT = OGRCreateCoordinateTransformation( &oSourceSRS, &oTargetSRS ); x = atof( papszArgv[i+3] ); y = atof( papszArgv[i+4] ); if( i < nArgc - 5 && (atof(papszArgv[i+5]) > 0.0 || papszArgv[i+5][0] == '0') ) { z_orig = z = atof(papszArgv[i+5]); nArgsUsed++; } else z_orig = z = 0; if( poCT == NULL || !poCT->Transform( 1, &x, &y, &z ) ) printf( "Transformation failed.\n" ); else printf( "(%f,%f,%f) -> (%f,%f,%f)\n", atof( papszArgv[i+3] ), atof( papszArgv[i+4] ), z_orig, x, y, z ); i += nArgsUsed; } else { if( oSRS.SetFromUserInput(papszArgv[i]) != OGRERR_NONE ) CPLError( CE_Failure, CPLE_AppDefined, "Error occured translating %s.\n", papszArgv[i] ); else { char *pszWKT = NULL; if( oSRS.Validate() != OGRERR_NONE ) printf( "Validate Fails.\n" ); else printf( "Validate Succeeds.\n" ); oSRS.exportToPrettyWkt( &pszWKT, FALSE ); printf( "WKT[%s] =\n%s\n", papszArgv[i], pszWKT ); CPLFree( pszWKT ); printf( "\n" ); oSRS.exportToPrettyWkt( &pszWKT, TRUE ); printf( "Simplified WKT[%s] =\n%s\n", papszArgv[i], pszWKT ); CPLFree( pszWKT ); printf( "\n" ); OGRSpatialReference *poSRS2; poSRS2 = oSRS.Clone(); poSRS2->StripCTParms(); poSRS2->exportToWkt( &pszWKT ); printf( "Old Style WKT[%s] = %s\n", papszArgv[i], pszWKT ); CPLFree( pszWKT ); OGRSpatialReference::DestroySpatialReference( poSRS2 ); poSRS2 = oSRS.Clone(); poSRS2->morphToESRI(); poSRS2->exportToPrettyWkt( &pszWKT, FALSE ); printf( "ESRI'ified WKT[%s] = \n%s\n", papszArgv[i], pszWKT ); CPLFree( pszWKT ); OGRSpatialReference::DestroySpatialReference( poSRS2 ); oSRS.exportToProj4( &pszWKT ); printf( "PROJ.4 rendering of [%s] = %s\n", papszArgv[i], pszWKT ); CPLFree( pszWKT ); if( bReportXML ) { char *pszRawXML; if( oSRS.exportToXML(&pszRawXML) == OGRERR_NONE ) { printf( "XML[%s] =\n%s\n", papszArgv[i], pszRawXML ); CPLFree( pszRawXML ); } else { printf( "XML translation failed\n" ); } } printf( "\n" ); } } } CSLDestroy( papszArgv ); OSRCleanup(); CPLFinderClean(); CPLCleanupTLS(); return 0; }
mit
airgames/vuforia-gamekit-integration
Gamekit/Ogre-1.7/RenderSystems/GL/src/OgreGLPlugin.cpp
6
2350
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd 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 "OgreGLPlugin.h" #include "OgreRoot.h" namespace Ogre { const String sPluginName = "GL RenderSystem"; //--------------------------------------------------------------------- GLPlugin::GLPlugin() : mRenderSystem(0) { } //--------------------------------------------------------------------- const String& GLPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void GLPlugin::install() { mRenderSystem = new GLRenderSystem(); Root::getSingleton().addRenderSystem(mRenderSystem); } //--------------------------------------------------------------------- void GLPlugin::initialise() { // nothing to do } //--------------------------------------------------------------------- void GLPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void GLPlugin::uninstall() { delete mRenderSystem; mRenderSystem = 0; } }
mit
Vertexwahn/appleseed
src/appleseed/renderer/modeling/entity/entity.cpp
6
4111
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "entity.h" // appleseed.renderer headers. #include "renderer/modeling/entity/onframebeginrecorder.h" #include "renderer/modeling/entity/onrenderbeginrecorder.h" // appleseed.foundation headers. #include "foundation/utility/api/apistring.h" // OpenImageIO headers. #include "foundation/platform/_beginoiioheaders.h" #include "OpenImageIO/ustring.h" #include "foundation/platform/_endoiioheaders.h" using namespace foundation; namespace renderer { struct Entity::Impl { std::string m_name; OIIO::ustring m_oiio_name; }; Entity::Entity( const UniqueID class_uid) : impl(new Impl()) , m_class_uid(class_uid) , m_parent(nullptr) { } Entity::Entity( const UniqueID class_uid, Entity* parent) : impl(new Impl()) , m_class_uid(class_uid) , m_parent(parent) { } Entity::Entity( const UniqueID class_uid, const ParamArray& params) : impl(new Impl()) , m_class_uid(class_uid) , m_parent(nullptr) , m_params(params) { } Entity::Entity( const UniqueID class_uid, Entity* parent, const ParamArray& params) : impl(new Impl()) , m_class_uid(class_uid) , m_parent(parent) , m_params(params) { } Entity::~Entity() { delete impl; } void Entity::set_name(const char* name) { assert(name); impl->m_name = name; impl->m_oiio_name = name; } const char* Entity::get_name() const { return impl->m_name.c_str(); } const void* Entity::get_name_as_ustring() const { return &impl->m_oiio_name; } APIString Entity::get_path() const { std::string path; for (const Entity* entity = this; entity != nullptr; entity = entity->get_parent()) { path.insert(0, entity->get_name()); path.insert(0, "/"); } return APIString(path.c_str()); } void Entity::collect_asset_paths(StringArray& paths) const { } void Entity::update_asset_paths(const StringDictionary& mappings) { } bool Entity::on_render_begin( const Project& project, const BaseGroup* parent, OnRenderBeginRecorder& recorder, IAbortSwitch* abort_switch) { recorder.record(this, parent); return true; } void Entity::on_render_end( const Project& project, const BaseGroup* parent) { } bool Entity::on_frame_begin( const Project& project, const BaseGroup* parent, OnFrameBeginRecorder& recorder, IAbortSwitch* abort_switch) { recorder.record(this, parent); return true; } void Entity::on_frame_end( const Project& project, const BaseGroup* parent) { } } // namespace renderer
mit
banditlev/meangarden
packages/custom/mail-templates/node_modules/node-sass/src/libsass/src/values.cpp
262
4884
#include "sass.h" #include "values.hpp" #include <stdint.h> namespace Sass { // convert value from C++ side to C-API union Sass_Value* ast_node_to_sass_value (const Expression* val) { if (val->concrete_type() == Expression::NUMBER) { const Number* res = dynamic_cast<const Number*>(val); return sass_make_number(res->value(), res->unit().c_str()); } else if (val->concrete_type() == Expression::COLOR) { const Color* col = dynamic_cast<const Color*>(val); return sass_make_color(col->r(), col->g(), col->b(), col->a()); } else if (val->concrete_type() == Expression::LIST) { const List* l = dynamic_cast<const List*>(val); union Sass_Value* list = sass_make_list(l->size(), l->separator()); for (size_t i = 0, L = l->length(); i < L; ++i) { auto val = ast_node_to_sass_value((*l)[i]); sass_list_set_value(list, i, val); } return list; } else if (val->concrete_type() == Expression::MAP) { const Map* m = dynamic_cast<const Map*>(val); union Sass_Value* map = sass_make_map(m->length()); size_t i = 0; for (auto key : m->keys()) { sass_map_set_key(map, i, ast_node_to_sass_value(key)); sass_map_set_value(map, i, ast_node_to_sass_value(m->at(key))); ++ i; } return map; } else if (val->concrete_type() == Expression::NULL_VAL) { return sass_make_null(); } else if (val->concrete_type() == Expression::BOOLEAN) { const Boolean* res = dynamic_cast<const Boolean*>(val); return sass_make_boolean(res->value()); } else if (val->concrete_type() == Expression::STRING) { if (const String_Quoted* qstr = dynamic_cast<const String_Quoted*>(val)) { return sass_make_qstring(qstr->value().c_str()); } else if (const String_Constant* cstr = dynamic_cast<const String_Constant*>(val)) { return sass_make_string(cstr->value().c_str()); } } return sass_make_error("unknown sass value type"); } // convert value from C-API to C++ side Value* sass_value_to_ast_node (Memory_Manager& mem, const union Sass_Value* val) { switch (sass_value_get_tag(val)) { case SASS_NUMBER: return SASS_MEMORY_NEW(mem, Number, ParserState("[C-VALUE]"), sass_number_get_value(val), sass_number_get_unit(val)); break; case SASS_BOOLEAN: return SASS_MEMORY_NEW(mem, Boolean, ParserState("[C-VALUE]"), sass_boolean_get_value(val)); break; case SASS_COLOR: return SASS_MEMORY_NEW(mem, Color, ParserState("[C-VALUE]"), sass_color_get_r(val), sass_color_get_g(val), sass_color_get_b(val), sass_color_get_a(val)); break; case SASS_STRING: if (sass_string_is_quoted(val)) { return SASS_MEMORY_NEW(mem, String_Quoted, ParserState("[C-VALUE]"), sass_string_get_value(val)); } else { return SASS_MEMORY_NEW(mem, String_Constant, ParserState("[C-VALUE]"), sass_string_get_value(val)); } break; case SASS_LIST: { List* l = SASS_MEMORY_NEW(mem, List, ParserState("[C-VALUE]"), sass_list_get_length(val), sass_list_get_separator(val)); for (size_t i = 0, L = sass_list_get_length(val); i < L; ++i) { *l << sass_value_to_ast_node(mem, sass_list_get_value(val, i)); } return l; } break; case SASS_MAP: { Map* m = SASS_MEMORY_NEW(mem, Map, ParserState("[C-VALUE]")); for (size_t i = 0, L = sass_map_get_length(val); i < L; ++i) { *m << std::make_pair( sass_value_to_ast_node(mem, sass_map_get_key(val, i)), sass_value_to_ast_node(mem, sass_map_get_value(val, i))); } return m; } break; case SASS_NULL: return SASS_MEMORY_NEW(mem, Null, ParserState("[C-VALUE]")); break; case SASS_ERROR: return SASS_MEMORY_NEW(mem, Custom_Error, ParserState("[C-VALUE]"), sass_error_get_message(val)); break; case SASS_WARNING: return SASS_MEMORY_NEW(mem, Custom_Warning, ParserState("[C-VALUE]"), sass_warning_get_message(val)); break; } return 0; } }
mit
honnibal/cython-blis
blis/_src/ivybridge/src/3/bli_l3_blocksize.c
7
10692
/* BLIS An object-based framework for developing high-performance BLAS-like libraries. Copyright (C) 2014, The University of Texas at Austin Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of The University of Texas at Austin 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. */ #include "blis.h" dim_t bli_l3_determine_kc ( dir_t direct, dim_t i, dim_t dim, obj_t* a, obj_t* b, bszid_t bszid, cntx_t* cntx, cntl_t* cntl ) { opid_t family = bli_cntl_family( cntl ); if ( family == BLIS_GEMM ) return bli_gemm_determine_kc( direct, i, dim, a, b, bszid, cntx ); else if ( family == BLIS_HERK ) return bli_herk_determine_kc( direct, i, dim, a, b, bszid, cntx ); else if ( family == BLIS_TRMM ) return bli_trmm_determine_kc( direct, i, dim, a, b, bszid, cntx ); else if ( family == BLIS_TRSM ) return bli_trsm_determine_kc( direct, i, dim, a, b, bszid, cntx ); // This should never execute. return bli_gemm_determine_kc( direct, i, dim, a, b, bszid, cntx ); } // ----------------------------------------------------------------------------- // // NOTE: We call a gemm/hemm/symm, trmm, or trsm-specific blocksize // function to determine the kc blocksize so that we can implement the // "nudging" of kc to be a multiple of mr or nr, as needed. // #undef GENFRONT #define GENFRONT( opname, l3op ) \ \ dim_t PASTEMAC0(opname) \ ( \ dir_t direct, \ dim_t i, \ dim_t dim, \ obj_t* a, \ obj_t* b, \ bszid_t bszid, \ cntx_t* cntx \ ) \ { \ if ( direct == BLIS_FWD ) \ return PASTEMAC(l3op,_determine_kc_f)( i, dim, a, b, bszid, cntx ); \ else \ return PASTEMAC(l3op,_determine_kc_b)( i, dim, a, b, bszid, cntx ); \ } GENFRONT( gemm_determine_kc, gemm ) GENFRONT( herk_determine_kc, trmm ) GENFRONT( trmm_determine_kc, trmm ) GENFRONT( trsm_determine_kc, trsm ) // ----------------------------------------------------------------------------- #undef GENFRONT #define GENFRONT( opname, chdir ) \ \ dim_t PASTEMAC0(opname) \ ( \ dim_t i, \ dim_t dim, \ obj_t* a, \ obj_t* b, \ bszid_t bszid, \ cntx_t* cntx \ ) \ { \ num_t dt; \ blksz_t* bsize; \ dim_t mnr; \ dim_t b_alg, b_max; \ dim_t b_use; \ \ /* bli_*_determine_kc_f(): We assume that this function is being called from an algorithm that is moving "forward" (ie: top to bottom, left to right, top-left to bottom-right). */ \ \ /* bli_*_determine_kc_b(): We assume that this function is being called from an algorithm that is moving "backward" (ie: bottom to top, right to left, bottom-right to top-left). */ \ \ /* Extract the execution datatype and use it to query the corresponding blocksize and blocksize maximum values from the blksz_t object. */ \ dt = bli_obj_execution_datatype( *a ); \ bsize = bli_cntx_get_blksz( bszid, cntx ); \ b_alg = bli_blksz_get_def( dt, bsize ); \ b_max = bli_blksz_get_max( dt, bsize ); \ \ /* Nudge the default and maximum kc blocksizes up to the nearest multiple of MR if A is Hermitian or symmetric, or NR if B is Hermitian or symmetric. If neither case applies, then we leave the blocksizes unchanged. */ \ if ( bli_obj_root_is_herm_or_symm( *a ) ) \ { \ mnr = bli_cntx_get_blksz_def_dt( dt, BLIS_MR, cntx ); \ b_alg = bli_align_dim_to_mult( b_alg, mnr ); \ b_max = bli_align_dim_to_mult( b_max, mnr ); \ } \ else if ( bli_obj_root_is_herm_or_symm( *b ) ) \ { \ mnr = bli_cntx_get_blksz_def_dt( dt, BLIS_NR, cntx ); \ b_alg = bli_align_dim_to_mult( b_alg, mnr ); \ b_max = bli_align_dim_to_mult( b_max, mnr ); \ } \ \ /* Call the bli_determine_blocksize_[fb]_sub() helper routine defined in bli_blksz.c */ \ b_use = PASTEMAC2(determine_blocksize_,chdir,_sub)( i, dim, b_alg, b_max ); \ \ return b_use; \ } GENFRONT( gemm_determine_kc_f, f ) GENFRONT( gemm_determine_kc_b, b ) // ----------------------------------------------------------------------------- #undef GENFRONT #define GENFRONT( opname, chdir ) \ \ dim_t PASTEMAC0(opname) \ ( \ dim_t i, \ dim_t dim, \ obj_t* a, \ obj_t* b, \ bszid_t bszid, \ cntx_t* cntx \ ) \ { \ num_t dt; \ blksz_t* bsize; \ dim_t b_alg, b_max; \ dim_t b_use; \ \ /* bli_*_determine_kc_f(): We assume that this function is being called from an algorithm that is moving "forward" (ie: top to bottom, left to right, top-left to bottom-right). */ \ \ /* bli_*_determine_kc_b(): We assume that this function is being called from an algorithm that is moving "backward" (ie: bottom to top, right to left, bottom-right to top-left). */ \ \ /* Extract the execution datatype and use it to query the corresponding blocksize and blocksize maximum values from the blksz_t object. */ \ dt = bli_obj_execution_datatype( *a ); \ bsize = bli_cntx_get_blksz( bszid, cntx ); \ b_alg = bli_blksz_get_def( dt, bsize ); \ b_max = bli_blksz_get_max( dt, bsize ); \ \ /* Notice that for herk, we do not need to perform any special handling for the default and maximum kc blocksizes vis-a-vis MR or NR. */ \ \ /* Call the bli_determine_blocksize_[fb]_sub() helper routine defined in bli_blksz.c */ \ b_use = PASTEMAC2(determine_blocksize_,chdir,_sub)( i, dim, b_alg, b_max ); \ \ return b_use; \ } GENFRONT( herk_determine_kc_f, f ) GENFRONT( herk_determine_kc_b, b ) // ----------------------------------------------------------------------------- #undef GENFRONT #define GENFRONT( opname, chdir ) \ \ dim_t PASTEMAC0(opname) \ ( \ dim_t i, \ dim_t dim, \ obj_t* a, \ obj_t* b, \ bszid_t bszid, \ cntx_t* cntx \ ) \ { \ num_t dt; \ blksz_t* bsize; \ dim_t mnr; \ dim_t b_alg, b_max; \ dim_t b_use; \ \ /* bli_*_determine_kc_f(): We assume that this function is being called from an algorithm that is moving "forward" (ie: top to bottom, left to right, top-left to bottom-right). */ \ \ /* bli_*_determine_kc_b(): We assume that this function is being called from an algorithm that is moving "backward" (ie: bottom to top, right to left, bottom-right to top-left). */ \ \ /* Extract the execution datatype and use it to query the corresponding blocksize and blocksize maximum values from the blksz_t object. */ \ dt = bli_obj_execution_datatype( *a ); \ bsize = bli_cntx_get_blksz( bszid, cntx ); \ b_alg = bli_blksz_get_def( dt, bsize ); \ b_max = bli_blksz_get_max( dt, bsize ); \ \ /* Nudge the default and maximum kc blocksizes up to the nearest multiple of MR if the triangular matrix is on the left, or NR if the triangular matrix is one the right. */ \ if ( bli_obj_root_is_triangular( *a ) ) \ mnr = bli_cntx_get_blksz_def_dt( dt, BLIS_MR, cntx ); \ else \ mnr = bli_cntx_get_blksz_def_dt( dt, BLIS_NR, cntx ); \ \ b_alg = bli_align_dim_to_mult( b_alg, mnr ); \ b_max = bli_align_dim_to_mult( b_max, mnr ); \ \ /* Call the bli_determine_blocksize_[fb]_sub() helper routine defined in bli_blksz.c */ \ b_use = PASTEMAC2(determine_blocksize_,chdir,_sub)( i, dim, b_alg, b_max ); \ \ return b_use; \ } GENFRONT( trmm_determine_kc_f, f ) GENFRONT( trmm_determine_kc_b, b ) // ----------------------------------------------------------------------------- #undef GENFRONT #define GENFRONT( opname, chdir ) \ \ dim_t PASTEMAC0(opname) \ ( \ dim_t i, \ dim_t dim, \ obj_t* a, \ obj_t* b, \ bszid_t bszid, \ cntx_t* cntx \ ) \ { \ num_t dt; \ blksz_t* bsize; \ dim_t mnr; \ dim_t b_alg, b_max; \ dim_t b_use; \ \ /* bli_*_determine_kc_f(): We assume that this function is being called from an algorithm that is moving "forward" (ie: top to bottom, left to right, top-left to bottom-right). */ \ \ /* bli_*_determine_kc_b(): We assume that this function is being called from an algorithm that is moving "backward" (ie: bottom to top, right to left, bottom-right to top-left). */ \ \ /* Extract the execution datatype and use it to query the corresponding blocksize and blocksize maximum values from the blksz_t object. */ \ dt = bli_obj_execution_datatype( *a ); \ bsize = bli_cntx_get_blksz( bszid, cntx ); \ b_alg = bli_blksz_get_def( dt, bsize ); \ b_max = bli_blksz_get_max( dt, bsize ); \ \ /* Nudge the default and maximum kc blocksizes up to the nearest multiple of MR. We always use MR (rather than sometimes using NR) because even when the triangle is on the right, packing of that matrix uses MR, since only left-side trsm micro-kernels are supported. */ \ mnr = bli_cntx_get_blksz_def_dt( dt, BLIS_MR, cntx ); \ b_alg = bli_align_dim_to_mult( b_alg, mnr ); \ b_max = bli_align_dim_to_mult( b_max, mnr ); \ \ /* Call the bli_determine_blocksize_[fb]_sub() helper routine defined in bli_blksz.c */ \ b_use = PASTEMAC2(determine_blocksize_,chdir,_sub)( i, dim, b_alg, b_max ); \ \ return b_use; \ } GENFRONT( trsm_determine_kc_f, f ) GENFRONT( trsm_determine_kc_b, b )
mit
instagibbs/bitcoin
src/test/descriptor_tests.cpp
7
80046
// Copyright (c) 2018-2021 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 <pubkey.h> #include <script/descriptor.h> #include <script/sign.h> #include <script/standard.h> #include <test/util/setup_common.h> #include <util/strencodings.h> #include <boost/test/unit_test.hpp> #include <optional> #include <string> #include <vector> namespace { void CheckUnparsable(const std::string& prv, const std::string& pub, const std::string& expected_error) { FlatSigningProvider keys_priv, keys_pub; std::string error; auto parse_priv = Parse(prv, keys_priv, error); auto parse_pub = Parse(pub, keys_pub, error); BOOST_CHECK_MESSAGE(!parse_priv, prv); BOOST_CHECK_MESSAGE(!parse_pub, pub); BOOST_CHECK_EQUAL(error, expected_error); } /** Check that the script is inferred as non-standard */ void CheckInferRaw(const CScript& script) { FlatSigningProvider dummy_provider; std::unique_ptr<Descriptor> desc = InferDescriptor(script, dummy_provider); BOOST_CHECK(desc->ToString().rfind("raw(", 0) == 0); } constexpr int DEFAULT = 0; constexpr int RANGE = 1; // Expected to be ranged descriptor constexpr int HARDENED = 2; // Derivation needs access to private keys constexpr int UNSOLVABLE = 4; // This descriptor is not expected to be solvable constexpr int SIGNABLE = 8; // We can sign with this descriptor (this is not true when actual BIP32 derivation is used, as that's not integrated in our signing code) constexpr int DERIVE_HARDENED = 16; // The final derivation is hardened, i.e. ends with *' or *h constexpr int MIXED_PUBKEYS = 32; constexpr int XONLY_KEYS = 64; // X-only pubkeys are in use (and thus inferring/caching may swap parity of pubkeys/keyids) constexpr int MISSING_PRIVKEYS = 128; // Not all private keys are available, so ToPrivateString will fail. /** Compare two descriptors. If only one of them has a checksum, the checksum is ignored. */ bool EqualDescriptor(std::string a, std::string b) { bool a_check = (a.size() > 9 && a[a.size() - 9] == '#'); bool b_check = (b.size() > 9 && b[b.size() - 9] == '#'); if (a_check != b_check) { if (a_check) a = a.substr(0, a.size() - 9); if (b_check) b = b.substr(0, b.size() - 9); } return a == b; } std::string UseHInsteadOfApostrophe(const std::string& desc) { std::string ret = desc; while (true) { auto it = ret.find('\''); if (it == std::string::npos) break; ret[it] = 'h'; } // GetDescriptorChecksum returns "" if the checksum exists but is bad. // Switching apostrophes with 'h' breaks the checksum if it exists - recalculate it and replace the broken one. if (GetDescriptorChecksum(ret) == "") { ret = ret.substr(0, desc.size() - 9); ret += std::string("#") + GetDescriptorChecksum(ret); } return ret; } // Count the number of times the string "xpub" appears in a descriptor string static size_t CountXpubs(const std::string& desc) { size_t count = 0; size_t p = desc.find("xpub", 0); while (p != std::string::npos) { count++; p = desc.find("xpub", p + 1); } return count; } const std::set<std::vector<uint32_t>> ONLY_EMPTY{{}}; std::set<CPubKey> GetKeyData(const FlatSigningProvider& provider, int flags) { std::set<CPubKey> ret; for (const auto& [_, pubkey] : provider.pubkeys) { if (flags & XONLY_KEYS) { unsigned char bytes[33]; BOOST_CHECK_EQUAL(pubkey.size(), 33); std::copy(pubkey.begin(), pubkey.end(), bytes); bytes[0] = 0x02; CPubKey norm_pubkey{bytes}; ret.insert(norm_pubkey); } else { ret.insert(pubkey); } } return ret; } std::set<std::pair<CPubKey, KeyOriginInfo>> GetKeyOriginData(const FlatSigningProvider& provider, int flags) { std::set<std::pair<CPubKey, KeyOriginInfo>> ret; for (const auto& [_, data] : provider.origins) { if (flags & XONLY_KEYS) { unsigned char bytes[33]; BOOST_CHECK_EQUAL(data.first.size(), 33); std::copy(data.first.begin(), data.first.end(), bytes); bytes[0] = 0x02; CPubKey norm_pubkey{bytes}; KeyOriginInfo norm_origin = data.second; std::fill(std::begin(norm_origin.fingerprint), std::end(norm_origin.fingerprint), 0); // fingerprints don't necessarily match. ret.emplace(norm_pubkey, norm_origin); } else { ret.insert(data); } } return ret; } void DoCheck(const std::string& prv, const std::string& pub, const std::string& norm_prv, const std::string& norm_pub, int flags, const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, const std::set<std::vector<uint32_t>>& paths = ONLY_EMPTY, bool replace_apostrophe_with_h_in_prv=false, bool replace_apostrophe_with_h_in_pub=false) { FlatSigningProvider keys_priv, keys_pub; std::set<std::vector<uint32_t>> left_paths = paths; std::string error; std::unique_ptr<Descriptor> parse_priv; std::unique_ptr<Descriptor> parse_pub; // Check that parsing succeeds. if (replace_apostrophe_with_h_in_prv) { parse_priv = Parse(UseHInsteadOfApostrophe(prv), keys_priv, error); } else { parse_priv = Parse(prv, keys_priv, error); } if (replace_apostrophe_with_h_in_pub) { parse_pub = Parse(UseHInsteadOfApostrophe(pub), keys_pub, error); } else { parse_pub = Parse(pub, keys_pub, error); } BOOST_CHECK(parse_priv); BOOST_CHECK(parse_pub); // Check that the correct OutputType is inferred BOOST_CHECK(parse_priv->GetOutputType() == type); BOOST_CHECK(parse_pub->GetOutputType() == type); // Check private keys are extracted from the private version but not the public one. BOOST_CHECK(keys_priv.keys.size()); BOOST_CHECK(!keys_pub.keys.size()); // Check that both versions serialize back to the public version. std::string pub1 = parse_priv->ToString(); std::string pub2 = parse_pub->ToString(); BOOST_CHECK(EqualDescriptor(pub, pub1)); BOOST_CHECK(EqualDescriptor(pub, pub2)); // Check that both can be serialized with private key back to the private version, but not without private key. if (!(flags & MISSING_PRIVKEYS)) { std::string prv1; BOOST_CHECK(parse_priv->ToPrivateString(keys_priv, prv1)); BOOST_CHECK(EqualDescriptor(prv, prv1)); BOOST_CHECK(!parse_priv->ToPrivateString(keys_pub, prv1)); BOOST_CHECK(parse_pub->ToPrivateString(keys_priv, prv1)); BOOST_CHECK(EqualDescriptor(prv, prv1)); BOOST_CHECK(!parse_pub->ToPrivateString(keys_pub, prv1)); } // Check that private can produce the normalized descriptors std::string norm1; BOOST_CHECK(parse_priv->ToNormalizedString(keys_priv, norm1)); BOOST_CHECK(EqualDescriptor(norm1, norm_pub)); BOOST_CHECK(parse_pub->ToNormalizedString(keys_priv, norm1)); BOOST_CHECK(EqualDescriptor(norm1, norm_pub)); // Check whether IsRange on both returns the expected result BOOST_CHECK_EQUAL(parse_pub->IsRange(), (flags & RANGE) != 0); BOOST_CHECK_EQUAL(parse_priv->IsRange(), (flags & RANGE) != 0); // * For ranged descriptors, the `scripts` parameter is a list of expected result outputs, for subsequent // positions to evaluate the descriptors on (so the first element of `scripts` is for evaluating the // descriptor at 0; the second at 1; and so on). To verify this, we evaluate the descriptors once for // each element in `scripts`. // * For non-ranged descriptors, we evaluate the descriptors at positions 0, 1, and 2, but expect the // same result in each case, namely the first element of `scripts`. Because of that, the size of // `scripts` must be one in that case. if (!(flags & RANGE)) assert(scripts.size() == 1); size_t max = (flags & RANGE) ? scripts.size() : 3; // Iterate over the position we'll evaluate the descriptors in. for (size_t i = 0; i < max; ++i) { // Call the expected result scripts `ref`. const auto& ref = scripts[(flags & RANGE) ? i : 0]; // When t=0, evaluate the `prv` descriptor; when t=1, evaluate the `pub` descriptor. for (int t = 0; t < 2; ++t) { // When the descriptor is hardened, evaluate with access to the private keys inside. const FlatSigningProvider& key_provider = (flags & HARDENED) ? keys_priv : keys_pub; // Evaluate the descriptor selected by `t` in position `i`. FlatSigningProvider script_provider, script_provider_cached; std::vector<CScript> spks, spks_cached; DescriptorCache desc_cache; BOOST_CHECK((t ? parse_priv : parse_pub)->Expand(i, key_provider, spks, script_provider, &desc_cache)); // Compare the output with the expected result. BOOST_CHECK_EQUAL(spks.size(), ref.size()); // Try to expand again using cached data, and compare. BOOST_CHECK(parse_pub->ExpandFromCache(i, desc_cache, spks_cached, script_provider_cached)); BOOST_CHECK(spks == spks_cached); BOOST_CHECK(GetKeyData(script_provider, flags) == GetKeyData(script_provider_cached, flags)); BOOST_CHECK(script_provider.scripts == script_provider_cached.scripts); BOOST_CHECK(GetKeyOriginData(script_provider, flags) == GetKeyOriginData(script_provider_cached, flags)); // Check whether keys are in the cache const auto& der_xpub_cache = desc_cache.GetCachedDerivedExtPubKeys(); const auto& parent_xpub_cache = desc_cache.GetCachedParentExtPubKeys(); const size_t num_xpubs = CountXpubs(pub1); if ((flags & RANGE) && !(flags & (DERIVE_HARDENED))) { // For ranged, unhardened derivation, None of the keys in origins should appear in the cache but the cache should have parent keys // But we can derive one level from each of those parent keys and find them all BOOST_CHECK(der_xpub_cache.empty()); BOOST_CHECK(parent_xpub_cache.size() > 0); std::set<CPubKey> pubkeys; for (const auto& xpub_pair : parent_xpub_cache) { const CExtPubKey& xpub = xpub_pair.second; CExtPubKey der; xpub.Derive(der, i); pubkeys.insert(der.pubkey); } int count_pks = 0; for (const auto& origin_pair : script_provider_cached.origins) { const CPubKey& pk = origin_pair.second.first; count_pks += pubkeys.count(pk); } if (flags & MIXED_PUBKEYS) { BOOST_CHECK_EQUAL(num_xpubs, count_pks); } else { BOOST_CHECK_EQUAL(script_provider_cached.origins.size(), count_pks); } } else if (num_xpubs > 0) { // For ranged, hardened derivation, or not ranged, but has an xpub, all of the keys should appear in the cache BOOST_CHECK(der_xpub_cache.size() + parent_xpub_cache.size() == num_xpubs); if (!(flags & MIXED_PUBKEYS)) { BOOST_CHECK(num_xpubs == script_provider_cached.origins.size()); } // Get all of the derived pubkeys std::set<CPubKey> pubkeys; for (const auto& xpub_map_pair : der_xpub_cache) { for (const auto& xpub_pair : xpub_map_pair.second) { const CExtPubKey& xpub = xpub_pair.second; pubkeys.insert(xpub.pubkey); } } // Derive one level from all of the parents for (const auto& xpub_pair : parent_xpub_cache) { const CExtPubKey& xpub = xpub_pair.second; pubkeys.insert(xpub.pubkey); CExtPubKey der; xpub.Derive(der, i); pubkeys.insert(der.pubkey); } int count_pks = 0; for (const auto& origin_pair : script_provider_cached.origins) { const CPubKey& pk = origin_pair.second.first; count_pks += pubkeys.count(pk); } if (flags & MIXED_PUBKEYS) { BOOST_CHECK_EQUAL(num_xpubs, count_pks); } else { BOOST_CHECK_EQUAL(script_provider_cached.origins.size(), count_pks); } } else if (!(flags & MIXED_PUBKEYS)) { // Only const pubkeys, nothing should be cached BOOST_CHECK(der_xpub_cache.empty()); BOOST_CHECK(parent_xpub_cache.empty()); } // Make sure we can expand using cached xpubs for unhardened derivation if (!(flags & DERIVE_HARDENED)) { // Evaluate the descriptor at i + 1 FlatSigningProvider script_provider1, script_provider_cached1; std::vector<CScript> spks1, spk1_from_cache; BOOST_CHECK((t ? parse_priv : parse_pub)->Expand(i + 1, key_provider, spks1, script_provider1, nullptr)); // Try again but use the cache from expanding i. That cache won't have the pubkeys for i + 1, but will have the parent xpub for derivation. BOOST_CHECK(parse_pub->ExpandFromCache(i + 1, desc_cache, spk1_from_cache, script_provider_cached1)); BOOST_CHECK(spks1 == spk1_from_cache); BOOST_CHECK(GetKeyData(script_provider1, flags) == GetKeyData(script_provider_cached1, flags)); BOOST_CHECK(script_provider1.scripts == script_provider_cached1.scripts); BOOST_CHECK(GetKeyOriginData(script_provider1, flags) == GetKeyOriginData(script_provider_cached1, flags)); } // For each of the produced scripts, verify solvability, and when possible, try to sign a transaction spending it. for (size_t n = 0; n < spks.size(); ++n) { BOOST_CHECK_EQUAL(ref[n], HexStr(spks[n])); BOOST_CHECK_EQUAL(IsSolvable(Merge(key_provider, script_provider), spks[n]), (flags & UNSOLVABLE) == 0); if (flags & SIGNABLE) { CMutableTransaction spend; spend.vin.resize(1); spend.vout.resize(1); std::vector<CTxOut> utxos(1); PrecomputedTransactionData txdata; txdata.Init(spend, std::move(utxos), /*force=*/true); MutableTransactionSignatureCreator creator{spend, 0, CAmount{0}, &txdata, SIGHASH_DEFAULT}; SignatureData sigdata; BOOST_CHECK_MESSAGE(ProduceSignature(Merge(keys_priv, script_provider), creator, spks[n], sigdata), prv); } /* Infer a descriptor from the generated script, and verify its solvability and that it roundtrips. */ auto inferred = InferDescriptor(spks[n], script_provider); BOOST_CHECK_EQUAL(inferred->IsSolvable(), !(flags & UNSOLVABLE)); std::vector<CScript> spks_inferred; FlatSigningProvider provider_inferred; BOOST_CHECK(inferred->Expand(0, provider_inferred, spks_inferred, provider_inferred)); BOOST_CHECK_EQUAL(spks_inferred.size(), 1U); BOOST_CHECK(spks_inferred[0] == spks[n]); BOOST_CHECK_EQUAL(IsSolvable(provider_inferred, spks_inferred[0]), !(flags & UNSOLVABLE)); BOOST_CHECK(GetKeyOriginData(provider_inferred, flags) == GetKeyOriginData(script_provider, flags)); } // Test whether the observed key path is present in the 'paths' variable (which contains expected, unobserved paths), // and then remove it from that set. for (const auto& origin : script_provider.origins) { BOOST_CHECK_MESSAGE(paths.count(origin.second.second.path), "Unexpected key path: " + prv); left_paths.erase(origin.second.second.path); } } } // Verify no expected paths remain that were not observed. BOOST_CHECK_MESSAGE(left_paths.empty(), "Not all expected key paths found: " + prv); } void Check(const std::string& prv, const std::string& pub, const std::string& norm_prv, const std::string& norm_pub, int flags, const std::vector<std::vector<std::string>>& scripts, const std::optional<OutputType>& type, const std::set<std::vector<uint32_t>>& paths = ONLY_EMPTY) { bool found_apostrophes_in_prv = false; bool found_apostrophes_in_pub = false; // Do not replace apostrophes with 'h' in prv and pub DoCheck(prv, pub, norm_prv, norm_pub, flags, scripts, type, paths); // Replace apostrophes with 'h' in prv but not in pub, if apostrophes are found in prv if (prv.find('\'') != std::string::npos) { found_apostrophes_in_prv = true; DoCheck(prv, pub, norm_prv, norm_pub, flags, scripts, type, paths, /* replace_apostrophe_with_h_in_prv = */true, /*replace_apostrophe_with_h_in_pub = */false); } // Replace apostrophes with 'h' in pub but not in prv, if apostrophes are found in pub if (pub.find('\'') != std::string::npos) { found_apostrophes_in_pub = true; DoCheck(prv, pub, norm_prv, norm_pub, flags, scripts, type, paths, /* replace_apostrophe_with_h_in_prv = */false, /*replace_apostrophe_with_h_in_pub = */true); } // Replace apostrophes with 'h' both in prv and in pub, if apostrophes are found in both if (found_apostrophes_in_prv && found_apostrophes_in_pub) { DoCheck(prv, pub, norm_prv, norm_pub, flags, scripts, type, paths, /* replace_apostrophe_with_h_in_prv = */true, /*replace_apostrophe_with_h_in_pub = */true); } } } BOOST_FIXTURE_TEST_SUITE(descriptor_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(descriptor_test) { // Basic single-key compressed Check("combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE, {{"2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac","76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac","00149a1c78a507689f6f54b847ad1cef1e614ee23f1e","a91484ab21b1b2fd065d4504ff693d832434b6108d7b87"}}, std::nullopt); Check("pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE, {{"2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bdac"}}, std::nullopt); Check("pkh([deadbeef/1/2'/3/4']L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pkh([deadbeef/1/2'/3/4']03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "pkh([deadbeef/1/2'/3/4']L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pkh([deadbeef/1/2'/3/4']03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE, {{"76a9149a1c78a507689f6f54b847ad1cef1e614ee23f1e88ac"}}, OutputType::LEGACY, {{1,0x80000002UL,3,0x80000004UL}}); Check("wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE, {{"00149a1c78a507689f6f54b847ad1cef1e614ee23f1e"}}, OutputType::BECH32); Check("sh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "sh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", SIGNABLE, {{"a91484ab21b1b2fd065d4504ff693d832434b6108d7b87"}}, OutputType::P2SH_SEGWIT); Check("tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE | XONLY_KEYS, {{"512077aab6e066f8a7419c5ab714c12c67d25007ed55a43cadcacb4d7a970a093f11"}}, OutputType::BECH32M); CheckUnparsable("sh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY2))", "sh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5))", "wpkh(): Pubkey '03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5' is invalid"); // Invalid pubkey CheckUnparsable("pkh(deadbeef/1/2'/3/4']L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pkh(deadbeef/1/2'/3/4']03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "pkh(): Key origin start '[ character expected but not found, got 'd' instead"); // Missing start bracket in key origin CheckUnparsable("pkh([deadbeef]/1/2'/3/4']L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "pkh([deadbeef]/1/2'/3/4']03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "pkh(): Multiple ']' characters found for a single pubkey"); // Multiple end brackets in key origin // Basic single-key uncompressed Check("combo(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "combo(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "combo(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "combo(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)",SIGNABLE, {{"4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac","76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac"}}, std::nullopt); Check("pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", SIGNABLE, {{"4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235ac"}}, std::nullopt); Check("pkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "pkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "pkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "pkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", SIGNABLE, {{"76a914b5bd079c4d57cc7fc28ecf8213a6b791625b818388ac"}}, OutputType::LEGACY); CheckUnparsable("wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "wpkh(): Uncompressed keys are not allowed"); // No uncompressed keys in witness CheckUnparsable("wsh(pk(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))", "wsh(pk(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))", "pk(): Uncompressed keys are not allowed"); // No uncompressed keys in witness CheckUnparsable("sh(wpkh(5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss))", "sh(wpkh(04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235))", "wpkh(): Uncompressed keys are not allowed"); // No uncompressed keys in witness // Some unconventional single-key constructions Check("sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", SIGNABLE, {{"a9141857af51a5e516552b3086430fd8ce55f7c1a52487"}}, OutputType::LEGACY); Check("sh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "sh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", SIGNABLE, {{"a9141a31ad23bf49c247dd531a623c2ef57da3c400c587"}}, OutputType::LEGACY); Check("wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", SIGNABLE, {{"00202e271faa2325c199d25d22e1ead982e45b64eeb4f31e73dbdf41bd4b5fec23fa"}}, OutputType::BECH32); Check("wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", SIGNABLE, {{"0020338e023079b91c58571b20e602d7805fb808c22473cbc391a41b1bd3a192e75b"}}, OutputType::BECH32); Check("sh(wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "sh(wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", "sh(wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "sh(wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", SIGNABLE, {{"a91472d0c5a3bfad8c3e7bd5303a72b94240e80b6f1787"}}, OutputType::P2SH_SEGWIT); Check("sh(wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "sh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", "sh(wsh(pkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "sh(wsh(pkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", SIGNABLE, {{"a914b61b92e2ca21bac1e72a3ab859a742982bea960a87"}}, OutputType::P2SH_SEGWIT); Check("tr(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5,{pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5),{pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1),pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5)}})", "tr(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5,{pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5),{pk(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd),pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5)}})", "tr(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5,{pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5),{pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1),pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5)}})", "tr(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5,{pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5),{pk(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd),pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5)}})", XONLY_KEYS | SIGNABLE | MISSING_PRIVKEYS, {{"51201497ae16f30dacb88523ed9301bff17773b609e8a90518a3f96ea328a47d1500"}}, OutputType::BECH32M); // Versions with BIP32 derivations Check("combo([01234567]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc)", "combo([01234567]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL)", "combo([01234567]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc)", "combo([01234567]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL)", SIGNABLE, {{"2102d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0ac","76a91431a507b815593dfc51ffc7245ae7e5aee304246e88ac","001431a507b815593dfc51ffc7245ae7e5aee304246e","a9142aafb926eb247cb18240a7f4c07983ad1f37922687"}}, std::nullopt); Check("pk(xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0)", "pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0)", "pk(xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0)", "pk(xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0)", DEFAULT, {{"210379e45b3cf75f9c5f9befd8e9506fb962f6a9d185ac87001ec44a8d3df8d4a9e3ac"}}, std::nullopt, {{0}}); Check("pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0)", "pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0)", "pkh([bd16bee5/2147483647']xprv9vHkqa6XAPwKqSKSEJMcAB3yoCZhaSVsGZbSkFY5L3Lfjjk8sjZucbsbvEw5o3QrSA69nPfZDCgFnNnLhQ2ohpZuwummndnPasDw2Qr6dC2/0)", "pkh([bd16bee5/2147483647']xpub69H7F5dQzmVd3vPuLKtcXJziMEQByuDidnX3YdwgtNsecY5HRGtAAQC5mXTt4dsv9RzyjgDjAQs9VGVV6ydYCHnprc9vvaA5YtqWyL6hyds/0)", HARDENED, {{"76a914ebdc90806a9c4356c1c88e42216611e1cb4c1c1788ac"}}, OutputType::LEGACY, {{0xFFFFFFFFUL,0}}); Check("wpkh([ffffffff/13']xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*)", "wpkh([ffffffff/13']xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*)", "wpkh([ffffffff/13']xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*)", "wpkh([ffffffff/13']xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*)", RANGE, {{"0014326b2249e3a25d5dc60935f044ee835d090ba859"},{"0014af0bd98abc2f2cae66e36896a39ffe2d32984fb7"},{"00141fa798efd1cbf95cebf912c031b8a4a6e9fb9f27"}}, OutputType::BECH32, {{0x8000000DUL, 1, 2, 0}, {0x8000000DUL, 1, 2, 1}, {0x8000000DUL, 1, 2, 2}}); Check("sh(wpkh(xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "sh(wpkh(xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "sh(wpkh(xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "sh(wpkh(xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", RANGE | HARDENED | DERIVE_HARDENED, {{"a9149a4d9901d6af519b2a23d4a2f51650fcba87ce7b87"},{"a914bed59fc0024fae941d6e20a3b44a109ae740129287"},{"a9148483aa1116eb9c05c482a72bada4b1db24af654387"}}, OutputType::P2SH_SEGWIT, {{10, 20, 30, 40, 0x80000000UL}, {10, 20, 30, 40, 0x80000001UL}, {10, 20, 30, 40, 0x80000002UL}}); Check("combo(xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/*)", "combo(xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/*)", "combo(xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/*)", "combo(xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/*)", RANGE, {{"2102df12b7035bdac8e3bab862a3a83d06ea6b17b6753d52edecba9be46f5d09e076ac","76a914f90e3178ca25f2c808dc76624032d352fdbdfaf288ac","0014f90e3178ca25f2c808dc76624032d352fdbdfaf2","a91408f3ea8c68d4a7585bf9e8bda226723f70e445f087"},{"21032869a233c9adff9a994e4966e5b821fd5bac066da6c3112488dc52383b4a98ecac","76a914a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b788ac","0014a8409d1b6dfb1ed2a3e8aa5e0ef2ff26b15b75b7","a91473e39884cb71ae4e5ac9739e9225026c99763e6687"}}, std::nullopt, {{0}, {1}}); Check("tr(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/0/*,pk(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/1/*))", "tr(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/0/*,pk(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*))", "tr(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/0/*,pk(xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/1/*))", "tr(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/0/*,pk(xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*))", XONLY_KEYS | RANGE, {{"512078bc707124daa551b65af74de2ec128b7525e10f374dc67b64e00ce0ab8b3e12"}, {"512001f0a02a17808c20134b78faab80ef93ffba82261ccef0a2314f5d62b6438f11"}, {"512021024954fcec88237a9386fce80ef2ced5f1e91b422b26c59ccfc174c8d1ad25"}}, OutputType::BECH32M, {{0, 0}, {0, 1}, {0, 2}, {1, 0}, {1, 1}, {1, 2}}); // Mixed xpubs and const pubkeys Check("wsh(multi(1,xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/0,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))","wsh(multi(1,xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/0,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))","wsh(multi(1,xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/0,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))","wsh(multi(1,xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/0,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", MIXED_PUBKEYS, {{"0020cb155486048b23a6da976d4c6fe071a2dbc8a7b57aaf225b8955f2e2a27b5f00"}},OutputType::BECH32,{{0},{}}); // Mixed range xpubs and const pubkeys Check("multi(1,xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/*,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)","multi(1,xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/*,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)","multi(1,xprvA2JDeKCSNNZky6uBCviVfJSKyQ1mDYahRjijr5idH2WwLsEd4Hsb2Tyh8RfQMuPh7f7RtyzTtdrbdqqsunu5Mm3wDvUAKRHSC34sJ7in334/*,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)","multi(1,xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV/*,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", RANGE | MIXED_PUBKEYS, {{"512102df12b7035bdac8e3bab862a3a83d06ea6b17b6753d52edecba9be46f5d09e0762103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd52ae"},{"5121032869a233c9adff9a994e4966e5b821fd5bac066da6c3112488dc52383b4a98ec2103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd52ae"},{"5121035d30b6c66dc1e036c45369da8287518cf7e0d6ed1e2b905171c605708f14ca032103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd52ae"}}, std::nullopt,{{2},{1},{0},{}}); CheckUnparsable("combo([012345678]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc)", "combo([012345678]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL)", "combo(): Fingerprint is not 4 bytes (9 characters instead of 8 characters)"); // Too long key fingerprint CheckUnparsable("pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483648)", "pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483648)", "pkh(): Key path value 2147483648 is out of range"); // BIP 32 path element overflow CheckUnparsable("pkh(xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/1aa)", "pkh(xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/1aa)", "pkh(): Key path value '1aa' is not a valid uint32"); // Path is not valid uint Check("pkh([01234567/10/20]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0)", "pkh([01234567/10/20]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0)", "pkh([01234567/10/20/2147483647']xprv9vHkqa6XAPwKqSKSEJMcAB3yoCZhaSVsGZbSkFY5L3Lfjjk8sjZucbsbvEw5o3QrSA69nPfZDCgFnNnLhQ2ohpZuwummndnPasDw2Qr6dC2/0)", "pkh([01234567/10/20/2147483647']xpub69H7F5dQzmVd3vPuLKtcXJziMEQByuDidnX3YdwgtNsecY5HRGtAAQC5mXTt4dsv9RzyjgDjAQs9VGVV6ydYCHnprc9vvaA5YtqWyL6hyds/0)", HARDENED, {{"76a914ebdc90806a9c4356c1c88e42216611e1cb4c1c1788ac"}}, OutputType::LEGACY, {{10, 20, 0xFFFFFFFFUL, 0}}); // Multisig constructions Check("multi(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "multi(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "multi(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "multi(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", SIGNABLE, {{"512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae"}}, std::nullopt); Check("sortedmulti(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "sortedmulti(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "sortedmulti(1,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "sortedmulti(1,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", SIGNABLE, {{"512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae"}}, std::nullopt); Check("sortedmulti(1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "sortedmulti(1,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "sortedmulti(1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "sortedmulti(1,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", SIGNABLE, {{"512103a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd4104a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea23552ae"}}, std::nullopt); Check("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))", "sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))", DEFAULT, {{"a91445a9a622a8b0a1269944be477640eedc447bbd8487"}}, OutputType::LEGACY, {{0x8000006FUL,222},{0}}); Check("sortedmulti(2,xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/*,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0/0/*)", "sortedmulti(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/0/*)", "sortedmulti(2,xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc/*,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0/0/*)", "sortedmulti(2,xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/*,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0/0/*)", RANGE, {{"5221025d5fc65ebb8d44a5274b53bac21ff8307fec2334a32df05553459f8b1f7fe1b62102fbd47cc8034098f0e6a94c6aeee8528abf0a2153a5d8e46d325b7284c046784652ae"}, {"52210264fd4d1f5dea8ded94c61e9641309349b62f27fbffe807291f664e286bfbe6472103f4ece6dfccfa37b211eb3d0af4d0c61dba9ef698622dc17eecdf764beeb005a652ae"}, {"5221022ccabda84c30bad578b13c89eb3b9544ce149787e5b538175b1d1ba259cbb83321024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c52ae"}}, std::nullopt, {{0}, {1}, {2}, {0, 0, 0}, {0, 0, 1}, {0, 0, 2}}); Check("wsh(multi(2,xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "wsh(multi(2,[bd16bee5/2147483647']xprv9vHkqa6XAPwKqSKSEJMcAB3yoCZhaSVsGZbSkFY5L3Lfjjk8sjZucbsbvEw5o3QrSA69nPfZDCgFnNnLhQ2ohpZuwummndnPasDw2Qr6dC2/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[bd16bee5/2147483647']xpub69H7F5dQzmVd3vPuLKtcXJziMEQByuDidnX3YdwgtNsecY5HRGtAAQC5mXTt4dsv9RzyjgDjAQs9VGVV6ydYCHnprc9vvaA5YtqWyL6hyds/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", HARDENED | RANGE | DERIVE_HARDENED, {{"0020b92623201f3bb7c3771d45b2ad1d0351ea8fbf8cfe0a0e570264e1075fa1948f"},{"002036a08bbe4923af41cf4316817c93b8d37e2f635dd25cfff06bd50df6ae7ea203"},{"0020a96e7ab4607ca6b261bfe3245ffda9c746b28d3f59e83d34820ec0e2b36c139c"}}, OutputType::BECH32, {{0xFFFFFFFFUL,0}, {1,2,0}, {1,2,1}, {1,2,2}, {10, 20, 30, 40, 0x80000000UL}, {10, 20, 30, 40, 0x80000001UL}, {10, 20, 30, 40, 0x80000002UL}}); Check("sh(wsh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9)))","sh(wsh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232)))", "sh(wsh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9)))","sh(wsh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232)))", SIGNABLE, {{"a9147fc63e13dc25e8a95a3cee3d9a714ac3afd96f1e87"}}, OutputType::P2SH_SEGWIT); Check("tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,pk(KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy))", "tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,pk(669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))", "tr(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,pk(KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy))", "tr(a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,pk(669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0))", SIGNABLE | XONLY_KEYS, {{"512017cf18db381d836d8923b1bdb246cfcd818da1a9f0e6e7907f187f0b2f937754"}}, OutputType::BECH32M); CheckUnparsable("sh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9))","sh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232))", "P2SH script is too large, 547 bytes is larger than 520 bytes"); // P2SH does not fit 16 compressed pubkeys in a redeemscript CheckUnparsable("wsh(multi(2,[aaaaaaaa][aaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[aaaaaaaa][aaaaaaaa]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "Multi: Multiple ']' characters found for a single pubkey"); // Double key origin descriptor CheckUnparsable("wsh(multi(2,[aaaagaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[aaagaaaa]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "Multi: Fingerprint 'aaagaaaa' is not hex"); // Non hex fingerprint CheckUnparsable("wsh(multi(2,[aaaaaaaa],xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[aaaaaaaa],xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "Multi: No key provided"); // No public key with origin CheckUnparsable("wsh(multi(2,[aaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[aaaaaaa]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "Multi: Fingerprint is not 4 bytes (7 characters instead of 8 characters)"); // Too short fingerprint CheckUnparsable("wsh(multi(2,[aaaaaaaaa]xprv9s21ZrQH143K31xYSDQpPDxsXRTUcvj2iNHm5NUtrGiGG5e2DtALGdso3pGz6ssrdK4PFmM8NSpSBHNqPqm55Qn3LqFtT2emdEXVYsCzC2U/2147483647'/0,xprv9vHkqa6EV4sPZHYqZznhT2NPtPCjKuDKGY38FBWLvgaDx45zo9WQRUT3dKYnjwih2yJD9mkrocEZXo1ex8G81dwSM1fwqWpWkeS3v86pgKt/1/2/*,xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi/10/20/30/40/*'))", "wsh(multi(2,[aaaaaaaaa]xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB/2147483647'/0,xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH/1/2/*,xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/10/20/30/40/*'))", "Multi: Fingerprint is not 4 bytes (9 characters instead of 8 characters)"); // Too long fingerprint CheckUnparsable("multi(a,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "multi(a,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "Multi threshold 'a' is not valid"); // Invalid threshold CheckUnparsable("multi(0,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "multi(0,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "Multisig threshold cannot be 0, must be at least 1"); // Threshold of 0 CheckUnparsable("multi(3,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1,5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss)", "multi(3,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd,04a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd5b8dec5235a0fa8722476c7709c02559e3aa73aa03918ba2d492eea75abea235)", "Multisig threshold cannot be larger than the number of keys; threshold is 3 but only 2 keys specified"); // Threshold larger than number of keys CheckUnparsable("multi(3,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f)", "multi(3,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8)", "Cannot have 4 pubkeys in bare multisig; only at most 3 pubkeys"); // Threshold larger than number of keys CheckUnparsable("sh(multi(16,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))","sh(multi(16,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232,03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "P2SH script is too large, 581 bytes is larger than 520 bytes"); // Cannot have more than 15 keys in a P2SH multisig, or we exceed maximum push size Check("wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv))","wsh(multi(20,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232,02bc2feaa536991d269aae46abb8f3772a5b3ad592314945e51543e7da84c4af6e,0318bf32e5217c1eb771a6d5ce1cd39395dff7ff665704f175c9a5451d95a2f2ca,02c681a6243f16208c2004bb81f5a8a67edfdd3e3711534eadeec3dcf0b010c759,0249fdd6b69768b8d84b4893f8ff84b36835c50183de20fcae8f366a45290d01fd))", "wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv))","wsh(multi(20,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232,02bc2feaa536991d269aae46abb8f3772a5b3ad592314945e51543e7da84c4af6e,0318bf32e5217c1eb771a6d5ce1cd39395dff7ff665704f175c9a5451d95a2f2ca,02c681a6243f16208c2004bb81f5a8a67edfdd3e3711534eadeec3dcf0b010c759,0249fdd6b69768b8d84b4893f8ff84b36835c50183de20fcae8f366a45290d01fd))", SIGNABLE, {{"0020376bd8344b8b6ebe504ff85ef743eaa1aa9272178223bcb6887e9378efb341ac"}}, OutputType::BECH32); // In P2WSH we can have up to 20 keys Check("sh(wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv)))","sh(wsh(multi(20,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232,02bc2feaa536991d269aae46abb8f3772a5b3ad592314945e51543e7da84c4af6e,0318bf32e5217c1eb771a6d5ce1cd39395dff7ff665704f175c9a5451d95a2f2ca,02c681a6243f16208c2004bb81f5a8a67edfdd3e3711534eadeec3dcf0b010c759,0249fdd6b69768b8d84b4893f8ff84b36835c50183de20fcae8f366a45290d01fd)))", "sh(wsh(multi(20,KzoAz5CanayRKex3fSLQ2BwJpN7U52gZvxMyk78nDMHuqrUxuSJy,KwGNz6YCCQtYvFzMtrC6D3tKTKdBBboMrLTsjr2NYVBwapCkn7Mr,KxogYhiNfwxuswvXV66eFyKcCpm7dZ7TqHVqujHAVUjJxyivxQ9X,L2BUNduTSyZwZjwNHynQTF14mv2uz2NRq5n5sYWTb4FkkmqgEE9f,L1okJGHGn1kFjdXHKxXjwVVtmCMR2JA5QsbKCSpSb7ReQjezKeoD,KxDCNSST75HFPaW5QKpzHtAyaCQC7p9Vo3FYfi2u4dXD1vgMiboK,L5edQjFtnkcf5UWURn6UuuoFrabgDQUHdheKCziwN42aLwS3KizU,KzF8UWFcEC7BYTq8Go1xVimMkDmyNYVmXV5PV7RuDicvAocoPB8i,L3nHUboKG2w4VSJ5jYZ5CBM97oeK6YuKvfZxrefdShECcjEYKMWZ,KyjHo36dWkYhimKmVVmQTq3gERv3pnqA4xFCpvUgbGDJad7eS8WE,KwsfyHKRUTZPQtysN7M3tZ4GXTnuov5XRgjdF2XCG8faAPmFruRF,KzCUbGhN9LJhdeFfL9zQgTJMjqxdBKEekRGZX24hXdgCNCijkkap,KzgpMBwwsDLwkaC5UrmBgCYaBD2WgZ7PBoGYXR8KT7gCA9UTN5a3,KyBXTPy4T7YG4q9tcAM3LkvfRpD1ybHMvcJ2ehaWXaSqeGUxEdkP,KzJDe9iwJRPtKP2F2AoN6zBgzS7uiuAwhWCfGdNeYJ3PC1HNJ8M8,L1xbHrxynrqLKkoYc4qtoQPx6uy5qYXR5ZDYVYBSRmCV5piU3JG9,KzRedjSwMggebB3VufhbzpYJnvHfHe9kPJSjCU5QpJdAW3NSZxYS,Kyjtp5858xL7JfeV4PNRCKy2t6XvgqNNepArGY9F9F1SSPqNEMs3,L2D4RLHPiHBidkHS8ftx11jJk1hGFELvxh8LoxNQheaGT58dKenW,KyLPZdwY4td98bKkXqEXTEBX3vwEYTQo1yyLjX2jKXA63GBpmSjv)))","sh(wsh(multi(20,03669b8afcec803a0d323e9a17f3ea8e68e8abe5a278020a929adbec52421adbd0,0260b2003c386519fc9eadf2b5cf124dd8eea4c4e68d5e154050a9346ea98ce600,0362a74e399c39ed5593852a30147f2959b56bb827dfa3e60e464b02ccf87dc5e8,0261345b53de74a4d721ef877c255429961b7e43714171ac06168d7e08c542a8b8,02da72e8b46901a65d4374fe6315538d8f368557dda3a1dcf9ea903f3afe7314c8,0318c82dd0b53fd3a932d16e0ba9e278fcc937c582d5781be626ff16e201f72286,0297ccef1ef99f9d73dec9ad37476ddb232f1238aff877af19e72ba04493361009,02e502cfd5c3f972fe9a3e2a18827820638f96b6f347e54d63deb839011fd5765d,03e687710f0e3ebe81c1037074da939d409c0025f17eb86adb9427d28f0f7ae0e9,02c04d3a5274952acdbc76987f3184b346a483d43be40874624b29e3692c1df5af,02ed06e0f418b5b43a7ec01d1d7d27290fa15f75771cb69b642a51471c29c84acd,036d46073cbb9ffee90473f3da429abc8de7f8751199da44485682a989a4bebb24,02f5d1ff7c9029a80a4e36b9a5497027ef7f3e73384a4a94fbfe7c4e9164eec8bc,02e41deffd1b7cce11cde209a781adcffdabd1b91c0ba0375857a2bfd9302419f3,02d76625f7956a7fc505ab02556c23ee72d832f1bac391bcd2d3abce5710a13d06,0399eb0a5487515802dc14544cf10b3666623762fbed2ec38a3975716e2c29c232,02bc2feaa536991d269aae46abb8f3772a5b3ad592314945e51543e7da84c4af6e,0318bf32e5217c1eb771a6d5ce1cd39395dff7ff665704f175c9a5451d95a2f2ca,02c681a6243f16208c2004bb81f5a8a67edfdd3e3711534eadeec3dcf0b010c759,0249fdd6b69768b8d84b4893f8ff84b36835c50183de20fcae8f366a45290d01fd)))", SIGNABLE, {{"a914c2c9c510e9d7f92fd6131e94803a8d34a8ef675e87"}}, OutputType::P2SH_SEGWIT); // Even if it's wrapped into P2SH // Check for invalid nesting of structures CheckUnparsable("sh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "sh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "A function is needed within P2SH"); // P2SH needs a script, not a key CheckUnparsable("sh(combo(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "sh(combo(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "Can only have combo() at top level"); // Old must be top level CheckUnparsable("wsh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)", "wsh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)", "A function is needed within P2WSH"); // P2WSH needs a script, not a key CheckUnparsable("wsh(wpkh(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1))", "wsh(wpkh(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd))", "Can only have wpkh() at top level or inside sh()"); // Cannot embed witness inside witness CheckUnparsable("wsh(sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "wsh(sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", "Can only have sh() at top level"); // Cannot embed P2SH inside P2WSH CheckUnparsable("sh(sh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "sh(sh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", "Can only have sh() at top level"); // Cannot embed P2SH inside P2SH CheckUnparsable("wsh(wsh(pk(L4rK1yDtCWekvXuE6oXD9jCYfFNV2cWRpVuPLBcCU2z8TrisoyY1)))", "wsh(wsh(pk(03a34b99f22c790c4e36b2b3c2c35a36db06226e41c692fc82b8b56ac1c540c5bd)))", "Can only have wsh() at top level or inside sh()"); // Cannot embed P2WSH inside P2WSH // Checksums Check("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggrsrxfy", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjg09x5t", "sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggrsrxfy", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjg09x5t", DEFAULT, {{"a91445a9a622a8b0a1269944be477640eedc447bbd8487"}}, OutputType::LEGACY, {{0x8000006FUL,222},{0}}); Check("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))", "sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))", DEFAULT, {{"a91445a9a622a8b0a1269944be477640eedc447bbd8487"}}, OutputType::LEGACY, {{0x8000006FUL,222},{0}}); CheckUnparsable("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#", "Expected 8 character checksum, not 0 characters"); // Empty checksum CheckUnparsable("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggrsrxfyq", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjg09x5tq", "Expected 8 character checksum, not 9 characters"); // Too long checksum CheckUnparsable("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggrsrxf", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjg09x5", "Expected 8 character checksum, not 7 characters"); // Too short checksum CheckUnparsable("sh(multi(3,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggrsrxfy", "sh(multi(3,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjg09x5t", "Provided checksum 'tjg09x5t' does not match computed checksum 'd4x0uxyv'"); // Error in payload CheckUnparsable("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))#ggssrxfy", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))#tjq09x4t", "Provided checksum 'tjq09x4t' does not match computed checksum 'tjg09x5t'"); // Error in checksum CheckUnparsable("sh(multi(2,[00000000/111'/222]xprvA1RpRA33e1JQ7ifknakTFpgNXPmW2YvmhqLQYMmrj4xJXXWYpDPS3xz7iAxn8L39njGVyuoseXzU6rcxFLJ8HFsTjSyQbLYnMpCqE2VbFWc,xprv9uPDJpEQgRQfDcW7BkF7eTya6RPxXeJCqCJGHuCJ4GiRVLzkTXBAJMu2qaMWPrS7AANYqdq6vcBcBUdJCVVFceUvJFjaPdGZ2y9WACViL4L/0))##ggssrxfy", "sh(multi(2,[00000000/111'/222]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL,xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y/0))##tjq09x4t", "Multiple '#' symbols"); // Error in checksum // Addr and raw tests CheckUnparsable("", "addr(asdf)", "Address is not valid"); // Invalid address CheckUnparsable("", "raw(asdf)", "Raw script is not hex"); // Invalid script CheckUnparsable("", "raw(Ü)#00000000", "Invalid characters in payload"); // Invalid chars // A 2of4 but using a direct push rather than OP_2 CScript nonminimalmultisig; CKey keys[4]; nonminimalmultisig << std::vector<unsigned char>{2}; for (int i = 0; i < 4; i++) { keys[i].MakeNewKey(true); nonminimalmultisig << ToByteVector(keys[i].GetPubKey()); } nonminimalmultisig << 4 << OP_CHECKMULTISIG; CheckInferRaw(nonminimalmultisig); // A 2of4 but using a direct push rather than OP_4 nonminimalmultisig.clear(); nonminimalmultisig << 2; for (int i = 0; i < 4; i++) { keys[i].MakeNewKey(true); nonminimalmultisig << ToByteVector(keys[i].GetPubKey()); } nonminimalmultisig << std::vector<unsigned char>{4} << OP_CHECKMULTISIG; CheckInferRaw(nonminimalmultisig); } BOOST_AUTO_TEST_SUITE_END()
mit
VendCoin/VendCoin
src/bitcoin-cli.cpp
8
9662
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparamsbase.h" #include "clientversion.h" #include "rpcclient.h" #include "rpcprotocol.h" #include "util.h" #include "utilstrencodings.h" #include <boost/filesystem/operations.hpp> #define _(x) std::string(x) /* Keep the _() around in case gettext or such will be used later to translate non-UI */ using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; std::string HelpMessageCli() { string strUsage; strUsage += _("Options:") + "\n"; strUsage += " -? " + _("This help message") + "\n"; strUsage += " -conf=<file> " + strprintf(_("Specify configuration file (default: %s)"), "litecoin.conf") + "\n"; strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -testnet " + _("Use the test network") + "\n"; strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " "solved instantly. This is intended for regression testing tools and app development.") + "\n"; strUsage += " -rpcconnect=<ip> " + strprintf(_("Send commands to node running on <ip> (default: %s)"), "127.0.0.1") + "\n"; strUsage += " -rpcport=<port> " + strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), 9332, 19332) + "\n"; strUsage += " -rpcwait " + _("Wait for RPC server to start") + "\n"; strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; strUsage += "\n" + _("SSL options: (see the Litecoin Wiki for SSL setup instructions)") + "\n"; strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; static bool AppInitRPC(int argc, char* argv[]) { // // Parameters // ParseParameters(argc, argv); if (argc<2 || mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) { std::string strUsage = _("Litcoin Core RPC client version") + " " + FormatFullVersion() + "\n"; if (!mapArgs.count("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " litecoin-cli [options] <command> [params] " + _("Send command to Litecoin Core") + "\n" + " litecoin-cli [options] help " + _("List commands") + "\n" + " litecoin-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); return false; } if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str()); return false; } try { ReadConfigFile(mapArgs, mapMultiArgs); } catch(std::exception &e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) if (!SelectBaseParamsFromCommandLine()) { fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n"); return false; } return true; } Object CallRPC(const string& strMethod, const Array& params) { if (mapArgs["-rpcuser"] == "" && mapArgs["-rpcpassword"] == "") throw runtime_error(strprintf( _("You must set rpcpassword=<password> in the configuration file:\n%s\n" "If the file does not exist, create it with owner-readable-only file permissions."), GetConfigFile().string().c_str())); // Connect to localhost bool fUseSSL = GetBoolArg("-rpcssl", false); asio::io_service io_service; ssl::context context(io_service, ssl::context::sslv23); context.set_options(ssl::context::no_sslv2 | ssl::context::no_sslv3); asio::ssl::stream<asio::ip::tcp::socket> sslStream(io_service, context); SSLIOStreamDevice<asio::ip::tcp> d(sslStream, fUseSSL); iostreams::stream< SSLIOStreamDevice<asio::ip::tcp> > stream(d); const bool fConnected = d.connect(GetArg("-rpcconnect", "127.0.0.1"), GetArg("-rpcport", itostr(BaseParams().RPCPort()))); if (!fConnected) throw CConnectionFailed("couldn't connect to server"); // HTTP basic authentication string strUserPass64 = EncodeBase64(mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]); map<string, string> mapRequestHeaders; mapRequestHeaders["Authorization"] = string("Basic ") + strUserPass64; // Send request string strRequest = JSONRPCRequest(strMethod, params, 1); string strPost = HTTPPost(strRequest, mapRequestHeaders); stream << strPost << std::flush; // Receive HTTP reply status int nProto = 0; int nStatus = ReadHTTPStatus(stream, nProto); // Receive HTTP reply message headers and body map<string, string> mapHeaders; string strReply; ReadHTTPMessage(stream, mapHeaders, strReply, nProto, std::numeric_limits<size_t>::max()); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (nStatus >= 400 && nStatus != HTTP_BAD_REQUEST && nStatus != HTTP_NOT_FOUND && nStatus != HTTP_INTERNAL_SERVER_ERROR) throw runtime_error(strprintf("server returned HTTP error %d", nStatus)); else if (strReply.empty()) throw runtime_error("no response from server"); // Parse reply Value valReply; if (!read_string(strReply, valReply)) throw runtime_error("couldn't parse reply from server"); const Object& reply = valReply.get_obj(); if (reply.empty()) throw runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } // Method if (argc < 2) throw runtime_error("too few parameters"); string strMethod = argv[1]; // Parameters default to strings std::vector<std::string> strParams(&argv[2], &argv[argc]); Array params = RPCConvertValues(strMethod, strParams); // Execute and handle connection failures with -rpcwait const bool fWait = GetBoolArg("-rpcwait", false); do { try { const Object reply = CallRPC(strMethod, params); // Parse reply const Value& result = find_value(reply, "result"); const Value& error = find_value(reply, "error"); if (error.type() != null_type) { // Error const int code = find_value(error.get_obj(), "code").get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + write_string(error, false); nRet = abs(code); } else { // Result if (result.type() == null_type) strPrint = ""; else if (result.type() == str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed& e) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (boost::thread_interrupted) { throw; } catch (std::exception& e) { strPrint = string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); try { if(!AppInitRPC(argc, argv)) return EXIT_FAILURE; } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(NULL, "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(NULL, "CommandLineRPC()"); } return ret; }
mit
manGoweb/BLEDataTransfer
firmware/examples/FW/1.0/libraries/ArduinoJson/test/JsonVariant_Undefined_Tests.cpp
8
1484
// Copyright Benoit Blanchon 2014-2016 // MIT License // // Arduino JSON library // https://github.com/bblanchon/ArduinoJson // If you like this project, please add a star! #include <gtest/gtest.h> #include <ArduinoJson.h> class JsonVariant_Undefined_Tests : public ::testing::Test { protected: JsonVariant variant; }; TEST_F(JsonVariant_Undefined_Tests, AsLongReturns0) { EXPECT_EQ(0, variant.as<long>()); } TEST_F(JsonVariant_Undefined_Tests, AsStringReturnsNull) { EXPECT_EQ(0, variant.asString()); } TEST_F(JsonVariant_Undefined_Tests, AsDoubleReturns0) { EXPECT_EQ(0, variant.as<double>()); } TEST_F(JsonVariant_Undefined_Tests, AsBoolReturnsFalse) { EXPECT_FALSE(variant.as<bool>()); } TEST_F(JsonVariant_Undefined_Tests, AsArrayReturnInvalid) { EXPECT_EQ(JsonArray::invalid(), variant.as<JsonArray&>()); } TEST_F(JsonVariant_Undefined_Tests, AsConstArrayReturnInvalid) { EXPECT_EQ(JsonArray::invalid(), variant.as<const JsonArray&>()); } TEST_F(JsonVariant_Undefined_Tests, AsObjectReturnInvalid) { EXPECT_EQ(JsonObject::invalid(), variant.as<JsonObject&>()); } TEST_F(JsonVariant_Undefined_Tests, AsConstObjectReturnInvalid) { EXPECT_EQ(JsonObject::invalid(), variant.as<const JsonObject&>()); } TEST_F(JsonVariant_Undefined_Tests, AsArrayWrapperReturnInvalid) { EXPECT_EQ(JsonArray::invalid(), variant.asArray()); } TEST_F(JsonVariant_Undefined_Tests, AsObjectWrapperReturnInvalid) { EXPECT_EQ(JsonObject::invalid(), variant.asObject()); }
mit
ageazrael/godot
editor/editor_log.cpp
10
6184
/*************************************************************************/ /* editor_log.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2017 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "editor_log.h" #include "editor_node.h" #include "scene/gui/center_container.h" #include "scene/resources/dynamic_font.h" #include "version.h" void EditorLog::_error_handler(void *p_self, const char *p_func, const char *p_file, int p_line, const char *p_error, const char *p_errorexp, ErrorHandlerType p_type) { EditorLog *self = (EditorLog *)p_self; if (self->current != Thread::get_caller_id()) return; String err_str; if (p_errorexp && p_errorexp[0]) { err_str = p_errorexp; } else { err_str = String(p_file) + ":" + itos(p_line) + " - " + String(p_error); } /* if (!self->is_visible_in_tree()) self->emit_signal("show_request"); */ self->add_message(err_str, true); } void EditorLog::_notification(int p_what) { if (p_what == NOTIFICATION_ENTER_TREE) { //button->set_icon(get_icon("Console","EditorIcons")); log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); } else if (p_what == NOTIFICATION_THEME_CHANGED) { Ref<DynamicFont> df_output_code = get_font("output_source", "EditorFonts"); if (df_output_code.is_valid()) { df_output_code->set_size(int(EDITOR_DEF("run/output/font_size", 13)) * EDSCALE); log->add_font_override("normal_font", get_font("output_source", "EditorFonts")); } } /*if (p_what==NOTIFICATION_DRAW) { RID ci = get_canvas_item(); get_stylebox("panel","PopupMenu")->draw(ci,Rect2(Point2(),get_size())); int top_ofs = 20; int border_ofs=4; Ref<StyleBox> style = get_stylebox("normal","TextEdit"); style->draw(ci,Rect2( Point2(border_ofs,top_ofs),get_size()-Size2(border_ofs*2,top_ofs+border_ofs))); }*/ } void EditorLog::_clear_request() { log->clear(); } void EditorLog::clear() { _clear_request(); } void EditorLog::add_message(const String &p_msg, bool p_error) { log->add_newline(); if (p_error) { log->push_color(get_color("error_color", "Editor")); Ref<Texture> icon = get_icon("Error", "EditorIcons"); log->add_image(icon); log->add_text(" "); //button->set_icon(icon); } else { //button->set_icon(Ref<Texture>()); } log->add_text(p_msg); //button->set_text(p_msg); if (p_error) log->pop(); } /* void EditorLog::_dragged(const Point2& p_ofs) { int ofs = ec->get_minsize().height; ofs = ofs-p_ofs.y; if (ofs<50) ofs=50; if (ofs>300) ofs=300; ec->set_minsize(Size2(ec->get_minsize().width,ofs)); minimum_size_changed(); } */ void EditorLog::_undo_redo_cbk(void *p_self, const String &p_name) { EditorLog *self = (EditorLog *)p_self; self->add_message(p_name); } void EditorLog::_bind_methods() { ClassDB::bind_method(D_METHOD("_clear_request"), &EditorLog::_clear_request); //ClassDB::bind_method(D_METHOD("_dragged"),&EditorLog::_dragged ); ADD_SIGNAL(MethodInfo("clear_request")); } EditorLog::EditorLog() { VBoxContainer *vb = this; add_constant_override("separation", get_constant("separation", "VBoxContainer")); HBoxContainer *hb = memnew(HBoxContainer); vb->add_child(hb); title = memnew(Label); title->set_text(TTR("Output:")); title->set_h_size_flags(SIZE_EXPAND_FILL); hb->add_child(title); clearbutton = memnew(Button); hb->add_child(clearbutton); clearbutton->set_text(TTR("Clear")); clearbutton->connect("pressed", this, "_clear_request"); log = memnew(RichTextLabel); log->set_scroll_follow(true); log->set_selection_enabled(true); log->set_focus_mode(FOCUS_CLICK); log->set_custom_minimum_size(Size2(0, 180) * EDSCALE); log->set_v_size_flags(SIZE_EXPAND_FILL); log->set_h_size_flags(SIZE_EXPAND_FILL); vb->add_child(log); add_message(VERSION_FULL_NAME " (c) 2008-2017 Juan Linietsky, Ariel Manzur."); //log->add_text("Initialization Complete.\n"); //because it looks cool. eh.errfunc = _error_handler; eh.userdata = this; add_error_handler(&eh); current = Thread::get_caller_id(); EditorNode::get_undo_redo()->set_commit_notify_callback(_undo_redo_cbk, this); } void EditorLog::deinit() { remove_error_handler(&eh); } EditorLog::~EditorLog() { }
mit
truthcoin/blocksize-market
src/primitives/transaction.cpp
10
7619
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "primitives/transaction.h" #include "hash.h" #include "tinyformat.h" #include "utilstrencodings.h" CTxOutValue::CTxOutValue() { vchCommitment.resize(nCommitmentSize); memset(&vchCommitment[0], 0xff, nCommitmentSize); } CTxOutValue::CTxOutValue(CAmount nAmountIn) { vchCommitment.resize(nCommitmentSize); SetToAmount(nAmountIn); } CTxOutValue::CTxOutValue(const std::vector<unsigned char>& vchValueCommitmentIn, const std::vector<unsigned char>& vchRangeproofIn) : vchCommitment(vchValueCommitmentIn), vchRangeproof(vchRangeproofIn) { assert(vchCommitment.size() == nCommitmentSize); assert(vchCommitment[0] == 2 || vchCommitment[0] == 3); } bool CTxOutValue::IsValid() const { switch (vchCommitment[0]) { case 0: { // Ensure all but the last sizeof(CAmount) bytes are zero for (size_t i = vchCommitment.size() - sizeof(CAmount); --i > 0; ) if (vchCommitment[i]) return false; return true; } case 2: case 3: // FIXME: Additional checks? return true; default: return false; } } bool CTxOutValue::IsNull() const { return vchCommitment[0] == 0xff; } bool CTxOutValue::IsAmount() const { return !vchCommitment[0]; } void CTxOutValue::SetToAmount(CAmount nAmount) { assert(vchCommitment.size() > sizeof(nAmount) + 1); memset(&vchCommitment[0], 0, vchCommitment.size() - sizeof(nAmount)); for (size_t i = 0; i < sizeof(nAmount); ++i) vchCommitment[vchCommitment.size() - (i + 1)] = ((nAmount >> (i * 8)) & 0xff); } CAmount CTxOutValue::GetAmount() const { assert(IsAmount()); CAmount nAmount = 0; for (size_t i = 0; i < sizeof(nAmount); ++i) nAmount |= CAmount(vchCommitment[vchCommitment.size() - (i + 1)]) << (i * 8); return nAmount; } bool operator==(const CTxOutValue& a, const CTxOutValue& b) { return a.vchRangeproof == b.vchRangeproof && a.vchCommitment == b.vchCommitment && a.vchNonceCommitment == b.vchNonceCommitment; } bool operator!=(const CTxOutValue& a, const CTxOutValue& b) { return !(a == b); } std::string COutPoint::ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10), n); } CTxIn::CTxIn(COutPoint prevoutIn, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn::CTxIn(uint256 hashPrevTx, uint32_t nOut, CScript scriptSigIn, uint32_t nSequenceIn) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } std::string CTxIn::ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig)); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24)); if (~nSequence) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } CTxOut::CTxOut(const CTxOutValue& valueIn, CScript scriptPubKeyIn) { nValue = valueIn; scriptPubKey = scriptPubKeyIn; } std::string CTxOut::ToString() const { return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", (nValue.IsAmount() ? strprintf("%d.%08d", nValue.GetAmount() / COIN, nValue.GetAmount() % COIN) : std::string("UNKNOWN")), scriptPubKey.ToString().substr(0,30)); } CMutableTransaction::CMutableTransaction() : nVersion(CTransaction::CURRENT_VERSION), nTxFee(0), nLockTime(0) {} CMutableTransaction::CMutableTransaction(const CTransaction& tx) : nVersion(tx.nVersion), vin(tx.vin), nTxFee(tx.nTxFee), vout(tx.vout), nLockTime(tx.nLockTime) {} uint256 CMutableTransaction::GetHash() const { if (IsCoinBase()) { return SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION); } else { return SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION | SERIALIZE_VERSION_MASK_NO_WITNESS); } } void CTransaction::UpdateHash() const { bool maybeBitcoinTx = true; for (unsigned int i = 0; i < vout.size(); i++) if (!vout[i].nValue.IsAmount()) maybeBitcoinTx = false; if (maybeBitcoinTx) *const_cast<uint256*>(&hashBitcoin) = SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION | SERIALIZE_VERSION_MASK_BITCOIN_TX); if (IsCoinBase()) { *const_cast<uint256*>(&hash) = SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION); } else { *const_cast<uint256*>(&hash) = SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION | SERIALIZE_VERSION_MASK_NO_WITNESS); } *const_cast<uint256*>(&hashWitness) = SerializeHash(*this, SER_GETHASH, PROTOCOL_VERSION | SERIALIZE_VERSION_MASK_ONLY_WITNESS); // Update full hash combining the normalized txid with the hash of the witness CHash256 hasher; hasher.Write((unsigned char*)&hash, hash.size()); hasher.Write((unsigned char*)&hashWitness, hashWitness.size()); hasher.Finalize((unsigned char*)&hashFull); } CTransaction::CTransaction() : hash(0), hashFull(0), nVersion(CTransaction::CURRENT_VERSION), vin(), nTxFee(0), vout(), nLockTime(0) { } CTransaction::CTransaction(const CMutableTransaction &tx) : nVersion(tx.nVersion), vin(tx.vin), nTxFee(tx.nTxFee), vout(tx.vout), nLockTime(tx.nLockTime) { UpdateHash(); } CTransaction& CTransaction::operator=(const CTransaction &tx) { *const_cast<int*>(&nVersion) = tx.nVersion; *const_cast<CAmount*>(&nTxFee) = tx.nTxFee; *const_cast<std::vector<CTxIn>*>(&vin) = tx.vin; *const_cast<std::vector<CTxOut>*>(&vout) = tx.vout; *const_cast<unsigned int*>(&nLockTime) = tx.nLockTime; *const_cast<uint256*>(&hash) = tx.hash; *const_cast<uint256*>(&hashFull) = tx.hashFull; return *this; } double CTransaction::ComputePriority(double dPriorityInputs, unsigned int nTxSize) const { nTxSize = CalculateModifiedSize(nTxSize); if (nTxSize == 0) return 0.0; return dPriorityInputs / nTxSize; } unsigned int CTransaction::CalculateModifiedSize(unsigned int nTxSize) const { // In order to avoid disincentivizing cleaning up the UTXO set we don't count // the constant overhead for each txin and up to 110 bytes of scriptSig (which // is enough to cover a compressed pubkey p2sh redemption) for priority. // Providing any more cleanup incentive than making additional inputs free would // risk encouraging people to create junk outputs to redeem later. if (nTxSize == 0) nTxSize = ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION); for (std::vector<CTxIn>::const_iterator it(vin.begin()); it != vin.end(); ++it) { unsigned int offset = 41U + std::min(110U, (unsigned int)it->scriptSig.size()); if (nTxSize > offset) nTxSize -= offset; } return nTxSize; } std::string CTransaction::ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%u, vout.size=%u, nLockTime=%u, fee=%u)\n", GetHash().ToString().substr(0,10), nVersion, vin.size(), vout.size(), nLockTime, nTxFee); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; }
mit
skiselev/upm
src/relay/relay_fti.c
11
2937
/* * Author: Sisinty Sasmita Patra <sisinty.s.patra@intel.com> * * Copyright (c) 2016 Intel Corporation. * * 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 "relay.h" #include "upm_fti.h" /** * This file implements the Function Table Interface (FTI) for this sensor */ const char upm_relay_name[] = "Grove Relay"; const char upm_relay_description[] = "Grove relay Sensor"; const upm_protocol_t upm_relay_protocol[] = {UPM_GPIO}; const upm_sensor_t upm_relay_category[] = {UPM_SWITCH}; // forward declarations const upm_sensor_descriptor_t upm_relay_get_descriptor(); const void* upm_relay_get_ft(upm_sensor_t sensor_type); void* upm_relay_init_name(); void upm_relay_close(void* dev); upm_result_t upm_relay_get_value(void* dev, bool* value, int num); const upm_sensor_descriptor_t upm_relay_get_descriptor() { upm_sensor_descriptor_t usd; usd.name = upm_relay_name; usd.description = upm_relay_description; usd.protocol_size = 1; usd.protocol = upm_relay_protocol; usd.category_size = 1; usd.category = upm_relay_category; return usd; } static const upm_sensor_ft ft = { .upm_sensor_init_name = &upm_relay_init_name, .upm_sensor_close = &upm_relay_close, .upm_sensor_get_descriptor = &upm_relay_get_descriptor }; static const upm_switch_ft sft = { .upm_switch_get_value = &upm_relay_get_value }; const void* upm_relay_get_ft(upm_sensor_t sensor_type) { if(sensor_type == UPM_SENSOR) { return &ft; } if(sensor_type == UPM_SWITCH) { return &sft; } return NULL; } void* upm_relay_init_name(){ return NULL; } void upm_relay_close(void* dev) { relay_close((relay_context)dev); } upm_result_t upm_relay_get_value(void* dev, bool* value, int num) { // num is unused if (relay_is_on((relay_context)dev)) *value = true; else *value = false; return UPM_SUCCESS; }
mit
petetnt/brackets-shell
appshell/cefclient_gtk.cpp
12
7911
// Copyright (c) 2011 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. #include "cefclient.h" #include <gtk/gtk.h> #include <stdlib.h> #include <unistd.h> #include <string> #include <sys/stat.h> #include "cefclient.h" #include "include/cef_app.h" #include "include/cef_version.h" #include "include/cef_browser.h" #include "include/cef_frame.h" #include "include/cef_runnable.h" #include "client_handler.h" #include "client_switches.h" #include "appshell_node_process.h" static std::string APPICONS[] = {"appshell32.png","appshell48.png","appshell128.png","appshell256.png"}; char szWorkingDir[512]; // The current working directory std::string szInitialUrl; std::string szRunningDir; int add_handler_id; bool isReallyClosing = false; // The global ClientHandler reference. extern CefRefPtr<ClientHandler> g_handler; // Application startup time time_t g_appStartupTime; void destroy(void) { CefQuitMessageLoop(); } void TerminationSignalHandler(int signatl) { destroy(); } void HandleAdd(GtkContainer *container, GtkWidget *widget, gpointer user_data) { g_signal_handler_disconnect(container, add_handler_id); if(gtk_widget_get_can_focus(widget)) { gtk_widget_grab_focus(widget); } else { add_handler_id = g_signal_connect(G_OBJECT(widget), "add", G_CALLBACK(HandleAdd), NULL); } } static gboolean HandleQuit(int signatl) { if (!isReallyClosing && g_handler.get() && g_handler->GetBrowserId()) { CefRefPtr<CommandCallback> callback = new CloseWindowCommandCallback(g_handler->GetBrowser()); g_handler->SendJSCommand(g_handler->GetBrowser(), FILE_CLOSE_WINDOW, callback); return TRUE; } destroy(); } bool FileExists(std::string path) { struct stat buf; return (stat(path.c_str(), &buf) >= 0) && (S_ISREG(buf.st_mode)); } int GetInitialUrl() { GtkWidget *dialog; const char* dialog_title = "Please select the index.html file"; GtkFileChooserAction file_or_directory = GTK_FILE_CHOOSER_ACTION_OPEN ; dialog = gtk_file_chooser_dialog_new (dialog_title, NULL, file_or_directory, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT) { szInitialUrl = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)); gtk_widget_destroy (dialog); return 0; } return -1; } // Global functions std::string AppGetWorkingDirectory() { return szWorkingDir; } std::string AppGetRunningDirectory() { if(szRunningDir.length() > 0) return szRunningDir; char buf[512]; int len = readlink("/proc/self/exe", buf, 512); if(len < 0) return AppGetWorkingDirectory(); //# Well, can't think of any real-world case where this would be happen for(; len >= 0; len--){ if(buf[len] == '/'){ buf[len] = '\0'; szRunningDir.append(buf); return szRunningDir; } } } CefString AppGetCachePath() { std::string cachePath = std::string(ClientApp::AppGetSupportDirectory()) + "/cef_data"; return CefString(cachePath); } GtkWidget* AddMenuEntry(GtkWidget* menu_widget, const char* text, GCallback callback) { GtkWidget* entry = gtk_menu_item_new_with_label(text); g_signal_connect(entry, "activate", callback, NULL); gtk_menu_shell_append(GTK_MENU_SHELL(menu_widget), entry); return entry; } GtkWidget* CreateMenu(GtkWidget* menu_bar, const char* text) { GtkWidget* menu_widget = gtk_menu_new(); GtkWidget* menu_header = gtk_menu_item_new_with_label(text); gtk_menu_item_set_submenu(GTK_MENU_ITEM(menu_header), menu_widget); gtk_menu_shell_append(GTK_MENU_SHELL(menu_bar), menu_header); return menu_widget; } // Callback for Debug > Get Source... menu item. gboolean GetSourceActivated(GtkWidget* widget) { return FALSE; } int main(int argc, char* argv[]) { CefMainArgs main_args(argc, argv); g_appStartupTime = time(NULL); gtk_init(&argc, &argv); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) return exit_code; //Retrieve the current working directory if (!getcwd(szWorkingDir, sizeof (szWorkingDir))) return -1; GtkWidget* window; // Parse command line arguments. AppInitCommandLine(argc, argv); CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); settings.no_sandbox = TRUE; // Check cache_path setting if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } CefRefPtr<CefCommandLine> cmdLine = AppGetCommandLine(); if (cmdLine->HasSwitch(cefclient::kStartupPath)) { szInitialUrl = cmdLine->GetSwitchValue(cefclient::kStartupPath); } else { szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/dev/src/index.html"); if (!FileExists(szInitialUrl)) { szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/www/index.html"); if (!FileExists(szInitialUrl)) { if (GetInitialUrl() < 0) return 0; } } } // Initialize CEF. CefInitialize(main_args, settings, app.get(), NULL); // Set window icon std::vector<std::string> icons(APPICONS, APPICONS + sizeof(APPICONS) / sizeof(APPICONS[0]) ); GList *list = NULL; for (int i = 0; i < icons.size(); ++i) { std::string path = icons[i]; GdkPixbuf *icon = gdk_pixbuf_new_from_file(path.c_str(), NULL); if (!icon) continue; list = g_list_append(list, icon); } window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_window_set_icon_list(GTK_WINDOW(window), list); // Free icon list g_list_foreach(list, (GFunc) g_object_unref, NULL); g_list_free(list); GtkWidget* vbox = gtk_vbox_new(FALSE, 0); GtkWidget* menuBar = gtk_menu_bar_new(); // GtkWidget* debug_menu = CreateMenu(menuBar, "Tests"); // AddMenuEntry(debug_menu, "Hello World Menu", // G_CALLBACK(GetSourceActivated)); gtk_box_pack_start(GTK_BOX(vbox), menuBar, FALSE, FALSE, 0); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(HandleQuit), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_widget_destroyed), &window); add_handler_id = g_signal_connect(G_OBJECT(window), "add", G_CALLBACK(HandleAdd), NULL); // g_signal_connect(G_OBJECT(window), "destroy", // G_CALLBACK(destroy), NULL); // Create the handler. g_handler = new ClientHandler(); g_handler->SetMainHwnd(vbox); // Create the browser view. CefWindowInfo window_info; CefBrowserSettings browserSettings; browserSettings.web_security = STATE_DISABLED; window_info.SetAsChild(vbox); CefBrowserHost::CreateBrowser( window_info, static_cast<CefRefPtr<CefClient> >(g_handler), "file://"+szInitialUrl, browserSettings, NULL); gtk_container_add(GTK_CONTAINER(window), vbox); gtk_widget_show_all(GTK_WIDGET(window)); // Install an signal handler so we clean up after ourselves. signal(SIGINT, TerminationSignalHandler); signal(SIGTERM, TerminationSignalHandler); // Start the node server process startNodeProcess(); CefRunMessageLoop(); CefShutdown(); return 0; } CefString AppGetProductVersionString() { // TODO return CefString(""); } CefString AppGetChromiumVersionString() { // TODO return CefString(""); }
mit
Djuffin/coreclr
src/pal/tests/palsuite/miscellaneous/InterlockedBit/test1/test.cpp
13
2006
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================ ** ** Source : test.c ** ** Purpose: Test for InterlockedBitTestAndReset() function ** ** **=========================================================*/ #include <palsuite.h> typedef struct tag_TEST_DATA { LONG baseValue; UINT bitPosition; LONG expectedValue; UCHAR expectedReturnValue; } TEST_DATA; TEST_DATA test_data[] = { { (LONG)0x00000000, 3, (LONG)0x00000000, 0 }, { (LONG)0x12341234, 2, (LONG)0x12341230, 1 }, { (LONG)0x12341234, 3, (LONG)0x12341234, 0 }, { (LONG)0x12341234, 31, (LONG)0x12341234, 0 }, { (LONG)0x12341234, 28, (LONG)0x02341234, 1 }, { (LONG)0xffffffff, 28, (LONG)0xefffffff, 1 } }; int __cdecl main(int argc, char *argv[]) { /* * Initialize the PAL and return FAILURE if this fails */ if(0 != (PAL_Initialize(argc, argv))) { return FAIL; } for (int i = 0; i < sizeof (test_data) / sizeof (TEST_DATA); i++) { LONG baseVal = test_data[i].baseValue; LONG bitPosition = test_data[i].bitPosition; UCHAR ret = InterlockedBitTestAndReset( &baseVal, /* Variable to manipulate */ bitPosition); if (ret != test_data[i].expectedReturnValue) { Fail("ERROR: InterlockedBitTestAndReset(%d): Expected return value is %d," "Actual return value is %d.", i, test_data[i].expectedReturnValue, ret); } if (baseVal != test_data[i].expectedValue) { Fail("ERROR: InterlockedBitTestAndReset(%d): Expected value is %x," "Actual value is %x.", i, test_data[i].expectedValue, baseVal); } } PAL_Terminate(); return PASS; }
mit
balaam/dinodeck
src/android/jni/ftgles/src/FTGL/ftglesGlue.cpp
13
7509
/* Copyright (c) 2010 David Petrie 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 "ftglesGlue.h" #define FTGLES_GLUE_MAX_VERTICES 32768 typedef struct { float xyz[3]; float st[2]; GLubyte rgba[4]; } ftglesVertex_t; typedef struct { ftglesVertex_t vertices[FTGLES_GLUE_MAX_VERTICES]; short quadIndices[FTGLES_GLUE_MAX_VERTICES * 3 / 2]; ftglesVertex_t currVertex; unsigned int currIndex; } ftglesGlueArrays_t; ftglesGlueArrays_t ftglesGlueArrays; GLenum ftglesCurrentPrimitive = GL_TRIANGLES; bool ftglesQuadIndicesInitted = false; GLvoid ftglBegin(GLenum prim) { if (!ftglesQuadIndicesInitted) { for (int i = 0; i < FTGLES_GLUE_MAX_VERTICES * 3 / 2; i += 6) { int q = i / 6 * 4; ftglesGlueArrays.quadIndices[i + 0] = q + 0; ftglesGlueArrays.quadIndices[i + 1] = q + 1; ftglesGlueArrays.quadIndices[i + 2] = q + 2; ftglesGlueArrays.quadIndices[i + 3] = q + 0; ftglesGlueArrays.quadIndices[i + 4] = q + 2; ftglesGlueArrays.quadIndices[i + 5] = q + 3; } ftglesQuadIndicesInitted = true; } ftglesGlueArrays.currIndex = 0; ftglesCurrentPrimitive = prim; } GLvoid ftglVertex3f(float x, float y, float z) { if (ftglesGlueArrays.currIndex >= FTGLES_GLUE_MAX_VERTICES) { return; } ftglesGlueArrays.currVertex.xyz[0] = x; ftglesGlueArrays.currVertex.xyz[1] = y; ftglesGlueArrays.currVertex.xyz[2] = z; ftglesGlueArrays.vertices[ftglesGlueArrays.currIndex] = ftglesGlueArrays.currVertex; ftglesGlueArrays.currIndex++; } GLvoid ftglVertex2f(float x, float y) { if (ftglesGlueArrays.currIndex >= FTGLES_GLUE_MAX_VERTICES) { return; } ftglesGlueArrays.currVertex.xyz[0] = x; ftglesGlueArrays.currVertex.xyz[1] = y; ftglesGlueArrays.currVertex.xyz[2] = 0.0f; ftglesGlueArrays.vertices[ftglesGlueArrays.currIndex] = ftglesGlueArrays.currVertex; ftglesGlueArrays.currIndex++; } GLvoid ftglColor4ub(GLubyte r, GLubyte g, GLubyte b, GLubyte a) { ftglesGlueArrays.currVertex.rgba[0] = r; ftglesGlueArrays.currVertex.rgba[1] = g; ftglesGlueArrays.currVertex.rgba[2] = b; ftglesGlueArrays.currVertex.rgba[3] = a; } GLvoid ftglColor4f(GLfloat r, GLfloat g, GLfloat b, GLfloat a) { ftglesGlueArrays.currVertex.rgba[0] = (GLubyte) (r * 255); ftglesGlueArrays.currVertex.rgba[1] = (GLubyte) (g * 255); ftglesGlueArrays.currVertex.rgba[2] = (GLubyte) (b * 255); ftglesGlueArrays.currVertex.rgba[3] = (GLubyte) (a * 255); } GLvoid ftglTexCoord2f(GLfloat s, GLfloat t) { ftglesGlueArrays.currVertex.st[0] = s; ftglesGlueArrays.currVertex.st[1] = t; } GLvoid bindArrayBuffers() { } GLvoid ftglBindTexture() { } GLvoid ftglEnd() { GLboolean vertexArrayEnabled; GLboolean texCoordArrayEnabled; GLboolean colorArrayEnabled; GLvoid * vertexArrayPointer; GLvoid * texCoordArrayPointer; GLvoid * colorArrayPointer; GLint vertexArrayType, texCoordArrayType, colorArrayType; GLint vertexArraySize, texCoordArraySize, colorArraySize; GLsizei vertexArrayStride, texCoordArrayStride, colorArrayStride; bool resetPointers = false; glGetPointerv(GL_VERTEX_ARRAY_POINTER, &vertexArrayPointer); glGetPointerv(GL_TEXTURE_COORD_ARRAY_POINTER, &texCoordArrayPointer); glGetPointerv(GL_COLOR_ARRAY_POINTER, &colorArrayPointer); glGetBooleanv(GL_VERTEX_ARRAY, &vertexArrayEnabled); glGetBooleanv(GL_TEXTURE_COORD_ARRAY, &texCoordArrayEnabled); glGetBooleanv(GL_COLOR_ARRAY, &colorArrayEnabled); if (!vertexArrayEnabled) { glEnableClientState(GL_VERTEX_ARRAY); } if (vertexArrayPointer != &ftglesGlueArrays.vertices[0].xyz) { glGetIntegerv(GL_VERTEX_ARRAY_TYPE, &vertexArrayType); glGetIntegerv(GL_VERTEX_ARRAY_SIZE, &vertexArraySize); glGetIntegerv(GL_VERTEX_ARRAY_STRIDE, &vertexArrayStride); if (texCoordArrayEnabled) { glGetIntegerv(GL_TEXTURE_COORD_ARRAY_TYPE, &texCoordArrayType); glGetIntegerv(GL_TEXTURE_COORD_ARRAY_SIZE, &texCoordArraySize); glGetIntegerv(GL_TEXTURE_COORD_ARRAY_STRIDE, &texCoordArrayStride); } if (colorArrayEnabled) { glGetIntegerv(GL_COLOR_ARRAY_TYPE, &colorArrayType); glGetIntegerv(GL_COLOR_ARRAY_SIZE, &colorArraySize); glGetIntegerv(GL_COLOR_ARRAY_STRIDE, &colorArrayStride); } glVertexPointer(3, GL_FLOAT, sizeof(ftglesVertex_t), ftglesGlueArrays.vertices[0].xyz); glTexCoordPointer(2, GL_FLOAT, sizeof(ftglesVertex_t), ftglesGlueArrays.vertices[0].st); glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(ftglesVertex_t), ftglesGlueArrays.vertices[0].rgba); resetPointers = true; } if (!texCoordArrayEnabled) glEnableClientState(GL_TEXTURE_COORD_ARRAY); if (!colorArrayEnabled) glEnableClientState(GL_COLOR_ARRAY); if (ftglesGlueArrays.currIndex == 0) { ftglesCurrentPrimitive = 0; return; } if (ftglesCurrentPrimitive == GL_QUADS) { glDrawElements(GL_TRIANGLES, ftglesGlueArrays.currIndex / 4 * 6, GL_UNSIGNED_SHORT, ftglesGlueArrays.quadIndices); } else { glDrawArrays(ftglesCurrentPrimitive, 0, ftglesGlueArrays.currIndex); } ftglesGlueArrays.currIndex = 0; ftglesCurrentPrimitive = 0; if (resetPointers) { if (vertexArrayEnabled) { glVertexPointer(vertexArraySize, vertexArrayType, vertexArrayStride, vertexArrayPointer); } if (texCoordArrayEnabled) { glTexCoordPointer(texCoordArraySize, texCoordArrayType, texCoordArrayStride, texCoordArrayPointer); } if (colorArrayEnabled) { glColorPointer(colorArraySize, colorArrayType, colorArrayStride, colorArrayPointer); } } if (!vertexArrayEnabled) glDisableClientState(GL_VERTEX_ARRAY); if (!texCoordArrayEnabled) glDisableClientState(GL_TEXTURE_COORD_ARRAY); if (!colorArrayEnabled) glDisableClientState(GL_COLOR_ARRAY); } GLvoid ftglError(const char *source) { GLenum error = glGetError(); switch (error) { case GL_NO_ERROR: break; case GL_INVALID_ENUM: printf("GL Error (%x): GL_INVALID_ENUM. %s\n\n", error, source); break; case GL_INVALID_VALUE: printf("GL Error (%x): GL_INVALID_VALUE. %s\n\n", error, source); break; case GL_INVALID_OPERATION: printf("GL Error (%x): GL_INVALID_OPERATION. %s\n\n", error, source); break; case GL_STACK_OVERFLOW: printf("GL Error (%x): GL_STACK_OVERFLOW. %s\n\n", error, source); break; case GL_STACK_UNDERFLOW: printf("GL Error (%x): GL_STACK_UNDERFLOW. %s\n\n", error, source); break; case GL_OUT_OF_MEMORY: printf("GL Error (%x): GL_OUT_OF_MEMORY. %s\n\n", error, source); break; default: printf("GL Error (%x): %s\n\n", error, source); break; } }
mit
Maseratigsg/kohencoin
src/pow.cpp
18
3269
// Copyright (c) 2009-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 "pow.h" #include "arith_uint256.h" #include "chain.h" #include "primitives/block.h" #include "uint256.h" unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { assert(pindexLast != NULL); unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact(); // Only change once per difficulty adjustment interval if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return nProofOfWorkLimit; else { // Return the last non-special-min-difficulty-rules-block const CBlockIndex* pindex = pindexLast; while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit) pindex = pindex->pprev; return pindex->nBits; } } return pindexLast->nBits; } // Go back by what we want to be 14 days worth of blocks int nHeightFirst = pindexLast->nHeight - (params.DifficultyAdjustmentInterval()-1); assert(nHeightFirst >= 0); const CBlockIndex* pindexFirst = pindexLast->GetAncestor(nHeightFirst); assert(pindexFirst); return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params); } unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params) { if (params.fPowNoRetargeting) return pindexLast->nBits; // Limit adjustment step int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime; if (nActualTimespan < params.nPowTargetTimespan/4) nActualTimespan = params.nPowTargetTimespan/4; if (nActualTimespan > params.nPowTargetTimespan*4) nActualTimespan = params.nPowTargetTimespan*4; // Retarget const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); arith_uint256 bnNew; bnNew.SetCompact(pindexLast->nBits); bnNew *= nActualTimespan; bnNew /= params.nPowTargetTimespan; if (bnNew > bnPowLimit) bnNew = bnPowLimit; return bnNew.GetCompact(); } bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) { bool fNegative; bool fOverflow; arith_uint256 bnTarget; bnTarget.SetCompact(nBits, &fNegative, &fOverflow); // Check range if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) return false; // Check proof of work matches claimed amount if (UintToArith256(hash) > bnTarget) return false; return true; }
mit
weinzierl-engineering/baos
thirdparty/poco/Foundation/src/EventLogChannel.cpp
20
7735
// // EventLogChannel.cpp // // $Id: //poco/1.4/Foundation/src/EventLogChannel.cpp#4 $ // // Library: Foundation // Package: Logging // Module: EventLogChannel // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "Poco/EventLogChannel.h" #include "Poco/Message.h" #include "Poco/String.h" #include "pocomsg.h" #if defined(POCO_WIN32_UTF8) #include "Poco/UnicodeConverter.h" #endif namespace Poco { const std::string EventLogChannel::PROP_NAME = "name"; const std::string EventLogChannel::PROP_HOST = "host"; const std::string EventLogChannel::PROP_LOGHOST = "loghost"; const std::string EventLogChannel::PROP_LOGFILE = "logfile"; EventLogChannel::EventLogChannel(): _logFile("Application"), _h(0) { const DWORD maxPathLen = MAX_PATH + 1; #if defined(POCO_WIN32_UTF8) wchar_t name[maxPathLen]; int n = GetModuleFileNameW(NULL, name, maxPathLen); if (n > 0) { wchar_t* end = name + n - 1; while (end > name && *end != '\\') --end; if (*end == '\\') ++end; std::wstring uname(end); UnicodeConverter::toUTF8(uname, _name); } #else char name[maxPathLen]; int n = GetModuleFileNameA(NULL, name, maxPathLen); if (n > 0) { char* end = name + n - 1; while (end > name && *end != '\\') --end; if (*end == '\\') ++end; _name = end; } #endif } EventLogChannel::EventLogChannel(const std::string& name): _name(name), _logFile("Application"), _h(0) { } EventLogChannel::EventLogChannel(const std::string& name, const std::string& host): _name(name), _host(host), _logFile("Application"), _h(0) { } EventLogChannel::~EventLogChannel() { try { close(); } catch (...) { poco_unexpected(); } } void EventLogChannel::open() { setUpRegistry(); #if defined(POCO_WIN32_UTF8) std::wstring uhost; UnicodeConverter::toUTF16(_host, uhost); std::wstring uname; UnicodeConverter::toUTF16(_name, uname); _h = RegisterEventSourceW(uhost.empty() ? NULL : uhost.c_str(), uname.c_str()); #else _h = RegisterEventSource(_host.empty() ? NULL : _host.c_str(), _name.c_str()); #endif if (!_h) throw SystemException("cannot register event source"); } void EventLogChannel::close() { if (_h) DeregisterEventSource(_h); _h = 0; } void EventLogChannel::log(const Message& msg) { if (!_h) open(); #if defined(POCO_WIN32_UTF8) std::wstring utext; UnicodeConverter::toUTF16(msg.getText(), utext); const wchar_t* pMsg = utext.c_str(); ReportEventW(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); #else const char* pMsg = msg.getText().c_str(); ReportEvent(_h, getType(msg), getCategory(msg), POCO_MSG_LOG, NULL, 1, 0, &pMsg, NULL); #endif } void EventLogChannel::setProperty(const std::string& name, const std::string& value) { if (icompare(name, PROP_NAME) == 0) _name = value; else if (icompare(name, PROP_HOST) == 0) _host = value; else if (icompare(name, PROP_LOGHOST) == 0) _host = value; else if (icompare(name, PROP_LOGFILE) == 0) _logFile = value; else Channel::setProperty(name, value); } std::string EventLogChannel::getProperty(const std::string& name) const { if (icompare(name, PROP_NAME) == 0) return _name; else if (icompare(name, PROP_HOST) == 0) return _host; else if (icompare(name, PROP_LOGHOST) == 0) return _host; else if (icompare(name, PROP_LOGFILE) == 0) return _logFile; else return Channel::getProperty(name); } int EventLogChannel::getType(const Message& msg) { switch (msg.getPriority()) { case Message::PRIO_TRACE: case Message::PRIO_DEBUG: case Message::PRIO_INFORMATION: return EVENTLOG_INFORMATION_TYPE; case Message::PRIO_NOTICE: case Message::PRIO_WARNING: return EVENTLOG_WARNING_TYPE; default: return EVENTLOG_ERROR_TYPE; } } int EventLogChannel::getCategory(const Message& msg) { switch (msg.getPriority()) { case Message::PRIO_TRACE: return POCO_CTG_TRACE; case Message::PRIO_DEBUG: return POCO_CTG_DEBUG; case Message::PRIO_INFORMATION: return POCO_CTG_INFORMATION; case Message::PRIO_NOTICE: return POCO_CTG_NOTICE; case Message::PRIO_WARNING: return POCO_CTG_WARNING; case Message::PRIO_ERROR: return POCO_CTG_ERROR; case Message::PRIO_CRITICAL: return POCO_CTG_CRITICAL; case Message::PRIO_FATAL: return POCO_CTG_FATAL; default: return 0; } } void EventLogChannel::setUpRegistry() const { std::string key = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\"; key.append(_logFile); key.append("\\"); key.append(_name); HKEY hKey; DWORD disp; #if defined(POCO_WIN32_UTF8) std::wstring ukey; UnicodeConverter::toUTF16(key, ukey); DWORD rc = RegCreateKeyExW(HKEY_LOCAL_MACHINE, ukey.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); #else DWORD rc = RegCreateKeyEx(HKEY_LOCAL_MACHINE, key.c_str(), 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, &disp); #endif if (rc != ERROR_SUCCESS) return; if (disp == REG_CREATED_NEW_KEY) { #if defined(POCO_WIN32_UTF8) std::wstring path; #if defined(POCO_DLL) #if defined(_DEBUG) #if defined(_WIN64) path = findLibrary(L"PocoFoundation64d.dll"); #else path = findLibrary(L"PocoFoundationd.dll"); #endif #else #if defined(_WIN64) path = findLibrary(L"PocoFoundation64.dll"); #else path = findLibrary(L"PocoFoundation.dll"); #endif #endif #endif if (path.empty()) path = findLibrary(L"PocoMsg.dll"); #else std::string path; #if defined(POCO_DLL) #if defined(_DEBUG) #if defined(_WIN64) path = findLibrary("PocoFoundation64d.dll"); #else path = findLibrary("PocoFoundationd.dll"); #endif #else #if defined(_WIN64) path = findLibrary("PocoFoundation64.dll"); #else path = findLibrary("PocoFoundation.dll"); #endif #endif #endif if (path.empty()) path = findLibrary("PocoMsg.dll"); #endif if (!path.empty()) { DWORD count = 8; DWORD types = 7; #if defined(POCO_WIN32_UTF8) RegSetValueExW(hKey, L"CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), static_cast<DWORD>(sizeof(wchar_t)*(path.size() + 1))); RegSetValueExW(hKey, L"EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), static_cast<DWORD>(sizeof(wchar_t)*(path.size() + 1))); RegSetValueExW(hKey, L"CategoryCount", 0, REG_DWORD, (const BYTE*) &count, static_cast<DWORD>(sizeof(count))); RegSetValueExW(hKey, L"TypesSupported", 0, REG_DWORD, (const BYTE*) &types, static_cast<DWORD>(sizeof(types))); #else RegSetValueEx(hKey, "CategoryMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), static_cast<DWORD>(path.size() + 1)); RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (const BYTE*) path.c_str(), static_cast<DWORD>(path.size() + 1)); RegSetValueEx(hKey, "CategoryCount", 0, REG_DWORD, (const BYTE*) &count, static_cast<DWORD>(sizeof(count))); RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (const BYTE*) &types, static_cast<DWORD>(sizeof(types))); #endif } } RegCloseKey(hKey); } #if defined(POCO_WIN32_UTF8) std::wstring EventLogChannel::findLibrary(const wchar_t* name) { std::wstring path; HMODULE dll = LoadLibraryW(name); if (dll) { const DWORD maxPathLen = MAX_PATH + 1; wchar_t name[maxPathLen]; int n = GetModuleFileNameW(dll, name, maxPathLen); if (n > 0) path = name; FreeLibrary(dll); } return path; } #else std::string EventLogChannel::findLibrary(const char* name) { std::string path; HMODULE dll = LoadLibraryA(name); if (dll) { const DWORD maxPathLen = MAX_PATH + 1; char name[maxPathLen]; int n = GetModuleFileNameA(dll, name, maxPathLen); if (n > 0) path = name; FreeLibrary(dll); } return path; } #endif } // namespace Poco
mit
UAF-SuperDARN-OPS/SuperDARN_MSI_ROS
qnx/root/operational_radar_code/ros/fftw-3.2.2/dft/ct.c
20
6287
/* * Copyright (c) 2003, 2007-8 Matteo Frigo * Copyright (c) 2003, 2007-8 Massachusetts Institute of Technology * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 "ct.h" ct_solver *(*X(mksolver_ct_hook))(size_t, INT, int, ct_mkinferior, ct_force_vrecursion) = 0; typedef struct { plan_dft super; plan *cld; plan *cldw; INT r; } P; static void apply_dit(const plan *ego_, R *ri, R *ii, R *ro, R *io) { const P *ego = (const P *) ego_; plan_dft *cld; plan_dftw *cldw; cld = (plan_dft *) ego->cld; cld->apply(ego->cld, ri, ii, ro, io); cldw = (plan_dftw *) ego->cldw; cldw->apply(ego->cldw, ro, io); } static void apply_dif(const plan *ego_, R *ri, R *ii, R *ro, R *io) { const P *ego = (const P *) ego_; plan_dft *cld; plan_dftw *cldw; cldw = (plan_dftw *) ego->cldw; cldw->apply(ego->cldw, ri, ii); cld = (plan_dft *) ego->cld; cld->apply(ego->cld, ri, ii, ro, io); } static void awake(plan *ego_, enum wakefulness wakefulness) { P *ego = (P *) ego_; X(plan_awake)(ego->cld, wakefulness); X(plan_awake)(ego->cldw, wakefulness); } static void destroy(plan *ego_) { P *ego = (P *) ego_; X(plan_destroy_internal)(ego->cldw); X(plan_destroy_internal)(ego->cld); } static void print(const plan *ego_, printer *p) { const P *ego = (const P *) ego_; p->print(p, "(dft-ct-%s/%D%(%p%)%(%p%))", ego->super.apply == apply_dit ? "dit" : "dif", ego->r, ego->cldw, ego->cld); } static int applicable0(const ct_solver *ego, const problem *p_, planner *plnr) { const problem_dft *p = (const problem_dft *) p_; INT r; return (1 && p->sz->rnk == 1 && p->vecsz->rnk <= 1 /* DIF destroys the input and we don't like it */ && (ego->dec == DECDIT || p->ri == p->ro || !NO_DESTROY_INPUTP(plnr)) && ((r = X(choose_radix)(ego->r, p->sz->dims[0].n)) > 1) && p->sz->dims[0].n > r); } int X(ct_applicable)(const ct_solver *ego, const problem *p_, planner *plnr) { const problem_dft *p; if (!applicable0(ego, p_, plnr)) return 0; p = (const problem_dft *) p_; return (0 || ego->dec == DECDIF+TRANSPOSE || p->vecsz->rnk == 0 || !NO_VRECURSEP(plnr) || (ego->force_vrecursionp && ego->force_vrecursionp(ego, p)) ); } static plan *mkplan(const solver *ego_, const problem *p_, planner *plnr) { const ct_solver *ego = (const ct_solver *) ego_; const problem_dft *p; P *pln = 0; plan *cld = 0, *cldw = 0; INT n, r, m, v, ivs, ovs; iodim *d; static const plan_adt padt = { X(dft_solve), awake, print, destroy }; if ((NO_NONTHREADEDP(plnr)) || !X(ct_applicable)(ego, p_, plnr)) return (plan *) 0; p = (const problem_dft *) p_; d = p->sz->dims; n = d[0].n; r = X(choose_radix)(ego->r, n); m = n / r; X(tensor_tornk1)(p->vecsz, &v, &ivs, &ovs); switch (ego->dec) { case DECDIT: { cldw = ego->mkcldw(ego, r, m * d[0].os, m * d[0].os, m, d[0].os, v, ovs, ovs, 0, m, p->ro, p->io, plnr); if (!cldw) goto nada; cld = X(mkplan_d)(plnr, X(mkproblem_dft_d)( X(mktensor_1d)(m, r * d[0].is, d[0].os), X(mktensor_2d)(r, d[0].is, m * d[0].os, v, ivs, ovs), p->ri, p->ii, p->ro, p->io) ); if (!cld) goto nada; pln = MKPLAN_DFT(P, &padt, apply_dit); break; } case DECDIF: case DECDIF+TRANSPOSE: { INT cors, covs; /* cldw ors, ovs */ if (ego->dec == DECDIF+TRANSPOSE) { cors = ivs; covs = m * d[0].is; /* ensure that we generate well-formed dftw subproblems */ /* FIXME: too conservative */ if (!(1 && r == v && d[0].is == r * cors)) goto nada; /* FIXME: allow in-place only for now, like in fftw-3.[01] */ if (!(1 && p->ri == p->ro && d[0].is == r * d[0].os && cors == d[0].os && covs == ovs )) goto nada; } else { cors = m * d[0].is; covs = ivs; } cldw = ego->mkcldw(ego, r, m * d[0].is, cors, m, d[0].is, v, ivs, covs, 0, m, p->ri, p->ii, plnr); if (!cldw) goto nada; cld = X(mkplan_d)(plnr, X(mkproblem_dft_d)( X(mktensor_1d)(m, d[0].is, r * d[0].os), X(mktensor_2d)(r, cors, d[0].os, v, covs, ovs), p->ri, p->ii, p->ro, p->io) ); if (!cld) goto nada; pln = MKPLAN_DFT(P, &padt, apply_dif); break; } default: A(0); } pln->cld = cld; pln->cldw = cldw; pln->r = r; X(ops_add)(&cld->ops, &cldw->ops, &pln->super.super.ops); /* inherit could_prune_now_p attribute from cldw */ pln->super.super.could_prune_now_p = cldw->could_prune_now_p; return &(pln->super.super); nada: X(plan_destroy_internal)(cldw); X(plan_destroy_internal)(cld); return (plan *) 0; } ct_solver *X(mksolver_ct)(size_t size, INT r, int dec, ct_mkinferior mkcldw, ct_force_vrecursion force_vrecursionp) { static const solver_adt sadt = { PROBLEM_DFT, mkplan, 0 }; ct_solver *slv = (ct_solver *)X(mksolver)(size, &sadt); slv->r = r; slv->dec = dec; slv->mkcldw = mkcldw; slv->force_vrecursionp = force_vrecursionp; return slv; } plan *X(mkplan_dftw)(size_t size, const plan_adt *adt, dftwapply apply) { plan_dftw *ego; ego = (plan_dftw *) X(mkplan)(size, adt); ego->apply = apply; return &(ego->super); }
mit
PUCSIE-embedded-course/stm32f4-examples
firmware/freertos/create_task/lib/FreeRTOSV8.2.3/FreeRTOS/Demo/Common/ethernet/lwIP/core/snmp/mib2.c
21
104667
/** * @file * Management Information Base II (RFC1213) objects and functions. * * @note the object identifiers for this MIB-2 and private MIB tree * must be kept in sorted ascending order. This to ensure correct getnext operation. */ /* * Copyright (c) 2006 Axon Digital Design B.V., The Netherlands. * 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. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. * * Author: Christiaan Simons <christiaan.simons@axon.tv> */ #include "arch/cc.h" #include "lwip/opt.h" #if LWIP_SNMP #include "lwip/snmp.h" #include "lwip/netif.h" #include "netif/etharp.h" #include "lwip/ip.h" #include "lwip/ip_frag.h" #include "lwip/tcp.h" #include "lwip/udp.h" #include "lwip/snmp_asn1.h" #include "lwip/snmp_structs.h" /** * IANA assigned enterprise ID for lwIP is 26381 * @see http://www.iana.org/assignments/enterprise-numbers * * @note this enterprise ID is assigned to the lwIP project, * all object identifiers living under this ID are assigned * by the lwIP maintainers (contact Christiaan Simons)! * @note don't change this define, use snmp_set_sysobjid() * * If you need to create your own private MIB you'll need * to apply for your own enterprise ID with IANA: * http://www.iana.org/numbers.html */ #define SNMP_ENTERPRISE_ID 26381 #define SNMP_SYSOBJID_LEN 7 #define SNMP_SYSOBJID {1, 3, 6, 1, 4, 1, SNMP_ENTERPRISE_ID} #ifndef SNMP_SYSSERVICES #define SNMP_SYSSERVICES ((1 << 6) | (1 << 3) | ((IP_FORWARD) << 2)) #endif static void system_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void system_get_value(struct obj_def *od, u16_t len, void *value); static u8_t system_set_test(struct obj_def *od, u16_t len, void *value); static void system_set_value(struct obj_def *od, u16_t len, void *value); static void interfaces_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void interfaces_get_value(struct obj_def *od, u16_t len, void *value); static void ifentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void ifentry_get_value(struct obj_def *od, u16_t len, void *value); static void atentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void atentry_get_value(struct obj_def *od, u16_t len, void *value); static void ip_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void ip_get_value(struct obj_def *od, u16_t len, void *value); static u8_t ip_set_test(struct obj_def *od, u16_t len, void *value); static void ip_addrentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void ip_addrentry_get_value(struct obj_def *od, u16_t len, void *value); static void ip_rteentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void ip_rteentry_get_value(struct obj_def *od, u16_t len, void *value); static void ip_ntomentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void ip_ntomentry_get_value(struct obj_def *od, u16_t len, void *value); static void icmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void icmp_get_value(struct obj_def *od, u16_t len, void *value); #if LWIP_TCP static void tcp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void tcp_get_value(struct obj_def *od, u16_t len, void *value); static void tcpconnentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void tcpconnentry_get_value(struct obj_def *od, u16_t len, void *value); #endif static void udp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void udp_get_value(struct obj_def *od, u16_t len, void *value); static void udpentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void udpentry_get_value(struct obj_def *od, u16_t len, void *value); static void snmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od); static void snmp_get_value(struct obj_def *od, u16_t len, void *value); static u8_t snmp_set_test(struct obj_def *od, u16_t len, void *value); static void snmp_set_value(struct obj_def *od, u16_t len, void *value); /* snmp .1.3.6.1.2.1.11 */ const mib_scalar_node snmp_scalar = { &snmp_get_object_def, &snmp_get_value, &snmp_set_test, &snmp_set_value, MIB_NODE_SC, 0 }; const s32_t snmp_ids[28] = { 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 24, 25, 26, 27, 28, 29, 30 }; struct mib_node* const snmp_nodes[28] = { (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar, (struct mib_node* const)&snmp_scalar }; const struct mib_array_node snmp = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 28, snmp_ids, snmp_nodes }; /* dot3 and EtherLike MIB not planned. (transmission .1.3.6.1.2.1.10) */ /* historical (some say hysterical). (cmot .1.3.6.1.2.1.9) */ /* lwIP has no EGP, thus may not implement it. (egp .1.3.6.1.2.1.8) */ /* udp .1.3.6.1.2.1.7 */ /** index root node for udpTable */ struct mib_list_rootnode udp_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t udpentry_ids[2] = { 1, 2 }; struct mib_node* const udpentry_nodes[2] = { (struct mib_node* const)&udp_root, (struct mib_node* const)&udp_root, }; const struct mib_array_node udpentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 2, udpentry_ids, udpentry_nodes }; s32_t udptable_id = 1; struct mib_node* udptable_node = (struct mib_node* const)&udpentry; struct mib_ram_array_node udptable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &udptable_id, &udptable_node }; const mib_scalar_node udp_scalar = { &udp_get_object_def, &udp_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_SC, 0 }; const s32_t udp_ids[5] = { 1, 2, 3, 4, 5 }; struct mib_node* const udp_nodes[5] = { (struct mib_node* const)&udp_scalar, (struct mib_node* const)&udp_scalar, (struct mib_node* const)&udp_scalar, (struct mib_node* const)&udp_scalar, (struct mib_node* const)&udptable }; const struct mib_array_node udp = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 5, udp_ids, udp_nodes }; /* tcp .1.3.6.1.2.1.6 */ #if LWIP_TCP /* only if the TCP protocol is available may implement this group */ /** index root node for tcpConnTable */ struct mib_list_rootnode tcpconntree_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t tcpconnentry_ids[5] = { 1, 2, 3, 4, 5 }; struct mib_node* const tcpconnentry_nodes[5] = { (struct mib_node* const)&tcpconntree_root, (struct mib_node* const)&tcpconntree_root, (struct mib_node* const)&tcpconntree_root, (struct mib_node* const)&tcpconntree_root, (struct mib_node* const)&tcpconntree_root }; const struct mib_array_node tcpconnentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 5, tcpconnentry_ids, tcpconnentry_nodes }; s32_t tcpconntable_id = 1; struct mib_node* tcpconntable_node = (struct mib_node* const)&tcpconnentry; struct mib_ram_array_node tcpconntable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, /** @todo update maxlength when inserting / deleting from table 0 when table is empty, 1 when more than one entry */ 0, &tcpconntable_id, &tcpconntable_node }; const mib_scalar_node tcp_scalar = { &tcp_get_object_def, &tcp_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_SC, 0 }; const s32_t tcp_ids[15] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; struct mib_node* const tcp_nodes[15] = { (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcpconntable, (struct mib_node* const)&tcp_scalar, (struct mib_node* const)&tcp_scalar }; const struct mib_array_node tcp = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 15, tcp_ids, tcp_nodes }; #endif /* icmp .1.3.6.1.2.1.5 */ const mib_scalar_node icmp_scalar = { &icmp_get_object_def, &icmp_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_SC, 0 }; const s32_t icmp_ids[26] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26 }; struct mib_node* const icmp_nodes[26] = { (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar, (struct mib_node* const)&icmp_scalar }; const struct mib_array_node icmp = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 26, icmp_ids, icmp_nodes }; /** index root node for ipNetToMediaTable */ struct mib_list_rootnode ipntomtree_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t ipntomentry_ids[4] = { 1, 2, 3, 4 }; struct mib_node* const ipntomentry_nodes[4] = { (struct mib_node* const)&ipntomtree_root, (struct mib_node* const)&ipntomtree_root, (struct mib_node* const)&ipntomtree_root, (struct mib_node* const)&ipntomtree_root }; const struct mib_array_node ipntomentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 4, ipntomentry_ids, ipntomentry_nodes }; s32_t ipntomtable_id = 1; struct mib_node* ipntomtable_node = (struct mib_node* const)&ipntomentry; struct mib_ram_array_node ipntomtable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &ipntomtable_id, &ipntomtable_node }; /** index root node for ipRouteTable */ struct mib_list_rootnode iprtetree_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t iprteentry_ids[13] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; struct mib_node* const iprteentry_nodes[13] = { (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root, (struct mib_node* const)&iprtetree_root }; const struct mib_array_node iprteentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 13, iprteentry_ids, iprteentry_nodes }; s32_t iprtetable_id = 1; struct mib_node* iprtetable_node = (struct mib_node* const)&iprteentry; struct mib_ram_array_node iprtetable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &iprtetable_id, &iprtetable_node }; /** index root node for ipAddrTable */ struct mib_list_rootnode ipaddrtree_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t ipaddrentry_ids[5] = { 1, 2, 3, 4, 5 }; struct mib_node* const ipaddrentry_nodes[5] = { (struct mib_node* const)&ipaddrtree_root, (struct mib_node* const)&ipaddrtree_root, (struct mib_node* const)&ipaddrtree_root, (struct mib_node* const)&ipaddrtree_root, (struct mib_node* const)&ipaddrtree_root }; const struct mib_array_node ipaddrentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 5, ipaddrentry_ids, ipaddrentry_nodes }; s32_t ipaddrtable_id = 1; struct mib_node* ipaddrtable_node = (struct mib_node* const)&ipaddrentry; struct mib_ram_array_node ipaddrtable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &ipaddrtable_id, &ipaddrtable_node }; /* ip .1.3.6.1.2.1.4 */ const mib_scalar_node ip_scalar = { &ip_get_object_def, &ip_get_value, &ip_set_test, &noleafs_set_value, MIB_NODE_SC, 0 }; const s32_t ip_ids[23] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; struct mib_node* const ip_nodes[23] = { (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ip_scalar, (struct mib_node* const)&ipaddrtable, (struct mib_node* const)&iprtetable, (struct mib_node* const)&ipntomtable, (struct mib_node* const)&ip_scalar }; const struct mib_array_node ip = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 23, ip_ids, ip_nodes }; /** index root node for atTable */ struct mib_list_rootnode arptree_root = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t atentry_ids[3] = { 1, 2, 3 }; struct mib_node* const atentry_nodes[3] = { (struct mib_node* const)&arptree_root, (struct mib_node* const)&arptree_root, (struct mib_node* const)&arptree_root }; const struct mib_array_node atentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 3, atentry_ids, atentry_nodes }; const s32_t attable_id = 1; struct mib_node* const attable_node = (struct mib_node* const)&atentry; const struct mib_array_node attable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 1, &attable_id, &attable_node }; /* at .1.3.6.1.2.1.3 */ s32_t at_id = 1; struct mib_node* at_node = (struct mib_node* const)&attable; struct mib_ram_array_node at = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &at_id, &at_node }; /** index root node for ifTable */ struct mib_list_rootnode iflist_root = { &ifentry_get_object_def, &ifentry_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_LR, 0, NULL, NULL, 0 }; const s32_t ifentry_ids[22] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 }; struct mib_node* const ifentry_nodes[22] = { (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root, (struct mib_node* const)&iflist_root }; const struct mib_array_node ifentry = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 22, ifentry_ids, ifentry_nodes }; s32_t iftable_id = 1; struct mib_node* iftable_node = (struct mib_node* const)&ifentry; struct mib_ram_array_node iftable = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_RA, 0, &iftable_id, &iftable_node }; /* interfaces .1.3.6.1.2.1.2 */ const mib_scalar_node interfaces_scalar = { &interfaces_get_object_def, &interfaces_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_SC, 0 }; const s32_t interfaces_ids[2] = { 1, 2 }; struct mib_node* const interfaces_nodes[2] = { (struct mib_node* const)&interfaces_scalar, (struct mib_node* const)&iftable }; const struct mib_array_node interfaces = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 2, interfaces_ids, interfaces_nodes }; /* 0 1 2 3 4 5 6 */ /* system .1.3.6.1.2.1.1 */ const mib_scalar_node sys_tem_scalar = { &system_get_object_def, &system_get_value, &system_set_test, &system_set_value, MIB_NODE_SC, 0 }; const s32_t sys_tem_ids[7] = { 1, 2, 3, 4, 5, 6, 7 }; struct mib_node* const sys_tem_nodes[7] = { (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar, (struct mib_node* const)&sys_tem_scalar }; /* work around name issue with 'sys_tem', some compiler(s?) seem to reserve 'system' */ const struct mib_array_node sys_tem = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 7, sys_tem_ids, sys_tem_nodes }; /* mib-2 .1.3.6.1.2.1 */ #if LWIP_TCP #define MIB2_GROUPS 8 #else #define MIB2_GROUPS 7 #endif const s32_t mib2_ids[MIB2_GROUPS] = { 1, 2, 3, 4, 5, #if LWIP_TCP 6, #endif 7, 11 }; struct mib_node* const mib2_nodes[MIB2_GROUPS] = { (struct mib_node* const)&sys_tem, (struct mib_node* const)&interfaces, (struct mib_node* const)&at, (struct mib_node* const)&ip, (struct mib_node* const)&icmp, #if LWIP_TCP (struct mib_node* const)&tcp, #endif (struct mib_node* const)&udp, (struct mib_node* const)&snmp }; const struct mib_array_node mib2 = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, MIB2_GROUPS, mib2_ids, mib2_nodes }; /* mgmt .1.3.6.1.2 */ const s32_t mgmt_ids[1] = { 1 }; struct mib_node* const mgmt_nodes[1] = { (struct mib_node* const)&mib2 }; const struct mib_array_node mgmt = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 1, mgmt_ids, mgmt_nodes }; /* internet .1.3.6.1 */ #if SNMP_PRIVATE_MIB s32_t internet_ids[2] = { 2, 4 }; struct mib_node* const internet_nodes[2] = { (struct mib_node* const)&mgmt, (struct mib_node* const)&private }; const struct mib_array_node internet = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 2, internet_ids, internet_nodes }; #else const s32_t internet_ids[1] = { 2 }; struct mib_node* const internet_nodes[1] = { (struct mib_node* const)&mgmt }; const struct mib_array_node internet = { &noleafs_get_object_def, &noleafs_get_value, &noleafs_set_test, &noleafs_set_value, MIB_NODE_AR, 1, internet_ids, internet_nodes }; #endif /** mib-2.system.sysObjectID */ static struct snmp_obj_id sysobjid = {SNMP_SYSOBJID_LEN, SNMP_SYSOBJID}; /** enterprise ID for generic TRAPs, .iso.org.dod.internet.mgmt.mib-2.snmp */ static struct snmp_obj_id snmpgrp_id = {7,{1,3,6,1,2,1,11}}; /** mib-2.system.sysServices */ static const s32_t sysservices = SNMP_SYSSERVICES; /** mib-2.system.sysDescr */ static const u8_t sysdescr_len_default = 4; static const u8_t sysdescr_default[] = "lwIP"; static u8_t* sysdescr_len_ptr = (u8_t*)&sysdescr_len_default; static u8_t* sysdescr_ptr = (u8_t*)&sysdescr_default[0]; /** mib-2.system.sysContact */ static const u8_t syscontact_len_default = 0; static const u8_t syscontact_default[] = ""; static u8_t* syscontact_len_ptr = (u8_t*)&syscontact_len_default; static u8_t* syscontact_ptr = (u8_t*)&syscontact_default[0]; /** mib-2.system.sysName */ static const u8_t sysname_len_default = 8; static const u8_t sysname_default[] = "FQDN-unk"; static u8_t* sysname_len_ptr = (u8_t*)&sysname_len_default; static u8_t* sysname_ptr = (u8_t*)&sysname_default[0]; /** mib-2.system.sysLocation */ static const u8_t syslocation_len_default = 0; static const u8_t syslocation_default[] = ""; static u8_t* syslocation_len_ptr = (u8_t*)&syslocation_len_default; static u8_t* syslocation_ptr = (u8_t*)&syslocation_default[0]; /** mib-2.snmp.snmpEnableAuthenTraps */ static const u8_t snmpenableauthentraps_default = 2; /* disabled */ static u8_t* snmpenableauthentraps_ptr = (u8_t*)&snmpenableauthentraps_default; /** mib-2.interfaces.ifTable.ifEntry.ifSpecific (zeroDotZero) */ static const struct snmp_obj_id ifspecific = {2, {0, 0}}; /** mib-2.ip.ipRouteTable.ipRouteEntry.ipRouteInfo (zeroDotZero) */ static const struct snmp_obj_id iprouteinfo = {2, {0, 0}}; /* mib-2.system counter(s) */ static u32_t sysuptime = 0; /* mib-2.ip counter(s) */ static u32_t ipinreceives = 0, ipinhdrerrors = 0, ipinaddrerrors = 0, ipforwdatagrams = 0, ipinunknownprotos = 0, ipindiscards = 0, ipindelivers = 0, ipoutrequests = 0, ipoutdiscards = 0, ipoutnoroutes = 0, ipreasmreqds = 0, ipreasmoks = 0, ipreasmfails = 0, ipfragoks = 0, ipfragfails = 0, ipfragcreates = 0, iproutingdiscards = 0; /* mib-2.icmp counter(s) */ static u32_t icmpinmsgs = 0, icmpinerrors = 0, icmpindestunreachs = 0, icmpintimeexcds = 0, icmpinparmprobs = 0, icmpinsrcquenchs = 0, icmpinredirects = 0, icmpinechos = 0, icmpinechoreps = 0, icmpintimestamps = 0, icmpintimestampreps = 0, icmpinaddrmasks = 0, icmpinaddrmaskreps = 0, icmpoutmsgs = 0, icmpouterrors = 0, icmpoutdestunreachs = 0, icmpouttimeexcds = 0, icmpoutparmprobs = 0, icmpoutsrcquenchs = 0, icmpoutredirects = 0, icmpoutechos = 0, icmpoutechoreps = 0, icmpouttimestamps = 0, icmpouttimestampreps = 0, icmpoutaddrmasks = 0, icmpoutaddrmaskreps = 0; /* mib-2.tcp counter(s) */ static u32_t tcpactiveopens = 0, tcppassiveopens = 0, tcpattemptfails = 0, tcpestabresets = 0, tcpinsegs = 0, tcpoutsegs = 0, tcpretranssegs = 0, tcpinerrs = 0, tcpoutrsts = 0; /* mib-2.udp counter(s) */ static u32_t udpindatagrams = 0, udpnoports = 0, udpinerrors = 0, udpoutdatagrams = 0; /* mib-2.snmp counter(s) */ static u32_t snmpinpkts = 0, snmpoutpkts = 0, snmpinbadversions = 0, snmpinbadcommunitynames = 0, snmpinbadcommunityuses = 0, snmpinasnparseerrs = 0, snmpintoobigs = 0, snmpinnosuchnames = 0, snmpinbadvalues = 0, snmpinreadonlys = 0, snmpingenerrs = 0, snmpintotalreqvars = 0, snmpintotalsetvars = 0, snmpingetrequests = 0, snmpingetnexts = 0, snmpinsetrequests = 0, snmpingetresponses = 0, snmpintraps = 0, snmpouttoobigs = 0, snmpoutnosuchnames = 0, snmpoutbadvalues = 0, snmpoutgenerrs = 0, snmpoutgetrequests = 0, snmpoutgetnexts = 0, snmpoutsetrequests = 0, snmpoutgetresponses = 0, snmpouttraps = 0; /* prototypes of the following functions are in lwip/src/include/lwip/snmp.h */ /** * Copy octet string. * * @param dst points to destination * @param src points to source * @param n number of octets to copy. */ void ocstrncpy(u8_t *dst, u8_t *src, u8_t n) { while (n > 0) { n--; *dst++ = *src++; } } /** * Copy object identifier (s32_t) array. * * @param dst points to destination * @param src points to source * @param n number of sub identifiers to copy. */ void objectidncpy(s32_t *dst, s32_t *src, u8_t n) { while(n > 0) { n--; *dst++ = *src++; } } /** * Initializes sysDescr pointers. * * @param str if non-NULL then copy str pointer * @param strlen points to string length, excluding zero terminator */ void snmp_set_sysdesr(u8_t *str, u8_t *strlen) { if (str != NULL) { sysdescr_ptr = str; sysdescr_len_ptr = strlen; } } void snmp_get_sysobjid_ptr(struct snmp_obj_id **oid) { *oid = &sysobjid; } /** * Initializes sysObjectID value. * * @param oid points to stuct snmp_obj_id to copy */ void snmp_set_sysobjid(struct snmp_obj_id *oid) { sysobjid = *oid; } /** * Must be called at regular 10 msec interval from a timer interrupt * or signal handler depending on your runtime environment. */ void snmp_inc_sysuptime(void) { sysuptime++; } void snmp_get_sysuptime(u32_t *value) { *value = sysuptime; } /** * Initializes sysContact pointers, * e.g. ptrs to non-volatile memory external to lwIP. * * @param str if non-NULL then copy str pointer * @param strlen points to string length, excluding zero terminator */ void snmp_set_syscontact(u8_t *ocstr, u8_t *ocstrlen) { if (ocstr != NULL) { syscontact_ptr = ocstr; syscontact_len_ptr = ocstrlen; } } /** * Initializes sysName pointers, * e.g. ptrs to non-volatile memory external to lwIP. * * @param str if non-NULL then copy str pointer * @param strlen points to string length, excluding zero terminator */ void snmp_set_sysname(u8_t *ocstr, u8_t *ocstrlen) { if (ocstr != NULL) { sysname_ptr = ocstr; sysname_len_ptr = ocstrlen; } } /** * Initializes sysLocation pointers, * e.g. ptrs to non-volatile memory external to lwIP. * * @param str if non-NULL then copy str pointer * @param strlen points to string length, excluding zero terminator */ void snmp_set_syslocation(u8_t *ocstr, u8_t *ocstrlen) { if (ocstr != NULL) { syslocation_ptr = ocstr; syslocation_len_ptr = ocstrlen; } } void snmp_add_ifinoctets(struct netif *ni, u32_t value) { ni->ifinoctets += value; } void snmp_inc_ifinucastpkts(struct netif *ni) { (ni->ifinucastpkts)++; } void snmp_inc_ifinnucastpkts(struct netif *ni) { (ni->ifinnucastpkts)++; } void snmp_inc_ifindiscards(struct netif *ni) { (ni->ifindiscards)++; } void snmp_add_ifoutoctets(struct netif *ni, u32_t value) { ni->ifoutoctets += value; } void snmp_inc_ifoutucastpkts(struct netif *ni) { (ni->ifoutucastpkts)++; } void snmp_inc_ifoutnucastpkts(struct netif *ni) { (ni->ifoutnucastpkts)++; } void snmp_inc_ifoutdiscards(struct netif *ni) { (ni->ifoutdiscards)++; } void snmp_inc_iflist(void) { struct mib_list_node *if_node = NULL; snmp_mib_node_insert(&iflist_root, iflist_root.count + 1, &if_node); /* enable getnext traversal on filled table */ iftable.maxlength = 1; } void snmp_dec_iflist(void) { snmp_mib_node_delete(&iflist_root, iflist_root.tail); /* disable getnext traversal on empty table */ if(iflist_root.count == 0) iftable.maxlength = 0; } /** * Inserts ARP table indexes (.xIfIndex.xNetAddress) * into arp table index trees (both atTable and ipNetToMediaTable). */ void snmp_insert_arpidx_tree(struct netif *ni, struct ip_addr *ip) { struct mib_list_rootnode *at_rn; struct mib_list_node *at_node; struct ip_addr hip; s32_t arpidx[5]; u8_t level, tree; LWIP_ASSERT("ni != NULL", ni != NULL); snmp_netiftoifindex(ni, &arpidx[0]); hip.addr = ntohl(ip->addr); snmp_iptooid(&hip, &arpidx[1]); for (tree = 0; tree < 2; tree++) { if (tree == 0) { at_rn = &arptree_root; } else { at_rn = &ipntomtree_root; } for (level = 0; level < 5; level++) { at_node = NULL; snmp_mib_node_insert(at_rn, arpidx[level], &at_node); if ((level != 4) && (at_node != NULL)) { if (at_node->nptr == NULL) { at_rn = snmp_mib_lrn_alloc(); at_node->nptr = (struct mib_node*)at_rn; if (at_rn != NULL) { if (level == 3) { if (tree == 0) { at_rn->get_object_def = atentry_get_object_def; at_rn->get_value = atentry_get_value; } else { at_rn->get_object_def = ip_ntomentry_get_object_def; at_rn->get_value = ip_ntomentry_get_value; } at_rn->set_test = noleafs_set_test; at_rn->set_value = noleafs_set_value; } } else { /* at_rn == NULL, malloc failure */ LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_arpidx_tree() insert failed, mem full")); break; } } else { at_rn = (struct mib_list_rootnode*)at_node->nptr; } } } } /* enable getnext traversal on filled tables */ at.maxlength = 1; ipntomtable.maxlength = 1; } /** * Removes ARP table indexes (.xIfIndex.xNetAddress) * from arp table index trees. */ void snmp_delete_arpidx_tree(struct netif *ni, struct ip_addr *ip) { struct mib_list_rootnode *at_rn, *next, *del_rn[5]; struct mib_list_node *at_n, *del_n[5]; struct ip_addr hip; s32_t arpidx[5]; u8_t fc, tree, level, del_cnt; snmp_netiftoifindex(ni, &arpidx[0]); hip.addr = ntohl(ip->addr); snmp_iptooid(&hip, &arpidx[1]); for (tree = 0; tree < 2; tree++) { /* mark nodes for deletion */ if (tree == 0) { at_rn = &arptree_root; } else { at_rn = &ipntomtree_root; } level = 0; del_cnt = 0; while ((level < 5) && (at_rn != NULL)) { fc = snmp_mib_node_find(at_rn, arpidx[level], &at_n); if (fc == 0) { /* arpidx[level] does not exist */ del_cnt = 0; at_rn = NULL; } else if (fc == 1) { del_rn[del_cnt] = at_rn; del_n[del_cnt] = at_n; del_cnt++; at_rn = (struct mib_list_rootnode*)(at_n->nptr); } else if (fc == 2) { /* reset delete (2 or more childs) */ del_cnt = 0; at_rn = (struct mib_list_rootnode*)(at_n->nptr); } level++; } /* delete marked index nodes */ while (del_cnt > 0) { del_cnt--; at_rn = del_rn[del_cnt]; at_n = del_n[del_cnt]; next = snmp_mib_node_delete(at_rn, at_n); if (next != NULL) { LWIP_ASSERT("next_count == 0",next->count == 0); snmp_mib_lrn_free(next); } } } /* disable getnext traversal on empty tables */ if(arptree_root.count == 0) at.maxlength = 0; if(ipntomtree_root.count == 0) ipntomtable.maxlength = 0; } void snmp_inc_ipinreceives(void) { ipinreceives++; } void snmp_inc_ipinhdrerrors(void) { ipinhdrerrors++; } void snmp_inc_ipinaddrerrors(void) { ipinaddrerrors++; } void snmp_inc_ipforwdatagrams(void) { ipforwdatagrams++; } void snmp_inc_ipinunknownprotos(void) { ipinunknownprotos++; } void snmp_inc_ipindiscards(void) { ipindiscards++; } void snmp_inc_ipindelivers(void) { ipindelivers++; } void snmp_inc_ipoutrequests(void) { ipoutrequests++; } void snmp_inc_ipoutdiscards(void) { ipoutdiscards++; } void snmp_inc_ipoutnoroutes(void) { ipoutnoroutes++; } void snmp_inc_ipreasmreqds(void) { ipreasmreqds++; } void snmp_inc_ipreasmoks(void) { ipreasmoks++; } void snmp_inc_ipreasmfails(void) { ipreasmfails++; } void snmp_inc_ipfragoks(void) { ipfragoks++; } void snmp_inc_ipfragfails(void) { ipfragfails++; } void snmp_inc_ipfragcreates(void) { ipfragcreates++; } void snmp_inc_iproutingdiscards(void) { iproutingdiscards++; } /** * Inserts ipAddrTable indexes (.ipAdEntAddr) * into index tree. */ void snmp_insert_ipaddridx_tree(struct netif *ni) { struct mib_list_rootnode *ipa_rn; struct mib_list_node *ipa_node; struct ip_addr ip; s32_t ipaddridx[4]; u8_t level; LWIP_ASSERT("ni != NULL", ni != NULL); ip.addr = ntohl(ni->ip_addr.addr); snmp_iptooid(&ip, &ipaddridx[0]); level = 0; ipa_rn = &ipaddrtree_root; while (level < 4) { ipa_node = NULL; snmp_mib_node_insert(ipa_rn, ipaddridx[level], &ipa_node); if ((level != 3) && (ipa_node != NULL)) { if (ipa_node->nptr == NULL) { ipa_rn = snmp_mib_lrn_alloc(); ipa_node->nptr = (struct mib_node*)ipa_rn; if (ipa_rn != NULL) { if (level == 2) { ipa_rn->get_object_def = ip_addrentry_get_object_def; ipa_rn->get_value = ip_addrentry_get_value; ipa_rn->set_test = noleafs_set_test; ipa_rn->set_value = noleafs_set_value; } } else { /* ipa_rn == NULL, malloc failure */ LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_ipaddridx_tree() insert failed, mem full")); break; } } else { ipa_rn = (struct mib_list_rootnode*)ipa_node->nptr; } } level++; } /* enable getnext traversal on filled table */ ipaddrtable.maxlength = 1; } /** * Removes ipAddrTable indexes (.ipAdEntAddr) * from index tree. */ void snmp_delete_ipaddridx_tree(struct netif *ni) { struct mib_list_rootnode *ipa_rn, *next, *del_rn[4]; struct mib_list_node *ipa_n, *del_n[4]; struct ip_addr ip; s32_t ipaddridx[4]; u8_t fc, level, del_cnt; LWIP_ASSERT("ni != NULL", ni != NULL); ip.addr = ntohl(ni->ip_addr.addr); snmp_iptooid(&ip, &ipaddridx[0]); /* mark nodes for deletion */ level = 0; del_cnt = 0; ipa_rn = &ipaddrtree_root; while ((level < 4) && (ipa_rn != NULL)) { fc = snmp_mib_node_find(ipa_rn, ipaddridx[level], &ipa_n); if (fc == 0) { /* ipaddridx[level] does not exist */ del_cnt = 0; ipa_rn = NULL; } else if (fc == 1) { del_rn[del_cnt] = ipa_rn; del_n[del_cnt] = ipa_n; del_cnt++; ipa_rn = (struct mib_list_rootnode*)(ipa_n->nptr); } else if (fc == 2) { /* reset delete (2 or more childs) */ del_cnt = 0; ipa_rn = (struct mib_list_rootnode*)(ipa_n->nptr); } level++; } /* delete marked index nodes */ while (del_cnt > 0) { del_cnt--; ipa_rn = del_rn[del_cnt]; ipa_n = del_n[del_cnt]; next = snmp_mib_node_delete(ipa_rn, ipa_n); if (next != NULL) { LWIP_ASSERT("next_count == 0",next->count == 0); snmp_mib_lrn_free(next); } } /* disable getnext traversal on empty table */ if (ipaddrtree_root.count == 0) ipaddrtable.maxlength = 0; } /** * Inserts ipRouteTable indexes (.ipRouteDest) * into index tree. * * @param dflt non-zero for the default rte, zero for network rte * @param netif points to network interface for this rte * * @todo record sysuptime for _this_ route when it is installed * (needed for ipRouteAge) in the netif. */ void snmp_insert_iprteidx_tree(u8_t dflt, struct netif *ni) { u8_t insert = 0; struct ip_addr dst; if (dflt != 0) { /* the default route 0.0.0.0 */ dst.addr = 0; insert = 1; } else { /* route to the network address */ dst.addr = ntohl(ni->ip_addr.addr & ni->netmask.addr); /* exclude 0.0.0.0 network (reserved for default rte) */ if (dst.addr != 0) insert = 1; } if (insert) { struct mib_list_rootnode *iprte_rn; struct mib_list_node *iprte_node; s32_t iprteidx[4]; u8_t level; snmp_iptooid(&dst, &iprteidx[0]); level = 0; iprte_rn = &iprtetree_root; while (level < 4) { iprte_node = NULL; snmp_mib_node_insert(iprte_rn, iprteidx[level], &iprte_node); if ((level != 3) && (iprte_node != NULL)) { if (iprte_node->nptr == NULL) { iprte_rn = snmp_mib_lrn_alloc(); iprte_node->nptr = (struct mib_node*)iprte_rn; if (iprte_rn != NULL) { if (level == 2) { iprte_rn->get_object_def = ip_rteentry_get_object_def; iprte_rn->get_value = ip_rteentry_get_value; iprte_rn->set_test = noleafs_set_test; iprte_rn->set_value = noleafs_set_value; } } else { /* iprte_rn == NULL, malloc failure */ LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_iprteidx_tree() insert failed, mem full")); break; } } else { iprte_rn = (struct mib_list_rootnode*)iprte_node->nptr; } } level++; } } /* enable getnext traversal on filled table */ iprtetable.maxlength = 1; } /** * Removes ipRouteTable indexes (.ipRouteDest) * from index tree. * * @param dflt non-zero for the default rte, zero for network rte * @param netif points to network interface for this rte or NULL * for default route to be removed. */ void snmp_delete_iprteidx_tree(u8_t dflt, struct netif *ni) { u8_t delete = 0; struct ip_addr dst; if (dflt != 0) { /* the default route 0.0.0.0 */ dst.addr = 0; delete = 1; } else { /* route to the network address */ dst.addr = ntohl(ni->ip_addr.addr & ni->netmask.addr); /* exclude 0.0.0.0 network (reserved for default rte) */ if (dst.addr != 0) delete = 1; } if (delete) { struct mib_list_rootnode *iprte_rn, *next, *del_rn[4]; struct mib_list_node *iprte_n, *del_n[4]; s32_t iprteidx[4]; u8_t fc, level, del_cnt; snmp_iptooid(&dst, &iprteidx[0]); /* mark nodes for deletion */ level = 0; del_cnt = 0; iprte_rn = &iprtetree_root; while ((level < 4) && (iprte_rn != NULL)) { fc = snmp_mib_node_find(iprte_rn, iprteidx[level], &iprte_n); if (fc == 0) { /* iprteidx[level] does not exist */ del_cnt = 0; iprte_rn = NULL; } else if (fc == 1) { del_rn[del_cnt] = iprte_rn; del_n[del_cnt] = iprte_n; del_cnt++; iprte_rn = (struct mib_list_rootnode*)(iprte_n->nptr); } else if (fc == 2) { /* reset delete (2 or more childs) */ del_cnt = 0; iprte_rn = (struct mib_list_rootnode*)(iprte_n->nptr); } level++; } /* delete marked index nodes */ while (del_cnt > 0) { del_cnt--; iprte_rn = del_rn[del_cnt]; iprte_n = del_n[del_cnt]; next = snmp_mib_node_delete(iprte_rn, iprte_n); if (next != NULL) { LWIP_ASSERT("next_count == 0",next->count == 0); snmp_mib_lrn_free(next); } } } /* disable getnext traversal on empty table */ if (iprtetree_root.count == 0) iprtetable.maxlength = 0; } void snmp_inc_icmpinmsgs(void) { icmpinmsgs++; } void snmp_inc_icmpinerrors(void) { icmpinerrors++; } void snmp_inc_icmpindestunreachs(void) { icmpindestunreachs++; } void snmp_inc_icmpintimeexcds(void) { icmpintimeexcds++; } void snmp_inc_icmpinparmprobs(void) { icmpinparmprobs++; } void snmp_inc_icmpinsrcquenchs(void) { icmpinsrcquenchs++; } void snmp_inc_icmpinredirects(void) { icmpinredirects++; } void snmp_inc_icmpinechos(void) { icmpinechos++; } void snmp_inc_icmpinechoreps(void) { icmpinechoreps++; } void snmp_inc_icmpintimestamps(void) { icmpintimestamps++; } void snmp_inc_icmpintimestampreps(void) { icmpintimestampreps++; } void snmp_inc_icmpinaddrmasks(void) { icmpinaddrmasks++; } void snmp_inc_icmpinaddrmaskreps(void) { icmpinaddrmaskreps++; } void snmp_inc_icmpoutmsgs(void) { icmpoutmsgs++; } void snmp_inc_icmpouterrors(void) { icmpouterrors++; } void snmp_inc_icmpoutdestunreachs(void) { icmpoutdestunreachs++; } void snmp_inc_icmpouttimeexcds(void) { icmpouttimeexcds++; } void snmp_inc_icmpoutparmprobs(void) { icmpoutparmprobs++; } void snmp_inc_icmpoutsrcquenchs(void) { icmpoutsrcquenchs++; } void snmp_inc_icmpoutredirects(void) { icmpoutredirects++; } void snmp_inc_icmpoutechos(void) { icmpoutechos++; } void snmp_inc_icmpoutechoreps(void) { icmpoutechoreps++; } void snmp_inc_icmpouttimestamps(void) { icmpouttimestamps++; } void snmp_inc_icmpouttimestampreps(void) { icmpouttimestampreps++; } void snmp_inc_icmpoutaddrmasks(void) { icmpoutaddrmasks++; } void snmp_inc_icmpoutaddrmaskreps(void) { icmpoutaddrmaskreps++; } void snmp_inc_tcpactiveopens(void) { tcpactiveopens++; } void snmp_inc_tcppassiveopens(void) { tcppassiveopens++; } void snmp_inc_tcpattemptfails(void) { tcpattemptfails++; } void snmp_inc_tcpestabresets(void) { tcpestabresets++; } void snmp_inc_tcpinsegs(void) { tcpinsegs++; } void snmp_inc_tcpoutsegs(void) { tcpoutsegs++; } void snmp_inc_tcpretranssegs(void) { tcpretranssegs++; } void snmp_inc_tcpinerrs(void) { tcpinerrs++; } void snmp_inc_tcpoutrsts(void) { tcpoutrsts++; } void snmp_inc_udpindatagrams(void) { udpindatagrams++; } void snmp_inc_udpnoports(void) { udpnoports++; } void snmp_inc_udpinerrors(void) { udpinerrors++; } void snmp_inc_udpoutdatagrams(void) { udpoutdatagrams++; } /** * Inserts udpTable indexes (.udpLocalAddress.udpLocalPort) * into index tree. */ void snmp_insert_udpidx_tree(struct udp_pcb *pcb) { struct mib_list_rootnode *udp_rn; struct mib_list_node *udp_node; struct ip_addr ip; s32_t udpidx[5]; u8_t level; LWIP_ASSERT("pcb != NULL", pcb != NULL); ip.addr = ntohl(pcb->local_ip.addr); snmp_iptooid(&ip, &udpidx[0]); udpidx[4] = pcb->local_port; udp_rn = &udp_root; for (level = 0; level < 5; level++) { udp_node = NULL; snmp_mib_node_insert(udp_rn, udpidx[level], &udp_node); if ((level != 4) && (udp_node != NULL)) { if (udp_node->nptr == NULL) { udp_rn = snmp_mib_lrn_alloc(); udp_node->nptr = (struct mib_node*)udp_rn; if (udp_rn != NULL) { if (level == 3) { udp_rn->get_object_def = udpentry_get_object_def; udp_rn->get_value = udpentry_get_value; udp_rn->set_test = noleafs_set_test; udp_rn->set_value = noleafs_set_value; } } else { /* udp_rn == NULL, malloc failure */ LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_insert_udpidx_tree() insert failed, mem full")); break; } } else { udp_rn = (struct mib_list_rootnode*)udp_node->nptr; } } } udptable.maxlength = 1; } /** * Removes udpTable indexes (.udpLocalAddress.udpLocalPort) * from index tree. */ void snmp_delete_udpidx_tree(struct udp_pcb *pcb) { struct mib_list_rootnode *udp_rn, *next, *del_rn[5]; struct mib_list_node *udp_n, *del_n[5]; struct ip_addr ip; s32_t udpidx[5]; u8_t bindings, fc, level, del_cnt; LWIP_ASSERT("pcb != NULL", pcb != NULL); ip.addr = ntohl(pcb->local_ip.addr); snmp_iptooid(&ip, &udpidx[0]); udpidx[4] = pcb->local_port; /* count PCBs for a given binding (e.g. when reusing ports or for temp output PCBs) */ bindings = 0; pcb = udp_pcbs; while ((pcb != NULL)) { if ((pcb->local_ip.addr == ip.addr) && (pcb->local_port == udpidx[4])) { bindings++; } pcb = pcb->next; } if (bindings == 1) { /* selectively remove */ /* mark nodes for deletion */ level = 0; del_cnt = 0; udp_rn = &udp_root; while ((level < 5) && (udp_rn != NULL)) { fc = snmp_mib_node_find(udp_rn, udpidx[level], &udp_n); if (fc == 0) { /* udpidx[level] does not exist */ del_cnt = 0; udp_rn = NULL; } else if (fc == 1) { del_rn[del_cnt] = udp_rn; del_n[del_cnt] = udp_n; del_cnt++; udp_rn = (struct mib_list_rootnode*)(udp_n->nptr); } else if (fc == 2) { /* reset delete (2 or more childs) */ del_cnt = 0; udp_rn = (struct mib_list_rootnode*)(udp_n->nptr); } level++; } /* delete marked index nodes */ while (del_cnt > 0) { del_cnt--; udp_rn = del_rn[del_cnt]; udp_n = del_n[del_cnt]; next = snmp_mib_node_delete(udp_rn, udp_n); if (next != NULL) { LWIP_ASSERT("next_count == 0",next->count == 0); snmp_mib_lrn_free(next); } } } /* disable getnext traversal on empty table */ if (udp_root.count == 0) udptable.maxlength = 0; } void snmp_inc_snmpinpkts(void) { snmpinpkts++; } void snmp_inc_snmpoutpkts(void) { snmpoutpkts++; } void snmp_inc_snmpinbadversions(void) { snmpinbadversions++; } void snmp_inc_snmpinbadcommunitynames(void) { snmpinbadcommunitynames++; } void snmp_inc_snmpinbadcommunityuses(void) { snmpinbadcommunityuses++; } void snmp_inc_snmpinasnparseerrs(void) { snmpinasnparseerrs++; } void snmp_inc_snmpintoobigs(void) { snmpintoobigs++; } void snmp_inc_snmpinnosuchnames(void) { snmpinnosuchnames++; } void snmp_inc_snmpinbadvalues(void) { snmpinbadvalues++; } void snmp_inc_snmpinreadonlys(void) { snmpinreadonlys++; } void snmp_inc_snmpingenerrs(void) { snmpingenerrs++; } void snmp_add_snmpintotalreqvars(u8_t value) { snmpintotalreqvars += value; } void snmp_add_snmpintotalsetvars(u8_t value) { snmpintotalsetvars += value; } void snmp_inc_snmpingetrequests(void) { snmpingetrequests++; } void snmp_inc_snmpingetnexts(void) { snmpingetnexts++; } void snmp_inc_snmpinsetrequests(void) { snmpinsetrequests++; } void snmp_inc_snmpingetresponses(void) { snmpingetresponses++; } void snmp_inc_snmpintraps(void) { snmpintraps++; } void snmp_inc_snmpouttoobigs(void) { snmpouttoobigs++; } void snmp_inc_snmpoutnosuchnames(void) { snmpoutnosuchnames++; } void snmp_inc_snmpoutbadvalues(void) { snmpoutbadvalues++; } void snmp_inc_snmpoutgenerrs(void) { snmpoutgenerrs++; } void snmp_inc_snmpoutgetrequests(void) { snmpoutgetrequests++; } void snmp_inc_snmpoutgetnexts(void) { snmpoutgetnexts++; } void snmp_inc_snmpoutsetrequests(void) { snmpoutsetrequests++; } void snmp_inc_snmpoutgetresponses(void) { snmpoutgetresponses++; } void snmp_inc_snmpouttraps(void) { snmpouttraps++; } void snmp_get_snmpgrpid_ptr(struct snmp_obj_id **oid) { *oid = &snmpgrp_id; } void snmp_set_snmpenableauthentraps(u8_t *value) { if (value != NULL) { snmpenableauthentraps_ptr = value; } } void snmp_get_snmpenableauthentraps(u8_t *value) { *value = *snmpenableauthentraps_ptr; } void noleafs_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { if (ident_len){} if (ident){} od->instance = MIB_OBJECT_NONE; } void noleafs_get_value(struct obj_def *od, u16_t len, void *value) { if (od){} if (len){} if (value){} } u8_t noleafs_set_test(struct obj_def *od, u16_t len, void *value) { if (od){} if (len){} if (value){} /* can't set */ return 0; } void noleafs_set_value(struct obj_def *od, u16_t len, void *value) { if (od){} if (len){} if (value){} } /** * Returns systems object definitions. * * @param ident_len the address length (2) * @param ident points to objectname.0 (object id trailer) * @param od points to object definition. */ static void system_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { u8_t id; /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def system.%"U16_F".0\n",(u16_t)id)); switch (id) { case 1: /* sysDescr */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = *sysdescr_len_ptr; break; case 2: /* sysObjectID */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); od->v_len = sysobjid.len * sizeof(s32_t); break; case 3: /* sysUpTime */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS); od->v_len = sizeof(u32_t); break; case 4: /* sysContact */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = *syscontact_len_ptr; break; case 5: /* sysName */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = *sysname_len_ptr; break; case 6: /* sysLocation */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = *syslocation_len_ptr; break; case 7: /* sysServices */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("system_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } /** * Returns system object value. * * @param ident_len the address length (2) * @param ident points to objectname.0 (object id trailer) * @param len return value space (in bytes) * @param value points to (varbind) space to copy value into. */ static void system_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; id = od->id_inst_ptr[0]; switch (id) { case 1: /* sysDescr */ ocstrncpy(value,sysdescr_ptr,len); break; case 2: /* sysObjectID */ objectidncpy((s32_t*)value,(s32_t*)sysobjid.id,len / sizeof(s32_t)); break; case 3: /* sysUpTime */ { u32_t *uint_ptr = value; *uint_ptr = sysuptime; } break; case 4: /* sysContact */ ocstrncpy(value,syscontact_ptr,len); break; case 5: /* sysName */ ocstrncpy(value,sysname_ptr,len); break; case 6: /* sysLocation */ ocstrncpy(value,syslocation_ptr,len); break; case 7: /* sysServices */ { s32_t *sint_ptr = value; *sint_ptr = sysservices; } break; }; } static u8_t system_set_test(struct obj_def *od, u16_t len, void *value) { u8_t id, set_ok; if (value) {} set_ok = 0; id = od->id_inst_ptr[0]; switch (id) { case 4: /* sysContact */ if ((syscontact_ptr != syscontact_default) && (len <= 255)) { set_ok = 1; } break; case 5: /* sysName */ if ((sysname_ptr != sysname_default) && (len <= 255)) { set_ok = 1; } break; case 6: /* sysLocation */ if ((syslocation_ptr != syslocation_default) && (len <= 255)) { set_ok = 1; } break; }; return set_ok; } static void system_set_value(struct obj_def *od, u16_t len, void *value) { u8_t id; id = od->id_inst_ptr[0]; switch (id) { case 4: /* sysContact */ ocstrncpy(syscontact_ptr,value,len); *syscontact_len_ptr = len; break; case 5: /* sysName */ ocstrncpy(sysname_ptr,value,len); *sysname_len_ptr = len; break; case 6: /* sysLocation */ ocstrncpy(syslocation_ptr,value,len); *syslocation_len_ptr = len; break; }; } /** * Returns interfaces.ifnumber object definition. * * @param ident_len the address length (2) * @param ident points to objectname.index * @param od points to object definition. */ static void interfaces_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("interfaces_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } /** * Returns interfaces.ifnumber object value. * * @param ident_len the address length (2) * @param ident points to objectname.0 (object id trailer) * @param len return value space (in bytes) * @param value points to (varbind) space to copy value into. */ static void interfaces_get_value(struct obj_def *od, u16_t len, void *value) { if (len){} if (od->id_inst_ptr[0] == 1) { s32_t *sint_ptr = value; *sint_ptr = iflist_root.count; } } /** * Returns ifentry object definitions. * * @param ident_len the address length (2) * @param ident points to objectname.index * @param od points to object definition. */ static void ifentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { u8_t id; /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def ifentry.%"U16_F"\n",(u16_t)id)); switch (id) { case 1: /* ifIndex */ case 3: /* ifType */ case 4: /* ifMtu */ case 8: /* ifOperStatus */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 2: /* ifDescr */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); /** @todo this should be some sort of sizeof(struct netif.name) */ od->v_len = 2; break; case 5: /* ifSpeed */ case 21: /* ifOutQLen */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE); od->v_len = sizeof(u32_t); break; case 6: /* ifPhysAddress */ { struct netif *netif; snmp_ifindextonetif(ident[1], &netif); od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = netif->hwaddr_len; } break; case 7: /* ifAdminStatus */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 9: /* ifLastChange */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_TIMETICKS); od->v_len = sizeof(u32_t); break; case 10: /* ifInOctets */ case 11: /* ifInUcastPkts */ case 12: /* ifInNUcastPkts */ case 13: /* ifInDiscarts */ case 14: /* ifInErrors */ case 15: /* ifInUnkownProtos */ case 16: /* ifOutOctets */ case 17: /* ifOutUcastPkts */ case 18: /* ifOutNUcastPkts */ case 19: /* ifOutDiscarts */ case 20: /* ifOutErrors */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); break; case 22: /* ifSpecific */ /** @note returning zeroDotZero (0.0) no media specific MIB support */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); od->v_len = ifspecific.len * sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("ifentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("ifentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } /** * Returns ifentry object value. * * @param ident_len the address length (2) * @param ident points to objectname.0 (object id trailer) * @param len return value space (in bytes) * @param value points to (varbind) space to copy value into. */ static void ifentry_get_value(struct obj_def *od, u16_t len, void *value) { struct netif *netif; u8_t id; snmp_ifindextonetif(od->id_inst_ptr[1], &netif); id = od->id_inst_ptr[0]; switch (id) { case 1: /* ifIndex */ { s32_t *sint_ptr = value; *sint_ptr = od->id_inst_ptr[1]; } break; case 2: /* ifDescr */ ocstrncpy(value,(u8_t*)netif->name,len); break; case 3: /* ifType */ { s32_t *sint_ptr = value; *sint_ptr = netif->link_type; } break; case 4: /* ifMtu */ { s32_t *sint_ptr = value; *sint_ptr = netif->mtu; } break; case 5: /* ifSpeed */ { u32_t *uint_ptr = value; *uint_ptr = netif->link_speed; } break; case 6: /* ifPhysAddress */ ocstrncpy(value,netif->hwaddr,len); break; case 7: /* ifAdminStatus */ case 8: /* ifOperStatus */ { s32_t *sint_ptr = value; if (netif_is_up(netif)) { *sint_ptr = 1; } else { *sint_ptr = 2; } } break; case 9: /* ifLastChange */ { u32_t *uint_ptr = value; *uint_ptr = netif->ts; } break; case 10: /* ifInOctets */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifinoctets; } break; case 11: /* ifInUcastPkts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifinucastpkts; } break; case 12: /* ifInNUcastPkts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifinnucastpkts; } break; case 13: /* ifInDiscarts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifindiscards; } break; case 14: /* ifInErrors */ case 15: /* ifInUnkownProtos */ /** @todo add these counters! */ { u32_t *uint_ptr = value; *uint_ptr = 0; } break; case 16: /* ifOutOctets */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifoutoctets; } break; case 17: /* ifOutUcastPkts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifoutucastpkts; } break; case 18: /* ifOutNUcastPkts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifoutnucastpkts; } break; case 19: /* ifOutDiscarts */ { u32_t *uint_ptr = value; *uint_ptr = netif->ifoutdiscards; } break; case 20: /* ifOutErrors */ /** @todo add this counter! */ { u32_t *uint_ptr = value; *uint_ptr = 0; } break; case 21: /* ifOutQLen */ /** @todo figure out if this must be 0 (no queue) or 1? */ { u32_t *uint_ptr = value; *uint_ptr = 0; } break; case 22: /* ifSpecific */ objectidncpy((s32_t*)value,(s32_t*)ifspecific.id,len / sizeof(s32_t)); break; }; } /** * Returns atentry object definitions. * * @param ident_len the address length (6) * @param ident points to objectname.atifindex.atnetaddress * @param od points to object definition. */ static void atentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (5) */ ident_len += 5; ident -= 5; if (ident_len == 6) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; switch (ident[0]) { case 1: /* atIfIndex */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 2: /* atPhysAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = sizeof(struct eth_addr); break; case 3: /* atNetAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("atentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; } } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("atentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void atentry_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; struct eth_addr* ethaddr_ret; struct ip_addr* ipaddr_ret; struct ip_addr ip; struct netif *netif; if (len) {} snmp_ifindextonetif(od->id_inst_ptr[1], &netif); snmp_oidtoip(&od->id_inst_ptr[2], &ip); ip.addr = htonl(ip.addr); if (etharp_find_addr(netif, &ip, &ethaddr_ret, &ipaddr_ret) > -1) { id = od->id_inst_ptr[0]; switch (id) { case 1: /* atIfIndex */ { s32_t *sint_ptr = value; *sint_ptr = od->id_inst_ptr[1]; } break; case 2: /* atPhysAddress */ { struct eth_addr *dst = value; *dst = *ethaddr_ret; } break; case 3: /* atNetAddress */ { struct ip_addr *dst = value; *dst = *ipaddr_ret; } break; } } } static void ip_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { u8_t id; /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def ip.%"U16_F".0\n",(u16_t)id)); switch (id) { case 1: /* ipForwarding */ case 2: /* ipDefaultTTL */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 3: /* ipInReceives */ case 4: /* ipInHdrErrors */ case 5: /* ipInAddrErrors */ case 6: /* ipForwDatagrams */ case 7: /* ipInUnknownProtos */ case 8: /* ipInDiscards */ case 9: /* ipInDelivers */ case 10: /* ipOutRequests */ case 11: /* ipOutDiscards */ case 12: /* ipOutNoRoutes */ case 14: /* ipReasmReqds */ case 15: /* ipReasmOKs */ case 16: /* ipReasmFails */ case 17: /* ipFragOKs */ case 18: /* ipFragFails */ case 19: /* ipFragCreates */ case 23: /* ipRoutingDiscards */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); break; case 13: /* ipReasmTimeout */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void ip_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; if (len) {} id = od->id_inst_ptr[0]; switch (id) { case 1: /* ipForwarding */ { s32_t *sint_ptr = value; #if IP_FORWARD /* forwarding */ *sint_ptr = 1; #else /* not-forwarding */ *sint_ptr = 2; #endif } break; case 2: /* ipDefaultTTL */ { s32_t *sint_ptr = value; *sint_ptr = IP_DEFAULT_TTL; } break; case 3: /* ipInReceives */ { u32_t *uint_ptr = value; *uint_ptr = ipinreceives; } break; case 4: /* ipInHdrErrors */ { u32_t *uint_ptr = value; *uint_ptr = ipinhdrerrors; } break; case 5: /* ipInAddrErrors */ { u32_t *uint_ptr = value; *uint_ptr = ipinaddrerrors; } break; case 6: /* ipForwDatagrams */ { u32_t *uint_ptr = value; *uint_ptr = ipforwdatagrams; } break; case 7: /* ipInUnknownProtos */ { u32_t *uint_ptr = value; *uint_ptr = ipinunknownprotos; } break; case 8: /* ipInDiscards */ { u32_t *uint_ptr = value; *uint_ptr = ipindiscards; } break; case 9: /* ipInDelivers */ { u32_t *uint_ptr = value; *uint_ptr = ipindelivers; } break; case 10: /* ipOutRequests */ { u32_t *uint_ptr = value; *uint_ptr = ipoutrequests; } break; case 11: /* ipOutDiscards */ { u32_t *uint_ptr = value; *uint_ptr = ipoutdiscards; } break; case 12: /* ipOutNoRoutes */ { u32_t *uint_ptr = value; *uint_ptr = ipoutnoroutes; } break; case 13: /* ipReasmTimeout */ { s32_t *sint_ptr = value; #if IP_REASSEMBLY *sint_ptr = IP_REASS_MAXAGE; #else *sint_ptr = 0; #endif } break; case 14: /* ipReasmReqds */ { u32_t *uint_ptr = value; *uint_ptr = ipreasmreqds; } break; case 15: /* ipReasmOKs */ { u32_t *uint_ptr = value; *uint_ptr = ipreasmoks; } break; case 16: /* ipReasmFails */ { u32_t *uint_ptr = value; *uint_ptr = ipreasmfails; } break; case 17: /* ipFragOKs */ { u32_t *uint_ptr = value; *uint_ptr = ipfragoks; } break; case 18: /* ipFragFails */ { u32_t *uint_ptr = value; *uint_ptr = ipfragfails; } break; case 19: /* ipFragCreates */ { u32_t *uint_ptr = value; *uint_ptr = ipfragcreates; } break; case 23: /* ipRoutingDiscards */ /** @todo can lwIP discard routes at all?? hardwire this to 0?? */ { u32_t *uint_ptr = value; *uint_ptr = iproutingdiscards; } break; }; } /** * Test ip object value before setting. * * @param od is the object definition * @param len return value space (in bytes) * @param value points to (varbind) space to copy value from. * * @note we allow set if the value matches the hardwired value, * otherwise return badvalue. */ static u8_t ip_set_test(struct obj_def *od, u16_t len, void *value) { u8_t id, set_ok; s32_t *sint_ptr = value; if (len) {} set_ok = 0; id = od->id_inst_ptr[0]; switch (id) { case 1: /* ipForwarding */ #if IP_FORWARD /* forwarding */ if (*sint_ptr == 1) #else /* not-forwarding */ if (*sint_ptr == 2) #endif { set_ok = 1; } break; case 2: /* ipDefaultTTL */ if (*sint_ptr == IP_DEFAULT_TTL) { set_ok = 1; } break; }; return set_ok; } static void ip_addrentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (4) */ ident_len += 4; ident -= 4; if (ident_len == 5) { u8_t id; od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; switch (id) { case 1: /* ipAdEntAddr */ case 3: /* ipAdEntNetMask */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; case 2: /* ipAdEntIfIndex */ case 4: /* ipAdEntBcastAddr */ case 5: /* ipAdEntReasmMaxSize */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_addrentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; } } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_addrentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void ip_addrentry_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; u16_t ifidx; struct ip_addr ip; struct netif *netif = netif_list; if (len) {} snmp_oidtoip(&od->id_inst_ptr[1], &ip); ip.addr = htonl(ip.addr); ifidx = 0; while ((netif != NULL) && !ip_addr_cmp(&ip, &netif->ip_addr)) { netif = netif->next; ifidx++; } if (netif != NULL) { id = od->id_inst_ptr[0]; switch (id) { case 1: /* ipAdEntAddr */ { struct ip_addr *dst = value; *dst = netif->ip_addr; } break; case 2: /* ipAdEntIfIndex */ { s32_t *sint_ptr = value; *sint_ptr = ifidx + 1; } break; case 3: /* ipAdEntNetMask */ { struct ip_addr *dst = value; *dst = netif->netmask; } break; case 4: /* ipAdEntBcastAddr */ { s32_t *sint_ptr = value; /* lwIP oddity, there's no broadcast address in the netif we can rely on */ *sint_ptr = ip_addr_broadcast.addr & 1; } break; case 5: /* ipAdEntReasmMaxSize */ { s32_t *sint_ptr = value; #if IP_REASSEMBLY *sint_ptr = (IP_HLEN + IP_REASS_BUFSIZE); #else /** @todo returning MTU would be a bad thing and returning a wild guess like '576' isn't good either */ *sint_ptr = 0; #endif } break; } } } /** * @note * lwIP IP routing is currently using the network addresses in netif_list. * if no suitable network IP is found in netif_list, the default_netif is used. */ static void ip_rteentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { u8_t id; /* return to object name, adding index depth (4) */ ident_len += 4; ident -= 4; if (ident_len == 5) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; switch (id) { case 1: /* ipRouteDest */ case 7: /* ipRouteNextHop */ case 11: /* ipRouteMask */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; case 2: /* ipRouteIfIndex */ case 3: /* ipRouteMetric1 */ case 4: /* ipRouteMetric2 */ case 5: /* ipRouteMetric3 */ case 6: /* ipRouteMetric4 */ case 8: /* ipRouteType */ case 10: /* ipRouteAge */ case 12: /* ipRouteMetric5 */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 9: /* ipRouteProto */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 13: /* ipRouteInfo */ /** @note returning zeroDotZero (0.0) no routing protocol specific MIB */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OBJ_ID); od->v_len = iprouteinfo.len * sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_rteentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; } } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_rteentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void ip_rteentry_get_value(struct obj_def *od, u16_t len, void *value) { struct netif *netif; struct ip_addr dest; s32_t *ident; u8_t id; ident = od->id_inst_ptr; snmp_oidtoip(&ident[1], &dest); dest.addr = htonl(dest.addr); if (dest.addr == 0) { /* ip_route() uses default netif for default route */ netif = netif_default; } else { /* not using ip_route(), need exact match! */ netif = netif_list; while ((netif != NULL) && !ip_addr_netcmp(&dest, &(netif->ip_addr), &(netif->netmask)) ) { netif = netif->next; } } if (netif != NULL) { id = ident[0]; switch (id) { case 1: /* ipRouteDest */ { struct ip_addr *dst = value; if (dest.addr == 0) { /* default rte has 0.0.0.0 dest */ dst->addr = 0; } else { /* netifs have netaddress dest */ dst->addr = netif->ip_addr.addr & netif->netmask.addr; } } break; case 2: /* ipRouteIfIndex */ { s32_t *sint_ptr = value; snmp_netiftoifindex(netif, sint_ptr); } break; case 3: /* ipRouteMetric1 */ { s32_t *sint_ptr = value; if (dest.addr == 0) { /* default rte has metric 1 */ *sint_ptr = 1; } else { /* other rtes have metric 0 */ *sint_ptr = 0; } } break; case 4: /* ipRouteMetric2 */ case 5: /* ipRouteMetric3 */ case 6: /* ipRouteMetric4 */ case 12: /* ipRouteMetric5 */ { s32_t *sint_ptr = value; /* not used */ *sint_ptr = -1; } break; case 7: /* ipRouteNextHop */ { struct ip_addr *dst = value; if (dest.addr == 0) { /* default rte: gateway */ *dst = netif->gw; } else { /* other rtes: netif ip_addr */ *dst = netif->ip_addr; } } break; case 8: /* ipRouteType */ { s32_t *sint_ptr = value; if (dest.addr == 0) { /* default rte is indirect */ *sint_ptr = 4; } else { /* other rtes are direct */ *sint_ptr = 3; } } break; case 9: /* ipRouteProto */ { s32_t *sint_ptr = value; /* locally defined routes */ *sint_ptr = 2; } break; case 10: /* ipRouteAge */ { s32_t *sint_ptr = value; /** @todo (sysuptime - timestamp last change) / 100 @see snmp_insert_iprteidx_tree() */ *sint_ptr = 0; } break; case 11: /* ipRouteMask */ { struct ip_addr *dst = value; if (dest.addr == 0) { /* default rte use 0.0.0.0 mask */ dst->addr = 0; } else { /* other rtes use netmask */ *dst = netif->netmask; } } break; case 13: /* ipRouteInfo */ objectidncpy((s32_t*)value,(s32_t*)iprouteinfo.id,len / sizeof(s32_t)); break; } } } static void ip_ntomentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (5) */ ident_len += 5; ident -= 5; if (ident_len == 6) { u8_t id; od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; switch (id) { case 1: /* ipNetToMediaIfIndex */ case 4: /* ipNetToMediaType */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 2: /* ipNetToMediaPhysAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_OC_STR); od->v_len = sizeof(struct eth_addr); break; case 3: /* ipNetToMediaNetAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_ntomentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; } } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("ip_ntomentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void ip_ntomentry_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; struct eth_addr* ethaddr_ret; struct ip_addr* ipaddr_ret; struct ip_addr ip; struct netif *netif; if (len) {} snmp_ifindextonetif(od->id_inst_ptr[1], &netif); snmp_oidtoip(&od->id_inst_ptr[2], &ip); ip.addr = htonl(ip.addr); if (etharp_find_addr(netif, &ip, &ethaddr_ret, &ipaddr_ret) > -1) { id = od->id_inst_ptr[0]; switch (id) { case 1: /* ipNetToMediaIfIndex */ { s32_t *sint_ptr = value; *sint_ptr = od->id_inst_ptr[1]; } break; case 2: /* ipNetToMediaPhysAddress */ { struct eth_addr *dst = value; *dst = *ethaddr_ret; } break; case 3: /* ipNetToMediaNetAddress */ { struct ip_addr *dst = value; *dst = *ipaddr_ret; } break; case 4: /* ipNetToMediaType */ { s32_t *sint_ptr = value; /* dynamic (?) */ *sint_ptr = 3; } break; } } } static void icmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if ((ident_len == 2) && (ident[0] > 0) && (ident[0] < 27)) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("icmp_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void icmp_get_value(struct obj_def *od, u16_t len, void *value) { u32_t *uint_ptr = value; u8_t id; if (len){} id = od->id_inst_ptr[0]; switch (id) { case 1: /* icmpInMsgs */ *uint_ptr = icmpinmsgs; break; case 2: /* icmpInErrors */ *uint_ptr = icmpinerrors; break; case 3: /* icmpInDestUnreachs */ *uint_ptr = icmpindestunreachs; break; case 4: /* icmpInTimeExcds */ *uint_ptr = icmpintimeexcds; break; case 5: /* icmpInParmProbs */ *uint_ptr = icmpinparmprobs; break; case 6: /* icmpInSrcQuenchs */ *uint_ptr = icmpinsrcquenchs; break; case 7: /* icmpInRedirects */ *uint_ptr = icmpinredirects; break; case 8: /* icmpInEchos */ *uint_ptr = icmpinechos; break; case 9: /* icmpInEchoReps */ *uint_ptr = icmpinechoreps; break; case 10: /* icmpInTimestamps */ *uint_ptr = icmpintimestamps; break; case 11: /* icmpInTimestampReps */ *uint_ptr = icmpintimestampreps; break; case 12: /* icmpInAddrMasks */ *uint_ptr = icmpinaddrmasks; break; case 13: /* icmpInAddrMaskReps */ *uint_ptr = icmpinaddrmaskreps; break; case 14: /* icmpOutMsgs */ *uint_ptr = icmpoutmsgs; break; case 15: /* icmpOutErrors */ *uint_ptr = icmpouterrors; break; case 16: /* icmpOutDestUnreachs */ *uint_ptr = icmpoutdestunreachs; break; case 17: /* icmpOutTimeExcds */ *uint_ptr = icmpouttimeexcds; break; case 18: /* icmpOutParmProbs */ *uint_ptr = icmpoutparmprobs; break; case 19: /* icmpOutSrcQuenchs */ *uint_ptr = icmpoutsrcquenchs; break; case 20: /* icmpOutRedirects */ *uint_ptr = icmpoutredirects; break; case 21: /* icmpOutEchos */ *uint_ptr = icmpoutechos; break; case 22: /* icmpOutEchoReps */ *uint_ptr = icmpoutechoreps; break; case 23: /* icmpOutTimestamps */ *uint_ptr = icmpouttimestamps; break; case 24: /* icmpOutTimestampReps */ *uint_ptr = icmpouttimestampreps; break; case 25: /* icmpOutAddrMasks */ *uint_ptr = icmpoutaddrmasks; break; case 26: /* icmpOutAddrMaskReps */ *uint_ptr = icmpoutaddrmaskreps; break; } } #if LWIP_TCP /** @todo tcp grp */ static void tcp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { u8_t id; /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def tcp.%"U16_F".0\n",(u16_t)id)); switch (id) { case 1: /* tcpRtoAlgorithm */ case 2: /* tcpRtoMin */ case 3: /* tcpRtoMax */ case 4: /* tcpMaxConn */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 5: /* tcpActiveOpens */ case 6: /* tcpPassiveOpens */ case 7: /* tcpAttemptFails */ case 8: /* tcpEstabResets */ case 10: /* tcpInSegs */ case 11: /* tcpOutSegs */ case 12: /* tcpRetransSegs */ case 14: /* tcpInErrs */ case 15: /* tcpOutRsts */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); break; case 9: /* tcpCurrEstab */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_GAUGE); od->v_len = sizeof(u32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcp_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcp_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void tcp_get_value(struct obj_def *od, u16_t len, void *value) { u32_t *uint_ptr = value; s32_t *sint_ptr = value; u8_t id; if (len){} id = od->id_inst_ptr[0]; switch (id) { case 1: /* tcpRtoAlgorithm, vanj(4) */ *sint_ptr = 4; break; case 2: /* tcpRtoMin */ /* @todo not the actual value, a guess, needs to be calculated */ *sint_ptr = 1000; break; case 3: /* tcpRtoMax */ /* @todo not the actual value, a guess, needs to be calculated */ *sint_ptr = 60000; break; case 4: /* tcpMaxConn */ *sint_ptr = MEMP_NUM_TCP_PCB; break; case 5: /* tcpActiveOpens */ *uint_ptr = tcpactiveopens; break; case 6: /* tcpPassiveOpens */ *uint_ptr = tcppassiveopens; break; case 7: /* tcpAttemptFails */ *uint_ptr = tcpattemptfails; break; case 8: /* tcpEstabResets */ *uint_ptr = tcpestabresets; break; case 9: /* tcpCurrEstab */ { u16_t tcpcurrestab = 0; struct tcp_pcb *pcb = tcp_active_pcbs; while (pcb != NULL) { if ((pcb->state == ESTABLISHED) || (pcb->state == CLOSE_WAIT)) { tcpcurrestab++; } pcb = pcb->next; } *uint_ptr = tcpcurrestab; } break; case 10: /* tcpInSegs */ *uint_ptr = tcpinsegs; break; case 11: /* tcpOutSegs */ *uint_ptr = tcpoutsegs; break; case 12: /* tcpRetransSegs */ *uint_ptr = tcpretranssegs; break; case 14: /* tcpInErrs */ *uint_ptr = tcpinerrs; break; case 15: /* tcpOutRsts */ *uint_ptr = tcpoutrsts; break; } } static void tcpconnentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (10) */ ident_len += 10; ident -= 10; if (ident_len == 11) { u8_t id; od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; LWIP_DEBUGF(SNMP_MIB_DEBUG,("get_object_def tcp.%"U16_F".0\n",(u16_t)id)); switch (id) { case 1: /* tcpConnState */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; case 2: /* tcpConnLocalAddress */ case 4: /* tcpConnRemAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; case 3: /* tcpConnLocalPort */ case 5: /* tcpConnRemPort */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcpconnentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("tcpconnentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; } } static void tcpconnentry_get_value(struct obj_def *od, u16_t len, void *value) { struct ip_addr lip, rip; u16_t lport, rport; s32_t *ident; ident = od->id_inst_ptr; snmp_oidtoip(&ident[1], &lip); lip.addr = htonl(lip.addr); lport = ident[5]; snmp_oidtoip(&ident[6], &rip); rip.addr = htonl(rip.addr); rport = ident[10]; /** @todo find matching PCB */ } #endif static void udp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if ((ident_len == 2) && (ident[0] > 0) && (ident[0] < 6)) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("udp_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void udp_get_value(struct obj_def *od, u16_t len, void *value) { u32_t *uint_ptr = value; u8_t id; if (len){} id = od->id_inst_ptr[0]; switch (id) { case 1: /* udpInDatagrams */ *uint_ptr = udpindatagrams; break; case 2: /* udpNoPorts */ *uint_ptr = udpnoports; break; case 3: /* udpInErrors */ *uint_ptr = udpinerrors; break; case 4: /* udpOutDatagrams */ *uint_ptr = udpoutdatagrams; break; } } static void udpentry_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (5) */ ident_len += 5; ident -= 5; if (ident_len == 6) { od->id_inst_len = ident_len; od->id_inst_ptr = ident; switch (ident[0]) { case 1: /* udpLocalAddress */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_IPADDR); od->v_len = 4; break; case 2: /* udpLocalPort */ od->instance = MIB_OBJECT_TAB; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("udpentry_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; } } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("udpentry_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void udpentry_get_value(struct obj_def *od, u16_t len, void *value) { u8_t id; struct udp_pcb *pcb; struct ip_addr ip; u16_t port; if (len){} snmp_oidtoip(&od->id_inst_ptr[1], &ip); ip.addr = htonl(ip.addr); port = od->id_inst_ptr[5]; pcb = udp_pcbs; while ((pcb != NULL) && !((pcb->local_ip.addr == ip.addr) && (pcb->local_port == port))) { pcb = pcb->next; } if (pcb != NULL) { id = od->id_inst_ptr[0]; switch (id) { case 1: /* udpLocalAddress */ { struct ip_addr *dst = value; *dst = pcb->local_ip; } break; case 2: /* udpLocalPort */ { s32_t *sint_ptr = value; *sint_ptr = pcb->local_port; } break; } } } static void snmp_get_object_def(u8_t ident_len, s32_t *ident, struct obj_def *od) { /* return to object name, adding index depth (1) */ ident_len += 1; ident -= 1; if (ident_len == 2) { u8_t id; od->id_inst_len = ident_len; od->id_inst_ptr = ident; id = ident[0]; switch (id) { case 1: /* snmpInPkts */ case 2: /* snmpOutPkts */ case 3: /* snmpInBadVersions */ case 4: /* snmpInBadCommunityNames */ case 5: /* snmpInBadCommunityUses */ case 6: /* snmpInASNParseErrs */ case 8: /* snmpInTooBigs */ case 9: /* snmpInNoSuchNames */ case 10: /* snmpInBadValues */ case 11: /* snmpInReadOnlys */ case 12: /* snmpInGenErrs */ case 13: /* snmpInTotalReqVars */ case 14: /* snmpInTotalSetVars */ case 15: /* snmpInGetRequests */ case 16: /* snmpInGetNexts */ case 17: /* snmpInSetRequests */ case 18: /* snmpInGetResponses */ case 19: /* snmpInTraps */ case 20: /* snmpOutTooBigs */ case 21: /* snmpOutNoSuchNames */ case 22: /* snmpOutBadValues */ case 24: /* snmpOutGenErrs */ case 25: /* snmpOutGetRequests */ case 26: /* snmpOutGetNexts */ case 27: /* snmpOutSetRequests */ case 28: /* snmpOutGetResponses */ case 29: /* snmpOutTraps */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_ONLY; od->asn_type = (SNMP_ASN1_APPLIC | SNMP_ASN1_PRIMIT | SNMP_ASN1_COUNTER); od->v_len = sizeof(u32_t); break; case 30: /* snmpEnableAuthenTraps */ od->instance = MIB_OBJECT_SCALAR; od->access = MIB_OBJECT_READ_WRITE; od->asn_type = (SNMP_ASN1_UNIV | SNMP_ASN1_PRIMIT | SNMP_ASN1_INTEG); od->v_len = sizeof(s32_t); break; default: LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_get_object_def: no such object\n")); od->instance = MIB_OBJECT_NONE; break; }; } else { LWIP_DEBUGF(SNMP_MIB_DEBUG,("snmp_get_object_def: no scalar\n")); od->instance = MIB_OBJECT_NONE; } } static void snmp_get_value(struct obj_def *od, u16_t len, void *value) { u32_t *uint_ptr = value; u8_t id; if (len){} id = od->id_inst_ptr[0]; switch (id) { case 1: /* snmpInPkts */ *uint_ptr = snmpinpkts; break; case 2: /* snmpOutPkts */ *uint_ptr = snmpoutpkts; break; case 3: /* snmpInBadVersions */ *uint_ptr = snmpinbadversions; break; case 4: /* snmpInBadCommunityNames */ *uint_ptr = snmpinbadcommunitynames; break; case 5: /* snmpInBadCommunityUses */ *uint_ptr = snmpinbadcommunityuses; break; case 6: /* snmpInASNParseErrs */ *uint_ptr = snmpinasnparseerrs; break; case 8: /* snmpInTooBigs */ *uint_ptr = snmpintoobigs; break; case 9: /* snmpInNoSuchNames */ *uint_ptr = snmpinnosuchnames; break; case 10: /* snmpInBadValues */ *uint_ptr = snmpinbadvalues; break; case 11: /* snmpInReadOnlys */ *uint_ptr = snmpinreadonlys; break; case 12: /* snmpInGenErrs */ *uint_ptr = snmpingenerrs; break; case 13: /* snmpInTotalReqVars */ *uint_ptr = snmpintotalreqvars; break; case 14: /* snmpInTotalSetVars */ *uint_ptr = snmpintotalsetvars; break; case 15: /* snmpInGetRequests */ *uint_ptr = snmpingetrequests; break; case 16: /* snmpInGetNexts */ *uint_ptr = snmpingetnexts; break; case 17: /* snmpInSetRequests */ *uint_ptr = snmpinsetrequests; break; case 18: /* snmpInGetResponses */ *uint_ptr = snmpingetresponses; break; case 19: /* snmpInTraps */ *uint_ptr = snmpintraps; break; case 20: /* snmpOutTooBigs */ *uint_ptr = snmpouttoobigs; break; case 21: /* snmpOutNoSuchNames */ *uint_ptr = snmpoutnosuchnames; break; case 22: /* snmpOutBadValues */ *uint_ptr = snmpoutbadvalues; break; case 24: /* snmpOutGenErrs */ *uint_ptr = snmpoutgenerrs; break; case 25: /* snmpOutGetRequests */ *uint_ptr = snmpoutgetrequests; break; case 26: /* snmpOutGetNexts */ *uint_ptr = snmpoutgetnexts; break; case 27: /* snmpOutSetRequests */ *uint_ptr = snmpoutsetrequests; break; case 28: /* snmpOutGetResponses */ *uint_ptr = snmpoutgetresponses; break; case 29: /* snmpOutTraps */ *uint_ptr = snmpouttraps; break; case 30: /* snmpEnableAuthenTraps */ *uint_ptr = *snmpenableauthentraps_ptr; break; }; } /** * Test snmp object value before setting. * * @param od is the object definition * @param len return value space (in bytes) * @param value points to (varbind) space to copy value from. */ static u8_t snmp_set_test(struct obj_def *od, u16_t len, void *value) { u8_t id, set_ok; if (len) {} set_ok = 0; id = od->id_inst_ptr[0]; if (id == 30) { /* snmpEnableAuthenTraps */ s32_t *sint_ptr = value; if (snmpenableauthentraps_ptr != &snmpenableauthentraps_default) { /* we should have writable non-volatile mem here */ if ((*sint_ptr == 1) || (*sint_ptr == 2)) { set_ok = 1; } } else { /* const or hardwired value */ if (*sint_ptr == snmpenableauthentraps_default) { set_ok = 1; } } } return set_ok; } static void snmp_set_value(struct obj_def *od, u16_t len, void *value) { u8_t id; if (len) {} id = od->id_inst_ptr[0]; if (id == 30) { /* snmpEnableAuthenTraps */ s32_t *sint_ptr = value; *snmpenableauthentraps_ptr = *sint_ptr; } } #endif /* LWIP_SNMP */
mit
zecke/old-pharo-vm-sctp
platforms/Cross/plugins/FloatMathPlugin/fdlibm/e_j1.c
24
15903
/* @(#)e_j1.c 1.3 95/01/18 */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ /* __ieee754_j1(x), __ieee754_y1(x) * Bessel function of the first and second kinds of order zero. * Method -- j1(x): * 1. For tiny x, we use j1(x) = x/2 - x^3/16 + x^5/384 - ... * 2. Reduce x to |x| since j1(x)=-j1(-x), and * for x in (0,2) * j1(x) = x/2 + x*z*R0/S0, where z = x*x; * (precision: |j1/x - 1/2 - R0/S0 |<2**-61.51 ) * for x in (2,inf) * j1(x) = sqrt(2/(pi*x))*(p1(x)*cos(x1)-q1(x)*sin(x1)) * y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1)) * where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1) * as follow: * cos(x1) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) * = 1/sqrt(2) * (sin(x) - cos(x)) * sin(x1) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) * = -1/sqrt(2) * (sin(x) + cos(x)) * (To avoid cancellation, use * sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) * to compute the worse one.) * * 3 Special cases * j1(nan)= nan * j1(0) = 0 * j1(inf) = 0 * * Method -- y1(x): * 1. screen out x<=0 cases: y1(0)=-inf, y1(x<0)=NaN * 2. For x<2. * Since * y1(x) = 2/pi*(j1(x)*(ln(x/2)+Euler)-1/x-x/2+5/64*x^3-...) * therefore y1(x)-2/pi*j1(x)*ln(x)-1/x is an odd function. * We use the following function to approximate y1, * y1(x) = x*U(z)/V(z) + (2/pi)*(j1(x)*ln(x)-1/x), z= x^2 * where for x in [0,2] (abs err less than 2**-65.89) * U(z) = U0[0] + U0[1]*z + ... + U0[4]*z^4 * V(z) = 1 + v0[0]*z + ... + v0[4]*z^5 * Note: For tiny x, 1/x dominate y1 and hence * y1(tiny) = -2/pi/tiny, (choose tiny<2**-54) * 3. For x>=2. * y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x1)+q1(x)*cos(x1)) * where x1 = x-3*pi/4. It is better to compute sin(x1),cos(x1) * by method mentioned above. */ #include "fdlibm.h" #ifdef __STDC__ static double pone(double), qone(double); #else static double pone(), qone(); #endif #ifdef __STDC__ static const double #else static double #endif huge = 1e300, one = 1.0, invsqrtpi= 5.64189583547756279280e-01, /* 0x3FE20DD7, 0x50429B6D */ tpi = 6.36619772367581382433e-01, /* 0x3FE45F30, 0x6DC9C883 */ /* R0/S0 on [0,2] */ r00 = -6.25000000000000000000e-02, /* 0xBFB00000, 0x00000000 */ r01 = 1.40705666955189706048e-03, /* 0x3F570D9F, 0x98472C61 */ r02 = -1.59955631084035597520e-05, /* 0xBEF0C5C6, 0xBA169668 */ r03 = 4.96727999609584448412e-08, /* 0x3E6AAAFA, 0x46CA0BD9 */ s01 = 1.91537599538363460805e-02, /* 0x3F939D0B, 0x12637E53 */ s02 = 1.85946785588630915560e-04, /* 0x3F285F56, 0xB9CDF664 */ s03 = 1.17718464042623683263e-06, /* 0x3EB3BFF8, 0x333F8498 */ s04 = 5.04636257076217042715e-09, /* 0x3E35AC88, 0xC97DFF2C */ s05 = 1.23542274426137913908e-11; /* 0x3DAB2ACF, 0xCFB97ED8 */ static double zero = 0.0; #ifdef __STDC__ double __ieee754_j1(double x) #else double __ieee754_j1(x) double x; #endif { double z, s,c,ss,cc,r,u,v,y; int hx,ix; hx = __HI(x); ix = hx&0x7fffffff; if(ix>=0x7ff00000) return one/x; y = fabs(x); if(ix >= 0x40000000) { /* |x| >= 2.0 */ s = sin(y); c = cos(y); ss = -s-c; cc = s-c; if(ix<0x7fe00000) { /* make sure y+y not overflow */ z = cos(y+y); if ((s*c)>zero) cc = z/ss; else ss = z/cc; } /* * j1(x) = 1/sqrt(pi) * (P(1,x)*cc - Q(1,x)*ss) / sqrt(x) * y1(x) = 1/sqrt(pi) * (P(1,x)*ss + Q(1,x)*cc) / sqrt(x) */ if(ix>0x48000000) z = (invsqrtpi*cc)/sqrt(y); else { u = pone(y); v = qone(y); z = invsqrtpi*(u*cc-v*ss)/sqrt(y); } if(hx<0) return -z; else return z; } if(ix<0x3e400000) { /* |x|<2**-27 */ if(huge+x>one) return 0.5*x;/* inexact if x!=0 necessary */ } z = x*x; r = z*(r00+z*(r01+z*(r02+z*r03))); s = one+z*(s01+z*(s02+z*(s03+z*(s04+z*s05)))); r *= x; return(x*0.5+r/s); } #ifdef __STDC__ static const double U0[5] = { #else static double U0[5] = { #endif -1.96057090646238940668e-01, /* 0xBFC91866, 0x143CBC8A */ 5.04438716639811282616e-02, /* 0x3FA9D3C7, 0x76292CD1 */ -1.91256895875763547298e-03, /* 0xBF5F55E5, 0x4844F50F */ 2.35252600561610495928e-05, /* 0x3EF8AB03, 0x8FA6B88E */ -9.19099158039878874504e-08, /* 0xBE78AC00, 0x569105B8 */ }; #ifdef __STDC__ static const double V0[5] = { #else static double V0[5] = { #endif 1.99167318236649903973e-02, /* 0x3F94650D, 0x3F4DA9F0 */ 2.02552581025135171496e-04, /* 0x3F2A8C89, 0x6C257764 */ 1.35608801097516229404e-06, /* 0x3EB6C05A, 0x894E8CA6 */ 6.22741452364621501295e-09, /* 0x3E3ABF1D, 0x5BA69A86 */ 1.66559246207992079114e-11, /* 0x3DB25039, 0xDACA772A */ }; #ifdef __STDC__ double __ieee754_y1(double x) #else double __ieee754_y1(x) double x; #endif { double z, s,c,ss,cc,u,v; int hx,ix,lx; hx = __HI(x); ix = 0x7fffffff&hx; lx = __LO(x); /* if Y1(NaN) is NaN, Y1(-inf) is NaN, Y1(inf) is 0 */ if(ix>=0x7ff00000) return one/(x+x*x); if((ix|lx)==0) return -one/zero; if(hx<0) return zero/zero; if(ix >= 0x40000000) { /* |x| >= 2.0 */ s = sin(x); c = cos(x); ss = -s-c; cc = s-c; if(ix<0x7fe00000) { /* make sure x+x not overflow */ z = cos(x+x); if ((s*c)>zero) cc = z/ss; else ss = z/cc; } /* y1(x) = sqrt(2/(pi*x))*(p1(x)*sin(x0)+q1(x)*cos(x0)) * where x0 = x-3pi/4 * Better formula: * cos(x0) = cos(x)cos(3pi/4)+sin(x)sin(3pi/4) * = 1/sqrt(2) * (sin(x) - cos(x)) * sin(x0) = sin(x)cos(3pi/4)-cos(x)sin(3pi/4) * = -1/sqrt(2) * (cos(x) + sin(x)) * To avoid cancellation, use * sin(x) +- cos(x) = -cos(2x)/(sin(x) -+ cos(x)) * to compute the worse one. */ if(ix>0x48000000) z = (invsqrtpi*ss)/sqrt(x); else { u = pone(x); v = qone(x); z = invsqrtpi*(u*ss+v*cc)/sqrt(x); } return z; } if(ix<=0x3c900000) { /* x < 2**-54 */ return(-tpi/x); } z = x*x; u = U0[0]+z*(U0[1]+z*(U0[2]+z*(U0[3]+z*U0[4]))); v = one+z*(V0[0]+z*(V0[1]+z*(V0[2]+z*(V0[3]+z*V0[4])))); return(x*(u/v) + tpi*(__ieee754_j1(x)*__ieee754_log(x)-one/x)); } /* For x >= 8, the asymptotic expansions of pone is * 1 + 15/128 s^2 - 4725/2^15 s^4 - ..., where s = 1/x. * We approximate pone by * pone(x) = 1 + (R/S) * where R = pr0 + pr1*s^2 + pr2*s^4 + ... + pr5*s^10 * S = 1 + ps0*s^2 + ... + ps4*s^10 * and * | pone(x)-1-R/S | <= 2 ** ( -60.06) */ #ifdef __STDC__ static const double pr8[6] = { /* for x in [inf, 8]=1/[0,0.125] */ #else static double pr8[6] = { /* for x in [inf, 8]=1/[0,0.125] */ #endif 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ 1.17187499999988647970e-01, /* 0x3FBDFFFF, 0xFFFFFCCE */ 1.32394806593073575129e+01, /* 0x402A7A9D, 0x357F7FCE */ 4.12051854307378562225e+02, /* 0x4079C0D4, 0x652EA590 */ 3.87474538913960532227e+03, /* 0x40AE457D, 0xA3A532CC */ 7.91447954031891731574e+03, /* 0x40BEEA7A, 0xC32782DD */ }; #ifdef __STDC__ static const double ps8[5] = { #else static double ps8[5] = { #endif 1.14207370375678408436e+02, /* 0x405C8D45, 0x8E656CAC */ 3.65093083420853463394e+03, /* 0x40AC85DC, 0x964D274F */ 3.69562060269033463555e+04, /* 0x40E20B86, 0x97C5BB7F */ 9.76027935934950801311e+04, /* 0x40F7D42C, 0xB28F17BB */ 3.08042720627888811578e+04, /* 0x40DE1511, 0x697A0B2D */ }; #ifdef __STDC__ static const double pr5[6] = { /* for x in [8,4.5454]=1/[0.125,0.22001] */ #else static double pr5[6] = { /* for x in [8,4.5454]=1/[0.125,0.22001] */ #endif 1.31990519556243522749e-11, /* 0x3DAD0667, 0xDAE1CA7D */ 1.17187493190614097638e-01, /* 0x3FBDFFFF, 0xE2C10043 */ 6.80275127868432871736e+00, /* 0x401B3604, 0x6E6315E3 */ 1.08308182990189109773e+02, /* 0x405B13B9, 0x452602ED */ 5.17636139533199752805e+02, /* 0x40802D16, 0xD052D649 */ 5.28715201363337541807e+02, /* 0x408085B8, 0xBB7E0CB7 */ }; #ifdef __STDC__ static const double ps5[5] = { #else static double ps5[5] = { #endif 5.92805987221131331921e+01, /* 0x404DA3EA, 0xA8AF633D */ 9.91401418733614377743e+02, /* 0x408EFB36, 0x1B066701 */ 5.35326695291487976647e+03, /* 0x40B4E944, 0x5706B6FB */ 7.84469031749551231769e+03, /* 0x40BEA4B0, 0xB8A5BB15 */ 1.50404688810361062679e+03, /* 0x40978030, 0x036F5E51 */ }; #ifdef __STDC__ static const double pr3[6] = { #else static double pr3[6] = {/* for x in [4.547,2.8571]=1/[0.2199,0.35001] */ #endif 3.02503916137373618024e-09, /* 0x3E29FC21, 0xA7AD9EDD */ 1.17186865567253592491e-01, /* 0x3FBDFFF5, 0x5B21D17B */ 3.93297750033315640650e+00, /* 0x400F76BC, 0xE85EAD8A */ 3.51194035591636932736e+01, /* 0x40418F48, 0x9DA6D129 */ 9.10550110750781271918e+01, /* 0x4056C385, 0x4D2C1837 */ 4.85590685197364919645e+01, /* 0x4048478F, 0x8EA83EE5 */ }; #ifdef __STDC__ static const double ps3[5] = { #else static double ps3[5] = { #endif 3.47913095001251519989e+01, /* 0x40416549, 0xA134069C */ 3.36762458747825746741e+02, /* 0x40750C33, 0x07F1A75F */ 1.04687139975775130551e+03, /* 0x40905B7C, 0x5037D523 */ 8.90811346398256432622e+02, /* 0x408BD67D, 0xA32E31E9 */ 1.03787932439639277504e+02, /* 0x4059F26D, 0x7C2EED53 */ }; #ifdef __STDC__ static const double pr2[6] = {/* for x in [2.8570,2]=1/[0.3499,0.5] */ #else static double pr2[6] = {/* for x in [2.8570,2]=1/[0.3499,0.5] */ #endif 1.07710830106873743082e-07, /* 0x3E7CE9D4, 0xF65544F4 */ 1.17176219462683348094e-01, /* 0x3FBDFF42, 0xBE760D83 */ 2.36851496667608785174e+00, /* 0x4002F2B7, 0xF98FAEC0 */ 1.22426109148261232917e+01, /* 0x40287C37, 0x7F71A964 */ 1.76939711271687727390e+01, /* 0x4031B1A8, 0x177F8EE2 */ 5.07352312588818499250e+00, /* 0x40144B49, 0xA574C1FE */ }; #ifdef __STDC__ static const double ps2[5] = { #else static double ps2[5] = { #endif 2.14364859363821409488e+01, /* 0x40356FBD, 0x8AD5ECDC */ 1.25290227168402751090e+02, /* 0x405F5293, 0x14F92CD5 */ 2.32276469057162813669e+02, /* 0x406D08D8, 0xD5A2DBD9 */ 1.17679373287147100768e+02, /* 0x405D6B7A, 0xDA1884A9 */ 8.36463893371618283368e+00, /* 0x4020BAB1, 0xF44E5192 */ }; #ifdef __STDC__ static double pone(double x) #else static double pone(x) double x; #endif { #ifdef __STDC__ const double *p,*q; #else double *p,*q; #endif double z,r,s; int ix; ix = 0x7fffffff&__HI(x); if(ix>=0x40200000) {p = pr8; q= ps8;} else if(ix>=0x40122E8B){p = pr5; q= ps5;} else if(ix>=0x4006DB6D){p = pr3; q= ps3;} else if(ix>=0x40000000){p = pr2; q= ps2;} z = one/(x*x); r = p[0]+z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))); s = one+z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*q[4])))); return one+ r/s; } /* For x >= 8, the asymptotic expansions of qone is * 3/8 s - 105/1024 s^3 - ..., where s = 1/x. * We approximate pone by * qone(x) = s*(0.375 + (R/S)) * where R = qr1*s^2 + qr2*s^4 + ... + qr5*s^10 * S = 1 + qs1*s^2 + ... + qs6*s^12 * and * | qone(x)/s -0.375-R/S | <= 2 ** ( -61.13) */ #ifdef __STDC__ static const double qr8[6] = { /* for x in [inf, 8]=1/[0,0.125] */ #else static double qr8[6] = { /* for x in [inf, 8]=1/[0,0.125] */ #endif 0.00000000000000000000e+00, /* 0x00000000, 0x00000000 */ -1.02539062499992714161e-01, /* 0xBFBA3FFF, 0xFFFFFDF3 */ -1.62717534544589987888e+01, /* 0xC0304591, 0xA26779F7 */ -7.59601722513950107896e+02, /* 0xC087BCD0, 0x53E4B576 */ -1.18498066702429587167e+04, /* 0xC0C724E7, 0x40F87415 */ -4.84385124285750353010e+04, /* 0xC0E7A6D0, 0x65D09C6A */ }; #ifdef __STDC__ static const double qs8[6] = { #else static double qs8[6] = { #endif 1.61395369700722909556e+02, /* 0x40642CA6, 0xDE5BCDE5 */ 7.82538599923348465381e+03, /* 0x40BE9162, 0xD0D88419 */ 1.33875336287249578163e+05, /* 0x4100579A, 0xB0B75E98 */ 7.19657723683240939863e+05, /* 0x4125F653, 0x72869C19 */ 6.66601232617776375264e+05, /* 0x412457D2, 0x7719AD5C */ -2.94490264303834643215e+05, /* 0xC111F969, 0x0EA5AA18 */ }; #ifdef __STDC__ static const double qr5[6] = { /* for x in [8,4.5454]=1/[0.125,0.22001] */ #else static double qr5[6] = { /* for x in [8,4.5454]=1/[0.125,0.22001] */ #endif -2.08979931141764104297e-11, /* 0xBDB6FA43, 0x1AA1A098 */ -1.02539050241375426231e-01, /* 0xBFBA3FFF, 0xCB597FEF */ -8.05644828123936029840e+00, /* 0xC0201CE6, 0xCA03AD4B */ -1.83669607474888380239e+02, /* 0xC066F56D, 0x6CA7B9B0 */ -1.37319376065508163265e+03, /* 0xC09574C6, 0x6931734F */ -2.61244440453215656817e+03, /* 0xC0A468E3, 0x88FDA79D */ }; #ifdef __STDC__ static const double qs5[6] = { #else static double qs5[6] = { #endif 8.12765501384335777857e+01, /* 0x405451B2, 0xFF5A11B2 */ 1.99179873460485964642e+03, /* 0x409F1F31, 0xE77BF839 */ 1.74684851924908907677e+04, /* 0x40D10F1F, 0x0D64CE29 */ 4.98514270910352279316e+04, /* 0x40E8576D, 0xAABAD197 */ 2.79480751638918118260e+04, /* 0x40DB4B04, 0xCF7C364B */ -4.71918354795128470869e+03, /* 0xC0B26F2E, 0xFCFFA004 */ }; #ifdef __STDC__ static const double qr3[6] = { #else static double qr3[6] = {/* for x in [4.547,2.8571]=1/[0.2199,0.35001] */ #endif -5.07831226461766561369e-09, /* 0xBE35CFA9, 0xD38FC84F */ -1.02537829820837089745e-01, /* 0xBFBA3FEB, 0x51AEED54 */ -4.61011581139473403113e+00, /* 0xC01270C2, 0x3302D9FF */ -5.78472216562783643212e+01, /* 0xC04CEC71, 0xC25D16DA */ -2.28244540737631695038e+02, /* 0xC06C87D3, 0x4718D55F */ -2.19210128478909325622e+02, /* 0xC06B66B9, 0x5F5C1BF6 */ }; #ifdef __STDC__ static const double qs3[6] = { #else static double qs3[6] = { #endif 4.76651550323729509273e+01, /* 0x4047D523, 0xCCD367E4 */ 6.73865112676699709482e+02, /* 0x40850EEB, 0xC031EE3E */ 3.38015286679526343505e+03, /* 0x40AA684E, 0x448E7C9A */ 5.54772909720722782367e+03, /* 0x40B5ABBA, 0xA61D54A6 */ 1.90311919338810798763e+03, /* 0x409DBC7A, 0x0DD4DF4B */ -1.35201191444307340817e+02, /* 0xC060E670, 0x290A311F */ }; #ifdef __STDC__ static const double qr2[6] = {/* for x in [2.8570,2]=1/[0.3499,0.5] */ #else static double qr2[6] = {/* for x in [2.8570,2]=1/[0.3499,0.5] */ #endif -1.78381727510958865572e-07, /* 0xBE87F126, 0x44C626D2 */ -1.02517042607985553460e-01, /* 0xBFBA3E8E, 0x9148B010 */ -2.75220568278187460720e+00, /* 0xC0060484, 0x69BB4EDA */ -1.96636162643703720221e+01, /* 0xC033A9E2, 0xC168907F */ -4.23253133372830490089e+01, /* 0xC04529A3, 0xDE104AAA */ -2.13719211703704061733e+01, /* 0xC0355F36, 0x39CF6E52 */ }; #ifdef __STDC__ static const double qs2[6] = { #else static double qs2[6] = { #endif 2.95333629060523854548e+01, /* 0x403D888A, 0x78AE64FF */ 2.52981549982190529136e+02, /* 0x406F9F68, 0xDB821CBA */ 7.57502834868645436472e+02, /* 0x4087AC05, 0xCE49A0F7 */ 7.39393205320467245656e+02, /* 0x40871B25, 0x48D4C029 */ 1.55949003336666123687e+02, /* 0x40637E5E, 0x3C3ED8D4 */ -4.95949898822628210127e+00, /* 0xC013D686, 0xE71BE86B */ }; #ifdef __STDC__ static double qone(double x) #else static double qone(x) double x; #endif { #ifdef __STDC__ const double *p,*q; #else double *p,*q; #endif double s,r,z; int ix; ix = 0x7fffffff&__HI(x); if(ix>=0x40200000) {p = qr8; q= qs8;} else if(ix>=0x40122E8B){p = qr5; q= qs5;} else if(ix>=0x4006DB6D){p = qr3; q= qs3;} else if(ix>=0x40000000){p = qr2; q= qs2;} z = one/(x*x); r = p[0]+z*(p[1]+z*(p[2]+z*(p[3]+z*(p[4]+z*p[5])))); s = one+z*(q[0]+z*(q[1]+z*(q[2]+z*(q[3]+z*(q[4]+z*q[5]))))); return (.375 + r/s)/x; }
mit
gentlemans/gentlemanly_engine
deps/freetype2/src/autofit/afhints.c
27
44217
/***************************************************************************/ /* */ /* afhints.c */ /* */ /* Auto-fitter hinting routines (body). */ /* */ /* Copyright 2003-2016 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include "afhints.h" #include "aferrors.h" #include FT_INTERNAL_CALC_H #include FT_INTERNAL_DEBUG_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_afhints /* Get new segment for given axis. */ FT_LOCAL_DEF( FT_Error ) af_axis_hints_new_segment( AF_AxisHints axis, FT_Memory memory, AF_Segment *asegment ) { FT_Error error = FT_Err_Ok; AF_Segment segment = NULL; if ( axis->num_segments < AF_SEGMENTS_EMBEDDED ) { if ( axis->segments == NULL ) { axis->segments = axis->embedded.segments; axis->max_segments = AF_SEGMENTS_EMBEDDED; } } else if ( axis->num_segments >= axis->max_segments ) { FT_Int old_max = axis->max_segments; FT_Int new_max = old_max; FT_Int big_max = (FT_Int)( FT_INT_MAX / sizeof ( *segment ) ); if ( old_max >= big_max ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } new_max += ( new_max >> 2 ) + 4; if ( new_max < old_max || new_max > big_max ) new_max = big_max; if ( axis->segments == axis->embedded.segments ) { if ( FT_NEW_ARRAY( axis->segments, new_max ) ) goto Exit; ft_memcpy( axis->segments, axis->embedded.segments, sizeof ( axis->embedded.segments ) ); } else { if ( FT_RENEW_ARRAY( axis->segments, old_max, new_max ) ) goto Exit; } axis->max_segments = new_max; } segment = axis->segments + axis->num_segments++; Exit: *asegment = segment; return error; } /* Get new edge for given axis, direction, and position, */ /* without initializing the edge itself. */ FT_LOCAL( FT_Error ) af_axis_hints_new_edge( AF_AxisHints axis, FT_Int fpos, AF_Direction dir, FT_Bool top_to_bottom_hinting, FT_Memory memory, AF_Edge *anedge ) { FT_Error error = FT_Err_Ok; AF_Edge edge = NULL; AF_Edge edges; if ( axis->num_edges < AF_EDGES_EMBEDDED ) { if ( axis->edges == NULL ) { axis->edges = axis->embedded.edges; axis->max_edges = AF_EDGES_EMBEDDED; } } else if ( axis->num_edges >= axis->max_edges ) { FT_Int old_max = axis->max_edges; FT_Int new_max = old_max; FT_Int big_max = (FT_Int)( FT_INT_MAX / sizeof ( *edge ) ); if ( old_max >= big_max ) { error = FT_THROW( Out_Of_Memory ); goto Exit; } new_max += ( new_max >> 2 ) + 4; if ( new_max < old_max || new_max > big_max ) new_max = big_max; if ( axis->edges == axis->embedded.edges ) { if ( FT_NEW_ARRAY( axis->edges, new_max ) ) goto Exit; ft_memcpy( axis->edges, axis->embedded.edges, sizeof ( axis->embedded.edges ) ); } else { if ( FT_RENEW_ARRAY( axis->edges, old_max, new_max ) ) goto Exit; } axis->max_edges = new_max; } edges = axis->edges; edge = edges + axis->num_edges; while ( edge > edges ) { if ( top_to_bottom_hinting ? ( edge[-1].fpos > fpos ) : ( edge[-1].fpos < fpos ) ) break; /* we want the edge with same position and minor direction */ /* to appear before those in the major one in the list */ if ( edge[-1].fpos == fpos && dir == axis->major_dir ) break; edge[0] = edge[-1]; edge--; } axis->num_edges++; Exit: *anedge = edge; return error; } #ifdef FT_DEBUG_AUTOFIT #include FT_CONFIG_STANDARD_LIBRARY_H /* The dump functions are used in the `ftgrid' demo program, too. */ #define AF_DUMP( varformat ) \ do \ { \ if ( to_stdout ) \ printf varformat; \ else \ FT_TRACE7( varformat ); \ } while ( 0 ) static const char* af_dir_str( AF_Direction dir ) { const char* result; switch ( dir ) { case AF_DIR_UP: result = "up"; break; case AF_DIR_DOWN: result = "down"; break; case AF_DIR_LEFT: result = "left"; break; case AF_DIR_RIGHT: result = "right"; break; default: result = "none"; } return result; } #define AF_INDEX_NUM( ptr, base ) (int)( (ptr) ? ( (ptr) - (base) ) : -1 ) static char* af_print_idx( char* p, int idx ) { if ( idx == -1 ) { p[0] = '-'; p[1] = '-'; p[2] = '\0'; } else ft_sprintf( p, "%d", idx ); return p; } static int af_get_segment_index( AF_GlyphHints hints, int point_idx, int dimension ) { AF_AxisHints axis = &hints->axis[dimension]; AF_Point point = hints->points + point_idx; AF_Segment segments = axis->segments; AF_Segment limit = segments + axis->num_segments; AF_Segment segment; for ( segment = segments; segment < limit; segment++ ) { if ( segment->first <= segment->last ) { if ( point >= segment->first && point <= segment->last ) break; } else { AF_Point p = segment->first; for (;;) { if ( point == p ) goto Exit; if ( p == segment->last ) break; p = p->next; } } } Exit: if ( segment == limit ) return -1; return (int)( segment - segments ); } static int af_get_edge_index( AF_GlyphHints hints, int segment_idx, int dimension ) { AF_AxisHints axis = &hints->axis[dimension]; AF_Edge edges = axis->edges; AF_Segment segment = axis->segments + segment_idx; return segment_idx == -1 ? -1 : AF_INDEX_NUM( segment->edge, edges ); } #ifdef __cplusplus extern "C" { #endif void af_glyph_hints_dump_points( AF_GlyphHints hints, FT_Bool to_stdout ) { AF_Point points = hints->points; AF_Point limit = points + hints->num_points; AF_Point* contour = hints->contours; AF_Point* climit = contour + hints->num_contours; AF_Point point; AF_DUMP(( "Table of points:\n" )); if ( hints->num_points ) AF_DUMP(( " index hedge hseg vedge vseg flags " " xorg yorg xscale yscale xfit yfit" )); else AF_DUMP(( " (none)\n" )); for ( point = points; point < limit; point++ ) { int point_idx = AF_INDEX_NUM( point, points ); int segment_idx_0 = af_get_segment_index( hints, point_idx, 0 ); int segment_idx_1 = af_get_segment_index( hints, point_idx, 1 ); char buf1[16], buf2[16], buf3[16], buf4[16]; /* insert extra newline at the beginning of a contour */ if ( contour < climit && *contour == point ) { AF_DUMP(( "\n" )); contour++; } AF_DUMP(( " %5d %5s %5s %5s %5s %s" " %5d %5d %7.2f %7.2f %7.2f %7.2f\n", point_idx, af_print_idx( buf1, af_get_edge_index( hints, segment_idx_1, 1 ) ), af_print_idx( buf2, segment_idx_1 ), af_print_idx( buf3, af_get_edge_index( hints, segment_idx_0, 0 ) ), af_print_idx( buf4, segment_idx_0 ), ( point->flags & AF_FLAG_NEAR ) ? " near " : ( point->flags & AF_FLAG_WEAK_INTERPOLATION ) ? " weak " : "strong", point->fx, point->fy, point->ox / 64.0, point->oy / 64.0, point->x / 64.0, point->y / 64.0 )); } AF_DUMP(( "\n" )); } #ifdef __cplusplus } #endif static const char* af_edge_flags_to_string( FT_UInt flags ) { static char temp[32]; int pos = 0; if ( flags & AF_EDGE_ROUND ) { ft_memcpy( temp + pos, "round", 5 ); pos += 5; } if ( flags & AF_EDGE_SERIF ) { if ( pos > 0 ) temp[pos++] = ' '; ft_memcpy( temp + pos, "serif", 5 ); pos += 5; } if ( pos == 0 ) return "normal"; temp[pos] = '\0'; return temp; } /* Dump the array of linked segments. */ #ifdef __cplusplus extern "C" { #endif void af_glyph_hints_dump_segments( AF_GlyphHints hints, FT_Bool to_stdout ) { FT_Int dimension; for ( dimension = 1; dimension >= 0; dimension-- ) { AF_AxisHints axis = &hints->axis[dimension]; AF_Point points = hints->points; AF_Edge edges = axis->edges; AF_Segment segments = axis->segments; AF_Segment limit = segments + axis->num_segments; AF_Segment seg; char buf1[16], buf2[16], buf3[16]; AF_DUMP(( "Table of %s segments:\n", dimension == AF_DIMENSION_HORZ ? "vertical" : "horizontal" )); if ( axis->num_segments ) AF_DUMP(( " index pos delta dir from to " " link serif edge" " height extra flags\n" )); else AF_DUMP(( " (none)\n" )); for ( seg = segments; seg < limit; seg++ ) AF_DUMP(( " %5d %5d %5d %5s %4d %4d" " %4s %5s %4s" " %6d %5d %11s\n", AF_INDEX_NUM( seg, segments ), seg->pos, seg->delta, af_dir_str( (AF_Direction)seg->dir ), AF_INDEX_NUM( seg->first, points ), AF_INDEX_NUM( seg->last, points ), af_print_idx( buf1, AF_INDEX_NUM( seg->link, segments ) ), af_print_idx( buf2, AF_INDEX_NUM( seg->serif, segments ) ), af_print_idx( buf3, AF_INDEX_NUM( seg->edge, edges ) ), seg->height, seg->height - ( seg->max_coord - seg->min_coord ), af_edge_flags_to_string( seg->flags ) )); AF_DUMP(( "\n" )); } } #ifdef __cplusplus } #endif /* Fetch number of segments. */ #ifdef __cplusplus extern "C" { #endif FT_Error af_glyph_hints_get_num_segments( AF_GlyphHints hints, FT_Int dimension, FT_Int* num_segments ) { AF_Dimension dim; AF_AxisHints axis; dim = ( dimension == 0 ) ? AF_DIMENSION_HORZ : AF_DIMENSION_VERT; axis = &hints->axis[dim]; *num_segments = axis->num_segments; return FT_Err_Ok; } #ifdef __cplusplus } #endif /* Fetch offset of segments into user supplied offset array. */ #ifdef __cplusplus extern "C" { #endif FT_Error af_glyph_hints_get_segment_offset( AF_GlyphHints hints, FT_Int dimension, FT_Int idx, FT_Pos *offset, FT_Bool *is_blue, FT_Pos *blue_offset ) { AF_Dimension dim; AF_AxisHints axis; AF_Segment seg; if ( !offset ) return FT_THROW( Invalid_Argument ); dim = ( dimension == 0 ) ? AF_DIMENSION_HORZ : AF_DIMENSION_VERT; axis = &hints->axis[dim]; if ( idx < 0 || idx >= axis->num_segments ) return FT_THROW( Invalid_Argument ); seg = &axis->segments[idx]; *offset = ( dim == AF_DIMENSION_HORZ ) ? seg->first->ox : seg->first->oy; if ( seg->edge ) *is_blue = (FT_Bool)( seg->edge->blue_edge != 0 ); else *is_blue = FALSE; if ( *is_blue ) *blue_offset = seg->edge->blue_edge->cur; else *blue_offset = 0; return FT_Err_Ok; } #ifdef __cplusplus } #endif /* Dump the array of linked edges. */ #ifdef __cplusplus extern "C" { #endif void af_glyph_hints_dump_edges( AF_GlyphHints hints, FT_Bool to_stdout ) { FT_Int dimension; for ( dimension = 1; dimension >= 0; dimension-- ) { AF_AxisHints axis = &hints->axis[dimension]; AF_Edge edges = axis->edges; AF_Edge limit = edges + axis->num_edges; AF_Edge edge; char buf1[16], buf2[16]; /* * note: AF_DIMENSION_HORZ corresponds to _vertical_ edges * since they have a constant X coordinate. */ if ( dimension == AF_DIMENSION_HORZ ) AF_DUMP(( "Table of %s edges (1px=%.2fu, 10u=%.2fpx):\n", "vertical", 65536.0 * 64.0 / hints->x_scale, 10.0 * hints->x_scale / 65536.0 / 64.0 )); else AF_DUMP(( "Table of %s edges (1px=%.2fu, 10u=%.2fpx):\n", "horizontal", 65536.0 * 64.0 / hints->y_scale, 10.0 * hints->y_scale / 65536.0 / 64.0 )); if ( axis->num_edges ) AF_DUMP(( " index pos dir link serif" " blue opos pos flags\n" )); else AF_DUMP(( " (none)\n" )); for ( edge = edges; edge < limit; edge++ ) AF_DUMP(( " %5d %7.2f %5s %4s %5s" " %c %7.2f %7.2f %11s\n", AF_INDEX_NUM( edge, edges ), (int)edge->opos / 64.0, af_dir_str( (AF_Direction)edge->dir ), af_print_idx( buf1, AF_INDEX_NUM( edge->link, edges ) ), af_print_idx( buf2, AF_INDEX_NUM( edge->serif, edges ) ), edge->blue_edge ? 'y' : 'n', edge->opos / 64.0, edge->pos / 64.0, af_edge_flags_to_string( edge->flags ) )); AF_DUMP(( "\n" )); } } #ifdef __cplusplus } #endif #undef AF_DUMP #endif /* !FT_DEBUG_AUTOFIT */ /* Compute the direction value of a given vector. */ FT_LOCAL_DEF( AF_Direction ) af_direction_compute( FT_Pos dx, FT_Pos dy ) { FT_Pos ll, ss; /* long and short arm lengths */ AF_Direction dir; /* candidate direction */ if ( dy >= dx ) { if ( dy >= -dx ) { dir = AF_DIR_UP; ll = dy; ss = dx; } else { dir = AF_DIR_LEFT; ll = -dx; ss = dy; } } else /* dy < dx */ { if ( dy >= -dx ) { dir = AF_DIR_RIGHT; ll = dx; ss = dy; } else { dir = AF_DIR_DOWN; ll = -dy; ss = dx; } } /* return no direction if arm lengths do not differ enough */ /* (value 14 is heuristic, corresponding to approx. 4.1 degrees) */ /* the long arm is never negative */ if ( ll <= 14 * FT_ABS( ss ) ) dir = AF_DIR_NONE; return dir; } FT_LOCAL_DEF( void ) af_glyph_hints_init( AF_GlyphHints hints, FT_Memory memory ) { /* no need to initialize the embedded items */ FT_MEM_ZERO( hints, sizeof ( *hints ) - sizeof ( hints->embedded ) ); hints->memory = memory; } FT_LOCAL_DEF( void ) af_glyph_hints_done( AF_GlyphHints hints ) { FT_Memory memory; int dim; if ( !( hints && hints->memory ) ) return; memory = hints->memory; /* * note that we don't need to free the segment and edge * buffers since they are really within the hints->points array */ for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ ) { AF_AxisHints axis = &hints->axis[dim]; axis->num_segments = 0; axis->max_segments = 0; if ( axis->segments != axis->embedded.segments ) FT_FREE( axis->segments ); axis->num_edges = 0; axis->max_edges = 0; if ( axis->edges != axis->embedded.edges ) FT_FREE( axis->edges ); } if ( hints->contours != hints->embedded.contours ) FT_FREE( hints->contours ); hints->max_contours = 0; hints->num_contours = 0; if ( hints->points != hints->embedded.points ) FT_FREE( hints->points ); hints->max_points = 0; hints->num_points = 0; hints->memory = NULL; } /* Reset metrics. */ FT_LOCAL_DEF( void ) af_glyph_hints_rescale( AF_GlyphHints hints, AF_StyleMetrics metrics ) { hints->metrics = metrics; hints->scaler_flags = metrics->scaler.flags; } /* Recompute all AF_Point in AF_GlyphHints from the definitions */ /* in a source outline. */ FT_LOCAL_DEF( FT_Error ) af_glyph_hints_reload( AF_GlyphHints hints, FT_Outline* outline ) { FT_Error error = FT_Err_Ok; AF_Point points; FT_UInt old_max, new_max; FT_Fixed x_scale = hints->x_scale; FT_Fixed y_scale = hints->y_scale; FT_Pos x_delta = hints->x_delta; FT_Pos y_delta = hints->y_delta; FT_Memory memory = hints->memory; hints->num_points = 0; hints->num_contours = 0; hints->axis[0].num_segments = 0; hints->axis[0].num_edges = 0; hints->axis[1].num_segments = 0; hints->axis[1].num_edges = 0; /* first of all, reallocate the contours array if necessary */ new_max = (FT_UInt)outline->n_contours; old_max = (FT_UInt)hints->max_contours; if ( new_max <= AF_CONTOURS_EMBEDDED ) { if ( hints->contours == NULL ) { hints->contours = hints->embedded.contours; hints->max_contours = AF_CONTOURS_EMBEDDED; } } else if ( new_max > old_max ) { if ( hints->contours == hints->embedded.contours ) hints->contours = NULL; new_max = ( new_max + 3 ) & ~3U; /* round up to a multiple of 4 */ if ( FT_RENEW_ARRAY( hints->contours, old_max, new_max ) ) goto Exit; hints->max_contours = (FT_Int)new_max; } /* * then reallocate the points arrays if necessary -- * note that we reserve two additional point positions, used to * hint metrics appropriately */ new_max = (FT_UInt)( outline->n_points + 2 ); old_max = (FT_UInt)hints->max_points; if ( new_max <= AF_POINTS_EMBEDDED ) { if ( hints->points == NULL ) { hints->points = hints->embedded.points; hints->max_points = AF_POINTS_EMBEDDED; } } else if ( new_max > old_max ) { if ( hints->points == hints->embedded.points ) hints->points = NULL; new_max = ( new_max + 2 + 7 ) & ~7U; /* round up to a multiple of 8 */ if ( FT_RENEW_ARRAY( hints->points, old_max, new_max ) ) goto Exit; hints->max_points = (FT_Int)new_max; } hints->num_points = outline->n_points; hints->num_contours = outline->n_contours; /* We can't rely on the value of `FT_Outline.flags' to know the fill */ /* direction used for a glyph, given that some fonts are broken (e.g., */ /* the Arphic ones). We thus recompute it each time we need to. */ /* */ hints->axis[AF_DIMENSION_HORZ].major_dir = AF_DIR_UP; hints->axis[AF_DIMENSION_VERT].major_dir = AF_DIR_LEFT; if ( FT_Outline_Get_Orientation( outline ) == FT_ORIENTATION_POSTSCRIPT ) { hints->axis[AF_DIMENSION_HORZ].major_dir = AF_DIR_DOWN; hints->axis[AF_DIMENSION_VERT].major_dir = AF_DIR_RIGHT; } hints->x_scale = x_scale; hints->y_scale = y_scale; hints->x_delta = x_delta; hints->y_delta = y_delta; hints->xmin_delta = 0; hints->xmax_delta = 0; points = hints->points; if ( hints->num_points == 0 ) goto Exit; { AF_Point point; AF_Point point_limit = points + hints->num_points; /* value 20 in `near_limit' is heuristic */ FT_UInt units_per_em = hints->metrics->scaler.face->units_per_EM; FT_Int near_limit = 20 * units_per_em / 2048; /* compute coordinates & Bezier flags, next and prev */ { FT_Vector* vec = outline->points; char* tag = outline->tags; FT_Short endpoint = outline->contours[0]; AF_Point end = points + endpoint; AF_Point prev = end; FT_Int contour_index = 0; for ( point = points; point < point_limit; point++, vec++, tag++ ) { FT_Pos out_x, out_y; point->in_dir = (FT_Char)AF_DIR_NONE; point->out_dir = (FT_Char)AF_DIR_NONE; point->fx = (FT_Short)vec->x; point->fy = (FT_Short)vec->y; point->ox = point->x = FT_MulFix( vec->x, x_scale ) + x_delta; point->oy = point->y = FT_MulFix( vec->y, y_scale ) + y_delta; end->fx = (FT_Short)outline->points[endpoint].x; end->fy = (FT_Short)outline->points[endpoint].y; switch ( FT_CURVE_TAG( *tag ) ) { case FT_CURVE_TAG_CONIC: point->flags = AF_FLAG_CONIC; break; case FT_CURVE_TAG_CUBIC: point->flags = AF_FLAG_CUBIC; break; default: point->flags = AF_FLAG_NONE; } out_x = point->fx - prev->fx; out_y = point->fy - prev->fy; if ( FT_ABS( out_x ) + FT_ABS( out_y ) < near_limit ) prev->flags |= AF_FLAG_NEAR; point->prev = prev; prev->next = point; prev = point; if ( point == end ) { if ( ++contour_index < outline->n_contours ) { endpoint = outline->contours[contour_index]; end = points + endpoint; prev = end; } } } } /* set up the contours array */ { AF_Point* contour = hints->contours; AF_Point* contour_limit = contour + hints->num_contours; short* end = outline->contours; short idx = 0; for ( ; contour < contour_limit; contour++, end++ ) { contour[0] = points + idx; idx = (short)( end[0] + 1 ); } } { /* * Compute directions of `in' and `out' vectors. * * Note that distances between points that are very near to each * other are accumulated. In other words, the auto-hinter either * prepends the small vectors between near points to the first * non-near vector, or the sum of small vector lengths exceeds a * threshold, thus `grouping' the small vectors. All intermediate * points are tagged as weak; the directions are adjusted also to * be equal to the accumulated one. */ FT_Int near_limit2 = 2 * near_limit - 1; AF_Point* contour; AF_Point* contour_limit = hints->contours + hints->num_contours; for ( contour = hints->contours; contour < contour_limit; contour++ ) { AF_Point first = *contour; AF_Point next, prev, curr; FT_Pos out_x, out_y; /* since the first point of a contour could be part of a */ /* series of near points, go backwards to find the first */ /* non-near point and adjust `first' */ point = first; prev = first->prev; while ( prev != first ) { out_x = point->fx - prev->fx; out_y = point->fy - prev->fy; /* * We use Taxicab metrics to measure the vector length. * * Note that the accumulated distances so far could have the * opposite direction of the distance measured here. For this * reason we use `near_limit2' for the comparison to get a * non-near point even in the worst case. */ if ( FT_ABS( out_x ) + FT_ABS( out_y ) >= near_limit2 ) break; point = prev; prev = prev->prev; } /* adjust first point */ first = point; /* now loop over all points of the contour to get */ /* `in' and `out' vector directions */ curr = first; /* * We abuse the `u' and `v' fields to store index deltas to the * next and previous non-near point, respectively. * * To avoid problems with not having non-near points, we point to * `first' by default as the next non-near point. * */ curr->u = (FT_Pos)( first - curr ); first->v = -curr->u; out_x = 0; out_y = 0; next = first; do { AF_Direction out_dir; point = next; next = point->next; out_x += next->fx - point->fx; out_y += next->fy - point->fy; if ( FT_ABS( out_x ) + FT_ABS( out_y ) < near_limit ) { next->flags |= AF_FLAG_WEAK_INTERPOLATION; continue; } curr->u = (FT_Pos)( next - curr ); next->v = -curr->u; out_dir = af_direction_compute( out_x, out_y ); /* adjust directions for all points inbetween; */ /* the loop also updates position of `curr' */ curr->out_dir = (FT_Char)out_dir; for ( curr = curr->next; curr != next; curr = curr->next ) { curr->in_dir = (FT_Char)out_dir; curr->out_dir = (FT_Char)out_dir; } next->in_dir = (FT_Char)out_dir; curr->u = (FT_Pos)( first - curr ); first->v = -curr->u; out_x = 0; out_y = 0; } while ( next != first ); } /* * The next step is to `simplify' an outline's topology so that we * can identify local extrema more reliably: A series of * non-horizontal or non-vertical vectors pointing into the same * quadrant are handled as a single, long vector. From a * topological point of the view, the intermediate points are of no * interest and thus tagged as weak. */ for ( point = points; point < point_limit; point++ ) { if ( point->flags & AF_FLAG_WEAK_INTERPOLATION ) continue; if ( point->in_dir == AF_DIR_NONE && point->out_dir == AF_DIR_NONE ) { /* check whether both vectors point into the same quadrant */ FT_Pos in_x, in_y; FT_Pos out_x, out_y; AF_Point next_u = point + point->u; AF_Point prev_v = point + point->v; in_x = point->fx - prev_v->fx; in_y = point->fy - prev_v->fy; out_x = next_u->fx - point->fx; out_y = next_u->fy - point->fy; if ( ( in_x ^ out_x ) >= 0 && ( in_y ^ out_y ) >= 0 ) { /* yes, so tag current point as weak */ /* and update index deltas */ point->flags |= AF_FLAG_WEAK_INTERPOLATION; prev_v->u = (FT_Pos)( next_u - prev_v ); next_u->v = -prev_v->u; } } } /* * Finally, check for remaining weak points. Everything else not * collected in edges so far is then implicitly classified as strong * points. */ for ( point = points; point < point_limit; point++ ) { if ( point->flags & AF_FLAG_WEAK_INTERPOLATION ) continue; if ( point->flags & AF_FLAG_CONTROL ) { /* control points are always weak */ Is_Weak_Point: point->flags |= AF_FLAG_WEAK_INTERPOLATION; } else if ( point->out_dir == point->in_dir ) { if ( point->out_dir != AF_DIR_NONE ) { /* current point lies on a horizontal or */ /* vertical segment (but doesn't start or end it) */ goto Is_Weak_Point; } { AF_Point next_u = point + point->u; AF_Point prev_v = point + point->v; if ( ft_corner_is_flat( point->fx - prev_v->fx, point->fy - prev_v->fy, next_u->fx - point->fx, next_u->fy - point->fy ) ) { /* either the `in' or the `out' vector is much more */ /* dominant than the other one, so tag current point */ /* as weak and update index deltas */ prev_v->u = (FT_Pos)( next_u - prev_v ); next_u->v = -prev_v->u; goto Is_Weak_Point; } } } else if ( point->in_dir == -point->out_dir ) { /* current point forms a spike */ goto Is_Weak_Point; } } } } Exit: return error; } /* Store the hinted outline in an FT_Outline structure. */ FT_LOCAL_DEF( void ) af_glyph_hints_save( AF_GlyphHints hints, FT_Outline* outline ) { AF_Point point = hints->points; AF_Point limit = point + hints->num_points; FT_Vector* vec = outline->points; char* tag = outline->tags; for ( ; point < limit; point++, vec++, tag++ ) { vec->x = point->x; vec->y = point->y; if ( point->flags & AF_FLAG_CONIC ) tag[0] = FT_CURVE_TAG_CONIC; else if ( point->flags & AF_FLAG_CUBIC ) tag[0] = FT_CURVE_TAG_CUBIC; else tag[0] = FT_CURVE_TAG_ON; } } /**************************************************************** * * EDGE POINT GRID-FITTING * ****************************************************************/ /* Align all points of an edge to the same coordinate value, */ /* either horizontally or vertically. */ FT_LOCAL_DEF( void ) af_glyph_hints_align_edge_points( AF_GlyphHints hints, AF_Dimension dim ) { AF_AxisHints axis = & hints->axis[dim]; AF_Segment segments = axis->segments; AF_Segment segment_limit = segments + axis->num_segments; AF_Segment seg; if ( dim == AF_DIMENSION_HORZ ) { for ( seg = segments; seg < segment_limit; seg++ ) { AF_Edge edge = seg->edge; AF_Point point, first, last; if ( edge == NULL ) continue; first = seg->first; last = seg->last; point = first; for (;;) { point->x = edge->pos; point->flags |= AF_FLAG_TOUCH_X; if ( point == last ) break; point = point->next; } } } else { for ( seg = segments; seg < segment_limit; seg++ ) { AF_Edge edge = seg->edge; AF_Point point, first, last; if ( edge == NULL ) continue; first = seg->first; last = seg->last; point = first; for (;;) { point->y = edge->pos; point->flags |= AF_FLAG_TOUCH_Y; if ( point == last ) break; point = point->next; } } } } /**************************************************************** * * STRONG POINT INTERPOLATION * ****************************************************************/ /* Hint the strong points -- this is equivalent to the TrueType `IP' */ /* hinting instruction. */ FT_LOCAL_DEF( void ) af_glyph_hints_align_strong_points( AF_GlyphHints hints, AF_Dimension dim ) { AF_Point points = hints->points; AF_Point point_limit = points + hints->num_points; AF_AxisHints axis = &hints->axis[dim]; AF_Edge edges = axis->edges; AF_Edge edge_limit = edges + axis->num_edges; FT_UInt touch_flag; if ( dim == AF_DIMENSION_HORZ ) touch_flag = AF_FLAG_TOUCH_X; else touch_flag = AF_FLAG_TOUCH_Y; if ( edges < edge_limit ) { AF_Point point; AF_Edge edge; for ( point = points; point < point_limit; point++ ) { FT_Pos u, ou, fu; /* point position */ FT_Pos delta; if ( point->flags & touch_flag ) continue; /* if this point is candidate to weak interpolation, we */ /* interpolate it after all strong points have been processed */ if ( ( point->flags & AF_FLAG_WEAK_INTERPOLATION ) ) continue; if ( dim == AF_DIMENSION_VERT ) { u = point->fy; ou = point->oy; } else { u = point->fx; ou = point->ox; } fu = u; /* is the point before the first edge? */ edge = edges; delta = edge->fpos - u; if ( delta >= 0 ) { u = edge->pos - ( edge->opos - ou ); goto Store_Point; } /* is the point after the last edge? */ edge = edge_limit - 1; delta = u - edge->fpos; if ( delta >= 0 ) { u = edge->pos + ( ou - edge->opos ); goto Store_Point; } { FT_PtrDist min, max, mid; FT_Pos fpos; /* find enclosing edges */ min = 0; max = edge_limit - edges; #if 1 /* for a small number of edges, a linear search is better */ if ( max <= 8 ) { FT_PtrDist nn; for ( nn = 0; nn < max; nn++ ) if ( edges[nn].fpos >= u ) break; if ( edges[nn].fpos == u ) { u = edges[nn].pos; goto Store_Point; } min = nn; } else #endif while ( min < max ) { mid = ( max + min ) >> 1; edge = edges + mid; fpos = edge->fpos; if ( u < fpos ) max = mid; else if ( u > fpos ) min = mid + 1; else { /* we are on the edge */ u = edge->pos; goto Store_Point; } } /* point is not on an edge */ { AF_Edge before = edges + min - 1; AF_Edge after = edges + min + 0; /* assert( before && after && before != after ) */ if ( before->scale == 0 ) before->scale = FT_DivFix( after->pos - before->pos, after->fpos - before->fpos ); u = before->pos + FT_MulFix( fu - before->fpos, before->scale ); } } Store_Point: /* save the point position */ if ( dim == AF_DIMENSION_HORZ ) point->x = u; else point->y = u; point->flags |= touch_flag; } } } /**************************************************************** * * WEAK POINT INTERPOLATION * ****************************************************************/ /* Shift the original coordinates of all points between `p1' and */ /* `p2' to get hinted coordinates, using the same difference as */ /* given by `ref'. */ static void af_iup_shift( AF_Point p1, AF_Point p2, AF_Point ref ) { AF_Point p; FT_Pos delta = ref->u - ref->v; if ( delta == 0 ) return; for ( p = p1; p < ref; p++ ) p->u = p->v + delta; for ( p = ref + 1; p <= p2; p++ ) p->u = p->v + delta; } /* Interpolate the original coordinates of all points between `p1' and */ /* `p2' to get hinted coordinates, using `ref1' and `ref2' as the */ /* reference points. The `u' and `v' members are the current and */ /* original coordinate values, respectively. */ /* */ /* Details can be found in the TrueType bytecode specification. */ static void af_iup_interp( AF_Point p1, AF_Point p2, AF_Point ref1, AF_Point ref2 ) { AF_Point p; FT_Pos u, v1, v2, u1, u2, d1, d2; if ( p1 > p2 ) return; if ( ref1->v > ref2->v ) { p = ref1; ref1 = ref2; ref2 = p; } v1 = ref1->v; v2 = ref2->v; u1 = ref1->u; u2 = ref2->u; d1 = u1 - v1; d2 = u2 - v2; if ( u1 == u2 || v1 == v2 ) { for ( p = p1; p <= p2; p++ ) { u = p->v; if ( u <= v1 ) u += d1; else if ( u >= v2 ) u += d2; else u = u1; p->u = u; } } else { FT_Fixed scale = FT_DivFix( u2 - u1, v2 - v1 ); for ( p = p1; p <= p2; p++ ) { u = p->v; if ( u <= v1 ) u += d1; else if ( u >= v2 ) u += d2; else u = u1 + FT_MulFix( u - v1, scale ); p->u = u; } } } /* Hint the weak points -- this is equivalent to the TrueType `IUP' */ /* hinting instruction. */ FT_LOCAL_DEF( void ) af_glyph_hints_align_weak_points( AF_GlyphHints hints, AF_Dimension dim ) { AF_Point points = hints->points; AF_Point point_limit = points + hints->num_points; AF_Point* contour = hints->contours; AF_Point* contour_limit = contour + hints->num_contours; FT_UInt touch_flag; AF_Point point; AF_Point end_point; AF_Point first_point; /* PASS 1: Move segment points to edge positions */ if ( dim == AF_DIMENSION_HORZ ) { touch_flag = AF_FLAG_TOUCH_X; for ( point = points; point < point_limit; point++ ) { point->u = point->x; point->v = point->ox; } } else { touch_flag = AF_FLAG_TOUCH_Y; for ( point = points; point < point_limit; point++ ) { point->u = point->y; point->v = point->oy; } } for ( ; contour < contour_limit; contour++ ) { AF_Point first_touched, last_touched; point = *contour; end_point = point->prev; first_point = point; /* find first touched point */ for (;;) { if ( point > end_point ) /* no touched point in contour */ goto NextContour; if ( point->flags & touch_flag ) break; point++; } first_touched = point; for (;;) { FT_ASSERT( point <= end_point && ( point->flags & touch_flag ) != 0 ); /* skip any touched neighbours */ while ( point < end_point && ( point[1].flags & touch_flag ) != 0 ) point++; last_touched = point; /* find the next touched point, if any */ point++; for (;;) { if ( point > end_point ) goto EndContour; if ( ( point->flags & touch_flag ) != 0 ) break; point++; } /* interpolate between last_touched and point */ af_iup_interp( last_touched + 1, point - 1, last_touched, point ); } EndContour: /* special case: only one point was touched */ if ( last_touched == first_touched ) af_iup_shift( first_point, end_point, first_touched ); else /* interpolate the last part */ { if ( last_touched < end_point ) af_iup_interp( last_touched + 1, end_point, last_touched, first_touched ); if ( first_touched > points ) af_iup_interp( first_point, first_touched - 1, last_touched, first_touched ); } NextContour: ; } /* now save the interpolated values back to x/y */ if ( dim == AF_DIMENSION_HORZ ) { for ( point = points; point < point_limit; point++ ) point->x = point->u; } else { for ( point = points; point < point_limit; point++ ) point->y = point->u; } } #ifdef AF_CONFIG_OPTION_USE_WARPER /* Apply (small) warp scale and warp delta for given dimension. */ FT_LOCAL_DEF( void ) af_glyph_hints_scale_dim( AF_GlyphHints hints, AF_Dimension dim, FT_Fixed scale, FT_Pos delta ) { AF_Point points = hints->points; AF_Point points_limit = points + hints->num_points; AF_Point point; if ( dim == AF_DIMENSION_HORZ ) { for ( point = points; point < points_limit; point++ ) point->x = FT_MulFix( point->fx, scale ) + delta; } else { for ( point = points; point < points_limit; point++ ) point->y = FT_MulFix( point->fy, scale ) + delta; } } #endif /* AF_CONFIG_OPTION_USE_WARPER */ /* END */
mit
ttyangf/nanomsg
perf/remote_lat.c
27
2612
/* Copyright (c) 2012 Martin Sustrik All rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, 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 "../src/nn.h" #include "../src/tcp.h" #include "../src/pair.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include "../src/utils/stopwatch.c" int main (int argc, char *argv []) { const char *connect_to; size_t sz; int rts; char *buf; int nbytes; int s; int rc; int i; int opt; struct nn_stopwatch sw; uint64_t total; double lat; if (argc != 4) { printf ("usage: remote_lat <connect-to> <msg-size> <roundtrips>\n"); return 1; } connect_to = argv [1]; sz = atoi (argv [2]); rts = atoi (argv [3]); s = nn_socket (AF_SP, NN_PAIR); assert (s != -1); opt = 1; rc = nn_setsockopt (s, NN_TCP, NN_TCP_NODELAY, &opt, sizeof (opt)); assert (rc == 0); rc = nn_connect (s, connect_to); assert (rc >= 0); buf = malloc (sz); assert (buf); memset (buf, 111, sz); nn_stopwatch_init (&sw); for (i = 0; i != rts; i++) { nbytes = nn_send (s, buf, sz, 0); assert (nbytes == (int)sz); nbytes = nn_recv (s, buf, sz, 0); assert (nbytes == (int)sz); } total = nn_stopwatch_term (&sw); lat = (double) total / (rts * 2); printf ("message size: %d [B]\n", (int) sz); printf ("roundtrip count: %d\n", (int) rts); printf ("average latency: %.3f [us]\n", (double) lat); free (buf); rc = nn_close (s); assert (rc == 0); return 0; }
mit
marqs87/Simple-2d-game
cocos2dx/platform/third_party/airplay/expat/examples/elements.c
28
1249
/* This is simple demonstration of how to use expat. This program reads an XML document from standard input and writes a line with the name of each element to standard output indenting child elements by one tab stop more than their parent element. */ #include <stdio.h> #include "expat.h" static void XMLCALL startElement(void *userData, const char *name, const char **atts) { int i; int *depthPtr = userData; for (i = 0; i < *depthPtr; i++) putchar('\t'); puts(name); *depthPtr += 1; } static void XMLCALL endElement(void *userData, const char *name) { int *depthPtr = userData; *depthPtr -= 1; } int main(int argc, char *argv[]) { char buf[BUFSIZ]; XML_Parser parser = XML_ParserCreate(NULL); int done; int depth = 0; XML_SetUserData(parser, &depth); XML_SetElementHandler(parser, startElement, endElement); do { size_t len = fread(buf, 1, sizeof(buf), stdin); done = len < sizeof(buf); if (XML_Parse(parser, buf, len, done) == XML_STATUS_ERROR) { fprintf(stderr, "%s at line %d\n", XML_ErrorString(XML_GetErrorCode(parser)), XML_GetCurrentLineNumber(parser)); return 1; } } while (!done); XML_ParserFree(parser); return 0; }
mit
jdgarcia/nodegit
vendor/libssh2/src/transport.c
29
33200
/* Copyright (C) 2007 The Written Word, Inc. All rights reserved. * Copyright (C) 2009-2010 by Daniel Stenberg * Author: Daniel Stenberg <daniel@haxx.se> * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the copyright holder nor the names * of any other contributors may be used to endorse or * promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * * This file handles reading and writing to the SECSH transport layer. RFC4253. */ #include "libssh2_priv.h" #include <errno.h> #include <fcntl.h> #include <ctype.h> #ifdef LIBSSH2DEBUG #include <stdio.h> #endif #include <assert.h> #include "transport.h" #include "mac.h" #define MAX_BLOCKSIZE 32 /* MUST fit biggest crypto block size we use/get */ #define MAX_MACSIZE 20 /* MUST fit biggest MAC length we support */ #ifdef LIBSSH2DEBUG #define UNPRINTABLE_CHAR '.' static void debugdump(LIBSSH2_SESSION * session, const char *desc, const unsigned char *ptr, size_t size) { size_t i; size_t c; unsigned int width = 0x10; char buffer[256]; /* Must be enough for width*4 + about 30 or so */ size_t used; static const char* hex_chars = "0123456789ABCDEF"; if (!(session->showmask & LIBSSH2_TRACE_TRANS)) { /* not asked for, bail out */ return; } used = snprintf(buffer, sizeof(buffer), "=> %s (%d bytes)\n", desc, (int) size); if (session->tracehandler) (session->tracehandler)(session, session->tracehandler_context, buffer, used); else fprintf(stderr, "%s", buffer); for(i = 0; i < size; i += width) { used = snprintf(buffer, sizeof(buffer), "%04lx: ", (long)i); /* hex not disabled, show it */ for(c = 0; c < width; c++) { if (i + c < size) { buffer[used++] = hex_chars[(ptr[i+c] >> 4) & 0xF]; buffer[used++] = hex_chars[ptr[i+c] & 0xF]; } else { buffer[used++] = ' '; buffer[used++] = ' '; } buffer[used++] = ' '; if ((width/2) - 1 == c) buffer[used++] = ' '; } buffer[used++] = ':'; buffer[used++] = ' '; for(c = 0; (c < width) && (i + c < size); c++) { buffer[used++] = isprint(ptr[i + c]) ? ptr[i + c] : UNPRINTABLE_CHAR; } buffer[used++] = '\n'; buffer[used] = 0; if (session->tracehandler) (session->tracehandler)(session, session->tracehandler_context, buffer, used); else fprintf(stderr, "%s", buffer); } } #else #define debugdump(a,x,y,z) #endif /* decrypt() decrypts 'len' bytes from 'source' to 'dest'. * * returns 0 on success and negative on failure */ static int decrypt(LIBSSH2_SESSION * session, unsigned char *source, unsigned char *dest, int len) { struct transportpacket *p = &session->packet; int blocksize = session->remote.crypt->blocksize; /* if we get called with a len that isn't an even number of blocksizes we risk losing those extra bytes */ assert((len % blocksize) == 0); while (len >= blocksize) { if (session->remote.crypt->crypt(session, source, blocksize, &session->remote.crypt_abstract)) { LIBSSH2_FREE(session, p->payload); return LIBSSH2_ERROR_DECRYPT; } /* if the crypt() function would write to a given address it wouldn't have to memcpy() and we could avoid this memcpy() too */ memcpy(dest, source, blocksize); len -= blocksize; /* less bytes left */ dest += blocksize; /* advance write pointer */ source += blocksize; /* advance read pointer */ } return LIBSSH2_ERROR_NONE; /* all is fine */ } /* * fullpacket() gets called when a full packet has been received and properly * collected. */ static int fullpacket(LIBSSH2_SESSION * session, int encrypted /* 1 or 0 */ ) { unsigned char macbuf[MAX_MACSIZE]; struct transportpacket *p = &session->packet; int rc; int compressed; if (session->fullpacket_state == libssh2_NB_state_idle) { session->fullpacket_macstate = LIBSSH2_MAC_CONFIRMED; session->fullpacket_payload_len = p->packet_length - 1; if (encrypted) { /* Calculate MAC hash */ session->remote.mac->hash(session, macbuf, /* store hash here */ session->remote.seqno, p->init, 5, p->payload, session->fullpacket_payload_len, &session->remote.mac_abstract); /* Compare the calculated hash with the MAC we just read from * the network. The read one is at the very end of the payload * buffer. Note that 'payload_len' here is the packet_length * field which includes the padding but not the MAC. */ if (memcmp(macbuf, p->payload + session->fullpacket_payload_len, session->remote.mac->mac_len)) { session->fullpacket_macstate = LIBSSH2_MAC_INVALID; } } session->remote.seqno++; /* ignore the padding */ session->fullpacket_payload_len -= p->padding_length; /* Check for and deal with decompression */ compressed = session->local.comp != NULL && session->local.comp->compress && ((session->state & LIBSSH2_STATE_AUTHENTICATED) || session->local.comp->use_in_auth); if (compressed && session->remote.comp_abstract) { /* * The buffer for the decompression (remote.comp_abstract) is * initialised in time when it is needed so as long it is NULL we * cannot decompress. */ unsigned char *data; size_t data_len; rc = session->remote.comp->decomp(session, &data, &data_len, LIBSSH2_PACKET_MAXDECOMP, p->payload, session->fullpacket_payload_len, &session->remote.comp_abstract); LIBSSH2_FREE(session, p->payload); if(rc) return rc; p->payload = data; session->fullpacket_payload_len = data_len; } session->fullpacket_packet_type = p->payload[0]; debugdump(session, "libssh2_transport_read() plain", p->payload, session->fullpacket_payload_len); session->fullpacket_state = libssh2_NB_state_created; } if (session->fullpacket_state == libssh2_NB_state_created) { rc = _libssh2_packet_add(session, p->payload, session->fullpacket_payload_len, session->fullpacket_macstate); if (rc) return rc; } session->fullpacket_state = libssh2_NB_state_idle; return session->fullpacket_packet_type; } /* * _libssh2_transport_read * * Collect a packet into the input queue. * * Returns packet type added to input queue (0 if nothing added), or a * negative error number. */ /* * This function reads the binary stream as specified in chapter 6 of RFC4253 * "The Secure Shell (SSH) Transport Layer Protocol" * * DOES NOT call _libssh2_error() for ANY error case. */ int _libssh2_transport_read(LIBSSH2_SESSION * session) { int rc; struct transportpacket *p = &session->packet; int remainbuf; int remainpack; int numbytes; int numdecrypt; unsigned char block[MAX_BLOCKSIZE]; int blocksize; int encrypted = 1; size_t total_num; /* default clear the bit */ session->socket_block_directions &= ~LIBSSH2_SESSION_BLOCK_INBOUND; /* * All channels, systems, subsystems, etc eventually make it down here * when looking for more incoming data. If a key exchange is going on * (LIBSSH2_STATE_EXCHANGING_KEYS bit is set) then the remote end will * ONLY send key exchange related traffic. In non-blocking mode, there is * a chance to break out of the kex_exchange function with an EAGAIN * status, and never come back to it. If LIBSSH2_STATE_EXCHANGING_KEYS is * active, then we must redirect to the key exchange. However, if * kex_exchange is active (as in it is the one that calls this execution * of packet_read, then don't redirect, as that would be an infinite loop! */ if (session->state & LIBSSH2_STATE_EXCHANGING_KEYS && !(session->state & LIBSSH2_STATE_KEX_ACTIVE)) { /* Whoever wants a packet won't get anything until the key re-exchange * is done! */ _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Redirecting into the" " key re-exchange from _libssh2_transport_read"); rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state); if (rc) return rc; } /* * =============================== NOTE =============================== * I know this is very ugly and not a really good use of "goto", but * this case statement would be even uglier to do it any other way */ if (session->readPack_state == libssh2_NB_state_jump1) { session->readPack_state = libssh2_NB_state_idle; encrypted = session->readPack_encrypted; goto libssh2_transport_read_point1; } do { if (session->socket_state == LIBSSH2_SOCKET_DISCONNECTED) { return LIBSSH2_ERROR_NONE; } if (session->state & LIBSSH2_STATE_NEWKEYS) { blocksize = session->remote.crypt->blocksize; } else { encrypted = 0; /* not encrypted */ blocksize = 5; /* not strictly true, but we can use 5 here to make the checks below work fine still */ } /* read/use a whole big chunk into a temporary area stored in the LIBSSH2_SESSION struct. We will decrypt data from that buffer into the packet buffer so this temp one doesn't have to be able to keep a whole SSH packet, just be large enough so that we can read big chunks from the network layer. */ /* how much data there is remaining in the buffer to deal with before we should read more from the network */ remainbuf = p->writeidx - p->readidx; /* if remainbuf turns negative we have a bad internal error */ assert(remainbuf >= 0); if (remainbuf < blocksize) { /* If we have less than a blocksize left, it is too little data to deal with, read more */ ssize_t nread; /* move any remainder to the start of the buffer so that we can do a full refill */ if (remainbuf) { memmove(p->buf, &p->buf[p->readidx], remainbuf); p->readidx = 0; p->writeidx = remainbuf; } else { /* nothing to move, just zero the indexes */ p->readidx = p->writeidx = 0; } /* now read a big chunk from the network into the temp buffer */ nread = LIBSSH2_RECV(session, &p->buf[remainbuf], PACKETBUFSIZE - remainbuf, LIBSSH2_SOCKET_RECV_FLAGS(session)); if (nread <= 0) { /* check if this is due to EAGAIN and return the special return code if so, error out normally otherwise */ if ((nread < 0) && (nread == -EAGAIN)) { session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_INBOUND; return LIBSSH2_ERROR_EAGAIN; } _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Error recving %d bytes (got %d)", PACKETBUFSIZE - remainbuf, -nread); return LIBSSH2_ERROR_SOCKET_RECV; } _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Recved %d/%d bytes to %p+%d", nread, PACKETBUFSIZE - remainbuf, p->buf, remainbuf); debugdump(session, "libssh2_transport_read() raw", &p->buf[remainbuf], nread); /* advance write pointer */ p->writeidx += nread; /* update remainbuf counter */ remainbuf = p->writeidx - p->readidx; } /* how much data to deal with from the buffer */ numbytes = remainbuf; if (!p->total_num) { /* No payload package area allocated yet. To know the size of this payload, we need to decrypt the first blocksize data. */ if (numbytes < blocksize) { /* we can't act on anything less than blocksize, but this check is only done for the initial block since once we have got the start of a block we can in fact deal with fractions */ session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_INBOUND; return LIBSSH2_ERROR_EAGAIN; } if (encrypted) { rc = decrypt(session, &p->buf[p->readidx], block, blocksize); if (rc != LIBSSH2_ERROR_NONE) { return rc; } /* save the first 5 bytes of the decrypted package, to be used in the hash calculation later down. */ memcpy(p->init, &p->buf[p->readidx], 5); } else { /* the data is plain, just copy it verbatim to the working block buffer */ memcpy(block, &p->buf[p->readidx], blocksize); } /* advance the read pointer */ p->readidx += blocksize; /* we now have the initial blocksize bytes decrypted, * and we can extract packet and padding length from it */ p->packet_length = _libssh2_ntohu32(block); if (p->packet_length < 1) return LIBSSH2_ERROR_DECRYPT; p->padding_length = block[4]; /* total_num is the number of bytes following the initial (5 bytes) packet length and padding length fields */ total_num = p->packet_length - 1 + (encrypted ? session->remote.mac->mac_len : 0); /* RFC4253 section 6.1 Maximum Packet Length says: * * "All implementations MUST be able to process * packets with uncompressed payload length of 32768 * bytes or less and total packet size of 35000 bytes * or less (including length, padding length, payload, * padding, and MAC.)." */ if (total_num > LIBSSH2_PACKET_MAXPAYLOAD) { return LIBSSH2_ERROR_OUT_OF_BOUNDARY; } /* Get a packet handle put data into. We get one to hold all data, including padding and MAC. */ p->payload = LIBSSH2_ALLOC(session, total_num); if (!p->payload) { return LIBSSH2_ERROR_ALLOC; } p->total_num = total_num; /* init write pointer to start of payload buffer */ p->wptr = p->payload; if (blocksize > 5) { /* copy the data from index 5 to the end of the blocksize from the temporary buffer to the start of the decrypted buffer */ memcpy(p->wptr, &block[5], blocksize - 5); p->wptr += blocksize - 5; /* advance write pointer */ } /* init the data_num field to the number of bytes of the package read so far */ p->data_num = p->wptr - p->payload; /* we already dealt with a blocksize worth of data */ numbytes -= blocksize; } /* how much there is left to add to the current payload package */ remainpack = p->total_num - p->data_num; if (numbytes > remainpack) { /* if we have more data in the buffer than what is going into this particular packet, we limit this round to this packet only */ numbytes = remainpack; } if (encrypted) { /* At the end of the incoming stream, there is a MAC, and we don't want to decrypt that since we need it "raw". We MUST however decrypt the padding data since it is used for the hash later on. */ int skip = session->remote.mac->mac_len; /* if what we have plus numbytes is bigger than the total minus the skip margin, we should lower the amount to decrypt even more */ if ((p->data_num + numbytes) > (p->total_num - skip)) { numdecrypt = (p->total_num - skip) - p->data_num; } else { int frac; numdecrypt = numbytes; frac = numdecrypt % blocksize; if (frac) { /* not an aligned amount of blocks, align it */ numdecrypt -= frac; /* and make it no unencrypted data after it */ numbytes = 0; } } } else { /* unencrypted data should not be decrypted at all */ numdecrypt = 0; } /* if there are bytes to decrypt, do that */ if (numdecrypt > 0) { /* now decrypt the lot */ rc = decrypt(session, &p->buf[p->readidx], p->wptr, numdecrypt); if (rc != LIBSSH2_ERROR_NONE) { return rc; } /* advance the read pointer */ p->readidx += numdecrypt; /* advance write pointer */ p->wptr += numdecrypt; /* increse data_num */ p->data_num += numdecrypt; /* bytes left to take care of without decryption */ numbytes -= numdecrypt; } /* if there are bytes to copy that aren't decrypted, simply copy them as-is to the target buffer */ if (numbytes > 0) { memcpy(p->wptr, &p->buf[p->readidx], numbytes); /* advance the read pointer */ p->readidx += numbytes; /* advance write pointer */ p->wptr += numbytes; /* increse data_num */ p->data_num += numbytes; } /* now check how much data there's left to read to finish the current packet */ remainpack = p->total_num - p->data_num; if (!remainpack) { /* we have a full packet */ libssh2_transport_read_point1: rc = fullpacket(session, encrypted); if (rc == LIBSSH2_ERROR_EAGAIN) { if (session->packAdd_state != libssh2_NB_state_idle) { /* fullpacket only returns LIBSSH2_ERROR_EAGAIN if * libssh2_packet_add returns LIBSSH2_ERROR_EAGAIN. If that * returns LIBSSH2_ERROR_EAGAIN but the packAdd_state is idle, * then the packet has been added to the brigade, but some * immediate action that was taken based on the packet * type (such as key re-exchange) is not yet complete. * Clear the way for a new packet to be read in. */ session->readPack_encrypted = encrypted; session->readPack_state = libssh2_NB_state_jump1; } return rc; } p->total_num = 0; /* no packet buffer available */ return rc; } } while (1); /* loop */ return LIBSSH2_ERROR_SOCKET_RECV; /* we never reach this point */ } static int send_existing(LIBSSH2_SESSION *session, const unsigned char *data, size_t data_len, ssize_t *ret) { ssize_t rc; ssize_t length; struct transportpacket *p = &session->packet; if (!p->olen) { *ret = 0; return LIBSSH2_ERROR_NONE; } /* send as much as possible of the existing packet */ if ((data != p->odata) || (data_len != p->olen)) { /* When we are about to complete the sending of a packet, it is vital that the caller doesn't try to send a new/different packet since we don't add this one up until the previous one has been sent. To make the caller really notice his/hers flaw, we return error for this case */ return LIBSSH2_ERROR_BAD_USE; } *ret = 1; /* set to make our parent return */ /* number of bytes left to send */ length = p->ototal_num - p->osent; rc = LIBSSH2_SEND(session, &p->outbuf[p->osent], length, LIBSSH2_SOCKET_SEND_FLAGS(session)); if (rc < 0) _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Error sending %d bytes: %d", length, -rc); else { _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Sent %d/%d bytes at %p+%d", rc, length, p->outbuf, p->osent); debugdump(session, "libssh2_transport_write send()", &p->outbuf[p->osent], rc); } if (rc == length) { /* the remainder of the package was sent */ p->ototal_num = 0; p->olen = 0; /* we leave *ret set so that the parent returns as we MUST return back a send success now, so that we don't risk sending EAGAIN later which then would confuse the parent function */ return LIBSSH2_ERROR_NONE; } else if (rc < 0) { /* nothing was sent */ if (rc != -EAGAIN) /* send failure! */ return LIBSSH2_ERROR_SOCKET_SEND; session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_OUTBOUND; return LIBSSH2_ERROR_EAGAIN; } p->osent += rc; /* we sent away this much data */ return rc < length ? LIBSSH2_ERROR_EAGAIN : LIBSSH2_ERROR_NONE; } /* * libssh2_transport_send * * Send a packet, encrypting it and adding a MAC code if necessary * Returns 0 on success, non-zero on failure. * * The data is provided as _two_ data areas that are combined by this * function. The 'data' part is sent immediately before 'data2'. 'data2' may * be set to NULL to only use a single part. * * Returns LIBSSH2_ERROR_EAGAIN if it would block or if the whole packet was * not sent yet. If it does so, the caller should call this function again as * soon as it is likely that more data can be sent, and this function MUST * then be called with the same argument set (same data pointer and same * data_len) until ERROR_NONE or failure is returned. * * This function DOES NOT call _libssh2_error() on any errors. */ int _libssh2_transport_send(LIBSSH2_SESSION *session, const unsigned char *data, size_t data_len, const unsigned char *data2, size_t data2_len) { int blocksize = (session->state & LIBSSH2_STATE_NEWKEYS) ? session->local.crypt->blocksize : 8; int padding_length; size_t packet_length; int total_length; #ifdef RANDOM_PADDING int rand_max; int seed = data[0]; /* FIXME: make this random */ #endif struct transportpacket *p = &session->packet; int encrypted; int compressed; ssize_t ret; int rc; const unsigned char *orgdata = data; size_t orgdata_len = data_len; /* * If the last read operation was interrupted in the middle of a key * exchange, we must complete that key exchange before continuing to write * further data. * * See the similar block in _libssh2_transport_read for more details. */ if (session->state & LIBSSH2_STATE_EXCHANGING_KEYS && !(session->state & LIBSSH2_STATE_KEX_ACTIVE)) { /* Don't write any new packets if we're still in the middle of a key * exchange. */ _libssh2_debug(session, LIBSSH2_TRACE_TRANS, "Redirecting into the" " key re-exchange from _libssh2_transport_send"); rc = _libssh2_kex_exchange(session, 1, &session->startup_key_state); if (rc) return rc; } debugdump(session, "libssh2_transport_write plain", data, data_len); if(data2) debugdump(session, "libssh2_transport_write plain2", data2, data2_len); /* FIRST, check if we have a pending write to complete. send_existing only sanity-check data and data_len and not data2 and data2_len!! */ rc = send_existing(session, data, data_len, &ret); if (rc) return rc; session->socket_block_directions &= ~LIBSSH2_SESSION_BLOCK_OUTBOUND; if (ret) /* set by send_existing if data was sent */ return rc; encrypted = (session->state & LIBSSH2_STATE_NEWKEYS) ? 1 : 0; compressed = session->local.comp != NULL && session->local.comp->compress && ((session->state & LIBSSH2_STATE_AUTHENTICATED) || session->local.comp->use_in_auth); if (encrypted && compressed) { /* the idea here is that these function must fail if the output gets larger than what fits in the assigned buffer so thus they don't check the input size as we don't know how much it compresses */ size_t dest_len = MAX_SSH_PACKET_LEN-5-256; size_t dest2_len = dest_len; /* compress directly to the target buffer */ rc = session->local.comp->comp(session, &p->outbuf[5], &dest_len, data, data_len, &session->local.comp_abstract); if(rc) return rc; /* compression failure */ if(data2 && data2_len) { /* compress directly to the target buffer right after where the previous call put data */ dest2_len -= dest_len; rc = session->local.comp->comp(session, &p->outbuf[5+dest_len], &dest2_len, data2, data2_len, &session->local.comp_abstract); } else dest2_len = 0; if(rc) return rc; /* compression failure */ data_len = dest_len + dest2_len; /* use the combined length */ } else { if((data_len + data2_len) >= (MAX_SSH_PACKET_LEN-0x100)) /* too large packet, return error for this until we make this function split it up and send multiple SSH packets */ return LIBSSH2_ERROR_INVAL; /* copy the payload data */ memcpy(&p->outbuf[5], data, data_len); if(data2 && data2_len) memcpy(&p->outbuf[5+data_len], data2, data2_len); data_len += data2_len; /* use the combined length */ } /* RFC4253 says: Note that the length of the concatenation of 'packet_length', 'padding_length', 'payload', and 'random padding' MUST be a multiple of the cipher block size or 8, whichever is larger. */ /* Plain math: (4 + 1 + packet_length + padding_length) % blocksize == 0 */ packet_length = data_len + 1 + 4; /* 1 is for padding_length field 4 for the packet_length field */ /* at this point we have it all except the padding */ /* first figure out our minimum padding amount to make it an even block size */ padding_length = blocksize - (packet_length % blocksize); /* if the padding becomes too small we add another blocksize worth of it (taken from the original libssh2 where it didn't have any real explanation) */ if (padding_length < 4) { padding_length += blocksize; } #ifdef RANDOM_PADDING /* FIXME: we can add padding here, but that also makes the packets bigger etc */ /* now we can add 'blocksize' to the padding_length N number of times (to "help thwart traffic analysis") but it must be less than 255 in total */ rand_max = (255 - padding_length) / blocksize + 1; padding_length += blocksize * (seed % rand_max); #endif packet_length += padding_length; /* append the MAC length to the total_length size */ total_length = packet_length + (encrypted ? session->local.mac->mac_len : 0); /* store packet_length, which is the size of the whole packet except the MAC and the packet_length field itself */ _libssh2_htonu32(p->outbuf, packet_length - 4); /* store padding_length */ p->outbuf[4] = padding_length; /* fill the padding area with random junk */ _libssh2_random(p->outbuf + 5 + data_len, padding_length); if (encrypted) { size_t i; /* Calculate MAC hash. Put the output at index packet_length, since that size includes the whole packet. The MAC is calculated on the entire unencrypted packet, including all fields except the MAC field itself. */ session->local.mac->hash(session, p->outbuf + packet_length, session->local.seqno, p->outbuf, packet_length, NULL, 0, &session->local.mac_abstract); /* Encrypt the whole packet data, one block size at a time. The MAC field is not encrypted. */ for(i = 0; i < packet_length; i += session->local.crypt->blocksize) { unsigned char *ptr = &p->outbuf[i]; if (session->local.crypt->crypt(session, ptr, session->local.crypt->blocksize, &session->local.crypt_abstract)) return LIBSSH2_ERROR_ENCRYPT; /* encryption failure */ } } session->local.seqno++; ret = LIBSSH2_SEND(session, p->outbuf, total_length, LIBSSH2_SOCKET_SEND_FLAGS(session)); if (ret < 0) _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Error sending %d bytes: %d", total_length, -ret); else { _libssh2_debug(session, LIBSSH2_TRACE_SOCKET, "Sent %d/%d bytes at %p", ret, total_length, p->outbuf); debugdump(session, "libssh2_transport_write send()", p->outbuf, ret); } if (ret != total_length) { if (ret >= 0 || ret == -EAGAIN) { /* the whole packet could not be sent, save the rest */ session->socket_block_directions |= LIBSSH2_SESSION_BLOCK_OUTBOUND; p->odata = orgdata; p->olen = orgdata_len; p->osent = ret <= 0 ? 0 : ret; p->ototal_num = total_length; return LIBSSH2_ERROR_EAGAIN; } return LIBSSH2_ERROR_SOCKET_SEND; } /* the whole thing got sent away */ p->odata = NULL; p->olen = 0; return LIBSSH2_ERROR_NONE; /* all is good */ }
mit
bioinformed/pysam
htslib/regidx.c
30
10171
/* Copyright (C) 2014 Genome Research Ltd. Author: Petr Danecek <pd3@sanger.ac.uk> 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 <config.h> #include "htslib/hts.h" #include "htslib/kstring.h" #include "htslib/kseq.h" #include "htslib/khash_str2int.h" #include "htslib/regidx.h" #define LIDX_SHIFT 13 // number of insignificant index bits // List of regions for one chromosome typedef struct { int *idx, nidx; int nregs, mregs; // n:used, m:alloced reg_t *regs; void *payload; } reglist_t; // Container of all sequences struct _regidx_t { int nseq, mseq; // n:used, m:alloced reglist_t *seq; // regions for each sequence void *seq2regs; // hash for fast lookup from chr name to regions char **seq_names; regidx_free_f free; // function to free any data allocated by regidx_parse_f regidx_parse_f parse; // parse one input line void *usr; // user data to pass to regidx_parse_f // temporary data for index initialization kstring_t str; int rid_prev, start_prev, end_prev; int payload_size; void *payload; }; int regidx_seq_nregs(regidx_t *idx, const char *seq) { int iseq; if ( khash_str2int_get(idx->seq2regs, seq, &iseq)!=0 ) return 0; // no such sequence return idx->seq[iseq].nregs; } int regidx_nregs(regidx_t *idx) { int i, nregs = 0; for (i=0; i<idx->nseq; i++) nregs += idx->seq[i].nregs; return nregs; } char **regidx_seq_names(regidx_t *idx, int *n) { *n = idx->nseq; return idx->seq_names; } int _regidx_build_index(regidx_t *idx) { int iseq; for (iseq=0; iseq<idx->nseq; iseq++) { reglist_t *list = &idx->seq[iseq]; int j,k, imax = 0; // max index bin for (j=0; j<list->nregs; j++) { int ibeg = list->regs[j].start >> LIDX_SHIFT; int iend = list->regs[j].end >> LIDX_SHIFT; if ( imax < iend + 1 ) { int old_imax = imax; imax = iend + 1; kroundup32(imax); list->idx = (int*) realloc(list->idx, imax*sizeof(int)); for (k=old_imax; k<imax; k++) list->idx[k] = -1; } if ( ibeg==iend ) { if ( list->idx[ibeg]<0 ) list->idx[ibeg] = j; } else { for (k=ibeg; k<=iend; k++) if ( list->idx[k]<0 ) list->idx[k] = j; } list->nidx = iend + 1; } } return 0; } int regidx_insert(regidx_t *idx, char *line) { if ( !line ) return _regidx_build_index(idx); char *chr_from, *chr_to; reg_t reg; int ret = idx->parse(line,&chr_from,&chr_to,&reg,idx->payload,idx->usr); if ( ret==-2 ) return -1; // error if ( ret==-1 ) return 0; // skip the line int rid; idx->str.l = 0; kputsn(chr_from, chr_to-chr_from+1, &idx->str); if ( khash_str2int_get(idx->seq2regs, idx->str.s, &rid)!=0 ) { idx->nseq++; int m_prev = idx->mseq; hts_expand0(reglist_t,idx->nseq,idx->mseq,idx->seq); hts_expand0(char*,idx->nseq,m_prev,idx->seq_names); idx->seq_names[idx->nseq-1] = strdup(idx->str.s); rid = khash_str2int_inc(idx->seq2regs, idx->seq_names[idx->nseq-1]); } reglist_t *list = &idx->seq[rid]; list->nregs++; int m_prev = list->mregs; hts_expand(reg_t,list->nregs,list->mregs,list->regs); list->regs[list->nregs-1] = reg; if ( idx->payload_size ) { if ( m_prev < list->mregs ) list->payload = realloc(list->payload,idx->payload_size*list->mregs); memcpy(list->payload + idx->payload_size*(list->nregs-1), idx->payload, idx->payload_size); } if ( idx->rid_prev==rid ) { if ( idx->start_prev > reg.start || (idx->start_prev==reg.start && idx->end_prev>reg.end) ) { fprintf(stderr,"The regions are not sorted: %s:%d-%d is before %s:%d-%d\n", idx->str.s,idx->start_prev+1,idx->end_prev+1,idx->str.s,reg.start+1,reg.end+1); return -1; } } idx->rid_prev = rid; idx->start_prev = reg.start; idx->end_prev = reg.end; return 0; } regidx_t *regidx_init(const char *fname, regidx_parse_f parser, regidx_free_f free_f, size_t payload_size, void *usr_dat) { if ( !parser ) { if ( !fname ) parser = regidx_parse_tab; else { int len = strlen(fname); if ( len>=7 && !strcasecmp(".bed.gz",fname+len-7) ) parser = regidx_parse_bed; else if ( len>=8 && !strcasecmp(".bed.bgz",fname+len-8) ) parser = regidx_parse_bed; else if ( len>=4 && !strcasecmp(".bed",fname+len-4) ) parser = regidx_parse_bed; else parser = regidx_parse_tab; } } regidx_t *idx = (regidx_t*) calloc(1,sizeof(regidx_t)); idx->free = free_f; idx->parse = parser; idx->usr = usr_dat; idx->seq2regs = khash_str2int_init(); idx->rid_prev = -1; idx->start_prev = -1; idx->end_prev = -1; idx->payload_size = payload_size; if ( payload_size ) idx->payload = malloc(payload_size); if ( !fname ) return idx; kstring_t str = {0,0,0}; htsFile *fp = hts_open(fname,"r"); if ( !fp ) goto error; while ( hts_getline(fp, KS_SEP_LINE, &str) > 0 ) { if ( regidx_insert(idx, str.s) ) goto error; } regidx_insert(idx, NULL); free(str.s); hts_close(fp); return idx; error: free(str.s); if ( fp ) hts_close(fp); regidx_destroy(idx); return NULL; } void regidx_destroy(regidx_t *idx) { int i, j; for (i=0; i<idx->nseq; i++) { reglist_t *list = &idx->seq[i]; if ( idx->free ) { for (j=0; j<list->nregs; j++) idx->free(list->payload + idx->payload_size*j); } free(list->payload); free(list->regs); free(list->idx); } free(idx->seq_names); free(idx->seq); free(idx->str.s); free(idx->payload); khash_str2int_destroy_free(idx->seq2regs); free(idx); } int regidx_overlap(regidx_t *idx, const char *chr, uint32_t from, uint32_t to, regitr_t *itr) { if ( itr ) itr->i = itr->n = 0; int iseq; if ( khash_str2int_get(idx->seq2regs, chr, &iseq)!=0 ) return 0; // no such sequence reglist_t *list = &idx->seq[iseq]; if ( !list->nregs ) return 0; int i, ibeg = from>>LIDX_SHIFT; int ireg = ibeg < list->nidx ? list->idx[ibeg] : list->idx[ list->nidx - 1 ]; if ( ireg < 0 ) { // linear search; if slow, replace with binary search if ( ibeg > list->nidx ) ibeg = list->nidx; for (i=ibeg - 1; i>=0; i--) if ( list->idx[i] >=0 ) break; ireg = i>=0 ? list->idx[i] : 0; } for (i=ireg; i<list->nregs; i++) { if ( list->regs[i].start > to ) return 0; // no match if ( list->regs[i].end >= from && list->regs[i].start <= to ) break; // found } if ( i>=list->nregs ) return 0; // no match if ( !itr ) return 1; itr->i = 0; itr->n = list->nregs - i; itr->reg = &idx->seq[iseq].regs[i]; if ( idx->payload_size ) itr->payload = idx->seq[iseq].payload + i*idx->payload_size; else itr->payload = NULL; return 1; } int regidx_parse_bed(const char *line, char **chr_beg, char **chr_end, reg_t *reg, void *payload, void *usr) { char *ss = (char*) line; while ( *ss && isspace(*ss) ) ss++; if ( !*ss ) return -1; // skip blank lines if ( *ss=='#' ) return -1; // skip comments char *se = ss; while ( *se && !isspace(*se) ) se++; if ( !*se ) { fprintf(stderr,"Could not parse bed line: %s\n", line); return -2; } *chr_beg = ss; *chr_end = se-1; ss = se+1; reg->start = hts_parse_decimal(ss, &se, 0); if ( ss==se ) { fprintf(stderr,"Could not parse bed line: %s\n", line); return -2; } ss = se+1; reg->end = hts_parse_decimal(ss, &se, 0) - 1; if ( ss==se ) { fprintf(stderr,"Could not parse bed line: %s\n", line); return -2; } return 0; } int regidx_parse_tab(const char *line, char **chr_beg, char **chr_end, reg_t *reg, void *payload, void *usr) { char *ss = (char*) line; while ( *ss && isspace(*ss) ) ss++; if ( !*ss ) return -1; // skip blank lines if ( *ss=='#' ) return -1; // skip comments char *se = ss; while ( *se && !isspace(*se) ) se++; if ( !*se ) { fprintf(stderr,"Could not parse bed line: %s\n", line); return -2; } *chr_beg = ss; *chr_end = se-1; ss = se+1; reg->start = hts_parse_decimal(ss, &se, 0) - 1; if ( ss==se ) { fprintf(stderr,"Could not parse bed line: %s\n", line); return -2; } if ( !se[0] || !se[1] ) reg->end = reg->start; else { ss = se+1; reg->end = hts_parse_decimal(ss, &se, 0); if ( ss==se ) reg->end = reg->start; else reg->end--; } return 0; }
mit
arrosado/xavenEngine
OpenGL/Game Engine/Physics Engine/Box2D/Dynamics/Joints/b2PulleyJoint.cpp
30
8542
/* * Copyright (c) 2007 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Box2D/Dynamics/Joints/b2PulleyJoint.h> #include <Box2D/Dynamics/b2Body.h> #include <Box2D/Dynamics/b2TimeStep.h> // Pulley: // length1 = norm(p1 - s1) // length2 = norm(p2 - s2) // C0 = (length1 + ratio * length2)_initial // C = C0 - (length1 + ratio * length2) // u1 = (p1 - s1) / norm(p1 - s1) // u2 = (p2 - s2) / norm(p2 - s2) // Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) // J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& groundA, const b2Vec2& groundB, const b2Vec2& anchorA, const b2Vec2& anchorB, float32 r) { bodyA = bA; bodyB = bB; groundAnchorA = groundA; groundAnchorB = groundB; localAnchorA = bodyA->GetLocalPoint(anchorA); localAnchorB = bodyB->GetLocalPoint(anchorB); b2Vec2 dA = anchorA - groundA; lengthA = dA.Length(); b2Vec2 dB = anchorB - groundB; lengthB = dB.Length(); ratio = r; b2Assert(ratio > b2_epsilon); } b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) : b2Joint(def) { m_groundAnchorA = def->groundAnchorA; m_groundAnchorB = def->groundAnchorB; m_localAnchorA = def->localAnchorA; m_localAnchorB = def->localAnchorB; m_lengthA = def->lengthA; m_lengthB = def->lengthB; b2Assert(def->ratio != 0.0f); m_ratio = def->ratio; m_constant = def->lengthA + m_ratio * def->lengthB; m_impulse = 0.0f; } void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) { m_indexA = m_bodyA->m_islandIndex; m_indexB = m_bodyB->m_islandIndex; m_localCenterA = m_bodyA->m_sweep.localCenter; m_localCenterB = m_bodyB->m_sweep.localCenter; m_invMassA = m_bodyA->m_invMass; m_invMassB = m_bodyB->m_invMass; m_invIA = m_bodyA->m_invI; m_invIB = m_bodyB->m_invI; b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Rot qA(aA), qB(aB); m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // Get the pulley axes. m_uA = cA + m_rA - m_groundAnchorA; m_uB = cB + m_rB - m_groundAnchorB; float32 lengthA = m_uA.Length(); float32 lengthB = m_uB.Length(); if (lengthA > 10.0f * b2_linearSlop) { m_uA *= 1.0f / lengthA; } else { m_uA.SetZero(); } if (lengthB > 10.0f * b2_linearSlop) { m_uB *= 1.0f / lengthB; } else { m_uB.SetZero(); } // Compute effective mass. float32 ruA = b2Cross(m_rA, m_uA); float32 ruB = b2Cross(m_rB, m_uB); float32 mA = m_invMassA + m_invIA * ruA * ruA; float32 mB = m_invMassB + m_invIB * ruB * ruB; m_mass = mA + m_ratio * m_ratio * mB; if (m_mass > 0.0f) { m_mass = 1.0f / m_mass; } if (data.step.warmStarting) { // Scale impulses to support variable time steps. m_impulse *= data.step.dtRatio; // Warm starting. b2Vec2 PA = -(m_impulse) * m_uA; b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; vA += m_invMassA * PA; wA += m_invIA * b2Cross(m_rA, PA); vB += m_invMassB * PB; wB += m_invIB * b2Cross(m_rB, PB); } else { m_impulse = 0.0f; } data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) { b2Vec2 vA = data.velocities[m_indexA].v; float32 wA = data.velocities[m_indexA].w; b2Vec2 vB = data.velocities[m_indexB].v; float32 wB = data.velocities[m_indexB].w; b2Vec2 vpA = vA + b2Cross(wA, m_rA); b2Vec2 vpB = vB + b2Cross(wB, m_rB); float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); float32 impulse = -m_mass * Cdot; m_impulse += impulse; b2Vec2 PA = -impulse * m_uA; b2Vec2 PB = -m_ratio * impulse * m_uB; vA += m_invMassA * PA; wA += m_invIA * b2Cross(m_rA, PA); vB += m_invMassB * PB; wB += m_invIB * b2Cross(m_rB, PB); data.velocities[m_indexA].v = vA; data.velocities[m_indexA].w = wA; data.velocities[m_indexB].v = vB; data.velocities[m_indexB].w = wB; } bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) { b2Vec2 cA = data.positions[m_indexA].c; float32 aA = data.positions[m_indexA].a; b2Vec2 cB = data.positions[m_indexB].c; float32 aB = data.positions[m_indexB].a; b2Rot qA(aA), qB(aB); b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); // Get the pulley axes. b2Vec2 uA = cA + rA - m_groundAnchorA; b2Vec2 uB = cB + rB - m_groundAnchorB; float32 lengthA = uA.Length(); float32 lengthB = uB.Length(); if (lengthA > 10.0f * b2_linearSlop) { uA *= 1.0f / lengthA; } else { uA.SetZero(); } if (lengthB > 10.0f * b2_linearSlop) { uB *= 1.0f / lengthB; } else { uB.SetZero(); } // Compute effective mass. float32 ruA = b2Cross(rA, uA); float32 ruB = b2Cross(rB, uB); float32 mA = m_invMassA + m_invIA * ruA * ruA; float32 mB = m_invMassB + m_invIB * ruB * ruB; float32 mass = mA + m_ratio * m_ratio * mB; if (mass > 0.0f) { mass = 1.0f / mass; } float32 C = m_constant - lengthA - m_ratio * lengthB; float32 linearError = b2Abs(C); float32 impulse = -mass * C; b2Vec2 PA = -impulse * uA; b2Vec2 PB = -m_ratio * impulse * uB; cA += m_invMassA * PA; aA += m_invIA * b2Cross(rA, PA); cB += m_invMassB * PB; aB += m_invIB * b2Cross(rB, PB); data.positions[m_indexA].c = cA; data.positions[m_indexA].a = aA; data.positions[m_indexB].c = cB; data.positions[m_indexB].a = aB; return linearError < b2_linearSlop; } b2Vec2 b2PulleyJoint::GetAnchorA() const { return m_bodyA->GetWorldPoint(m_localAnchorA); } b2Vec2 b2PulleyJoint::GetAnchorB() const { return m_bodyB->GetWorldPoint(m_localAnchorB); } b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const { b2Vec2 P = m_impulse * m_uB; return inv_dt * P; } float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const { B2_NOT_USED(inv_dt); return 0.0f; } b2Vec2 b2PulleyJoint::GetGroundAnchorA() const { return m_groundAnchorA; } b2Vec2 b2PulleyJoint::GetGroundAnchorB() const { return m_groundAnchorB; } float32 b2PulleyJoint::GetLengthA() const { b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); b2Vec2 s = m_groundAnchorA; b2Vec2 d = p - s; return d.Length(); } float32 b2PulleyJoint::GetLengthB() const { b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); b2Vec2 s = m_groundAnchorB; b2Vec2 d = p - s; return d.Length(); } float32 b2PulleyJoint::GetRatio() const { return m_ratio; } void b2PulleyJoint::Dump() { int32 indexA = m_bodyA->m_islandIndex; int32 indexB = m_bodyB->m_islandIndex; b2Log(" b2PulleyJointDef jd;\n"); b2Log(" jd.bodyA = bodies[%d];\n", indexA); b2Log(" jd.bodyB = bodies[%d];\n", indexB); b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); b2Log(" jd.ratio = %.15lef;\n", m_ratio); b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); }
mit
quyse/inanity
deps/bullet/repo/Extras/CDTestFramework/Opcode/Ice/IceTriangle.cpp
31
13367
/* * ICE / OPCODE - Optimized Collision Detection * http://www.codercorner.com/Opcode.htm * * Copyright (c) 2001-2008 Pierre Terdiman, pierre@codercorner.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains a handy triangle class. * \file IceTriangle.cpp * \author Pierre Terdiman * \date January, 17, 2000 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Precompiled Header #include "Stdafx.h" using namespace Opcode; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Contains a triangle class. * * \class Tri * \author Pierre Terdiman * \version 1.0 * \date 08.15.98 */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// static sdword VPlaneSideEps(const Point& v, const Plane& plane, float epsilon) { // Compute distance from current vertex to the plane float Dist = plane.Distance(v); // Compute side: // 1 = the vertex is on the positive side of the plane // -1 = the vertex is on the negative side of the plane // 0 = the vertex is on the plane (within epsilon) return Dist > epsilon ? 1 : Dist < -epsilon ? -1 : 0; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Flips the winding order. */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Triangle::Flip() { Point Tmp = mVerts[1]; mVerts[1] = mVerts[2]; mVerts[2] = Tmp; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle area. * \return the area */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float Triangle::Area() const { const Point& p0 = mVerts[0]; const Point& p1 = mVerts[1]; const Point& p2 = mVerts[2]; return ((p0 - p1)^(p0 - p2)).Magnitude() * 0.5f; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle perimeter. * \return the perimeter */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float Triangle::Perimeter() const { const Point& p0 = mVerts[0]; const Point& p1 = mVerts[1]; const Point& p2 = mVerts[2]; return p0.Distance(p1) + p0.Distance(p2) + p1.Distance(p2); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle compacity. * \return the compacity */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float Triangle::Compacity() const { float P = Perimeter(); if(P==0.0f) return 0.0f; return (4.0f*PI*Area()/(P*P)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle normal. * \param normal [out] the computed normal */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Triangle::Normal(Point& normal) const { const Point& p0 = mVerts[0]; const Point& p1 = mVerts[1]; const Point& p2 = mVerts[2]; normal = ((p0 - p1)^(p0 - p2)).Normalize(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle denormalized normal. * \param normal [out] the computed normal */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Triangle::DenormalizedNormal(Point& normal) const { const Point& p0 = mVerts[0]; const Point& p1 = mVerts[1]; const Point& p2 = mVerts[2]; normal = ((p0 - p1)^(p0 - p2)); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle center. * \param center [out] the computed center */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Triangle::Center(Point& center) const { const Point& p0 = mVerts[0]; const Point& p1 = mVerts[1]; const Point& p2 = mVerts[2]; center = (p0 + p1 + p2)*INV3; } PartVal Triangle::TestAgainstPlane(const Plane& plane, float epsilon) const { bool Pos = false, Neg = false; // Loop through all vertices for(udword i=0;i<3;i++) { // Compute side: sdword Side = VPlaneSideEps(mVerts[i], plane, epsilon); if (Side < 0) Neg = true; else if (Side > 0) Pos = true; } if (!Pos && !Neg) return TRI_ON_PLANE; else if (Pos && Neg) return TRI_INTERSECT; else if (Pos && !Neg) return TRI_PLUS_SPACE; else if (!Pos && Neg) return TRI_MINUS_SPACE; // What?! return TRI_FORCEDWORD; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle moment. * \param m [out] the moment */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* void Triangle::ComputeMoment(Moment& m) { // Compute the area of the triangle m.mArea = Area(); // Compute the centroid Center(m.mCentroid); // Second-order components. Handle zero-area faces. Point& p = mVerts[0]; Point& q = mVerts[1]; Point& r = mVerts[2]; if(m.mArea==0.0f) { // This triangle has zero area. The second order components would be eliminated with the usual formula, so, for the // sake of robustness we use an alternative form. These are the centroid and second-order components of the triangle's vertices. m.mCovariance.m[0][0] = (p.x*p.x + q.x*q.x + r.x*r.x); m.mCovariance.m[0][1] = (p.x*p.y + q.x*q.y + r.x*r.y); m.mCovariance.m[0][2] = (p.x*p.z + q.x*q.z + r.x*r.z); m.mCovariance.m[1][1] = (p.y*p.y + q.y*q.y + r.y*r.y); m.mCovariance.m[1][2] = (p.y*p.z + q.y*q.z + r.y*r.z); m.mCovariance.m[2][2] = (p.z*p.z + q.z*q.z + r.z*r.z); m.mCovariance.m[2][1] = m.mCovariance.m[1][2]; m.mCovariance.m[1][0] = m.mCovariance.m[0][1]; m.mCovariance.m[2][0] = m.mCovariance.m[0][2]; } else { const float OneOverTwelve = 1.0f / 12.0f; m.mCovariance.m[0][0] = m.mArea * (9.0f * m.mCentroid.x*m.mCentroid.x + p.x*p.x + q.x*q.x + r.x*r.x) * OneOverTwelve; m.mCovariance.m[0][1] = m.mArea * (9.0f * m.mCentroid.x*m.mCentroid.y + p.x*p.y + q.x*q.y + r.x*r.y) * OneOverTwelve; m.mCovariance.m[1][1] = m.mArea * (9.0f * m.mCentroid.y*m.mCentroid.y + p.y*p.y + q.y*q.y + r.y*r.y) * OneOverTwelve; m.mCovariance.m[0][2] = m.mArea * (9.0f * m.mCentroid.x*m.mCentroid.z + p.x*p.z + q.x*q.z + r.x*r.z) * OneOverTwelve; m.mCovariance.m[1][2] = m.mArea * (9.0f * m.mCentroid.y*m.mCentroid.z + p.y*p.z + q.y*q.z + r.y*r.z) * OneOverTwelve; m.mCovariance.m[2][2] = m.mArea * (9.0f * m.mCentroid.z*m.mCentroid.z + p.z*p.z + q.z*q.z + r.z*r.z) * OneOverTwelve; m.mCovariance.m[2][1] = m.mCovariance.m[1][2]; m.mCovariance.m[1][0] = m.mCovariance.m[0][1]; m.mCovariance.m[2][0] = m.mCovariance.m[0][2]; } } */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle's smallest edge length. * \return the smallest edge length */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float Triangle::MinEdgeLength() const { float Min = MAX_FLOAT; float Length01 = mVerts[0].Distance(mVerts[1]); float Length02 = mVerts[0].Distance(mVerts[2]); float Length12 = mVerts[1].Distance(mVerts[2]); if(Length01 < Min) Min = Length01; if(Length02 < Min) Min = Length02; if(Length12 < Min) Min = Length12; return Min; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes the triangle's largest edge length. * \return the largest edge length */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// float Triangle::MaxEdgeLength() const { float Max = MIN_FLOAT; float Length01 = mVerts[0].Distance(mVerts[1]); float Length02 = mVerts[0].Distance(mVerts[2]); float Length12 = mVerts[1].Distance(mVerts[2]); if(Length01 > Max) Max = Length01; if(Length02 > Max) Max = Length02; if(Length12 > Max) Max = Length12; return Max; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * Computes a point on the triangle according to the stabbing information. * \param u,v [in] point's barycentric coordinates * \param pt [out] point on triangle * \param nearvtx [out] index of nearest vertex */ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void Triangle::ComputePoint(float u, float v, Point& pt, udword* nearvtx) const { // Compute point coordinates pt = (1.0f - u - v)*mVerts[0] + u*mVerts[1] + v*mVerts[2]; // Compute nearest vertex if needed if(nearvtx) { // Compute distance vector Point d(mVerts[0].SquareDistance(pt), // Distance^2 from vertex 0 to point on the face mVerts[1].SquareDistance(pt), // Distance^2 from vertex 1 to point on the face mVerts[2].SquareDistance(pt)); // Distance^2 from vertex 2 to point on the face // Get smallest distance *nearvtx = d.SmallestAxis(); } } void Triangle::Inflate(float fat_coeff, bool constant_border) { // Compute triangle center Point TriangleCenter; Center(TriangleCenter); // Don't normalize? // Normalize => add a constant border, regardless of triangle size // Don't => add more to big triangles for(udword i=0;i<3;i++) { Point v = mVerts[i] - TriangleCenter; if(constant_border) v.Normalize(); mVerts[i] += v * fat_coeff; } }
mit
Hom-Wang/SmartIMU
firmware/NRF_Peripheral_TEMP/Libraries/modules/nrfx/drivers/src/nrfx_power.c
34
8662
/** * Copyright (c) 2017 - 2018, Nordic Semiconductor ASA * * 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, except as embedded into a Nordic * Semiconductor ASA integrated circuit in a product or a software update for * such product, 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 Nordic Semiconductor ASA nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * 4. This software, with or without modification, must only be used with a * Nordic Semiconductor ASA integrated circuit. * * 5. Any software provided in binary form under this license must not be reverse * engineered, decompiled, modified and/or disassembled. * * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <nrfx.h> #if NRFX_CHECK(NRFX_POWER_ENABLED) #include <nrfx_power.h> #if NRFX_CHECK(NRFX_CLOCK_ENABLED) extern bool nrfx_clock_irq_enabled; #endif /** * @internal * @defgroup nrfx_power_internals POWER driver internals * @ingroup nrfx_power * * Internal variables, auxiliary macros and functions of POWER driver. * @{ */ /** * This variable is used to check whether common POWER_CLOCK common interrupt * should be disabled or not if @ref nrfx_clock tries to disable the interrupt. */ bool nrfx_power_irq_enabled; /** * @brief The initialization flag */ #define m_initialized nrfx_power_irq_enabled /** * @brief The handler of power fail comparator warning event */ static nrfx_power_pofwarn_event_handler_t m_pofwarn_handler; #if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__) /** * @brief The handler of sleep event handler */ static nrfx_power_sleep_event_handler_t m_sleepevt_handler; #endif #if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__) /** * @brief The handler of USB power events */ static nrfx_power_usb_event_handler_t m_usbevt_handler; #endif /** @} */ nrfx_power_pofwarn_event_handler_t nrfx_power_pof_handler_get(void) { return m_pofwarn_handler; } #if NRF_POWER_HAS_USBREG nrfx_power_usb_event_handler_t nrfx_power_usb_handler_get(void) { return m_usbevt_handler; } #endif nrfx_err_t nrfx_power_init(nrfx_power_config_t const * p_config) { NRFX_ASSERT(p_config); if (m_initialized) { return NRFX_ERROR_ALREADY_INITIALIZED; } #if NRF_POWER_HAS_VDDH nrf_power_dcdcen_vddh_set(p_config->dcdcenhv); #endif nrf_power_dcdcen_set(p_config->dcdcen); nrfx_power_clock_irq_init(); m_initialized = true; return NRFX_SUCCESS; } void nrfx_power_uninit(void) { NRFX_ASSERT(m_initialized); #if NRFX_CHECK(NRFX_CLOCK_ENABLED) if (!nrfx_clock_irq_enabled) #endif { NRFX_IRQ_DISABLE(POWER_CLOCK_IRQn); } nrfx_power_pof_uninit(); #if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__) nrfx_power_sleepevt_uninit(); #endif #if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__) nrfx_power_usbevt_uninit(); #endif m_initialized = false; } void nrfx_power_pof_init(nrfx_power_pofwarn_config_t const * p_config) { NRFX_ASSERT(p_config != NULL); nrfx_power_pof_uninit(); if (p_config->handler != NULL) { m_pofwarn_handler = p_config->handler; } } void nrfx_power_pof_enable(nrfx_power_pofwarn_config_t const * p_config) { nrf_power_pofcon_set(true, p_config->thr); #if NRF_POWER_HAS_VDDH || defined(__NRFX_DOXYGEN__) nrf_power_pofcon_vddh_set(p_config->thrvddh); #endif if (m_pofwarn_handler != NULL) { nrf_power_int_enable(NRF_POWER_INT_POFWARN_MASK); } } void nrfx_power_pof_disable(void) { nrf_power_int_disable(NRF_POWER_INT_POFWARN_MASK); } void nrfx_power_pof_uninit(void) { m_pofwarn_handler = NULL; } #if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__) void nrfx_power_sleepevt_init(nrfx_power_sleepevt_config_t const * p_config) { NRFX_ASSERT(p_config != NULL); nrfx_power_sleepevt_uninit(); if (p_config->handler != NULL) { m_sleepevt_handler = p_config->handler; } } void nrfx_power_sleepevt_enable(nrfx_power_sleepevt_config_t const * p_config) { uint32_t enmask = 0; if (p_config->en_enter) { enmask |= NRF_POWER_INT_SLEEPENTER_MASK; nrf_power_event_clear(NRF_POWER_EVENT_SLEEPENTER); } if (p_config->en_exit) { enmask |= NRF_POWER_INT_SLEEPEXIT_MASK; nrf_power_event_clear(NRF_POWER_EVENT_SLEEPEXIT); } nrf_power_int_enable(enmask); } void nrfx_power_sleepevt_disable(void) { nrf_power_int_disable( NRF_POWER_INT_SLEEPENTER_MASK | NRF_POWER_INT_SLEEPEXIT_MASK); } void nrfx_power_sleepevt_uninit(void) { m_sleepevt_handler = NULL; } #endif /* NRF_POWER_HAS_SLEEPEVT */ #if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__) void nrfx_power_usbevt_init(nrfx_power_usbevt_config_t const * p_config) { nrfx_power_usbevt_uninit(); if (p_config->handler != NULL) { m_usbevt_handler = p_config->handler; } } void nrfx_power_usbevt_enable(void) { nrf_power_int_enable( NRF_POWER_INT_USBDETECTED_MASK | NRF_POWER_INT_USBREMOVED_MASK | NRF_POWER_INT_USBPWRRDY_MASK); } void nrfx_power_usbevt_disable(void) { nrf_power_int_disable( NRF_POWER_INT_USBDETECTED_MASK | NRF_POWER_INT_USBREMOVED_MASK | NRF_POWER_INT_USBPWRRDY_MASK); } void nrfx_power_usbevt_uninit(void) { m_usbevt_handler = NULL; } #endif /* NRF_POWER_HAS_USBREG */ void nrfx_power_irq_handler(void) { uint32_t enabled = nrf_power_int_enable_get(); if ((0 != (enabled & NRF_POWER_INT_POFWARN_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_POFWARN)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_pofwarn_handler != NULL); m_pofwarn_handler(); } #if NRF_POWER_HAS_SLEEPEVT || defined(__NRFX_DOXYGEN__) if ((0 != (enabled & NRF_POWER_INT_SLEEPENTER_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_SLEEPENTER)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_sleepevt_handler != NULL); m_sleepevt_handler(NRFX_POWER_SLEEP_EVT_ENTER); } if ((0 != (enabled & NRF_POWER_INT_SLEEPEXIT_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_SLEEPEXIT)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_sleepevt_handler != NULL); m_sleepevt_handler(NRFX_POWER_SLEEP_EVT_EXIT); } #endif #if NRF_POWER_HAS_USBREG || defined(__NRFX_DOXYGEN__) if ((0 != (enabled & NRF_POWER_INT_USBDETECTED_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBDETECTED)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_usbevt_handler != NULL); m_usbevt_handler(NRFX_POWER_USB_EVT_DETECTED); } if ((0 != (enabled & NRF_POWER_INT_USBREMOVED_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBREMOVED)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_usbevt_handler != NULL); m_usbevt_handler(NRFX_POWER_USB_EVT_REMOVED); } if ((0 != (enabled & NRF_POWER_INT_USBPWRRDY_MASK)) && nrf_power_event_get_and_clear(NRF_POWER_EVENT_USBPWRRDY)) { /* Cannot be null if event is enabled */ NRFX_ASSERT(m_usbevt_handler != NULL); m_usbevt_handler(NRFX_POWER_USB_EVT_READY); } #endif } #endif // NRFX_CHECK(NRFX_POWER_ENABLED)
mit
pedrohenriquerls/flappybird_cocos2d
cocos2d/cocos/platform/winrt/CCDevice.cpp
36
7741
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "platform/CCPlatformConfig.h" #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) #include "platform/CCDevice.h" #include "platform/CCFileUtils.h" #include "platform/winrt/CCFreeTypeFont.h" #include "platform/winrt/CCWinRTUtils.h" #include "platform/CCStdC.h" #include "platform/winrt/CCGLViewImpl-winrt.h" using namespace Windows::Graphics::Display; using namespace Windows::Devices::Sensors; using namespace Windows::Foundation; #if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) using namespace Windows::Phone::Devices::Notification; #endif // (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) NS_CC_BEGIN CCFreeTypeFont sFT; int Device::getDPI() { return cocos2d::GLViewImpl::sharedOpenGLView()->GetDPI(); } static Accelerometer^ sAccelerometer = nullptr; void Device::setAccelerometerEnabled(bool isEnabled) { static Windows::Foundation::EventRegistrationToken sToken; static bool sEnabled = false; // we always need to reset the accelerometer if (sAccelerometer) { sAccelerometer->ReadingChanged -= sToken; sAccelerometer = nullptr; sEnabled = false; } if (isEnabled) { sAccelerometer = Accelerometer::GetDefault(); if(sAccelerometer == nullptr) { // It's not a friendly experience and may cause crash. //MessageBox("This device does not have an accelerometer.","Alert"); log("This device does not have an accelerometer."); return; } setAccelerometerInterval(0.0f); sEnabled = true; sToken = sAccelerometer->ReadingChanged += ref new TypedEventHandler <Accelerometer^,AccelerometerReadingChangedEventArgs^> ([](Accelerometer^ a, AccelerometerReadingChangedEventArgs^ e) { if (!sEnabled) { return; } AccelerometerReading^ reading = e->Reading; cocos2d::Acceleration acc; acc.x = reading->AccelerationX; acc.y = reading->AccelerationY; acc.z = reading->AccelerationZ; acc.timestamp = 0; auto orientation = GLViewImpl::sharedOpenGLView()->getDeviceOrientation(); if (isWindowsPhone()) { switch (orientation) { case DisplayOrientations::Portrait: acc.x = reading->AccelerationX; acc.y = reading->AccelerationY; break; case DisplayOrientations::Landscape: acc.x = -reading->AccelerationY; acc.y = reading->AccelerationX; break; case DisplayOrientations::PortraitFlipped: acc.x = -reading->AccelerationX; acc.y = reading->AccelerationY; break; case DisplayOrientations::LandscapeFlipped: acc.x = reading->AccelerationY; acc.y = -reading->AccelerationX; break; default: acc.x = reading->AccelerationX; acc.y = reading->AccelerationY; break; } } else // Windows Store App { // from http://msdn.microsoft.com/en-us/library/windows/apps/dn440593 switch (orientation) { case DisplayOrientations::Portrait: acc.x = reading->AccelerationY; acc.y = -reading->AccelerationX; break; case DisplayOrientations::Landscape: acc.x = reading->AccelerationX; acc.y = reading->AccelerationY; break; case DisplayOrientations::PortraitFlipped: acc.x = -reading->AccelerationY; acc.y = reading->AccelerationX; break; case DisplayOrientations::LandscapeFlipped: acc.x = -reading->AccelerationX; acc.y = -reading->AccelerationY; break; default: acc.x = reading->AccelerationY; acc.y = -reading->AccelerationX; break; } } std::shared_ptr<cocos2d::InputEvent> event(new AccelerometerEvent(acc)); cocos2d::GLViewImpl::sharedOpenGLView()->QueueEvent(event); }); } } void Device::setAccelerometerInterval(float interval) { if (sAccelerometer) { try { int minInterval = sAccelerometer->MinimumReportInterval; int reqInterval = (int) interval; sAccelerometer->ReportInterval = reqInterval < minInterval ? minInterval : reqInterval; } catch (Platform::COMException^) { CCLOG("Device::setAccelerometerInterval not supported on this device"); } } else { CCLOG("Device::setAccelerometerInterval: accelerometer not enabled."); } } Data Device::getTextureDataForText(const char * text, const FontDefinition& textDefinition, TextAlign align, int &width, int &height, bool& hasPremultipliedAlpha) { Data ret; ssize_t dataLen; unsigned char* data = sFT.initWithString(text, textDefinition, align, width, height, dataLen); if (data) { ret.fastSet(data, dataLen); hasPremultipliedAlpha = false; } return ret; } void Device::setKeepScreenOn(bool value) { CC_UNUSED_PARAM(value); } void Device::vibrate(float duration) { #if (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) Windows::Foundation::TimeSpan timespan; // A time period expressed in 100-nanosecond units, see https://msdn.microsoft.com/en-us/library/windows/apps/windows.foundation.timespan.aspx // The duration is limited to a maximum of 5 seconds, see https://msdn.microsoft.com/en-us/library/windows/apps/windows.phone.devices.notification.vibrationdevice.aspx timespan.Duration = std::min(static_cast<int>(duration * 10000), 50000); VibrationDevice^ testVibrationDevice = VibrationDevice::GetDefault(); testVibrationDevice->Vibrate(timespan); #else CC_UNUSED_PARAM(duration); #endif // (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) } NS_CC_END #endif // (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
mit
orefkov/Urho3D
Source/ThirdParty/FreeType/src/sfnt/ttkern.c
38
7930
/***************************************************************************/ /* */ /* ttkern.c */ /* */ /* Load the basic TrueType kerning table. This doesn't handle */ /* kerning data within the GPOS table at the moment. */ /* */ /* Copyright 1996-2017 by */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ #include <ft2build.h> #include FT_INTERNAL_DEBUG_H #include FT_INTERNAL_STREAM_H #include FT_TRUETYPE_TAGS_H #include "ttkern.h" #include "sferrors.h" /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_ttkern #undef TT_KERN_INDEX #define TT_KERN_INDEX( g1, g2 ) ( ( (FT_ULong)(g1) << 16 ) | (g2) ) FT_LOCAL_DEF( FT_Error ) tt_face_load_kern( TT_Face face, FT_Stream stream ) { FT_Error error; FT_ULong table_size; FT_Byte* p; FT_Byte* p_limit; FT_UInt nn, num_tables; FT_UInt32 avail = 0, ordered = 0; /* the kern table is optional; exit silently if it is missing */ error = face->goto_table( face, TTAG_kern, stream, &table_size ); if ( error ) goto Exit; if ( table_size < 4 ) /* the case of a malformed table */ { FT_ERROR(( "tt_face_load_kern:" " kerning table is too small - ignored\n" )); error = FT_THROW( Table_Missing ); goto Exit; } if ( FT_FRAME_EXTRACT( table_size, face->kern_table ) ) { FT_ERROR(( "tt_face_load_kern:" " could not extract kerning table\n" )); goto Exit; } face->kern_table_size = table_size; p = face->kern_table; p_limit = p + table_size; p += 2; /* skip version */ num_tables = FT_NEXT_USHORT( p ); if ( num_tables > 32 ) /* we only support up to 32 sub-tables */ num_tables = 32; for ( nn = 0; nn < num_tables; nn++ ) { FT_UInt num_pairs, length, coverage; FT_Byte* p_next; FT_UInt32 mask = (FT_UInt32)1UL << nn; if ( p + 6 > p_limit ) break; p_next = p; p += 2; /* skip version */ length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); if ( length <= 6 + 8 ) break; p_next += length; if ( p_next > p_limit ) /* handle broken table */ p_next = p_limit; /* only use horizontal kerning tables */ if ( ( coverage & 3U ) != 0x0001 || p + 8 > p_next ) goto NextTable; num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( p_next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( p_next - p ) / 6 ); avail |= mask; /* * Now check whether the pairs in this table are ordered. * We then can use binary search. */ if ( num_pairs > 0 ) { FT_ULong count; FT_ULong old_pair; old_pair = FT_NEXT_ULONG( p ); p += 2; for ( count = num_pairs - 1; count > 0; count-- ) { FT_UInt32 cur_pair; cur_pair = FT_NEXT_ULONG( p ); if ( cur_pair <= old_pair ) break; p += 2; old_pair = cur_pair; } if ( count == 0 ) ordered |= mask; } NextTable: p = p_next; } face->num_kern_tables = nn; face->kern_avail_bits = avail; face->kern_order_bits = ordered; Exit: return error; } FT_LOCAL_DEF( void ) tt_face_done_kern( TT_Face face ) { FT_Stream stream = face->root.stream; FT_FRAME_RELEASE( face->kern_table ); face->kern_table_size = 0; face->num_kern_tables = 0; face->kern_avail_bits = 0; face->kern_order_bits = 0; } FT_LOCAL_DEF( FT_Int ) tt_face_get_kerning( TT_Face face, FT_UInt left_glyph, FT_UInt right_glyph ) { FT_Int result = 0; FT_UInt count, mask; FT_Byte* p = face->kern_table; FT_Byte* p_limit = p + face->kern_table_size; p += 4; mask = 0x0001; for ( count = face->num_kern_tables; count > 0 && p + 6 <= p_limit; count--, mask <<= 1 ) { FT_Byte* base = p; FT_Byte* next; FT_UInt version = FT_NEXT_USHORT( p ); FT_UInt length = FT_NEXT_USHORT( p ); FT_UInt coverage = FT_NEXT_USHORT( p ); FT_UInt num_pairs; FT_Int value = 0; FT_UNUSED( version ); next = base + length; if ( next > p_limit ) /* handle broken table */ next = p_limit; if ( ( face->kern_avail_bits & mask ) == 0 ) goto NextTable; FT_ASSERT( p + 8 <= next ); /* tested in tt_face_load_kern */ num_pairs = FT_NEXT_USHORT( p ); p += 6; if ( ( next - p ) < 6 * (int)num_pairs ) /* handle broken count */ num_pairs = (FT_UInt)( ( next - p ) / 6 ); switch ( coverage >> 8 ) { case 0: { FT_ULong key0 = TT_KERN_INDEX( left_glyph, right_glyph ); if ( face->kern_order_bits & mask ) /* binary search */ { FT_UInt min = 0; FT_UInt max = num_pairs; while ( min < max ) { FT_UInt mid = ( min + max ) >> 1; FT_Byte* q = p + 6 * mid; FT_ULong key; key = FT_NEXT_ULONG( q ); if ( key == key0 ) { value = FT_PEEK_SHORT( q ); goto Found; } if ( key < key0 ) min = mid + 1; else max = mid; } } else /* linear search */ { FT_UInt count2; for ( count2 = num_pairs; count2 > 0; count2-- ) { FT_ULong key = FT_NEXT_ULONG( p ); if ( key == key0 ) { value = FT_PEEK_SHORT( p ); goto Found; } p += 2; } } } break; /* * We don't support format 2 because we haven't seen a single font * using it in real life... */ default: ; } goto NextTable; Found: if ( coverage & 8 ) /* override or add */ result = value; else result += value; NextTable: p = next; } return result; } #undef TT_KERN_INDEX /* END */
mit
pikoro/sharpsdr
PortAudio/branches/OpenBSD_sndio/src/common/pa_dither.c
295
7177
/* * $Id: pa_dither.c 1418 2009-10-12 21:00:53Z philburk $ * Portable Audio I/O Library triangular dither generator * * Based on the Open Source API proposed by Ross Bencina * Copyright (c) 1999-2002 Phil Burk, Ross Bencina * * 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. */ /* * The text above constitutes the entire PortAudio license; however, * the PortAudio community also makes the following non-binding requests: * * Any person wishing to distribute modifications to the Software is * requested to send the modifications to the original developer so that * they can be incorporated into the canonical version. It is also * requested that these non-binding requests be included along with the * license above. */ /** @file @ingroup common_src @brief Functions for generating dither noise */ #include "pa_types.h" #include "pa_dither.h" /* Note that the linear congruential algorithm requires 32 bit integers * because it uses arithmetic overflow. So use PaUint32 instead of * unsigned long so it will work on 64 bit systems. */ #define PA_DITHER_BITS_ (15) void PaUtil_InitializeTriangularDitherState( PaUtilTriangularDitherGenerator *state ) { state->previous = 0; state->randSeed1 = 22222; state->randSeed2 = 5555555; } PaInt32 PaUtil_Generate16BitTriangularDither( PaUtilTriangularDitherGenerator *state ) { PaInt32 current, highPass; /* Generate two random numbers. */ state->randSeed1 = (state->randSeed1 * 196314165) + 907633515; state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; /* Generate triangular distribution about 0. * Shift before adding to prevent overflow which would skew the distribution. * Also shift an extra bit for the high pass filter. */ #define DITHER_SHIFT_ ((sizeof(PaInt32)*8 - PA_DITHER_BITS_) + 1) current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) + (((PaInt32)state->randSeed2)>>DITHER_SHIFT_); /* High pass filter to reduce audibility. */ highPass = current - state->previous; state->previous = current; return highPass; } /* Multiply by PA_FLOAT_DITHER_SCALE_ to get a float between -2.0 and +1.99999 */ #define PA_FLOAT_DITHER_SCALE_ (1.0f / ((1<<PA_DITHER_BITS_)-1)) static const float const_float_dither_scale_ = PA_FLOAT_DITHER_SCALE_; float PaUtil_GenerateFloatTriangularDither( PaUtilTriangularDitherGenerator *state ) { PaInt32 current, highPass; /* Generate two random numbers. */ state->randSeed1 = (state->randSeed1 * 196314165) + 907633515; state->randSeed2 = (state->randSeed2 * 196314165) + 907633515; /* Generate triangular distribution about 0. * Shift before adding to prevent overflow which would skew the distribution. * Also shift an extra bit for the high pass filter. */ current = (((PaInt32)state->randSeed1)>>DITHER_SHIFT_) + (((PaInt32)state->randSeed2)>>DITHER_SHIFT_); /* High pass filter to reduce audibility. */ highPass = current - state->previous; state->previous = current; return ((float)highPass) * const_float_dither_scale_; } /* The following alternate dither algorithms (from musicdsp.org) could be considered */ /*Noise shaped dither (March 2000) ------------------- This is a simple implementation of highpass triangular-PDF dither with 2nd-order noise shaping, for use when truncating floating point audio data to fixed point. The noise shaping lowers the noise floor by 11dB below 5kHz (@ 44100Hz sample rate) compared to triangular-PDF dither. The code below assumes input data is in the range +1 to -1 and doesn't check for overloads! To save time when generating dither for multiple channels you can do things like this: r3=(r1 & 0x7F)<<8; instead of calling rand() again. int r1, r2; //rectangular-PDF random numbers float s1, s2; //error feedback buffers float s = 0.5f; //set to 0.0f for no noise shaping float w = pow(2.0,bits-1); //word length (usually bits=16) float wi= 1.0f/w; float d = wi / RAND_MAX; //dither amplitude (2 lsb) float o = wi * 0.5f; //remove dc offset float in, tmp; int out; //for each sample... r2=r1; //can make HP-TRI dither by r1=rand(); //subtracting previous rand() in += s * (s1 + s1 - s2); //error feedback tmp = in + o + d * (float)(r1 - r2); //dc offset and dither out = (int)(w * tmp); //truncate downwards if(tmp<0.0f) out--; //this is faster than floor() s2 = s1; s1 = in - wi * (float)out; //error -- paul.kellett@maxim.abel.co.uk http://www.maxim.abel.co.uk */ /* 16-to-8-bit first-order dither Type : First order error feedforward dithering code References : Posted by Jon Watte Notes : This is about as simple a dithering algorithm as you can implement, but it's likely to sound better than just truncating to N bits. Note that you might not want to carry forward the full difference for infinity. It's probably likely that the worst performance hit comes from the saturation conditionals, which can be avoided with appropriate instructions on many DSPs and integer SIMD type instructions, or CMOV. Last, if sound quality is paramount (such as when going from > 16 bits to 16 bits) you probably want to use a higher-order dither function found elsewhere on this site. Code : // This code will down-convert and dither a 16-bit signed short // mono signal into an 8-bit unsigned char signal, using a first // order forward-feeding error term dither. #define uchar unsigned char void dither_one_channel_16_to_8( short * input, uchar * output, int count, int * memory ) { int m = *memory; while( count-- > 0 ) { int i = *input++; i += m; int j = i + 32768 - 128; uchar o; if( j < 0 ) { o = 0; } else if( j > 65535 ) { o = 255; } else { o = (uchar)((j>>8)&0xff); } m = ((j-32768+128)-i); *output++ = o; } *memory = m; } */
mit
CCPorg/PARTY-PartyCoin-Ver-631-Original
src/key.cpp
1063
11215
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2012 Litecoin Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <map> #include <openssl/ecdsa.h> #include <openssl/obj_mac.h> #include "key.h" // Generate a private key from just the secret parameter int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key) { int ok = 0; BN_CTX *ctx = NULL; EC_POINT *pub_key = NULL; if (!eckey) return 0; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) goto err; pub_key = EC_POINT_new(group); if (pub_key == NULL) goto err; if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto err; EC_KEY_set_private_key(eckey,priv_key); EC_KEY_set_public_key(eckey,pub_key); ok = 1; err: if (pub_key) EC_POINT_free(pub_key); if (ctx != NULL) BN_CTX_free(ctx); return(ok); } // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields // recid selects which key is recovered // if check is nonzero, additional checks are performed int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check) { if (!eckey) return 0; int ret = 0; BN_CTX *ctx = NULL; BIGNUM *x = NULL; BIGNUM *e = NULL; BIGNUM *order = NULL; BIGNUM *sor = NULL; BIGNUM *eor = NULL; BIGNUM *field = NULL; EC_POINT *R = NULL; EC_POINT *O = NULL; EC_POINT *Q = NULL; BIGNUM *rr = NULL; BIGNUM *zero = NULL; int n = 0; int i = recid / 2; const EC_GROUP *group = EC_KEY_get0_group(eckey); if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; } BN_CTX_start(ctx); order = BN_CTX_get(ctx); if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; } x = BN_CTX_get(ctx); if (!BN_copy(x, order)) { ret=-1; goto err; } if (!BN_mul_word(x, i)) { ret=-1; goto err; } if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; } field = BN_CTX_get(ctx); if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; } if (BN_cmp(x, field) >= 0) { ret=0; goto err; } if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; } if (check) { if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; } if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; } } if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } n = EC_GROUP_get_degree(group); e = BN_CTX_get(ctx); if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; } if (8*msglen > n) BN_rshift(e, e, 8-(n & 7)); zero = BN_CTX_get(ctx); if (!BN_zero(zero)) { ret=-1; goto err; } if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; } rr = BN_CTX_get(ctx); if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; } sor = BN_CTX_get(ctx); if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; } eor = BN_CTX_get(ctx); if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; } if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; } if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; } ret = 1; err: if (ctx) { BN_CTX_end(ctx); BN_CTX_free(ctx); } if (R != NULL) EC_POINT_free(R); if (O != NULL) EC_POINT_free(O); if (Q != NULL) EC_POINT_free(Q); return ret; } void CKey::SetCompressedPubKey() { EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED); fCompressedPubKey = true; } void CKey::Reset() { fCompressedPubKey = false; if (pkey != NULL) EC_KEY_free(pkey); pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (pkey == NULL) throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed"); fSet = false; } CKey::CKey() { pkey = NULL; Reset(); } CKey::CKey(const CKey& b) { pkey = EC_KEY_dup(b.pkey); if (pkey == NULL) throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed"); fSet = b.fSet; } CKey& CKey::operator=(const CKey& b) { if (!EC_KEY_copy(pkey, b.pkey)) throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed"); fSet = b.fSet; return (*this); } CKey::~CKey() { EC_KEY_free(pkey); } bool CKey::IsNull() const { return !fSet; } bool CKey::IsCompressed() const { return fCompressedPubKey; } void CKey::MakeNewKey(bool fCompressed) { if (!EC_KEY_generate_key(pkey)) throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed"); if (fCompressed) SetCompressedPubKey(); fSet = true; } bool CKey::SetPrivKey(const CPrivKey& vchPrivKey) { const unsigned char* pbegin = &vchPrivKey[0]; if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size())) return false; fSet = true; return true; } bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed) { EC_KEY_free(pkey); pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (pkey == NULL) throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed"); if (vchSecret.size() != 32) throw key_error("CKey::SetSecret() : secret must be 32 bytes"); BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new()); if (bn == NULL) throw key_error("CKey::SetSecret() : BN_bin2bn failed"); if (!EC_KEY_regenerate_key(pkey,bn)) { BN_clear_free(bn); throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed"); } BN_clear_free(bn); fSet = true; if (fCompressed || fCompressedPubKey) SetCompressedPubKey(); return true; } CSecret CKey::GetSecret(bool &fCompressed) const { CSecret vchRet; vchRet.resize(32); const BIGNUM *bn = EC_KEY_get0_private_key(pkey); int nBytes = BN_num_bytes(bn); if (bn == NULL) throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed"); int n=BN_bn2bin(bn,&vchRet[32 - nBytes]); if (n != nBytes) throw key_error("CKey::GetSecret(): BN_bn2bin failed"); fCompressed = fCompressedPubKey; return vchRet; } CPrivKey CKey::GetPrivKey() const { int nSize = i2d_ECPrivateKey(pkey, NULL); if (!nSize) throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed"); CPrivKey vchPrivKey(nSize, 0); unsigned char* pbegin = &vchPrivKey[0]; if (i2d_ECPrivateKey(pkey, &pbegin) != nSize) throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size"); return vchPrivKey; } bool CKey::SetPubKey(const CPubKey& vchPubKey) { const unsigned char* pbegin = &vchPubKey.vchPubKey[0]; if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size())) return false; fSet = true; if (vchPubKey.vchPubKey.size() == 33) SetCompressedPubKey(); return true; } CPubKey CKey::GetPubKey() const { int nSize = i2o_ECPublicKey(pkey, NULL); if (!nSize) throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed"); std::vector<unsigned char> vchPubKey(nSize, 0); unsigned char* pbegin = &vchPubKey[0]; if (i2o_ECPublicKey(pkey, &pbegin) != nSize) throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size"); return CPubKey(vchPubKey); } bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig) { unsigned int nSize = ECDSA_size(pkey); vchSig.resize(nSize); // Make sure it is big enough if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], &nSize, pkey)) { vchSig.clear(); return false; } vchSig.resize(nSize); // Shrink to fit actual size return true; } // create a compact signature (65 bytes), which allows reconstructing the used public key // The format is one header byte, followed by two times 32 bytes for the serialized r and s values. // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig) { bool fOk = false; ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey); if (sig==NULL) return false; vchSig.clear(); vchSig.resize(65,0); int nBitsR = BN_num_bits(sig->r); int nBitsS = BN_num_bits(sig->s); if (nBitsR <= 256 && nBitsS <= 256) { int nRecId = -1; for (int i=0; i<4; i++) { CKey keyRec; keyRec.fSet = true; if (fCompressedPubKey) keyRec.SetCompressedPubKey(); if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) if (keyRec.GetPubKey() == this->GetPubKey()) { nRecId = i; break; } } if (nRecId == -1) throw key_error("CKey::SignCompact() : unable to construct recoverable key"); vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0); BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]); BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]); fOk = true; } ECDSA_SIG_free(sig); return fOk; } // reconstruct public key from a compact signature // This is only slightly more CPU intensive than just verifying it. // If this function succeeds, the recovered public key is guaranteed to be valid // (the signature is a valid signature of the given data for that key) bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig) { if (vchSig.size() != 65) return false; int nV = vchSig[0]; if (nV<27 || nV>=35) return false; ECDSA_SIG *sig = ECDSA_SIG_new(); BN_bin2bn(&vchSig[1],32,sig->r); BN_bin2bn(&vchSig[33],32,sig->s); EC_KEY_free(pkey); pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if (nV >= 31) { SetCompressedPubKey(); nV -= 4; } if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1) { fSet = true; ECDSA_SIG_free(sig); return true; } return false; } bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig) { // -1 = error, 0 = bad sig, 1 = good if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) return false; return true; } bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig) { CKey key; if (!key.SetCompactSignature(hash, vchSig)) return false; if (GetPubKey() != key.GetPubKey()) return false; return true; } bool CKey::IsValid() { if (!fSet) return false; bool fCompr; CSecret secret = GetSecret(fCompr); CKey key2; key2.SetSecret(secret, fCompr); return GetPubKey() == key2.GetPubKey(); }
mit
nicecapj/crossplatfromMmorpgServer
ThirdParty/boost_1_61_0/libs/system/test/error_code_user_test.cpp
42
12894
// error_code_user_test.cpp ------------------------------------------------// // Copyright Beman Dawes 2006 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See library home page at http://www.boost.org/libs/system // ------------------------------------------------------------------------ // // This program demonstrates creation and use of new categories of error // codes. Several scenarios are demonstrated and tested. // Motivation was a Boost posting by Christopher Kohlhoff on June 28, 2006. #define BOOST_SYSTEM_NO_DEPRECATED #include <boost/system/error_code.hpp> #include <boost/cerrno.hpp> #include <string> #include <cstdio> #include <boost/detail/lightweight_test.hpp> #ifdef BOOST_POSIX_API # include <sys/stat.h> #else # include <windows.h> #endif // ------------------------------------------------------------------------ // // Library 1: User function passes through an error code from the // operating system. boost::system::error_code my_mkdir( const std::string & path ) { return boost::system::error_code( # ifdef BOOST_POSIX_API ::mkdir( path.c_str(), S_IRWXU|S_IRWXG|S_IROTH|S_IXOTH ) == 0 ? 0 : errno, # else ::CreateDirectoryA( path.c_str(), 0 ) != 0 ? 0 : ::GetLastError(), # endif boost::system::system_category() ); } // ------------------------------------------------------------------------ // // Library 2: User function passes through errno from the C-runtime. #include <cstdio> boost::system::error_code my_remove( const std::string & path ) { return boost::system::error_code( std::remove( path.c_str() ) == 0 ? 0 : errno, boost::system::generic_category() ); // OK for both Windows and POSIX // Alternatively, could use generic_category() // on Windows and system_category() on // POSIX-based systems. } // ------------------------------------------------------------------------ // // Library 3: Library uses enum to identify library specific errors. // This particular example is for a library within the parent namespace. For // an example of a library not within the parent namespace, see library 4. // header lib3.hpp: namespace boost { namespace lib3 { // lib3 has its own error_category: const boost::system::error_category & get_lib3_error_category() BOOST_SYSTEM_NOEXCEPT; const boost::system::error_category & lib3_error_category = get_lib3_error_category(); enum error { boo_boo=123, big_boo_boo }; } namespace system { template<> struct is_error_code_enum<boost::lib3::error> { static const bool value = true; }; } namespace lib3 { inline boost::system::error_code make_error_code(error e) { return boost::system::error_code(e,lib3_error_category); } } } // implementation file lib3.cpp: // #include <lib3.hpp> namespace boost { namespace lib3 { class lib3_error_category_imp : public boost::system::error_category { public: lib3_error_category_imp() : boost::system::error_category() { } const char * name() const BOOST_SYSTEM_NOEXCEPT { return "lib3"; } boost::system::error_condition default_error_condition( int ev ) const BOOST_SYSTEM_NOEXCEPT { return ev == boo_boo ? boost::system::error_condition( boost::system::errc::io_error, boost::system::generic_category() ) : boost::system::error_condition( ev, boost::lib3::lib3_error_category ); } std::string message( int ev ) const { if ( ev == boo_boo ) return std::string("boo boo"); if ( ev == big_boo_boo ) return std::string("big boo boo"); return std::string("unknown error"); } }; const boost::system::error_category & get_lib3_error_category() BOOST_SYSTEM_NOEXCEPT { static const lib3_error_category_imp l3ecat; return l3ecat; } } } // ------------------------------------------------------------------------ // // Library 4: Library uses const error_code's to identify library specific // errors. // This particular example is for a library not within the parent namespace. // For an example of a library within the parent namespace, see library 3. // header lib4.hpp: namespace lib4 { // lib4 has its own error_category: const boost::system::error_category & get_lib4_error_category() BOOST_SYSTEM_NOEXCEPT; const boost::system::error_category & lib4_error_category = get_lib4_error_category(); extern const boost::system::error_code boo_boo; extern const boost::system::error_code big_boo_boo; } // implementation file lib4.cpp: // #include <lib4.hpp> namespace lib4 { class lib4_error_category_imp : public boost::system::error_category { public: lib4_error_category_imp() : boost::system::error_category() { } const char * name() const BOOST_SYSTEM_NOEXCEPT { return "lib4"; } boost::system::error_condition default_error_condition( int ev ) const BOOST_SYSTEM_NOEXCEPT { return ev == boo_boo.value() ? boost::system::error_condition( boost::system::errc::io_error, boost::system::generic_category() ) : boost::system::error_condition( ev, lib4::lib4_error_category ); } std::string message( int ev ) const { if ( ev == boo_boo.value() ) return std::string("boo boo"); if ( ev == big_boo_boo.value() ) return std::string("big boo boo"); return std::string("unknown error"); } }; const boost::system::error_category & get_lib4_error_category() BOOST_SYSTEM_NOEXCEPT { static const lib4_error_category_imp l4ecat; return l4ecat; } const boost::system::error_code boo_boo( 456, lib4_error_category ); const boost::system::error_code big_boo_boo( 789, lib4_error_category ); } // ------------------------------------------------------------------------ // // Chris Kolhoff's Test3, modified to work with error_code.hpp // Test3 // ===== // Define error classes to check for success, permission_denied and // out_of_memory, but add additional mappings for a user-defined error category. // //namespace test3 { // enum user_err // { // user_success = 0, // user_permission_denied, // user_out_of_memory // }; // // class user_error_category_imp : public boost::system::error_category // { // public: // const std::string & name() const // { // static std::string s( "test3" ); // return s; // } // // boost::system::error_code portable_error_code( int ev ) const // { // switch (ev) // { // case user_success: // return boost::system::error_code(boost::system::errc::success, boost::system::generic_category()); // case user_permission_denied: // return boost::system::error_code(boost::system::errc::permission_denied, boost::system::generic_category()); // case user_out_of_memory: // return boost::system::error_code(boost::system::errc::not_enough_memory, boost::system::generic_category()); // default: // break; // } // return boost::system::error_code(boost::system::errc::no_posix_equivalent, boost::system::generic_category()); // } // // }; // // const user_error_category_imp user_error_category_const; // // const boost::system::error_category & user_error_category // = user_error_category_const; // // template<> inline boost::system::error_code make_error_code(user_err e) // { // return boost::system::error_code(e, user_error_category); // } // // // test code // // void check_success(const boost::system::error_code& ec, bool expect) // { // BOOST_TEST( (ec == boost::system::errc::success) == expect ); // if (ec == boost::system::errc::success) // std::cout << "yes... " << (expect ? "ok" : "fail") << '\n'; // else // std::cout << "no... " << (expect ? "fail" : "ok") << '\n'; // } // // void check_permission_denied(const boost::system::error_code& ec, bool expect) // { // BOOST_TEST( (ec == boost::system::errc::permission_denied) == expect ); // if (ec == boost::system::errc::permission_denied) // std::cout << "yes... " << (expect ? "ok" : "fail") << '\n'; // else // std::cout << "no... " << (expect ? "fail" : "ok") << '\n'; // } // // void check_out_of_memory(const boost::system::error_code& ec, bool expect) // { // BOOST_TEST( (ec == boost::system::errc::not_enough_memory) == expect ); // if (ec == boost::system::errc::not_enough_memory) // std::cout << "yes... " << (expect ? "ok" : "fail") << '\n'; // else // std::cout << "no... " << (expect ? "fail" : "ok") << '\n'; // } // // void run() // { // printf("Test3\n"); // printf("=====\n"); // boost::system::error_code ec; // check_success(ec, true); // check_success(boost::system::errc::success, true); // check_success(boost::system::errc::permission_denied, false); // check_success(boost::system::errc::not_enough_memory, false); // check_success(user_success, true); // check_success(user_permission_denied, false); // check_success(user_out_of_memory, false); // check_permission_denied(ec, false); // check_permission_denied(boost::system::errc::success, false); // check_permission_denied(boost::system::errc::permission_denied, true); // check_permission_denied(boost::system::errc::not_enough_memory, false); // check_permission_denied(user_success, false); // check_permission_denied(user_permission_denied, true); // check_permission_denied(user_out_of_memory, false); // check_out_of_memory(ec, false); // check_out_of_memory(boost::system::errc::success, false); // check_out_of_memory(boost::system::errc::permission_denied, false); // check_out_of_memory(boost::system::errc::not_enough_memory, true); // check_out_of_memory(user_success, false); // check_out_of_memory(user_permission_denied, false); // check_out_of_memory(user_out_of_memory, true); // //# ifdef BOOST_WINDOWS_API // check_success(boost::system::windows::success, true); // check_success(boost::system::windows::access_denied, false); // check_success(boost::system::windows::not_enough_memory, false); // check_permission_denied(boost::system::windows::success, false); // check_permission_denied(boost::system::windows::access_denied, true); // check_permission_denied(boost::system::windows::not_enough_memory, false); // check_out_of_memory(boost::system::windows::success, false); // check_out_of_memory(boost::system::windows::access_denied, false); // check_out_of_memory(boost::system::windows::not_enough_memory, true); //# endif // // printf("\n"); // } // //} // namespace test3 // ------------------------------------------------------------------------ // int main( int, char *[] ) { boost::system::error_code ec; // Library 1 tests: ec = my_mkdir( "/no-such-file-or-directory/will-not-succeed" ); std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::system::errc::no_such_file_or_directory ); BOOST_TEST( ec.category() == boost::system::system_category() ); // Library 2 tests: ec = my_remove( "/no-such-file-or-directory" ); std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::system::errc::no_such_file_or_directory ); BOOST_TEST( ec.category() == boost::system::generic_category() ); // Library 3 tests: ec = boost::lib3::boo_boo; std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == boost::lib3::boo_boo ); BOOST_TEST( ec.value() == boost::lib3::boo_boo ); BOOST_TEST( ec.category() == boost::lib3::lib3_error_category ); BOOST_TEST( ec == boost::system::errc::io_error ); boost::system::error_code ec3( boost::lib3::boo_boo+100, boost::lib3::lib3_error_category ); BOOST_TEST( ec3.category() == boost::lib3::lib3_error_category ); BOOST_TEST( ec3.default_error_condition().category() == boost::lib3::lib3_error_category ); // Library 4 tests: ec = lib4::boo_boo; std::cout << "ec.value() is " << ec.value() << '\n'; BOOST_TEST( ec ); BOOST_TEST( ec == lib4::boo_boo ); BOOST_TEST( ec.value() == lib4::boo_boo.value() ); BOOST_TEST( ec.category() == lib4::lib4_error_category ); BOOST_TEST( ec == boost::system::errc::io_error ); boost::system::error_code ec4( lib4::boo_boo.value()+100, lib4::lib4_error_category ); BOOST_TEST( ec4.default_error_condition().category() == lib4::lib4_error_category ); // Test 3 //test3::run(); return ::boost::report_errors(); }
mit
mozilla-b2g/fairphone2_kernel_lk
lib/libc/string/strtok.c
45
1662
/* ** Copyright 2001, Travis Geiselbrecht. All rights reserved. ** Distributed under the terms of the NewOS License. */ /* * Copyright (c) 2008 Travis Geiselbrecht * * 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 <string.h> #include <sys/types.h> static char *___strtok = NULL; char * strtok(char *s, char const *ct) { char *sbegin, *send; sbegin = s ? s : ___strtok; if (!sbegin) { return NULL; } sbegin += strspn(sbegin,ct); if (*sbegin == '\0') { ___strtok = NULL; return( NULL ); } send = strpbrk( sbegin, ct); if (send && *send != '\0') *send++ = '\0'; ___strtok = send; return (sbegin); }
mit
mitreaadrian/Soccersim
boost/boost_1_59_0/libs/config/test/no_cxx11_inline_namespaces_pass.cpp
47
1095
// This file was automatically generated on Sun Apr 28 18:36:48 2013 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version.// // Revision $Id$ // // Test file for macro BOOST_NO_CXX11_INLINE_NAMESPACES // This file should compile, if it does not then // BOOST_NO_CXX11_INLINE_NAMESPACES should be defined. // See file boost_no_cxx11_inline_namespaces.ipp for details // Must not have BOOST_ASSERT_CONFIG set; it defeats // the objective of this file: #ifdef BOOST_ASSERT_CONFIG # undef BOOST_ASSERT_CONFIG #endif #include <boost/config.hpp> #include "test.hpp" #ifndef BOOST_NO_CXX11_INLINE_NAMESPACES #include "boost_no_cxx11_inline_namespaces.ipp" #else namespace boost_no_cxx11_inline_namespaces = empty_boost; #endif int main( int, char *[] ) { return boost_no_cxx11_inline_namespaces::test(); }
mit
keichan100yen/ode-ext
boost/libs/numeric/odeint/test/stepper_with_units.cpp
49
11488
/* [auto_generated] libs/numeric/odeint/test/stepper_with_units.cpp [begin_description] This file tests if the steppers play well with Boost.Units. [end_description] Copyright 2011-2012 Karsten Ahnert Copyright 2011-2013 Mario Mulansky Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #define BOOST_TEST_MODULE odeint_stepper_with_units // the runge-kutta 78 stepper invoked with boost units requires increased fusion macro variables! // note that by default the rk78 + units test case is disabled as it requires enormous memory when compiling (5 GB) #define BOOST_FUSION_INVOKE_MAX_ARITY 15 #define BOOST_RESULT_OF_NUM_ARGS 15 #include <boost/numeric/odeint/config.hpp> #include <boost/test/unit_test.hpp> #include <boost/units/systems/si/length.hpp> #include <boost/units/systems/si/time.hpp> #include <boost/units/systems/si/velocity.hpp> #include <boost/units/systems/si/acceleration.hpp> #include <boost/units/systems/si/io.hpp> #include <boost/fusion/container.hpp> #include <boost/mpl/vector.hpp> #include <boost/numeric/odeint/stepper/euler.hpp> #include <boost/numeric/odeint/stepper/runge_kutta4.hpp> #include <boost/numeric/odeint/stepper/runge_kutta4_classic.hpp> #include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54.hpp> #include <boost/numeric/odeint/stepper/runge_kutta_cash_karp54_classic.hpp> #include <boost/numeric/odeint/stepper/runge_kutta_dopri5.hpp> #include <boost/numeric/odeint/stepper/runge_kutta_fehlberg78.hpp> #include <boost/numeric/odeint/stepper/controlled_runge_kutta.hpp> #include <boost/numeric/odeint/stepper/dense_output_runge_kutta.hpp> #include <boost/numeric/odeint/stepper/bulirsch_stoer.hpp> #include <boost/numeric/odeint/stepper/bulirsch_stoer_dense_out.hpp> #include <boost/numeric/odeint/algebra/fusion_algebra.hpp> #include <boost/numeric/odeint/algebra/fusion_algebra_dispatcher.hpp> using namespace boost::numeric::odeint; using namespace boost::unit_test; namespace mpl = boost::mpl; namespace fusion = boost::fusion; namespace units = boost::units; namespace si = boost::units::si; typedef double value_type; typedef units::quantity< si::time , value_type > time_type; typedef units::quantity< si::length , value_type > length_type; typedef units::quantity< si::velocity , value_type > velocity_type; typedef units::quantity< si::acceleration , value_type > acceleration_type; typedef fusion::vector< length_type , velocity_type > state_type; typedef fusion::vector< velocity_type , acceleration_type > deriv_type; void oscillator( const state_type &x , deriv_type &dxdt , time_type t ) { const units::quantity< si::frequency , value_type > omega = 1.0 * si::hertz; fusion::at_c< 0 >( dxdt ) = fusion::at_c< 1 >( x ); fusion::at_c< 1 >( dxdt ) = - omega * omega * fusion::at_c< 0 >( x ); } template< class Stepper > void check_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; typedef typename stepper_type::order_type order_type; typedef typename stepper_type::algebra_type algebra_type; typedef typename stepper_type::operations_type operations_type; const time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ); // test call method one stepper.do_step( oscillator , x , t , dt ); // test call method two stepper.do_step( oscillator , x , t , x , dt ); // test call method three deriv_type dxdt; oscillator( x , dxdt , t ); stepper.do_step( oscillator , x , dxdt , t , dt ); // test call method four oscillator( x , dxdt , t ); stepper.do_step( oscillator , x , dxdt , t , x , dt ); } template< class Stepper > void check_fsal_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; typedef typename stepper_type::order_type order_type; typedef typename stepper_type::algebra_type algebra_type; typedef typename stepper_type::operations_type operations_type; const time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ); // test call method one stepper.do_step( oscillator , x , t , dt ); // test call method two stepper.do_step( oscillator , x , t , x , dt ); // test call method three deriv_type dxdt; oscillator( x , dxdt , t ); stepper.do_step( oscillator , x , dxdt , t , dt ); // test call method four stepper.do_step( oscillator , x , dxdt , t , x , dxdt , dt ); } template< class Stepper > void check_error_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; typedef typename stepper_type::order_type order_type; typedef typename stepper_type::algebra_type algebra_type; typedef typename stepper_type::operations_type operations_type; const time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ) , xerr; // test call method one stepper.do_step( oscillator , x , t , dt , xerr ); // test call method two stepper.do_step( oscillator , x , t , x , dt , xerr ); // test call method three deriv_type dxdt; oscillator( x , dxdt , t ); stepper.do_step( oscillator , x , dxdt , t , dt , xerr ); // test call method four stepper.do_step( oscillator , x , dxdt , t , x , dt , xerr ); } template< class Stepper > void check_fsal_error_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; typedef typename stepper_type::order_type order_type; typedef typename stepper_type::algebra_type algebra_type; typedef typename stepper_type::operations_type operations_type; const time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ) , xerr; // test call method one stepper.do_step( oscillator , x , t , dt , xerr ); // test call method two stepper.do_step( oscillator , x , t , x , dt , xerr ); // test call method three deriv_type dxdt; oscillator( x , dxdt , t ); stepper.do_step( oscillator , x , dxdt , t , dt , xerr ); // test call method four stepper.do_step( oscillator , x , dxdt , t , x , dxdt , dt , xerr ); } template< class Stepper > void check_controlled_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ); // test call method one stepper.try_step( oscillator , x , t , dt ); } template< class Stepper > void check_dense_output_stepper( Stepper &stepper ) { typedef Stepper stepper_type; typedef typename stepper_type::state_type state_type; typedef typename stepper_type::value_type value_type; typedef typename stepper_type::deriv_type deriv_type; typedef typename stepper_type::time_type time_type; // typedef typename stepper_type::order_type order_type; time_type t( 0.0 * si::second ); time_type dt( 0.1 * si::second ); state_type x( 1.0 * si::meter , 0.0 * si::meter_per_second ) , x2; stepper.initialize( x , t , dt ); stepper.do_step( oscillator ); stepper.calc_state( dt / 2.0 , x2 ); } class stepper_types : public mpl::vector < euler< state_type , value_type , deriv_type , time_type >, runge_kutta4< state_type , value_type , deriv_type , time_type > , runge_kutta4_classic< state_type , value_type , deriv_type , time_type > , runge_kutta_cash_karp54< state_type , value_type , deriv_type , time_type >, runge_kutta_cash_karp54_classic< state_type , value_type , deriv_type , time_type > // don't run rk78 test - gcc requires > 5GB RAM to compile this //, runge_kutta_fehlberg78< state_type , value_type , deriv_type , time_type > > { }; class fsal_stepper_types : public mpl::vector < runge_kutta_dopri5< state_type , value_type , deriv_type , time_type > > { }; class error_stepper_types : public mpl::vector < runge_kutta_cash_karp54_classic< state_type , value_type , deriv_type , time_type > //, runge_kutta_fehlberg78< state_type , value_type , deriv_type , time_type > > { }; class fsal_error_stepper_types : public mpl::vector < runge_kutta_dopri5< state_type , value_type , deriv_type , time_type > > { }; class controlled_stepper_types : public mpl::vector < controlled_runge_kutta< runge_kutta_cash_karp54_classic< state_type , value_type , deriv_type , time_type > > , controlled_runge_kutta< runge_kutta_dopri5< state_type , value_type , deriv_type , time_type > > , bulirsch_stoer< state_type , value_type , deriv_type , time_type > // rk78 with units needs up to 3GB memory to compile - disable testing... //, controlled_runge_kutta< runge_kutta_fehlberg78< state_type , value_type , deriv_type , time_type > > > { }; class dense_output_stepper_types : public mpl::vector < dense_output_runge_kutta< euler< state_type , value_type , deriv_type , time_type > > , dense_output_runge_kutta< controlled_runge_kutta< runge_kutta_dopri5< state_type , value_type , deriv_type , time_type > > > //, bulirsch_stoer_dense_out< state_type , value_type , deriv_type , time_type > > { }; BOOST_AUTO_TEST_SUITE( stepper_with_units ) BOOST_AUTO_TEST_CASE_TEMPLATE( stepper_test , Stepper , stepper_types ) { Stepper stepper; check_stepper( stepper ); } BOOST_AUTO_TEST_CASE_TEMPLATE( fsl_stepper_test , Stepper , fsal_stepper_types ) { Stepper stepper; check_fsal_stepper( stepper ); } BOOST_AUTO_TEST_CASE_TEMPLATE( error_stepper_test , Stepper , error_stepper_types ) { Stepper stepper; check_error_stepper( stepper ); } BOOST_AUTO_TEST_CASE_TEMPLATE( fsal_error_stepper_test , Stepper , fsal_error_stepper_types ) { Stepper stepper; check_fsal_error_stepper( stepper ); } BOOST_AUTO_TEST_CASE_TEMPLATE( controlled_stepper_test , Stepper , controlled_stepper_types ) { Stepper stepper; check_controlled_stepper( stepper ); } BOOST_AUTO_TEST_CASE_TEMPLATE( dense_ouput_test , Stepper , dense_output_stepper_types ) { Stepper stepper; check_dense_output_stepper( stepper ); } BOOST_AUTO_TEST_SUITE_END()
mit
pichina/lk
lib/openssl/crypto/x509/x509_txt.c
53
8392
/* crypto/x509/x509_txt.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ #include <stdio.h> #ifndef LK_NO_TIME #include <time.h> #endif #include <errno.h> #include "cryptlib.h" #include <openssl/lhash.h> #include <openssl/buffer.h> #include <openssl/evp.h> #include <openssl/asn1.h> #include <openssl/x509.h> #include <openssl/objects.h> const char *X509_verify_cert_error_string(long n) { static char buf[100]; switch ((int)n) { case X509_V_OK: return("ok"); case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT: return("unable to get issuer certificate"); case X509_V_ERR_UNABLE_TO_GET_CRL: return("unable to get certificate CRL"); case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE: return("unable to decrypt certificate's signature"); case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE: return("unable to decrypt CRL's signature"); case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY: return("unable to decode issuer public key"); case X509_V_ERR_CERT_SIGNATURE_FAILURE: return("certificate signature failure"); case X509_V_ERR_CRL_SIGNATURE_FAILURE: return("CRL signature failure"); case X509_V_ERR_CERT_NOT_YET_VALID: return("certificate is not yet valid"); case X509_V_ERR_CRL_NOT_YET_VALID: return("CRL is not yet valid"); case X509_V_ERR_CERT_HAS_EXPIRED: return("certificate has expired"); case X509_V_ERR_CRL_HAS_EXPIRED: return("CRL has expired"); case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD: return("format error in certificate's notBefore field"); case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD: return("format error in certificate's notAfter field"); case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD: return("format error in CRL's lastUpdate field"); case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD: return("format error in CRL's nextUpdate field"); case X509_V_ERR_OUT_OF_MEM: return("out of memory"); case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT: return("self signed certificate"); case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN: return("self signed certificate in certificate chain"); case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: return("unable to get local issuer certificate"); case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE: return("unable to verify the first certificate"); case X509_V_ERR_CERT_CHAIN_TOO_LONG: return("certificate chain too long"); case X509_V_ERR_CERT_REVOKED: return("certificate revoked"); case X509_V_ERR_INVALID_CA: return ("invalid CA certificate"); case X509_V_ERR_INVALID_NON_CA: return ("invalid non-CA certificate (has CA markings)"); case X509_V_ERR_PATH_LENGTH_EXCEEDED: return ("path length constraint exceeded"); case X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED: return("proxy path length constraint exceeded"); case X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED: return("proxy certificates not allowed, please set the appropriate flag"); case X509_V_ERR_INVALID_PURPOSE: return ("unsupported certificate purpose"); case X509_V_ERR_CERT_UNTRUSTED: return ("certificate not trusted"); case X509_V_ERR_CERT_REJECTED: return ("certificate rejected"); case X509_V_ERR_APPLICATION_VERIFICATION: return("application verification failure"); case X509_V_ERR_SUBJECT_ISSUER_MISMATCH: return("subject issuer mismatch"); case X509_V_ERR_AKID_SKID_MISMATCH: return("authority and subject key identifier mismatch"); case X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH: return("authority and issuer serial number mismatch"); case X509_V_ERR_KEYUSAGE_NO_CERTSIGN: return("key usage does not include certificate signing"); case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER: return("unable to get CRL issuer certificate"); case X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION: return("unhandled critical extension"); case X509_V_ERR_KEYUSAGE_NO_CRL_SIGN: return("key usage does not include CRL signing"); case X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE: return("key usage does not include digital signature"); case X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION: return("unhandled critical CRL extension"); case X509_V_ERR_INVALID_EXTENSION: return("invalid or inconsistent certificate extension"); case X509_V_ERR_INVALID_POLICY_EXTENSION: return("invalid or inconsistent certificate policy extension"); case X509_V_ERR_NO_EXPLICIT_POLICY: return("no explicit policy"); case X509_V_ERR_DIFFERENT_CRL_SCOPE: return("Different CRL scope"); case X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE: return("Unsupported extension feature"); case X509_V_ERR_UNNESTED_RESOURCE: return("RFC 3779 resource not subset of parent's resources"); case X509_V_ERR_PERMITTED_VIOLATION: return("permitted subtree violation"); case X509_V_ERR_EXCLUDED_VIOLATION: return("excluded subtree violation"); case X509_V_ERR_SUBTREE_MINMAX: return("name constraints minimum and maximum not supported"); case X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE: return("unsupported name constraint type"); case X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX: return("unsupported or invalid name constraint syntax"); case X509_V_ERR_UNSUPPORTED_NAME_SYNTAX: return("unsupported or invalid name syntax"); case X509_V_ERR_CRL_PATH_VALIDATION_ERROR: return("CRL path validation error"); default: BIO_snprintf(buf,sizeof buf,"error number %ld",n); return(buf); } }
mit
chaos7theory/coreclr
src/jit/smgen.cpp
61
13828
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XX XX XX Code sequence state machine generator XX XX XX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #include "smgen.h" #include "smcommon.cpp" static bool debug = false; #define debugprint(x) if (debug) printf x; // // State machine generator // SMGen::SMGen() { memset(this, 0, sizeof(*this)); States[SM_STATE_ID_START].id = SM_STATE_ID_START; SMGenDestStateDesc * pDestStateListHead = new SMGenDestStateDesc(); pDestStateListHead->next = NULL; States[SM_STATE_ID_START].destStateList = pDestStateListHead; lastStateID = 1; // // Process all interesting code sequences // debugprint(("\n======== The code sequences =================\n")); SM_OPCODE * CodeSeqs = (SM_OPCODE *)s_CodeSeqs; while (*CodeSeqs != CODE_SEQUENCE_END) { ProcessSeq(CodeSeqs); CodeSeqs += MAX_CODE_SEQUENCE_LENGTH; } debugprint(("\n======== The state machine =================\n")); for (SM_STATE_ID i=1; i<=lastStateID; ++i) { debugprint(("State %-4d : length=%-2d prev=%-4d lngest=%-4d (%c) Desc=[%s]\n", i, States[i].length, States[i].prevState, States[i].longestTermState, States[i].term?'*':' ', StateDesc(i))); for (unsigned j=0; j<SM_COUNT; ++j) { if (States[i].getDestState((SM_OPCODE)j) != 0) { debugprint((" [%s] ==> %d\n", smOpcodeNames[(SM_OPCODE)j], States[i].getDestState((SM_OPCODE)j))); } } } debugprint(("\n# MethodName| NativeSize| ILBytes| ILInstrCount| 0Args| 1Args| 2Args| 3AndMoreArgs| NoLocals| NoCalls")); unsigned termStateCount = 0; for (SM_STATE_ID i=1; i<=lastStateID; ++i) { if (States[i].term) { ++termStateCount; debugprint(("| %s[%d]", StateDesc(i), i)); } } debugprint(("\n\n%d termination states.\n", termStateCount)); } SMGen::~SMGen() { } void SMGen::ProcessSeq(SM_OPCODE * CodeSeq) { SM_STATE_ID longestTermState = 0; SM_STATE_ID curState = SM_STATE_ID_START; BYTE curLen = 0; SM_OPCODE * pOpcode = CodeSeq; SM_OPCODE opcode; debugprint(("\nCodeSeq : {")); do { opcode = * pOpcode; debugprint(("%s, " , smOpcodeNames[opcode])); assert(curLen < MAX_CODE_SEQUENCE_LENGTH); assert(curLen < 255); ++curLen; SM_STATE_ID nextState = States[curState].getDestState(opcode); if (nextState == 0) { // Need to create a new state assert(lastStateID < MAX_NUM_STATES); ++lastStateID; States[curState].setDestState(opcode, lastStateID); States[lastStateID].id = lastStateID; States[lastStateID].longestTermState = longestTermState; States[lastStateID].prevState = curState; States[lastStateID].opc = opcode; States[lastStateID].term = false; SMGenDestStateDesc * pDestStateListHead = new SMGenDestStateDesc(); pDestStateListHead->next = NULL; States[lastStateID].destStateList = pDestStateListHead; curState = lastStateID; States[curState].length = curLen; } else { curState = nextState; if (States[curState].term) { longestTermState = curState; } } } while (* (++pOpcode) != CODE_SEQUENCE_END); assert(curState != SM_STATE_ID_START); assert(!States[curState].term && "Duplicated rule."); States[curState].term = true; debugprint((" }\n")); } void SMGen::Emit() { // Zero out the entire buffer. memset(&emitBuffer, 0, sizeof(emitBuffer)); BYTE * pBuffer = (BYTE *)&emitBuffer; pAllStates = (SMState *) pBuffer; pBuffer += sizeof(*pAllStates) * (lastStateID+1); pAllJumpTables = (JumpTableCell *) pBuffer; pJumpTableMax = 0; // // Loop through each state and fill in the buffer // for (SM_STATE_ID i=1; i<=lastStateID; ++i) { SMState * pState = pAllStates+i; pState->term = States[i].term; pState->length = States[i].length; pState->longestTermState = States[i].longestTermState; pState->prevState = States[i].prevState; pState->opc = States[i].opc; pState->jumpTableByteOffset = JumpTableSet(i); } debugprint(("pJumpTableMax at starts at cell# %d\n", pJumpTableMax-pAllJumpTables)); totalCellNeeded = pJumpTableMax - pAllJumpTables + SM_COUNT; debugprint(("MAX_NUM_STATES = %d\n", MAX_NUM_STATES)); debugprint(("Actual total number of states = %d\n", lastStateID+1)); assert(lastStateID+1 <= MAX_NUM_STATES); debugprint(("Total number of cells = %d\n", totalCellNeeded)); assert(totalCellNeeded <= MAX_CELL_COUNT); debugprint(("sizeof(SMState) = %d\n", sizeof(SMState))); debugprint(("sizeof(JumpTableCell) = %d\n", sizeof(JumpTableCell))); debugprint(("sizeof(emitBuffer) = %d\n", sizeof(emitBuffer))); EmitDone(); } void SMGen::EmitDone() { printf("// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"); printf("//\n"); printf("// Automatically generated code. DO NOT MODIFY! \n"); printf("// To generate this file. Do \"smgen.exe > SMData.cpp\" \n"); printf("//\n"); printf("// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\n"); printf("#include \"jitpch.h\"\n"); printf("//\n"); printf("// States in the state machine\n"); printf("//\n"); printf("const SMState g_SMStates[] = \n{\n"); printf(" // {term, len, lng, prev, SMOpcode and SMOpcodeName , offsets } // state ID and name\n"); // Print out states for (SM_STATE_ID id=0; id<=lastStateID; ++id) { SMState * pState = pAllStates+id; printf(" {"); printf("%4d, ", pState->term); printf("%3d, ", pState->length); printf("%3d, ", pState->longestTermState); printf("%4d, ", pState->prevState); printf("(SM_OPCODE)%3d /* %-15s */, ", pState->opc, smOpcodeNames[pState->opc]); printf("%7d" , pState->jumpTableByteOffset); printf(" }, // "); printf("state %d [%s]", id, StateDesc(id)); printf("\n"); } printf("};\n\n"); printf("static_assert_no_msg(NUM_SM_STATES == sizeof(g_SMStates)/sizeof(g_SMStates[0]));\n\n"); printf("const SMState * gp_SMStates = g_SMStates;\n\n"); printf("//\n"); printf("// JumpTableCells in the state machine\n"); printf("//\n"); printf("const JumpTableCell g_SMJumpTableCells[] = \n{\n"); printf(" // {src, dest }\n"); for (unsigned i=0; i<totalCellNeeded; ++i) { JumpTableCell * cell = pAllJumpTables+i; printf(" {"); printf("%3d, ", cell->srcState); printf("%4d", cell->destState); printf(" }, // cell# %d", i); if (cell->srcState != 0) { JumpTableCell * pThisJumpTable = (JumpTableCell * )(((PBYTE)pAllJumpTables) + pAllStates[cell->srcState].jumpTableByteOffset); assert(cell >= pThisJumpTable); SM_OPCODE opcode = (SM_OPCODE) (cell - pThisJumpTable); printf(" : state %d [%s]", cell->srcState, StateDesc(cell->srcState)); printf(" --(%d %s)--> ", opcode, smOpcodeNames[opcode]); printf("state %d [%s]", cell->destState, StateDesc(cell->destState)); } printf("\n"); } printf("};\n\n"); printf("const JumpTableCell * gp_SMJumpTableCells = g_SMJumpTableCells;\n\n"); } unsigned short SMGen::JumpTableSet(SM_STATE_ID id) { JumpTableCell * pThisJumpTable = pAllJumpTables; while (true) { if (bJumpTableFit(pThisJumpTable, id)) { JumpTableFill(pThisJumpTable, id); if (pThisJumpTable > pJumpTableMax) pJumpTableMax = pThisJumpTable; unsigned offset = ((BYTE*)pThisJumpTable) - ((BYTE*)pAllJumpTables); assert(offset == (unsigned short)offset); return (unsigned short)offset; } ++pThisJumpTable; } } bool SMGen::bJumpTableFit(JumpTableCell * pTable, SM_STATE_ID id) { SMGenDestStateDesc * p = States[id].destStateList->next; // Skip the list head. while (p) { SM_OPCODE opcode = p->opcode; JumpTableCell * pCell = pTable + opcode; if (pCell->srcState != 0) { // This cell has been occupied. return false; } p = p->next; } debugprint(("JumpTable for state %d [%s] starts at cell# %d:\n", id, StateDesc(id), pTable-pAllJumpTables)); return true; } void SMGen::JumpTableFill(JumpTableCell * pTable, SM_STATE_ID id) { SMGenDestStateDesc * p = States[id].destStateList->next; // Skip the list head. while (p) { SM_OPCODE opcode = p->opcode; JumpTableCell * pCell = pTable + opcode; assert(pCell->srcState == 0); pCell->srcState = id; pCell->destState = p->destState; debugprint((" cell# %d : [%s (%d)] --> %d\n", pCell-pAllJumpTables, smOpcodeNames[opcode], opcode, pCell->destState)); p = p->next; } } char * SMGen::StateDesc(SM_STATE_ID stateID) { static char s_StateDesc[500]; static SM_OPCODE s_StateDescOpcodes[MAX_CODE_SEQUENCE_LENGTH]; if (stateID == 0) return "invalid"; if (stateID == SM_STATE_ID_START) return "start"; unsigned i = 0; SM_STATE_ID b = stateID; while (States[b].prevState != 0) { s_StateDescOpcodes[i] = States[b].opc; b = States[b].prevState; ++i; } assert(i == States[stateID].length && i>0); * s_StateDesc = 0; while (--i>0) { strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[i]]); strcat(s_StateDesc, " -> "); } strcat(s_StateDesc, smOpcodeNames[s_StateDescOpcodes[0]]); return s_StateDesc; } SM_STATE_ID SMGenState::getDestState(SM_OPCODE opcode) { assert(opcode < SM_COUNT); SMGenDestStateDesc * p = destStateList->next; // Skip the list head. int lastSeenOpcode = -1; while (p) { assert(lastSeenOpcode < p->opcode); // opcode should be in accending order. lastSeenOpcode = p->opcode; if (p->opcode == opcode) { assert(p->destState != 0); return p->destState; } p = p->next; } return 0; } void SMGenState::setDestState(SM_OPCODE opcode, SM_STATE_ID destState) { assert(id != 0); // Should not have come here for the invalid state. assert(getDestState(opcode) == 0); // Don't set it twice. SMGenDestStateDesc * newSMGenDestStateDesc = new SMGenDestStateDesc(); newSMGenDestStateDesc->opcode = opcode; newSMGenDestStateDesc->destState = destState; // Insert the new entry in accending order SMGenDestStateDesc * p = destStateList; SMGenDestStateDesc * q = p->next; while (q) { if (q->opcode > opcode) break; p = q; q = q->next; } newSMGenDestStateDesc->next = p->next; p->next = newSMGenDestStateDesc; } void Usage() { printf("JIT code sequence state machine generator\n"); printf("==============================================\n"); printf("smgen -? : Print usage.\n"); printf("smgen : Generate static array for the state machine.\n"); printf("smgen debug: Print debug info.\n"); } //----------------------------------------------------------------------------- // main //----------------------------------------------------------------------------- extern "C" int _cdecl wmain(int argc, __in_ecount(argc) WCHAR **argv) { if (argc > 1) { if (wcscmp(argv[1], W("-?")) == 0 || wcscmp(argv[1], W("/?")) == 0) { Usage(); return 1; } if (wcscmp(argv[1], W("debug")) == 0) { debug = true; } } // Generate the state machine SMGen smGen; smGen.Emit(); return 0; }
mit
xtypebee/coreclr
src/coreclr/hosts/corerun/logger.cpp
61
9335
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // #include <stdio.h> #include <windows.h> #include <Logger.h> #include "palclr.h" void Logger::Enable() { m_isEnabled = true; } void Logger::Disable() { m_isEnabled = false; } void print(const wchar_t *val) { // If val is longer than 2048 characters, wprintf will refuse to print it. // So write it in chunks. const size_t chunkSize = 1024; wchar_t chunk[chunkSize]; auto valLength = ::wcslen(val); for (size_t i = 0 ; i < valLength ; i += chunkSize) { ::wcsncpy_s(chunk, chunkSize, val + i, _TRUNCATE); ::wprintf(W("%s"), chunk); } } Logger& Logger::operator<< (bool val) { if (m_isEnabled) { if (val) { EnsurePrefixIsPrinted(); print(W("true")); } else { EnsurePrefixIsPrinted(); print(W("false")); } } return *this; } void PrintAsHResult(int val) { const wchar_t * str = nullptr; switch (val) { case 0x00000000: str = W("S_OK"); break; case 0x00000001: str = W("S_FALSE"); break; case 0x8000000B: str = W("E_BOUNDS"); break; case 0x8000000C: str = W("E_CHANGED_STATE"); break; case 0x80000013: str = W("RO_E_CLOSED"); break; case 0x8000211D: str = W("COR_E_AMBIGUOUSMATCH"); break; case 0x80004001: str = W("E_NOTIMPL"); break; case 0x80004002: str = W("COR_E_INVALIDCAST"); break; //case 0x80004002: str = W("E_NOINTERFACE"); break; case 0x80004003: str = W("COR_E_NULLREFERENCE"); break; //case 0x80004003: str = W("E_POINTER"); break; case 0x80004004: str = W("E_ABORT"); break; case 0x80004005: str = W("E_FAIL"); break; case 0x8000FFFF: str = W("E_UNEXPECTED"); break; case 0x8002000a: str = W("DISP_E_OVERFLOW"); break; case 0x8002000e: str = W("COR_E_TARGETPARAMCOUNT"); break; case 0x80020012: str = W("COR_E_DIVIDEBYZERO"); break; case 0x80028ca0: str = W("TYPE_E_TYPEMISMATCH"); break; case 0x80070005: str = W("COR_E_UNAUTHORIZEDACCESS"); break; //case 0x80070005: str = W("E_ACCESSDENIED"); break; case 0x80070006: str = W("E_HANDLE"); break; case 0x8007000B: str = W("COR_E_BADIMAGEFORMAT"); break; case 0x8007000E: str = W("COR_E_OUTOFMEMORY"); break; //case 0x8007000E: str = W("E_OUTOFMEMORY"); break; case 0x80070057: str = W("COR_E_ARGUMENT"); break; //case 0x80070057: str = W("E_INVALIDARG"); break; case 0x80070216: str = W("COR_E_ARITHMETIC"); break; case 0x800703E9: str = W("COR_E_STACKOVERFLOW"); break; case 0x80090020: str = W("NTE_FAIL"); break; case 0x80131013: str = W("COR_E_TYPEUNLOADED"); break; case 0x80131014: str = W("COR_E_APPDOMAINUNLOADED"); break; case 0x80131015: str = W("COR_E_CANNOTUNLOADAPPDOMAIN"); break; case 0x80131040: str = W("FUSION_E_REF_DEF_MISMATCH"); break; case 0x80131047: str = W("FUSION_E_INVALID_NAME"); break; case 0x80131416: str = W("CORSEC_E_POLICY_EXCEPTION"); break; case 0x80131417: str = W("CORSEC_E_MIN_GRANT_FAIL"); break; case 0x80131418: str = W("CORSEC_E_NO_EXEC_PERM"); break; //case 0x80131418: str = W("CORSEC_E_XMLSYNTAX"); break; case 0x80131430: str = W("CORSEC_E_CRYPTO"); break; case 0x80131431: str = W("CORSEC_E_CRYPTO_UNEX_OPER"); break; case 0x80131500: str = W("COR_E_EXCEPTION"); break; case 0x80131501: str = W("COR_E_SYSTEM"); break; case 0x80131502: str = W("COR_E_ARGUMENTOUTOFRANGE"); break; case 0x80131503: str = W("COR_E_ARRAYTYPEMISMATCH"); break; case 0x80131504: str = W("COR_E_CONTEXTMARSHAL"); break; case 0x80131505: str = W("COR_E_TIMEOUT"); break; case 0x80131506: str = W("COR_E_EXECUTIONENGINE"); break; case 0x80131507: str = W("COR_E_FIELDACCESS"); break; case 0x80131508: str = W("COR_E_INDEXOUTOFRANGE"); break; case 0x80131509: str = W("COR_E_INVALIDOPERATION"); break; case 0x8013150A: str = W("COR_E_SECURITY"); break; case 0x8013150C: str = W("COR_E_SERIALIZATION"); break; case 0x8013150D: str = W("COR_E_VERIFICATION"); break; case 0x80131510: str = W("COR_E_METHODACCESS"); break; case 0x80131511: str = W("COR_E_MISSINGFIELD"); break; case 0x80131512: str = W("COR_E_MISSINGMEMBER"); break; case 0x80131513: str = W("COR_E_MISSINGMETHOD"); break; case 0x80131514: str = W("COR_E_MULTICASTNOTSUPPORTED"); break; case 0x80131515: str = W("COR_E_NOTSUPPORTED"); break; case 0x80131516: str = W("COR_E_OVERFLOW"); break; case 0x80131517: str = W("COR_E_RANK"); break; case 0x80131518: str = W("COR_E_SYNCHRONIZATIONLOCK"); break; case 0x80131519: str = W("COR_E_THREADINTERRUPTED"); break; case 0x8013151A: str = W("COR_E_MEMBERACCESS"); break; case 0x80131520: str = W("COR_E_THREADSTATE"); break; case 0x80131521: str = W("COR_E_THREADSTOP"); break; case 0x80131522: str = W("COR_E_TYPELOAD"); break; case 0x80131523: str = W("COR_E_ENTRYPOINTNOTFOUND"); break; //case 0x80131523: str = W("COR_E_UNSUPPORTEDFORMAT"); break; case 0x80131524: str = W("COR_E_DLLNOTFOUND"); break; case 0x80131525: str = W("COR_E_THREADSTART"); break; case 0x80131527: str = W("COR_E_INVALIDCOMOBJECT"); break; case 0x80131528: str = W("COR_E_NOTFINITENUMBER"); break; case 0x80131529: str = W("COR_E_DUPLICATEWAITOBJECT"); break; case 0x8013152B: str = W("COR_E_SEMAPHOREFULL"); break; case 0x8013152C: str = W("COR_E_WAITHANDLECANNOTBEOPENED"); break; case 0x8013152D: str = W("COR_E_ABANDONEDMUTEX"); break; case 0x80131530: str = W("COR_E_THREADABORTED"); break; case 0x80131531: str = W("COR_E_INVALIDOLEVARIANTTYPE"); break; case 0x80131532: str = W("COR_E_MISSINGMANIFESTRESOURCE"); break; case 0x80131533: str = W("COR_E_SAFEARRAYTYPEMISMATCH"); break; case 0x80131534: str = W("COR_E_TYPEINITIALIZATION"); break; case 0x80131535: str = W("COR_E_COMEMULATE"); break; //case 0x80131535: str = W("COR_E_MARSHALDIRECTIVE"); break; case 0x80131536: str = W("COR_E_MISSINGSATELLITEASSEMBLY"); break; case 0x80131537: str = W("COR_E_FORMAT"); break; case 0x80131538: str = W("COR_E_SAFEARRAYRANKMISMATCH"); break; case 0x80131539: str = W("COR_E_PLATFORMNOTSUPPORTED"); break; case 0x8013153A: str = W("COR_E_INVALIDPROGRAM"); break; case 0x8013153B: str = W("COR_E_OPERATIONCANCELED"); break; case 0x8013153D: str = W("COR_E_INSUFFICIENTMEMORY"); break; case 0x8013153E: str = W("COR_E_RUNTIMEWRAPPED"); break; case 0x80131541: str = W("COR_E_DATAMISALIGNED"); break; case 0x80131543: str = W("COR_E_TYPEACCESS"); break; case 0x80131577: str = W("COR_E_KEYNOTFOUND"); break; case 0x80131578: str = W("COR_E_INSUFFICIENTEXECUTIONSTACK"); break; case 0x80131600: str = W("COR_E_APPLICATION"); break; case 0x80131601: str = W("COR_E_INVALIDFILTERCRITERIA"); break; case 0x80131602: str = W("COR_E_REFLECTIONTYPELOAD "); break; case 0x80131603: str = W("COR_E_TARGET"); break; case 0x80131604: str = W("COR_E_TARGETINVOCATION"); break; case 0x80131605: str = W("COR_E_CUSTOMATTRIBUTEFORMAT"); break; case 0x80131622: str = W("COR_E_OBJECTDISPOSED"); break; case 0x80131623: str = W("COR_E_SAFEHANDLEMISSINGATTRIBUTE"); break; case 0x80131640: str = W("COR_E_HOSTPROTECTION"); break; } ::wprintf(W("0x%x"), val); if (str != nullptr) { ::wprintf(W("/%0s"), str); } } Logger& Logger::operator<< (int val) { if (m_isEnabled) { EnsurePrefixIsPrinted(); if (m_formatHRESULT) { PrintAsHResult(val); m_formatHRESULT = false; } else { ::wprintf(W("%d"), val); } } return *this; } #ifdef _MSC_VER Logger& Logger::operator<< (long val) { if (m_isEnabled) { EnsurePrefixIsPrinted(); if (m_formatHRESULT) { PrintAsHResult(val); m_formatHRESULT = false; } else { ::wprintf(W("%d"), val); } } return *this; } Logger& Logger::operator<< (unsigned long val) { if (m_isEnabled) { EnsurePrefixIsPrinted(); if (m_formatHRESULT) { PrintAsHResult(val); m_formatHRESULT = false; } else { ::wprintf(W("%d"), val); } } return *this; } #endif Logger& Logger::operator<< (const wchar_t *val) { if (m_isEnabled) { EnsurePrefixIsPrinted(); print(val); } return *this; } Logger& Logger::operator<< (Logger& ( *pf )(Logger&)) { if (m_isEnabled) { return pf(*this); } else { return *this; } } void Logger::EnsurePrefixIsPrinted() { if (this->m_isEnabled && this->m_prefixRequired) { print(W(" HOSTLOG: ")); m_prefixRequired = false; } } // Manipulators // Newline Logger& Logger::endl (Logger& log) { if (log.m_isEnabled) { log.EnsurePrefixIsPrinted(); print(W("\r\n")); log.m_prefixRequired = true; log.m_formatHRESULT = false; } return log; } // Format the next integer value as an HResult Logger& Logger::hresult (Logger& log) { log.m_formatHRESULT = true; return log; }
mit
chenxizhang/coreclr
src/pal/tests/palsuite/pal_specific/PAL_Initialize_Terminate/test2/pal_initialize_twice.c
62
1260
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================= ** ** Source: pal_initialize_twice.c ** ** Purpose: Positive test of PAL_Initialize and PAL_Terminate APIs. ** Calls PAL_Initialize twice to ensure that doing so ** will not cause unexpected failures in the PAL. ** Calls PAL_Terminate twice to clean up the PAL. ** ** **============================================================*/ #include <palsuite.h> int __cdecl main(int argc, char *argv[]) { /* Initialize the PAL environment */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } /* Try calling PAL_Initialize again - should just increment the init_count. */ if (0 != (PAL_Initialize(argc, argv))) { // Call terminate due to the first PAL initialization. PAL_TerminateEx(FAIL); return FAIL; } /* If both calls to PAL_Initialize succeed, then PAL_Terminate must be called twice. The first call just decrements the init_count to 1. */ PAL_Terminate(); PAL_Terminate(); return PASS; }
mit
Rapier-Foundation/rapier-script
src/rapierlang/test/CXX/temp/temp.fct.spec/temp.deduct/temp.deduct.call/basic.cpp
62
1136
// RUN: %clang_cc1 -fsyntax-only -verify %s template<typename T> struct A { }; template<typename T> A<T> f0(T*); void test_f0(int *ip, float const *cfp) { A<int> a0 = f0(ip); A<const float> a1 = f0(cfp); } template<typename T> void f1(T*, int); void test_f1(int *ip, float fv) { f1(ip, fv); } template<typename T> void f2(T*, T*); // expected-note {{candidate template ignored: could not match 'T *' against 'ConvToIntPtr'}} \ // expected-note{{candidate template ignored: deduced conflicting types for parameter 'T' ('int' vs. 'float')}} struct ConvToIntPtr { operator int*() const; }; void test_f2(int *ip, float *fp) { f2(ip, ConvToIntPtr()); // expected-error{{no matching function}} f2(ip, ip); // okay f2(ip, fp); // expected-error{{no matching function}} } namespace test3 { template<typename T> struct bar { }; template<typename T> struct foo { operator bar<T>(); }; template<typename T> void func(bar<T>) { // expected-note {{candidate template ignored: could not match 'bar' against 'foo'}} } void test() { func(foo<int>()); // expected-error {{no matching function}} } }
mit
geertdoornbos/coreclr
src/pal/tests/palsuite/c_runtime/_wtoi/test1/test1.c
62
2168
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*===================================================================== ** ** Source: test1.c ** ** Purpose: Tests the PAL implementation of the _wtoi function. ** Check to ensure that the different ints are handled properly. ** Exponents and decimals should be treated as invalid characters, ** causing the conversion to quit. Whitespace before the int is valid. ** Check would-be octal/hex digits to ensure they're treated no ** differently than other strings. ** ** **===================================================================*/ #include <palsuite.h> struct testCase { int IntValue; char avalue[20]; }; int __cdecl main(int argc, char **argv) { int result=0; int i=0; WCHAR* temp; struct testCase testCases[] = { {1234, "1234"}, {-1234, "-1234"}, {1234, "+1234"}, {1234, "1234.44"}, {1234, "1234e-5"}, {1234, "1234e+5"}, {1234, "1234E5"}, {1234, "\t1234"}, {0, "0x21"}, {17, "017"}, {1234, "1234.657e-8"}, {1234567, " 1234567e-8 foo"}, {0, "foo 32 bar"} }; if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } /* Loop through each case. Convert the wide string to an int and then compare to ensure that it is the correct value. */ for(i = 0; i < sizeof(testCases) / sizeof(struct testCase); i++) { /* Convert to a wide string, then call _wtoi to convert to an int */ temp = convert(testCases[i].avalue); result = _wtoi(temp); free(temp); if (testCases[i].IntValue != result) { Fail("ERROR: _wtoi misinterpreted \"%s\" as %i instead of %i.\n", testCases[i].avalue, result, testCases[i].IntValue); } } PAL_Terminate(); return PASS; }
mit
danawoodman/nodegit
vendor/openssl/openssl/crypto/engine/eng_ctrl.c
830
12340
/* crypto/engine/eng_ctrl.c */ /* ==================================================================== * Copyright (c) 1999-2001 The OpenSSL 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ #include "eng_int.h" /* When querying a ENGINE-specific control command's 'description', this string * is used if the ENGINE_CMD_DEFN has cmd_desc set to NULL. */ static const char *int_no_description = ""; /* These internal functions handle 'CMD'-related control commands when the * ENGINE in question has asked us to take care of it (ie. the ENGINE did not * set the ENGINE_FLAGS_MANUAL_CMD_CTRL flag. */ static int int_ctrl_cmd_is_null(const ENGINE_CMD_DEFN *defn) { if((defn->cmd_num == 0) || (defn->cmd_name == NULL)) return 1; return 0; } static int int_ctrl_cmd_by_name(const ENGINE_CMD_DEFN *defn, const char *s) { int idx = 0; while(!int_ctrl_cmd_is_null(defn) && (strcmp(defn->cmd_name, s) != 0)) { idx++; defn++; } if(int_ctrl_cmd_is_null(defn)) /* The given name wasn't found */ return -1; return idx; } static int int_ctrl_cmd_by_num(const ENGINE_CMD_DEFN *defn, unsigned int num) { int idx = 0; /* NB: It is stipulated that 'cmd_defn' lists are ordered by cmd_num. So * our searches don't need to take any longer than necessary. */ while(!int_ctrl_cmd_is_null(defn) && (defn->cmd_num < num)) { idx++; defn++; } if(defn->cmd_num == num) return idx; /* The given cmd_num wasn't found */ return -1; } static int int_ctrl_helper(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) { int idx; char *s = (char *)p; /* Take care of the easy one first (eg. it requires no searches) */ if(cmd == ENGINE_CTRL_GET_FIRST_CMD_TYPE) { if((e->cmd_defns == NULL) || int_ctrl_cmd_is_null(e->cmd_defns)) return 0; return e->cmd_defns->cmd_num; } /* One or two commands require that "p" be a valid string buffer */ if((cmd == ENGINE_CTRL_GET_CMD_FROM_NAME) || (cmd == ENGINE_CTRL_GET_NAME_FROM_CMD) || (cmd == ENGINE_CTRL_GET_DESC_FROM_CMD)) { if(s == NULL) { ENGINEerr(ENGINE_F_INT_CTRL_HELPER, ERR_R_PASSED_NULL_PARAMETER); return -1; } } /* Now handle cmd_name -> cmd_num conversion */ if(cmd == ENGINE_CTRL_GET_CMD_FROM_NAME) { if((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_name( e->cmd_defns, s)) < 0)) { ENGINEerr(ENGINE_F_INT_CTRL_HELPER, ENGINE_R_INVALID_CMD_NAME); return -1; } return e->cmd_defns[idx].cmd_num; } /* For the rest of the commands, the 'long' argument must specify a * valie command number - so we need to conduct a search. */ if((e->cmd_defns == NULL) || ((idx = int_ctrl_cmd_by_num(e->cmd_defns, (unsigned int)i)) < 0)) { ENGINEerr(ENGINE_F_INT_CTRL_HELPER, ENGINE_R_INVALID_CMD_NUMBER); return -1; } /* Now the logic splits depending on command type */ switch(cmd) { case ENGINE_CTRL_GET_NEXT_CMD_TYPE: idx++; if(int_ctrl_cmd_is_null(e->cmd_defns + idx)) /* end-of-list */ return 0; else return e->cmd_defns[idx].cmd_num; case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD: return strlen(e->cmd_defns[idx].cmd_name); case ENGINE_CTRL_GET_NAME_FROM_CMD: return BIO_snprintf(s,strlen(e->cmd_defns[idx].cmd_name) + 1, "%s", e->cmd_defns[idx].cmd_name); case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD: if(e->cmd_defns[idx].cmd_desc) return strlen(e->cmd_defns[idx].cmd_desc); return strlen(int_no_description); case ENGINE_CTRL_GET_DESC_FROM_CMD: if(e->cmd_defns[idx].cmd_desc) return BIO_snprintf(s, strlen(e->cmd_defns[idx].cmd_desc) + 1, "%s", e->cmd_defns[idx].cmd_desc); return BIO_snprintf(s, strlen(int_no_description) + 1,"%s", int_no_description); case ENGINE_CTRL_GET_CMD_FLAGS: return e->cmd_defns[idx].cmd_flags; } /* Shouldn't really be here ... */ ENGINEerr(ENGINE_F_INT_CTRL_HELPER,ENGINE_R_INTERNAL_LIST_ERROR); return -1; } int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p, void (*f)(void)) { int ctrl_exists, ref_exists; if(e == NULL) { ENGINEerr(ENGINE_F_ENGINE_CTRL,ERR_R_PASSED_NULL_PARAMETER); return 0; } CRYPTO_w_lock(CRYPTO_LOCK_ENGINE); ref_exists = ((e->struct_ref > 0) ? 1 : 0); CRYPTO_w_unlock(CRYPTO_LOCK_ENGINE); ctrl_exists = ((e->ctrl == NULL) ? 0 : 1); if(!ref_exists) { ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_REFERENCE); return 0; } /* Intercept any "root-level" commands before trying to hand them on to * ctrl() handlers. */ switch(cmd) { case ENGINE_CTRL_HAS_CTRL_FUNCTION: return ctrl_exists; case ENGINE_CTRL_GET_FIRST_CMD_TYPE: case ENGINE_CTRL_GET_NEXT_CMD_TYPE: case ENGINE_CTRL_GET_CMD_FROM_NAME: case ENGINE_CTRL_GET_NAME_LEN_FROM_CMD: case ENGINE_CTRL_GET_NAME_FROM_CMD: case ENGINE_CTRL_GET_DESC_LEN_FROM_CMD: case ENGINE_CTRL_GET_DESC_FROM_CMD: case ENGINE_CTRL_GET_CMD_FLAGS: if(ctrl_exists && !(e->flags & ENGINE_FLAGS_MANUAL_CMD_CTRL)) return int_ctrl_helper(e,cmd,i,p,f); if(!ctrl_exists) { ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_CONTROL_FUNCTION); /* For these cmd-related functions, failure is indicated * by a -1 return value (because 0 is used as a valid * return in some places). */ return -1; } default: break; } /* Anything else requires a ctrl() handler to exist. */ if(!ctrl_exists) { ENGINEerr(ENGINE_F_ENGINE_CTRL,ENGINE_R_NO_CONTROL_FUNCTION); return 0; } return e->ctrl(e, cmd, i, p, f); } int ENGINE_cmd_is_executable(ENGINE *e, int cmd) { int flags; if((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, cmd, NULL, NULL)) < 0) { ENGINEerr(ENGINE_F_ENGINE_CMD_IS_EXECUTABLE, ENGINE_R_INVALID_CMD_NUMBER); return 0; } if(!(flags & ENGINE_CMD_FLAG_NO_INPUT) && !(flags & ENGINE_CMD_FLAG_NUMERIC) && !(flags & ENGINE_CMD_FLAG_STRING)) return 0; return 1; } int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name, long i, void *p, void (*f)(void), int cmd_optional) { int num; if((e == NULL) || (cmd_name == NULL)) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD, ERR_R_PASSED_NULL_PARAMETER); return 0; } if((e->ctrl == NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FROM_NAME, 0, (void *)cmd_name, NULL)) <= 0)) { /* If the command didn't *have* to be supported, we fake * success. This allows certain settings to be specified for * multiple ENGINEs and only require a change of ENGINE id * (without having to selectively apply settings). Eg. changing * from a hardware device back to the regular software ENGINE * without editing the config file, etc. */ if(cmd_optional) { ERR_clear_error(); return 1; } ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD, ENGINE_R_INVALID_CMD_NAME); return 0; } /* Force the result of the control command to 0 or 1, for the reasons * mentioned before. */ if (ENGINE_ctrl(e, num, i, p, f) > 0) return 1; return 0; } int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg, int cmd_optional) { int num, flags; long l; char *ptr; if((e == NULL) || (cmd_name == NULL)) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ERR_R_PASSED_NULL_PARAMETER); return 0; } if((e->ctrl == NULL) || ((num = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FROM_NAME, 0, (void *)cmd_name, NULL)) <= 0)) { /* If the command didn't *have* to be supported, we fake * success. This allows certain settings to be specified for * multiple ENGINEs and only require a change of ENGINE id * (without having to selectively apply settings). Eg. changing * from a hardware device back to the regular software ENGINE * without editing the config file, etc. */ if(cmd_optional) { ERR_clear_error(); return 1; } ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_INVALID_CMD_NAME); return 0; } if(!ENGINE_cmd_is_executable(e, num)) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_CMD_NOT_EXECUTABLE); return 0; } if((flags = ENGINE_ctrl(e, ENGINE_CTRL_GET_CMD_FLAGS, num, NULL, NULL)) < 0) { /* Shouldn't happen, given that ENGINE_cmd_is_executable() * returned success. */ ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } /* If the command takes no input, there must be no input. And vice * versa. */ if(flags & ENGINE_CMD_FLAG_NO_INPUT) { if(arg != NULL) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_COMMAND_TAKES_NO_INPUT); return 0; } /* We deliberately force the result of ENGINE_ctrl() to 0 or 1 * rather than returning it as "return data". This is to ensure * usage of these commands is consistent across applications and * that certain applications don't understand it one way, and * others another. */ if(ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0) return 1; return 0; } /* So, we require input */ if(arg == NULL) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_COMMAND_TAKES_INPUT); return 0; } /* If it takes string input, that's easy */ if(flags & ENGINE_CMD_FLAG_STRING) { /* Same explanation as above */ if(ENGINE_ctrl(e, num, 0, (void *)arg, NULL) > 0) return 1; return 0; } /* If it doesn't take numeric either, then it is unsupported for use in * a config-setting situation, which is what this function is for. This * should never happen though, because ENGINE_cmd_is_executable() was * used. */ if(!(flags & ENGINE_CMD_FLAG_NUMERIC)) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_INTERNAL_LIST_ERROR); return 0; } l = strtol(arg, &ptr, 10); if((arg == ptr) || (*ptr != '\0')) { ENGINEerr(ENGINE_F_ENGINE_CTRL_CMD_STRING, ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER); return 0; } /* Force the result of the control command to 0 or 1, for the reasons * mentioned before. */ if(ENGINE_ctrl(e, num, l, NULL, NULL) > 0) return 1; return 0; }
mit
Officine-KOIN/Officine-Koin
koin/src/qt/bitcoinaddressvalidator.cpp
73
2022
#include "bitcoinaddressvalidator.h" /* Base58 characters are: "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" This is: - All numbers except for '0' - All uppercase letters except for 'I' and 'O' - All lowercase letters except for 'l' User friendly Base58 input can map - 'l' and 'I' to '1' - '0' and 'O' to 'o' */ BitcoinAddressValidator::BitcoinAddressValidator(QObject *parent) : QValidator(parent) { } QValidator::State BitcoinAddressValidator::validate(QString &input, int &pos) const { // Correction for(int idx=0; idx<input.size();) { bool removeChar = false; QChar ch = input.at(idx); // Corrections made are very conservative on purpose, to avoid // users unexpectedly getting away with typos that would normally // be detected, and thus sending to the wrong address. switch(ch.unicode()) { // Qt categorizes these as "Other_Format" not "Separator_Space" case 0x200B: // ZERO WIDTH SPACE case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE removeChar = true; break; default: break; } // Remove whitespace if(ch.isSpace()) removeChar = true; // To next character if(removeChar) input.remove(idx, 1); else ++idx; } // Validation QValidator::State state = QValidator::Acceptable; for(int idx=0; idx<input.size(); ++idx) { int ch = input.at(idx).unicode(); if(((ch >= '0' && ch<='9') || (ch >= 'a' && ch<='z') || (ch >= 'A' && ch<='Z')) && ch != 'l' && ch != 'I' && ch != '0' && ch != 'O') { // Luckynumeric and not a 'forbidden' character } else { state = QValidator::Invalid; } } // Empty address is "intermediate" input if(input.isEmpty()) { state = QValidator::Intermediate; } return state; }
mit
dxxb/micropython
stmhal/hal/f4/src/stm32f4xx_hal_adc_ex.c
74
30089
/** ****************************************************************************** * @file stm32f4xx_hal_adc_ex.c * @author MCD Application Team * @version V1.1.0 * @date 19-June-2014 * @brief This file provides firmware functions to manage the following * functionalities of the ADC extension peripheral: * + Extended features functions * @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (#)Initialize the ADC low level resources by implementing the HAL_ADC_MspInit(): (##) Enable the ADC interface clock using __ADC_CLK_ENABLE() (##) ADC pins configuration (+++) Enable the clock for the ADC GPIOs using the following function: __GPIOx_CLK_ENABLE() (+++) Configure these ADC pins in analog mode using HAL_GPIO_Init() (##) In case of using interrupts (e.g. HAL_ADC_Start_IT()) (+++) Configure the ADC interrupt priority using HAL_NVIC_SetPriority() (+++) Enable the ADC IRQ handler using HAL_NVIC_EnableIRQ() (+++) In ADC IRQ handler, call HAL_ADC_IRQHandler() (##) In case of using DMA to control data transfer (e.g. HAL_ADC_Start_DMA()) (+++) Enable the DMAx interface clock using __DMAx_CLK_ENABLE() (+++) Configure and enable two DMA streams stream for managing data transfer from peripheral to memory (output stream) (+++) Associate the initilalized DMA handle to the ADC DMA handle using __HAL_LINKDMA() (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the two DMA Streams. The output stream should have higher priority than the input stream. (#) Configure the ADC Prescaler, conversion resolution and data alignment using the HAL_ADC_Init() function. (#) Configure the ADC Injected channels group features, use HAL_ADC_Init() and HAL_ADC_ConfigChannel() functions. (#) Three operation modes are available within this driver : *** Polling mode IO operation *** ================================= [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart() (+) Wait for end of conversion using HAL_ADC_PollForConversion(), at this stage user can specify the value of timeout according to his end application (+) To read the ADC converted values, use the HAL_ADCEx_InjectedGetValue() function. (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop() *** Interrupt mode IO operation *** =================================== [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_IT() (+) Use HAL_ADC_IRQHandler() called under ADC_IRQHandler() Interrupt subroutine (+) At ADC end of conversion HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback (+) In case of ADC Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_IT() *** DMA mode IO operation *** ============================== [..] (+) Start the ADC peripheral using HAL_ADCEx_InjectedStart_DMA(), at this stage the user specify the length of data to be transferred at each end of conversion (+) At The end of data transfer ba HAL_ADCEx_InjectedConvCpltCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedConvCpltCallback (+) In case of transfer Error, HAL_ADCEx_InjectedErrorCallback() function is executed and user can add his own code by customization of function pointer HAL_ADCEx_InjectedErrorCallback (+) Stop the ADC peripheral using HAL_ADCEx_InjectedStop_DMA() *** Multi mode ADCs Regular channels configuration *** ====================================================== [..] (+) Select the Multi mode ADC regular channels features (dual or triple mode) and configure the DMA mode using HAL_ADCEx_MultiModeConfigChannel() functions. (+) Start the ADC peripheral using HAL_ADCEx_MultiModeStart_DMA(), at this stage the user specify the length of data to be transferred at each end of conversion (+) Read the ADCs converted values using the HAL_ADCEx_MultiModeGetValue() function. @endverbatim ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2014 STMicroelectronics</center></h2> * * 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 STMicroelectronics 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. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_hal.h" /** @addtogroup STM32F4xx_HAL_Driver * @{ */ /** @defgroup ADCEx * @brief ADC Extended driver modules * @{ */ #ifdef HAL_ADC_MODULE_ENABLED /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma); static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma); static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma); /* Private functions ---------------------------------------------------------*/ /** @defgroup ADCEx_Private_Functions * @{ */ /** @defgroup ADCEx_Group1 Extended features functions * @brief Extended features functions * @verbatim =============================================================================== ##### Extended features functions ##### =============================================================================== [..] This section provides functions allowing to: (+) Start conversion of injected channel. (+) Stop conversion of injected channel. (+) Start multimode and enable DMA transfer. (+) Stop multimode and disable DMA transfer. (+) Get result of injected channel conversion. (+) Get result of multimode conversion. (+) Configure injected channels. (+) Configure multimode. @endverbatim * @{ */ /** * @brief Enables the selected ADC software start conversion of the injected channels. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart(ADC_HandleTypeDef* hadc) { uint32_t i = 0, tmp1 = 0, tmp2 = 0; /* Process locked */ __HAL_LOCK(hadc); /* Check if a regular conversion is ongoing */ if(hadc->State == HAL_ADC_STATE_BUSY_REG) { /* Change ADC state */ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG; } else { /* Change ADC state */ hadc->State = HAL_ADC_STATE_BUSY_INJ; } /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay inserted to wait during Tstab time the ADC's stabilazation */ for(; i <= 540; i++) { __NOP(); } } /* Check if Multimode enabled */ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if(tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } else { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if((hadc->Instance == ADC1) && tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Enables the interrupt and starts ADC conversion of injected channels. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_InjectedStart_IT(ADC_HandleTypeDef* hadc) { uint32_t i = 0, tmp1 = 0, tmp2 =0; /* Process locked */ __HAL_LOCK(hadc); /* Check if a regular conversion is ongoing */ if(hadc->State == HAL_ADC_STATE_BUSY_REG) { /* Change ADC state */ hadc->State = HAL_ADC_STATE_BUSY_INJ_REG; } else { /* Change ADC state */ hadc->State = HAL_ADC_STATE_BUSY_INJ; } /* Set ADC error code to none */ hadc->ErrorCode = HAL_ADC_ERROR_NONE; /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay inserted to wait during Tstab time the ADC's stabilazation */ for(; i <= 540; i++) { __NOP(); } } /* Enable the ADC end of conversion interrupt for injected group */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_JEOC); /* Enable the ADC overrun interrupt */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); /* Check if Multimode enabled */ if(HAL_IS_BIT_CLR(ADC->CCR, ADC_CCR_MULTI)) { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if(tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } else { tmp1 = HAL_IS_BIT_CLR(hadc->Instance->CR2, ADC_CR2_JEXTEN); tmp2 = HAL_IS_BIT_CLR(hadc->Instance->CR1, ADC_CR1_JAUTO); if((hadc->Instance == ADC1) && tmp1 && tmp2) { /* Enable the selected ADC software conversion for injected group */ hadc->Instance->CR2 |= ADC_CR2_JSWSTART; } } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Disables ADC and stop conversion of injected channels. * * @note Caution: This function will stop also regular channels. * * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop(ADC_HandleTypeDef* hadc) { /* Disable the Peripheral */ __HAL_ADC_DISABLE(hadc); /* Change ADC state */ hadc->State = HAL_ADC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Poll for injected conversion complete * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param Timeout: Timeout value in millisecond. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_InjectedPollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) { uint32_t tickstart = 0; /* Get tick */ tickstart = HAL_GetTick(); /* Check End of conversion flag */ while(!(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_JEOC))) { /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { if((Timeout == 0)||((HAL_GetTick() - tickstart ) > Timeout)) { hadc->State= HAL_ADC_STATE_TIMEOUT; /* Process unlocked */ __HAL_UNLOCK(hadc); return HAL_TIMEOUT; } } } /* Check if a regular conversion is ready */ if(hadc->State == HAL_ADC_STATE_EOC_REG) { /* Change ADC state */ hadc->State = HAL_ADC_STATE_EOC_INJ_REG; } else { /* Change ADC state */ hadc->State = HAL_ADC_STATE_EOC_INJ; } /* Return ADC state */ return HAL_OK; } /** * @brief Disables the interrupt and stop ADC conversion of injected channels. * * @note Caution: This function will stop also regular channels. * * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status. */ HAL_StatusTypeDef HAL_ADCEx_InjectedStop_IT(ADC_HandleTypeDef* hadc) { /* Disable the ADC end of conversion interrupt for regular group */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); /* Disable the ADC end of conversion interrupt for injected group */ __HAL_ADC_DISABLE_IT(hadc, ADC_CR1_JEOCIE); /* Enable the Periphral */ __HAL_ADC_DISABLE(hadc); /* Change ADC state */ hadc->State = HAL_ADC_STATE_READY; /* Return function status */ return HAL_OK; } /** * @brief Gets the converted value from data register of injected channel. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param InjectedRank: the ADC injected rank. * This parameter can be one of the following values: * @arg ADC_INJECTED_RANK_1: Injected Channel1 selected * @arg ADC_INJECTED_RANK_2: Injected Channel2 selected * @arg ADC_INJECTED_RANK_3: Injected Channel3 selected * @arg ADC_INJECTED_RANK_4: Injected Channel4 selected * @retval None */ uint32_t HAL_ADCEx_InjectedGetValue(ADC_HandleTypeDef* hadc, uint32_t InjectedRank) { __IO uint32_t tmp = 0; /* Check the parameters */ assert_param(IS_ADC_INJECTED_RANK(InjectedRank)); /* Clear the ADCx's flag for injected end of conversion */ __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_JEOC); /* Return the selected ADC converted value */ switch(InjectedRank) { case ADC_INJECTED_RANK_4: { tmp = hadc->Instance->JDR4; } break; case ADC_INJECTED_RANK_3: { tmp = hadc->Instance->JDR3; } break; case ADC_INJECTED_RANK_2: { tmp = hadc->Instance->JDR2; } break; case ADC_INJECTED_RANK_1: { tmp = hadc->Instance->JDR1; } break; default: break; } return tmp; } /** * @brief Enables ADC DMA request after last transfer (Multi-ADC mode) and enables ADC peripheral * * @note Caution: This function must be used only with the ADC master. * * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param pData: Pointer to buffer in which transferred from ADC peripheral to memory will be stored. * @param Length: The length of data to be transferred from ADC peripheral to memory. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStart_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) { uint16_t counter = 0; /* Check the parameters */ assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); assert_param(IS_ADC_EXT_TRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); /* Process locked */ __HAL_LOCK(hadc); /* Enable ADC overrun interrupt */ __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); if (hadc->Init.DMAContinuousRequests != DISABLE) { /* Enable the selected ADC DMA request after last transfer */ ADC->CCR |= ADC_CCR_DDS; } else { /* Disable the selected ADC EOC rising on each regular channel conversion */ ADC->CCR &= ~ADC_CCR_DDS; } /* Set the DMA transfer complete callback */ hadc->DMA_Handle->XferCpltCallback = ADC_MultiModeDMAConvCplt; /* Set the DMA half transfer complete callback */ hadc->DMA_Handle->XferHalfCpltCallback = ADC_MultiModeDMAHalfConvCplt; /* Set the DMA error callback */ hadc->DMA_Handle->XferErrorCallback = ADC_MultiModeDMAError ; /* Enable the DMA Stream */ HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&ADC->CDR, (uint32_t)pData, Length); /* Change ADC state */ hadc->State = HAL_ADC_STATE_BUSY_REG; /* Check if ADC peripheral is disabled in order to enable it and wait during Tstab time the ADC's stabilization */ if((hadc->Instance->CR2 & ADC_CR2_ADON) != ADC_CR2_ADON) { /* Enable the Peripheral */ __HAL_ADC_ENABLE(hadc); /* Delay inserted to wait during Tstab time the ADC's stabilazation */ for(; counter <= 540; counter++) { __NOP(); } } /* if no external trigger present enable software conversion of regular channels */ if (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIGCONVEDGE_NONE) { /* Enable the selected ADC software conversion for regular group */ hadc->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Disables ADC DMA (multi-ADC mode) and disables ADC peripheral * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeStop_DMA(ADC_HandleTypeDef* hadc) { /* Process locked */ __HAL_LOCK(hadc); /* Enable the Peripheral */ __HAL_ADC_DISABLE(hadc); /* Disable ADC overrun interrupt */ __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); /* Disable the selected ADC DMA request after last transfer */ ADC->CCR &= ~ADC_CCR_DDS; /* Disable the ADC DMA Stream */ HAL_DMA_Abort(hadc->DMA_Handle); /* Change ADC state */ hadc->State = HAL_ADC_STATE_READY; /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Returns the last ADC1, ADC2 and ADC3 regular conversions results * data in the selected multi mode. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval The converted data value. */ uint32_t HAL_ADCEx_MultiModeGetValue(ADC_HandleTypeDef* hadc) { /* Return the multi mode conversion value */ return ADC->CDR; } /** * @brief Injected conversion complete callback in non blocking mode * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @retval None */ __weak void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc) { /* NOTE : This function Should not be modified, when the callback is needed, the HAL_ADC_InjectedConvCpltCallback could be implemented in the user file */ } /** * @brief Configures for the selected ADC injected channel its corresponding * rank in the sequencer and its sample time. * @param hadc: pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param sConfigInjected: ADC configuration structure for injected channel. * @retval None */ HAL_StatusTypeDef HAL_ADCEx_InjectedConfigChannel(ADC_HandleTypeDef* hadc, ADC_InjectionConfTypeDef* sConfigInjected) { #ifdef USE_FULL_ASSERT uint32_t tmp = 0; #endif /* USE_FULL_ASSERT */ /* Check the parameters */ assert_param(IS_ADC_CHANNEL(sConfigInjected->InjectedChannel)); assert_param(IS_ADC_INJECTED_RANK(sConfigInjected->InjectedRank)); assert_param(IS_ADC_SAMPLE_TIME(sConfigInjected->InjectedSamplingTime)); assert_param(IS_ADC_EXT_INJEC_TRIG(sConfigInjected->ExternalTrigInjecConv)); assert_param(IS_ADC_EXT_INJEC_TRIG_EDGE(sConfigInjected->ExternalTrigInjecConvEdge)); assert_param(IS_ADC_INJECTED_LENGTH(sConfigInjected->InjectedNbrOfConversion)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->AutoInjectedConv)); assert_param(IS_FUNCTIONAL_STATE(sConfigInjected->InjectedDiscontinuousConvMode)); #ifdef USE_FULL_ASSERT tmp = __HAL_ADC_GET_RESOLUTION(hadc); assert_param(IS_ADC_RANGE(tmp, sConfigInjected->InjectedOffset)); #endif /* USE_FULL_ASSERT */ /* Process locked */ __HAL_LOCK(hadc); /* if ADC_Channel_10 ... ADC_Channel_18 is selected */ if (sConfigInjected->InjectedChannel > ADC_CHANNEL_9) { /* Clear the old sample time */ hadc->Instance->SMPR1 &= ~__HAL_ADC_SMPR1(ADC_SMPR1_SMP10, sConfigInjected->InjectedChannel); /* Set the new sample time */ hadc->Instance->SMPR1 |= __HAL_ADC_SMPR1(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); } else /* ADC_Channel include in ADC_Channel_[0..9] */ { /* Clear the old sample time */ hadc->Instance->SMPR2 &= ~__HAL_ADC_SMPR2(ADC_SMPR2_SMP0, sConfigInjected->InjectedChannel); /* Set the new sample time */ hadc->Instance->SMPR2 |= __HAL_ADC_SMPR2(sConfigInjected->InjectedSamplingTime, sConfigInjected->InjectedChannel); } /*---------------------------- ADCx JSQR Configuration -----------------*/ hadc->Instance->JSQR &= ~(ADC_JSQR_JL); hadc->Instance->JSQR |= __HAL_ADC_SQR1(sConfigInjected->InjectedNbrOfConversion); /* Rank configuration */ /* Clear the old SQx bits for the selected rank */ hadc->Instance->JSQR &= ~__HAL_ADC_JSQR(ADC_JSQR_JSQ1, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); /* Set the SQx bits for the selected rank */ hadc->Instance->JSQR |= __HAL_ADC_JSQR(sConfigInjected->InjectedChannel, sConfigInjected->InjectedRank,sConfigInjected->InjectedNbrOfConversion); /* Select external trigger to start conversion */ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTSEL); hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConv; /* Select external trigger polarity */ hadc->Instance->CR2 &= ~(ADC_CR2_JEXTEN); hadc->Instance->CR2 |= sConfigInjected->ExternalTrigInjecConvEdge; if (sConfigInjected->AutoInjectedConv != DISABLE) { /* Enable the selected ADC automatic injected group conversion */ hadc->Instance->CR1 |= ADC_CR1_JAUTO; } else { /* Disable the selected ADC automatic injected group conversion */ hadc->Instance->CR1 &= ~(ADC_CR1_JAUTO); } if (sConfigInjected->InjectedDiscontinuousConvMode != DISABLE) { /* Enable the selected ADC injected discontinuous mode */ hadc->Instance->CR1 |= ADC_CR1_JDISCEN; } else { /* Disable the selected ADC injected discontinuous mode */ hadc->Instance->CR1 &= ~(ADC_CR1_JDISCEN); } switch(sConfigInjected->InjectedRank) { case 1: /* Set injected channel 1 offset */ hadc->Instance->JOFR1 &= ~(ADC_JOFR1_JOFFSET1); hadc->Instance->JOFR1 |= sConfigInjected->InjectedOffset; break; case 2: /* Set injected channel 2 offset */ hadc->Instance->JOFR2 &= ~(ADC_JOFR2_JOFFSET2); hadc->Instance->JOFR2 |= sConfigInjected->InjectedOffset; break; case 3: /* Set injected channel 3 offset */ hadc->Instance->JOFR3 &= ~(ADC_JOFR3_JOFFSET3); hadc->Instance->JOFR3 |= sConfigInjected->InjectedOffset; break; default: /* Set injected channel 4 offset */ hadc->Instance->JOFR4 &= ~(ADC_JOFR4_JOFFSET4); hadc->Instance->JOFR4 |= sConfigInjected->InjectedOffset; break; } /* if ADC1 Channel_18 is selected enable VBAT Channel */ if ((hadc->Instance == ADC1) && (sConfigInjected->InjectedChannel == ADC_CHANNEL_VBAT)) { /* Enable the VBAT channel*/ ADC->CCR |= ADC_CCR_VBATE; } /* if ADC1 Channel_16 or Channel_17 is selected enable TSVREFE Channel(Temperature sensor and VREFINT) */ if ((hadc->Instance == ADC1) && ((sConfigInjected->InjectedChannel == ADC_CHANNEL_TEMPSENSOR) || (sConfigInjected->InjectedChannel == ADC_CHANNEL_VREFINT))) { /* Enable the TSVREFE channel*/ ADC->CCR |= ADC_CCR_TSVREFE; } /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @brief Configures the ADC multi-mode * @param hadc : pointer to a ADC_HandleTypeDef structure that contains * the configuration information for the specified ADC. * @param multimode : pointer to an ADC_MultiModeTypeDef structure that contains * the configuration information for multimode. * @retval HAL status */ HAL_StatusTypeDef HAL_ADCEx_MultiModeConfigChannel(ADC_HandleTypeDef* hadc, ADC_MultiModeTypeDef* multimode) { /* Check the parameters */ assert_param(IS_ADC_MODE(multimode->Mode)); assert_param(IS_ADC_DMA_ACCESS_MODE(multimode->DMAAccessMode)); assert_param(IS_ADC_SAMPLING_DELAY(multimode->TwoSamplingDelay)); /* Process locked */ __HAL_LOCK(hadc); /* Set ADC mode */ ADC->CCR &= ~(ADC_CCR_MULTI); ADC->CCR |= multimode->Mode; /* Set the ADC DMA access mode */ ADC->CCR &= ~(ADC_CCR_DMA); ADC->CCR |= multimode->DMAAccessMode; /* Set delay between two sampling phases */ ADC->CCR &= ~(ADC_CCR_DELAY); ADC->CCR |= multimode->TwoSamplingDelay; /* Process unlocked */ __HAL_UNLOCK(hadc); /* Return function status */ return HAL_OK; } /** * @} */ /** * @brief DMA transfer complete callback. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAConvCplt(DMA_HandleTypeDef *hdma) { ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* Check if an injected conversion is ready */ if(hadc->State == HAL_ADC_STATE_EOC_INJ) { /* Change ADC state */ hadc->State = HAL_ADC_STATE_EOC_INJ_REG; } else { /* Change ADC state */ hadc->State = HAL_ADC_STATE_EOC_REG; } HAL_ADC_ConvCpltCallback(hadc); } /** * @brief DMA half transfer complete callback. * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAHalfConvCplt(DMA_HandleTypeDef *hdma) { ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; /* Conversion complete callback */ HAL_ADC_ConvHalfCpltCallback(hadc); } /** * @brief DMA error callback * @param hdma: pointer to a DMA_HandleTypeDef structure that contains * the configuration information for the specified DMA module. * @retval None */ static void ADC_MultiModeDMAError(DMA_HandleTypeDef *hdma) { ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; hadc->State= HAL_ADC_STATE_ERROR; /* Set ADC error code to DMA error */ hadc->ErrorCode |= HAL_ADC_ERROR_DMA; HAL_ADC_ErrorCallback(hadc); } /** * @} */ #endif /* HAL_ADC_MODULE_ENABLED */ /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
mit
suda/micropython
lib/libm/kf_sin.c
78
1655
/* * This file is part of the Micro Python project, http://micropython.org/ * * These math functions are taken from newlib-nano-2, the newlib/libm/math * directory, available from https://github.com/32bitmicro/newlib-nano-2. * * Appropriate copyright headers are reproduced below. */ /* kf_sin.c -- float version of k_sin.c * Conversion to float by Ian Lance Taylor, Cygnus Support, ian@cygnus.com. */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #include "fdlibm.h" #ifdef __STDC__ static const float #else static float #endif half = 5.0000000000e-01,/* 0x3f000000 */ S1 = -1.6666667163e-01, /* 0xbe2aaaab */ S2 = 8.3333337680e-03, /* 0x3c088889 */ S3 = -1.9841270114e-04, /* 0xb9500d01 */ S4 = 2.7557314297e-06, /* 0x3638ef1b */ S5 = -2.5050759689e-08, /* 0xb2d72f34 */ S6 = 1.5896910177e-10; /* 0x2f2ec9d3 */ #ifdef __STDC__ float __kernel_sinf(float x, float y, int iy) #else float __kernel_sinf(x, y, iy) float x,y; int iy; /* iy=0 if y is zero */ #endif { float z,r,v; __int32_t ix; GET_FLOAT_WORD(ix,x); ix &= 0x7fffffff; /* high word of x */ if(ix<0x32000000) /* |x| < 2**-27 */ {if((int)x==0) return x;} /* generate inexact */ z = x*x; v = z*x; r = S2+z*(S3+z*(S4+z*(S5+z*S6))); if(iy==0) return x+v*(S1+z*r); else return x-((z*(half*y-v*r)-y)-v*S1); }
mit
EvanDWalsh/HackerCoin
src/qt/editaddressdialog.cpp
83
3564
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setDisabled(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid barcoin address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
mit
attackjz/Cocos2d-x_CustomSliderList
CustomSliderList/cocos2d/cocos/editor-support/cocostudio/CCTween.cpp
91
12811
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "cocostudio/CCTween.h" #include "cocostudio/CCArmatureAnimation.h" #include "cocostudio/CCBone.h" #include "cocostudio/CCArmature.h" #include "cocostudio/CCUtilMath.h" #include "cocostudio/CCTransformHelp.h" namespace cocostudio { using cocos2d::tweenfunc::Linear; Tween *Tween::create(Bone *bone) { Tween *pTween = new Tween(); if (pTween && pTween->init(bone)) { pTween->autorelease(); return pTween; } CC_SAFE_DELETE(pTween); return nullptr; } Tween::Tween() : _movementBoneData(nullptr) , _tweenData(nullptr) , _from(nullptr) , _to(nullptr) , _between(nullptr) , _bone(nullptr) , _frameTweenEasing(Linear) , _fromIndex(0) , _toIndex(0) , _animation(nullptr) , _passLastFrame(false) { } Tween::~Tween(void) { CC_SAFE_DELETE( _from ); CC_SAFE_DELETE( _between ); } bool Tween::init(Bone *bone) { bool bRet = false; do { _from = new FrameData(); _between = new FrameData(); _bone = bone; _tweenData = _bone->getTweenData(); _tweenData->displayIndex = -1; _animation = _bone->getArmature() != nullptr ? _bone->getArmature()->getAnimation() : nullptr; bRet = true; } while (0); return bRet; } void Tween::play(MovementBoneData *movementBoneData, int durationTo, int durationTween, int loop, int tweenEasing) { ProcessBase::play(durationTo, durationTween, loop, tweenEasing); if (loop) { _loopType = ANIMATION_TO_LOOP_FRONT; } else { _loopType = ANIMATION_NO_LOOP; } _totalDuration = 0; _betweenDuration = 0; _fromIndex = _toIndex = 0; bool difMovement = movementBoneData != _movementBoneData; setMovementBoneData(movementBoneData); _rawDuration = _movementBoneData->duration; FrameData *nextKeyFrame = _movementBoneData->getFrameData(0); _tweenData->displayIndex = nextKeyFrame->displayIndex; if (_bone->getArmature()->getArmatureData()->dataVersion >= VERSION_COMBINED) { TransformHelp::nodeSub(*_tweenData, *_bone->getBoneData()); _tweenData->scaleX += 1; _tweenData->scaleY += 1; } if (_rawDuration == 0 ) { _loopType = SINGLE_FRAME; if(durationTo == 0) { setBetween(nextKeyFrame, nextKeyFrame); } else { setBetween(_tweenData, nextKeyFrame); } _frameTweenEasing = Linear; } else if (_movementBoneData->frameList.size() > 1) { _durationTween = durationTween * _movementBoneData->scale; if (loop && _movementBoneData->delay != 0) { setBetween(_tweenData, tweenNodeTo(updateFrameData(1 - _movementBoneData->delay), _between)); } else { if (!difMovement || durationTo == 0) { setBetween(nextKeyFrame, nextKeyFrame); } else { setBetween(_tweenData, nextKeyFrame); } } } tweenNodeTo(0); } void Tween::gotoAndPlay(int frameIndex) { ProcessBase::gotoFrame(frameIndex); _totalDuration = 0; _betweenDuration = 0; _fromIndex = _toIndex = 0; _isPlaying = true; _isComplete = _isPause = false; _currentPercent = (float)_curFrameIndex / ((float)_rawDuration-1); _currentFrame = _nextFrameIndex * _currentPercent; } void Tween::gotoAndPause(int frameIndex) { gotoAndPlay(frameIndex); pause(); } void Tween::updateHandler() { if (_currentPercent >= 1) { switch(_loopType) { case SINGLE_FRAME: { _currentPercent = 1; _isComplete = true; _isPlaying = false; } break; case ANIMATION_NO_LOOP: { _loopType = ANIMATION_MAX; if (_durationTween <= 0) { _currentPercent = 1; } else { _currentPercent = (_currentPercent - 1) * _nextFrameIndex / _durationTween; } if (_currentPercent >= 1) { _currentPercent = 1; _isComplete = true; _isPlaying = false; break; } else { _nextFrameIndex = _durationTween; _currentFrame = _currentPercent * _nextFrameIndex; _totalDuration = 0; _betweenDuration = 0; _fromIndex = _toIndex = 0; break; } } break; case ANIMATION_TO_LOOP_FRONT: { _loopType = ANIMATION_LOOP_FRONT; _nextFrameIndex = _durationTween > 0 ? _durationTween : 1; if (_movementBoneData->delay != 0) { // _currentFrame = (1 - _movementBoneData->delay) * (float)_nextFrameIndex; _currentPercent = _currentFrame / _nextFrameIndex; } else { _currentPercent = 0; _currentFrame = 0; } _totalDuration = 0; _betweenDuration = 0; _fromIndex = _toIndex = 0; } break; case ANIMATION_MAX: { _currentPercent = 1; _isComplete = true; _isPlaying = false; } break; default: { _currentFrame = fmodf(_currentFrame, _nextFrameIndex); } break; } } if (_currentPercent < 1 && _loopType <= ANIMATION_TO_LOOP_BACK) { _currentPercent = sin(_currentPercent * CC_HALF_PI); } float percent = _currentPercent; if (_loopType > ANIMATION_TO_LOOP_BACK) { percent = updateFrameData(percent); } if(_frameTweenEasing != ::cocos2d::tweenfunc::TWEEN_EASING_MAX) { tweenNodeTo(percent); } } void Tween::setBetween(FrameData *from, FrameData *to, bool limit) { do { if(from->displayIndex < 0 && to->displayIndex >= 0) { _from->copy(to); _between->subtract(to, to, limit); break; } else if(to->displayIndex < 0 && from->displayIndex >= 0) { _from->copy(from); _between->subtract(to, to, limit); break; } _from->copy(from); _between->subtract(from, to, limit); } while (0); if (!from->isTween) { _tweenData->copy(from); _tweenData->isTween = true; } arriveKeyFrame(from); } void Tween::arriveKeyFrame(FrameData *keyFrameData) { if(keyFrameData) { DisplayManager *displayManager = _bone->getDisplayManager(); //! Change bone's display int displayIndex = keyFrameData->displayIndex; if (!displayManager->isForceChangeDisplay()) { displayManager->changeDisplayWithIndex(displayIndex, false); } //! Update bone zorder, bone's zorder is determined by frame zorder and bone zorder _tweenData->zOrder = keyFrameData->zOrder; _bone->updateZOrder(); //! Update blend type _bone->setBlendFunc(keyFrameData->blendFunc); //! Update child armature's movement Armature *childAramture = _bone->getChildArmature(); if(childAramture) { if(keyFrameData->strMovement.length() != 0) { childAramture->getAnimation()->play(keyFrameData->strMovement.c_str()); } } } } FrameData *Tween::tweenNodeTo(float percent, FrameData *node) { node = node == nullptr ? _tweenData : node; if (!_from->isTween) { percent = 0; } node->x = _from->x + percent * _between->x; node->y = _from->y + percent * _between->y; node->scaleX = _from->scaleX + percent * _between->scaleX; node->scaleY = _from->scaleY + percent * _between->scaleY; node->skewX = _from->skewX + percent * _between->skewX; node->skewY = _from->skewY + percent * _between->skewY; _bone->setTransformDirty(true); if (node && _between->isUseColorInfo) { tweenColorTo(percent, node); } return node; } void Tween::tweenColorTo(float percent, FrameData *node) { node->a = _from->a + percent * _between->a; node->r = _from->r + percent * _between->r; node->g = _from->g + percent * _between->g; node->b = _from->b + percent * _between->b; _bone->updateColor(); } float Tween::updateFrameData(float currentPercent) { if (currentPercent > 1 && _movementBoneData->delay != 0) { currentPercent = fmodf(currentPercent, 1); } float playedTime = ((float)_rawDuration-1) * currentPercent; //! If play to current frame's front or back, then find current frame again if (playedTime < _totalDuration || playedTime >= _totalDuration + _betweenDuration) { /* * Get frame length, if _toIndex >= _length, then set _toIndex to 0, start anew. * _toIndex is next index will play */ long length = _movementBoneData->frameList.size(); cocos2d::Vector<FrameData *> &frames = _movementBoneData->frameList; FrameData *from = nullptr; FrameData *to = nullptr; if (playedTime < frames.at(0)->frameID) { from = to = frames.at(0); setBetween(from, to); return _currentPercent; } if(playedTime >= frames.at(length - 1)->frameID) { // If _passLastFrame is true and playedTime >= frames[length - 1]->frameID, then do not need to go on. if (_passLastFrame) { from = to = frames.at(length - 1); setBetween(from, to); return _currentPercent; } _passLastFrame = true; } else { _passLastFrame = false; } do { _fromIndex = _toIndex; from = frames.at(_fromIndex); _totalDuration = from->frameID; _toIndex = _fromIndex + 1; if (_toIndex >= length) { _toIndex = 0; } to = frames.at(_toIndex); //! Guaranteed to trigger frame event if(from->strEvent.length() != 0 && !_animation->isIgnoreFrameEvent()) { _animation->frameEvent(_bone, from->strEvent.c_str(), from->frameID, playedTime); } if (playedTime == from->frameID || (_passLastFrame && _fromIndex == length-1)) { break; } } while (playedTime < from->frameID || playedTime >= to->frameID); _betweenDuration = to->frameID - from->frameID; _frameTweenEasing = from->tweenEasing; setBetween(from, to, false); } currentPercent = _betweenDuration == 0 ? 0 : (playedTime - _totalDuration) / (float)_betweenDuration; /* * If frame tween easing equal to TWEEN_EASING_MAX, then it will not do tween. */ TweenType tweenType = (_frameTweenEasing != Linear) ? _frameTweenEasing : _tweenEasing; if (tweenType != cocos2d::tweenfunc::TWEEN_EASING_MAX && tweenType != Linear && !_passLastFrame) { currentPercent = cocos2d::tweenfunc::tweenTo(currentPercent, tweenType, _from->easingParams); } return currentPercent; } }
mit
impedimentToProgress/UCI-BlueChip
snapgear_linux/linux-2.6.21.1/drivers/isdn/hisax/arcofi.c
352
3664
/* $Id: arcofi.c,v 1.14.2.3 2004/01/13 14:31:24 keil Exp $ * * Ansteuerung ARCOFI 2165 * * Author Karsten Keil * Copyright by Karsten Keil <keil@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include "hisax.h" #include "isdnl1.h" #include "isac.h" #include "arcofi.h" #define ARCOFI_TIMER_VALUE 20 static void add_arcofi_timer(struct IsdnCardState *cs) { if (test_and_set_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) { del_timer(&cs->dc.isac.arcofitimer); } init_timer(&cs->dc.isac.arcofitimer); cs->dc.isac.arcofitimer.expires = jiffies + ((ARCOFI_TIMER_VALUE * HZ)/1000); add_timer(&cs->dc.isac.arcofitimer); } static void send_arcofi(struct IsdnCardState *cs) { u_char val; add_arcofi_timer(cs); cs->dc.isac.mon_txp = 0; cs->dc.isac.mon_txc = cs->dc.isac.arcofi_list->len; memcpy(cs->dc.isac.mon_tx, cs->dc.isac.arcofi_list->msg, cs->dc.isac.mon_txc); switch(cs->dc.isac.arcofi_bc) { case 0: break; case 1: cs->dc.isac.mon_tx[1] |= 0x40; break; default: break; } cs->dc.isac.mocr &= 0x0f; cs->dc.isac.mocr |= 0xa0; cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr); val = cs->readisac(cs, ISAC_MOSR); cs->writeisac(cs, ISAC_MOX1, cs->dc.isac.mon_tx[cs->dc.isac.mon_txp++]); cs->dc.isac.mocr |= 0x10; cs->writeisac(cs, ISAC_MOCR, cs->dc.isac.mocr); } int arcofi_fsm(struct IsdnCardState *cs, int event, void *data) { if (cs->debug & L1_DEB_MONITOR) { debugl1(cs, "arcofi state %d event %d", cs->dc.isac.arcofi_state, event); } if (event == ARCOFI_TIMEOUT) { cs->dc.isac.arcofi_state = ARCOFI_NOP; test_and_set_bit(FLG_ARCOFI_ERROR, &cs->HW_Flags); wake_up(&cs->dc.isac.arcofi_wait); return(1); } switch (cs->dc.isac.arcofi_state) { case ARCOFI_NOP: if (event == ARCOFI_START) { cs->dc.isac.arcofi_list = data; cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT; send_arcofi(cs); } break; case ARCOFI_TRANSMIT: if (event == ARCOFI_TX_END) { if (cs->dc.isac.arcofi_list->receive) { add_arcofi_timer(cs); cs->dc.isac.arcofi_state = ARCOFI_RECEIVE; } else { if (cs->dc.isac.arcofi_list->next) { cs->dc.isac.arcofi_list = cs->dc.isac.arcofi_list->next; send_arcofi(cs); } else { if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) { del_timer(&cs->dc.isac.arcofitimer); } cs->dc.isac.arcofi_state = ARCOFI_NOP; wake_up(&cs->dc.isac.arcofi_wait); } } } break; case ARCOFI_RECEIVE: if (event == ARCOFI_RX_END) { if (cs->dc.isac.arcofi_list->next) { cs->dc.isac.arcofi_list = cs->dc.isac.arcofi_list->next; cs->dc.isac.arcofi_state = ARCOFI_TRANSMIT; send_arcofi(cs); } else { if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) { del_timer(&cs->dc.isac.arcofitimer); } cs->dc.isac.arcofi_state = ARCOFI_NOP; wake_up(&cs->dc.isac.arcofi_wait); } } break; default: debugl1(cs, "Arcofi unknown state %x", cs->dc.isac.arcofi_state); return(2); } return(0); } static void arcofi_timer(struct IsdnCardState *cs) { arcofi_fsm(cs, ARCOFI_TIMEOUT, NULL); } void clear_arcofi(struct IsdnCardState *cs) { if (test_and_clear_bit(FLG_ARCOFI_TIMER, &cs->HW_Flags)) { del_timer(&cs->dc.isac.arcofitimer); } } void init_arcofi(struct IsdnCardState *cs) { cs->dc.isac.arcofitimer.function = (void *) arcofi_timer; cs->dc.isac.arcofitimer.data = (long) cs; init_timer(&cs->dc.isac.arcofitimer); init_waitqueue_head(&cs->dc.isac.arcofi_wait); test_and_set_bit(HW_ARCOFI, &cs->HW_Flags); }
mit
mihyaeru21/ItoToshi
cocos2d/extensions/Particle3D/PU/CCPUDoStopSystemEventHandler.cpp
97
1983
/**************************************************************************** Copyright (C) 2013 Henry van Merode. All rights reserved. Copyright (c) 2015 Chukong Technologies Inc. http://www.cocos2d-x.org 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 "extensions/Particle3D/PU/CCPUDoStopSystemEventHandler.h" #include "extensions/Particle3D/PU/CCPUParticleSystem3D.h" NS_CC_BEGIN //----------------------------------------------------------------------- void PUDoStopSystemEventHandler::handle (PUParticleSystem3D* particleSystem, PUParticle3D* particle, float timeElapsed) { ParticleSystem3D *parent = particleSystem->getParentParticleSystem(); if (parent) parent->stopParticleSystem(); } PUDoStopSystemEventHandler* PUDoStopSystemEventHandler::create() { auto peh = new (std::nothrow) PUDoStopSystemEventHandler(); peh->autorelease(); return peh; } NS_CC_END
mit
yy1300326388/iBooks
jni/mupdf/freetype/src/gxvalid/gxvjust.c
356
21301
/***************************************************************************/ /* */ /* gxvjust.c */ /* */ /* TrueTypeGX/AAT just table validation (body). */ /* */ /* Copyright 2005 by suzuki toshiya, Masatake YAMATO, Red Hat K.K., */ /* David Turner, Robert Wilhelm, and Werner Lemberg. */ /* */ /* This file is part of the FreeType project, and may only be used, */ /* modified, and distributed under the terms of the FreeType project */ /* license, LICENSE.TXT. By continuing to use, modify, or distribute */ /* this file you indicate that you have read the license and */ /* understand and accept it fully. */ /* */ /***************************************************************************/ /***************************************************************************/ /* */ /* gxvalid is derived from both gxlayout module and otvalid module. */ /* Development of gxlayout is supported by the Information-technology */ /* Promotion Agency(IPA), Japan. */ /* */ /***************************************************************************/ #include "gxvalid.h" #include "gxvcommn.h" #include FT_SFNT_NAMES_H /*************************************************************************/ /* */ /* The macro FT_COMPONENT is used in trace mode. It is an implicit */ /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */ /* messages during execution. */ /* */ #undef FT_COMPONENT #define FT_COMPONENT trace_gxvjust /* * referred `just' table format specification: * http://developer.apple.com/fonts/TTRefMan/RM06/Chap6just.html * last updated 2000. * ---------------------------------------------- * [JUST HEADER]: GXV_JUST_HEADER_SIZE * version (fixed: 32bit) = 0x00010000 * format (uint16: 16bit) = 0 is only defined (2000) * horizOffset (uint16: 16bit) * vertOffset (uint16: 16bit) * ---------------------------------------------- */ typedef struct GXV_just_DataRec_ { FT_UShort wdc_offset_max; FT_UShort wdc_offset_min; FT_UShort pc_offset_max; FT_UShort pc_offset_min; } GXV_just_DataRec, *GXV_just_Data; #define GXV_JUST_DATA( a ) GXV_TABLE_DATA( just, a ) /* GX just table does not define their subset of GID */ static void gxv_just_check_max_gid( FT_UShort gid, const FT_String* msg_tag, GXV_Validator valid ) { if ( gid < valid->face->num_glyphs ) return; GXV_TRACE(( "just table includes too large %s" " GID=%d > %d (in maxp)\n", msg_tag, gid, valid->face->num_glyphs )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_GLYPH_ID ); } static void gxv_just_wdp_entry_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong justClass; #ifdef GXV_LOAD_UNUSED_VARS FT_Fixed beforeGrowLimit; FT_Fixed beforeShrinkGrowLimit; FT_Fixed afterGrowLimit; FT_Fixed afterShrinkGrowLimit; FT_UShort growFlags; FT_UShort shrinkFlags; #endif GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 + 4 + 2 + 2 ); justClass = FT_NEXT_ULONG( p ); #ifndef GXV_LOAD_UNUSED_VARS p += 4 + 4 + 4 + 4 + 2 + 2; #else beforeGrowLimit = FT_NEXT_ULONG( p ); beforeShrinkGrowLimit = FT_NEXT_ULONG( p ); afterGrowLimit = FT_NEXT_ULONG( p ); afterShrinkGrowLimit = FT_NEXT_ULONG( p ); growFlags = FT_NEXT_USHORT( p ); shrinkFlags = FT_NEXT_USHORT( p ); #endif /* According to Apple spec, only 7bits in justClass is used */ if ( ( justClass & 0xFFFFFF80 ) != 0 ) { GXV_TRACE(( "just table includes non-zero value" " in unused justClass higher bits" " of WidthDeltaPair" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } valid->subtable_length = p - table; } static void gxv_just_wdc_entry_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong count, i; GXV_LIMIT_CHECK( 4 ); count = FT_NEXT_ULONG( p ); for ( i = 0; i < count; i++ ) { GXV_TRACE(( "validating wdc pair %d/%d\n", i + 1, count )); gxv_just_wdp_entry_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; } static void gxv_just_widthDeltaClusters_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table ; FT_Bytes wdc_end = table + GXV_JUST_DATA( wdc_offset_max ); FT_UInt i; GXV_NAME_ENTER( "just justDeltaClusters" ); if ( limit <= wdc_end ) FT_INVALID_OFFSET; for ( i = 0; p <= wdc_end; i++ ) { gxv_just_wdc_entry_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_actSubrecord_type0_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_Fixed lowerLimit; FT_Fixed upperLimit; #ifdef GXV_LOAD_UNUSED_VARS FT_UShort order; #endif FT_UShort decomposedCount; FT_UInt i; GXV_LIMIT_CHECK( 4 + 4 + 2 + 2 ); lowerLimit = FT_NEXT_ULONG( p ); upperLimit = FT_NEXT_ULONG( p ); #ifdef GXV_LOAD_UNUSED_VARS order = FT_NEXT_USHORT( p ); #else p += 2; #endif decomposedCount = FT_NEXT_USHORT( p ); if ( lowerLimit >= upperLimit ) { GXV_TRACE(( "just table includes invalid range spec:" " lowerLimit(%d) > upperLimit(%d)\n" )); GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); } for ( i = 0; i < decomposedCount; i++ ) { FT_UShort glyphs; GXV_LIMIT_CHECK( 2 ); glyphs = FT_NEXT_USHORT( p ); gxv_just_check_max_gid( glyphs, "type0:glyphs", valid ); } valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type1_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort addGlyph; GXV_LIMIT_CHECK( 2 ); addGlyph = FT_NEXT_USHORT( p ); gxv_just_check_max_gid( addGlyph, "type1:addGlyph", valid ); valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type2_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; #ifdef GXV_LOAD_UNUSED_VARS FT_Fixed substThreshhold; /* Apple misspelled "Threshhold" */ #endif FT_UShort addGlyph; FT_UShort substGlyph; GXV_LIMIT_CHECK( 4 + 2 + 2 ); #ifdef GXV_LOAD_UNUSED_VARS substThreshhold = FT_NEXT_ULONG( p ); #else p += 4; #endif addGlyph = FT_NEXT_USHORT( p ); substGlyph = FT_NEXT_USHORT( p ); if ( addGlyph != 0xFFFF ) gxv_just_check_max_gid( addGlyph, "type2:addGlyph", valid ); gxv_just_check_max_gid( substGlyph, "type2:substGlyph", valid ); valid->subtable_length = p - table; } static void gxv_just_actSubrecord_type4_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong variantsAxis; FT_Fixed minimumLimit; FT_Fixed noStretchValue; FT_Fixed maximumLimit; GXV_LIMIT_CHECK( 4 + 4 + 4 + 4 ); variantsAxis = FT_NEXT_ULONG( p ); minimumLimit = FT_NEXT_ULONG( p ); noStretchValue = FT_NEXT_ULONG( p ); maximumLimit = FT_NEXT_ULONG( p ); valid->subtable_length = p - table; if ( variantsAxis != 0x64756374 ) /* 'duct' */ GXV_TRACE(( "variantsAxis 0x%08x is non default value", variantsAxis )); if ( minimumLimit > noStretchValue ) GXV_TRACE(( "type4:minimumLimit 0x%08x > noStretchValue 0x%08x\n", minimumLimit, noStretchValue )); else if ( noStretchValue > maximumLimit ) GXV_TRACE(( "type4:noStretchValue 0x%08x > maximumLimit 0x%08x\n", noStretchValue, maximumLimit )); else if ( !IS_PARANOID_VALIDATION ) return; FT_INVALID_DATA; } static void gxv_just_actSubrecord_type5_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort flags; FT_UShort glyph; GXV_LIMIT_CHECK( 2 + 2 ); flags = FT_NEXT_USHORT( p ); glyph = FT_NEXT_USHORT( p ); if ( flags ) GXV_TRACE(( "type5: nonzero value 0x%04x in unused flags\n", flags )); gxv_just_check_max_gid( glyph, "type5:glyph", valid ); valid->subtable_length = p - table; } /* parse single actSubrecord */ static void gxv_just_actSubrecord_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort actionClass; FT_UShort actionType; FT_ULong actionLength; GXV_NAME_ENTER( "just actSubrecord" ); GXV_LIMIT_CHECK( 2 + 2 + 4 ); actionClass = FT_NEXT_USHORT( p ); actionType = FT_NEXT_USHORT( p ); actionLength = FT_NEXT_ULONG( p ); /* actionClass is related with justClass using 7bit only */ if ( ( actionClass & 0xFF80 ) != 0 ) GXV_SET_ERR_IF_PARANOID( FT_INVALID_DATA ); if ( actionType == 0 ) gxv_just_actSubrecord_type0_validate( p, limit, valid ); else if ( actionType == 1 ) gxv_just_actSubrecord_type1_validate( p, limit, valid ); else if ( actionType == 2 ) gxv_just_actSubrecord_type2_validate( p, limit, valid ); else if ( actionType == 3 ) ; /* Stretch glyph action: no actionData */ else if ( actionType == 4 ) gxv_just_actSubrecord_type4_validate( p, limit, valid ); else if ( actionType == 5 ) gxv_just_actSubrecord_type5_validate( p, limit, valid ); else FT_INVALID_DATA; valid->subtable_length = actionLength; GXV_EXIT; } static void gxv_just_pcActionRecord_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_ULong actionCount; FT_ULong i; GXV_LIMIT_CHECK( 4 ); actionCount = FT_NEXT_ULONG( p ); GXV_TRACE(( "actionCount = %d\n", actionCount )); for ( i = 0; i < actionCount; i++ ) { gxv_just_actSubrecord_validate( p, limit, valid ); p += valid->subtable_length; } valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_pcTable_LookupValue_entry_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); if ( value_p->u > GXV_JUST_DATA( pc_offset_max ) ) GXV_JUST_DATA( pc_offset_max ) = value_p->u; if ( value_p->u < GXV_JUST_DATA( pc_offset_max ) ) GXV_JUST_DATA( pc_offset_min ) = value_p->u; } static void gxv_just_pcLookupTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "just pcLookupTable" ); GXV_JUST_DATA( pc_offset_max ) = 0x0000; GXV_JUST_DATA( pc_offset_min ) = 0xFFFFU; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_just_pcTable_LookupValue_entry_validate; gxv_LookupTable_validate( p, limit, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } static void gxv_just_postcompTable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_NAME_ENTER( "just postcompTable" ); gxv_just_pcLookupTable_validate( p, limit, valid ); p += valid->subtable_length; gxv_just_pcActionRecord_validate( p, limit, valid ); p += valid->subtable_length; valid->subtable_length = p - table; GXV_EXIT; } static void gxv_just_classTable_entry_validate( FT_Byte state, FT_UShort flags, GXV_StateTable_GlyphOffsetCPtr glyphOffset_p, FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { #ifdef GXV_LOAD_UNUSED_VARS /* TODO: validate markClass & currentClass */ FT_UShort setMark; FT_UShort dontAdvance; FT_UShort markClass; FT_UShort currentClass; #endif FT_UNUSED( state ); FT_UNUSED( glyphOffset_p ); FT_UNUSED( table ); FT_UNUSED( limit ); FT_UNUSED( valid ); #ifndef GXV_LOAD_UNUSED_VARS FT_UNUSED( flags ); #else setMark = (FT_UShort)( ( flags >> 15 ) & 1 ); dontAdvance = (FT_UShort)( ( flags >> 14 ) & 1 ); markClass = (FT_UShort)( ( flags >> 7 ) & 0x7F ); currentClass = (FT_UShort)( flags & 0x7F ); #endif } static void gxv_just_justClassTable_validate ( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; FT_UShort length; FT_UShort coverage; FT_ULong subFeatureFlags; GXV_NAME_ENTER( "just justClassTable" ); GXV_LIMIT_CHECK( 2 + 2 + 4 ); length = FT_NEXT_USHORT( p ); coverage = FT_NEXT_USHORT( p ); subFeatureFlags = FT_NEXT_ULONG( p ); GXV_TRACE(( " justClassTable: coverage = 0x%04x (%s) ", coverage )); if ( ( coverage & 0x4000 ) == 0 ) GXV_TRACE(( "ascending\n" )); else GXV_TRACE(( "descending\n" )); if ( subFeatureFlags ) GXV_TRACE(( " justClassTable: nonzero value (0x%08x)" " in unused subFeatureFlags\n", subFeatureFlags )); valid->statetable.optdata = NULL; valid->statetable.optdata_load_func = NULL; valid->statetable.subtable_setup_func = NULL; valid->statetable.entry_glyphoffset_fmt = GXV_GLYPHOFFSET_NONE; valid->statetable.entry_validate_func = gxv_just_classTable_entry_validate; gxv_StateTable_validate( p, table + length, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } static void gxv_just_wdcTable_LookupValue_validate( FT_UShort glyph, GXV_LookupValueCPtr value_p, GXV_Validator valid ) { FT_UNUSED( glyph ); if ( value_p->u > GXV_JUST_DATA( wdc_offset_max ) ) GXV_JUST_DATA( wdc_offset_max ) = value_p->u; if ( value_p->u < GXV_JUST_DATA( wdc_offset_min ) ) GXV_JUST_DATA( wdc_offset_min ) = value_p->u; } static void gxv_just_justData_lookuptable_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { FT_Bytes p = table; GXV_JUST_DATA( wdc_offset_max ) = 0x0000; GXV_JUST_DATA( wdc_offset_min ) = 0xFFFFU; valid->lookupval_sign = GXV_LOOKUPVALUE_UNSIGNED; valid->lookupval_func = gxv_just_wdcTable_LookupValue_validate; gxv_LookupTable_validate( p, limit, valid ); /* subtable_length is set by gxv_LookupTable_validate() */ GXV_EXIT; } /* * gxv_just_justData_validate() parses and validates horizData, vertData. */ static void gxv_just_justData_validate( FT_Bytes table, FT_Bytes limit, GXV_Validator valid ) { /* * following 3 offsets are measured from the start of `just' * (which table points to), not justData */ FT_UShort justClassTableOffset; FT_UShort wdcTableOffset; FT_UShort pcTableOffset; FT_Bytes p = table; GXV_ODTECT( 4, odtect ); GXV_NAME_ENTER( "just justData" ); GXV_ODTECT_INIT( odtect ); GXV_LIMIT_CHECK( 2 + 2 + 2 ); justClassTableOffset = FT_NEXT_USHORT( p ); wdcTableOffset = FT_NEXT_USHORT( p ); pcTableOffset = FT_NEXT_USHORT( p ); GXV_TRACE(( " (justClassTableOffset = 0x%04x)\n", justClassTableOffset )); GXV_TRACE(( " (wdcTableOffset = 0x%04x)\n", wdcTableOffset )); GXV_TRACE(( " (pcTableOffset = 0x%04x)\n", pcTableOffset )); gxv_just_justData_lookuptable_validate( p, limit, valid ); gxv_odtect_add_range( p, valid->subtable_length, "just_LookupTable", odtect ); if ( wdcTableOffset ) { gxv_just_widthDeltaClusters_validate( valid->root->base + wdcTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + wdcTableOffset, valid->subtable_length, "just_wdcTable", odtect ); } if ( pcTableOffset ) { gxv_just_postcompTable_validate( valid->root->base + pcTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + pcTableOffset, valid->subtable_length, "just_pcTable", odtect ); } if ( justClassTableOffset ) { gxv_just_justClassTable_validate( valid->root->base + justClassTableOffset, limit, valid ); gxv_odtect_add_range( valid->root->base + justClassTableOffset, valid->subtable_length, "just_justClassTable", odtect ); } gxv_odtect_validate( odtect, valid ); GXV_EXIT; } FT_LOCAL_DEF( void ) gxv_just_validate( FT_Bytes table, FT_Face face, FT_Validator ftvalid ) { FT_Bytes p = table; FT_Bytes limit = 0; GXV_ValidatorRec validrec; GXV_Validator valid = &validrec; GXV_just_DataRec justrec; GXV_just_Data just = &justrec; FT_ULong version; FT_UShort format; FT_UShort horizOffset; FT_UShort vertOffset; GXV_ODTECT( 3, odtect ); GXV_ODTECT_INIT( odtect ); valid->root = ftvalid; valid->table_data = just; valid->face = face; FT_TRACE3(( "validating `just' table\n" )); GXV_INIT; limit = valid->root->limit; GXV_LIMIT_CHECK( 4 + 2 + 2 + 2 ); version = FT_NEXT_ULONG( p ); format = FT_NEXT_USHORT( p ); horizOffset = FT_NEXT_USHORT( p ); vertOffset = FT_NEXT_USHORT( p ); gxv_odtect_add_range( table, p - table, "just header", odtect ); /* Version 1.0 (always:2000) */ GXV_TRACE(( " (version = 0x%08x)\n", version )); if ( version != 0x00010000UL ) FT_INVALID_FORMAT; /* format 0 (always:2000) */ GXV_TRACE(( " (format = 0x%04x)\n", format )); if ( format != 0x0000 ) FT_INVALID_FORMAT; GXV_TRACE(( " (horizOffset = %d)\n", horizOffset )); GXV_TRACE(( " (vertOffset = %d)\n", vertOffset )); /* validate justData */ if ( 0 < horizOffset ) { gxv_just_justData_validate( table + horizOffset, limit, valid ); gxv_odtect_add_range( table + horizOffset, valid->subtable_length, "horizJustData", odtect ); } if ( 0 < vertOffset ) { gxv_just_justData_validate( table + vertOffset, limit, valid ); gxv_odtect_add_range( table + vertOffset, valid->subtable_length, "vertJustData", odtect ); } gxv_odtect_validate( odtect, valid ); FT_TRACE4(( "\n" )); } /* END */
mit
DustinTriplett/godot
drivers/builtin_openssl2/crypto/x509v3/v3_asid.c
614
24159
/* * Contributed to the OpenSSL Project by the American Registry for * Internet Numbers ("ARIN"). */ /* ==================================================================== * Copyright (c) 2006 The OpenSSL 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * licensing@OpenSSL.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). */ /* * Implementation of RFC 3779 section 3.2. */ #include <stdio.h> #include <string.h> #include "cryptlib.h" #include <openssl/conf.h> #include <openssl/asn1.h> #include <openssl/asn1t.h> #include <openssl/x509v3.h> #include <openssl/x509.h> #include <openssl/bn.h> #ifndef OPENSSL_NO_RFC3779 /* * OpenSSL ASN.1 template translation of RFC 3779 3.2.3. */ ASN1_SEQUENCE(ASRange) = { ASN1_SIMPLE(ASRange, min, ASN1_INTEGER), ASN1_SIMPLE(ASRange, max, ASN1_INTEGER) } ASN1_SEQUENCE_END(ASRange) ASN1_CHOICE(ASIdOrRange) = { ASN1_SIMPLE(ASIdOrRange, u.id, ASN1_INTEGER), ASN1_SIMPLE(ASIdOrRange, u.range, ASRange) } ASN1_CHOICE_END(ASIdOrRange) ASN1_CHOICE(ASIdentifierChoice) = { ASN1_SIMPLE(ASIdentifierChoice, u.inherit, ASN1_NULL), ASN1_SEQUENCE_OF(ASIdentifierChoice, u.asIdsOrRanges, ASIdOrRange) } ASN1_CHOICE_END(ASIdentifierChoice) ASN1_SEQUENCE(ASIdentifiers) = { ASN1_EXP_OPT(ASIdentifiers, asnum, ASIdentifierChoice, 0), ASN1_EXP_OPT(ASIdentifiers, rdi, ASIdentifierChoice, 1) } ASN1_SEQUENCE_END(ASIdentifiers) IMPLEMENT_ASN1_FUNCTIONS(ASRange) IMPLEMENT_ASN1_FUNCTIONS(ASIdOrRange) IMPLEMENT_ASN1_FUNCTIONS(ASIdentifierChoice) IMPLEMENT_ASN1_FUNCTIONS(ASIdentifiers) /* * i2r method for an ASIdentifierChoice. */ static int i2r_ASIdentifierChoice(BIO *out, ASIdentifierChoice *choice, int indent, const char *msg) { int i; char *s; if (choice == NULL) return 1; BIO_printf(out, "%*s%s:\n", indent, "", msg); switch (choice->type) { case ASIdentifierChoice_inherit: BIO_printf(out, "%*sinherit\n", indent + 2, ""); break; case ASIdentifierChoice_asIdsOrRanges: for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges); i++) { ASIdOrRange *aor = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); switch (aor->type) { case ASIdOrRange_id: if ((s = i2s_ASN1_INTEGER(NULL, aor->u.id)) == NULL) return 0; BIO_printf(out, "%*s%s\n", indent + 2, "", s); OPENSSL_free(s); break; case ASIdOrRange_range: if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->min)) == NULL) return 0; BIO_printf(out, "%*s%s-", indent + 2, "", s); OPENSSL_free(s); if ((s = i2s_ASN1_INTEGER(NULL, aor->u.range->max)) == NULL) return 0; BIO_printf(out, "%s\n", s); OPENSSL_free(s); break; default: return 0; } } break; default: return 0; } return 1; } /* * i2r method for an ASIdentifier extension. */ static int i2r_ASIdentifiers(const X509V3_EXT_METHOD *method, void *ext, BIO *out, int indent) { ASIdentifiers *asid = ext; return (i2r_ASIdentifierChoice(out, asid->asnum, indent, "Autonomous System Numbers") && i2r_ASIdentifierChoice(out, asid->rdi, indent, "Routing Domain Identifiers")); } /* * Sort comparision function for a sequence of ASIdOrRange elements. */ static int ASIdOrRange_cmp(const ASIdOrRange * const *a_, const ASIdOrRange * const *b_) { const ASIdOrRange *a = *a_, *b = *b_; OPENSSL_assert((a->type == ASIdOrRange_id && a->u.id != NULL) || (a->type == ASIdOrRange_range && a->u.range != NULL && a->u.range->min != NULL && a->u.range->max != NULL)); OPENSSL_assert((b->type == ASIdOrRange_id && b->u.id != NULL) || (b->type == ASIdOrRange_range && b->u.range != NULL && b->u.range->min != NULL && b->u.range->max != NULL)); if (a->type == ASIdOrRange_id && b->type == ASIdOrRange_id) return ASN1_INTEGER_cmp(a->u.id, b->u.id); if (a->type == ASIdOrRange_range && b->type == ASIdOrRange_range) { int r = ASN1_INTEGER_cmp(a->u.range->min, b->u.range->min); return r != 0 ? r : ASN1_INTEGER_cmp(a->u.range->max, b->u.range->max); } if (a->type == ASIdOrRange_id) return ASN1_INTEGER_cmp(a->u.id, b->u.range->min); else return ASN1_INTEGER_cmp(a->u.range->min, b->u.id); } /* * Add an inherit element. */ int v3_asid_add_inherit(ASIdentifiers *asid, int which) { ASIdentifierChoice **choice; if (asid == NULL) return 0; switch (which) { case V3_ASID_ASNUM: choice = &asid->asnum; break; case V3_ASID_RDI: choice = &asid->rdi; break; default: return 0; } if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; OPENSSL_assert((*choice)->u.inherit == NULL); if (((*choice)->u.inherit = ASN1_NULL_new()) == NULL) return 0; (*choice)->type = ASIdentifierChoice_inherit; } return (*choice)->type == ASIdentifierChoice_inherit; } /* * Add an ID or range to an ASIdentifierChoice. */ int v3_asid_add_id_or_range(ASIdentifiers *asid, int which, ASN1_INTEGER *min, ASN1_INTEGER *max) { ASIdentifierChoice **choice; ASIdOrRange *aor; if (asid == NULL) return 0; switch (which) { case V3_ASID_ASNUM: choice = &asid->asnum; break; case V3_ASID_RDI: choice = &asid->rdi; break; default: return 0; } if (*choice != NULL && (*choice)->type == ASIdentifierChoice_inherit) return 0; if (*choice == NULL) { if ((*choice = ASIdentifierChoice_new()) == NULL) return 0; OPENSSL_assert((*choice)->u.asIdsOrRanges == NULL); (*choice)->u.asIdsOrRanges = sk_ASIdOrRange_new(ASIdOrRange_cmp); if ((*choice)->u.asIdsOrRanges == NULL) return 0; (*choice)->type = ASIdentifierChoice_asIdsOrRanges; } if ((aor = ASIdOrRange_new()) == NULL) return 0; if (max == NULL) { aor->type = ASIdOrRange_id; aor->u.id = min; } else { aor->type = ASIdOrRange_range; if ((aor->u.range = ASRange_new()) == NULL) goto err; ASN1_INTEGER_free(aor->u.range->min); aor->u.range->min = min; ASN1_INTEGER_free(aor->u.range->max); aor->u.range->max = max; } if (!(sk_ASIdOrRange_push((*choice)->u.asIdsOrRanges, aor))) goto err; return 1; err: ASIdOrRange_free(aor); return 0; } /* * Extract min and max values from an ASIdOrRange. */ static void extract_min_max(ASIdOrRange *aor, ASN1_INTEGER **min, ASN1_INTEGER **max) { OPENSSL_assert(aor != NULL && min != NULL && max != NULL); switch (aor->type) { case ASIdOrRange_id: *min = aor->u.id; *max = aor->u.id; return; case ASIdOrRange_range: *min = aor->u.range->min; *max = aor->u.range->max; return; } } /* * Check whether an ASIdentifierChoice is in canonical form. */ static int ASIdentifierChoice_is_canonical(ASIdentifierChoice *choice) { ASN1_INTEGER *a_max_plus_one = NULL; BIGNUM *bn = NULL; int i, ret = 0; /* * Empty element or inheritance is canonical. */ if (choice == NULL || choice->type == ASIdentifierChoice_inherit) return 1; /* * If not a list, or if empty list, it's broken. */ if (choice->type != ASIdentifierChoice_asIdsOrRanges || sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0) return 0; /* * It's a list, check it. */ for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1); ASN1_INTEGER *a_min, *a_max, *b_min, *b_max; extract_min_max(a, &a_min, &a_max); extract_min_max(b, &b_min, &b_max); /* * Punt misordered list, overlapping start, or inverted range. */ if (ASN1_INTEGER_cmp(a_min, b_min) >= 0 || ASN1_INTEGER_cmp(a_min, a_max) > 0 || ASN1_INTEGER_cmp(b_min, b_max) > 0) goto done; /* * Calculate a_max + 1 to check for adjacency. */ if ((bn == NULL && (bn = BN_new()) == NULL) || ASN1_INTEGER_to_BN(a_max, bn) == NULL || !BN_add_word(bn, 1) || (a_max_plus_one = BN_to_ASN1_INTEGER(bn, a_max_plus_one)) == NULL) { X509V3err(X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL, ERR_R_MALLOC_FAILURE); goto done; } /* * Punt if adjacent or overlapping. */ if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) >= 0) goto done; } /* * Check for inverted range. */ i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { extract_min_max(a, &a_min, &a_max); if (ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } ret = 1; done: ASN1_INTEGER_free(a_max_plus_one); BN_free(bn); return ret; } /* * Check whether an ASIdentifier extension is in canonical form. */ int v3_asid_is_canonical(ASIdentifiers *asid) { return (asid == NULL || (ASIdentifierChoice_is_canonical(asid->asnum) && ASIdentifierChoice_is_canonical(asid->rdi))); } /* * Whack an ASIdentifierChoice into canonical form. */ static int ASIdentifierChoice_canonize(ASIdentifierChoice *choice) { ASN1_INTEGER *a_max_plus_one = NULL; BIGNUM *bn = NULL; int i, ret = 0; /* * Nothing to do for empty element or inheritance. */ if (choice == NULL || choice->type == ASIdentifierChoice_inherit) return 1; /* * If not a list, or if empty list, it's broken. */ if (choice->type != ASIdentifierChoice_asIdsOrRanges || sk_ASIdOrRange_num(choice->u.asIdsOrRanges) == 0) { X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, X509V3_R_EXTENSION_VALUE_ERROR); return 0; } /* * We have a non-empty list. Sort it. */ sk_ASIdOrRange_sort(choice->u.asIdsOrRanges); /* * Now check for errors and suboptimal encoding, rejecting the * former and fixing the latter. */ for (i = 0; i < sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; i++) { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASIdOrRange *b = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i + 1); ASN1_INTEGER *a_min, *a_max, *b_min, *b_max; extract_min_max(a, &a_min, &a_max); extract_min_max(b, &b_min, &b_max); /* * Make sure we're properly sorted (paranoia). */ OPENSSL_assert(ASN1_INTEGER_cmp(a_min, b_min) <= 0); /* * Punt inverted ranges. */ if (ASN1_INTEGER_cmp(a_min, a_max) > 0 || ASN1_INTEGER_cmp(b_min, b_max) > 0) goto done; /* * Check for overlaps. */ if (ASN1_INTEGER_cmp(a_max, b_min) >= 0) { X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, X509V3_R_EXTENSION_VALUE_ERROR); goto done; } /* * Calculate a_max + 1 to check for adjacency. */ if ((bn == NULL && (bn = BN_new()) == NULL) || ASN1_INTEGER_to_BN(a_max, bn) == NULL || !BN_add_word(bn, 1) || (a_max_plus_one = BN_to_ASN1_INTEGER(bn, a_max_plus_one)) == NULL) { X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, ERR_R_MALLOC_FAILURE); goto done; } /* * If a and b are adjacent, merge them. */ if (ASN1_INTEGER_cmp(a_max_plus_one, b_min) == 0) { ASRange *r; switch (a->type) { case ASIdOrRange_id: if ((r = OPENSSL_malloc(sizeof(ASRange))) == NULL) { X509V3err(X509V3_F_ASIDENTIFIERCHOICE_CANONIZE, ERR_R_MALLOC_FAILURE); goto done; } r->min = a_min; r->max = b_max; a->type = ASIdOrRange_range; a->u.range = r; break; case ASIdOrRange_range: ASN1_INTEGER_free(a->u.range->max); a->u.range->max = b_max; break; } switch (b->type) { case ASIdOrRange_id: b->u.id = NULL; break; case ASIdOrRange_range: b->u.range->max = NULL; break; } ASIdOrRange_free(b); (void) sk_ASIdOrRange_delete(choice->u.asIdsOrRanges, i + 1); i--; continue; } } /* * Check for final inverted range. */ i = sk_ASIdOrRange_num(choice->u.asIdsOrRanges) - 1; { ASIdOrRange *a = sk_ASIdOrRange_value(choice->u.asIdsOrRanges, i); ASN1_INTEGER *a_min, *a_max; if (a != NULL && a->type == ASIdOrRange_range) { extract_min_max(a, &a_min, &a_max); if (ASN1_INTEGER_cmp(a_min, a_max) > 0) goto done; } } OPENSSL_assert(ASIdentifierChoice_is_canonical(choice)); /* Paranoia */ ret = 1; done: ASN1_INTEGER_free(a_max_plus_one); BN_free(bn); return ret; } /* * Whack an ASIdentifier extension into canonical form. */ int v3_asid_canonize(ASIdentifiers *asid) { return (asid == NULL || (ASIdentifierChoice_canonize(asid->asnum) && ASIdentifierChoice_canonize(asid->rdi))); } /* * v2i method for an ASIdentifier extension. */ static void *v2i_ASIdentifiers(const struct v3_ext_method *method, struct v3_ext_ctx *ctx, STACK_OF(CONF_VALUE) *values) { ASN1_INTEGER *min = NULL, *max = NULL; ASIdentifiers *asid = NULL; int i; if ((asid = ASIdentifiers_new()) == NULL) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE); return NULL; } for (i = 0; i < sk_CONF_VALUE_num(values); i++) { CONF_VALUE *val = sk_CONF_VALUE_value(values, i); int i1, i2, i3, is_range, which; /* * Figure out whether this is an AS or an RDI. */ if ( !name_cmp(val->name, "AS")) { which = V3_ASID_ASNUM; } else if (!name_cmp(val->name, "RDI")) { which = V3_ASID_RDI; } else { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_EXTENSION_NAME_ERROR); X509V3_conf_err(val); goto err; } /* * Handle inheritance. */ if (!strcmp(val->value, "inherit")) { if (v3_asid_add_inherit(asid, which)) continue; X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_INHERITANCE); X509V3_conf_err(val); goto err; } /* * Number, range, or mistake, pick it apart and figure out which. */ i1 = strspn(val->value, "0123456789"); if (val->value[i1] == '\0') { is_range = 0; } else { is_range = 1; i2 = i1 + strspn(val->value + i1, " \t"); if (val->value[i2] != '-') { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_ASNUMBER); X509V3_conf_err(val); goto err; } i2++; i2 = i2 + strspn(val->value + i2, " \t"); i3 = i2 + strspn(val->value + i2, "0123456789"); if (val->value[i3] != '\0') { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_INVALID_ASRANGE); X509V3_conf_err(val); goto err; } } /* * Syntax is ok, read and add it. */ if (!is_range) { if (!X509V3_get_value_int(val, &min)) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE); goto err; } } else { char *s = BUF_strdup(val->value); if (s == NULL) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE); goto err; } s[i1] = '\0'; min = s2i_ASN1_INTEGER(NULL, s); max = s2i_ASN1_INTEGER(NULL, s + i2); OPENSSL_free(s); if (min == NULL || max == NULL) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE); goto err; } if (ASN1_INTEGER_cmp(min, max) > 0) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, X509V3_R_EXTENSION_VALUE_ERROR); goto err; } } if (!v3_asid_add_id_or_range(asid, which, min, max)) { X509V3err(X509V3_F_V2I_ASIDENTIFIERS, ERR_R_MALLOC_FAILURE); goto err; } min = max = NULL; } /* * Canonize the result, then we're done. */ if (!v3_asid_canonize(asid)) goto err; return asid; err: ASIdentifiers_free(asid); ASN1_INTEGER_free(min); ASN1_INTEGER_free(max); return NULL; } /* * OpenSSL dispatch. */ const X509V3_EXT_METHOD v3_asid = { NID_sbgp_autonomousSysNum, /* nid */ 0, /* flags */ ASN1_ITEM_ref(ASIdentifiers), /* template */ 0, 0, 0, 0, /* old functions, ignored */ 0, /* i2s */ 0, /* s2i */ 0, /* i2v */ v2i_ASIdentifiers, /* v2i */ i2r_ASIdentifiers, /* i2r */ 0, /* r2i */ NULL /* extension-specific data */ }; /* * Figure out whether extension uses inheritance. */ int v3_asid_inherits(ASIdentifiers *asid) { return (asid != NULL && ((asid->asnum != NULL && asid->asnum->type == ASIdentifierChoice_inherit) || (asid->rdi != NULL && asid->rdi->type == ASIdentifierChoice_inherit))); } /* * Figure out whether parent contains child. */ static int asid_contains(ASIdOrRanges *parent, ASIdOrRanges *child) { ASN1_INTEGER *p_min, *p_max, *c_min, *c_max; int p, c; if (child == NULL || parent == child) return 1; if (parent == NULL) return 0; p = 0; for (c = 0; c < sk_ASIdOrRange_num(child); c++) { extract_min_max(sk_ASIdOrRange_value(child, c), &c_min, &c_max); for (;; p++) { if (p >= sk_ASIdOrRange_num(parent)) return 0; extract_min_max(sk_ASIdOrRange_value(parent, p), &p_min, &p_max); if (ASN1_INTEGER_cmp(p_max, c_max) < 0) continue; if (ASN1_INTEGER_cmp(p_min, c_min) > 0) return 0; break; } } return 1; } /* * Test whether a is a subet of b. */ int v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b) { return (a == NULL || a == b || (b != NULL && !v3_asid_inherits(a) && !v3_asid_inherits(b) && asid_contains(b->asnum->u.asIdsOrRanges, a->asnum->u.asIdsOrRanges) && asid_contains(b->rdi->u.asIdsOrRanges, a->rdi->u.asIdsOrRanges))); } /* * Validation error handling via callback. */ #define validation_err(_err_) \ do { \ if (ctx != NULL) { \ ctx->error = _err_; \ ctx->error_depth = i; \ ctx->current_cert = x; \ ret = ctx->verify_cb(0, ctx); \ } else { \ ret = 0; \ } \ if (!ret) \ goto done; \ } while (0) /* * Core code for RFC 3779 3.3 path validation. */ static int v3_asid_validate_path_internal(X509_STORE_CTX *ctx, STACK_OF(X509) *chain, ASIdentifiers *ext) { ASIdOrRanges *child_as = NULL, *child_rdi = NULL; int i, ret = 1, inherit_as = 0, inherit_rdi = 0; X509 *x; OPENSSL_assert(chain != NULL && sk_X509_num(chain) > 0); OPENSSL_assert(ctx != NULL || ext != NULL); OPENSSL_assert(ctx == NULL || ctx->verify_cb != NULL); /* * Figure out where to start. If we don't have an extension to * check, we're done. Otherwise, check canonical form and * set up for walking up the chain. */ if (ext != NULL) { i = -1; x = NULL; } else { i = 0; x = sk_X509_value(chain, i); OPENSSL_assert(x != NULL); if ((ext = x->rfc3779_asid) == NULL) goto done; } if (!v3_asid_is_canonical(ext)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (ext->asnum != NULL) { switch (ext->asnum->type) { case ASIdentifierChoice_inherit: inherit_as = 1; break; case ASIdentifierChoice_asIdsOrRanges: child_as = ext->asnum->u.asIdsOrRanges; break; } } if (ext->rdi != NULL) { switch (ext->rdi->type) { case ASIdentifierChoice_inherit: inherit_rdi = 1; break; case ASIdentifierChoice_asIdsOrRanges: child_rdi = ext->rdi->u.asIdsOrRanges; break; } } /* * Now walk up the chain. Extensions must be in canonical form, no * cert may list resources that its parent doesn't list. */ for (i++; i < sk_X509_num(chain); i++) { x = sk_X509_value(chain, i); OPENSSL_assert(x != NULL); if (x->rfc3779_asid == NULL) { if (child_as != NULL || child_rdi != NULL) validation_err(X509_V_ERR_UNNESTED_RESOURCE); continue; } if (!v3_asid_is_canonical(x->rfc3779_asid)) validation_err(X509_V_ERR_INVALID_EXTENSION); if (x->rfc3779_asid->asnum == NULL && child_as != NULL) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); child_as = NULL; inherit_as = 0; } if (x->rfc3779_asid->asnum != NULL && x->rfc3779_asid->asnum->type == ASIdentifierChoice_asIdsOrRanges) { if (inherit_as || asid_contains(x->rfc3779_asid->asnum->u.asIdsOrRanges, child_as)) { child_as = x->rfc3779_asid->asnum->u.asIdsOrRanges; inherit_as = 0; } else { validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } if (x->rfc3779_asid->rdi == NULL && child_rdi != NULL) { validation_err(X509_V_ERR_UNNESTED_RESOURCE); child_rdi = NULL; inherit_rdi = 0; } if (x->rfc3779_asid->rdi != NULL && x->rfc3779_asid->rdi->type == ASIdentifierChoice_asIdsOrRanges) { if (inherit_rdi || asid_contains(x->rfc3779_asid->rdi->u.asIdsOrRanges, child_rdi)) { child_rdi = x->rfc3779_asid->rdi->u.asIdsOrRanges; inherit_rdi = 0; } else { validation_err(X509_V_ERR_UNNESTED_RESOURCE); } } } /* * Trust anchor can't inherit. */ OPENSSL_assert(x != NULL); if (x->rfc3779_asid != NULL) { if (x->rfc3779_asid->asnum != NULL && x->rfc3779_asid->asnum->type == ASIdentifierChoice_inherit) validation_err(X509_V_ERR_UNNESTED_RESOURCE); if (x->rfc3779_asid->rdi != NULL && x->rfc3779_asid->rdi->type == ASIdentifierChoice_inherit) validation_err(X509_V_ERR_UNNESTED_RESOURCE); } done: return ret; } #undef validation_err /* * RFC 3779 3.3 path validation -- called from X509_verify_cert(). */ int v3_asid_validate_path(X509_STORE_CTX *ctx) { return v3_asid_validate_path_internal(ctx, ctx->chain, NULL); } /* * RFC 3779 3.3 path validation of an extension. * Test whether chain covers extension. */ int v3_asid_validate_resource_set(STACK_OF(X509) *chain, ASIdentifiers *ext, int allow_inheritance) { if (ext == NULL) return 1; if (chain == NULL || sk_X509_num(chain) == 0) return 0; if (!allow_inheritance && v3_asid_inherits(ext)) return 0; return v3_asid_validate_path_internal(NULL, chain, ext); } #endif /* OPENSSL_NO_RFC3779 */
mit
cnsuperx/Cocos2d-x-2.2.5
cocos2dx/platform/third_party/wp8/libcurl/lib/if2ip.c
108
5957
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ #include "curl_setup.h" #ifdef HAVE_NETINET_IN_H # include <netinet/in.h> #endif #ifdef HAVE_ARPA_INET_H # include <arpa/inet.h> #endif #ifdef HAVE_NET_IF_H # include <net/if.h> #endif #ifdef HAVE_SYS_IOCTL_H # include <sys/ioctl.h> #endif #ifdef HAVE_NETDB_H # include <netdb.h> #endif #ifdef HAVE_SYS_SOCKIO_H # include <sys/sockio.h> #endif #ifdef HAVE_IFADDRS_H # include <ifaddrs.h> #endif #ifdef HAVE_STROPTS_H # include <stropts.h> #endif #ifdef __VMS # include <inet.h> #endif #include "inet_ntop.h" #include "strequal.h" #include "if2ip.h" #define _MPRINTF_REPLACE /* use our functions only */ #include <curl/mprintf.h> #include "curl_memory.h" /* The last #include file should be: */ #include "memdebug.h" /* ------------------------------------------------------------------ */ #if defined(HAVE_GETIFADDRS) bool Curl_if_is_interface_name(const char *interf) { bool result = FALSE; struct ifaddrs *iface, *head; if(getifaddrs(&head) >= 0) { for(iface=head; iface != NULL; iface=iface->ifa_next) { if(curl_strequal(iface->ifa_name, interf)) { result = TRUE; break; } } freeifaddrs(head); } return result; } if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, const char *interf, char *buf, int buf_size) { struct ifaddrs *iface, *head; if2ip_result_t res = IF2IP_NOT_FOUND; #ifndef ENABLE_IPV6 (void) remote_scope; #endif if(getifaddrs(&head) >= 0) { for(iface=head; iface != NULL; iface=iface->ifa_next) { if(iface->ifa_addr != NULL) { if(iface->ifa_addr->sa_family == af) { if(curl_strequal(iface->ifa_name, interf)) { void *addr; char *ip; char scope[12]=""; char ipstr[64]; #ifdef ENABLE_IPV6 if(af == AF_INET6) { unsigned int scopeid = 0; addr = &((struct sockaddr_in6 *)iface->ifa_addr)->sin6_addr; #ifdef HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID /* Include the scope of this interface as part of the address */ scopeid = ((struct sockaddr_in6 *)iface->ifa_addr)->sin6_scope_id; #endif if(scopeid != remote_scope) { /* We are interested only in interface addresses whose scope ID matches the remote address we want to connect to: global (0) for global, link-local for link-local, etc... */ if(res == IF2IP_NOT_FOUND) res = IF2IP_AF_NOT_SUPPORTED; continue; } if(scopeid) snprintf(scope, sizeof(scope), "%%%u", scopeid); } else #endif addr = &((struct sockaddr_in *)iface->ifa_addr)->sin_addr; res = IF2IP_FOUND; ip = (char *) Curl_inet_ntop(af, addr, ipstr, sizeof(ipstr)); snprintf(buf, buf_size, "%s%s", ip, scope); break; } } else if((res == IF2IP_NOT_FOUND) && curl_strequal(iface->ifa_name, interf)) { res = IF2IP_AF_NOT_SUPPORTED; } } } freeifaddrs(head); } return res; } #elif defined(HAVE_IOCTL_SIOCGIFADDR) bool Curl_if_is_interface_name(const char *interf) { /* This is here just to support the old interfaces */ char buf[256]; return (Curl_if2ip(AF_INET, 0, interf, buf, sizeof(buf)) == IF2IP_NOT_FOUND) ? FALSE : TRUE; } if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, const char *interf, char *buf, int buf_size) { struct ifreq req; struct in_addr in; struct sockaddr_in *s; curl_socket_t dummy; size_t len; (void)remote_scope; if(!interf || (af != AF_INET)) return IF2IP_NOT_FOUND; len = strlen(interf); if(len >= sizeof(req.ifr_name)) return IF2IP_NOT_FOUND; dummy = socket(AF_INET, SOCK_STREAM, 0); if(CURL_SOCKET_BAD == dummy) return IF2IP_NOT_FOUND; memset(&req, 0, sizeof(req)); memcpy(req.ifr_name, interf, len+1); req.ifr_addr.sa_family = AF_INET; if(ioctl(dummy, SIOCGIFADDR, &req) < 0) { sclose(dummy); /* With SIOCGIFADDR, we cannot tell the difference between an interface that does not exist and an interface that has no address of the correct family. Assume the interface does not exist */ return IF2IP_NOT_FOUND; } s = (struct sockaddr_in *)&req.ifr_addr; memcpy(&in, &s->sin_addr, sizeof(in)); Curl_inet_ntop(s->sin_family, &in, buf, buf_size); sclose(dummy); return IF2IP_FOUND; } #else bool Curl_if_is_interface_name(const char *interf) { (void) interf; return FALSE; } if2ip_result_t Curl_if2ip(int af, unsigned int remote_scope, const char *interf, char *buf, int buf_size) { (void) af; (void) remote_scope; (void) interf; (void) buf; (void) buf_size; return IF2IP_NOT_FOUND; } #endif
mit
rhosilver/rhodes-1
lib/extensions/openssl.so/ext/sources/crypto/des/des_opts.c
879
15854
/* crypto/des/des_opts.c */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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 AUTHOR 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. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* define PART1, PART2, PART3 or PART4 to build only with a few of the options. * This is for machines with 64k code segment size restrictions. */ #if !defined(OPENSSL_SYS_MSDOS) && (!defined(OPENSSL_SYS_VMS) || defined(__DECC)) && !defined(OPENSSL_SYS_MACOSX) #define TIMES #endif #include <stdio.h> #ifndef OPENSSL_SYS_MSDOS #include <openssl/e_os2.h> #include OPENSSL_UNISTD #else #include <io.h> extern void exit(); #endif #ifndef OPENSSL_SYS_NETWARE #include <signal.h> #endif #ifndef _IRIX #include <time.h> #endif #ifdef TIMES #include <sys/types.h> #include <sys/times.h> #endif /* Depending on the VMS version, the tms structure is perhaps defined. The __TMS macro will show if it was. If it wasn't defined, we should undefine TIMES, since that tells the rest of the program how things should be handled. -- Richard Levitte */ #if defined(OPENSSL_SYS_VMS_DECC) && !defined(__TMS) #undef TIMES #endif #ifndef TIMES #include <sys/timeb.h> #endif #if defined(sun) || defined(__ultrix) #define _POSIX_SOURCE #include <limits.h> #include <sys/param.h> #endif #include <openssl/des.h> #include "spr.h" #define DES_DEFAULT_OPTIONS #if !defined(PART1) && !defined(PART2) && !defined(PART3) && !defined(PART4) #define PART1 #define PART2 #define PART3 #define PART4 #endif #ifdef PART1 #undef DES_UNROLL #undef DES_RISC1 #undef DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #define DES_encrypt1 des_encrypt_u4_cisc_idx #define DES_encrypt2 des_encrypt2_u4_cisc_idx #define DES_encrypt3 des_encrypt3_u4_cisc_idx #define DES_decrypt3 des_decrypt3_u4_cisc_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #undef DES_RISC1 #undef DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_cisc_idx #define DES_encrypt2 des_encrypt2_u16_cisc_idx #define DES_encrypt3 des_encrypt3_u16_cisc_idx #define DES_decrypt3 des_decrypt3_u16_cisc_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #undef DES_UNROLL #define DES_RISC1 #undef DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u4_risc1_idx #define DES_encrypt2 des_encrypt2_u4_risc1_idx #define DES_encrypt3 des_encrypt3_u4_risc1_idx #define DES_decrypt3 des_decrypt3_u4_risc1_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #endif #ifdef PART2 #undef DES_UNROLL #undef DES_RISC1 #define DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u4_risc2_idx #define DES_encrypt2 des_encrypt2_u4_risc2_idx #define DES_encrypt3 des_encrypt3_u4_risc2_idx #define DES_decrypt3 des_decrypt3_u4_risc2_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #define DES_RISC1 #undef DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_risc1_idx #define DES_encrypt2 des_encrypt2_u16_risc1_idx #define DES_encrypt3 des_encrypt3_u16_risc1_idx #define DES_decrypt3 des_decrypt3_u16_risc1_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #undef DES_RISC1 #define DES_RISC2 #undef DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_risc2_idx #define DES_encrypt2 des_encrypt2_u16_risc2_idx #define DES_encrypt3 des_encrypt3_u16_risc2_idx #define DES_decrypt3 des_decrypt3_u16_risc2_idx #undef HEADER_DES_LOCL_H #include "des_enc.c" #endif #ifdef PART3 #undef DES_UNROLL #undef DES_RISC1 #undef DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u4_cisc_ptr #define DES_encrypt2 des_encrypt2_u4_cisc_ptr #define DES_encrypt3 des_encrypt3_u4_cisc_ptr #define DES_decrypt3 des_decrypt3_u4_cisc_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #undef DES_RISC1 #undef DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_cisc_ptr #define DES_encrypt2 des_encrypt2_u16_cisc_ptr #define DES_encrypt3 des_encrypt3_u16_cisc_ptr #define DES_decrypt3 des_decrypt3_u16_cisc_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #undef DES_UNROLL #define DES_RISC1 #undef DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u4_risc1_ptr #define DES_encrypt2 des_encrypt2_u4_risc1_ptr #define DES_encrypt3 des_encrypt3_u4_risc1_ptr #define DES_decrypt3 des_decrypt3_u4_risc1_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #endif #ifdef PART4 #undef DES_UNROLL #undef DES_RISC1 #define DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u4_risc2_ptr #define DES_encrypt2 des_encrypt2_u4_risc2_ptr #define DES_encrypt3 des_encrypt3_u4_risc2_ptr #define DES_decrypt3 des_decrypt3_u4_risc2_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #define DES_RISC1 #undef DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_risc1_ptr #define DES_encrypt2 des_encrypt2_u16_risc1_ptr #define DES_encrypt3 des_encrypt3_u16_risc1_ptr #define DES_decrypt3 des_decrypt3_u16_risc1_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #define DES_UNROLL #undef DES_RISC1 #define DES_RISC2 #define DES_PTR #undef D_ENCRYPT #undef DES_encrypt1 #undef DES_encrypt2 #undef DES_encrypt3 #undef DES_decrypt3 #define DES_encrypt1 des_encrypt_u16_risc2_ptr #define DES_encrypt2 des_encrypt2_u16_risc2_ptr #define DES_encrypt3 des_encrypt3_u16_risc2_ptr #define DES_decrypt3 des_decrypt3_u16_risc2_ptr #undef HEADER_DES_LOCL_H #include "des_enc.c" #endif /* The following if from times(3) man page. It may need to be changed */ #ifndef HZ # ifndef CLK_TCK # ifndef _BSD_CLK_TCK_ /* FreeBSD fix */ # define HZ 100.0 # else /* _BSD_CLK_TCK_ */ # define HZ ((double)_BSD_CLK_TCK_) # endif # else /* CLK_TCK */ # define HZ ((double)CLK_TCK) # endif #endif #define BUFSIZE ((long)1024) long run=0; double Time_F(int s); #ifdef SIGALRM #if defined(__STDC__) || defined(sgi) #define SIGRETTYPE void #else #define SIGRETTYPE int #endif SIGRETTYPE sig_done(int sig); SIGRETTYPE sig_done(int sig) { signal(SIGALRM,sig_done); run=0; #ifdef LINT sig=sig; #endif } #endif #define START 0 #define STOP 1 double Time_F(int s) { double ret; #ifdef TIMES static struct tms tstart,tend; if (s == START) { times(&tstart); return(0); } else { times(&tend); ret=((double)(tend.tms_utime-tstart.tms_utime))/HZ; return((ret == 0.0)?1e-6:ret); } #else /* !times() */ static struct timeb tstart,tend; long i; if (s == START) { ftime(&tstart); return(0); } else { ftime(&tend); i=(long)tend.millitm-(long)tstart.millitm; ret=((double)(tend.time-tstart.time))+((double)i)/1000.0; return((ret == 0.0)?1e-6:ret); } #endif } #ifdef SIGALRM #define print_name(name) fprintf(stderr,"Doing %s's for 10 seconds\n",name); alarm(10); #else #define print_name(name) fprintf(stderr,"Doing %s %ld times\n",name,cb); #endif #define time_it(func,name,index) \ print_name(name); \ Time_F(START); \ for (count=0,run=1; COND(cb); count++) \ { \ unsigned long d[2]; \ func(d,&sch,DES_ENCRYPT); \ } \ tm[index]=Time_F(STOP); \ fprintf(stderr,"%ld %s's in %.2f second\n",count,name,tm[index]); \ tm[index]=((double)COUNT(cb))/tm[index]; #define print_it(name,index) \ fprintf(stderr,"%s bytes per sec = %12.2f (%5.1fuS)\n",name, \ tm[index]*8,1.0e6/tm[index]); int main(int argc, char **argv) { long count; static unsigned char buf[BUFSIZE]; static DES_cblock key ={0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0}; static DES_cblock key2={0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12}; static DES_cblock key3={0x56,0x78,0x9a,0xbc,0xde,0xf0,0x12,0x34}; DES_key_schedule sch,sch2,sch3; double d,tm[16],max=0; int rank[16]; char *str[16]; int max_idx=0,i,num=0,j; #ifndef SIGALARM long ca,cb,cc,cd,ce; #endif for (i=0; i<12; i++) { tm[i]=0.0; rank[i]=0; } #ifndef TIMES fprintf(stderr,"To get the most accurate results, try to run this\n"); fprintf(stderr,"program when this computer is idle.\n"); #endif DES_set_key_unchecked(&key,&sch); DES_set_key_unchecked(&key2,&sch2); DES_set_key_unchecked(&key3,&sch3); #ifndef SIGALRM fprintf(stderr,"First we calculate the approximate speed ...\n"); DES_set_key_unchecked(&key,sch); count=10; do { long i; unsigned long data[2]; count*=2; Time_F(START); for (i=count; i; i--) DES_encrypt1(data,&(sch[0]),DES_ENCRYPT); d=Time_F(STOP); } while (d < 3.0); ca=count; cb=count*3; cc=count*3*8/BUFSIZE+1; cd=count*8/BUFSIZE+1; ce=count/20+1; #define COND(d) (count != (d)) #define COUNT(d) (d) #else #define COND(c) (run) #define COUNT(d) (count) signal(SIGALRM,sig_done); alarm(10); #endif #ifdef PART1 time_it(des_encrypt_u4_cisc_idx, "des_encrypt_u4_cisc_idx ", 0); time_it(des_encrypt_u16_cisc_idx, "des_encrypt_u16_cisc_idx ", 1); time_it(des_encrypt_u4_risc1_idx, "des_encrypt_u4_risc1_idx ", 2); num+=3; #endif #ifdef PART2 time_it(des_encrypt_u16_risc1_idx,"des_encrypt_u16_risc1_idx", 3); time_it(des_encrypt_u4_risc2_idx, "des_encrypt_u4_risc2_idx ", 4); time_it(des_encrypt_u16_risc2_idx,"des_encrypt_u16_risc2_idx", 5); num+=3; #endif #ifdef PART3 time_it(des_encrypt_u4_cisc_ptr, "des_encrypt_u4_cisc_ptr ", 6); time_it(des_encrypt_u16_cisc_ptr, "des_encrypt_u16_cisc_ptr ", 7); time_it(des_encrypt_u4_risc1_ptr, "des_encrypt_u4_risc1_ptr ", 8); num+=3; #endif #ifdef PART4 time_it(des_encrypt_u16_risc1_ptr,"des_encrypt_u16_risc1_ptr", 9); time_it(des_encrypt_u4_risc2_ptr, "des_encrypt_u4_risc2_ptr ",10); time_it(des_encrypt_u16_risc2_ptr,"des_encrypt_u16_risc2_ptr",11); num+=3; #endif #ifdef PART1 str[0]=" 4 c i"; print_it("des_encrypt_u4_cisc_idx ",0); max=tm[0]; max_idx=0; str[1]="16 c i"; print_it("des_encrypt_u16_cisc_idx ",1); if (max < tm[1]) { max=tm[1]; max_idx=1; } str[2]=" 4 r1 i"; print_it("des_encrypt_u4_risc1_idx ",2); if (max < tm[2]) { max=tm[2]; max_idx=2; } #endif #ifdef PART2 str[3]="16 r1 i"; print_it("des_encrypt_u16_risc1_idx",3); if (max < tm[3]) { max=tm[3]; max_idx=3; } str[4]=" 4 r2 i"; print_it("des_encrypt_u4_risc2_idx ",4); if (max < tm[4]) { max=tm[4]; max_idx=4; } str[5]="16 r2 i"; print_it("des_encrypt_u16_risc2_idx",5); if (max < tm[5]) { max=tm[5]; max_idx=5; } #endif #ifdef PART3 str[6]=" 4 c p"; print_it("des_encrypt_u4_cisc_ptr ",6); if (max < tm[6]) { max=tm[6]; max_idx=6; } str[7]="16 c p"; print_it("des_encrypt_u16_cisc_ptr ",7); if (max < tm[7]) { max=tm[7]; max_idx=7; } str[8]=" 4 r1 p"; print_it("des_encrypt_u4_risc1_ptr ",8); if (max < tm[8]) { max=tm[8]; max_idx=8; } #endif #ifdef PART4 str[9]="16 r1 p"; print_it("des_encrypt_u16_risc1_ptr",9); if (max < tm[9]) { max=tm[9]; max_idx=9; } str[10]=" 4 r2 p"; print_it("des_encrypt_u4_risc2_ptr ",10); if (max < tm[10]) { max=tm[10]; max_idx=10; } str[11]="16 r2 p"; print_it("des_encrypt_u16_risc2_ptr",11); if (max < tm[11]) { max=tm[11]; max_idx=11; } #endif printf("options des ecb/s\n"); printf("%s %12.2f 100.0%%\n",str[max_idx],tm[max_idx]); d=tm[max_idx]; tm[max_idx]= -2.0; max= -1.0; for (;;) { for (i=0; i<12; i++) { if (max < tm[i]) { max=tm[i]; j=i; } } if (max < 0.0) break; printf("%s %12.2f %4.1f%%\n",str[j],tm[j],tm[j]/d*100.0); tm[j]= -2.0; max= -1.0; } switch (max_idx) { case 0: printf("-DDES_DEFAULT_OPTIONS\n"); break; case 1: printf("-DDES_UNROLL\n"); break; case 2: printf("-DDES_RISC1\n"); break; case 3: printf("-DDES_UNROLL -DDES_RISC1\n"); break; case 4: printf("-DDES_RISC2\n"); break; case 5: printf("-DDES_UNROLL -DDES_RISC2\n"); break; case 6: printf("-DDES_PTR\n"); break; case 7: printf("-DDES_UNROLL -DDES_PTR\n"); break; case 8: printf("-DDES_RISC1 -DDES_PTR\n"); break; case 9: printf("-DDES_UNROLL -DDES_RISC1 -DDES_PTR\n"); break; case 10: printf("-DDES_RISC2 -DDES_PTR\n"); break; case 11: printf("-DDES_UNROLL -DDES_RISC2 -DDES_PTR\n"); break; } exit(0); #if defined(LINT) || defined(OPENSSL_SYS_MSDOS) return(0); #endif }
mit
djtms/NetSCoin
src/qt/bitcoinamountfield.cpp
2164
4315
#include "bitcoinamountfield.h" #include "qvaluecombobox.h" #include "bitcoinunits.h" #include "guiconstants.h" #include <QLabel> #include <QLineEdit> #include <QRegExpValidator> #include <QHBoxLayout> #include <QKeyEvent> #include <QDoubleSpinBox> #include <QComboBox> #include <QApplication> #include <qmath.h> BitcoinAmountField::BitcoinAmountField(QWidget *parent): QWidget(parent), amount(0), currentUnit(-1) { amount = new QDoubleSpinBox(this); amount->setLocale(QLocale::c()); amount->setDecimals(8); amount->installEventFilter(this); amount->setMaximumWidth(170); amount->setSingleStep(0.001); QHBoxLayout *layout = new QHBoxLayout(this); layout->addWidget(amount); unit = new QValueComboBox(this); unit->setModel(new BitcoinUnits(this)); layout->addWidget(unit); layout->addStretch(1); layout->setContentsMargins(0,0,0,0); setLayout(layout); setFocusPolicy(Qt::TabFocus); setFocusProxy(amount); // If one if the widgets changes, the combined content changes as well connect(amount, SIGNAL(valueChanged(QString)), this, SIGNAL(textChanged())); connect(unit, SIGNAL(currentIndexChanged(int)), this, SLOT(unitChanged(int))); // Set default based on configuration unitChanged(unit->currentIndex()); } void BitcoinAmountField::setText(const QString &text) { if (text.isEmpty()) amount->clear(); else amount->setValue(text.toDouble()); } void BitcoinAmountField::clear() { amount->clear(); unit->setCurrentIndex(0); } bool BitcoinAmountField::validate() { bool valid = true; if (amount->value() == 0.0) valid = false; if (valid && !BitcoinUnits::parse(currentUnit, text(), 0)) valid = false; setValid(valid); return valid; } void BitcoinAmountField::setValid(bool valid) { if (valid) amount->setStyleSheet(""); else amount->setStyleSheet(STYLE_INVALID); } QString BitcoinAmountField::text() const { if (amount->text().isEmpty()) return QString(); else return amount->text(); } bool BitcoinAmountField::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::FocusIn) { // Clear invalid flag on focus setValid(true); } else if (event->type() == QEvent::KeyPress || event->type() == QEvent::KeyRelease) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if (keyEvent->key() == Qt::Key_Comma) { // Translate a comma into a period QKeyEvent periodKeyEvent(event->type(), Qt::Key_Period, keyEvent->modifiers(), ".", keyEvent->isAutoRepeat(), keyEvent->count()); qApp->sendEvent(object, &periodKeyEvent); return true; } } return QWidget::eventFilter(object, event); } QWidget *BitcoinAmountField::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, amount); return amount; } qint64 BitcoinAmountField::value(bool *valid_out) const { qint64 val_out = 0; bool valid = BitcoinUnits::parse(currentUnit, text(), &val_out); if(valid_out) { *valid_out = valid; } return val_out; } void BitcoinAmountField::setValue(qint64 value) { setText(BitcoinUnits::format(currentUnit, value)); } void BitcoinAmountField::unitChanged(int idx) { // Use description tooltip for current unit for the combobox unit->setToolTip(unit->itemData(idx, Qt::ToolTipRole).toString()); // Determine new unit ID int newUnit = unit->itemData(idx, BitcoinUnits::UnitRole).toInt(); // Parse current value and convert to new unit bool valid = false; qint64 currentValue = value(&valid); currentUnit = newUnit; // Set max length after retrieving the value, to prevent truncation amount->setDecimals(BitcoinUnits::decimals(currentUnit)); amount->setMaximum(qPow(10, BitcoinUnits::amountDigits(currentUnit)) - qPow(10, -amount->decimals())); if(valid) { // If value was valid, re-place it in the widget with the new unit setValue(currentValue); } else { // If current value is invalid, just clear field setText(""); } setValid(true); } void BitcoinAmountField::setDisplayUnit(int newUnit) { unit->setValue(newUnit); }
mit
nokat/bitbean
src/test/bignum_tests.cpp
1153
3786
#include <boost/test/unit_test.hpp> #include <limits> #include "bignum.h" #include "util.h" BOOST_AUTO_TEST_SUITE(bignum_tests) // Unfortunately there's no standard way of preventing a function from being // inlined, so we define a macro for it. // // You should use it like this: // NOINLINE void function() {...} #if defined(__GNUC__) // This also works and will be defined for any compiler implementing GCC // extensions, such as Clang and ICC. #define NOINLINE __attribute__((noinline)) #elif defined(_MSC_VER) #define NOINLINE __declspec(noinline) #else // We give out a warning because it impacts the correctness of one bignum test. #warning You should define NOINLINE for your compiler. #define NOINLINE #endif // For the following test case, it is useful to use additional tools. // // The simplest one to use is the compiler flag -ftrapv, which detects integer // overflows and similar errors. However, due to optimizations and compilers // taking advantage of undefined behavior sometimes it may not actually detect // anything. // // You can also use compiler-based stack protection to possibly detect possible // stack buffer overruns. // // For more accurate diagnostics, you can use an undefined arithmetic operation // detector such as the clang-based tool: // // "IOC: An Integer Overflow Checker for C/C++" // // Available at: http://embed.cs.utah.edu/ioc/ // // It might also be useful to use Google's AddressSanitizer to detect // stack buffer overruns, which valgrind can't currently detect. // Let's force this code not to be inlined, in order to actually // test a generic version of the function. This increases the chance // that -ftrapv will detect overflows. NOINLINE void mysetint64(CBigNum& num, int64 n) { num.setint64(n); } // For each number, we do 2 tests: one with inline code, then we reset the // value to 0, then the second one with a non-inlined function. BOOST_AUTO_TEST_CASE(bignum_setint64) { int64 n; { n = 0; CBigNum num(n); BOOST_CHECK(num.ToString() == "0"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "0"); } { n = 1; CBigNum num(n); BOOST_CHECK(num.ToString() == "1"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "1"); } { n = -1; CBigNum num(n); BOOST_CHECK(num.ToString() == "-1"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "-1"); } { n = 5; CBigNum num(n); BOOST_CHECK(num.ToString() == "5"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "5"); } { n = -5; CBigNum num(n); BOOST_CHECK(num.ToString() == "-5"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "-5"); } { n = std::numeric_limits<int64>::min(); CBigNum num(n); BOOST_CHECK(num.ToString() == "-9223372036854775808"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "-9223372036854775808"); } { n = std::numeric_limits<int64>::max(); CBigNum num(n); BOOST_CHECK(num.ToString() == "9223372036854775807"); num.setulong(0); BOOST_CHECK(num.ToString() == "0"); mysetint64(num, n); BOOST_CHECK(num.ToString() == "9223372036854775807"); } } BOOST_AUTO_TEST_SUITE_END()
mit
RYPTAR/SkullCode
SkullCode/cocos2d/external/flatbuffers/idl_parser.cpp
131
40881
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" namespace flatbuffers { const char *const kTypeNames[] = { #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD nullptr }; const char kTypeSizes[] = { #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ sizeof(CTYPE), FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; static void Error(const std::string &msg) { throw msg; } // Ensure that integer values we parse fit inside the declared integer type. static void CheckBitsFit(int64_t val, size_t bits) { auto mask = (1ll << bits) - 1; // Bits we allow to be used. if (bits < 64 && (val & ~mask) != 0 && // Positive or unsigned. (val | mask) != -1) // Negative. Error("constant does not fit in a " + NumToString(bits) + "-bit field"); } // atot: templated version of atoi/atof: convert a string to an instance of T. template<typename T> inline T atot(const char *s) { auto val = StringToInt(s); CheckBitsFit(val, sizeof(T) * 8); return (T)val; } template<> inline bool atot<bool>(const char *s) { return 0 != atoi(s); } template<> inline float atot<float>(const char *s) { return static_cast<float>(strtod(s, nullptr)); } template<> inline double atot<double>(const char *s) { return strtod(s, nullptr); } template<> inline Offset<void> atot<Offset<void>>(const char *s) { return Offset<void>(atoi(s)); } // Declare tokens we'll use. Single character tokens are represented by their // ascii character code (e.g. '{'), others above 256. #define FLATBUFFERS_GEN_TOKENS(TD) \ TD(Eof, 256, "end of file") \ TD(StringConstant, 257, "string constant") \ TD(IntegerConstant, 258, "integer constant") \ TD(FloatConstant, 259, "float constant") \ TD(Identifier, 260, "identifier") \ TD(Table, 261, "table") \ TD(Struct, 262, "struct") \ TD(Enum, 263, "enum") \ TD(Union, 264, "union") \ TD(NameSpace, 265, "namespace") \ TD(RootType, 266, "root_type") \ TD(FileIdentifier, 267, "file_identifier") \ TD(FileExtension, 268, "file_extension") \ TD(Include, 269, "include") #ifdef __GNUC__ __extension__ // Stop GCC complaining about trailing comma with -Wpendantic. #endif enum { #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) kToken ## NAME = VALUE, FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) #undef FLATBUFFERS_TOKEN #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ kToken ## ENUM, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; static std::string TokenToString(int t) { static const char *tokens[] = { #define FLATBUFFERS_TOKEN(NAME, VALUE, STRING) STRING, FLATBUFFERS_GEN_TOKENS(FLATBUFFERS_TOKEN) #undef FLATBUFFERS_TOKEN #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) IDLTYPE, FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD }; if (t < 256) { // A single ascii char token. std::string s; s.append(1, static_cast<char>(t)); return s; } else { // Other tokens. return tokens[t - 256]; } } // Parses exactly nibbles worth of hex digits into a number, or error. int64_t Parser::ParseHexNum(int nibbles) { for (int i = 0; i < nibbles; i++) if (!isxdigit(cursor_[i])) Error("escape code must be followed by " + NumToString(nibbles) + " hex digits"); auto val = StringToInt(cursor_, 16); cursor_ += nibbles; return val; } void Parser::Next() { doc_comment_.clear(); bool seen_newline = false; for (;;) { char c = *cursor_++; token_ = c; switch (c) { case '\0': cursor_--; token_ = kTokenEof; return; case ' ': case '\r': case '\t': break; case '\n': line_++; seen_newline = true; break; case '{': case '}': case '(': case ')': case '[': case ']': return; case ',': case ':': case ';': case '=': return; case '.': if(!isdigit(*cursor_)) return; Error("floating point constant can\'t start with \".\""); break; case '\"': attribute_ = ""; while (*cursor_ != '\"') { if (*cursor_ < ' ' && *cursor_ >= 0) Error("illegal character in string constant"); if (*cursor_ == '\\') { cursor_++; switch (*cursor_) { case 'n': attribute_ += '\n'; cursor_++; break; case 't': attribute_ += '\t'; cursor_++; break; case 'r': attribute_ += '\r'; cursor_++; break; case 'b': attribute_ += '\b'; cursor_++; break; case 'f': attribute_ += '\f'; cursor_++; break; case '\"': attribute_ += '\"'; cursor_++; break; case '\\': attribute_ += '\\'; cursor_++; break; case '/': attribute_ += '/'; cursor_++; break; case 'x': { // Not in the JSON standard cursor_++; attribute_ += static_cast<char>(ParseHexNum(2)); break; } case 'u': { cursor_++; ToUTF8(static_cast<int>(ParseHexNum(4)), &attribute_); break; } default: Error("unknown escape code in string constant"); break; } } else { // printable chars + UTF-8 bytes attribute_ += *cursor_++; } } cursor_++; token_ = kTokenStringConstant; return; case '/': if (*cursor_ == '/') { const char *start = ++cursor_; while (*cursor_ && *cursor_ != '\n') cursor_++; if (*start == '/') { // documentation comment if (!seen_newline) Error("a documentation comment should be on a line on its own"); doc_comment_.push_back(std::string(start + 1, cursor_)); } break; } // fall thru default: if (isalpha(static_cast<unsigned char>(c))) { // Collect all chars of an identifier: const char *start = cursor_ - 1; while (isalnum(static_cast<unsigned char>(*cursor_)) || *cursor_ == '_') cursor_++; attribute_.clear(); attribute_.append(start, cursor_); // First, see if it is a type keyword from the table of types: #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ if (attribute_ == IDLTYPE) { \ token_ = kToken ## ENUM; \ return; \ } FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD // If it's a boolean constant keyword, turn those into integers, // which simplifies our logic downstream. if (attribute_ == "true" || attribute_ == "false") { attribute_ = NumToString(attribute_ == "true"); token_ = kTokenIntegerConstant; return; } // Check for declaration keywords: if (attribute_ == "table") { token_ = kTokenTable; return; } if (attribute_ == "struct") { token_ = kTokenStruct; return; } if (attribute_ == "enum") { token_ = kTokenEnum; return; } if (attribute_ == "union") { token_ = kTokenUnion; return; } if (attribute_ == "namespace") { token_ = kTokenNameSpace; return; } if (attribute_ == "root_type") { token_ = kTokenRootType; return; } if (attribute_ == "include") { token_ = kTokenInclude; return; } if (attribute_ == "file_identifier") { token_ = kTokenFileIdentifier; return; } if (attribute_ == "file_extension") { token_ = kTokenFileExtension; return; } // If not, it is a user-defined identifier: token_ = kTokenIdentifier; return; } else if (isdigit(static_cast<unsigned char>(c)) || c == '-') { const char *start = cursor_ - 1; while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; if (*cursor_ == '.') { cursor_++; while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; // See if this float has a scientific notation suffix. Both JSON // and C++ (through strtod() we use) have the same format: if (*cursor_ == 'e' || *cursor_ == 'E') { cursor_++; if (*cursor_ == '+' || *cursor_ == '-') cursor_++; while (isdigit(static_cast<unsigned char>(*cursor_))) cursor_++; } token_ = kTokenFloatConstant; } else { token_ = kTokenIntegerConstant; } attribute_.clear(); attribute_.append(start, cursor_); return; } std::string ch; ch = c; if (c < ' ' || c > '~') ch = "code: " + NumToString(c); Error("illegal character: " + ch); break; } } } // Check if a given token is next, if so, consume it as well. bool Parser::IsNext(int t) { bool isnext = t == token_; if (isnext) Next(); return isnext; } // Expect a given token to be next, consume it, or error if not present. void Parser::Expect(int t) { if (t != token_) { Error("expecting: " + TokenToString(t) + " instead got: " + TokenToString(token_)); } Next(); } void Parser::ParseTypeIdent(Type &type) { auto enum_def = enums_.Lookup(attribute_); if (enum_def) { type = enum_def->underlying_type; if (enum_def->is_union) type.base_type = BASE_TYPE_UNION; } else { type.base_type = BASE_TYPE_STRUCT; type.struct_def = LookupCreateStruct(attribute_); } } // Parse any IDL type. void Parser::ParseType(Type &type) { if (token_ >= kTokenBOOL && token_ <= kTokenSTRING) { type.base_type = static_cast<BaseType>(token_ - kTokenNONE); } else { if (token_ == kTokenIdentifier) { ParseTypeIdent(type); } else if (token_ == '[') { Next(); Type subtype; ParseType(subtype); if (subtype.base_type == BASE_TYPE_VECTOR) { // We could support this, but it will complicate things, and it's // easier to work around with a struct around the inner vector. Error("nested vector types not supported (wrap in table first)."); } if (subtype.base_type == BASE_TYPE_UNION) { // We could support this if we stored a struct of 2 elements per // union element. Error("vector of union types not supported (wrap in table first)."); } type = Type(BASE_TYPE_VECTOR, subtype.struct_def, subtype.enum_def); type.element = subtype.base_type; Expect(']'); return; } else { Error("illegal type syntax"); } } Next(); } FieldDef &Parser::AddField(StructDef &struct_def, const std::string &name, const Type &type) { auto &field = *new FieldDef(); field.value.offset = FieldIndexToOffset(static_cast<voffset_t>(struct_def.fields.vec.size())); field.name = name; field.value.type = type; if (struct_def.fixed) { // statically compute the field offset auto size = InlineSize(type); auto alignment = InlineAlignment(type); // structs_ need to have a predictable format, so we need to align to // the largest scalar struct_def.minalign = std::max(struct_def.minalign, alignment); struct_def.PadLastField(alignment); field.value.offset = static_cast<voffset_t>(struct_def.bytesize); struct_def.bytesize += size; } if (struct_def.fields.Add(name, &field)) Error("field already exists: " + name); return field; } void Parser::ParseField(StructDef &struct_def) { std::string name = attribute_; std::vector<std::string> dc = doc_comment_; Expect(kTokenIdentifier); Expect(':'); Type type; ParseType(type); if (struct_def.fixed && !IsScalar(type.base_type) && !IsStruct(type)) Error("structs_ may contain only scalar or struct fields"); FieldDef *typefield = nullptr; if (type.base_type == BASE_TYPE_UNION) { // For union fields, add a second auto-generated field to hold the type, // with _type appended as the name. typefield = &AddField(struct_def, name + "_type", type.enum_def->underlying_type); } auto &field = AddField(struct_def, name, type); if (token_ == '=') { Next(); if (!IsScalar(type.base_type)) Error("default values currently only supported for scalars"); ParseSingleValue(field.value); } if (type.enum_def && IsScalar(type.base_type) && !struct_def.fixed && !type.enum_def->attributes.Lookup("bit_flags") && !type.enum_def->ReverseLookup(static_cast<int>( StringToInt(field.value.constant.c_str())))) Error("enum " + type.enum_def->name + " does not have a declaration for this field\'s default of " + field.value.constant); field.doc_comment = dc; ParseMetaData(field); field.deprecated = field.attributes.Lookup("deprecated") != nullptr; if (field.deprecated && struct_def.fixed) Error("can't deprecate fields in a struct"); field.required = field.attributes.Lookup("required") != nullptr; if (field.required && (struct_def.fixed || IsScalar(field.value.type.base_type))) Error("only non-scalar fields in tables may be 'required'"); auto nested = field.attributes.Lookup("nested_flatbuffer"); if (nested) { if (nested->type.base_type != BASE_TYPE_STRING) Error("nested_flatbuffer attribute must be a string (the root type)"); if (field.value.type.base_type != BASE_TYPE_VECTOR || field.value.type.element != BASE_TYPE_UCHAR) Error("nested_flatbuffer attribute may only apply to a vector of ubyte"); // This will cause an error if the root type of the nested flatbuffer // wasn't defined elsewhere. LookupCreateStruct(nested->constant); } if (typefield) { // If this field is a union, and it has a manually assigned id, // the automatically added type field should have an id as well (of N - 1). auto attr = field.attributes.Lookup("id"); if (attr) { auto id = atoi(attr->constant.c_str()); auto val = new Value(); val->type = attr->type; val->constant = NumToString(id - 1); typefield->attributes.Add("id", val); } } Expect(';'); } void Parser::ParseAnyValue(Value &val, FieldDef *field) { switch (val.type.base_type) { case BASE_TYPE_UNION: { assert(field); if (!field_stack_.size() || field_stack_.back().second->value.type.base_type != BASE_TYPE_UTYPE) Error("missing type field before this union value: " + field->name); auto enum_idx = atot<unsigned char>( field_stack_.back().first.constant.c_str()); auto enum_val = val.type.enum_def->ReverseLookup(enum_idx); if (!enum_val) Error("illegal type id for: " + field->name); val.constant = NumToString(ParseTable(*enum_val->struct_def)); break; } case BASE_TYPE_STRUCT: val.constant = NumToString(ParseTable(*val.type.struct_def)); break; case BASE_TYPE_STRING: { auto s = attribute_; Expect(kTokenStringConstant); val.constant = NumToString(builder_.CreateString(s).o); break; } case BASE_TYPE_VECTOR: { Expect('['); val.constant = NumToString(ParseVector(val.type.VectorType())); break; } default: ParseSingleValue(val); break; } } void Parser::SerializeStruct(const StructDef &struct_def, const Value &val) { auto off = atot<uoffset_t>(val.constant.c_str()); assert(struct_stack_.size() - off == struct_def.bytesize); builder_.Align(struct_def.minalign); builder_.PushBytes(&struct_stack_[off], struct_def.bytesize); struct_stack_.resize(struct_stack_.size() - struct_def.bytesize); builder_.AddStructOffset(val.offset, builder_.GetSize()); } uoffset_t Parser::ParseTable(const StructDef &struct_def) { Expect('{'); size_t fieldn = 0; if (!IsNext('}')) for (;;) { std::string name = attribute_; if (!IsNext(kTokenStringConstant)) Expect(kTokenIdentifier); auto field = struct_def.fields.Lookup(name); if (!field) Error("unknown field: " + name); if (struct_def.fixed && (fieldn >= struct_def.fields.vec.size() || struct_def.fields.vec[fieldn] != field)) { Error("struct field appearing out of order: " + name); } Expect(':'); Value val = field->value; ParseAnyValue(val, field); field_stack_.push_back(std::make_pair(val, field)); fieldn++; if (IsNext('}')) break; Expect(','); } for (auto it = field_stack_.rbegin(); it != field_stack_.rbegin() + fieldn; ++it) { if (it->second->used) Error("field set more than once: " + it->second->name); it->second->used = true; } for (auto it = field_stack_.rbegin(); it != field_stack_.rbegin() + fieldn; ++it) { it->second->used = false; } if (struct_def.fixed && fieldn != struct_def.fields.vec.size()) Error("incomplete struct initialization: " + struct_def.name); auto start = struct_def.fixed ? builder_.StartStruct(struct_def.minalign) : builder_.StartTable(); for (size_t size = struct_def.sortbysize ? sizeof(largest_scalar_t) : 1; size; size /= 2) { // Go through elements in reverse, since we're building the data backwards. for (auto it = field_stack_.rbegin(); it != field_stack_.rbegin() + fieldn; ++it) { auto &value = it->first; auto field = it->second; if (!struct_def.sortbysize || size == SizeOf(value.type.base_type)) { switch (value.type.base_type) { #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ builder_.Pad(field->padding); \ if (struct_def.fixed) { \ builder_.PushElement(atot<CTYPE>(value.constant.c_str())); \ } else { \ builder_.AddElement(value.offset, \ atot<CTYPE>( value.constant.c_str()), \ atot<CTYPE>(field->value.constant.c_str())); \ } \ break; FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD); #undef FLATBUFFERS_TD #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ builder_.Pad(field->padding); \ if (IsStruct(field->value.type)) { \ SerializeStruct(*field->value.type.struct_def, value); \ } else { \ builder_.AddOffset(value.offset, \ atot<CTYPE>(value.constant.c_str())); \ } \ break; FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD); #undef FLATBUFFERS_TD } } } } for (size_t i = 0; i < fieldn; i++) field_stack_.pop_back(); if (struct_def.fixed) { builder_.ClearOffsets(); builder_.EndStruct(); // Temporarily store this struct in a side buffer, since this data has to // be stored in-line later in the parent object. auto off = struct_stack_.size(); struct_stack_.insert(struct_stack_.end(), builder_.GetBufferPointer(), builder_.GetBufferPointer() + struct_def.bytesize); builder_.PopBytes(struct_def.bytesize); return static_cast<uoffset_t>(off); } else { return builder_.EndTable( start, static_cast<voffset_t>(struct_def.fields.vec.size())); } } uoffset_t Parser::ParseVector(const Type &type) { int count = 0; if (token_ != ']') for (;;) { Value val; val.type = type; ParseAnyValue(val, NULL); #ifdef WP8 field_stack_.push_back(std::make_pair(val, (FieldDef *)nullptr)); #else field_stack_.push_back(std::make_pair(val, nullptr)); #endif count++; if (token_ == ']') break; Expect(','); } Next(); builder_.StartVector(count * InlineSize(type) / InlineAlignment(type), InlineAlignment(type)); for (int i = 0; i < count; i++) { // start at the back, since we're building the data backwards. auto &val = field_stack_.back().first; switch (val.type.base_type) { #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, JTYPE, GTYPE, NTYPE) \ case BASE_TYPE_ ## ENUM: \ if (IsStruct(val.type)) SerializeStruct(*val.type.struct_def, val); \ else builder_.PushElement(atot<CTYPE>(val.constant.c_str())); \ break; FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD) #undef FLATBUFFERS_TD } field_stack_.pop_back(); } builder_.ClearOffsets(); return builder_.EndVector(count); } void Parser::ParseMetaData(Definition &def) { if (IsNext('(')) { for (;;) { auto name = attribute_; Expect(kTokenIdentifier); auto e = new Value(); def.attributes.Add(name, e); if (IsNext(':')) { ParseSingleValue(*e); } if (IsNext(')')) break; Expect(','); } } } bool Parser::TryTypedValue(int dtoken, bool check, Value &e, BaseType req) { bool match = dtoken == token_; if (match) { e.constant = attribute_; if (!check) { if (e.type.base_type == BASE_TYPE_NONE) { e.type.base_type = req; } else { Error(std::string("type mismatch: expecting: ") + kTypeNames[e.type.base_type] + ", found: " + kTypeNames[req]); } } Next(); } return match; } int64_t Parser::ParseIntegerFromString(Type &type) { int64_t result = 0; // Parse one or more enum identifiers, separated by spaces. const char *next = attribute_.c_str(); do { const char *divider = strchr(next, ' '); std::string word; if (divider) { word = std::string(next, divider); next = divider + strspn(divider, " "); } else { word = next; next += word.length(); } if (type.enum_def) { // The field has an enum type auto enum_val = type.enum_def->vals.Lookup(word); if (!enum_val) Error("unknown enum value: " + word + ", for enum: " + type.enum_def->name); result |= enum_val->value; } else { // No enum type, probably integral field. if (!IsInteger(type.base_type)) Error("not a valid value for this field: " + word); // TODO: could check if its a valid number constant here. const char *dot = strchr(word.c_str(), '.'); if (!dot) Error("enum values need to be qualified by an enum type"); std::string enum_def_str(word.c_str(), dot); std::string enum_val_str(dot + 1, word.c_str() + word.length()); auto enum_def = enums_.Lookup(enum_def_str); if (!enum_def) Error("unknown enum: " + enum_def_str); auto enum_val = enum_def->vals.Lookup(enum_val_str); if (!enum_val) Error("unknown enum value: " + enum_val_str); result |= enum_val->value; } } while(*next); return result; } void Parser::ParseSingleValue(Value &e) { // First check if this could be a string/identifier enum value: if (e.type.base_type != BASE_TYPE_STRING && e.type.base_type != BASE_TYPE_NONE && (token_ == kTokenIdentifier || token_ == kTokenStringConstant)) { e.constant = NumToString(ParseIntegerFromString(e.type)); Next(); } else if (TryTypedValue(kTokenIntegerConstant, IsScalar(e.type.base_type), e, BASE_TYPE_INT) || TryTypedValue(kTokenFloatConstant, IsFloat(e.type.base_type), e, BASE_TYPE_FLOAT) || TryTypedValue(kTokenStringConstant, e.type.base_type == BASE_TYPE_STRING, e, BASE_TYPE_STRING)) { } else { Error("cannot parse value starting with: " + TokenToString(token_)); } } StructDef *Parser::LookupCreateStruct(const std::string &name) { auto struct_def = structs_.Lookup(name); if (!struct_def) { // Rather than failing, we create a "pre declared" StructDef, due to // circular references, and check for errors at the end of parsing. struct_def = new StructDef(); structs_.Add(name, struct_def); struct_def->name = name; struct_def->predecl = true; struct_def->defined_namespace = namespaces_.back(); } return struct_def; } void Parser::ParseEnum(bool is_union) { std::vector<std::string> dc = doc_comment_; Next(); std::string name = attribute_; Expect(kTokenIdentifier); auto &enum_def = *new EnumDef(); enum_def.name = name; enum_def.doc_comment = dc; enum_def.is_union = is_union; enum_def.defined_namespace = namespaces_.back(); if (enums_.Add(name, &enum_def)) Error("enum already exists: " + name); if (is_union) { enum_def.underlying_type.base_type = BASE_TYPE_UTYPE; enum_def.underlying_type.enum_def = &enum_def; } else { if (proto_mode_) { enum_def.underlying_type.base_type = BASE_TYPE_SHORT; } else { // Give specialized error message, since this type spec used to // be optional in the first FlatBuffers release. if (!IsNext(':')) Error("must specify the underlying integer type for this" " enum (e.g. \': short\', which was the default)."); // Specify the integer type underlying this enum. ParseType(enum_def.underlying_type); if (!IsInteger(enum_def.underlying_type.base_type)) Error("underlying enum type must be integral"); } // Make this type refer back to the enum it was derived from. enum_def.underlying_type.enum_def = &enum_def; } ParseMetaData(enum_def); Expect('{'); if (is_union) enum_def.vals.Add("NONE", new EnumVal("NONE", 0)); do { std::string name = attribute_; std::vector<std::string> dc = doc_comment_; Expect(kTokenIdentifier); auto prevsize = enum_def.vals.vec.size(); auto value = enum_def.vals.vec.size() ? enum_def.vals.vec.back()->value + 1 : 0; auto &ev = *new EnumVal(name, value); if (enum_def.vals.Add(name, &ev)) Error("enum value already exists: " + name); ev.doc_comment = dc; if (is_union) { ev.struct_def = LookupCreateStruct(name); } if (IsNext('=')) { ev.value = atoi(attribute_.c_str()); Expect(kTokenIntegerConstant); if (prevsize && enum_def.vals.vec[prevsize - 1]->value >= ev.value) Error("enum values must be specified in ascending order"); } } while (IsNext(proto_mode_ ? ';' : ',') && token_ != '}'); Expect('}'); if (enum_def.attributes.Lookup("bit_flags")) { for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end(); ++it) { if (static_cast<size_t>((*it)->value) >= SizeOf(enum_def.underlying_type.base_type) * 8) Error("bit flag out of range of underlying integral type"); (*it)->value = 1LL << (*it)->value; } } } StructDef &Parser::StartStruct() { std::string name = attribute_; Expect(kTokenIdentifier); auto &struct_def = *LookupCreateStruct(name); if (!struct_def.predecl) Error("datatype already exists: " + name); struct_def.predecl = false; struct_def.name = name; // Move this struct to the back of the vector just in case it was predeclared, // to preserve declaration order. remove(structs_.vec.begin(), structs_.vec.end(), &struct_def); structs_.vec.back() = &struct_def; return struct_def; } void Parser::ParseDecl() { std::vector<std::string> dc = doc_comment_; bool fixed = IsNext(kTokenStruct); if (!fixed) Expect(kTokenTable); auto &struct_def = StartStruct(); struct_def.doc_comment = dc; struct_def.fixed = fixed; ParseMetaData(struct_def); struct_def.sortbysize = struct_def.attributes.Lookup("original_order") == nullptr && !fixed; Expect('{'); while (token_ != '}') ParseField(struct_def); auto force_align = struct_def.attributes.Lookup("force_align"); if (fixed && force_align) { auto align = static_cast<size_t>(atoi(force_align->constant.c_str())); if (force_align->type.base_type != BASE_TYPE_INT || align < struct_def.minalign || align > 256 || align & (align - 1)) Error("force_align must be a power of two integer ranging from the" "struct\'s natural alignment to 256"); struct_def.minalign = align; } struct_def.PadLastField(struct_def.minalign); // Check if this is a table that has manual id assignments auto &fields = struct_def.fields.vec; if (!struct_def.fixed && fields.size()) { size_t num_id_fields = 0; for (auto it = fields.begin(); it != fields.end(); ++it) { if ((*it)->attributes.Lookup("id")) num_id_fields++; } // If any fields have ids.. if (num_id_fields) { // Then all fields must have them. if (num_id_fields != fields.size()) Error("either all fields or no fields must have an 'id' attribute"); // Simply sort by id, then the fields are the same as if no ids had // been specified. std::sort(fields.begin(), fields.end(), [](const FieldDef *a, const FieldDef *b) -> bool { auto a_id = atoi(a->attributes.Lookup("id")->constant.c_str()); auto b_id = atoi(b->attributes.Lookup("id")->constant.c_str()); return a_id < b_id; }); // Verify we have a contiguous set, and reassign vtable offsets. for (int i = 0; i < static_cast<int>(fields.size()); i++) { if (i != atoi(fields[i]->attributes.Lookup("id")->constant.c_str())) Error("field id\'s must be consecutive from 0, id " + NumToString(i) + " missing or set twice"); fields[i]->value.offset = FieldIndexToOffset(static_cast<voffset_t>(i)); } } } // Check that no identifiers clash with auto generated fields. // This is not an ideal situation, but should occur very infrequently, // and allows us to keep using very readable names for type & length fields // without inducing compile errors. auto CheckClash = [&fields, &struct_def](const char *suffix, BaseType basetype) { auto len = strlen(suffix); for (auto it = fields.begin(); it != fields.end(); ++it) { auto &name = (*it)->name; if (name.length() > len && name.compare(name.length() - len, len, suffix) == 0 && (*it)->value.type.base_type != BASE_TYPE_UTYPE) { auto field = struct_def.fields.Lookup( name.substr(0, name.length() - len)); if (field && field->value.type.base_type == basetype) Error("Field " + name + " would clash with generated functions for field " + field->name); } } }; CheckClash("_type", BASE_TYPE_UNION); CheckClash("Type", BASE_TYPE_UNION); CheckClash("_length", BASE_TYPE_VECTOR); CheckClash("Length", BASE_TYPE_VECTOR); Expect('}'); } bool Parser::SetRootType(const char *name) { root_struct_def = structs_.Lookup(name); return root_struct_def != nullptr; } void Parser::MarkGenerated() { // Since the Parser object retains definitions across files, we must // ensure we only output code for definitions once, in the file they are first // declared. This function marks all existing definitions as having already // been generated. for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { (*it)->generated = true; } for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) { (*it)->generated = true; } } void Parser::ParseNamespace() { Next(); auto ns = new Namespace(); namespaces_.push_back(ns); for (;;) { ns->components.push_back(attribute_); Expect(kTokenIdentifier); if (!IsNext('.')) break; } Expect(';'); } // Best effort parsing of .proto declarations, with the aim to turn them // in the closest corresponding FlatBuffer equivalent. // We parse everything as identifiers instead of keywords, since we don't // want protobuf keywords to become invalid identifiers in FlatBuffers. void Parser::ParseProtoDecl() { if (attribute_ == "package") { // These are identical in syntax to FlatBuffer's namespace decl. ParseNamespace(); } else if (attribute_ == "message") { Next(); auto &struct_def = StartStruct(); Expect('{'); while (token_ != '}') { // Parse the qualifier. bool required = false; bool repeated = false; if (attribute_ == "optional") { // This is the default. } else if (attribute_ == "required") { required = true; } else if (attribute_ == "repeated") { repeated = true; } else { Error("expecting optional/required/repeated, got: " + attribute_); } Type type = ParseTypeFromProtoType(); // Repeated elements get mapped to a vector. if (repeated) { type.element = type.base_type; type.base_type = BASE_TYPE_VECTOR; } std::string name = attribute_; Expect(kTokenIdentifier); // Parse the field id. Since we're just translating schemas, not // any kind of binary compatibility, we can safely ignore these, and // assign our own. Expect('='); Expect(kTokenIntegerConstant); auto &field = AddField(struct_def, name, type); field.required = required; // See if there's a default specified. if (IsNext('[')) { if (attribute_ != "default") Error("\'default\' expected"); Next(); Expect('='); field.value.constant = attribute_; Next(); Expect(']'); } Expect(';'); } Next(); } else if (attribute_ == "enum") { // These are almost the same, just with different terminator: ParseEnum(false); } else if (attribute_ == "import") { Next(); included_files_[attribute_] = true; Expect(kTokenStringConstant); Expect(';'); } else if (attribute_ == "option") { // Skip these. Next(); Expect(kTokenIdentifier); Expect('='); Next(); // Any single token. Expect(';'); } else { Error("don\'t know how to parse .proto declaration starting with " + attribute_); } } // Parse a protobuf type, and map it to the corresponding FlatBuffer one. Type Parser::ParseTypeFromProtoType() { Expect(kTokenIdentifier); struct type_lookup { const char *proto_type; BaseType fb_type; }; static type_lookup lookup[] = { { "float", BASE_TYPE_FLOAT }, { "double", BASE_TYPE_DOUBLE }, { "int32", BASE_TYPE_INT }, { "int64", BASE_TYPE_LONG }, { "uint32", BASE_TYPE_UINT }, { "uint64", BASE_TYPE_ULONG }, { "sint32", BASE_TYPE_INT }, { "sint64", BASE_TYPE_LONG }, { "fixed32", BASE_TYPE_UINT }, { "fixed64", BASE_TYPE_ULONG }, { "sfixed32", BASE_TYPE_INT }, { "sfixed64", BASE_TYPE_LONG }, { "bool", BASE_TYPE_BOOL }, { "string", BASE_TYPE_STRING }, { "bytes", BASE_TYPE_STRING }, { nullptr, BASE_TYPE_NONE } }; Type type; for (auto tl = lookup; tl->proto_type; tl++) { if (attribute_ == tl->proto_type) { type.base_type = tl->fb_type; Next(); return type; } } ParseTypeIdent(type); Expect(kTokenIdentifier); return type; } bool Parser::Parse(const char *source, const char **include_paths, const char *source_filename) { if (source_filename) included_files_[source_filename] = true; source_ = cursor_ = source; line_ = 1; error_.clear(); builder_.Clear(); try { Next(); // Includes must come first: while (IsNext(kTokenInclude)) { auto name = attribute_; Expect(kTokenStringConstant); if (included_files_.find(name) == included_files_.end()) { // We found an include file that we have not parsed yet. // Load it and parse it. std::string contents; if (!include_paths) { const char *current_directory[] = { "", nullptr }; include_paths = current_directory; } for (auto paths = include_paths; paths && *paths; paths++) { auto filepath = flatbuffers::ConCatPathFileName(*paths, name); if(LoadFile(filepath.c_str(), true, &contents)) break; } if (contents.empty()) Error("unable to load include file: " + name); included_files_[name] = true; if (!Parse(contents.c_str(), include_paths)) { // Any errors, we're done. return false; } // We do not want to output code for any included files: MarkGenerated(); // This is the easiest way to continue this file after an include: // instead of saving and restoring all the state, we simply start the // file anew. This will cause it to encounter the same include statement // again, but this time it will skip it, because it was entered into // included_files_. // This is recursive, but only go as deep as the number of include // statements. return Parse(source, include_paths, source_filename); } Expect(';'); } // Now parse all other kinds of declarations: while (token_ != kTokenEof) { if (proto_mode_) { ParseProtoDecl(); } else if (token_ == kTokenNameSpace) { ParseNamespace(); } else if (token_ == '{') { if (!root_struct_def) Error("no root type set to parse json with"); if (builder_.GetSize()) { Error("cannot have more than one json object in a file"); } builder_.Finish(Offset<Table>(ParseTable(*root_struct_def)), file_identifier_.length() ? file_identifier_.c_str() : nullptr); } else if (token_ == kTokenEnum) { ParseEnum(false); } else if (token_ == kTokenUnion) { ParseEnum(true); } else if (token_ == kTokenRootType) { Next(); auto root_type = attribute_; Expect(kTokenIdentifier); if (!SetRootType(root_type.c_str())) Error("unknown root type: " + root_type); if (root_struct_def->fixed) Error("root type must be a table"); Expect(';'); } else if (token_ == kTokenFileIdentifier) { Next(); file_identifier_ = attribute_; Expect(kTokenStringConstant); if (file_identifier_.length() != FlatBufferBuilder::kFileIdentifierLength) Error("file_identifier must be exactly " + NumToString(FlatBufferBuilder::kFileIdentifierLength) + " characters"); Expect(';'); } else if (token_ == kTokenFileExtension) { Next(); file_extension_ = attribute_; Expect(kTokenStringConstant); Expect(';'); } else if(token_ == kTokenInclude) { Error("includes must come before declarations"); } else { ParseDecl(); } } for (auto it = structs_.vec.begin(); it != structs_.vec.end(); ++it) { if ((*it)->predecl) Error("type referenced but not defined: " + (*it)->name); } for (auto it = enums_.vec.begin(); it != enums_.vec.end(); ++it) { auto &enum_def = **it; if (enum_def.is_union) { for (auto it = enum_def.vals.vec.begin(); it != enum_def.vals.vec.end(); ++it) { auto &val = **it; if (val.struct_def && val.struct_def->fixed) Error("only tables can be union elements: " + val.name); } } } } catch (const std::string &msg) { error_ = source_filename ? AbsolutePath(source_filename) : ""; #ifdef _WIN32 error_ += "(" + NumToString(line_) + ")"; // MSVC alike #else if (source_filename) error_ += ":"; error_ += NumToString(line_) + ":0"; // gcc alike #endif error_ += ": error: " + msg; return false; } assert(!struct_stack_.size()); return true; } } // namespace flatbuffers
mit
huoxudong125/poedit
deps/icu4c/source/samples/translit/answers/unaccent.cpp
388
1466
/******************************************************************** * COPYRIGHT: * Copyright (c) 1999-2002, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ #include "unaccent.h" /** * Constructor */ UnaccentTransliterator::UnaccentTransliterator() : normalizer("", Normalizer::DECOMP), Transliterator("Unaccent", 0) { } /** * Destructor */ UnaccentTransliterator::~UnaccentTransliterator() { } /** * Remove accents from a character using Normalizer. */ UChar UnaccentTransliterator::unaccent(UChar c) const { UnicodeString str(c); UErrorCode status = U_ZERO_ERROR; UnaccentTransliterator* t = (UnaccentTransliterator*)this; t->normalizer.setText(str, status); if (U_FAILURE(status)) { return c; } return (UChar) t->normalizer.next(); } /** * Implement Transliterator API */ void UnaccentTransliterator::handleTransliterate(Replaceable& text, UTransPosition& index, UBool incremental) const { UnicodeString str("a"); while (index.start < index.limit) { UChar c = text.charAt(index.start); UChar d = unaccent(c); if (c != d) { str.setCharAt(0, d); text.handleReplaceBetween(index.start, index.start+1, str); } index.start++; } }
mit
Raag079/self-driving-car
Term02-SensorFusion-Localization-and-Control/MPC-Quizzes/polyfit/src/Eigen-3.3/blas/f2c/dsbmv.c
133
10188
/* dsbmv.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "datatypes.h" /* Subroutine */ int dsbmv_(char *uplo, integer *n, integer *k, doublereal * alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy, ftnlen uplo_len) { /* System generated locals */ integer a_dim1, a_offset, i__1, i__2, i__3, i__4; /* Local variables */ integer i__, j, l, ix, iy, jx, jy, kx, ky, info; doublereal temp1, temp2; extern logical lsame_(char *, char *, ftnlen, ftnlen); integer kplus1; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* Purpose */ /* ======= */ /* DSBMV performs the matrix-vector operation */ /* y := alpha*A*x + beta*y, */ /* where alpha and beta are scalars, x and y are n element vectors and */ /* A is an n by n symmetric band matrix, with k super-diagonals. */ /* Arguments */ /* ========== */ /* UPLO - CHARACTER*1. */ /* On entry, UPLO specifies whether the upper or lower */ /* triangular part of the band matrix A is being supplied as */ /* follows: */ /* UPLO = 'U' or 'u' The upper triangular part of A is */ /* being supplied. */ /* UPLO = 'L' or 'l' The lower triangular part of A is */ /* being supplied. */ /* Unchanged on exit. */ /* N - INTEGER. */ /* On entry, N specifies the order of the matrix A. */ /* N must be at least zero. */ /* Unchanged on exit. */ /* K - INTEGER. */ /* On entry, K specifies the number of super-diagonals of the */ /* matrix A. K must satisfy 0 .le. K. */ /* Unchanged on exit. */ /* ALPHA - DOUBLE PRECISION. */ /* On entry, ALPHA specifies the scalar alpha. */ /* Unchanged on exit. */ /* A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). */ /* Before entry with UPLO = 'U' or 'u', the leading ( k + 1 ) */ /* by n part of the array A must contain the upper triangular */ /* band part of the symmetric matrix, supplied column by */ /* column, with the leading diagonal of the matrix in row */ /* ( k + 1 ) of the array, the first super-diagonal starting at */ /* position 2 in row k, and so on. The top left k by k triangle */ /* of the array A is not referenced. */ /* The following program segment will transfer the upper */ /* triangular part of a symmetric band matrix from conventional */ /* full matrix storage to band storage: */ /* DO 20, J = 1, N */ /* M = K + 1 - J */ /* DO 10, I = MAX( 1, J - K ), J */ /* A( M + I, J ) = matrix( I, J ) */ /* 10 CONTINUE */ /* 20 CONTINUE */ /* Before entry with UPLO = 'L' or 'l', the leading ( k + 1 ) */ /* by n part of the array A must contain the lower triangular */ /* band part of the symmetric matrix, supplied column by */ /* column, with the leading diagonal of the matrix in row 1 of */ /* the array, the first sub-diagonal starting at position 1 in */ /* row 2, and so on. The bottom right k by k triangle of the */ /* array A is not referenced. */ /* The following program segment will transfer the lower */ /* triangular part of a symmetric band matrix from conventional */ /* full matrix storage to band storage: */ /* DO 20, J = 1, N */ /* M = 1 - J */ /* DO 10, I = J, MIN( N, J + K ) */ /* A( M + I, J ) = matrix( I, J ) */ /* 10 CONTINUE */ /* 20 CONTINUE */ /* Unchanged on exit. */ /* LDA - INTEGER. */ /* On entry, LDA specifies the first dimension of A as declared */ /* in the calling (sub) program. LDA must be at least */ /* ( k + 1 ). */ /* Unchanged on exit. */ /* X - DOUBLE PRECISION array of DIMENSION at least */ /* ( 1 + ( n - 1 )*abs( INCX ) ). */ /* Before entry, the incremented array X must contain the */ /* vector x. */ /* Unchanged on exit. */ /* INCX - INTEGER. */ /* On entry, INCX specifies the increment for the elements of */ /* X. INCX must not be zero. */ /* Unchanged on exit. */ /* BETA - DOUBLE PRECISION. */ /* On entry, BETA specifies the scalar beta. */ /* Unchanged on exit. */ /* Y - DOUBLE PRECISION array of DIMENSION at least */ /* ( 1 + ( n - 1 )*abs( INCY ) ). */ /* Before entry, the incremented array Y must contain the */ /* vector y. On exit, Y is overwritten by the updated vector y. */ /* INCY - INTEGER. */ /* On entry, INCY specifies the increment for the elements of */ /* Y. INCY must not be zero. */ /* Unchanged on exit. */ /* Level 2 Blas routine. */ /* -- Written on 22-October-1986. */ /* Jack Dongarra, Argonne National Lab. */ /* Jeremy Du Croz, Nag Central Office. */ /* Sven Hammarling, Nag Central Office. */ /* Richard Hanson, Sandia National Labs. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* Test the input parameters. */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1; a -= a_offset; --x; --y; /* Function Body */ info = 0; if (! lsame_(uplo, "U", (ftnlen)1, (ftnlen)1) && ! lsame_(uplo, "L", ( ftnlen)1, (ftnlen)1)) { info = 1; } else if (*n < 0) { info = 2; } else if (*k < 0) { info = 3; } else if (*lda < *k + 1) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { xerbla_("DSBMV ", &info, (ftnlen)6); return 0; } /* Quick return if possible. */ if (*n == 0 || (*alpha == 0. && *beta == 1.)) { return 0; } /* Set up the start points in X and Y. */ if (*incx > 0) { kx = 1; } else { kx = 1 - (*n - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (*n - 1) * *incy; } /* Start the operations. In this version the elements of the array A */ /* are accessed sequentially with one pass through A. */ /* First form y := beta*y. */ if (*beta != 1.) { if (*incy == 1) { if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = 0.; /* L10: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[i__] = *beta * y[i__]; /* L20: */ } } } else { iy = ky; if (*beta == 0.) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = 0.; iy += *incy; /* L30: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { y[iy] = *beta * y[iy]; iy += *incy; /* L40: */ } } } } if (*alpha == 0.) { return 0; } if (lsame_(uplo, "U", (ftnlen)1, (ftnlen)1)) { /* Form y when upper triangle of A is stored. */ kplus1 = *k + 1; if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; l = kplus1 - j; /* Computing MAX */ i__2 = 1, i__3 = j - *k; i__4 = j - 1; for (i__ = max(i__2,i__3); i__ <= i__4; ++i__) { y[i__] += temp1 * a[l + i__ + j * a_dim1]; temp2 += a[l + i__ + j * a_dim1] * x[i__]; /* L50: */ } y[j] = y[j] + temp1 * a[kplus1 + j * a_dim1] + *alpha * temp2; /* L60: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; ix = kx; iy = ky; l = kplus1 - j; /* Computing MAX */ i__4 = 1, i__2 = j - *k; i__3 = j - 1; for (i__ = max(i__4,i__2); i__ <= i__3; ++i__) { y[iy] += temp1 * a[l + i__ + j * a_dim1]; temp2 += a[l + i__ + j * a_dim1] * x[ix]; ix += *incx; iy += *incy; /* L70: */ } y[jy] = y[jy] + temp1 * a[kplus1 + j * a_dim1] + *alpha * temp2; jx += *incx; jy += *incy; if (j > *k) { kx += *incx; ky += *incy; } /* L80: */ } } } else { /* Form y when lower triangle of A is stored. */ if (*incx == 1 && *incy == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[j]; temp2 = 0.; y[j] += temp1 * a[j * a_dim1 + 1]; l = 1 - j; /* Computing MIN */ i__4 = *n, i__2 = j + *k; i__3 = min(i__4,i__2); for (i__ = j + 1; i__ <= i__3; ++i__) { y[i__] += temp1 * a[l + i__ + j * a_dim1]; temp2 += a[l + i__ + j * a_dim1] * x[i__]; /* L90: */ } y[j] += *alpha * temp2; /* L100: */ } } else { jx = kx; jy = ky; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp1 = *alpha * x[jx]; temp2 = 0.; y[jy] += temp1 * a[j * a_dim1 + 1]; l = 1 - j; ix = jx; iy = jy; /* Computing MIN */ i__4 = *n, i__2 = j + *k; i__3 = min(i__4,i__2); for (i__ = j + 1; i__ <= i__3; ++i__) { ix += *incx; iy += *incy; y[iy] += temp1 * a[l + i__ + j * a_dim1]; temp2 += a[l + i__ + j * a_dim1] * x[ix]; /* L110: */ } y[jy] += *alpha * temp2; jx += *incx; jy += *incy; /* L120: */ } } } return 0; /* End of DSBMV . */ } /* dsbmv_ */
mit
KristFoundation/Programs
luaide/sound/soc/soc-topology.c
134
49184
/* * soc-topology.c -- ALSA SoC Topology * * Copyright (C) 2012 Texas Instruments Inc. * Copyright (C) 2015 Intel Corporation. * * Authors: Liam Girdwood <liam.r.girdwood@linux.intel.com> * K, Mythri P <mythri.p.k@intel.com> * Prusty, Subhransu S <subhransu.s.prusty@intel.com> * B, Jayachandran <jayachandran.b@intel.com> * Abdullah, Omair M <omair.m.abdullah@intel.com> * Jin, Yao <yao.jin@intel.com> * Lin, Mengdong <mengdong.lin@intel.com> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * Add support to read audio firmware topology alongside firmware text. The * topology data can contain kcontrols, DAPM graphs, widgets, DAIs, DAI links, * equalizers, firmware, coefficients etc. * * This file only manages the core ALSA and ASoC components, all other bespoke * firmware topology data is passed to component drivers for bespoke handling. */ #include <linux/kernel.h> #include <linux/export.h> #include <linux/list.h> #include <linux/firmware.h> #include <linux/slab.h> #include <sound/soc.h> #include <sound/soc-dapm.h> #include <sound/soc-topology.h> #include <sound/tlv.h> /* * We make several passes over the data (since it wont necessarily be ordered) * and process objects in the following order. This guarantees the component * drivers will be ready with any vendor data before the mixers and DAPM objects * are loaded (that may make use of the vendor data). */ #define SOC_TPLG_PASS_MANIFEST 0 #define SOC_TPLG_PASS_VENDOR 1 #define SOC_TPLG_PASS_MIXER 2 #define SOC_TPLG_PASS_WIDGET 3 #define SOC_TPLG_PASS_PCM_DAI 4 #define SOC_TPLG_PASS_GRAPH 5 #define SOC_TPLG_PASS_PINS 6 #define SOC_TPLG_PASS_START SOC_TPLG_PASS_MANIFEST #define SOC_TPLG_PASS_END SOC_TPLG_PASS_PINS struct soc_tplg { const struct firmware *fw; /* runtime FW parsing */ const u8 *pos; /* read postion */ const u8 *hdr_pos; /* header position */ unsigned int pass; /* pass number */ /* component caller */ struct device *dev; struct snd_soc_component *comp; u32 index; /* current block index */ u32 req_index; /* required index, only loaded/free matching blocks */ /* vendor specific kcontrol operations */ const struct snd_soc_tplg_kcontrol_ops *io_ops; int io_ops_count; /* vendor specific bytes ext handlers, for TLV bytes controls */ const struct snd_soc_tplg_bytes_ext_ops *bytes_ext_ops; int bytes_ext_ops_count; /* optional fw loading callbacks to component drivers */ struct snd_soc_tplg_ops *ops; }; static int soc_tplg_process_headers(struct soc_tplg *tplg); static void soc_tplg_complete(struct soc_tplg *tplg); struct snd_soc_dapm_widget * snd_soc_dapm_new_control_unlocked(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget); struct snd_soc_dapm_widget * snd_soc_dapm_new_control(struct snd_soc_dapm_context *dapm, const struct snd_soc_dapm_widget *widget); /* check we dont overflow the data for this control chunk */ static int soc_tplg_check_elem_count(struct soc_tplg *tplg, size_t elem_size, unsigned int count, size_t bytes, const char *elem_type) { const u8 *end = tplg->pos + elem_size * count; if (end > tplg->fw->data + tplg->fw->size) { dev_err(tplg->dev, "ASoC: %s overflow end of data\n", elem_type); return -EINVAL; } /* check there is enough room in chunk for control. extra bytes at the end of control are for vendor data here */ if (elem_size * count > bytes) { dev_err(tplg->dev, "ASoC: %s count %d of size %zu is bigger than chunk %zu\n", elem_type, count, elem_size, bytes); return -EINVAL; } return 0; } static inline int soc_tplg_is_eof(struct soc_tplg *tplg) { const u8 *end = tplg->hdr_pos; if (end >= tplg->fw->data + tplg->fw->size) return 1; return 0; } static inline unsigned long soc_tplg_get_hdr_offset(struct soc_tplg *tplg) { return (unsigned long)(tplg->hdr_pos - tplg->fw->data); } static inline unsigned long soc_tplg_get_offset(struct soc_tplg *tplg) { return (unsigned long)(tplg->pos - tplg->fw->data); } /* mapping of Kcontrol types and associated operations. */ static const struct snd_soc_tplg_kcontrol_ops io_ops[] = { {SND_SOC_TPLG_CTL_VOLSW, snd_soc_get_volsw, snd_soc_put_volsw, snd_soc_info_volsw}, {SND_SOC_TPLG_CTL_VOLSW_SX, snd_soc_get_volsw_sx, snd_soc_put_volsw_sx, NULL}, {SND_SOC_TPLG_CTL_ENUM, snd_soc_get_enum_double, snd_soc_put_enum_double, snd_soc_info_enum_double}, {SND_SOC_TPLG_CTL_ENUM_VALUE, snd_soc_get_enum_double, snd_soc_put_enum_double, NULL}, {SND_SOC_TPLG_CTL_BYTES, snd_soc_bytes_get, snd_soc_bytes_put, snd_soc_bytes_info}, {SND_SOC_TPLG_CTL_RANGE, snd_soc_get_volsw_range, snd_soc_put_volsw_range, snd_soc_info_volsw_range}, {SND_SOC_TPLG_CTL_VOLSW_XR_SX, snd_soc_get_xr_sx, snd_soc_put_xr_sx, snd_soc_info_xr_sx}, {SND_SOC_TPLG_CTL_STROBE, snd_soc_get_strobe, snd_soc_put_strobe, NULL}, {SND_SOC_TPLG_DAPM_CTL_VOLSW, snd_soc_dapm_get_volsw, snd_soc_dapm_put_volsw, snd_soc_info_volsw}, {SND_SOC_TPLG_DAPM_CTL_ENUM_DOUBLE, snd_soc_dapm_get_enum_double, snd_soc_dapm_put_enum_double, snd_soc_info_enum_double}, {SND_SOC_TPLG_DAPM_CTL_ENUM_VIRT, snd_soc_dapm_get_enum_double, snd_soc_dapm_put_enum_double, NULL}, {SND_SOC_TPLG_DAPM_CTL_ENUM_VALUE, snd_soc_dapm_get_enum_double, snd_soc_dapm_put_enum_double, NULL}, {SND_SOC_TPLG_DAPM_CTL_PIN, snd_soc_dapm_get_pin_switch, snd_soc_dapm_put_pin_switch, snd_soc_dapm_info_pin_switch}, }; struct soc_tplg_map { int uid; int kid; }; /* mapping of widget types from UAPI IDs to kernel IDs */ static const struct soc_tplg_map dapm_map[] = { {SND_SOC_TPLG_DAPM_INPUT, snd_soc_dapm_input}, {SND_SOC_TPLG_DAPM_OUTPUT, snd_soc_dapm_output}, {SND_SOC_TPLG_DAPM_MUX, snd_soc_dapm_mux}, {SND_SOC_TPLG_DAPM_MIXER, snd_soc_dapm_mixer}, {SND_SOC_TPLG_DAPM_PGA, snd_soc_dapm_pga}, {SND_SOC_TPLG_DAPM_OUT_DRV, snd_soc_dapm_out_drv}, {SND_SOC_TPLG_DAPM_ADC, snd_soc_dapm_adc}, {SND_SOC_TPLG_DAPM_DAC, snd_soc_dapm_dac}, {SND_SOC_TPLG_DAPM_SWITCH, snd_soc_dapm_switch}, {SND_SOC_TPLG_DAPM_PRE, snd_soc_dapm_pre}, {SND_SOC_TPLG_DAPM_POST, snd_soc_dapm_post}, {SND_SOC_TPLG_DAPM_AIF_IN, snd_soc_dapm_aif_in}, {SND_SOC_TPLG_DAPM_AIF_OUT, snd_soc_dapm_aif_out}, {SND_SOC_TPLG_DAPM_DAI_IN, snd_soc_dapm_dai_in}, {SND_SOC_TPLG_DAPM_DAI_OUT, snd_soc_dapm_dai_out}, {SND_SOC_TPLG_DAPM_DAI_LINK, snd_soc_dapm_dai_link}, }; static int tplc_chan_get_reg(struct soc_tplg *tplg, struct snd_soc_tplg_channel *chan, int map) { int i; for (i = 0; i < SND_SOC_TPLG_MAX_CHAN; i++) { if (chan[i].id == map) return chan[i].reg; } return -EINVAL; } static int tplc_chan_get_shift(struct soc_tplg *tplg, struct snd_soc_tplg_channel *chan, int map) { int i; for (i = 0; i < SND_SOC_TPLG_MAX_CHAN; i++) { if (chan[i].id == map) return chan[i].shift; } return -EINVAL; } static int get_widget_id(int tplg_type) { int i; for (i = 0; i < ARRAY_SIZE(dapm_map); i++) { if (tplg_type == dapm_map[i].uid) return dapm_map[i].kid; } return -EINVAL; } static enum snd_soc_dobj_type get_dobj_mixer_type( struct snd_soc_tplg_ctl_hdr *control_hdr) { if (control_hdr == NULL) return SND_SOC_DOBJ_NONE; switch (control_hdr->ops.info) { case SND_SOC_TPLG_CTL_VOLSW: case SND_SOC_TPLG_CTL_VOLSW_SX: case SND_SOC_TPLG_CTL_VOLSW_XR_SX: case SND_SOC_TPLG_CTL_RANGE: case SND_SOC_TPLG_CTL_STROBE: return SND_SOC_DOBJ_MIXER; case SND_SOC_TPLG_CTL_ENUM: case SND_SOC_TPLG_CTL_ENUM_VALUE: return SND_SOC_DOBJ_ENUM; case SND_SOC_TPLG_CTL_BYTES: return SND_SOC_DOBJ_BYTES; default: return SND_SOC_DOBJ_NONE; } } static enum snd_soc_dobj_type get_dobj_type(struct snd_soc_tplg_hdr *hdr, struct snd_soc_tplg_ctl_hdr *control_hdr) { switch (hdr->type) { case SND_SOC_TPLG_TYPE_MIXER: return get_dobj_mixer_type(control_hdr); case SND_SOC_TPLG_TYPE_DAPM_GRAPH: case SND_SOC_TPLG_TYPE_MANIFEST: return SND_SOC_DOBJ_NONE; case SND_SOC_TPLG_TYPE_DAPM_WIDGET: return SND_SOC_DOBJ_WIDGET; case SND_SOC_TPLG_TYPE_DAI_LINK: return SND_SOC_DOBJ_DAI_LINK; case SND_SOC_TPLG_TYPE_PCM: return SND_SOC_DOBJ_PCM; case SND_SOC_TPLG_TYPE_CODEC_LINK: return SND_SOC_DOBJ_CODEC_LINK; default: return SND_SOC_DOBJ_NONE; } } static inline void soc_bind_err(struct soc_tplg *tplg, struct snd_soc_tplg_ctl_hdr *hdr, int index) { dev_err(tplg->dev, "ASoC: invalid control type (g,p,i) %d:%d:%d index %d at 0x%lx\n", hdr->ops.get, hdr->ops.put, hdr->ops.info, index, soc_tplg_get_offset(tplg)); } static inline void soc_control_err(struct soc_tplg *tplg, struct snd_soc_tplg_ctl_hdr *hdr, const char *name) { dev_err(tplg->dev, "ASoC: no complete mixer IO handler for %s type (g,p,i) %d:%d:%d at 0x%lx\n", name, hdr->ops.get, hdr->ops.put, hdr->ops.info, soc_tplg_get_offset(tplg)); } /* pass vendor data to component driver for processing */ static int soc_tplg_vendor_load_(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { int ret = 0; if (tplg->comp && tplg->ops && tplg->ops->vendor_load) ret = tplg->ops->vendor_load(tplg->comp, hdr); else { dev_err(tplg->dev, "ASoC: no vendor load callback for ID %d\n", hdr->vendor_type); return -EINVAL; } if (ret < 0) dev_err(tplg->dev, "ASoC: vendor load failed at hdr offset %ld/0x%lx for type %d:%d\n", soc_tplg_get_hdr_offset(tplg), soc_tplg_get_hdr_offset(tplg), hdr->type, hdr->vendor_type); return ret; } /* pass vendor data to component driver for processing */ static int soc_tplg_vendor_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { if (tplg->pass != SOC_TPLG_PASS_VENDOR) return 0; return soc_tplg_vendor_load_(tplg, hdr); } /* optionally pass new dynamic widget to component driver. This is mainly for * external widgets where we can assign private data/ops */ static int soc_tplg_widget_load(struct soc_tplg *tplg, struct snd_soc_dapm_widget *w, struct snd_soc_tplg_dapm_widget *tplg_w) { if (tplg->comp && tplg->ops && tplg->ops->widget_load) return tplg->ops->widget_load(tplg->comp, w, tplg_w); return 0; } /* pass dynamic FEs configurations to component driver */ static int soc_tplg_pcm_dai_load(struct soc_tplg *tplg, struct snd_soc_tplg_pcm_dai *pcm_dai, int num_pcm_dai) { if (tplg->comp && tplg->ops && tplg->ops->pcm_dai_load) return tplg->ops->pcm_dai_load(tplg->comp, pcm_dai, num_pcm_dai); return 0; } /* tell the component driver that all firmware has been loaded in this request */ static void soc_tplg_complete(struct soc_tplg *tplg) { if (tplg->comp && tplg->ops && tplg->ops->complete) tplg->ops->complete(tplg->comp); } /* add a dynamic kcontrol */ static int soc_tplg_add_dcontrol(struct snd_card *card, struct device *dev, const struct snd_kcontrol_new *control_new, const char *prefix, void *data, struct snd_kcontrol **kcontrol) { int err; *kcontrol = snd_soc_cnew(control_new, data, control_new->name, prefix); if (*kcontrol == NULL) { dev_err(dev, "ASoC: Failed to create new kcontrol %s\n", control_new->name); return -ENOMEM; } err = snd_ctl_add(card, *kcontrol); if (err < 0) { dev_err(dev, "ASoC: Failed to add %s: %d\n", control_new->name, err); return err; } return 0; } /* add a dynamic kcontrol for component driver */ static int soc_tplg_add_kcontrol(struct soc_tplg *tplg, struct snd_kcontrol_new *k, struct snd_kcontrol **kcontrol) { struct snd_soc_component *comp = tplg->comp; return soc_tplg_add_dcontrol(comp->card->snd_card, comp->dev, k, NULL, comp, kcontrol); } /* remove a mixer kcontrol */ static void remove_mixer(struct snd_soc_component *comp, struct snd_soc_dobj *dobj, int pass) { struct snd_card *card = comp->card->snd_card; struct soc_mixer_control *sm = container_of(dobj, struct soc_mixer_control, dobj); const unsigned int *p = NULL; if (pass != SOC_TPLG_PASS_MIXER) return; if (dobj->ops && dobj->ops->control_unload) dobj->ops->control_unload(comp, dobj); if (sm->dobj.control.kcontrol->tlv.p) p = sm->dobj.control.kcontrol->tlv.p; snd_ctl_remove(card, sm->dobj.control.kcontrol); list_del(&sm->dobj.list); kfree(sm); kfree(p); } /* remove an enum kcontrol */ static void remove_enum(struct snd_soc_component *comp, struct snd_soc_dobj *dobj, int pass) { struct snd_card *card = comp->card->snd_card; struct soc_enum *se = container_of(dobj, struct soc_enum, dobj); int i; if (pass != SOC_TPLG_PASS_MIXER) return; if (dobj->ops && dobj->ops->control_unload) dobj->ops->control_unload(comp, dobj); snd_ctl_remove(card, se->dobj.control.kcontrol); list_del(&se->dobj.list); kfree(se->dobj.control.dvalues); for (i = 0; i < se->items; i++) kfree(se->dobj.control.dtexts[i]); kfree(se); } /* remove a byte kcontrol */ static void remove_bytes(struct snd_soc_component *comp, struct snd_soc_dobj *dobj, int pass) { struct snd_card *card = comp->card->snd_card; struct soc_bytes_ext *sb = container_of(dobj, struct soc_bytes_ext, dobj); if (pass != SOC_TPLG_PASS_MIXER) return; if (dobj->ops && dobj->ops->control_unload) dobj->ops->control_unload(comp, dobj); snd_ctl_remove(card, sb->dobj.control.kcontrol); list_del(&sb->dobj.list); kfree(sb); } /* remove a widget and it's kcontrols - routes must be removed first */ static void remove_widget(struct snd_soc_component *comp, struct snd_soc_dobj *dobj, int pass) { struct snd_card *card = comp->card->snd_card; struct snd_soc_dapm_widget *w = container_of(dobj, struct snd_soc_dapm_widget, dobj); int i; if (pass != SOC_TPLG_PASS_WIDGET) return; if (dobj->ops && dobj->ops->widget_unload) dobj->ops->widget_unload(comp, dobj); /* * Dynamic Widgets either have 1 enum kcontrol or 1..N mixers. * The enum may either have an array of values or strings. */ if (dobj->widget.kcontrol_enum) { /* enumerated widget mixer */ struct soc_enum *se = (struct soc_enum *)w->kcontrols[0]->private_value; snd_ctl_remove(card, w->kcontrols[0]); kfree(se->dobj.control.dvalues); for (i = 0; i < se->items; i++) kfree(se->dobj.control.dtexts[i]); kfree(se); kfree(w->kcontrol_news); } else { /* non enumerated widget mixer */ for (i = 0; i < w->num_kcontrols; i++) { struct snd_kcontrol *kcontrol = w->kcontrols[i]; struct soc_mixer_control *sm = (struct soc_mixer_control *) kcontrol->private_value; kfree(w->kcontrols[i]->tlv.p); snd_ctl_remove(card, w->kcontrols[i]); kfree(sm); } kfree(w->kcontrol_news); } /* widget w is freed by soc-dapm.c */ } /* remove PCM DAI configurations */ static void remove_pcm_dai(struct snd_soc_component *comp, struct snd_soc_dobj *dobj, int pass) { if (pass != SOC_TPLG_PASS_PCM_DAI) return; if (dobj->ops && dobj->ops->pcm_dai_unload) dobj->ops->pcm_dai_unload(comp, dobj); list_del(&dobj->list); kfree(dobj); } /* bind a kcontrol to it's IO handlers */ static int soc_tplg_kcontrol_bind_io(struct snd_soc_tplg_ctl_hdr *hdr, struct snd_kcontrol_new *k, const struct soc_tplg *tplg) { const struct snd_soc_tplg_kcontrol_ops *ops; const struct snd_soc_tplg_bytes_ext_ops *ext_ops; int num_ops, i; if (hdr->ops.info == SND_SOC_TPLG_CTL_BYTES && k->iface & SNDRV_CTL_ELEM_IFACE_MIXER && k->access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE && k->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK) { struct soc_bytes_ext *sbe; struct snd_soc_tplg_bytes_control *be; sbe = (struct soc_bytes_ext *)k->private_value; be = container_of(hdr, struct snd_soc_tplg_bytes_control, hdr); /* TLV bytes controls need standard kcontrol info handler, * TLV callback and extended put/get handlers. */ k->info = snd_soc_bytes_info_ext; k->tlv.c = snd_soc_bytes_tlv_callback; ext_ops = tplg->bytes_ext_ops; num_ops = tplg->bytes_ext_ops_count; for (i = 0; i < num_ops; i++) { if (!sbe->put && ext_ops[i].id == be->ext_ops.put) sbe->put = ext_ops[i].put; if (!sbe->get && ext_ops[i].id == be->ext_ops.get) sbe->get = ext_ops[i].get; } if (sbe->put && sbe->get) return 0; else return -EINVAL; } /* try and map vendor specific kcontrol handlers first */ ops = tplg->io_ops; num_ops = tplg->io_ops_count; for (i = 0; i < num_ops; i++) { if (k->put == NULL && ops[i].id == hdr->ops.put) k->put = ops[i].put; if (k->get == NULL && ops[i].id == hdr->ops.get) k->get = ops[i].get; if (k->info == NULL && ops[i].id == hdr->ops.info) k->info = ops[i].info; } /* vendor specific handlers found ? */ if (k->put && k->get && k->info) return 0; /* none found so try standard kcontrol handlers */ ops = io_ops; num_ops = ARRAY_SIZE(io_ops); for (i = 0; i < num_ops; i++) { if (k->put == NULL && ops[i].id == hdr->ops.put) k->put = ops[i].put; if (k->get == NULL && ops[i].id == hdr->ops.get) k->get = ops[i].get; if (k->info == NULL && ops[i].id == hdr->ops.info) k->info = ops[i].info; } /* standard handlers found ? */ if (k->put && k->get && k->info) return 0; /* nothing to bind */ return -EINVAL; } /* bind a widgets to it's evnt handlers */ int snd_soc_tplg_widget_bind_event(struct snd_soc_dapm_widget *w, const struct snd_soc_tplg_widget_events *events, int num_events, u16 event_type) { int i; w->event = NULL; for (i = 0; i < num_events; i++) { if (event_type == events[i].type) { /* found - so assign event */ w->event = events[i].event_handler; return 0; } } /* not found */ return -EINVAL; } EXPORT_SYMBOL_GPL(snd_soc_tplg_widget_bind_event); /* optionally pass new dynamic kcontrol to component driver. */ static int soc_tplg_init_kcontrol(struct soc_tplg *tplg, struct snd_kcontrol_new *k, struct snd_soc_tplg_ctl_hdr *hdr) { if (tplg->comp && tplg->ops && tplg->ops->control_load) return tplg->ops->control_load(tplg->comp, k, hdr); return 0; } static int soc_tplg_create_tlv_db_scale(struct soc_tplg *tplg, struct snd_kcontrol_new *kc, struct snd_soc_tplg_tlv_dbscale *scale) { unsigned int item_len = 2 * sizeof(unsigned int); unsigned int *p; p = kzalloc(item_len + 2 * sizeof(unsigned int), GFP_KERNEL); if (!p) return -ENOMEM; p[0] = SNDRV_CTL_TLVT_DB_SCALE; p[1] = item_len; p[2] = scale->min; p[3] = (scale->step & TLV_DB_SCALE_MASK) | (scale->mute ? TLV_DB_SCALE_MUTE : 0); kc->tlv.p = (void *)p; return 0; } static int soc_tplg_create_tlv(struct soc_tplg *tplg, struct snd_kcontrol_new *kc, struct snd_soc_tplg_ctl_hdr *tc) { struct snd_soc_tplg_ctl_tlv *tplg_tlv; if (!(tc->access & SNDRV_CTL_ELEM_ACCESS_TLV_READWRITE)) return 0; if (!(tc->access & SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK)) { tplg_tlv = &tc->tlv; switch (tplg_tlv->type) { case SNDRV_CTL_TLVT_DB_SCALE: return soc_tplg_create_tlv_db_scale(tplg, kc, &tplg_tlv->scale); /* TODO: add support for other TLV types */ default: dev_dbg(tplg->dev, "Unsupported TLV type %d\n", tplg_tlv->type); return -EINVAL; } } return 0; } static inline void soc_tplg_free_tlv(struct soc_tplg *tplg, struct snd_kcontrol_new *kc) { kfree(kc->tlv.p); } static int soc_tplg_dbytes_create(struct soc_tplg *tplg, unsigned int count, size_t size) { struct snd_soc_tplg_bytes_control *be; struct soc_bytes_ext *sbe; struct snd_kcontrol_new kc; int i, err; if (soc_tplg_check_elem_count(tplg, sizeof(struct snd_soc_tplg_bytes_control), count, size, "mixer bytes")) { dev_err(tplg->dev, "ASoC: Invalid count %d for byte control\n", count); return -EINVAL; } for (i = 0; i < count; i++) { be = (struct snd_soc_tplg_bytes_control *)tplg->pos; /* validate kcontrol */ if (strnlen(be->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; sbe = kzalloc(sizeof(*sbe), GFP_KERNEL); if (sbe == NULL) return -ENOMEM; tplg->pos += (sizeof(struct snd_soc_tplg_bytes_control) + be->priv.size); dev_dbg(tplg->dev, "ASoC: adding bytes kcontrol %s with access 0x%x\n", be->hdr.name, be->hdr.access); memset(&kc, 0, sizeof(kc)); kc.name = be->hdr.name; kc.private_value = (long)sbe; kc.iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc.access = be->hdr.access; sbe->max = be->max; sbe->dobj.type = SND_SOC_DOBJ_BYTES; sbe->dobj.ops = tplg->ops; INIT_LIST_HEAD(&sbe->dobj.list); /* map io handlers */ err = soc_tplg_kcontrol_bind_io(&be->hdr, &kc, tplg); if (err) { soc_control_err(tplg, &be->hdr, be->hdr.name); kfree(sbe); continue; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, &kc, (struct snd_soc_tplg_ctl_hdr *)be); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", be->hdr.name); kfree(sbe); continue; } /* register control here */ err = soc_tplg_add_kcontrol(tplg, &kc, &sbe->dobj.control.kcontrol); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to add %s\n", be->hdr.name); kfree(sbe); continue; } list_add(&sbe->dobj.list, &tplg->comp->dobj_list); } return 0; } static int soc_tplg_dmixer_create(struct soc_tplg *tplg, unsigned int count, size_t size) { struct snd_soc_tplg_mixer_control *mc; struct soc_mixer_control *sm; struct snd_kcontrol_new kc; int i, err; if (soc_tplg_check_elem_count(tplg, sizeof(struct snd_soc_tplg_mixer_control), count, size, "mixers")) { dev_err(tplg->dev, "ASoC: invalid count %d for controls\n", count); return -EINVAL; } for (i = 0; i < count; i++) { mc = (struct snd_soc_tplg_mixer_control *)tplg->pos; /* validate kcontrol */ if (strnlen(mc->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; sm = kzalloc(sizeof(*sm), GFP_KERNEL); if (sm == NULL) return -ENOMEM; tplg->pos += (sizeof(struct snd_soc_tplg_mixer_control) + mc->priv.size); dev_dbg(tplg->dev, "ASoC: adding mixer kcontrol %s with access 0x%x\n", mc->hdr.name, mc->hdr.access); memset(&kc, 0, sizeof(kc)); kc.name = mc->hdr.name; kc.private_value = (long)sm; kc.iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc.access = mc->hdr.access; /* we only support FL/FR channel mapping atm */ sm->reg = tplc_chan_get_reg(tplg, mc->channel, SNDRV_CHMAP_FL); sm->rreg = tplc_chan_get_reg(tplg, mc->channel, SNDRV_CHMAP_FR); sm->shift = tplc_chan_get_shift(tplg, mc->channel, SNDRV_CHMAP_FL); sm->rshift = tplc_chan_get_shift(tplg, mc->channel, SNDRV_CHMAP_FR); sm->max = mc->max; sm->min = mc->min; sm->invert = mc->invert; sm->platform_max = mc->platform_max; sm->dobj.index = tplg->index; sm->dobj.ops = tplg->ops; sm->dobj.type = SND_SOC_DOBJ_MIXER; INIT_LIST_HEAD(&sm->dobj.list); /* map io handlers */ err = soc_tplg_kcontrol_bind_io(&mc->hdr, &kc, tplg); if (err) { soc_control_err(tplg, &mc->hdr, mc->hdr.name); kfree(sm); continue; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, &kc, (struct snd_soc_tplg_ctl_hdr *) mc); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", mc->hdr.name); kfree(sm); continue; } /* create any TLV data */ soc_tplg_create_tlv(tplg, &kc, &mc->hdr); /* register control here */ err = soc_tplg_add_kcontrol(tplg, &kc, &sm->dobj.control.kcontrol); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to add %s\n", mc->hdr.name); soc_tplg_free_tlv(tplg, &kc); kfree(sm); continue; } list_add(&sm->dobj.list, &tplg->comp->dobj_list); } return 0; } static int soc_tplg_denum_create_texts(struct soc_enum *se, struct snd_soc_tplg_enum_control *ec) { int i, ret; se->dobj.control.dtexts = kzalloc(sizeof(char *) * ec->items, GFP_KERNEL); if (se->dobj.control.dtexts == NULL) return -ENOMEM; for (i = 0; i < ec->items; i++) { if (strnlen(ec->texts[i], SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) { ret = -EINVAL; goto err; } se->dobj.control.dtexts[i] = kstrdup(ec->texts[i], GFP_KERNEL); if (!se->dobj.control.dtexts[i]) { ret = -ENOMEM; goto err; } } return 0; err: for (--i; i >= 0; i--) kfree(se->dobj.control.dtexts[i]); kfree(se->dobj.control.dtexts); return ret; } static int soc_tplg_denum_create_values(struct soc_enum *se, struct snd_soc_tplg_enum_control *ec) { if (ec->items > sizeof(*ec->values)) return -EINVAL; se->dobj.control.dvalues = kmemdup(ec->values, ec->items * sizeof(u32), GFP_KERNEL); if (!se->dobj.control.dvalues) return -ENOMEM; return 0; } static int soc_tplg_denum_create(struct soc_tplg *tplg, unsigned int count, size_t size) { struct snd_soc_tplg_enum_control *ec; struct soc_enum *se; struct snd_kcontrol_new kc; int i, ret, err; if (soc_tplg_check_elem_count(tplg, sizeof(struct snd_soc_tplg_enum_control), count, size, "enums")) { dev_err(tplg->dev, "ASoC: invalid count %d for enum controls\n", count); return -EINVAL; } for (i = 0; i < count; i++) { ec = (struct snd_soc_tplg_enum_control *)tplg->pos; tplg->pos += (sizeof(struct snd_soc_tplg_enum_control) + ec->priv.size); /* validate kcontrol */ if (strnlen(ec->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; se = kzalloc((sizeof(*se)), GFP_KERNEL); if (se == NULL) return -ENOMEM; dev_dbg(tplg->dev, "ASoC: adding enum kcontrol %s size %d\n", ec->hdr.name, ec->items); memset(&kc, 0, sizeof(kc)); kc.name = ec->hdr.name; kc.private_value = (long)se; kc.iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc.access = ec->hdr.access; se->reg = tplc_chan_get_reg(tplg, ec->channel, SNDRV_CHMAP_FL); se->shift_l = tplc_chan_get_shift(tplg, ec->channel, SNDRV_CHMAP_FL); se->shift_r = tplc_chan_get_shift(tplg, ec->channel, SNDRV_CHMAP_FL); se->items = ec->items; se->mask = ec->mask; se->dobj.index = tplg->index; se->dobj.type = SND_SOC_DOBJ_ENUM; se->dobj.ops = tplg->ops; INIT_LIST_HEAD(&se->dobj.list); switch (ec->hdr.ops.info) { case SND_SOC_TPLG_DAPM_CTL_ENUM_VALUE: case SND_SOC_TPLG_CTL_ENUM_VALUE: err = soc_tplg_denum_create_values(se, ec); if (err < 0) { dev_err(tplg->dev, "ASoC: could not create values for %s\n", ec->hdr.name); kfree(se); continue; } /* fall through and create texts */ case SND_SOC_TPLG_CTL_ENUM: case SND_SOC_TPLG_DAPM_CTL_ENUM_DOUBLE: case SND_SOC_TPLG_DAPM_CTL_ENUM_VIRT: err = soc_tplg_denum_create_texts(se, ec); if (err < 0) { dev_err(tplg->dev, "ASoC: could not create texts for %s\n", ec->hdr.name); kfree(se); continue; } break; default: dev_err(tplg->dev, "ASoC: invalid enum control type %d for %s\n", ec->hdr.ops.info, ec->hdr.name); kfree(se); continue; } /* map io handlers */ err = soc_tplg_kcontrol_bind_io(&ec->hdr, &kc, tplg); if (err) { soc_control_err(tplg, &ec->hdr, ec->hdr.name); kfree(se); continue; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, &kc, (struct snd_soc_tplg_ctl_hdr *) ec); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", ec->hdr.name); kfree(se); continue; } /* register control here */ ret = soc_tplg_add_kcontrol(tplg, &kc, &se->dobj.control.kcontrol); if (ret < 0) { dev_err(tplg->dev, "ASoC: could not add kcontrol %s\n", ec->hdr.name); kfree(se); continue; } list_add(&se->dobj.list, &tplg->comp->dobj_list); } return 0; } static int soc_tplg_kcontrol_elems_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { struct snd_soc_tplg_ctl_hdr *control_hdr; int i; if (tplg->pass != SOC_TPLG_PASS_MIXER) { tplg->pos += hdr->size + hdr->payload_size; return 0; } dev_dbg(tplg->dev, "ASoC: adding %d kcontrols at 0x%lx\n", hdr->count, soc_tplg_get_offset(tplg)); for (i = 0; i < hdr->count; i++) { control_hdr = (struct snd_soc_tplg_ctl_hdr *)tplg->pos; switch (control_hdr->ops.info) { case SND_SOC_TPLG_CTL_VOLSW: case SND_SOC_TPLG_CTL_STROBE: case SND_SOC_TPLG_CTL_VOLSW_SX: case SND_SOC_TPLG_CTL_VOLSW_XR_SX: case SND_SOC_TPLG_CTL_RANGE: case SND_SOC_TPLG_DAPM_CTL_VOLSW: case SND_SOC_TPLG_DAPM_CTL_PIN: soc_tplg_dmixer_create(tplg, 1, hdr->payload_size); break; case SND_SOC_TPLG_CTL_ENUM: case SND_SOC_TPLG_CTL_ENUM_VALUE: case SND_SOC_TPLG_DAPM_CTL_ENUM_DOUBLE: case SND_SOC_TPLG_DAPM_CTL_ENUM_VIRT: case SND_SOC_TPLG_DAPM_CTL_ENUM_VALUE: soc_tplg_denum_create(tplg, 1, hdr->payload_size); break; case SND_SOC_TPLG_CTL_BYTES: soc_tplg_dbytes_create(tplg, 1, hdr->payload_size); break; default: soc_bind_err(tplg, control_hdr, i); return -EINVAL; } } return 0; } static int soc_tplg_dapm_graph_elems_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { struct snd_soc_dapm_context *dapm = &tplg->comp->dapm; struct snd_soc_dapm_route route; struct snd_soc_tplg_dapm_graph_elem *elem; int count = hdr->count, i; if (tplg->pass != SOC_TPLG_PASS_GRAPH) { tplg->pos += hdr->size + hdr->payload_size; return 0; } if (soc_tplg_check_elem_count(tplg, sizeof(struct snd_soc_tplg_dapm_graph_elem), count, hdr->payload_size, "graph")) { dev_err(tplg->dev, "ASoC: invalid count %d for DAPM routes\n", count); return -EINVAL; } dev_dbg(tplg->dev, "ASoC: adding %d DAPM routes\n", count); for (i = 0; i < count; i++) { elem = (struct snd_soc_tplg_dapm_graph_elem *)tplg->pos; tplg->pos += sizeof(struct snd_soc_tplg_dapm_graph_elem); /* validate routes */ if (strnlen(elem->source, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; if (strnlen(elem->sink, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; if (strnlen(elem->control, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; route.source = elem->source; route.sink = elem->sink; route.connected = NULL; /* set to NULL atm for tplg users */ if (strnlen(elem->control, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == 0) route.control = NULL; else route.control = elem->control; /* add route, but keep going if some fail */ snd_soc_dapm_add_routes(dapm, &route, 1); } return 0; } static struct snd_kcontrol_new *soc_tplg_dapm_widget_dmixer_create( struct soc_tplg *tplg, int num_kcontrols) { struct snd_kcontrol_new *kc; struct soc_mixer_control *sm; struct snd_soc_tplg_mixer_control *mc; int i, err; kc = kcalloc(num_kcontrols, sizeof(*kc), GFP_KERNEL); if (kc == NULL) return NULL; for (i = 0; i < num_kcontrols; i++) { mc = (struct snd_soc_tplg_mixer_control *)tplg->pos; sm = kzalloc(sizeof(*sm), GFP_KERNEL); if (sm == NULL) goto err; tplg->pos += (sizeof(struct snd_soc_tplg_mixer_control) + mc->priv.size); /* validate kcontrol */ if (strnlen(mc->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) goto err_str; dev_dbg(tplg->dev, " adding DAPM widget mixer control %s at %d\n", mc->hdr.name, i); kc[i].name = mc->hdr.name; kc[i].private_value = (long)sm; kc[i].iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc[i].access = mc->hdr.access; /* we only support FL/FR channel mapping atm */ sm->reg = tplc_chan_get_reg(tplg, mc->channel, SNDRV_CHMAP_FL); sm->rreg = tplc_chan_get_reg(tplg, mc->channel, SNDRV_CHMAP_FR); sm->shift = tplc_chan_get_shift(tplg, mc->channel, SNDRV_CHMAP_FL); sm->rshift = tplc_chan_get_shift(tplg, mc->channel, SNDRV_CHMAP_FR); sm->max = mc->max; sm->min = mc->min; sm->invert = mc->invert; sm->platform_max = mc->platform_max; sm->dobj.index = tplg->index; INIT_LIST_HEAD(&sm->dobj.list); /* map io handlers */ err = soc_tplg_kcontrol_bind_io(&mc->hdr, &kc[i], tplg); if (err) { soc_control_err(tplg, &mc->hdr, mc->hdr.name); kfree(sm); continue; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, &kc[i], (struct snd_soc_tplg_ctl_hdr *)mc); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", mc->hdr.name); kfree(sm); continue; } } return kc; err_str: kfree(sm); err: for (--i; i >= 0; i--) kfree((void *)kc[i].private_value); kfree(kc); return NULL; } static struct snd_kcontrol_new *soc_tplg_dapm_widget_denum_create( struct soc_tplg *tplg) { struct snd_kcontrol_new *kc; struct snd_soc_tplg_enum_control *ec; struct soc_enum *se; int i, err; ec = (struct snd_soc_tplg_enum_control *)tplg->pos; tplg->pos += (sizeof(struct snd_soc_tplg_enum_control) + ec->priv.size); /* validate kcontrol */ if (strnlen(ec->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return NULL; kc = kzalloc(sizeof(*kc), GFP_KERNEL); if (kc == NULL) return NULL; se = kzalloc(sizeof(*se), GFP_KERNEL); if (se == NULL) goto err; dev_dbg(tplg->dev, " adding DAPM widget enum control %s\n", ec->hdr.name); kc->name = ec->hdr.name; kc->private_value = (long)se; kc->iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc->access = ec->hdr.access; /* we only support FL/FR channel mapping atm */ se->reg = tplc_chan_get_reg(tplg, ec->channel, SNDRV_CHMAP_FL); se->shift_l = tplc_chan_get_shift(tplg, ec->channel, SNDRV_CHMAP_FL); se->shift_r = tplc_chan_get_shift(tplg, ec->channel, SNDRV_CHMAP_FR); se->items = ec->items; se->mask = ec->mask; se->dobj.index = tplg->index; switch (ec->hdr.ops.info) { case SND_SOC_TPLG_CTL_ENUM_VALUE: case SND_SOC_TPLG_DAPM_CTL_ENUM_VALUE: err = soc_tplg_denum_create_values(se, ec); if (err < 0) { dev_err(tplg->dev, "ASoC: could not create values for %s\n", ec->hdr.name); goto err_se; } /* fall through to create texts */ case SND_SOC_TPLG_CTL_ENUM: case SND_SOC_TPLG_DAPM_CTL_ENUM_DOUBLE: case SND_SOC_TPLG_DAPM_CTL_ENUM_VIRT: err = soc_tplg_denum_create_texts(se, ec); if (err < 0) { dev_err(tplg->dev, "ASoC: could not create texts for %s\n", ec->hdr.name); goto err_se; } break; default: dev_err(tplg->dev, "ASoC: invalid enum control type %d for %s\n", ec->hdr.ops.info, ec->hdr.name); goto err_se; } /* map io handlers */ err = soc_tplg_kcontrol_bind_io(&ec->hdr, kc, tplg); if (err) { soc_control_err(tplg, &ec->hdr, ec->hdr.name); goto err_se; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, kc, (struct snd_soc_tplg_ctl_hdr *)ec); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", ec->hdr.name); goto err_se; } return kc; err_se: /* free values and texts */ kfree(se->dobj.control.dvalues); for (i = 0; i < ec->items; i++) kfree(se->dobj.control.dtexts[i]); kfree(se); err: kfree(kc); return NULL; } static struct snd_kcontrol_new *soc_tplg_dapm_widget_dbytes_create( struct soc_tplg *tplg, int count) { struct snd_soc_tplg_bytes_control *be; struct soc_bytes_ext *sbe; struct snd_kcontrol_new *kc; int i, err; kc = kcalloc(count, sizeof(*kc), GFP_KERNEL); if (!kc) return NULL; for (i = 0; i < count; i++) { be = (struct snd_soc_tplg_bytes_control *)tplg->pos; /* validate kcontrol */ if (strnlen(be->hdr.name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) goto err; sbe = kzalloc(sizeof(*sbe), GFP_KERNEL); if (sbe == NULL) goto err; tplg->pos += (sizeof(struct snd_soc_tplg_bytes_control) + be->priv.size); dev_dbg(tplg->dev, "ASoC: adding bytes kcontrol %s with access 0x%x\n", be->hdr.name, be->hdr.access); kc[i].name = be->hdr.name; kc[i].private_value = (long)sbe; kc[i].iface = SNDRV_CTL_ELEM_IFACE_MIXER; kc[i].access = be->hdr.access; sbe->max = be->max; INIT_LIST_HEAD(&sbe->dobj.list); /* map standard io handlers and check for external handlers */ err = soc_tplg_kcontrol_bind_io(&be->hdr, &kc[i], tplg); if (err) { soc_control_err(tplg, &be->hdr, be->hdr.name); kfree(sbe); continue; } /* pass control to driver for optional further init */ err = soc_tplg_init_kcontrol(tplg, &kc[i], (struct snd_soc_tplg_ctl_hdr *)be); if (err < 0) { dev_err(tplg->dev, "ASoC: failed to init %s\n", be->hdr.name); kfree(sbe); continue; } } return kc; err: for (--i; i >= 0; i--) kfree((void *)kc[i].private_value); kfree(kc); return NULL; } static int soc_tplg_dapm_widget_create(struct soc_tplg *tplg, struct snd_soc_tplg_dapm_widget *w) { struct snd_soc_dapm_context *dapm = &tplg->comp->dapm; struct snd_soc_dapm_widget template, *widget; struct snd_soc_tplg_ctl_hdr *control_hdr; struct snd_soc_card *card = tplg->comp->card; int ret = 0; if (strnlen(w->name, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; if (strnlen(w->sname, SNDRV_CTL_ELEM_ID_NAME_MAXLEN) == SNDRV_CTL_ELEM_ID_NAME_MAXLEN) return -EINVAL; dev_dbg(tplg->dev, "ASoC: creating DAPM widget %s id %d\n", w->name, w->id); memset(&template, 0, sizeof(template)); /* map user to kernel widget ID */ template.id = get_widget_id(w->id); if (template.id < 0) return template.id; template.name = kstrdup(w->name, GFP_KERNEL); if (!template.name) return -ENOMEM; template.sname = kstrdup(w->sname, GFP_KERNEL); if (!template.sname) { ret = -ENOMEM; goto err; } template.reg = w->reg; template.shift = w->shift; template.mask = w->mask; template.subseq = w->subseq; template.on_val = w->invert ? 0 : 1; template.off_val = w->invert ? 1 : 0; template.ignore_suspend = w->ignore_suspend; template.event_flags = w->event_flags; template.dobj.index = tplg->index; tplg->pos += (sizeof(struct snd_soc_tplg_dapm_widget) + w->priv.size); if (w->num_kcontrols == 0) { template.num_kcontrols = 0; goto widget; } control_hdr = (struct snd_soc_tplg_ctl_hdr *)tplg->pos; dev_dbg(tplg->dev, "ASoC: template %s has %d controls of type %x\n", w->name, w->num_kcontrols, control_hdr->type); switch (control_hdr->ops.info) { case SND_SOC_TPLG_CTL_VOLSW: case SND_SOC_TPLG_CTL_STROBE: case SND_SOC_TPLG_CTL_VOLSW_SX: case SND_SOC_TPLG_CTL_VOLSW_XR_SX: case SND_SOC_TPLG_CTL_RANGE: case SND_SOC_TPLG_DAPM_CTL_VOLSW: template.num_kcontrols = w->num_kcontrols; template.kcontrol_news = soc_tplg_dapm_widget_dmixer_create(tplg, template.num_kcontrols); if (!template.kcontrol_news) { ret = -ENOMEM; goto hdr_err; } break; case SND_SOC_TPLG_CTL_ENUM: case SND_SOC_TPLG_CTL_ENUM_VALUE: case SND_SOC_TPLG_DAPM_CTL_ENUM_DOUBLE: case SND_SOC_TPLG_DAPM_CTL_ENUM_VIRT: case SND_SOC_TPLG_DAPM_CTL_ENUM_VALUE: template.dobj.widget.kcontrol_enum = 1; template.num_kcontrols = 1; template.kcontrol_news = soc_tplg_dapm_widget_denum_create(tplg); if (!template.kcontrol_news) { ret = -ENOMEM; goto hdr_err; } break; case SND_SOC_TPLG_CTL_BYTES: template.num_kcontrols = w->num_kcontrols; template.kcontrol_news = soc_tplg_dapm_widget_dbytes_create(tplg, template.num_kcontrols); if (!template.kcontrol_news) { ret = -ENOMEM; goto hdr_err; } break; default: dev_err(tplg->dev, "ASoC: invalid widget control type %d:%d:%d\n", control_hdr->ops.get, control_hdr->ops.put, control_hdr->ops.info); ret = -EINVAL; goto hdr_err; } widget: ret = soc_tplg_widget_load(tplg, &template, w); if (ret < 0) goto hdr_err; /* card dapm mutex is held by the core if we are loading topology * data during sound card init. */ if (card->instantiated) widget = snd_soc_dapm_new_control(dapm, &template); else widget = snd_soc_dapm_new_control_unlocked(dapm, &template); if (widget == NULL) { dev_err(tplg->dev, "ASoC: failed to create widget %s controls\n", w->name); goto hdr_err; } widget->dobj.type = SND_SOC_DOBJ_WIDGET; widget->dobj.ops = tplg->ops; widget->dobj.index = tplg->index; list_add(&widget->dobj.list, &tplg->comp->dobj_list); return 0; hdr_err: kfree(template.sname); err: kfree(template.name); return ret; } static int soc_tplg_dapm_widget_elems_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { struct snd_soc_tplg_dapm_widget *widget; int ret, count = hdr->count, i; if (tplg->pass != SOC_TPLG_PASS_WIDGET) return 0; dev_dbg(tplg->dev, "ASoC: adding %d DAPM widgets\n", count); for (i = 0; i < count; i++) { widget = (struct snd_soc_tplg_dapm_widget *) tplg->pos; ret = soc_tplg_dapm_widget_create(tplg, widget); if (ret < 0) dev_err(tplg->dev, "ASoC: failed to load widget %s\n", widget->name); } return 0; } static int soc_tplg_dapm_complete(struct soc_tplg *tplg) { struct snd_soc_card *card = tplg->comp->card; int ret; /* Card might not have been registered at this point. * If so, just return success. */ if (!card || !card->instantiated) { dev_warn(tplg->dev, "ASoC: Parent card not yet available," "Do not add new widgets now\n"); return 0; } ret = snd_soc_dapm_new_widgets(card); if (ret < 0) dev_err(tplg->dev, "ASoC: failed to create new widgets %d\n", ret); return 0; } static int soc_tplg_pcm_dai_elems_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { struct snd_soc_tplg_pcm_dai *pcm_dai; struct snd_soc_dobj *dobj; int count = hdr->count; int ret; if (tplg->pass != SOC_TPLG_PASS_PCM_DAI) return 0; pcm_dai = (struct snd_soc_tplg_pcm_dai *)tplg->pos; if (soc_tplg_check_elem_count(tplg, sizeof(struct snd_soc_tplg_pcm), count, hdr->payload_size, "PCM DAI")) { dev_err(tplg->dev, "ASoC: invalid count %d for PCM DAI elems\n", count); return -EINVAL; } dev_dbg(tplg->dev, "ASoC: adding %d PCM DAIs\n", count); tplg->pos += sizeof(struct snd_soc_tplg_pcm) * count; dobj = kzalloc(sizeof(struct snd_soc_dobj), GFP_KERNEL); if (dobj == NULL) return -ENOMEM; /* Call the platform driver call back to register the dais */ ret = soc_tplg_pcm_dai_load(tplg, pcm_dai, count); if (ret < 0) { dev_err(tplg->comp->dev, "ASoC: PCM DAI loading failed\n"); goto err; } dobj->type = get_dobj_type(hdr, NULL); dobj->pcm_dai.count = count; dobj->pcm_dai.pd = pcm_dai; dobj->ops = tplg->ops; dobj->index = tplg->index; list_add(&dobj->list, &tplg->comp->dobj_list); return 0; err: kfree(dobj); return ret; } static int soc_tplg_manifest_load(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { struct snd_soc_tplg_manifest *manifest; if (tplg->pass != SOC_TPLG_PASS_MANIFEST) return 0; manifest = (struct snd_soc_tplg_manifest *)tplg->pos; tplg->pos += sizeof(struct snd_soc_tplg_manifest); if (tplg->comp && tplg->ops && tplg->ops->manifest) return tplg->ops->manifest(tplg->comp, manifest); dev_err(tplg->dev, "ASoC: Firmware manifest not supported\n"); return 0; } /* validate header magic, size and type */ static int soc_valid_header(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { if (soc_tplg_get_hdr_offset(tplg) >= tplg->fw->size) return 0; /* big endian firmware objects not supported atm */ if (hdr->magic == cpu_to_be32(SND_SOC_TPLG_MAGIC)) { dev_err(tplg->dev, "ASoC: pass %d big endian not supported header got %x at offset 0x%lx size 0x%zx.\n", tplg->pass, hdr->magic, soc_tplg_get_hdr_offset(tplg), tplg->fw->size); return -EINVAL; } if (hdr->magic != SND_SOC_TPLG_MAGIC) { dev_err(tplg->dev, "ASoC: pass %d does not have a valid header got %x at offset 0x%lx size 0x%zx.\n", tplg->pass, hdr->magic, soc_tplg_get_hdr_offset(tplg), tplg->fw->size); return -EINVAL; } if (hdr->abi != SND_SOC_TPLG_ABI_VERSION) { dev_err(tplg->dev, "ASoC: pass %d invalid ABI version got 0x%x need 0x%x at offset 0x%lx size 0x%zx.\n", tplg->pass, hdr->abi, SND_SOC_TPLG_ABI_VERSION, soc_tplg_get_hdr_offset(tplg), tplg->fw->size); return -EINVAL; } if (hdr->payload_size == 0) { dev_err(tplg->dev, "ASoC: header has 0 size at offset 0x%lx.\n", soc_tplg_get_hdr_offset(tplg)); return -EINVAL; } if (tplg->pass == hdr->type) dev_dbg(tplg->dev, "ASoC: Got 0x%x bytes of type %d version %d vendor %d at pass %d\n", hdr->payload_size, hdr->type, hdr->version, hdr->vendor_type, tplg->pass); return 1; } /* check header type and call appropriate handler */ static int soc_tplg_load_header(struct soc_tplg *tplg, struct snd_soc_tplg_hdr *hdr) { tplg->pos = tplg->hdr_pos + sizeof(struct snd_soc_tplg_hdr); /* check for matching ID */ if (hdr->index != tplg->req_index && hdr->index != SND_SOC_TPLG_INDEX_ALL) return 0; tplg->index = hdr->index; switch (hdr->type) { case SND_SOC_TPLG_TYPE_MIXER: case SND_SOC_TPLG_TYPE_ENUM: case SND_SOC_TPLG_TYPE_BYTES: return soc_tplg_kcontrol_elems_load(tplg, hdr); case SND_SOC_TPLG_TYPE_DAPM_GRAPH: return soc_tplg_dapm_graph_elems_load(tplg, hdr); case SND_SOC_TPLG_TYPE_DAPM_WIDGET: return soc_tplg_dapm_widget_elems_load(tplg, hdr); case SND_SOC_TPLG_TYPE_PCM: case SND_SOC_TPLG_TYPE_DAI_LINK: case SND_SOC_TPLG_TYPE_CODEC_LINK: return soc_tplg_pcm_dai_elems_load(tplg, hdr); case SND_SOC_TPLG_TYPE_MANIFEST: return soc_tplg_manifest_load(tplg, hdr); default: /* bespoke vendor data object */ return soc_tplg_vendor_load(tplg, hdr); } return 0; } /* process the topology file headers */ static int soc_tplg_process_headers(struct soc_tplg *tplg) { struct snd_soc_tplg_hdr *hdr; int ret; tplg->pass = SOC_TPLG_PASS_START; /* process the header types from start to end */ while (tplg->pass <= SOC_TPLG_PASS_END) { tplg->hdr_pos = tplg->fw->data; hdr = (struct snd_soc_tplg_hdr *)tplg->hdr_pos; while (!soc_tplg_is_eof(tplg)) { /* make sure header is valid before loading */ ret = soc_valid_header(tplg, hdr); if (ret < 0) return ret; else if (ret == 0) break; /* load the header object */ ret = soc_tplg_load_header(tplg, hdr); if (ret < 0) return ret; /* goto next header */ tplg->hdr_pos += hdr->payload_size + sizeof(struct snd_soc_tplg_hdr); hdr = (struct snd_soc_tplg_hdr *)tplg->hdr_pos; } /* next data type pass */ tplg->pass++; } /* signal DAPM we are complete */ ret = soc_tplg_dapm_complete(tplg); if (ret < 0) dev_err(tplg->dev, "ASoC: failed to initialise DAPM from Firmware\n"); return ret; } static int soc_tplg_load(struct soc_tplg *tplg) { int ret; ret = soc_tplg_process_headers(tplg); if (ret == 0) soc_tplg_complete(tplg); return ret; } /* load audio component topology from "firmware" file */ int snd_soc_tplg_component_load(struct snd_soc_component *comp, struct snd_soc_tplg_ops *ops, const struct firmware *fw, u32 id) { struct soc_tplg tplg; /* setup parsing context */ memset(&tplg, 0, sizeof(tplg)); tplg.fw = fw; tplg.dev = comp->dev; tplg.comp = comp; tplg.ops = ops; tplg.req_index = id; tplg.io_ops = ops->io_ops; tplg.io_ops_count = ops->io_ops_count; tplg.bytes_ext_ops = ops->bytes_ext_ops; tplg.bytes_ext_ops_count = ops->bytes_ext_ops_count; return soc_tplg_load(&tplg); } EXPORT_SYMBOL_GPL(snd_soc_tplg_component_load); /* remove this dynamic widget */ void snd_soc_tplg_widget_remove(struct snd_soc_dapm_widget *w) { /* make sure we are a widget */ if (w->dobj.type != SND_SOC_DOBJ_WIDGET) return; remove_widget(w->dapm->component, &w->dobj, SOC_TPLG_PASS_WIDGET); } EXPORT_SYMBOL_GPL(snd_soc_tplg_widget_remove); /* remove all dynamic widgets from this DAPM context */ void snd_soc_tplg_widget_remove_all(struct snd_soc_dapm_context *dapm, u32 index) { struct snd_soc_dapm_widget *w, *next_w; list_for_each_entry_safe(w, next_w, &dapm->card->widgets, list) { /* make sure we are a widget with correct context */ if (w->dobj.type != SND_SOC_DOBJ_WIDGET || w->dapm != dapm) continue; /* match ID */ if (w->dobj.index != index && w->dobj.index != SND_SOC_TPLG_INDEX_ALL) continue; /* check and free and dynamic widget kcontrols */ snd_soc_tplg_widget_remove(w); snd_soc_dapm_free_widget(w); } snd_soc_dapm_reset_cache(dapm); } EXPORT_SYMBOL_GPL(snd_soc_tplg_widget_remove_all); /* remove dynamic controls from the component driver */ int snd_soc_tplg_component_remove(struct snd_soc_component *comp, u32 index) { struct snd_soc_dobj *dobj, *next_dobj; int pass = SOC_TPLG_PASS_END; /* process the header types from end to start */ while (pass >= SOC_TPLG_PASS_START) { /* remove mixer controls */ list_for_each_entry_safe(dobj, next_dobj, &comp->dobj_list, list) { /* match index */ if (dobj->index != index && dobj->index != SND_SOC_TPLG_INDEX_ALL) continue; switch (dobj->type) { case SND_SOC_DOBJ_MIXER: remove_mixer(comp, dobj, pass); break; case SND_SOC_DOBJ_ENUM: remove_enum(comp, dobj, pass); break; case SND_SOC_DOBJ_BYTES: remove_bytes(comp, dobj, pass); break; case SND_SOC_DOBJ_WIDGET: remove_widget(comp, dobj, pass); break; case SND_SOC_DOBJ_PCM: case SND_SOC_DOBJ_DAI_LINK: case SND_SOC_DOBJ_CODEC_LINK: remove_pcm_dai(comp, dobj, pass); break; default: dev_err(comp->dev, "ASoC: invalid component type %d for removal\n", dobj->type); break; } } pass--; } /* let caller know if FW can be freed when no objects are left */ return !list_empty(&comp->dobj_list); } EXPORT_SYMBOL_GPL(snd_soc_tplg_component_remove);
mit
vinnyrom/coreclr
src/pal/tests/palsuite/exception_handling/PAL_EXCEPT_FILTER/test1/PAL_EXCEPT_FILTER.c
137
3102
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*===================================================================== ** ** Source: pal_except_filter.c (test 1) ** ** Purpose: Tests the PAL implementation of the PAL_EXCEPT_FILTER. An ** exception is forced and a known value is passed to the filter ** fuction. The known value as well as booleans are tested to ** ensure proper functioning. ** ** **===================================================================*/ #include <palsuite.h> BOOL bFilter = FALSE; BOOL bTry = FALSE; const int nValidator = 12321; LONG ExitFilter(EXCEPTION_POINTERS* ep, LPVOID pnTestInt) { int nTestInt = *(int *)pnTestInt; /* let the main know we've hit the filter function */ bFilter = TRUE; if (!bTry) { Fail("PAL_EXCEPT_FILTER: ERROR -> Something weird is going on." " The filter was hit without PAL_TRY being hit.\n"); } /* was the correct value passed? */ if (nValidator != nTestInt) { Fail("PAL_EXCEPT_FILTER: ERROR -> Parameter passed to filter function" " should have been \"%d\" but was \"%d\".\n", nValidator, nTestInt); } return EXCEPTION_EXECUTE_HANDLER; } int __cdecl main(int argc, char *argv[]) { int* p = 0x00000000; /* pointer to NULL */ BOOL bExcept = FALSE; if (0 != PAL_Initialize(argc, argv)) { return FAIL; } /* ** test to make sure we get into the exception block */ PAL_TRY { if (bExcept) { Fail("PAL_EXCEPT_FILTER: ERROR -> Something weird is going on." " PAL_EXCEPT_FILTER was hit before PAL_TRY.\n"); } bTry = TRUE; /* indicate we hit the PAL_TRY block */ *p = 13; /* causes an access violation exception */ Fail("PAL_EXCEPT_FILTER: ERROR -> code was executed after the " "access violation.\n"); } PAL_EXCEPT_FILTER(ExitFilter, (LPVOID)&nValidator) { if (!bTry) { Fail("PAL_EXCEPT_FILTER: ERROR -> Something weird is going on." " PAL_EXCEPT_FILTER was hit without PAL_TRY being hit.\n"); } bExcept = TRUE; /* indicate we hit the PAL_EXCEPT_FILTER block */ } PAL_ENDTRY; if (!bTry) { Trace("PAL_EXCEPT_FILTER: ERROR -> It appears the code in the PAL_TRY" " block was not executed.\n"); } if (!bExcept) { Trace("PAL_EXCEPT_FILTER: ERROR -> It appears the code in the " "PAL_EXCEPT_FILTER block was not executed.\n"); } if (!bFilter) { Trace("PAL_EXCEPT_FILTER: ERROR -> It appears the code in the filter" " function was not executed.\n"); } /* did we hit all the code blocks? */ if(!bTry || !bExcept || !bFilter) { Fail(""); } PAL_Terminate(); return PASS; }
mit
daleooo/barrelfish
lib/newlib/newlib/libc/machine/spu/ftell.c
139
1773
/* (C) Copyright IBM Corp. 2006 All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of IBM 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Author: Joel Schopp <jschopp@austin.ibm.com> */ #include <stdio.h> #include "c99ppe.h" #ifndef _REENT_ONLY long _DEFUN (ftell, (fp), FILE * fp) { long ret; CHECK_INIT(_REENT); ret = fp->_fp; return __send_to_ppe(SPE_C99_SIGNALCODE, SPE_C99_FTELL, &ret); } #endif /* ! _REENT_ONLY */
mit
Jaberer/WinObjC
deps/3rdparty/icu/icu/source/test/cintltst/cldrtest.c
166
66726
/******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2014, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ #include "cintltst.h" #include "unicode/ures.h" #include "unicode/ucurr.h" #include "unicode/ustring.h" #include "unicode/uset.h" #include "unicode/udat.h" #include "unicode/uscript.h" #include "unicode/ulocdata.h" #include "cstring.h" #include "locmap.h" #include "uresimp.h" /* returns a new UnicodeSet that is a flattened form of the original UnicodeSet. */ static USet* createFlattenSet(USet *origSet, UErrorCode *status) { USet *newSet = NULL; int32_t origItemCount = 0; int32_t idx, graphmeSize; UChar32 start, end; UChar graphme[64]; if (U_FAILURE(*status)) { log_err("createFlattenSet called with %s\n", u_errorName(*status)); return NULL; } newSet = uset_open(1, 0); origItemCount = uset_getItemCount(origSet); for (idx = 0; idx < origItemCount; idx++) { graphmeSize = uset_getItem(origSet, idx, &start, &end, graphme, (int32_t)(sizeof(graphme)/sizeof(graphme[0])), status); if (U_FAILURE(*status)) { log_err("ERROR: uset_getItem returned %s\n", u_errorName(*status)); *status = U_ZERO_ERROR; } if (graphmeSize) { uset_addAllCodePoints(newSet, graphme, graphmeSize); } else { uset_addRange(newSet, start, end); } } uset_closeOver(newSet,USET_CASE_INSENSITIVE); return newSet; } static UBool isCurrencyPreEuro(const char* currencyKey){ if( strcmp(currencyKey, "PTE") == 0 || strcmp(currencyKey, "ESP") == 0 || strcmp(currencyKey, "LUF") == 0 || strcmp(currencyKey, "GRD") == 0 || strcmp(currencyKey, "BEF") == 0 || strcmp(currencyKey, "ITL") == 0 || strcmp(currencyKey, "EEK") == 0){ return TRUE; } return FALSE; } #if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION static void TestKeyInRootRecursive(UResourceBundle *root, const char *rootName, UResourceBundle *currentBundle, const char *locale) { UErrorCode errorCode = U_ZERO_ERROR; UResourceBundle *subRootBundle = NULL, *subBundle = NULL, *arr = NULL; ures_resetIterator(root); ures_resetIterator(currentBundle); while (ures_hasNext(currentBundle)) { const char *subBundleKey = NULL; const char *currentBundleKey = NULL; errorCode = U_ZERO_ERROR; currentBundleKey = ures_getKey(currentBundle); (void)currentBundleKey; /* Suppress set but not used warning. */ subBundle = ures_getNextResource(currentBundle, NULL, &errorCode); if (U_FAILURE(errorCode)) { log_err("Can't open a resource for lnocale %s. Error: %s\n", locale, u_errorName(errorCode)); continue; } subBundleKey = ures_getKey(subBundle); subRootBundle = ures_getByKey(root, subBundleKey, NULL, &errorCode); if (U_FAILURE(errorCode)) { log_err("Can't open a resource with key \"%s\" in \"%s\" from %s for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), rootName, locale); ures_close(subBundle); continue; } if (ures_getType(subRootBundle) != ures_getType(subBundle)) { log_err("key \"%s\" in \"%s\" has a different type from root for locale \"%s\"\n" "\troot=%d, locale=%d\n", subBundleKey, ures_getKey(currentBundle), locale, ures_getType(subRootBundle), ures_getType(subBundle)); ures_close(subBundle); continue; } else if (ures_getType(subBundle) == URES_INT_VECTOR) { int32_t minSize; int32_t subBundleSize; int32_t idx; UBool sameArray = TRUE; const int32_t *subRootBundleArr = ures_getIntVector(subRootBundle, &minSize, &errorCode); const int32_t *subBundleArr = ures_getIntVector(subBundle, &subBundleSize, &errorCode); if (minSize > subBundleSize) { minSize = subBundleSize; log_err("Arrays are different size with key \"%s\" in \"%s\" from root for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); } for (idx = 0; idx < minSize && sameArray; idx++) { if (subRootBundleArr[idx] != subBundleArr[idx]) { sameArray = FALSE; } if (strcmp(subBundleKey, "DateTimeElements") == 0 && (subBundleArr[idx] < 1 || 7 < subBundleArr[idx])) { log_err("Value out of range with key \"%s\" at index %d in \"%s\" for locale \"%s\"\n", subBundleKey, idx, ures_getKey(currentBundle), locale); } } /* Special exception es_US and DateTimeElements */ if (sameArray && !(strcmp(locale, "es_US") == 0 && strcmp(subBundleKey, "DateTimeElements") == 0)) { log_err("Integer vectors are the same with key \"%s\" in \"%s\" from root for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); } } else if (ures_getType(subBundle) == URES_ARRAY) { UResourceBundle *subSubBundle = ures_getByIndex(subBundle, 0, NULL, &errorCode); UResourceBundle *subSubRootBundle = ures_getByIndex(subRootBundle, 0, NULL, &errorCode); if (U_SUCCESS(errorCode) && (ures_getType(subSubBundle) == URES_ARRAY || ures_getType(subSubRootBundle) == URES_ARRAY)) { /* Here is one of the recursive parts */ TestKeyInRootRecursive(subRootBundle, rootName, subBundle, locale); } else { int32_t minSize = ures_getSize(subRootBundle); int32_t idx; UBool sameArray = TRUE; if (minSize > ures_getSize(subBundle)) { minSize = ures_getSize(subBundle); } if ((subBundleKey == NULL || (subBundleKey != NULL && strcmp(subBundleKey, "LocaleScript") != 0 && !isCurrencyPreEuro(subBundleKey))) && ures_getSize(subRootBundle) != ures_getSize(subBundle)) { log_err("Different size array with key \"%s\" in \"%s\" from root for locale \"%s\"\n" "\troot array size=%d, locale array size=%d\n", subBundleKey, ures_getKey(currentBundle), locale, ures_getSize(subRootBundle), ures_getSize(subBundle)); } /* if(isCurrencyPreEuro(subBundleKey) && ures_getSize(subBundle)!=3){ log_err("Different size array with key \"%s\" in \"%s\" for locale \"%s\" the expected size is 3 got size=%d\n", subBundleKey, ures_getKey(currentBundle), locale, ures_getSize(subBundle)); } */ for (idx = 0; idx < minSize; idx++) { int32_t rootStrLen, localeStrLen; const UChar *rootStr = ures_getStringByIndex(subRootBundle,idx,&rootStrLen,&errorCode); const UChar *localeStr = ures_getStringByIndex(subBundle,idx,&localeStrLen,&errorCode); if (rootStr && localeStr && U_SUCCESS(errorCode)) { if (u_strcmp(rootStr, localeStr) != 0) { sameArray = FALSE; } } else { if ( rootStrLen > 1 && rootStr[0] == 0x41 && rootStr[1] >= 0x30 && rootStr[1] <= 0x39 ) { /* A2 or A4 in the root string indicates that the resource can optionally be an array instead of a */ /* string. Attempt to read it as an array. */ errorCode = U_ZERO_ERROR; arr = ures_getByIndex(subBundle,idx,NULL,&errorCode); if (U_FAILURE(errorCode)) { log_err("Got a NULL string with key \"%s\" in \"%s\" at index %d for root or locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), idx, locale); continue; } if (ures_getType(arr) != URES_ARRAY || ures_getSize(arr) != (int32_t)rootStr[1] - 0x30) { log_err("Got something other than a string or array of size %d for key \"%s\" in \"%s\" at index %d for root or locale \"%s\"\n", rootStr[1] - 0x30, subBundleKey, ures_getKey(currentBundle), idx, locale); ures_close(arr); continue; } localeStr = ures_getStringByIndex(arr,0,&localeStrLen,&errorCode); ures_close(arr); if (U_FAILURE(errorCode)) { log_err("Got something other than a string or array for key \"%s\" in \"%s\" at index %d for root or locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), idx, locale); continue; } } else { log_err("Got a NULL string with key \"%s\" in \"%s\" at index %d for root or locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), idx, locale); continue; } } if (localeStr[0] == (UChar)0x20) { log_err("key \"%s\" at index %d in \"%s\" starts with a space in locale \"%s\"\n", subBundleKey, idx, ures_getKey(currentBundle), locale); } else if ((localeStr[localeStrLen - 1] == (UChar)0x20) && (strcmp(subBundleKey,"separator") != 0)) { log_err("key \"%s\" at index %d in \"%s\" ends with a space in locale \"%s\"\n", subBundleKey, idx, ures_getKey(currentBundle), locale); } else if (subBundleKey != NULL && strcmp(subBundleKey, "DateTimePatterns") == 0) { int32_t quoted = 0; const UChar *localeStrItr = localeStr; while (*localeStrItr) { if (*localeStrItr == (UChar)0x27 /* ' */) { quoted++; } else if ((quoted % 2) == 0) { /* Search for unquoted characters */ if (4 <= idx && idx <= 7 && (*localeStrItr == (UChar)0x6B /* k */ || *localeStrItr == (UChar)0x48 /* H */ || *localeStrItr == (UChar)0x6D /* m */ || *localeStrItr == (UChar)0x73 /* s */ || *localeStrItr == (UChar)0x53 /* S */ || *localeStrItr == (UChar)0x61 /* a */ || *localeStrItr == (UChar)0x68 /* h */ || *localeStrItr == (UChar)0x7A /* z */)) { log_err("key \"%s\" at index %d has time pattern chars in date for locale \"%s\"\n", subBundleKey, idx, locale); } else if (0 <= idx && idx <= 3 && (*localeStrItr == (UChar)0x47 /* G */ || *localeStrItr == (UChar)0x79 /* y */ || *localeStrItr == (UChar)0x4D /* M */ || *localeStrItr == (UChar)0x64 /* d */ || *localeStrItr == (UChar)0x45 /* E */ || *localeStrItr == (UChar)0x44 /* D */ || *localeStrItr == (UChar)0x46 /* F */ || *localeStrItr == (UChar)0x77 /* w */ || *localeStrItr == (UChar)0x57 /* W */)) { log_err("key \"%s\" at index %d has date pattern chars in time for locale \"%s\"\n", subBundleKey, idx, locale); } } localeStrItr++; } } else if (idx == 4 && subBundleKey != NULL && strcmp(subBundleKey, "NumberElements") == 0 && u_charDigitValue(localeStr[0]) != 0) { log_err("key \"%s\" at index %d has a non-zero based number for locale \"%s\"\n", subBundleKey, idx, locale); } } (void)sameArray; /* Suppress set but not used warning. */ /* if (sameArray && strcmp(rootName, "root") == 0) { log_err("Arrays are the same with key \"%s\" in \"%s\" from root for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); }*/ } ures_close(subSubBundle); ures_close(subSubRootBundle); } else if (ures_getType(subBundle) == URES_STRING) { int32_t len = 0; const UChar *string = ures_getString(subBundle, &len, &errorCode); if (U_FAILURE(errorCode) || string == NULL) { log_err("Can't open a string with key \"%s\" in \"%s\" for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); } else if (string[0] == (UChar)0x20) { log_err("key \"%s\" in \"%s\" starts with a space in locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); /* localeDisplayPattern/separator can end with a space */ } else if (string[len - 1] == (UChar)0x20 && (strcmp(subBundleKey,"separator"))) { log_err("key \"%s\" in \"%s\" ends with a space in locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); } else if (strcmp(subBundleKey, "localPatternChars") == 0) { /* Note: We no longer import localPatternChars data starting * ICU 3.8. So it never comes into this else if block. (ticket#5597) */ /* Check well-formedness of localPatternChars. First, the * length must match the number of fields defined by * DateFormat. Second, each character in the string must * be in the set [A-Za-z]. Finally, each character must be * unique. */ int32_t i,j; #if !UCONFIG_NO_FORMATTING if (len != UDAT_FIELD_COUNT) { log_err("key \"%s\" has the wrong number of characters in locale \"%s\"\n", subBundleKey, locale); } #endif /* Check char validity. */ for (i=0; i<len; ++i) { if (!((string[i] >= 65/*'A'*/ && string[i] <= 90/*'Z'*/) || (string[i] >= 97/*'a'*/ && string[i] <= 122/*'z'*/))) { log_err("key \"%s\" has illegal character '%c' in locale \"%s\"\n", subBundleKey, (char) string[i], locale); } /* Do O(n^2) check for duplicate chars. */ for (j=0; j<i; ++j) { if (string[j] == string[i]) { log_err("key \"%s\" has duplicate character '%c' in locale \"%s\"\n", subBundleKey, (char) string[i], locale); } } } } /* No fallback was done. Check for duplicate data */ /* The ures_* API does not do fallback of sub-resource bundles, So we can't do this now. */ #if 0 else if (strcmp(locale, "root") != 0 && errorCode == U_ZERO_ERROR) { const UChar *rootString = ures_getString(subRootBundle, &len, &errorCode); if (U_FAILURE(errorCode) || rootString == NULL) { log_err("Can't open a string with key \"%s\" in \"%s\" in root\n", ures_getKey(subRootBundle), ures_getKey(currentBundle)); continue; } else if (u_strcmp(string, rootString) == 0) { if (strcmp(locale, "de_CH") != 0 && strcmp(subBundleKey, "Countries") != 0 && strcmp(subBundleKey, "Version") != 0) { log_err("Found duplicate data with key \"%s\" in \"%s\" in locale \"%s\"\n", ures_getKey(subRootBundle), ures_getKey(currentBundle), locale); } else { /* Ignore for now. */ /* Can be fixed if fallback through de locale was done. */ log_verbose("Skipping key %s in %s\n", subBundleKey, locale); } } } #endif } else if (ures_getType(subBundle) == URES_TABLE) { if (strcmp(subBundleKey, "availableFormats")!=0) { /* Here is one of the recursive parts */ TestKeyInRootRecursive(subRootBundle, rootName, subBundle, locale); } else { log_verbose("Skipping key %s in %s\n", subBundleKey, locale); } } else if (ures_getType(subBundle) == URES_BINARY || ures_getType(subBundle) == URES_INT) { /* Can't do anything to check it */ /* We'll assume it's all correct */ if (strcmp(subBundleKey, "MeasurementSystem") != 0) { log_verbose("Skipping key \"%s\" in \"%s\" for locale \"%s\"\n", subBundleKey, ures_getKey(currentBundle), locale); } /* Testing for MeasurementSystem is done in VerifyTranslation */ } else { log_err("Type %d for key \"%s\" in \"%s\" is unknown for locale \"%s\"\n", ures_getType(subBundle), subBundleKey, ures_getKey(currentBundle), locale); } ures_close(subRootBundle); ures_close(subBundle); } } #endif static void testLCID(UResourceBundle *currentBundle, const char *localeName) { UErrorCode status = U_ZERO_ERROR; uint32_t expectedLCID; char lcidStringC[64] = {0}; int32_t len; expectedLCID = uloc_getLCID(localeName); if (expectedLCID == 0) { log_verbose("INFO: %-5s does not have any LCID mapping\n", localeName); return; } status = U_ZERO_ERROR; len = uprv_convertToPosix(expectedLCID, lcidStringC, sizeof(lcidStringC)/sizeof(lcidStringC[0]) - 1, &status); if (U_FAILURE(status)) { log_err("ERROR: %.4x does not have a POSIX mapping due to %s\n", expectedLCID, u_errorName(status)); } lcidStringC[len] = 0; if(strcmp(localeName, lcidStringC) != 0) { char langName[1024]; char langLCID[1024]; uloc_getLanguage(localeName, langName, sizeof(langName), &status); uloc_getLanguage(lcidStringC, langLCID, sizeof(langLCID), &status); if (strcmp(langName, langLCID) == 0) { log_verbose("WARNING: %-5s resolves to %s (0x%.4x)\n", localeName, lcidStringC, expectedLCID); } else { log_err("ERROR: %-5s has 0x%.4x and the number resolves wrongfully to %s\n", localeName, expectedLCID, lcidStringC); } } } #if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION static void TestLocaleStructure(void) { // This test checks the locale structure against a key file located // at source/test/testdata/structLocale.txt. When adding new data to // a locale file such as en.txt, the structLocale.txt file must be changed // too to include the the template of the new data. Otherwise this test // will fail! UResourceBundle *root, *currentLocale; int32_t locCount = uloc_countAvailable(); int32_t locIndex; UErrorCode errorCode = U_ZERO_ERROR; const char *currLoc, *resolvedLoc; /* TODO: Compare against parent's data too. This code can't handle fallbacks that some tools do already. */ /* char locName[ULOC_FULLNAME_CAPACITY]; char *locNamePtr; for (locIndex = 0; locIndex < locCount; locIndex++) { errorCode=U_ZERO_ERROR; strcpy(locName, uloc_getAvailable(locIndex)); locNamePtr = strrchr(locName, '_'); if (locNamePtr) { *locNamePtr = 0; } else { strcpy(locName, "root"); } root = ures_openDirect(NULL, locName, &errorCode); if(U_FAILURE(errorCode)) { log_err("Can't open %s\n", locName); continue; } */ if (locCount <= 1) { log_data_err("At least root needs to be installed\n"); } root = ures_openDirect(loadTestData(&errorCode), "structLocale", &errorCode); if(U_FAILURE(errorCode)) { log_data_err("Can't open structLocale\n"); return; } for (locIndex = 0; locIndex < locCount; locIndex++) { errorCode=U_ZERO_ERROR; currLoc = uloc_getAvailable(locIndex); currentLocale = ures_open(NULL, currLoc, &errorCode); if(errorCode != U_ZERO_ERROR) { if(U_SUCCESS(errorCode)) { /* It's installed, but there is no data. It's installed for the g18n white paper [grhoten] */ log_err("ERROR: Locale %-5s not installed, and it should be, err %s\n", uloc_getAvailable(locIndex), u_errorName(errorCode)); } else { log_err("%%%%%%% Unexpected error %d in %s %%%%%%%", u_errorName(errorCode), uloc_getAvailable(locIndex)); } ures_close(currentLocale); continue; } ures_getStringByKey(currentLocale, "Version", NULL, &errorCode); if(errorCode != U_ZERO_ERROR) { log_err("No version information is available for locale %s, and it should be!\n", currLoc); } else if (ures_getStringByKey(currentLocale, "Version", NULL, &errorCode)[0] == (UChar)(0x78)) { log_verbose("WARNING: The locale %s is experimental! It shouldn't be listed as an installed locale.\n", currLoc); } resolvedLoc = ures_getLocaleByType(currentLocale, ULOC_ACTUAL_LOCALE, &errorCode); if (strcmp(resolvedLoc, currLoc) != 0) { /* All locales have at least a Version resource. If it's absolutely empty, then the previous test will fail too.*/ log_err("Locale resolves to different locale. Is %s an alias of %s?\n", currLoc, resolvedLoc); } TestKeyInRootRecursive(root, "root", currentLocale, currLoc); testLCID(currentLocale, currLoc); ures_close(currentLocale); } ures_close(root); } #endif static void compareArrays(const char *keyName, UResourceBundle *fromArray, const char *fromLocale, UResourceBundle *toArray, const char *toLocale, int32_t start, int32_t end) { int32_t fromSize = ures_getSize(fromArray); int32_t toSize = ures_getSize(fromArray); int32_t idx; UErrorCode errorCode = U_ZERO_ERROR; if (fromSize > toSize) { fromSize = toSize; log_err("Arrays are different size from \"%s\" to \"%s\"\n", fromLocale, toLocale); } for (idx = start; idx <= end; idx++) { const UChar *fromBundleStr = ures_getStringByIndex(fromArray, idx, NULL, &errorCode); const UChar *toBundleStr = ures_getStringByIndex(toArray, idx, NULL, &errorCode); if (fromBundleStr && toBundleStr && u_strcmp(fromBundleStr, toBundleStr) != 0) { log_err("Difference for %s at index %d from %s= \"%s\" to %s= \"%s\"\n", keyName, idx, fromLocale, austrdup(fromBundleStr), toLocale, austrdup(toBundleStr)); } } } static void compareConsistentCountryInfo(const char *fromLocale, const char *toLocale) { UErrorCode errorCode = U_ZERO_ERROR; UResourceBundle *fromArray, *toArray; UResourceBundle *fromLocaleBund = ures_open(NULL, fromLocale, &errorCode); UResourceBundle *toLocaleBund = ures_open(NULL, toLocale, &errorCode); UResourceBundle *toCalendar, *fromCalendar, *toGregorian, *fromGregorian; if(U_FAILURE(errorCode)) { log_err("Can't open resource bundle %s or %s - %s\n", fromLocale, toLocale, u_errorName(errorCode)); return; } fromCalendar = ures_getByKey(fromLocaleBund, "calendar", NULL, &errorCode); fromGregorian = ures_getByKeyWithFallback(fromCalendar, "gregorian", NULL, &errorCode); toCalendar = ures_getByKey(toLocaleBund, "calendar", NULL, &errorCode); toGregorian = ures_getByKeyWithFallback(toCalendar, "gregorian", NULL, &errorCode); fromArray = ures_getByKey(fromLocaleBund, "CurrencyElements", NULL, &errorCode); toArray = ures_getByKey(toLocaleBund, "CurrencyElements", NULL, &errorCode); if (strcmp(fromLocale, "en_CA") != 0) { /* The first one is probably localized. */ compareArrays("CurrencyElements", fromArray, fromLocale, toArray, toLocale, 1, 2); } ures_close(fromArray); ures_close(toArray); fromArray = ures_getByKey(fromLocaleBund, "NumberPatterns", NULL, &errorCode); toArray = ures_getByKey(toLocaleBund, "NumberPatterns", NULL, &errorCode); if (strcmp(fromLocale, "en_CA") != 0) { compareArrays("NumberPatterns", fromArray, fromLocale, toArray, toLocale, 0, 3); } ures_close(fromArray); ures_close(toArray); /* Difficult to test properly */ /* fromArray = ures_getByKey(fromLocaleBund, "DateTimePatterns", NULL, &errorCode); toArray = ures_getByKey(toLocaleBund, "DateTimePatterns", NULL, &errorCode); { compareArrays("DateTimePatterns", fromArray, fromLocale, toArray, toLocale); } ures_close(fromArray); ures_close(toArray);*/ fromArray = ures_getByKey(fromLocaleBund, "NumberElements", NULL, &errorCode); toArray = ures_getByKey(toLocaleBund, "NumberElements", NULL, &errorCode); if (strcmp(fromLocale, "en_CA") != 0) { compareArrays("NumberElements", fromArray, fromLocale, toArray, toLocale, 0, 3); /* Index 4 is a script based 0 */ compareArrays("NumberElements", fromArray, fromLocale, toArray, toLocale, 5, 10); } ures_close(fromArray); ures_close(toArray); ures_close(fromCalendar); ures_close(toCalendar); ures_close(fromGregorian); ures_close(toGregorian); ures_close(fromLocaleBund); ures_close(toLocaleBund); } static void TestConsistentCountryInfo(void) { /* UResourceBundle *fromLocale, *toLocale;*/ int32_t locCount = uloc_countAvailable(); int32_t fromLocIndex, toLocIndex; int32_t fromCountryLen, toCountryLen; char fromCountry[ULOC_FULLNAME_CAPACITY], toCountry[ULOC_FULLNAME_CAPACITY]; int32_t fromVariantLen, toVariantLen; char fromVariant[ULOC_FULLNAME_CAPACITY], toVariant[ULOC_FULLNAME_CAPACITY]; UErrorCode errorCode = U_ZERO_ERROR; for (fromLocIndex = 0; fromLocIndex < locCount; fromLocIndex++) { const char *fromLocale = uloc_getAvailable(fromLocIndex); errorCode=U_ZERO_ERROR; fromCountryLen = uloc_getCountry(fromLocale, fromCountry, ULOC_FULLNAME_CAPACITY, &errorCode); if (fromCountryLen <= 0) { /* Ignore countryless locales */ continue; } fromVariantLen = uloc_getVariant(fromLocale, fromVariant, ULOC_FULLNAME_CAPACITY, &errorCode); if (fromVariantLen > 0) { /* Most variants are ignorable like PREEURO, or collation variants. */ continue; } /* Start comparing only after the current index. Previous loop should have already compared fromLocIndex. */ for (toLocIndex = fromLocIndex + 1; toLocIndex < locCount; toLocIndex++) { const char *toLocale = uloc_getAvailable(toLocIndex); toCountryLen = uloc_getCountry(toLocale, toCountry, ULOC_FULLNAME_CAPACITY, &errorCode); if(U_FAILURE(errorCode)) { log_err("Unknown failure fromLocale=%s toLocale=%s errorCode=%s\n", fromLocale, toLocale, u_errorName(errorCode)); continue; } if (toCountryLen <= 0) { /* Ignore countryless locales */ continue; } toVariantLen = uloc_getVariant(toLocale, toVariant, ULOC_FULLNAME_CAPACITY, &errorCode); if (toVariantLen > 0) { /* Most variants are ignorable like PREEURO, or collation variants. */ /* They're a variant for a reason. */ continue; } if (strcmp(fromCountry, toCountry) == 0) { log_verbose("comparing fromLocale=%s toLocale=%s\n", fromLocale, toLocale); compareConsistentCountryInfo(fromLocale, toLocale); } } } } static int32_t findStringSetMismatch(const char *currLoc, const UChar *string, int32_t langSize, USet * mergedExemplarSet, UBool ignoreNumbers, UChar* badCharPtr) { UErrorCode errorCode = U_ZERO_ERROR; USet *exemplarSet; int32_t strIdx; if (mergedExemplarSet == NULL) { return -1; } exemplarSet = createFlattenSet(mergedExemplarSet, &errorCode); if (U_FAILURE(errorCode)) { log_err("%s: error createFlattenSet returned %s\n", currLoc, u_errorName(errorCode)); return -1; } for (strIdx = 0; strIdx < langSize; strIdx++) { if (!uset_contains(exemplarSet, string[strIdx]) && string[strIdx] != 0x0020 && string[strIdx] != 0x00A0 && string[strIdx] != 0x002e && string[strIdx] != 0x002c && string[strIdx] != 0x002d && string[strIdx] != 0x0027 && string[strIdx] != 0x005B && string[strIdx] != 0x005D && string[strIdx] != 0x2019 && string[strIdx] != 0x0f0b && string[strIdx] != 0x200C && string[strIdx] != 0x200D) { if (!ignoreNumbers || (ignoreNumbers && (string[strIdx] < 0x30 || string[strIdx] > 0x39))) { uset_close(exemplarSet); if (badCharPtr) { *badCharPtr = string[strIdx]; } return strIdx; } } } uset_close(exemplarSet); if (badCharPtr) { *badCharPtr = 0; } return -1; } /* include non-invariant chars */ static int32_t myUCharsToChars(const UChar* us, char* cs, int32_t len){ int32_t i=0; for(; i< len; i++){ if(us[i] < 0x7f){ cs[i] = (char)us[i]; }else{ return -1; } } return i; } static void findSetMatch( UScriptCode *scriptCodes, int32_t scriptsLen, USet *exemplarSet, const char *locale){ USet *scripts[10]= {0}; char pattern[256] = { '[', ':', 0x000 }; int32_t patternLen; UChar uPattern[256] = {0}; UErrorCode status = U_ZERO_ERROR; int32_t i; /* create the sets with script codes */ for(i = 0; i<scriptsLen; i++){ strcat(pattern, uscript_getShortName(scriptCodes[i])); strcat(pattern, ":]"); patternLen = (int32_t)strlen(pattern); u_charsToUChars(pattern, uPattern, patternLen); scripts[i] = uset_openPattern(uPattern, patternLen, &status); if(U_FAILURE(status)){ log_err("Could not create set for pattern %s. Error: %s\n", pattern, u_errorName(status)); return; } pattern[2] = 0; } if (strcmp(locale, "uk") == 0 || strcmp(locale, "uk_UA") == 0) { /* Special addition. Add the modifying apostrophe, which isn't in Cyrillic. */ uset_add(scripts[0], 0x2bc); } if(U_SUCCESS(status)){ UBool existsInScript = FALSE; /* iterate over the exemplarSet and ascertain if all * UChars in exemplarSet belong to the scripts returned * by getScript */ int32_t count = uset_getItemCount(exemplarSet); for( i=0; i < count; i++){ UChar32 start = 0; UChar32 end = 0; UChar *str = NULL; int32_t strCapacity = 0; strCapacity = uset_getItem(exemplarSet, i, &start, &end, str, strCapacity, &status); if(U_SUCCESS(status)){ int32_t j; if(strCapacity == 0){ /* ok the item is a range */ for( j = 0; j < scriptsLen; j++){ if(uset_containsRange(scripts[j], start, end) == TRUE){ existsInScript = TRUE; } } if(existsInScript == FALSE){ for( j = 0; j < scriptsLen; j++){ UChar toPattern[500]={'\0'}; char pat[500]={'\0'}; int32_t len = uset_toPattern(scripts[j], toPattern, 500, TRUE, &status); len = myUCharsToChars(toPattern, pat, len); log_err("uset_indexOf(\\u%04X)=%i uset_indexOf(\\u%04X)=%i\n", start, uset_indexOf(scripts[0], start), end, uset_indexOf(scripts[0], end)); if(len!=-1){ log_err("Pattern: %s\n",pat); } } log_err("ExemplarCharacters and LocaleScript containment test failed for locale %s. \n", locale); } }else{ strCapacity++; /* increment for NUL termination */ /* allocate the str and call the api again */ str = (UChar*) malloc(U_SIZEOF_UCHAR * strCapacity); strCapacity = uset_getItem(exemplarSet, i, &start, &end, str, strCapacity, &status); /* iterate over the scripts and figure out if the string contained is actually * in the script set */ for( j = 0; j < scriptsLen; j++){ if(uset_containsString(scripts[j],str, strCapacity) == TRUE){ existsInScript = TRUE; } } if(existsInScript == FALSE){ log_err("ExemplarCharacters and LocaleScript containment test failed for locale %s. \n", locale); } } } } } /* close the sets */ for(i = 0; i<scriptsLen; i++){ uset_close(scripts[i]); } } static void VerifyTranslation(void) { UResourceBundle *root, *currentLocale; int32_t locCount = uloc_countAvailable(); int32_t locIndex; UErrorCode errorCode = U_ZERO_ERROR; const char *currLoc; UScriptCode scripts[USCRIPT_CODE_LIMIT]; int32_t numScripts; int32_t idx; int32_t end; UResourceBundle *resArray; if (locCount <= 1) { log_data_err("At least root needs to be installed\n"); } root = ures_openDirect(NULL, "root", &errorCode); if(U_FAILURE(errorCode)) { log_data_err("Can't open root\n"); return; } for (locIndex = 0; locIndex < locCount; locIndex++) { USet * mergedExemplarSet = NULL; errorCode=U_ZERO_ERROR; currLoc = uloc_getAvailable(locIndex); currentLocale = ures_open(NULL, currLoc, &errorCode); if(errorCode != U_ZERO_ERROR) { if(U_SUCCESS(errorCode)) { /* It's installed, but there is no data. It's installed for the g18n white paper [grhoten] */ log_err("ERROR: Locale %-5s not installed, and it should be!\n", uloc_getAvailable(locIndex)); } else { log_err("%%%%%%% Unexpected error %d in %s %%%%%%%", u_errorName(errorCode), uloc_getAvailable(locIndex)); } ures_close(currentLocale); continue; } { UErrorCode exemplarStatus = U_ZERO_ERROR; ULocaleData * uld = ulocdata_open(currLoc, &exemplarStatus); if (U_SUCCESS(exemplarStatus)) { USet * exemplarSet = ulocdata_getExemplarSet(uld, NULL, USET_ADD_CASE_MAPPINGS, ULOCDATA_ES_STANDARD, &exemplarStatus); if (U_SUCCESS(exemplarStatus)) { mergedExemplarSet = uset_cloneAsThawed(exemplarSet); uset_close(exemplarSet); exemplarSet = ulocdata_getExemplarSet(uld, NULL, USET_ADD_CASE_MAPPINGS, ULOCDATA_ES_AUXILIARY, &exemplarStatus); if (U_SUCCESS(exemplarStatus)) { uset_addAll(mergedExemplarSet, exemplarSet); uset_close(exemplarSet); } exemplarStatus = U_ZERO_ERROR; exemplarSet = ulocdata_getExemplarSet(uld, NULL, 0, ULOCDATA_ES_PUNCTUATION, &exemplarStatus); if (U_SUCCESS(exemplarStatus)) { uset_addAll(mergedExemplarSet, exemplarSet); uset_close(exemplarSet); } } else { log_err("error ulocdata_getExemplarSet (main) for locale %s returned %s\n", currLoc, u_errorName(errorCode)); } ulocdata_close(uld); } else { log_err("error ulocdata_open for locale %s returned %s\n", currLoc, u_errorName(errorCode)); } } if (mergedExemplarSet == NULL /*|| (getTestOption(QUICK_OPTION) && uset_size() > 2048)*/) { log_verbose("skipping test for %s\n", currLoc); } //else if (uprv_strncmp(currLoc,"bem",3) == 0 || uprv_strncmp(currLoc,"mgo",3) == 0 || uprv_strncmp(currLoc,"nl",2) == 0) { // log_verbose("skipping test for %s, some month and country names known to use aux exemplars\n", currLoc); //} else { UChar langBuffer[128]; int32_t langSize; int32_t strIdx; UChar badChar; langSize = uloc_getDisplayLanguage(currLoc, currLoc, langBuffer, sizeof(langBuffer)/sizeof(langBuffer[0]), &errorCode); if (U_FAILURE(errorCode)) { log_err("error uloc_getDisplayLanguage returned %s\n", u_errorName(errorCode)); } else { strIdx = findStringSetMismatch(currLoc, langBuffer, langSize, mergedExemplarSet, FALSE, &badChar); if (strIdx >= 0) { log_err("getDisplayLanguage(%s) at index %d returned characters not in the exemplar characters: %04X.\n", currLoc, strIdx, badChar); } } langSize = uloc_getDisplayCountry(currLoc, currLoc, langBuffer, sizeof(langBuffer)/sizeof(langBuffer[0]), &errorCode); if (U_FAILURE(errorCode)) { log_err("error uloc_getDisplayCountry returned %s\n", u_errorName(errorCode)); } { UResourceBundle* cal = ures_getByKey(currentLocale, "calendar", NULL, &errorCode); UResourceBundle* greg = ures_getByKeyWithFallback(cal, "gregorian", NULL, &errorCode); UResourceBundle* names = ures_getByKeyWithFallback(greg, "dayNames", NULL, &errorCode); UResourceBundle* format = ures_getByKeyWithFallback(names, "format", NULL, &errorCode); resArray = ures_getByKeyWithFallback(format, "wide", NULL, &errorCode); if (U_FAILURE(errorCode)) { log_err("error ures_getByKey returned %s\n", u_errorName(errorCode)); } if (getTestOption(QUICK_OPTION)) { end = 1; } else { end = ures_getSize(resArray); } for (idx = 0; idx < end; idx++) { const UChar *fromBundleStr = ures_getStringByIndex(resArray, idx, &langSize, &errorCode); if (U_FAILURE(errorCode)) { log_err("error ures_getStringByIndex(%d) returned %s\n", idx, u_errorName(errorCode)); continue; } strIdx = findStringSetMismatch(currLoc, fromBundleStr, langSize, mergedExemplarSet, TRUE, &badChar); if (strIdx >= 0) { log_err("getDayNames(%s, %d) at index %d returned characters not in the exemplar characters: %04X.\n", currLoc, idx, strIdx, badChar); } } ures_close(resArray); ures_close(format); ures_close(names); names = ures_getByKeyWithFallback(greg, "monthNames", NULL, &errorCode); format = ures_getByKeyWithFallback(names,"format", NULL, &errorCode); resArray = ures_getByKeyWithFallback(format, "wide", NULL, &errorCode); if (U_FAILURE(errorCode)) { log_err("error ures_getByKey returned %s\n", u_errorName(errorCode)); } if (getTestOption(QUICK_OPTION)) { end = 1; } else { end = ures_getSize(resArray); } for (idx = 0; idx < end; idx++) { const UChar *fromBundleStr = ures_getStringByIndex(resArray, idx, &langSize, &errorCode); if (U_FAILURE(errorCode)) { log_err("error ures_getStringByIndex(%d) returned %s\n", idx, u_errorName(errorCode)); continue; } strIdx = findStringSetMismatch(currLoc, fromBundleStr, langSize, mergedExemplarSet, TRUE, &badChar); if (strIdx >= 0) { log_err("getMonthNames(%s, %d) at index %d returned characters not in the exemplar characters: %04X.\n", currLoc, idx, strIdx, badChar); } } ures_close(resArray); ures_close(format); ures_close(names); ures_close(greg); ures_close(cal); } errorCode = U_ZERO_ERROR; numScripts = uscript_getCode(currLoc, scripts, sizeof(scripts)/sizeof(scripts[0]), &errorCode); if (strcmp(currLoc, "yi") == 0 && numScripts > 0 && log_knownIssue("11217", "Fix result of uscript_getCode for yi: USCRIPT_YI -> USCRIPT_HEBREW")) { scripts[0] = USCRIPT_HEBREW; } if (numScripts == 0) { log_err("uscript_getCode(%s) doesn't work.\n", currLoc); }else if(scripts[0] == USCRIPT_COMMON){ log_err("uscript_getCode(%s) returned USCRIPT_COMMON.\n", currLoc); } /* test that the scripts are a superset of exemplar characters. */ { ULocaleData *uld = ulocdata_open(currLoc,&errorCode); USet *exemplarSet = ulocdata_getExemplarSet(uld, NULL, 0, ULOCDATA_ES_STANDARD, &errorCode); /* test if exemplar characters are part of script code */ findSetMatch(scripts, numScripts, exemplarSet, currLoc); uset_close(exemplarSet); ulocdata_close(uld); } /* test that the paperSize API works */ { int32_t height=0, width=0; ulocdata_getPaperSize(currLoc, &height, &width, &errorCode); if(U_FAILURE(errorCode)){ log_err("ulocdata_getPaperSize failed for locale %s with error: %s \n", currLoc, u_errorName(errorCode)); } if(strstr(currLoc, "_US")!=NULL && height != 279 && width != 216 ){ log_err("ulocdata_getPaperSize did not return expected data for locale %s \n", currLoc); } } /* test that the MeasurementSystem API works */ { char fullLoc[ULOC_FULLNAME_CAPACITY]; UMeasurementSystem measurementSystem; int32_t height = 0, width = 0; uloc_addLikelySubtags(currLoc, fullLoc, ULOC_FULLNAME_CAPACITY, &errorCode); errorCode = U_ZERO_ERROR; measurementSystem = ulocdata_getMeasurementSystem(currLoc, &errorCode); if (U_FAILURE(errorCode)) { log_err("ulocdata_getMeasurementSystem failed for locale %s with error: %s \n", currLoc, u_errorName(errorCode)); } else { if ( strstr(fullLoc, "_US")!=NULL || strstr(fullLoc, "_MM")!=NULL || strstr(fullLoc, "_LR")!=NULL ) { if(measurementSystem != UMS_US){ log_err("ulocdata_getMeasurementSystem did not return expected data for locale %s \n", currLoc); } } else if ( strstr(fullLoc, "_GB")!=NULL ) { if(measurementSystem != UMS_UK){ log_err("ulocdata_getMeasurementSystem did not return expected data for locale %s \n", currLoc); } } else if (measurementSystem != UMS_SI) { log_err("ulocdata_getMeasurementSystem did not return expected data for locale %s \n", currLoc); } } errorCode = U_ZERO_ERROR; ulocdata_getPaperSize(currLoc, &height, &width, &errorCode); if (U_FAILURE(errorCode)) { log_err("ulocdata_getPaperSize failed for locale %s with error: %s \n", currLoc, u_errorName(errorCode)); } else { if ( strstr(fullLoc, "_US")!=NULL || strstr(fullLoc, "_BZ")!=NULL || strstr(fullLoc, "_CA")!=NULL || strstr(fullLoc, "_CL")!=NULL || strstr(fullLoc, "_CO")!=NULL || strstr(fullLoc, "_CR")!=NULL || strstr(fullLoc, "_GT")!=NULL || strstr(fullLoc, "_MX")!=NULL || strstr(fullLoc, "_NI")!=NULL || strstr(fullLoc, "_PA")!=NULL || strstr(fullLoc, "_PH")!=NULL || strstr(fullLoc, "_PR")!=NULL || strstr(fullLoc, "_SV")!=NULL || strstr(fullLoc, "_VE")!=NULL ) { if (height != 279 || width != 216) { log_err("ulocdata_getPaperSize did not return expected data for locale %s \n", currLoc); } } else if (height != 297 || width != 210) { log_err("ulocdata_getPaperSize did not return expected data for locale %s \n", currLoc); } } } } if (mergedExemplarSet != NULL) { uset_close(mergedExemplarSet); } ures_close(currentLocale); } ures_close(root); } /* adjust this limit as appropriate */ #define MAX_SCRIPTS_PER_LOCALE 8 static void TestExemplarSet(void){ int32_t i, j, k, m, n; int32_t equalCount = 0; UErrorCode ec = U_ZERO_ERROR; UEnumeration* avail; USet* exemplarSets[2]; USet* unassignedSet; UScriptCode code[MAX_SCRIPTS_PER_LOCALE]; USet* codeSets[MAX_SCRIPTS_PER_LOCALE]; int32_t codeLen; char cbuf[32]; /* 9 should be enough */ UChar ubuf[64]; /* adjust as needed */ UBool existsInScript; int32_t itemCount; int32_t strLen; UChar32 start, end; unassignedSet = NULL; exemplarSets[0] = NULL; exemplarSets[1] = NULL; for (i=0; i<MAX_SCRIPTS_PER_LOCALE; ++i) { codeSets[i] = NULL; } avail = ures_openAvailableLocales(NULL, &ec); if (!assertSuccess("ures_openAvailableLocales", &ec)) goto END; n = uenum_count(avail, &ec); if (!assertSuccess("uenum_count", &ec)) goto END; u_uastrcpy(ubuf, "[:unassigned:]"); unassignedSet = uset_openPattern(ubuf, -1, &ec); if (!assertSuccess("uset_openPattern", &ec)) goto END; for(i=0; i<n; i++){ const char* locale = uenum_next(avail, NULL, &ec); if (!assertSuccess("uenum_next", &ec)) goto END; log_verbose("%s\n", locale); for (k=0; k<2; ++k) { uint32_t option = (k==0) ? 0 : USET_CASE_INSENSITIVE; ULocaleData *uld = ulocdata_open(locale,&ec); USet* exemplarSet = ulocdata_getExemplarSet(uld,NULL, option, ULOCDATA_ES_STANDARD, &ec); uset_close(exemplarSets[k]); ulocdata_close(uld); exemplarSets[k] = exemplarSet; if (!assertSuccess("ulocaledata_getExemplarSet", &ec)) goto END; if (uset_containsSome(exemplarSet, unassignedSet)) { log_err("ExemplarSet contains unassigned characters for locale : %s\n", locale); } codeLen = uscript_getCode(locale, code, 8, &ec); if (strcmp(locale, "yi") == 0 && codeLen > 0 && log_knownIssue("11217", "Fix result of uscript_getCode for yi: USCRIPT_YI -> USCRIPT_HEBREW")) { code[0] = USCRIPT_HEBREW; } if (!assertSuccess("uscript_getCode", &ec)) goto END; for (j=0; j<MAX_SCRIPTS_PER_LOCALE; ++j) { uset_close(codeSets[j]); codeSets[j] = NULL; } for (j=0; j<codeLen; ++j) { uprv_strcpy(cbuf, "[:"); if(code[j]==-1){ log_err("USCRIPT_INVALID_CODE returned for locale: %s\n", locale); continue; } uprv_strcat(cbuf, uscript_getShortName(code[j])); uprv_strcat(cbuf, ":]"); u_uastrcpy(ubuf, cbuf); codeSets[j] = uset_openPattern(ubuf, -1, &ec); } if (!assertSuccess("uset_openPattern", &ec)) goto END; existsInScript = FALSE; itemCount = uset_getItemCount(exemplarSet); for (m=0; m<itemCount && !existsInScript; ++m) { strLen = uset_getItem(exemplarSet, m, &start, &end, ubuf, sizeof(ubuf)/sizeof(ubuf[0]), &ec); /* failure here might mean str[] needs to be larger */ if (!assertSuccess("uset_getItem", &ec)) goto END; if (strLen == 0) { for (j=0; j<codeLen; ++j) { if (codeSets[j]!=NULL && uset_containsRange(codeSets[j], start, end)) { existsInScript = TRUE; break; } } } else { for (j=0; j<codeLen; ++j) { if (codeSets[j]!=NULL && uset_containsString(codeSets[j], ubuf, strLen)) { existsInScript = TRUE; break; } } } } if (existsInScript == FALSE){ log_err("ExemplarSet containment failed for locale : %s\n", locale); } } assertTrue("case-folded is a superset", uset_containsAll(exemplarSets[1], exemplarSets[0])); if (uset_equals(exemplarSets[1], exemplarSets[0])) { ++equalCount; } } /* Note: The case-folded set should sometimes be a strict superset and sometimes be equal. */ assertTrue("case-folded is sometimes a strict superset, and sometimes equal", equalCount > 0 && equalCount < n); END: uenum_close(avail); uset_close(exemplarSets[0]); uset_close(exemplarSets[1]); uset_close(unassignedSet); for (i=0; i<MAX_SCRIPTS_PER_LOCALE; ++i) { uset_close(codeSets[i]); } } enum { kUBufMax = 32 }; static void TestLocaleDisplayPattern(void){ UErrorCode status; UChar pattern[kUBufMax] = {0,}; UChar separator[kUBufMax] = {0,}; ULocaleData *uld; static const UChar enExpectPat[] = { 0x007B,0x0030,0x007D,0x0020,0x0028,0x007B,0x0031,0x007D,0x0029,0 }; /* "{0} ({1})" */ static const UChar enExpectSep[] = { 0x002C,0x0020,0 }; /* ", " */ static const UChar zhExpectPat[] = { 0x007B,0x0030,0x007D,0xFF08,0x007B,0x0031,0x007D,0xFF09,0 }; static const UChar zhExpectSep[] = { 0x3001,0 }; status = U_ZERO_ERROR; uld = ulocdata_open("en", &status); if(U_FAILURE(status)){ log_data_err("ulocdata_open en error %s", u_errorName(status)); } else { ulocdata_getLocaleDisplayPattern(uld, pattern, kUBufMax, &status); if (U_FAILURE(status)){ log_err("ulocdata_getLocaleDisplayPattern en error %s", u_errorName(status)); } else if (u_strcmp(pattern, enExpectPat) != 0) { log_err("ulocdata_getLocaleDisplayPattern en returns unexpected pattern"); } status = U_ZERO_ERROR; ulocdata_getLocaleSeparator(uld, separator, kUBufMax, &status); if (U_FAILURE(status)){ log_err("ulocdata_getLocaleSeparator en error %s", u_errorName(status)); } else if (u_strcmp(separator, enExpectSep) != 0) { log_err("ulocdata_getLocaleSeparator en returns unexpected string "); } ulocdata_close(uld); } status = U_ZERO_ERROR; uld = ulocdata_open("zh", &status); if(U_FAILURE(status)){ log_data_err("ulocdata_open zh error %s", u_errorName(status)); } else { ulocdata_getLocaleDisplayPattern(uld, pattern, kUBufMax, &status); if (U_FAILURE(status)){ log_err("ulocdata_getLocaleDisplayPattern zh error %s", u_errorName(status)); } else if (u_strcmp(pattern, zhExpectPat) != 0) { log_err("ulocdata_getLocaleDisplayPattern zh returns unexpected pattern"); } status = U_ZERO_ERROR; ulocdata_getLocaleSeparator(uld, separator, kUBufMax, &status); if (U_FAILURE(status)){ log_err("ulocdata_getLocaleSeparator zh error %s", u_errorName(status)); } else if (u_strcmp(separator, zhExpectSep) != 0) { log_err("ulocdata_getLocaleSeparator zh returns unexpected string "); } ulocdata_close(uld); } } static void TestCoverage(void){ ULocaleDataDelimiterType types[] = { ULOCDATA_QUOTATION_START, /* Quotation start */ ULOCDATA_QUOTATION_END, /* Quotation end */ ULOCDATA_ALT_QUOTATION_START, /* Alternate quotation start */ ULOCDATA_ALT_QUOTATION_END, /* Alternate quotation end */ ULOCDATA_DELIMITER_COUNT }; int i; UBool sub; UErrorCode status = U_ZERO_ERROR; ULocaleData *uld = ulocdata_open(uloc_getDefault(), &status); if(U_FAILURE(status)){ log_data_err("ulocdata_open error"); return; } for(i = 0; i < ULOCDATA_DELIMITER_COUNT; i++){ UChar result[32] = {0,}; status = U_ZERO_ERROR; ulocdata_getDelimiter(uld, types[i], result, 32, &status); if (U_FAILURE(status)){ log_err("ulocdata_getgetDelimiter error with type %d", types[i]); } } sub = ulocdata_getNoSubstitute(uld); ulocdata_setNoSubstitute(uld,sub); ulocdata_close(uld); } static void TestIndexChars(void) { /* Very basic test of ULOCDATA_ES_INDEX. * No comprehensive test of data, just basic check that the code path is alive. */ UErrorCode status = U_ZERO_ERROR; ULocaleData *uld; USet *exemplarChars; USet *indexChars; uld = ulocdata_open("en", &status); exemplarChars = uset_openEmpty(); indexChars = uset_openEmpty(); ulocdata_getExemplarSet(uld, exemplarChars, 0, ULOCDATA_ES_STANDARD, &status); ulocdata_getExemplarSet(uld, indexChars, 0, ULOCDATA_ES_INDEX, &status); if (U_FAILURE(status)) { log_data_err("File %s, line %d, Failure opening exemplar chars: %s", __FILE__, __LINE__, u_errorName(status)); goto close_sets; } /* en data, standard exemplars are [a-z], lower case. */ /* en data, index characters are [A-Z], upper case. */ if ((uset_contains(exemplarChars, (UChar32)0x41) || uset_contains(indexChars, (UChar32)0x61))) { log_err("File %s, line %d, Exemplar characters incorrect.", __FILE__, __LINE__ ); goto close_sets; } if (!(uset_contains(exemplarChars, (UChar32)0x61) && uset_contains(indexChars, (UChar32)0x41) )) { log_err("File %s, line %d, Exemplar characters incorrect.", __FILE__, __LINE__ ); goto close_sets; } close_sets: uset_close(exemplarChars); uset_close(indexChars); ulocdata_close(uld); } #if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION static void TestCurrencyList(void){ #if !UCONFIG_NO_FORMATTING UErrorCode errorCode = U_ZERO_ERROR; int32_t structLocaleCount, currencyCount; UEnumeration *en = ucurr_openISOCurrencies(UCURR_ALL, &errorCode); const char *isoCode, *structISOCode; UResourceBundle *subBundle; UResourceBundle *currencies = ures_openDirect(loadTestData(&errorCode), "structLocale", &errorCode); if(U_FAILURE(errorCode)) { log_data_err("Can't open structLocale\n"); return; } currencies = ures_getByKey(currencies, "Currencies", currencies, &errorCode); currencyCount = uenum_count(en, &errorCode); structLocaleCount = ures_getSize(currencies); if (currencyCount != structLocaleCount) { log_err("structLocale(%d) and ISO4217(%d) currency list are out of sync.\n", structLocaleCount, currencyCount); #if U_CHARSET_FAMILY == U_ASCII_FAMILY ures_resetIterator(currencies); while ((isoCode = uenum_next(en, NULL, &errorCode)) != NULL && ures_hasNext(currencies)) { subBundle = ures_getNextResource(currencies, NULL, &errorCode); structISOCode = ures_getKey(subBundle); ures_close(subBundle); if (strcmp(structISOCode, isoCode) != 0) { log_err("First difference found at structLocale(%s) and ISO4217(%s).\n", structISOCode, isoCode); break; } } #endif } ures_close(currencies); uenum_close(en); #endif } #endif static void TestAvailableIsoCodes(void){ #if !UCONFIG_NO_FORMATTING UErrorCode errorCode = U_ZERO_ERROR; const char* eurCode = "EUR"; const char* usdCode = "USD"; const char* lastCode = "RHD"; const char* zzzCode = "ZZZ"; UDate date1950 = (UDate)-630720000000.0;/* year 1950 */ UDate date1970 = (UDate)0.0; /* year 1970 */ UDate date1975 = (UDate)173448000000.0; /* year 1975 */ UDate date1978 = (UDate)260172000000.0; /* year 1978 */ UDate date1981 = (UDate)346896000000.0; /* year 1981 */ UDate date1992 = (UDate)693792000000.0; /* year 1992 */ UChar* isoCode = (UChar*)malloc(sizeof(UChar) * (uprv_strlen(usdCode) + 1)); /* testing available codes with no time ranges */ u_charsToUChars(eurCode, isoCode, uprv_strlen(usdCode) + 1); if (ucurr_isAvailable(isoCode, U_DATE_MIN, U_DATE_MAX, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) is not found.\n", eurCode); } u_charsToUChars(usdCode, isoCode, uprv_strlen(zzzCode) + 1); if (ucurr_isAvailable(isoCode, U_DATE_MIN, U_DATE_MAX, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) is not found.\n", usdCode); } u_charsToUChars(zzzCode, isoCode, uprv_strlen(zzzCode) + 1); if (ucurr_isAvailable(isoCode, U_DATE_MIN, U_DATE_MAX, &errorCode) == TRUE) { log_err("FAIL: ISO code (%s) is reported as available, but it doesn't exist.\n", zzzCode); } u_charsToUChars(lastCode, isoCode, uprv_strlen(zzzCode) + 1); if (ucurr_isAvailable(isoCode, U_DATE_MIN, U_DATE_MAX, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) is not found.\n", lastCode); } /* RHD was used from 1970-02-17 to 1980-04-18*/ /* to = null */ if (ucurr_isAvailable(isoCode, date1970, U_DATE_MAX, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range >1970-01-01.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1975, U_DATE_MAX, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range >1975.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1981, U_DATE_MAX, &errorCode) == TRUE) { log_err("FAIL: ISO code (%s) was not available in time range >1981.\n", lastCode); } /* from = null */ if (ucurr_isAvailable(isoCode, U_DATE_MIN, date1970, &errorCode) == TRUE) { log_err("FAIL: ISO code (%s) was not available in time range <1970.\n", lastCode); } if (ucurr_isAvailable(isoCode, U_DATE_MIN, date1975, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range <1975.\n", lastCode); } if (ucurr_isAvailable(isoCode, U_DATE_MIN, date1981, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range <1981.\n", lastCode); } /* full ranges */ if (ucurr_isAvailable(isoCode, date1975, date1978, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range 1975-1978.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1970, date1975, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range 1970-1975.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1975, date1981, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range 1975-1981.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1970, date1981, &errorCode) == FALSE) { log_data_err("FAIL: ISO code (%s) was available in time range 1970-1981.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1981, date1992, &errorCode) == TRUE) { log_err("FAIL: ISO code (%s) was not available in time range 1981-1992.\n", lastCode); } if (ucurr_isAvailable(isoCode, date1950, date1970, &errorCode) == TRUE) { log_err("FAIL: ISO code (%s) was not available in time range 1950-1970.\n", lastCode); } /* wrong range - from > to*/ if (ucurr_isAvailable(isoCode, date1975, date1970, &errorCode) == TRUE) { log_err("FAIL: Wrong range 1975-1970 for ISO code (%s) was not reported.\n", lastCode); } else if (errorCode != U_ILLEGAL_ARGUMENT_ERROR) { log_data_err("FAIL: Error code not reported for wrong range 1975-1970 for ISO code (%s).\n", lastCode); } free(isoCode); #endif } #define TESTCASE(name) addTest(root, &name, "tsutil/cldrtest/" #name) void addCLDRTest(TestNode** root); void addCLDRTest(TestNode** root) { #if !UCONFIG_NO_FILE_IO && !UCONFIG_NO_LEGACY_CONVERSION TESTCASE(TestLocaleStructure); TESTCASE(TestCurrencyList); #endif TESTCASE(TestConsistentCountryInfo); TESTCASE(VerifyTranslation); TESTCASE(TestExemplarSet); TESTCASE(TestLocaleDisplayPattern); TESTCASE(TestCoverage); TESTCASE(TestIndexChars); TESTCASE(TestAvailableIsoCodes); }
mit
caidongyun/WinObjC
deps/3rdparty/icu/icu/source/test/cintltst/cdattst.c
166
79052
/******************************************************************** * COPYRIGHT: * Copyright (c) 1997-2015, International Business Machines Corporation and * others. All Rights Reserved. ********************************************************************/ /******************************************************************************** * * File CDATTST.C * * Modification History: * Name Description * Madhu Katragadda Creation ********************************************************************************* */ /* C API TEST FOR DATE FORMAT */ #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING #include "unicode/uloc.h" #include "unicode/udat.h" #include "unicode/udatpg.h" #include "unicode/ucal.h" #include "unicode/unum.h" #include "unicode/ustring.h" #include "unicode/ufieldpositer.h" #include "cintltst.h" #include "cdattst.h" #include "cformtst.h" #include "cmemory.h" #include <math.h> static void TestExtremeDates(void); static void TestAllLocales(void); static void TestRelativeCrash(void); static void TestContext(void); static void TestCalendarDateParse(void); static void TestParseErrorReturnValue(void); static void TestFormatForFields(void); #define LEN(a) (sizeof(a)/sizeof(a[0])) void addDateForTest(TestNode** root); #define TESTCASE(x) addTest(root, &x, "tsformat/cdattst/" #x) void addDateForTest(TestNode** root) { TESTCASE(TestDateFormat); TESTCASE(TestRelativeDateFormat); TESTCASE(TestSymbols); TESTCASE(TestDateFormatCalendar); TESTCASE(TestExtremeDates); TESTCASE(TestAllLocales); TESTCASE(TestRelativeCrash); TESTCASE(TestContext); TESTCASE(TestCalendarDateParse); TESTCASE(TestOverrideNumberFormat); TESTCASE(TestParseErrorReturnValue); TESTCASE(TestFormatForFields); } /* Testing the DateFormat API */ static void TestDateFormat() { UDateFormat *def, *fr, *it, *de, *def1, *fr_pat; UDateFormat *any; UDateFormat *copy; UErrorCode status = U_ZERO_ERROR; UChar* result = NULL; const UCalendar *cal; const UNumberFormat *numformat1, *numformat2; UNumberFormat *adoptNF; UChar temp[50]; int32_t numlocales; UDate d1; int i; int32_t resultlength; int32_t resultlengthneeded; int32_t parsepos; UDate d = 837039928046.0; double num = -10456.37; /*const char* str="yyyy.MM.dd G 'at' hh:mm:ss z"; const char t[]="2/3/76 2:50 AM";*/ /*Testing udat_open() to open a dateformat */ ctest_setTimeZone(NULL, &status); log_verbose("\nTesting udat_open() with various parameters\n"); fr = udat_open(UDAT_FULL, UDAT_DEFAULT, "fr_FR", NULL,0, NULL, 0,&status); if(U_FAILURE(status)) { log_data_err("FAIL: error in creating the dateformat using full time style with french locale -> %s (Are you missing data?)\n", myErrorName(status) ); return; } /* this is supposed to open default date format, but later on it treats it like it is "en_US" - very bad if you try to run the tests on machine where default locale is NOT "en_US" */ /* def = udat_open(UDAT_SHORT, UDAT_SHORT, NULL, NULL, 0, &status); */ def = udat_open(UDAT_SHORT, UDAT_SHORT, "en_US", NULL, 0,NULL, 0, &status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } it = udat_open(UDAT_DEFAULT, UDAT_MEDIUM, "it_IT", NULL, 0, NULL, 0,&status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using medium date style with italian locale\n %s\n", myErrorName(status) ); return; } de = udat_open(UDAT_LONG, UDAT_LONG, "de_DE", NULL, 0, NULL, 0,&status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using long time and date styles with german locale\n %s\n", myErrorName(status)); return; } /*creating a default dateformat */ def1 = udat_open(UDAT_SHORT, UDAT_SHORT, NULL, NULL, 0,NULL, 0, &status); if(U_FAILURE(status)) { log_err("FAIL: error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } /*Testing udat_getAvailable() and udat_countAvailable()*/ log_verbose("\nTesting getAvailableLocales and countAvailable()\n"); numlocales=udat_countAvailable(); /* use something sensible w/o hardcoding the count */ if(numlocales < 0) log_data_err("FAIL: error in countAvailable\n"); log_verbose("The number of locales for which date/time formatting patterns are available is %d\n", numlocales); for(i=0;i<numlocales;i++) { UErrorCode subStatus = U_ZERO_ERROR; log_verbose("Testing open of %s\n", udat_getAvailable(i)); any = udat_open(UDAT_SHORT, UDAT_SHORT, udat_getAvailable(i), NULL ,0, NULL, 0, &subStatus); if(U_FAILURE(subStatus)) { log_data_err("FAIL: date format %s (getAvailable(%d)) is not instantiable: %s\n", udat_getAvailable(i), i, u_errorName(subStatus)); } udat_close(any); } /*Testing udat_clone()*/ log_verbose("\nTesting the udat_clone() function of date format\n"); copy=udat_clone(def, &status); if(U_FAILURE(status)){ log_err("Error in creating the clone using udat_clone: %s\n", myErrorName(status) ); } /*if(def != copy) log_err("Error in udat_clone");*/ /*how should i check for equality???? */ /*Testing udat_format()*/ log_verbose("\nTesting the udat_format() function of date format\n"); u_uastrcpy(temp, "7/10/96, 4:05 PM"); /*format using def */ resultlength=0; resultlengthneeded=udat_format(def, d, NULL, resultlength, NULL, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_format(def, d, result, resultlength, NULL, &status); } if(U_FAILURE(status) || !result) { log_err("FAIL: Error in formatting using udat_format(.....) %s\n", myErrorName(status) ); return; } else log_verbose("PASS: formatting successful\n"); if(u_strcmp(result, temp)==0) log_verbose("PASS: Date Format for US locale successful using udat_format()\n"); else { char xbuf[2048]; char gbuf[2048]; u_austrcpy(xbuf, temp); u_austrcpy(gbuf, result); log_err("FAIL: Date Format for US locale failed using udat_format() - expected %s got %s\n", xbuf, gbuf); } /*format using fr */ u_unescape("10 juil. 1996 16:05:28 heure d\\u2019\\u00E9t\\u00E9 du Pacifique", temp, 50); if(result != NULL) { free(result); result = NULL; } result=myDateFormat(fr, d); if(u_strcmp(result, temp)==0) log_verbose("PASS: Date Format for french locale successful using udat_format()\n"); else log_data_err("FAIL: Date Format for french locale failed using udat_format().\n" ); /*format using it */ u_uastrcpy(temp, "10 lug 1996, 16:05:28"); { UChar *fmtted; char g[100]; char x[100]; fmtted = myDateFormat(it,d); u_austrcpy(g, fmtted); u_austrcpy(x, temp); if(u_strcmp(fmtted, temp)==0) { log_verbose("PASS: Date Format for italian locale successful uisng udat_format() - wanted %s, got %s\n", x, g); } else { log_data_err("FAIL: Date Format for italian locale failed using udat_format() - wanted %s, got %s\n", x, g); } } /*Testing parsing using udat_parse()*/ log_verbose("\nTesting parsing using udat_parse()\n"); u_uastrcpy(temp,"2/3/76, 2:50 AM"); parsepos=0; status=U_ZERO_ERROR; d1=udat_parse(def, temp, u_strlen(temp), &parsepos, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in parsing using udat_parse(.....) %s\n", myErrorName(status) ); } else log_verbose("PASS: parsing succesful\n"); /*format it back and check for equality */ if(u_strcmp(myDateFormat(def, d1),temp)!=0) log_err("FAIL: error in parsing\n"); /*Testing parsing using udat_parse()*/ log_verbose("\nTesting parsing using udat_parse()\n"); u_uastrcpy(temp,"2/Don't parse this part"); status=U_ZERO_ERROR; d1=udat_parse(def, temp, u_strlen(temp), NULL, &status); if(status != U_PARSE_ERROR) { log_err("FAIL: udat_parse(\"bad string\") passed when it should have failed\n"); } else log_verbose("PASS: parsing succesful\n"); /*Testing udat_openPattern() */ status=U_ZERO_ERROR; log_verbose("\nTesting the udat_openPattern with a specified pattern\n"); /*for french locale */ fr_pat=udat_open(UDAT_PATTERN, UDAT_PATTERN,"fr_FR",NULL,0,temp, u_strlen(temp), &status); if(U_FAILURE(status)) { log_err("FAIL: Error in creating a date format using udat_openPattern \n %s\n", myErrorName(status) ); } else log_verbose("PASS: creating dateformat using udat_openPattern() succesful\n"); /*Testing applyPattern and toPattern */ log_verbose("\nTesting applyPattern and toPattern()\n"); udat_applyPattern(def1, FALSE, temp, u_strlen(temp)); log_verbose("Extracting the pattern\n"); resultlength=0; resultlengthneeded=udat_toPattern(def1, FALSE, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded + 1; result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(def1, FALSE, result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } if(u_strcmp(result, temp)!=0) log_err("FAIL: Error in extracting the pattern\n"); else log_verbose("PASS: applyPattern and toPattern work fine\n"); if(result != NULL) { free(result); result = NULL; } /*Testing getter and setter functions*/ /*isLenient and setLenient()*/ log_verbose("\nTesting the isLenient and setLenient properties\n"); udat_setLenient(fr, udat_isLenient(it)); if(udat_isLenient(fr) != udat_isLenient(it)) log_err("ERROR: setLenient() failed\n"); else log_verbose("PASS: setLenient() successful\n"); /*Test get2DigitYearStart set2DigitYearStart */ log_verbose("\nTesting the get and set 2DigitYearStart properties\n"); d1= udat_get2DigitYearStart(fr_pat,&status); if(U_FAILURE(status)) { log_err("ERROR: udat_get2DigitYearStart failed %s\n", myErrorName(status) ); } status = U_ZERO_ERROR; udat_set2DigitYearStart(def1 ,d1, &status); if(U_FAILURE(status)) { log_err("ERROR: udat_set2DigitYearStart failed %s\n", myErrorName(status) ); } if(udat_get2DigitYearStart(fr_pat, &status) != udat_get2DigitYearStart(def1, &status)) log_err("FAIL: error in set2DigitYearStart\n"); else log_verbose("PASS: set2DigitYearStart successful\n"); /*try setting it to another value */ udat_set2DigitYearStart(de, 2000.0, &status); if(U_FAILURE(status)){ log_verbose("ERROR: udat_set2DigitYearStart failed %s\n", myErrorName(status) ); } if(udat_get2DigitYearStart(de, &status) != 2000) log_err("FAIL: error in set2DigitYearStart\n"); else log_verbose("PASS: set2DigitYearStart successful\n"); /*Test getNumberFormat() and setNumberFormat() */ log_verbose("\nTesting the get and set NumberFormat properties of date format\n"); numformat1=udat_getNumberFormat(fr_pat); udat_setNumberFormat(def1, numformat1); numformat2=udat_getNumberFormat(def1); if(u_strcmp(myNumformat(numformat1, num), myNumformat(numformat2, num)) !=0) log_err("FAIL: error in setNumberFormat or getNumberFormat()\n"); else log_verbose("PASS:setNumberFormat and getNumberFormat succesful\n"); /*Test getNumberFormat() and adoptNumberFormat() */ log_verbose("\nTesting the get and adopt NumberFormat properties of date format\n"); adoptNF= unum_open(UNUM_DEFAULT, NULL, 0, NULL, NULL, &status); udat_adoptNumberFormat(def1, adoptNF); numformat2=udat_getNumberFormat(def1); if(u_strcmp(myNumformat(adoptNF, num), myNumformat(numformat2, num)) !=0) log_err("FAIL: error in adoptNumberFormat or getNumberFormat()\n"); else log_verbose("PASS:adoptNumberFormat and getNumberFormat succesful\n"); /*try setting the number format to another format */ numformat1=udat_getNumberFormat(def); udat_setNumberFormat(def1, numformat1); numformat2=udat_getNumberFormat(def1); if(u_strcmp(myNumformat(numformat1, num), myNumformat(numformat2, num)) !=0) log_err("FAIL: error in setNumberFormat or getNumberFormat()\n"); else log_verbose("PASS: setNumberFormat and getNumberFormat succesful\n"); /*Test getCalendar and setCalendar*/ log_verbose("\nTesting the udat_getCalendar() and udat_setCalendar() properties\n"); cal=udat_getCalendar(fr_pat); udat_setCalendar(def1, cal); if(!ucal_equivalentTo(udat_getCalendar(fr_pat), udat_getCalendar(def1))) log_err("FAIL: Error in setting and getting the calendar\n"); else log_verbose("PASS: getting and setting calendar successful\n"); if(result!=NULL) { free(result); } /*Closing the UDateForamt */ udat_close(def); udat_close(fr); udat_close(it); udat_close(de); udat_close(def1); udat_close(fr_pat); udat_close(copy); ctest_resetTimeZone(); } /* Test combined relative date formatting (relative date + non-relative time). This is a bit tricky since we can't have static test data for comparison, the relative date formatting is relative to the time the tests are run. We generate the data for comparison dynamically. However, the tests could fail if they are run right at midnight Pacific time and the call to ucal_getNow() is before midnight while the calls to udat_format are after midnight or span midnight. */ static const UDate dayInterval = 24.0*60.0*60.0*1000.0; static const UChar trdfZone[] = { 0x0055, 0x0053, 0x002F, 0x0050, 0x0061, 0x0063, 0x0069, 0x0066, 0x0069, 0x0063, 0 }; /* US/Pacific */ static const char trdfLocale[] = "en_US"; static const UChar minutesPatn[] = { 0x006D, 0x006D, 0 }; /* "mm" */ static const UChar monthLongPatn[] = { 0x004D, 0x004D, 0x004D, 0x004D, 0 }; /* "MMMM" */ static const UChar monthMediumPatn[] = { 0x004D, 0x004D, 0x004D, 0 }; /* "MMM" */ static const UChar monthShortPatn[] = { 0x004D, 0 }; /* "M" */ static const UDateFormatStyle dateStylesList[] = { UDAT_FULL, UDAT_LONG, UDAT_MEDIUM, UDAT_SHORT, UDAT_NONE }; static const UChar *monthPatnsList[] = { monthLongPatn, monthLongPatn, monthMediumPatn, monthShortPatn, NULL }; static const UChar newTimePatn[] = { 0x0048, 0x0048, 0x002C, 0x006D, 0x006D, 0 }; /* "HH,mm" */ static const UChar minutesStr[] = { 0x0034, 0x0039, 0 }; /* "49", minutes string to search for in output */ enum { kDateOrTimeOutMax = 96, kDateAndTimeOutMax = 192 }; static const UDate minutesTolerance = 2 * 60.0 * 1000.0; static const UDate daysTolerance = 2 * 24.0 * 60.0 * 60.0 * 1000.0; static void TestRelativeDateFormat() { UDate today = 0.0; const UDateFormatStyle * stylePtr; const UChar ** monthPtnPtr; UErrorCode status = U_ZERO_ERROR; UCalendar * ucal = ucal_open(trdfZone, -1, trdfLocale, UCAL_GREGORIAN, &status); if ( U_SUCCESS(status) ) { int32_t year, month, day; ucal_setMillis(ucal, ucal_getNow(), &status); year = ucal_get(ucal, UCAL_YEAR, &status); month = ucal_get(ucal, UCAL_MONTH, &status); day = ucal_get(ucal, UCAL_DATE, &status); ucal_setDateTime(ucal, year, month, day, 18, 49, 0, &status); /* set to today at 18:49:00 */ today = ucal_getMillis(ucal, &status); ucal_close(ucal); } if ( U_FAILURE(status) || today == 0.0 ) { log_data_err("Generate UDate for a specified time today fails, error %s - (Are you missing data?)\n", myErrorName(status) ); return; } for (stylePtr = dateStylesList, monthPtnPtr = monthPatnsList; *stylePtr != UDAT_NONE; ++stylePtr, ++monthPtnPtr) { UDateFormat* fmtRelDateTime; UDateFormat* fmtRelDate; UDateFormat* fmtTime; int32_t dayOffset, limit; UFieldPosition fp; UChar strDateTime[kDateAndTimeOutMax]; UChar strDate[kDateOrTimeOutMax]; UChar strTime[kDateOrTimeOutMax]; UChar * strPtr; int32_t dtpatLen; fmtRelDateTime = udat_open(UDAT_SHORT, *stylePtr | UDAT_RELATIVE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_data_err("udat_open timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s (Are you missing data?)\n", *stylePtr, myErrorName(status) ); continue; } fmtRelDate = udat_open(UDAT_NONE, *stylePtr | UDAT_RELATIVE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_err("udat_open timeStyle NONE dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); udat_close(fmtRelDateTime); continue; } fmtTime = udat_open(UDAT_SHORT, UDAT_NONE, trdfLocale, trdfZone, -1, NULL, 0, &status); if ( U_FAILURE(status) ) { log_err("udat_open timeStyle SHORT dateStyle NONE fails, error %s\n", myErrorName(status) ); udat_close(fmtRelDateTime); udat_close(fmtRelDate); continue; } dtpatLen = udat_toPatternRelativeDate(fmtRelDateTime, strDate, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPatternRelativeDate timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDate, *monthPtnPtr) == NULL || dtpatLen != u_strlen(strDate) ) { log_err("udat_toPatternRelativeDate timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) date pattern incorrect\n", *stylePtr ); } dtpatLen = udat_toPatternRelativeTime(fmtRelDateTime, strTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPatternRelativeTime timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strTime, minutesPatn) == NULL || dtpatLen != u_strlen(strTime) ) { log_err("udat_toPatternRelativeTime timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) time pattern incorrect\n", *stylePtr ); } dtpatLen = udat_toPattern(fmtRelDateTime, FALSE, strDateTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strDate) == NULL || u_strstr(strDateTime, strTime) == NULL || dtpatLen != u_strlen(strDateTime) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) dateTime pattern incorrect\n", *stylePtr ); } udat_applyPatternRelative(fmtRelDateTime, strDate, u_strlen(strDate), newTimePatn, u_strlen(newTimePatn), &status); if ( U_FAILURE(status) ) { log_err("udat_applyPatternRelative timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else { udat_toPattern(fmtRelDateTime, FALSE, strDateTime, kDateAndTimeOutMax, &status); if ( U_FAILURE(status) ) { log_err("udat_toPattern timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, newTimePatn) == NULL ) { log_err("udat_applyPatternRelative timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) didn't update time pattern\n", *stylePtr ); } } udat_applyPatternRelative(fmtRelDateTime, strDate, u_strlen(strDate), strTime, u_strlen(strTime), &status); /* restore original */ fp.field = UDAT_MINUTE_FIELD; for (dayOffset = -2, limit = 2; dayOffset <= limit; ++dayOffset) { UDate dateToUse = today + (float)dayOffset*dayInterval; udat_format(fmtRelDateTime, dateToUse, strDateTime, kDateAndTimeOutMax, &fp, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else { int32_t parsePos = 0; UDate dateResult = udat_parse(fmtRelDateTime, strDateTime, -1, &parsePos, &status); UDate dateDiff = (dateResult >= dateToUse)? dateResult - dateToUse: dateToUse - dateResult; if ( U_FAILURE(status) || dateDiff > minutesTolerance ) { log_err("udat_parse timeStyle SHORT dateStyle (%d | UDAT_RELATIVE) fails, error %s, expect approx %.1f, got %.1f, parsePos %d\n", *stylePtr, myErrorName(status), dateToUse, dateResult, parsePos ); status = U_ZERO_ERROR; } udat_format(fmtRelDate, dateToUse, strDate, kDateOrTimeOutMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle NONE dateStyle (%d | UDAT_RELATIVE) fails, error %s\n", *stylePtr, myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strDate) == NULL ) { log_err("relative date string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } else { parsePos = 0; dateResult = udat_parse(fmtRelDate, strDate, -1, &parsePos, &status); dateDiff = (dateResult >= dateToUse)? dateResult - dateToUse: dateToUse - dateResult; if ( U_FAILURE(status) || dateDiff > daysTolerance ) { log_err("udat_parse timeStyle NONE dateStyle (%d | UDAT_RELATIVE) fails, error %s, expect approx %.1f, got %.1f, parsePos %d\n", *stylePtr, myErrorName(status), dateToUse, dateResult, parsePos ); status = U_ZERO_ERROR; } } udat_format(fmtTime, dateToUse, strTime, kDateOrTimeOutMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("udat_format timeStyle SHORT dateStyle NONE fails, error %s\n", myErrorName(status) ); status = U_ZERO_ERROR; } else if ( u_strstr(strDateTime, strTime) == NULL ) { log_err("time string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } strPtr = u_strstr(strDateTime, minutesStr); if ( strPtr != NULL ) { int32_t beginIndex = strPtr - strDateTime; if ( fp.beginIndex != beginIndex ) { log_err("UFieldPosition beginIndex %d, expected %d, in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", fp.beginIndex, beginIndex, *stylePtr ); } } else { log_err("minutes string not found in udat_format timeStyle SHORT dateStyle (%d | UDAT_RELATIVE)\n", *stylePtr ); } } } udat_close(fmtRelDateTime); udat_close(fmtRelDate); udat_close(fmtTime); } } /*Testing udat_getSymbols() and udat_setSymbols() and udat_countSymbols()*/ static void TestSymbols() { UDateFormat *def, *fr, *zhChiCal; UErrorCode status = U_ZERO_ERROR; UChar *value=NULL; UChar *result = NULL; int32_t resultlength; int32_t resultlengthout; UChar *pattern; /*creating a dateformat with french locale */ log_verbose("\ncreating a date format with french locale\n"); fr = udat_open(UDAT_FULL, UDAT_DEFAULT, "fr_FR", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_data_err("error in creating the dateformat using full time style with french locale -> %s (Are you missing data?)\n", myErrorName(status) ); return; } /*creating a default dateformat */ log_verbose("\ncreating a date format with default locale\n"); /* this is supposed to open default date format, but later on it treats it like it is "en_US" - very bad if you try to run the tests on machine where default locale is NOT "en_US" */ /* def = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,NULL, NULL, 0, &status); */ def = udat_open(UDAT_DEFAULT,UDAT_DEFAULT ,"en_US", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_err("error in creating the dateformat using short date and time style\n %s\n", myErrorName(status) ); return; } /*creating a dateformat with zh locale */ log_verbose("\ncreating a date format with zh locale for chinese calendar\n"); zhChiCal = udat_open(UDAT_NONE, UDAT_FULL, "zh@calendar=chinese", NULL, 0, NULL, 0, &status); if(U_FAILURE(status)) { log_data_err("error in creating the dateformat using full date, no time, locale zh@calendar=chinese -> %s (Are you missing data?)\n", myErrorName(status) ); return; } /*Testing countSymbols, getSymbols and setSymbols*/ log_verbose("\nTesting countSymbols\n"); /*since the month names has the last string empty and week names are 1 based 1.e first string in the weeknames array is empty */ if(udat_countSymbols(def, UDAT_ERAS)!=2 || udat_countSymbols(def, UDAT_MONTHS)!=12 || udat_countSymbols(def, UDAT_SHORT_MONTHS)!=12 || udat_countSymbols(def, UDAT_WEEKDAYS)!=8 || udat_countSymbols(def, UDAT_SHORT_WEEKDAYS)!=8 || udat_countSymbols(def, UDAT_AM_PMS)!=2 || udat_countSymbols(def, UDAT_QUARTERS) != 4 || udat_countSymbols(def, UDAT_SHORT_QUARTERS) != 4 || udat_countSymbols(def, UDAT_LOCALIZED_CHARS)!=1 || udat_countSymbols(def, UDAT_SHORTER_WEEKDAYS)!=8 || udat_countSymbols(zhChiCal, UDAT_CYCLIC_YEARS_NARROW)!=60 || udat_countSymbols(zhChiCal, UDAT_ZODIAC_NAMES_NARROW)!=12) { log_err("FAIL: error in udat_countSymbols\n"); } else log_verbose("PASS: udat_countSymbols() successful\n"); /*testing getSymbols*/ log_verbose("\nTesting getSymbols\n"); pattern=(UChar*)malloc(sizeof(UChar) * 10); u_uastrcpy(pattern, "jeudi"); resultlength=0; resultlengthout=udat_getSymbols(fr, UDAT_WEEKDAYS, 5 , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(fr, UDAT_WEEKDAYS, 5, result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: Error in udat_getSymbols().... %s\n", myErrorName(status) ); } else log_verbose("PASS: getSymbols succesful\n"); if(u_strcmp(result, pattern)==0) log_verbose("PASS: getSymbols retrieved the right value\n"); else log_data_err("FAIL: getSymbols retrieved the wrong value\n"); /*run series of tests to test getsymbols regressively*/ log_verbose("\nTesting getSymbols() regressively\n"); VerifygetSymbols(fr, UDAT_WEEKDAYS, 1, "dimanche"); VerifygetSymbols(def, UDAT_WEEKDAYS, 1, "Sunday"); VerifygetSymbols(fr, UDAT_SHORT_WEEKDAYS, 7, "sam."); VerifygetSymbols(fr, UDAT_SHORTER_WEEKDAYS, 7, "sa"); VerifygetSymbols(def, UDAT_SHORT_WEEKDAYS, 7, "Sat"); VerifygetSymbols(def, UDAT_MONTHS, 11, "December"); VerifygetSymbols(def, UDAT_MONTHS, 0, "January"); VerifygetSymbols(fr, UDAT_ERAS, 0, "av. J.-C."); VerifygetSymbols(def, UDAT_AM_PMS, 0, "AM"); VerifygetSymbols(def, UDAT_AM_PMS, 1, "PM"); VerifygetSymbols(fr, UDAT_SHORT_MONTHS, 0, "janv."); VerifygetSymbols(def, UDAT_SHORT_MONTHS, 11, "Dec"); VerifygetSymbols(fr, UDAT_QUARTERS, 0, "1er trimestre"); VerifygetSymbols(def, UDAT_QUARTERS, 3, "4th quarter"); VerifygetSymbols(fr, UDAT_SHORT_QUARTERS, 1, "T2"); VerifygetSymbols(def, UDAT_SHORT_QUARTERS, 2, "Q3"); VerifygetSymbols(zhChiCal, UDAT_CYCLIC_YEARS_ABBREVIATED, 0, "\\u7532\\u5B50"); VerifygetSymbols(zhChiCal, UDAT_CYCLIC_YEARS_NARROW, 59, "\\u7678\\u4EA5"); VerifygetSymbols(zhChiCal, UDAT_ZODIAC_NAMES_ABBREVIATED, 0, "\\u9F20"); VerifygetSymbols(zhChiCal, UDAT_ZODIAC_NAMES_WIDE, 11, "\\u732A"); VerifygetSymbols(def,UDAT_LOCALIZED_CHARS, 0, "GyMdkHmsSEDFwWahKzYeugAZvcLQqVUOXxr:"); if(result != NULL) { free(result); result = NULL; } free(pattern); log_verbose("\nTesting setSymbols\n"); /*applying the pattern so that setSymbolss works */ resultlength=0; resultlengthout=udat_toPattern(fr, FALSE, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout + 1; pattern=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(fr, FALSE, pattern, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } udat_applyPattern(def, FALSE, pattern, u_strlen(pattern)); resultlength=0; resultlengthout=udat_toPattern(def, FALSE, NULL, resultlength,&status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout + 1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_toPattern(fr, FALSE,result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: error in extracting the pattern from UNumberFormat\n %s\n", myErrorName(status) ); } if(u_strcmp(result, pattern)==0) log_verbose("Pattern applied properly\n"); else log_err("pattern could not be applied properly\n"); free(pattern); /*testing set symbols */ resultlength=0; resultlengthout=udat_getSymbols(fr, UDAT_MONTHS, 11 , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; if(result != NULL) { free(result); result = NULL; } result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(fr, UDAT_MONTHS, 11, result, resultlength, &status); } if(U_FAILURE(status)) log_err("FAIL: error in getSymbols() %s\n", myErrorName(status) ); resultlength=resultlengthout+1; udat_setSymbols(def, UDAT_MONTHS, 11, result, resultlength, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in udat_setSymbols() : %s\n", myErrorName(status) ); } else log_verbose("PASS: SetSymbols successful\n"); resultlength=0; resultlengthout=udat_getSymbols(def, UDAT_MONTHS, 11, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; value=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(def, UDAT_MONTHS, 11, value, resultlength, &status); } if(U_FAILURE(status)) log_err("FAIL: error in retrieving the value using getSymbols i.e roundtrip\n"); if(u_strcmp(result, value)!=0) log_data_err("FAIL: Error in settting and getting symbols\n"); else log_verbose("PASS: setSymbols successful\n"); /*run series of tests to test setSymbols regressively*/ log_verbose("\nTesting setSymbols regressively\n"); VerifysetSymbols(def, UDAT_ERAS, 0, "BeforeChrist"); VerifysetSymbols(def, UDAT_ERA_NAMES, 1, "AnnoDomini"); VerifysetSymbols(def, UDAT_WEEKDAYS, 1, "Sundayweek"); VerifysetSymbols(def, UDAT_SHORT_WEEKDAYS, 7, "Satweek"); VerifysetSymbols(def, UDAT_NARROW_WEEKDAYS, 4, "M"); VerifysetSymbols(def, UDAT_STANDALONE_WEEKDAYS, 1, "Sonntagweek"); VerifysetSymbols(def, UDAT_STANDALONE_SHORT_WEEKDAYS, 7, "Sams"); VerifysetSymbols(def, UDAT_STANDALONE_NARROW_WEEKDAYS, 4, "V"); VerifysetSymbols(fr, UDAT_MONTHS, 11, "december"); VerifysetSymbols(fr, UDAT_SHORT_MONTHS, 0, "Jan"); VerifysetSymbols(fr, UDAT_NARROW_MONTHS, 1, "R"); VerifysetSymbols(fr, UDAT_STANDALONE_MONTHS, 11, "dezember"); VerifysetSymbols(fr, UDAT_STANDALONE_SHORT_MONTHS, 7, "Aug"); VerifysetSymbols(fr, UDAT_STANDALONE_NARROW_MONTHS, 2, "M"); VerifysetSymbols(fr, UDAT_QUARTERS, 0, "1. Quart"); VerifysetSymbols(fr, UDAT_SHORT_QUARTERS, 1, "QQ2"); VerifysetSymbols(fr, UDAT_STANDALONE_QUARTERS, 2, "3rd Quar."); VerifysetSymbols(fr, UDAT_STANDALONE_SHORT_QUARTERS, 3, "4QQ"); VerifysetSymbols(zhChiCal, UDAT_CYCLIC_YEARS_ABBREVIATED, 1, "yi-chou"); VerifysetSymbols(zhChiCal, UDAT_ZODIAC_NAMES_ABBREVIATED, 1, "Ox"); /*run series of tests to test get and setSymbols regressively*/ log_verbose("\nTesting get and set symbols regressively\n"); VerifygetsetSymbols(fr, def, UDAT_WEEKDAYS, 1); VerifygetsetSymbols(fr, def, UDAT_WEEKDAYS, 7); VerifygetsetSymbols(fr, def, UDAT_SHORT_WEEKDAYS, 1); VerifygetsetSymbols(fr, def, UDAT_SHORT_WEEKDAYS, 7); VerifygetsetSymbols(fr, def, UDAT_MONTHS, 0); VerifygetsetSymbols(fr, def, UDAT_SHORT_MONTHS, 0); VerifygetsetSymbols(fr, def, UDAT_ERAS,1); VerifygetsetSymbols(fr, def, UDAT_LOCALIZED_CHARS, 0); VerifygetsetSymbols(fr, def, UDAT_AM_PMS, 1); /*closing*/ udat_close(fr); udat_close(def); udat_close(zhChiCal); if(result != NULL) { free(result); result = NULL; } free(value); } /** * Test DateFormat(Calendar) API */ static void TestDateFormatCalendar() { UDateFormat *date=0, *time=0, *full=0; UCalendar *cal=0; UChar buf[256]; char cbuf[256]; int32_t pos; UDate when; UErrorCode ec = U_ZERO_ERROR; UChar buf1[256]; int32_t len1; const char *expected; UChar uExpected[32]; ctest_setTimeZone(NULL, &ec); /* Create a formatter for date fields. */ date = udat_open(UDAT_NONE, UDAT_SHORT, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_data_err("FAIL: udat_open(NONE, SHORT, en_US) failed with %s (Are you missing data?)\n", u_errorName(ec)); goto FAIL; } /* Create a formatter for time fields. */ time = udat_open(UDAT_SHORT, UDAT_NONE, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_open(SHORT, NONE, en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Create a full format for output */ full = udat_open(UDAT_FULL, UDAT_FULL, "en_US", NULL, 0, NULL, 0, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_open(FULL, FULL, en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Create a calendar */ cal = ucal_open(NULL, 0, "en_US", UCAL_GREGORIAN, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_open(en_US) failed with %s\n", u_errorName(ec)); goto FAIL; } /* Parse the date */ ucal_clear(cal); u_uastrcpy(buf, "4/5/2001"); pos = 0; udat_parseCalendar(date, cal, buf, -1, &pos, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_parseCalendar(4/5/2001) failed at %d with %s\n", pos, u_errorName(ec)); goto FAIL; } /* Check if formatCalendar matches the original date */ len1 = udat_formatCalendar(date, cal, buf1, UPRV_LENGTHOF(buf1), NULL, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_formatCalendar(4/5/2001) failed with %s\n", u_errorName(ec)); goto FAIL; } expected = "4/5/01"; u_uastrcpy(uExpected, expected); if (u_strlen(uExpected) != len1 || u_strncmp(uExpected, buf1, len1) != 0) { log_err("FAIL: udat_formatCalendar(4/5/2001), expected: %s", expected); } /* Parse the time */ u_uastrcpy(buf, "5:45 PM"); pos = 0; udat_parseCalendar(time, cal, buf, -1, &pos, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_parseCalendar(17:45) failed at %d with %s\n", pos, u_errorName(ec)); goto FAIL; } /* Check if formatCalendar matches the original time */ len1 = udat_formatCalendar(time, cal, buf1, UPRV_LENGTHOF(buf1), NULL, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_formatCalendar(17:45) failed with %s\n", u_errorName(ec)); goto FAIL; } expected = "5:45 PM"; u_uastrcpy(uExpected, expected); if (u_strlen(uExpected) != len1 || u_strncmp(uExpected, buf1, len1) != 0) { log_err("FAIL: udat_formatCalendar(17:45), expected: %s", expected); } /* Check result */ when = ucal_getMillis(cal, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_getMillis() failed with %s\n", u_errorName(ec)); goto FAIL; } udat_format(full, when, buf, sizeof(buf), NULL, &ec); if (U_FAILURE(ec)) { log_err("FAIL: udat_format() failed with %s\n", u_errorName(ec)); goto FAIL; } u_austrcpy(cbuf, buf); /* Thursday, April 5, 2001 5:45:00 PM PDT 986517900000 */ if (when == 986517900000.0) { log_verbose("Ok: Parsed result: %s\n", cbuf); } else { log_err("FAIL: Parsed result: %s, exp 4/5/2001 5:45 PM\n", cbuf); } FAIL: udat_close(date); udat_close(time); udat_close(full); ucal_close(cal); ctest_resetTimeZone(); } /** * Test parsing two digit year against "YY" vs. "YYYY" patterns */ static void TestCalendarDateParse() { int32_t result; UErrorCode ec = U_ZERO_ERROR; UDateFormat* simpleDateFormat = 0; int32_t parsePos = 0; int32_t twoDigitCenturyStart = 75; int32_t currentTwoDigitYear = 0; int32_t startCentury = 0; UCalendar* tempCal = 0; UCalendar* calendar = 0; U_STRING_DECL(pattern, "yyyy", 4); U_STRING_DECL(pattern2, "yy", 2); U_STRING_DECL(text, "75", 2); U_STRING_INIT(pattern, "yyyy", 4); U_STRING_INIT(pattern2, "yy", 2); U_STRING_INIT(text, "75", 2); simpleDateFormat = udat_open(UDAT_FULL, UDAT_FULL, "en-GB", 0, 0, 0, 0, &ec); if (U_FAILURE(ec)) { log_data_err("udat_open(UDAT_FULL, UDAT_FULL, \"en-GB\", 0, 0, 0, 0, &ec) failed: %s - (Are you missing data?)\n", u_errorName(ec)); return; } udat_applyPattern(simpleDateFormat, 0, pattern, u_strlen(pattern)); udat_setLenient(simpleDateFormat, 0); currentTwoDigitYear = getCurrentYear() % 100; startCentury = getCurrentYear() - currentTwoDigitYear; if (twoDigitCenturyStart > currentTwoDigitYear) { startCentury -= 100; } tempCal = ucal_open(NULL, -1, NULL, UCAL_GREGORIAN, &ec); ucal_setMillis(tempCal, 0, &ec); ucal_setDateTime(tempCal, startCentury + twoDigitCenturyStart, UCAL_JANUARY, 1, 0, 0, 0, &ec); udat_set2DigitYearStart(simpleDateFormat, ucal_getMillis(tempCal, &ec), &ec); calendar = ucal_open(NULL, -1, NULL, UCAL_GREGORIAN, &ec); ucal_setMillis(calendar, 0, &ec); ucal_setDateTime(calendar, twoDigitCenturyStart, UCAL_JANUARY, 1, 0, 0, 0, &ec); udat_parseCalendar(simpleDateFormat, calendar, text, u_strlen(text), &parsePos, &ec); /* Check result */ result = ucal_get(calendar, UCAL_YEAR, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_get(UCAL_YEAR) failed with %s\n", u_errorName(ec)); goto FAIL; } if (result != 75) { log_err("FAIL: parsed incorrect year: %d\n", result); goto FAIL; } parsePos = 0; udat_applyPattern(simpleDateFormat, 0, pattern2, u_strlen(pattern2)); udat_parseCalendar(simpleDateFormat, calendar, text, u_strlen(text), &parsePos, &ec); /* Check result */ result = ucal_get(calendar, UCAL_YEAR, &ec); if (U_FAILURE(ec)) { log_err("FAIL: ucal_get(UCAL_YEAR) failed with %s\n", u_errorName(ec)); goto FAIL; } if (result != 1975) { log_err("FAIL: parsed incorrect year: %d\n", result); goto FAIL; } FAIL: udat_close(simpleDateFormat); udat_close(tempCal); udat_close(calendar); } /*INTERNAL FUNCTIONS USED*/ static int getCurrentYear() { static int currentYear = 0; if (currentYear == 0) { UErrorCode status = U_ZERO_ERROR; UCalendar *cal = ucal_open(NULL, -1, NULL, UCAL_GREGORIAN, &status); if (!U_FAILURE(status)) { /* Get the current year from the default UCalendar */ currentYear = ucal_get(cal, UCAL_YEAR, &status); ucal_close(cal); } } return currentYear; } /* N.B.: use idx instead of index to avoid 'shadow' warnings in strict mode. */ static void VerifygetSymbols(UDateFormat* datfor, UDateFormatSymbolType type, int32_t idx, const char* expected) { UChar *pattern=NULL; UErrorCode status = U_ZERO_ERROR; UChar *result=NULL; int32_t resultlength, resultlengthout; int32_t patternSize = strlen(expected) + 1; pattern=(UChar*)malloc(sizeof(UChar) * patternSize); u_unescape(expected, pattern, patternSize); resultlength=0; resultlengthout=udat_getSymbols(datfor, type, idx , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthout+1; result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(datfor, type, idx, result, resultlength, &status); } if(U_FAILURE(status)) { log_err("FAIL: Error in udat_getSymbols()... %s\n", myErrorName(status) ); return; } if(u_strcmp(result, pattern)==0) log_verbose("PASS: getSymbols retrieved the right value\n"); else{ log_data_err("FAIL: getSymbols retrieved the wrong value\n Expected %s Got %s\n", expected, aescstrdup(result,-1) ); } free(result); free(pattern); } static void VerifysetSymbols(UDateFormat* datfor, UDateFormatSymbolType type, int32_t idx, const char* expected) { UChar *result=NULL; UChar *value=NULL; int32_t resultlength, resultlengthout; UErrorCode status = U_ZERO_ERROR; int32_t valueLen, valueSize = strlen(expected) + 1; value=(UChar*)malloc(sizeof(UChar) * valueSize); valueLen = u_unescape(expected, value, valueSize); udat_setSymbols(datfor, type, idx, value, valueLen, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in udat_setSymbols() %s\n", myErrorName(status) ); return; } resultlength=0; resultlengthout=udat_getSymbols(datfor, type, idx, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(datfor, type, idx, result, resultlength, &status); } if(U_FAILURE(status)){ log_err("FAIL: error in retrieving the value using getSymbols after setting it previously\n %s\n", myErrorName(status) ); return; } if(u_strcmp(result, value)!=0){ log_err("FAIL:Error in setting and then getting symbols\n Expected %s Got %s\n", expected, aescstrdup(result,-1) ); } else log_verbose("PASS: setSymbols successful\n"); free(value); free(result); } static void VerifygetsetSymbols(UDateFormat* from, UDateFormat* to, UDateFormatSymbolType type, int32_t idx) { UChar *result=NULL; UChar *value=NULL; int32_t resultlength, resultlengthout; UErrorCode status = U_ZERO_ERROR; resultlength=0; resultlengthout=udat_getSymbols(from, type, idx , NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; result=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(from, type, idx, result, resultlength, &status); } if(U_FAILURE(status)){ log_err("FAIL: error in getSymbols() %s\n", myErrorName(status) ); return; } resultlength=resultlengthout+1; udat_setSymbols(to, type, idx, result, resultlength, &status); if(U_FAILURE(status)) { log_err("FAIL: Error in udat_setSymbols() : %s\n", myErrorName(status) ); return; } resultlength=0; resultlengthout=udat_getSymbols(to, type, idx, NULL, resultlength, &status); if(status==U_BUFFER_OVERFLOW_ERROR){ status=U_ZERO_ERROR; resultlength=resultlengthout+1; value=(UChar*)malloc(sizeof(UChar) * resultlength); udat_getSymbols(to, type, idx, value, resultlength, &status); } if(U_FAILURE(status)){ log_err("FAIL: error in retrieving the value using getSymbols i.e roundtrip\n %s\n", myErrorName(status) ); return; } if(u_strcmp(result, value)!=0){ log_data_err("FAIL:Error in setting and then getting symbols\n Expected %s Got %s\n", austrdup(result), austrdup(value) ); } else log_verbose("PASS: setSymbols successful\n"); free(value); free(result); } static UChar* myNumformat(const UNumberFormat* numfor, double d) { UChar *result2=NULL; int32_t resultlength, resultlengthneeded; UErrorCode status = U_ZERO_ERROR; resultlength=0; resultlengthneeded=unum_formatDouble(numfor, d, NULL, resultlength, NULL, &status); if(status==U_BUFFER_OVERFLOW_ERROR) { status=U_ZERO_ERROR; resultlength=resultlengthneeded+1; /*result2=(UChar*)malloc(sizeof(UChar) * resultlength);*/ /* this leaks */ result2=(UChar*)ctst_malloc(sizeof(UChar) * resultlength); /*this won't*/ unum_formatDouble(numfor, d, result2, resultlength, NULL, &status); } if(U_FAILURE(status)) { log_err("FAIL: Error in formatting using unum_format(.....) %s\n", myErrorName(status) ); return 0; } return result2; } /** * The search depth for TestExtremeDates. The total number of * dates that will be tested is (2^EXTREME_DATES_DEPTH) - 1. */ #define EXTREME_DATES_DEPTH 8 /** * Support for TestExtremeDates (below). * * Test a single date to see whether udat_format handles it properly. */ static UBool _aux1ExtremeDates(UDateFormat* fmt, UDate date, UChar* buf, int32_t buflen, char* cbuf, UErrorCode* ec) { int32_t len = udat_format(fmt, date, buf, buflen, 0, ec); if (!assertSuccess("udat_format", ec)) return FALSE; u_austrncpy(cbuf, buf, buflen); if (len < 4) { log_err("FAIL: udat_format(%g) => \"%s\"\n", date, cbuf); } else { log_verbose("udat_format(%g) => \"%s\"\n", date, cbuf); } return TRUE; } /** * Support for TestExtremeDates (below). * * Recursively test between 'small' and 'large', up to the depth * limit specified by EXTREME_DATES_DEPTH. */ static UBool _aux2ExtremeDates(UDateFormat* fmt, UDate small, UDate large, UChar* buf, int32_t buflen, char* cbuf, int32_t count, UErrorCode* ec) { /* Logarithmic midpoint; see below */ UDate mid = (UDate) exp((log(small) + log(large)) / 2); if (count == EXTREME_DATES_DEPTH) { return TRUE; } return _aux1ExtremeDates(fmt, mid, buf, buflen, cbuf, ec) && _aux2ExtremeDates(fmt, small, mid, buf, buflen, cbuf, count+1, ec) && _aux2ExtremeDates(fmt, mid, large, buf, buflen, cbuf, count+1, ec); } /** * http://www.jtcsv.com/cgibin/icu-bugs?findid=3659 * * For certain large dates, udat_format crashes on MacOS. This test * attempts to reproduce this problem by doing a recursive logarithmic* * binary search of a predefined interval (from 'small' to 'large'). * * The limit of the search is given by EXTREME_DATES_DEPTH, above. * * *The search has to be logarithmic, not linear. A linear search of the * range 0..10^30, for example, will find 0.5*10^30, then 0.25*10^30 and * 0.75*10^30, etc. A logarithmic search will find 10^15, then 10^7.5 * and 10^22.5, etc. */ static void TestExtremeDates() { UDateFormat *fmt; UErrorCode ec; UChar buf[256]; char cbuf[256]; const double small = 1000; /* 1 sec */ const double large = 1e+30; /* well beyond usable UDate range */ /* There is no need to test larger values from 1e+30 to 1e+300; the failures occur around 1e+27, and never above 1e+30. */ ec = U_ZERO_ERROR; fmt = udat_open(UDAT_LONG, UDAT_LONG, "en_US", 0, 0, 0, 0, &ec); if (U_FAILURE(ec)) { log_data_err("FAIL: udat_open (%s) (Are you missing data?)\n", u_errorName(ec)); return; } _aux2ExtremeDates(fmt, small, large, buf, LEN(buf), cbuf, 0, &ec); udat_close(fmt); } static void TestAllLocales(void) { int32_t idx, dateIdx, timeIdx, localeCount; static const UDateFormatStyle style[] = { UDAT_FULL, UDAT_LONG, UDAT_MEDIUM, UDAT_SHORT }; localeCount = uloc_countAvailable(); for (idx = 0; idx < localeCount; idx++) { for (dateIdx = 0; dateIdx < (int32_t)(sizeof(style)/sizeof(style[0])); dateIdx++) { for (timeIdx = 0; timeIdx < (int32_t)(sizeof(style)/sizeof(style[0])); timeIdx++) { UErrorCode status = U_ZERO_ERROR; udat_close(udat_open(style[dateIdx], style[timeIdx], uloc_getAvailable(idx), NULL, 0, NULL, 0, &status)); if (U_FAILURE(status)) { log_err("FAIL: udat_open(%s) failed with (%s) dateIdx=%d, timeIdx=%d\n", uloc_getAvailable(idx), u_errorName(status), dateIdx, timeIdx); } } } } } static void TestRelativeCrash(void) { static const UChar tzName[] = { 0x0055, 0x0053, 0x002F, 0x0050, 0x0061, 0x0063, 0x0069, 0x0066, 0x0069, 0x0063, 0 }; static const UDate aDate = -631152000000.0; UErrorCode status = U_ZERO_ERROR; UErrorCode expectStatus = U_ILLEGAL_ARGUMENT_ERROR; UDateFormat icudf; icudf = udat_open(UDAT_NONE, UDAT_SHORT_RELATIVE, "en", tzName, -1, NULL, 0, &status); if ( U_SUCCESS(status) ) { const char *what = "???"; { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_set2DigitYearStart"; log_verbose("Trying %s on a relative date..\n", what); udat_set2DigitYearStart(icudf, aDate, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { /* clone works polymorphically. try it anyways */ UErrorCode subStatus = U_ZERO_ERROR; UDateFormat *oth; what = "clone"; log_verbose("Trying %s on a relative date..\n", what); oth = udat_clone(icudf, &subStatus); if(subStatus == U_ZERO_ERROR) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); udat_close(oth); /* ? */ } else { log_err("FAIL: didn't crash on %s, but got %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_get2DigitYearStart"; log_verbose("Trying %s on a relative date..\n", what); udat_get2DigitYearStart(icudf, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { /* Now udat_toPattern works for relative date formatters, unless localized is TRUE */ UErrorCode subStatus = U_ZERO_ERROR; what = "udat_toPattern"; log_verbose("Trying %s on a relative date..\n", what); udat_toPattern(icudf, TRUE,NULL,0, &subStatus); if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_applyPattern"; log_verbose("Trying %s on a relative date..\n", what); udat_applyPattern(icudf, FALSE,tzName,-1); subStatus = U_ILLEGAL_ARGUMENT_ERROR; /* what it should be, if this took an errorcode. */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UChar erabuf[32]; UErrorCode subStatus = U_ZERO_ERROR; what = "udat_getSymbols"; log_verbose("Trying %s on a relative date..\n", what); udat_getSymbols(icudf, UDAT_ERAS,0,erabuf,sizeof(erabuf)/sizeof(erabuf[0]), &subStatus); if(subStatus == U_ZERO_ERROR) { log_verbose("Success: %s returned %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got %s instead of U_ZERO_ERROR.\n", what, u_errorName(subStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; UChar symbolValue = 0x0041; what = "udat_setSymbols"; log_verbose("Trying %s on a relative date..\n", what); udat_setSymbols(icudf, UDAT_ERAS,0,&symbolValue,1, &subStatus); /* bogus values */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } { UErrorCode subStatus = U_ZERO_ERROR; what = "udat_countSymbols"; log_verbose("Trying %s on a relative date..\n", what); udat_countSymbols(icudf, UDAT_ERAS); subStatus = U_ILLEGAL_ARGUMENT_ERROR; /* should have an errorcode. */ if(subStatus == expectStatus) { log_verbose("Success: did not crash on %s, but got %s.\n", what, u_errorName(subStatus)); } else { log_err("FAIL: didn't crash on %s, but got success %s instead of %s. \n", what, u_errorName(subStatus), u_errorName(expectStatus)); } } udat_close(icudf); } else { log_data_err("FAIL: err calling udat_open() ->%s (Are you missing data?)\n", u_errorName(status)); } } static const UChar skeleton_yMMMM[] = { 0x79,0x4D,0x4D,0x4D,0x4D,0 }; /* "yMMMM"; fr maps to "MMMM y", cs maps to "LLLL y" */ static const UChar july2008_frDefault[] = { 0x6A,0x75,0x69,0x6C,0x6C,0x65,0x74,0x20,0x32,0x30,0x30,0x38,0 }; /* "juillet 2008" */ static const UChar july2008_frTitle[] = { 0x4A,0x75,0x69,0x6C,0x6C,0x65,0x74,0x20,0x32,0x30,0x30,0x38,0 }; /* "Juillet 2008" sentence-begin, standalone */ static const UChar july2008_csDefault[] = { 0x10D,0x65,0x72,0x76,0x65,0x6E,0x65,0x63,0x20,0x32,0x30,0x30,0x38,0 }; /* "c(hacek)ervenec 2008" */ static const UChar july2008_csTitle[] = { 0x10C,0x65,0x72,0x76,0x65,0x6E,0x65,0x63,0x20,0x32,0x30,0x30,0x38,0 }; /* "C(hacek)ervenec 2008" sentence-begin, uiListOrMenu */ typedef struct { const char * locale; const UChar * skeleton; UDisplayContext capitalizationContext; const UChar * expectedFormat; } TestContextItem; static const TestContextItem textContextItems[] = { { "fr", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_NONE, july2008_frDefault }, #if !UCONFIG_NO_BREAK_ITERATION { "fr", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, july2008_frDefault }, { "fr", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, july2008_frTitle }, { "fr", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, july2008_frDefault }, { "fr", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, july2008_frTitle }, #endif { "cs", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_NONE, july2008_csDefault }, #if !UCONFIG_NO_BREAK_ITERATION { "cs", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, july2008_csDefault }, { "cs", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, july2008_csTitle }, { "cs", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, july2008_csTitle }, { "cs", skeleton_yMMMM, UDISPCTX_CAPITALIZATION_FOR_STANDALONE, july2008_csDefault }, #endif { NULL, NULL, (UDisplayContext)0, NULL } }; static const UChar today_enDefault[] = { 0x74,0x6F,0x64,0x61,0x79,0 }; /* "today" */ static const UChar today_enTitle[] = { 0x54,0x6F,0x64,0x61,0x79,0 }; /* "Today" sentence-begin, uiListOrMenu, standalone */ static const UChar yesterday_enDefault[] = { 0x79,0x65,0x73,0x74,0x65,0x72,0x64,0x61,0x79,0 }; /* "yesterday" */ static const UChar yesterday_enTitle[] = { 0x59,0x65,0x73,0x74,0x65,0x72,0x64,0x61,0x79,0 }; /* "Yesterday" sentence-begin, uiListOrMenu, standalone */ static const UChar today_nbDefault[] = { 0x69,0x20,0x64,0x61,0x67,0 }; /* "i dag" */ static const UChar today_nbTitle[] = { 0x49,0x20,0x64,0x61,0x67,0 }; /* "I dag" sentence-begin, standalone */ static const UChar yesterday_nbDefault[] = { 0x69,0x20,0x67,0xE5,0x72,0 }; static const UChar yesterday_nbTitle[] = { 0x49,0x20,0x67,0xE5,0x72,0 }; typedef struct { const char * locale; UDisplayContext capitalizationContext; const UChar * expectedFormatToday; const UChar * expectedFormatYesterday; } TestRelativeContextItem; static const TestRelativeContextItem textContextRelativeItems[] = { { "en", UDISPCTX_CAPITALIZATION_NONE, today_enDefault, yesterday_enDefault }, #if !UCONFIG_NO_BREAK_ITERATION { "en", UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, today_enDefault, yesterday_enDefault }, { "en", UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, today_enTitle, yesterday_enTitle }, { "en", UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, today_enTitle, yesterday_enTitle }, { "en", UDISPCTX_CAPITALIZATION_FOR_STANDALONE, today_enTitle, yesterday_enTitle }, #endif { "nb", UDISPCTX_CAPITALIZATION_NONE, today_nbDefault, yesterday_nbDefault }, #if !UCONFIG_NO_BREAK_ITERATION { "nb", UDISPCTX_CAPITALIZATION_FOR_MIDDLE_OF_SENTENCE, today_nbDefault, yesterday_nbDefault }, { "nb", UDISPCTX_CAPITALIZATION_FOR_BEGINNING_OF_SENTENCE, today_nbTitle, yesterday_nbTitle }, { "nb", UDISPCTX_CAPITALIZATION_FOR_UI_LIST_OR_MENU, today_nbDefault, yesterday_nbDefault }, { "nb", UDISPCTX_CAPITALIZATION_FOR_STANDALONE, today_nbTitle, yesterday_nbTitle }, #endif { NULL, (UDisplayContext)0, NULL, NULL } }; static const UChar zoneGMT[] = { 0x47,0x4D,0x54,0 }; /* "GMT" */ static const UDate july022008 = 1215000000000.0; enum { kUbufMax = 64, kBbufMax = 3*kUbufMax }; static void TestContext(void) { const TestContextItem* textContextItemPtr; const TestRelativeContextItem* textRelContextItemPtr; for (textContextItemPtr = textContextItems; textContextItemPtr->locale != NULL; ++textContextItemPtr) { UErrorCode status = U_ZERO_ERROR; UDateTimePatternGenerator* udtpg = udatpg_open(textContextItemPtr->locale, &status); if ( U_SUCCESS(status) ) { UChar ubuf[kUbufMax]; int32_t len = udatpg_getBestPattern(udtpg, textContextItemPtr->skeleton, -1, ubuf, kUbufMax, &status); if ( U_SUCCESS(status) ) { UDateFormat* udfmt = udat_open(UDAT_PATTERN, UDAT_PATTERN, textContextItemPtr->locale, zoneGMT, -1, ubuf, len, &status); if ( U_SUCCESS(status) ) { udat_setContext(udfmt, textContextItemPtr->capitalizationContext, &status); if ( U_SUCCESS(status) ) { UDisplayContext getContext; len = udat_format(udfmt, july022008, ubuf, kUbufMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("FAIL: udat_format for locale %s, capitalizationContext %d, status %s\n", textContextItemPtr->locale, (int)textContextItemPtr->capitalizationContext, u_errorName(status) ); status = U_ZERO_ERROR; } else if (u_strncmp(ubuf, textContextItemPtr->expectedFormat, kUbufMax) != 0) { char bbuf1[kBbufMax]; char bbuf2[kBbufMax]; log_err("FAIL: udat_format for locale %s, capitalizationContext %d, expected %s, got %s\n", textContextItemPtr->locale, (int)textContextItemPtr->capitalizationContext, u_austrncpy(bbuf1,textContextItemPtr->expectedFormat,kUbufMax), u_austrncpy(bbuf2,ubuf,kUbufMax) ); } getContext = udat_getContext(udfmt, UDISPCTX_TYPE_CAPITALIZATION, &status); if ( U_FAILURE(status) ) { log_err("FAIL: udat_getContext for locale %s, capitalizationContext %d, status %s\n", textContextItemPtr->locale, (int)textContextItemPtr->capitalizationContext, u_errorName(status) ); } else if (getContext != textContextItemPtr->capitalizationContext) { log_err("FAIL: udat_getContext for locale %s, capitalizationContext %d, got context %d\n", textContextItemPtr->locale, (int)textContextItemPtr->capitalizationContext, (int)getContext ); } } else { log_err("FAIL: udat_setContext for locale %s, capitalizationContext %d, status %s\n", textContextItemPtr->locale, (int)textContextItemPtr->capitalizationContext, u_errorName(status) ); } udat_close(udfmt); } else { log_data_err("FAIL: udat_open for locale %s, status %s\n", textContextItemPtr->locale, u_errorName(status) ); } } else { log_err("FAIL: udatpg_getBestPattern for locale %s, status %s\n", textContextItemPtr->locale, u_errorName(status) ); } udatpg_close(udtpg); } else { log_data_err("FAIL: udatpg_open for locale %s, status %s\n", textContextItemPtr->locale, u_errorName(status) ); } } for (textRelContextItemPtr = textContextRelativeItems; textRelContextItemPtr->locale != NULL; ++textRelContextItemPtr) { UErrorCode status = U_ZERO_ERROR; UCalendar* ucal = ucal_open(zoneGMT, -1, "root", UCAL_GREGORIAN, &status); if ( U_SUCCESS(status) ) { UDateFormat* udfmt = udat_open(UDAT_NONE, UDAT_LONG_RELATIVE, textRelContextItemPtr->locale, zoneGMT, -1, NULL, 0, &status); if ( U_SUCCESS(status) ) { udat_setContext(udfmt, textRelContextItemPtr->capitalizationContext, &status); if ( U_SUCCESS(status) ) { UDate yesterday, today = ucal_getNow(); UChar ubuf[kUbufMax]; char bbuf1[kBbufMax]; char bbuf2[kBbufMax]; int32_t len = udat_format(udfmt, today, ubuf, kUbufMax, NULL, &status); (void)len; if ( U_FAILURE(status) ) { log_err("FAIL: udat_format today for locale %s, capitalizationContext %d, status %s\n", textRelContextItemPtr->locale, (int)textRelContextItemPtr->capitalizationContext, u_errorName(status) ); } else if (u_strncmp(ubuf, textRelContextItemPtr->expectedFormatToday, kUbufMax) != 0) { log_err("FAIL: udat_format today for locale %s, capitalizationContext %d, expected %s, got %s\n", textRelContextItemPtr->locale, (int)textRelContextItemPtr->capitalizationContext, u_austrncpy(bbuf1,textRelContextItemPtr->expectedFormatToday,kUbufMax), u_austrncpy(bbuf2,ubuf,kUbufMax) ); } status = U_ZERO_ERROR; ucal_setMillis(ucal, today, &status); ucal_add(ucal, UCAL_DATE, -1, &status); yesterday = ucal_getMillis(ucal, &status); if ( U_SUCCESS(status) ) { len = udat_format(udfmt, yesterday, ubuf, kUbufMax, NULL, &status); if ( U_FAILURE(status) ) { log_err("FAIL: udat_format yesterday for locale %s, capitalizationContext %d, status %s\n", textRelContextItemPtr->locale, (int)textRelContextItemPtr->capitalizationContext, u_errorName(status) ); } else if (u_strncmp(ubuf, textRelContextItemPtr->expectedFormatYesterday, kUbufMax) != 0) { log_err("FAIL: udat_format yesterday for locale %s, capitalizationContext %d, expected %s, got %s\n", textRelContextItemPtr->locale, (int)textRelContextItemPtr->capitalizationContext, u_austrncpy(bbuf1,textRelContextItemPtr->expectedFormatYesterday,kUbufMax), u_austrncpy(bbuf2,ubuf,kUbufMax) ); } } } else { log_err("FAIL: udat_setContext relative for locale %s, capitalizationContext %d, status %s\n", textRelContextItemPtr->locale, (int)textRelContextItemPtr->capitalizationContext, u_errorName(status) ); } udat_close(udfmt); } else { log_data_err("FAIL: udat_open relative for locale %s, status %s\n", textRelContextItemPtr->locale, u_errorName(status) ); } ucal_close(ucal); } else { log_data_err("FAIL: ucal_open for locale root, status %s\n", u_errorName(status) ); } } } // overrideNumberFormat[i][0] is to tell which field to set, // overrideNumberFormat[i][1] is the expected result static const char * overrideNumberFormat[][2] = { {"", "\\u521D\\u4E03 \\u521D\\u4E8C"}, {"d", "07 \\u521D\\u4E8C"}, {"do", "07 \\u521D\\u4E8C"}, {"Md", "\\u521D\\u4E03 \\u521D\\u4E8C"}, {"MdMMd", "\\u521D\\u4E03 \\u521D\\u4E8C"}, {"mixed", "\\u521D\\u4E03 \\u521D\\u4E8C"} }; static void TestOverrideNumberFormat(void) { UErrorCode status = U_ZERO_ERROR; UChar pattern[50]; UChar expected[50]; UChar fields[50]; char bbuf1[kBbufMax]; char bbuf2[kBbufMax]; const char* localeString = "zh@numbers=hanidays"; UDateFormat* fmt; const UNumberFormat* getter_result; int32_t i; u_uastrcpy(fields, "d"); u_uastrcpy(pattern,"MM d"); fmt=udat_open(UDAT_PATTERN, UDAT_PATTERN, "en_US", zoneGMT, -1, pattern, u_strlen(pattern), &status); if (!assertSuccess("udat_open()", &status)) { return; } // loop 5 times to check getter/setter for (i = 0; i < 5; i++){ UNumberFormat* overrideFmt; overrideFmt = unum_open(UNUM_DEFAULT, NULL, 0, localeString, NULL, &status); assertSuccess("unum_open()", &status); udat_adoptNumberFormatForFields(fmt, fields, overrideFmt, &status); overrideFmt = NULL; // no longer valid assertSuccess("udat_setNumberFormatForField()", &status); getter_result = udat_getNumberFormatForField(fmt, 'd'); if(getter_result == NULL) { log_err("FAIL: udat_getNumberFormatForField did not return a valid pointer\n"); } } { UNumberFormat* overrideFmt; overrideFmt = unum_open(UNUM_DEFAULT, NULL, 0, localeString, NULL, &status); assertSuccess("unum_open()", &status); udat_setNumberFormat(fmt, overrideFmt); // test the same override NF will not crash unum_close(overrideFmt); } udat_close(fmt); for (i=0; i<UPRV_LENGTHOF(overrideNumberFormat); i++){ UChar ubuf[kUbufMax]; UDateFormat* fmt2; UNumberFormat* overrideFmt2; fmt2 =udat_open(UDAT_PATTERN, UDAT_PATTERN,"en_US", zoneGMT, -1, pattern, u_strlen(pattern), &status); assertSuccess("udat_open() with en_US", &status); overrideFmt2 = unum_open(UNUM_DEFAULT, NULL, 0, localeString, NULL, &status); assertSuccess("unum_open() in loop", &status); u_uastrcpy(fields, overrideNumberFormat[i][0]); u_unescape(overrideNumberFormat[i][1], expected, UPRV_LENGTHOF(expected)); if ( strcmp(overrideNumberFormat[i][0], "") == 0 ) { // use the one w/o field udat_adoptNumberFormat(fmt2, overrideFmt2); } else if ( strcmp(overrideNumberFormat[i][0], "mixed") == 0 ) { // set 1 field at first but then full override, both(M & d) should be override const char* singleLocale = "en@numbers=hebr"; UNumberFormat* singleOverrideFmt; u_uastrcpy(fields, "d"); singleOverrideFmt = unum_open(UNUM_DEFAULT, NULL, 0, singleLocale, NULL, &status); assertSuccess("unum_open() in mixed", &status); udat_adoptNumberFormatForFields(fmt2, fields, singleOverrideFmt, &status); assertSuccess("udat_setNumberFormatForField() in mixed", &status); udat_adoptNumberFormat(fmt2, overrideFmt2); } else if ( strcmp(overrideNumberFormat[i][0], "do") == 0 ) { // o is an invalid field udat_adoptNumberFormatForFields(fmt2, fields, overrideFmt2, &status); if(status == U_INVALID_FORMAT_ERROR) { udat_close(fmt2); status = U_ZERO_ERROR; continue; } } else { udat_adoptNumberFormatForFields(fmt2, fields, overrideFmt2, &status); assertSuccess("udat_setNumberFormatForField() in loop", &status); } udat_format(fmt2, july022008, ubuf, kUbufMax, NULL, &status); assertSuccess("udat_format() july022008", &status); if (u_strncmp(ubuf, expected, kUbufMax) != 0) log_err("fail: udat_format for locale, expected %s, got %s\n", u_austrncpy(bbuf1,expected,kUbufMax), u_austrncpy(bbuf2,ubuf,kUbufMax) ); udat_close(fmt2); } } /* * Ticket #11523 * udat_parse and udat_parseCalendar should have the same error code when given the same invalid input. */ static void TestParseErrorReturnValue(void) { UErrorCode status = U_ZERO_ERROR; UErrorCode expectStatus = U_PARSE_ERROR; UDateFormat* df; UCalendar* cal; df = udat_open(UDAT_DEFAULT, UDAT_DEFAULT, NULL, NULL, -1, NULL, -1, &status); if (!assertSuccessCheck("udat_open()", &status, TRUE)) { return; } cal = ucal_open(NULL, 0, "en_US", UCAL_GREGORIAN, &status); if (!assertSuccess("ucal_open()", &status)) { return; } udat_parse(df, NULL, -1, NULL, &status); if (status != expectStatus) { log_err("%s should have been returned by udat_parse when given an invalid input, instead got - %s\n", u_errorName(expectStatus), u_errorName(status)); } status = U_ZERO_ERROR; udat_parseCalendar(df, cal, NULL, -1, NULL, &status); if (status != expectStatus) { log_err("%s should have been returned by udat_parseCalendar when given an invalid input, instead got - %s\n", u_errorName(expectStatus), u_errorName(status)); } ucal_close(cal); udat_close(df); } /* * Ticket #11553 * Test new udat_formatForFields, udat_formatCalendarForFields (and UFieldPositionIterator) */ static const char localeForFields[] = "en_US"; /* zoneGMT[]defined above */ static const UDate date2015Feb25 = 1424841000000.0; /* Wednesday, February 25, 2015 at 5:10:00 AM GMT */ typedef struct { int32_t field; int32_t beginPos; int32_t endPos; } FieldsData; static const FieldsData expectedFields[] = { { UDAT_DAY_OF_WEEK_FIELD /* 9*/, 0, 9 }, { UDAT_MONTH_FIELD /* 2*/, 11, 19 }, { UDAT_DATE_FIELD /* 3*/, 20, 22 }, { UDAT_YEAR_FIELD /* 1*/, 24, 28 }, { UDAT_HOUR1_FIELD /*15*/, 32, 33 }, { UDAT_TIME_SEPARATOR_FIELD /*35*/, 33, 34 }, { UDAT_MINUTE_FIELD /* 6*/, 34, 36 }, { UDAT_TIME_SEPARATOR_FIELD /*35*/, 36, 37 }, { UDAT_SECOND_FIELD /* 7*/, 37, 39 }, { UDAT_AM_PM_FIELD /*14*/, 40, 42 }, { UDAT_TIMEZONE_FIELD /*17*/, 43, 46 }, { -1, -1, -1 }, }; enum {kUBufFieldsLen = 128, kBBufFieldsLen = 256 }; static void TestFormatForFields(void) { UErrorCode status = U_ZERO_ERROR; UFieldPositionIterator* fpositer = ufieldpositer_open(&status); if ( U_FAILURE(status) ) { log_err("ufieldpositer_open fails, status %s\n", u_errorName(status)); } else { UDateFormat* udfmt = udat_open(UDAT_LONG, UDAT_FULL, localeForFields, zoneGMT, -1, NULL, 0, &status); UCalendar* ucal = ucal_open(zoneGMT, -1, localeForFields, UCAL_DEFAULT, &status); if ( U_FAILURE(status) ) { log_data_err("udat_open or ucal_open fails for locale %s, status %s (Are you missing data?)\n", localeForFields, u_errorName(status)); } else { int32_t ulen, field, beginPos, endPos; UChar ubuf[kUBufFieldsLen]; const FieldsData * fptr; status = U_ZERO_ERROR; ulen = udat_formatForFields(udfmt, date2015Feb25, ubuf, kUBufFieldsLen, fpositer, &status); if ( U_FAILURE(status) ) { log_err("udat_formatForFields fails, status %s\n", u_errorName(status)); } else { for (fptr = expectedFields; ; fptr++) { field = ufieldpositer_next(fpositer, &beginPos, &endPos); if (field != fptr->field || (field >= 0 && (beginPos != fptr->beginPos || endPos != fptr->endPos))) { if (fptr->field >= 0) { log_err("udat_formatForFields as \"%s\"; expect field %d range %d-%d, get field %d range %d-%d\n", aescstrdup(ubuf, ulen), fptr->field, fptr->beginPos, fptr->endPos, field, beginPos, endPos); } else { log_err("udat_formatForFields as \"%s\"; expect field < 0, get field %d range %d-%d\n", aescstrdup(ubuf, ulen), field, beginPos, endPos); } break; } if (field < 0) { break; } } } ucal_setMillis(ucal, date2015Feb25, &status); status = U_ZERO_ERROR; ulen = udat_formatCalendarForFields(udfmt, ucal, ubuf, kUBufFieldsLen, fpositer, &status); if ( U_FAILURE(status) ) { log_err("udat_formatCalendarForFields fails, status %s\n", u_errorName(status)); } else { for (fptr = expectedFields; ; fptr++) { field = ufieldpositer_next(fpositer, &beginPos, &endPos); if (field != fptr->field || (field >= 0 && (beginPos != fptr->beginPos || endPos != fptr->endPos))) { if (fptr->field >= 0) { log_err("udat_formatFudat_formatCalendarForFieldsorFields as \"%s\"; expect field %d range %d-%d, get field %d range %d-%d\n", aescstrdup(ubuf, ulen), fptr->field, fptr->beginPos, fptr->endPos, field, beginPos, endPos); } else { log_err("udat_formatCalendarForFields as \"%s\"; expect field < 0, get field %d range %d-%d\n", aescstrdup(ubuf, ulen), field, beginPos, endPos); } break; } if (field < 0) { break; } } } ucal_close(ucal); udat_close(udfmt); } ufieldpositer_close(fpositer); } } #endif /* #if !UCONFIG_NO_FORMATTING */
mit
SyllaJay/WinObjC
tools/vsimporter/src/PBX/XCBuildConfiguration.cpp
169
2003
//****************************************************************************** // // Copyright (c) 2015 Microsoft Corporation. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 "PlistFuncs.h" #include "SBLog.h" #include "utils.h" #include "XCBuildConfiguration.h" #include "PBXFileReference.h" #include "PBXObjectIdConvert.h" XCBuildConfiguration::~XCBuildConfiguration() {} XCBuildConfiguration::XCBuildConfiguration() {} XCBuildConfiguration* XCBuildConfiguration::createFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc) { XCBuildConfiguration* ret = new XCBuildConfiguration; ret->initFromPlist(id, plist, pbxDoc); return ret; } void XCBuildConfiguration::initFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc) { // Call super init PBXObject::initFromPlist(id, plist, pbxDoc); // Get name getStringForKey(plist, "name", m_name, VALUE_REQUIRED, m_parseER); // Get baseConfigurationReference getStringForKey(plist, "baseConfigurationReference", m_baseConfigurationId, VALUE_OPTIONAL, m_parseER); // Get buildSettings getStringMapForKey(plist, "buildSettings", m_buildSettings, VALUE_REQUIRED, m_parseER); } void XCBuildConfiguration::resolvePointers() { // Resolve baseConfigurationReference ptr convertObjectId(m_pbxDoc, m_baseConfigurationId, m_baseConfigurationPtr); }
mit
MasterX1582/bitcoin-becoin
src/secp256k1/src/bench_recover.c
171
1687
/********************************************************************** * Copyright (c) 2014 Pieter Wuille * * Distributed under the MIT software license, see the accompanying * * file COPYING or http://www.opensource.org/licenses/mit-license.php.* **********************************************************************/ #include "include/secp256k1.h" #include "util.h" #include "bench.h" typedef struct { secp256k1_context_t *ctx; unsigned char msg[32]; unsigned char sig[64]; } bench_recover_t; void bench_recover(void* arg) { int i; bench_recover_t *data = (bench_recover_t*)arg; unsigned char pubkey[33]; for (i = 0; i < 20000; i++) { int j; int pubkeylen = 33; CHECK(secp256k1_ecdsa_recover_compact(data->ctx, data->msg, data->sig, pubkey, &pubkeylen, 1, i % 2)); for (j = 0; j < 32; j++) { data->sig[j + 32] = data->msg[j]; /* Move former message to S. */ data->msg[j] = data->sig[j]; /* Move former R to message. */ data->sig[j] = pubkey[j + 1]; /* Move recovered pubkey X coordinate to R (which must be a valid X coordinate). */ } } } void bench_recover_setup(void* arg) { int i; bench_recover_t *data = (bench_recover_t*)arg; for (i = 0; i < 32; i++) data->msg[i] = 1 + i; for (i = 0; i < 64; i++) data->sig[i] = 65 + i; } int main(void) { bench_recover_t data; data.ctx = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); run_benchmark("ecdsa_recover", bench_recover, bench_recover_setup, NULL, &data, 10, 20000); secp256k1_context_destroy(data.ctx); return 0; }
mit
shengwen1997/stm32_pratice
firmware/peripheral/usart_dma/lib/CMSIS/DSP_Lib/Examples/arm_variance_example/system_ARMCM4.c
430
2707
/**************************************************************************//** * @file system_ARMCM4.c * @brief CMSIS Cortex-M4 Device System Source File * for CM4 Device Series * @version V1.05 * @date 26. July 2011 * * @note * Copyright (C) 2010-2011 ARM Limited. All rights reserved. * * @par * ARM Limited (ARM) is supplying this software for use with Cortex-M * processor based microcontrollers. This file can be freely distributed * within development tools that are supporting such ARM based processors. * * @par * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. * ******************************************************************************/ #include "ARMCM4.h" /*---------------------------------------------------------------------------- Define clocks *----------------------------------------------------------------------------*/ #define __HSI ( 8000000UL) #define __XTAL (12000000UL) /* Oscillator frequency */ #define __SYSTEM_CLOCK (4*__XTAL) /*---------------------------------------------------------------------------- Clock Variable definitions *----------------------------------------------------------------------------*/ uint32_t SystemCoreClock = __SYSTEM_CLOCK;/*!< System Clock Frequency (Core Clock)*/ /*---------------------------------------------------------------------------- Clock functions *----------------------------------------------------------------------------*/ void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ { SystemCoreClock = __SYSTEM_CLOCK; } /** * Initialize the system * * @param none * @return none * * @brief Setup the microcontroller system. * Initialize the System. */ void SystemInit (void) { #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) SCB->CPACR |= ((3UL << 10*2) | /* set CP10 Full Access */ (3UL << 11*2) ); /* set CP11 Full Access */ #endif SystemCoreClock = __SYSTEM_CLOCK; #ifdef __USE_GPIO ARM_GPIO0->DATA[0].WORD = 0; ARM_GPIO0->IE = 0; ARM_GPIO0->DIR = 0xff83; ARM_GPIO1->DATA[0].WORD = 0; ARM_GPIO1->IE = 0; ARM_GPIO1->DIR = 0; ARM_GPIO2->DATA[0].WORD = 0; ARM_GPIO2->IE = 0; ARM_GPIO2->DIR = 0; #endif }
mit
unbornchikken/lwip
src/lib/jpeg/jdapistd.c
432
9393
/* * jdapistd.c * * Copyright (C) 1994-1996, Thomas G. Lane. * Modified 2002-2013 by Guido Vollbeding. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains application interface code for the decompression half * of the JPEG library. These are the "standard" API routines that are * used in the normal full-decompression case. They are not used by a * transcoding-only application. Note that if an application links in * jpeg_start_decompress, it will end up linking in the entire decompressor. * We thus must separate this file from jdapimin.c to avoid linking the * whole decompression library into a transcoder. */ #define JPEG_INTERNALS #include "jinclude.h" #include "jpeglib.h" /* Forward declarations */ LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo)); /* * Decompression initialization. * jpeg_read_header must be completed before calling this. * * If a multipass operating mode was selected, this will do all but the * last pass, and thus may take a great deal of time. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL(boolean) jpeg_start_decompress (j_decompress_ptr cinfo) { if (cinfo->global_state == DSTATE_READY) { /* First call: initialize master control, select active modules */ jinit_master_decompress(cinfo); if (cinfo->buffered_image) { /* No more work here; expecting jpeg_start_output next */ cinfo->global_state = DSTATE_BUFIMAGE; return TRUE; } cinfo->global_state = DSTATE_PRELOAD; } if (cinfo->global_state == DSTATE_PRELOAD) { /* If file has multiple scans, absorb them all into the coef buffer */ if (cinfo->inputctl->has_multiple_scans) { #ifdef D_MULTISCAN_FILES_SUPPORTED for (;;) { int retcode; /* Call progress monitor hook if present */ if (cinfo->progress != NULL) (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); /* Absorb some more input */ retcode = (*cinfo->inputctl->consume_input) (cinfo); if (retcode == JPEG_SUSPENDED) return FALSE; if (retcode == JPEG_REACHED_EOI) break; /* Advance progress counter if appropriate */ if (cinfo->progress != NULL && (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) { if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) { /* jdmaster underestimated number of scans; ratchet up one scan */ cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows; } } } #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif /* D_MULTISCAN_FILES_SUPPORTED */ } cinfo->output_scan_number = cinfo->input_scan_number; } else if (cinfo->global_state != DSTATE_PRESCAN) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Perform any dummy output passes, and set up for the final pass */ return output_pass_setup(cinfo); } /* * Set up for an output pass, and perform any dummy pass(es) needed. * Common subroutine for jpeg_start_decompress and jpeg_start_output. * Entry: global_state = DSTATE_PRESCAN only if previously suspended. * Exit: If done, returns TRUE and sets global_state for proper output mode. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN. */ LOCAL(boolean) output_pass_setup (j_decompress_ptr cinfo) { if (cinfo->global_state != DSTATE_PRESCAN) { /* First call: do pass setup */ (*cinfo->master->prepare_for_output_pass) (cinfo); cinfo->output_scanline = 0; cinfo->global_state = DSTATE_PRESCAN; } /* Loop over any required dummy passes */ while (cinfo->master->is_dummy_pass) { #ifdef QUANT_2PASS_SUPPORTED /* Crank through the dummy pass */ while (cinfo->output_scanline < cinfo->output_height) { JDIMENSION last_scanline; /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Process some data */ last_scanline = cinfo->output_scanline; (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL, &cinfo->output_scanline, (JDIMENSION) 0); if (cinfo->output_scanline == last_scanline) return FALSE; /* No progress made, must suspend */ } /* Finish up dummy pass, and set up for another one */ (*cinfo->master->finish_output_pass) (cinfo); (*cinfo->master->prepare_for_output_pass) (cinfo); cinfo->output_scanline = 0; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif /* QUANT_2PASS_SUPPORTED */ } /* Ready for application to drive output pass through * jpeg_read_scanlines or jpeg_read_raw_data. */ cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING; return TRUE; } /* * Read some scanlines of data from the JPEG decompressor. * * The return value will be the number of lines actually read. * This may be less than the number requested in several cases, * including bottom of image, data source suspension, and operating * modes that emit multiple scanlines at a time. * * Note: we warn about excess calls to jpeg_read_scanlines() since * this likely signals an application programmer error. However, * an oversize buffer (max_lines > scanlines remaining) is not an error. */ GLOBAL(JDIMENSION) jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines, JDIMENSION max_lines) { JDIMENSION row_ctr; if (cinfo->global_state != DSTATE_SCANNING) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->output_scanline >= cinfo->output_height) { WARNMS(cinfo, JWRN_TOO_MUCH_DATA); return 0; } /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Process some data */ row_ctr = 0; (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines); cinfo->output_scanline += row_ctr; return row_ctr; } /* * Alternate entry point to read raw data. * Processes exactly one iMCU row per call, unless suspended. */ GLOBAL(JDIMENSION) jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data, JDIMENSION max_lines) { JDIMENSION lines_per_iMCU_row; if (cinfo->global_state != DSTATE_RAW_OK) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); if (cinfo->output_scanline >= cinfo->output_height) { WARNMS(cinfo, JWRN_TOO_MUCH_DATA); return 0; } /* Call progress monitor hook if present */ if (cinfo->progress != NULL) { cinfo->progress->pass_counter = (long) cinfo->output_scanline; cinfo->progress->pass_limit = (long) cinfo->output_height; (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo); } /* Verify that at least one iMCU row can be returned. */ lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_v_scaled_size; if (max_lines < lines_per_iMCU_row) ERREXIT(cinfo, JERR_BUFFER_SIZE); /* Decompress directly into user's buffer. */ if (! (*cinfo->coef->decompress_data) (cinfo, data)) return 0; /* suspension forced, can do nothing more */ /* OK, we processed one iMCU row. */ cinfo->output_scanline += lines_per_iMCU_row; return lines_per_iMCU_row; } /* Additional entry points for buffered-image mode. */ #ifdef D_MULTISCAN_FILES_SUPPORTED /* * Initialize for an output pass in buffered-image mode. */ GLOBAL(boolean) jpeg_start_output (j_decompress_ptr cinfo, int scan_number) { if (cinfo->global_state != DSTATE_BUFIMAGE && cinfo->global_state != DSTATE_PRESCAN) ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); /* Limit scan number to valid range */ if (scan_number <= 0) scan_number = 1; if (cinfo->inputctl->eoi_reached && scan_number > cinfo->input_scan_number) scan_number = cinfo->input_scan_number; cinfo->output_scan_number = scan_number; /* Perform any dummy output passes, and set up for the real pass */ return output_pass_setup(cinfo); } /* * Finish up after an output pass in buffered-image mode. * * Returns FALSE if suspended. The return value need be inspected only if * a suspending data source is used. */ GLOBAL(boolean) jpeg_finish_output (j_decompress_ptr cinfo) { if ((cinfo->global_state == DSTATE_SCANNING || cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) { /* Terminate this pass. */ /* We do not require the whole pass to have been completed. */ (*cinfo->master->finish_output_pass) (cinfo); cinfo->global_state = DSTATE_BUFPOST; } else if (cinfo->global_state != DSTATE_BUFPOST) { /* BUFPOST = repeat call after a suspension, anything else is error */ ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state); } /* Read markers looking for SOS or EOI */ while (cinfo->input_scan_number <= cinfo->output_scan_number && ! cinfo->inputctl->eoi_reached) { if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED) return FALSE; /* Suspend, come back later */ } cinfo->global_state = DSTATE_BUFIMAGE; return TRUE; } #endif /* D_MULTISCAN_FILES_SUPPORTED */
mit