text,length,is_long_context,metric_val,label_metric " #include #include #include #include ""bundle_info.hpp"" #include ""generated_entity_lookup.hpp"" #include ""tailf_netconf_query.hpp"" using namespace ydk; namespace cisco_ios_xe { namespace tailf_netconf_query { StartQuery::StartQuery() : input(std::make_shared()) , output(std::make_shared()) { input->parent = this; output->parent = this; yang_name = ""start-query""; yang_parent_name = ""tailf-netconf-query""; is_top_level_class = true; has_list_ancestor = false; } StartQuery::~StartQuery() { } bool StartQuery::has_data() const { if (is_presence_container) return true; return (input != nullptr && input->has_data()) || (output != nullptr && output->has_data()); } bool StartQuery::has_operation() const { return is_set(yfilter) || (input != nullptr && input->has_operation()) || (output != nullptr && output->has_operation()); } std::string StartQuery::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:start-query""; return path_buffer.str(); } std::vector > StartQuery::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr StartQuery::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""input"") { if(input == nullptr) { input = std::make_shared(); } return input; } if(child_yang_name == ""output"") { if(output == nullptr) { output = std::make_shared(); } return output; } return nullptr; } std::map> StartQuery::get_children() const { std::map> _children{}; char count_=0; if(input != nullptr) { _children[""input""] = input; } if(output != nullptr) { _children[""output""] = output; } return _children; } void StartQuery::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void StartQuery::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr StartQuery::clone_ptr() const { return std::make_shared(); } std::string StartQuery::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string StartQuery::get_bundle_name() const { return ""cisco_ios_xe""; } augment_capabilities_function StartQuery::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map, std::string> StartQuery::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool StartQuery::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""input"" || name == ""output"") return true; return false; } StartQuery::Input::Input() : foreach{YType::str, ""foreach""}, sort_by{YType::str, ""sort-by""}, limit{YType::uint32, ""limit""}, offset{YType::uint32, ""offset""}, timeout{YType::uint32, ""timeout""} , select(this, {}) { yang_name = ""input""; yang_parent_name = ""start-query""; is_top_level_class = false; has_list_ancestor = false; } StartQuery::Input::~Input() { } bool StartQuery::Input::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } for (auto const & leaf : sort_by.getYLeafs()) { if(leaf.is_set) return true; } return foreach.is_set || limit.is_set || offset.is_set || timeout.is_set; } bool StartQuery::Input::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } for (auto const & leaf : sort_by.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(foreach.yfilter) || ydk::is_set(sort_by.yfilter) || ydk::is_set(limit.yfilter) || ydk::is_set(offset.yfilter) || ydk::is_set(timeout.yfilter); } std::string StartQuery::Input::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:start-query/"" << get_segment_path(); return path_buffer.str(); } std::string StartQuery::Input::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""input""; return path_buffer.str(); } std::vector > StartQuery::Input::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (foreach.is_set || is_set(foreach.yfilter)) leaf_name_data.push_back(foreach.get_name_leafdata()); if (limit.is_set || is_set(limit.yfilter)) leaf_name_data.push_back(limit.get_name_leafdata()); if (offset.is_set || is_set(offset.yfilter)) leaf_name_data.push_back(offset.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); auto sort_by_name_datas = sort_by.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), sort_by_name_datas.begin(), sort_by_name_datas.end()); return leaf_name_data; } std::shared_ptr StartQuery::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""select"") { auto ent_ = std::make_shared(); ent_->parent = this; select.append(ent_); return ent_; } return nullptr; } std::map> StartQuery::Input::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : select.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void StartQuery::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""foreach"") { foreach = value; foreach.value_namespace = name_space; foreach.value_namespace_prefix = name_space_prefix; } if(value_path == ""sort-by"") { sort_by.append(value); } if(value_path == ""limit"") { limit = value; limit.value_namespace = name_space; limit.value_namespace_prefix = name_space_prefix; } if(value_path == ""offset"") { offset = value; offset.value_namespace = name_space; offset.value_namespace_prefix = name_space_prefix; } if(value_path == ""timeout"") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } } void StartQuery::Input::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""foreach"") { foreach.yfilter = yfilter; } if(value_path == ""sort-by"") { sort_by.yfilter = yfilter; } if(value_path == ""limit"") { limit.yfilter = yfilter; } if(value_path == ""offset"") { offset.yfilter = yfilter; } if(value_path == ""timeout"") { timeout.yfilter = yfilter; } } bool StartQuery::Input::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""select"" || name == ""foreach"" || name == ""sort-by"" || name == ""limit"" || name == ""offset"" || name == ""timeout"") return true; return false; } StartQuery::Input::Select::Select() : label{YType::str, ""label""}, expression{YType::str, ""expression""}, result_type{YType::enumeration, ""result-type""} { yang_name = ""select""; yang_parent_name = ""input""; is_top_level_class = false; has_list_ancestor = false; } StartQuery::Input::Select::~Select() { } bool StartQuery::Input::Select::has_data() const { if (is_presence_container) return true; for (auto const & leaf : result_type.getYLeafs()) { if(leaf.is_set) return true; } return label.is_set || expression.is_set; } bool StartQuery::Input::Select::has_operation() const { for (auto const & leaf : result_type.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(label.yfilter) || ydk::is_set(expression.yfilter) || ydk::is_set(result_type.yfilter); } std::string StartQuery::Input::Select::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:start-query/input/"" << get_segment_path(); return path_buffer.str(); } std::string StartQuery::Input::Select::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""select""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > StartQuery::Input::Select::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (label.is_set || is_set(label.yfilter)) leaf_name_data.push_back(label.get_name_leafdata()); if (expression.is_set || is_set(expression.yfilter)) leaf_name_data.push_back(expression.get_name_leafdata()); auto result_type_name_datas = result_type.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), result_type_name_datas.begin(), result_type_name_datas.end()); return leaf_name_data; } std::shared_ptr StartQuery::Input::Select::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> StartQuery::Input::Select::get_children() const { std::map> _children{}; char count_=0; return _children; } void StartQuery::Input::Select::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""label"") { label = value; label.value_namespace = name_space; label.value_namespace_prefix = name_space_prefix; } if(value_path == ""expression"") { expression = value; expression.value_namespace = name_space; expression.value_namespace_prefix = name_space_prefix; } if(value_path == ""result-type"") { result_type.append(value); } } void StartQuery::Input::Select::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""label"") { label.yfilter = yfilter; } if(value_path == ""expression"") { expression.yfilter = yfilter; } if(value_path == ""result-type"") { result_type.yfilter = yfilter; } } bool StartQuery::Input::Select::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""label"" || name == ""expression"" || name == ""result-type"") return true; return false; } StartQuery::Output::Output() : query_handle{YType::uint32, ""query-handle""} { yang_name = ""output""; yang_parent_name = ""start-query""; is_top_level_class = false; has_list_ancestor = false; } StartQuery::Output::~Output() { } bool StartQuery::Output::has_data() const { if (is_presence_container) return true; return query_handle.is_set; } bool StartQuery::Output::has_operation() const { return is_set(yfilter) || ydk::is_set(query_handle.yfilter); } std::string StartQuery::Output::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:start-query/"" << get_segment_path(); return path_buffer.str(); } std::string StartQuery::Output::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""output""; return path_buffer.str(); } std::vector > StartQuery::Output::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (query_handle.is_set || is_set(query_handle.yfilter)) leaf_name_data.push_back(query_handle.get_name_leafdata()); return leaf_name_data; } std::shared_ptr StartQuery::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> StartQuery::Output::get_children() const { std::map> _children{}; char count_=0; return _children; } void StartQuery::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""query-handle"") { query_handle = value; query_handle.value_namespace = name_space; query_handle.value_namespace_prefix = name_space_prefix; } } void StartQuery::Output::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""query-handle"") { query_handle.yfilter = yfilter; } } bool StartQuery::Output::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-handle"") return true; return false; } FetchQueryResult::FetchQueryResult() : input(std::make_shared()) , output(std::make_shared()) { input->parent = this; output->parent = this; yang_name = ""fetch-query-result""; yang_parent_name = ""tailf-netconf-query""; is_top_level_class = true; has_list_ancestor = false; } FetchQueryResult::~FetchQueryResult() { } bool FetchQueryResult::has_data() const { if (is_presence_container) return true; return (input != nullptr && input->has_data()) || (output != nullptr && output->has_data()); } bool FetchQueryResult::has_operation() const { return is_set(yfilter) || (input != nullptr && input->has_operation()) || (output != nullptr && output->has_operation()); } std::string FetchQueryResult::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result""; return path_buffer.str(); } std::vector > FetchQueryResult::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr FetchQueryResult::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""input"") { if(input == nullptr) { input = std::make_shared(); } return input; } if(child_yang_name == ""output"") { if(output == nullptr) { output = std::make_shared(); } return output; } return nullptr; } std::map> FetchQueryResult::get_children() const { std::map> _children{}; char count_=0; if(input != nullptr) { _children[""input""] = input; } if(output != nullptr) { _children[""output""] = output; } return _children; } void FetchQueryResult::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void FetchQueryResult::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr FetchQueryResult::clone_ptr() const { return std::make_shared(); } std::string FetchQueryResult::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string FetchQueryResult::get_bundle_name() const { return ""cisco_ios_xe""; } augment_capabilities_function FetchQueryResult::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map, std::string> FetchQueryResult::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool FetchQueryResult::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""input"" || name == ""output"") return true; return false; } FetchQueryResult::Input::Input() : query_handle{YType::uint32, ""query-handle""} { yang_name = ""input""; yang_parent_name = ""fetch-query-result""; is_top_level_class = false; has_list_ancestor = false; } FetchQueryResult::Input::~Input() { } bool FetchQueryResult::Input::has_data() const { if (is_presence_container) return true; return query_handle.is_set; } bool FetchQueryResult::Input::has_operation() const { return is_set(yfilter) || ydk::is_set(query_handle.yfilter); } std::string FetchQueryResult::Input::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result/"" << get_segment_path(); return path_buffer.str(); } std::string FetchQueryResult::Input::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""input""; return path_buffer.str(); } std::vector > FetchQueryResult::Input::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (query_handle.is_set || is_set(query_handle.yfilter)) leaf_name_data.push_back(query_handle.get_name_leafdata()); return leaf_name_data; } std::shared_ptr FetchQueryResult::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> FetchQueryResult::Input::get_children() const { std::map> _children{}; char count_=0; return _children; } void FetchQueryResult::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""query-handle"") { query_handle = value; query_handle.value_namespace = name_space; query_handle.value_namespace_prefix = name_space_prefix; } } void FetchQueryResult::Input::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""query-handle"") { query_handle.yfilter = yfilter; } } bool FetchQueryResult::Input::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-handle"") return true; return false; } FetchQueryResult::Output::Output() : query_result(std::make_shared()) { query_result->parent = this; yang_name = ""output""; yang_parent_name = ""fetch-query-result""; is_top_level_class = false; has_list_ancestor = false; } FetchQueryResult::Output::~Output() { } bool FetchQueryResult::Output::has_data() const { if (is_presence_container) return true; return (query_result != nullptr && query_result->has_data()); } bool FetchQueryResult::Output::has_operation() const { return is_set(yfilter) || (query_result != nullptr && query_result->has_operation()); } std::string FetchQueryResult::Output::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result/"" << get_segment_path(); return path_buffer.str(); } std::string FetchQueryResult::Output::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""output""; return path_buffer.str(); } std::vector > FetchQueryResult::Output::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr FetchQueryResult::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""query-result"") { if(query_result == nullptr) { query_result = std::make_shared(); } return query_result; } return nullptr; } std::map> FetchQueryResult::Output::get_children() const { std::map> _children{}; char count_=0; if(query_result != nullptr) { _children[""query-result""] = query_result; } return _children; } void FetchQueryResult::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void FetchQueryResult::Output::set_filter(const std::string & value_path, YFilter yfilter) { } bool FetchQueryResult::Output::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-result"") return true; return false; } FetchQueryResult::Output::QueryResult::QueryResult() : result(this, {}) { yang_name = ""query-result""; yang_parent_name = ""output""; is_top_level_class = false; has_list_ancestor = false; } FetchQueryResult::Output::QueryResult::~QueryResult() { } bool FetchQueryResult::Output::QueryResult::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return false; } bool FetchQueryResult::Output::QueryResult::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter); } std::string FetchQueryResult::Output::QueryResult::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result/output/"" << get_segment_path(); return path_buffer.str(); } std::string FetchQueryResult::Output::QueryResult::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""query-result""; return path_buffer.str(); } std::vector > FetchQueryResult::Output::QueryResult::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr FetchQueryResult::Output::QueryResult::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""result"") { auto ent_ = std::make_shared(); ent_->parent = this; result.append(ent_); return ent_; } return nullptr; } std::map> FetchQueryResult::Output::QueryResult::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : result.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void FetchQueryResult::Output::QueryResult::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void FetchQueryResult::Output::QueryResult::set_filter(const std::string & value_path, YFilter yfilter) { } bool FetchQueryResult::Output::QueryResult::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""result"") return true; return false; } FetchQueryResult::Output::QueryResult::Result::Result() : select(this, {}) { yang_name = ""result""; yang_parent_name = ""query-result""; is_top_level_class = false; has_list_ancestor = false; } FetchQueryResult::Output::QueryResult::Result::~Result() { } bool FetchQueryResult::Output::QueryResult::Result::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return false; } bool FetchQueryResult::Output::QueryResult::Result::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter); } std::string FetchQueryResult::Output::QueryResult::Result::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result/output/query-result/"" << get_segment_path(); return path_buffer.str(); } std::string FetchQueryResult::Output::QueryResult::Result::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""result""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > FetchQueryResult::Output::QueryResult::Result::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr FetchQueryResult::Output::QueryResult::Result::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""select"") { auto ent_ = std::make_shared(); ent_->parent = this; select.append(ent_); return ent_; } return nullptr; } std::map> FetchQueryResult::Output::QueryResult::Result::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : select.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void FetchQueryResult::Output::QueryResult::Result::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void FetchQueryResult::Output::QueryResult::Result::set_filter(const std::string & value_path, YFilter yfilter) { } bool FetchQueryResult::Output::QueryResult::Result::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""select"") return true; return false; } FetchQueryResult::Output::QueryResult::Result::Select::Select() : label{YType::str, ""label""}, path{YType::str, ""path""}, value_{YType::str, ""value""}, data{YType::str, ""data""} { yang_name = ""select""; yang_parent_name = ""result""; is_top_level_class = false; has_list_ancestor = false; } FetchQueryResult::Output::QueryResult::Result::Select::~Select() { } bool FetchQueryResult::Output::QueryResult::Result::Select::has_data() const { if (is_presence_container) return true; return label.is_set || path.is_set || value_.is_set || data.is_set; } bool FetchQueryResult::Output::QueryResult::Result::Select::has_operation() const { return is_set(yfilter) || ydk::is_set(label.yfilter) || ydk::is_set(path.yfilter) || ydk::is_set(value_.yfilter) || ydk::is_set(data.yfilter); } std::string FetchQueryResult::Output::QueryResult::Result::Select::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:fetch-query-result/output/query-result/result/"" << get_segment_path(); return path_buffer.str(); } std::string FetchQueryResult::Output::QueryResult::Result::Select::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""select""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > FetchQueryResult::Output::QueryResult::Result::Select::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (label.is_set || is_set(label.yfilter)) leaf_name_data.push_back(label.get_name_leafdata()); if (path.is_set || is_set(path.yfilter)) leaf_name_data.push_back(path.get_name_leafdata()); if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata()); if (data.is_set || is_set(data.yfilter)) leaf_name_data.push_back(data.get_name_leafdata()); return leaf_name_data; } std::shared_ptr FetchQueryResult::Output::QueryResult::Result::Select::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> FetchQueryResult::Output::QueryResult::Result::Select::get_children() const { std::map> _children{}; char count_=0; return _children; } void FetchQueryResult::Output::QueryResult::Result::Select::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""label"") { label = value; label.value_namespace = name_space; label.value_namespace_prefix = name_space_prefix; } if(value_path == ""path"") { path = value; path.value_namespace = name_space; path.value_namespace_prefix = name_space_prefix; } if(value_path == ""value"") { value_ = value; value_.value_namespace = name_space; value_.value_namespace_prefix = name_space_prefix; } if(value_path == ""data"") { data = value; data.value_namespace = name_space; data.value_namespace_prefix = name_space_prefix; } } void FetchQueryResult::Output::QueryResult::Result::Select::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""label"") { label.yfilter = yfilter; } if(value_path == ""path"") { path.yfilter = yfilter; } if(value_path == ""value"") { value_.yfilter = yfilter; } if(value_path == ""data"") { data.yfilter = yfilter; } } bool FetchQueryResult::Output::QueryResult::Result::Select::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""label"" || name == ""path"" || name == ""value"" || name == ""data"") return true; return false; } ImmediateQuery::ImmediateQuery() : input(std::make_shared()) , output(std::make_shared()) { input->parent = this; output->parent = this; yang_name = ""immediate-query""; yang_parent_name = ""tailf-netconf-query""; is_top_level_class = true; has_list_ancestor = false; } ImmediateQuery::~ImmediateQuery() { } bool ImmediateQuery::has_data() const { if (is_presence_container) return true; return (input != nullptr && input->has_data()) || (output != nullptr && output->has_data()); } bool ImmediateQuery::has_operation() const { return is_set(yfilter) || (input != nullptr && input->has_operation()) || (output != nullptr && output->has_operation()); } std::string ImmediateQuery::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query""; return path_buffer.str(); } std::vector > ImmediateQuery::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr ImmediateQuery::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""input"") { if(input == nullptr) { input = std::make_shared(); } return input; } if(child_yang_name == ""output"") { if(output == nullptr) { output = std::make_shared(); } return output; } return nullptr; } std::map> ImmediateQuery::get_children() const { std::map> _children{}; char count_=0; if(input != nullptr) { _children[""input""] = input; } if(output != nullptr) { _children[""output""] = output; } return _children; } void ImmediateQuery::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void ImmediateQuery::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr ImmediateQuery::clone_ptr() const { return std::make_shared(); } std::string ImmediateQuery::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string ImmediateQuery::get_bundle_name() const { return ""cisco_ios_xe""; } augment_capabilities_function ImmediateQuery::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map, std::string> ImmediateQuery::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool ImmediateQuery::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""input"" || name == ""output"") return true; return false; } ImmediateQuery::Input::Input() : foreach{YType::str, ""foreach""}, sort_by{YType::str, ""sort-by""}, limit{YType::uint32, ""limit""}, offset{YType::uint32, ""offset""}, timeout{YType::uint32, ""timeout""} , select(this, {}) { yang_name = ""input""; yang_parent_name = ""immediate-query""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Input::~Input() { } bool ImmediateQuery::Input::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } for (auto const & leaf : sort_by.getYLeafs()) { if(leaf.is_set) return true; } return foreach.is_set || limit.is_set || offset.is_set || timeout.is_set; } bool ImmediateQuery::Input::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } for (auto const & leaf : sort_by.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(foreach.yfilter) || ydk::is_set(sort_by.yfilter) || ydk::is_set(limit.yfilter) || ydk::is_set(offset.yfilter) || ydk::is_set(timeout.yfilter); } std::string ImmediateQuery::Input::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Input::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""input""; return path_buffer.str(); } std::vector > ImmediateQuery::Input::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (foreach.is_set || is_set(foreach.yfilter)) leaf_name_data.push_back(foreach.get_name_leafdata()); if (limit.is_set || is_set(limit.yfilter)) leaf_name_data.push_back(limit.get_name_leafdata()); if (offset.is_set || is_set(offset.yfilter)) leaf_name_data.push_back(offset.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); auto sort_by_name_datas = sort_by.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), sort_by_name_datas.begin(), sort_by_name_datas.end()); return leaf_name_data; } std::shared_ptr ImmediateQuery::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""select"") { auto ent_ = std::make_shared(); ent_->parent = this; select.append(ent_); return ent_; } return nullptr; } std::map> ImmediateQuery::Input::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : select.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void ImmediateQuery::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""foreach"") { foreach = value; foreach.value_namespace = name_space; foreach.value_namespace_prefix = name_space_prefix; } if(value_path == ""sort-by"") { sort_by.append(value); } if(value_path == ""limit"") { limit = value; limit.value_namespace = name_space; limit.value_namespace_prefix = name_space_prefix; } if(value_path == ""offset"") { offset = value; offset.value_namespace = name_space; offset.value_namespace_prefix = name_space_prefix; } if(value_path == ""timeout"") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } } void ImmediateQuery::Input::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""foreach"") { foreach.yfilter = yfilter; } if(value_path == ""sort-by"") { sort_by.yfilter = yfilter; } if(value_path == ""limit"") { limit.yfilter = yfilter; } if(value_path == ""offset"") { offset.yfilter = yfilter; } if(value_path == ""timeout"") { timeout.yfilter = yfilter; } } bool ImmediateQuery::Input::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""select"" || name == ""foreach"" || name == ""sort-by"" || name == ""limit"" || name == ""offset"" || name == ""timeout"") return true; return false; } ImmediateQuery::Input::Select::Select() : label{YType::str, ""label""}, expression{YType::str, ""expression""}, result_type{YType::enumeration, ""result-type""} { yang_name = ""select""; yang_parent_name = ""input""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Input::Select::~Select() { } bool ImmediateQuery::Input::Select::has_data() const { if (is_presence_container) return true; for (auto const & leaf : result_type.getYLeafs()) { if(leaf.is_set) return true; } return label.is_set || expression.is_set; } bool ImmediateQuery::Input::Select::has_operation() const { for (auto const & leaf : result_type.getYLeafs()) { if(is_set(leaf.yfilter)) return true; } return is_set(yfilter) || ydk::is_set(label.yfilter) || ydk::is_set(expression.yfilter) || ydk::is_set(result_type.yfilter); } std::string ImmediateQuery::Input::Select::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/input/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Input::Select::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""select""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > ImmediateQuery::Input::Select::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (label.is_set || is_set(label.yfilter)) leaf_name_data.push_back(label.get_name_leafdata()); if (expression.is_set || is_set(expression.yfilter)) leaf_name_data.push_back(expression.get_name_leafdata()); auto result_type_name_datas = result_type.get_name_leafdata(); leaf_name_data.insert(leaf_name_data.end(), result_type_name_datas.begin(), result_type_name_datas.end()); return leaf_name_data; } std::shared_ptr ImmediateQuery::Input::Select::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> ImmediateQuery::Input::Select::get_children() const { std::map> _children{}; char count_=0; return _children; } void ImmediateQuery::Input::Select::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""label"") { label = value; label.value_namespace = name_space; label.value_namespace_prefix = name_space_prefix; } if(value_path == ""expression"") { expression = value; expression.value_namespace = name_space; expression.value_namespace_prefix = name_space_prefix; } if(value_path == ""result-type"") { result_type.append(value); } } void ImmediateQuery::Input::Select::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""label"") { label.yfilter = yfilter; } if(value_path == ""expression"") { expression.yfilter = yfilter; } if(value_path == ""result-type"") { result_type.yfilter = yfilter; } } bool ImmediateQuery::Input::Select::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""label"" || name == ""expression"" || name == ""result-type"") return true; return false; } ImmediateQuery::Output::Output() : query_result(std::make_shared()) { query_result->parent = this; yang_name = ""output""; yang_parent_name = ""immediate-query""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Output::~Output() { } bool ImmediateQuery::Output::has_data() const { if (is_presence_container) return true; return (query_result != nullptr && query_result->has_data()); } bool ImmediateQuery::Output::has_operation() const { return is_set(yfilter) || (query_result != nullptr && query_result->has_operation()); } std::string ImmediateQuery::Output::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Output::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""output""; return path_buffer.str(); } std::vector > ImmediateQuery::Output::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr ImmediateQuery::Output::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""query-result"") { if(query_result == nullptr) { query_result = std::make_shared(); } return query_result; } return nullptr; } std::map> ImmediateQuery::Output::get_children() const { std::map> _children{}; char count_=0; if(query_result != nullptr) { _children[""query-result""] = query_result; } return _children; } void ImmediateQuery::Output::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void ImmediateQuery::Output::set_filter(const std::string & value_path, YFilter yfilter) { } bool ImmediateQuery::Output::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-result"") return true; return false; } ImmediateQuery::Output::QueryResult::QueryResult() : result(this, {}) { yang_name = ""query-result""; yang_parent_name = ""output""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Output::QueryResult::~QueryResult() { } bool ImmediateQuery::Output::QueryResult::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return false; } bool ImmediateQuery::Output::QueryResult::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter); } std::string ImmediateQuery::Output::QueryResult::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/output/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Output::QueryResult::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""query-result""; return path_buffer.str(); } std::vector > ImmediateQuery::Output::QueryResult::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr ImmediateQuery::Output::QueryResult::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""result"") { auto ent_ = std::make_shared(); ent_->parent = this; result.append(ent_); return ent_; } return nullptr; } std::map> ImmediateQuery::Output::QueryResult::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : result.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void ImmediateQuery::Output::QueryResult::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void ImmediateQuery::Output::QueryResult::set_filter(const std::string & value_path, YFilter yfilter) { } bool ImmediateQuery::Output::QueryResult::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""result"") return true; return false; } ImmediateQuery::Output::QueryResult::Result::Result() : select(this, {}) { yang_name = ""result""; yang_parent_name = ""query-result""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Output::QueryResult::Result::~Result() { } bool ImmediateQuery::Output::QueryResult::Result::has_data() const { if (is_presence_container) return true; for (std::size_t index=0; indexhas_data()) return true; } return false; } bool ImmediateQuery::Output::QueryResult::Result::has_operation() const { for (std::size_t index=0; indexhas_operation()) return true; } return is_set(yfilter); } std::string ImmediateQuery::Output::QueryResult::Result::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/output/query-result/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Output::QueryResult::Result::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""result""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > ImmediateQuery::Output::QueryResult::Result::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr ImmediateQuery::Output::QueryResult::Result::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""select"") { auto ent_ = std::make_shared(); ent_->parent = this; select.append(ent_); return ent_; } return nullptr; } std::map> ImmediateQuery::Output::QueryResult::Result::get_children() const { std::map> _children{}; char count_=0; count_ = 0; for (auto ent_ : select.entities()) { if(_children.find(ent_->get_segment_path()) == _children.end()) _children[ent_->get_segment_path()] = ent_; else _children[ent_->get_segment_path()+count_++] = ent_; } return _children; } void ImmediateQuery::Output::QueryResult::Result::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void ImmediateQuery::Output::QueryResult::Result::set_filter(const std::string & value_path, YFilter yfilter) { } bool ImmediateQuery::Output::QueryResult::Result::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""select"") return true; return false; } ImmediateQuery::Output::QueryResult::Result::Select::Select() : label{YType::str, ""label""}, path{YType::str, ""path""}, value_{YType::str, ""value""}, data{YType::str, ""data""} { yang_name = ""select""; yang_parent_name = ""result""; is_top_level_class = false; has_list_ancestor = false; } ImmediateQuery::Output::QueryResult::Result::Select::~Select() { } bool ImmediateQuery::Output::QueryResult::Result::Select::has_data() const { if (is_presence_container) return true; return label.is_set || path.is_set || value_.is_set || data.is_set; } bool ImmediateQuery::Output::QueryResult::Result::Select::has_operation() const { return is_set(yfilter) || ydk::is_set(label.yfilter) || ydk::is_set(path.yfilter) || ydk::is_set(value_.yfilter) || ydk::is_set(data.yfilter); } std::string ImmediateQuery::Output::QueryResult::Result::Select::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:immediate-query/output/query-result/result/"" << get_segment_path(); return path_buffer.str(); } std::string ImmediateQuery::Output::QueryResult::Result::Select::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""select""; path_buffer << ""["" << get_ylist_key() << ""]""; return path_buffer.str(); } std::vector > ImmediateQuery::Output::QueryResult::Result::Select::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (label.is_set || is_set(label.yfilter)) leaf_name_data.push_back(label.get_name_leafdata()); if (path.is_set || is_set(path.yfilter)) leaf_name_data.push_back(path.get_name_leafdata()); if (value_.is_set || is_set(value_.yfilter)) leaf_name_data.push_back(value_.get_name_leafdata()); if (data.is_set || is_set(data.yfilter)) leaf_name_data.push_back(data.get_name_leafdata()); return leaf_name_data; } std::shared_ptr ImmediateQuery::Output::QueryResult::Result::Select::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> ImmediateQuery::Output::QueryResult::Result::Select::get_children() const { std::map> _children{}; char count_=0; return _children; } void ImmediateQuery::Output::QueryResult::Result::Select::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""label"") { label = value; label.value_namespace = name_space; label.value_namespace_prefix = name_space_prefix; } if(value_path == ""path"") { path = value; path.value_namespace = name_space; path.value_namespace_prefix = name_space_prefix; } if(value_path == ""value"") { value_ = value; value_.value_namespace = name_space; value_.value_namespace_prefix = name_space_prefix; } if(value_path == ""data"") { data = value; data.value_namespace = name_space; data.value_namespace_prefix = name_space_prefix; } } void ImmediateQuery::Output::QueryResult::Result::Select::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""label"") { label.yfilter = yfilter; } if(value_path == ""path"") { path.yfilter = yfilter; } if(value_path == ""value"") { value_.yfilter = yfilter; } if(value_path == ""data"") { data.yfilter = yfilter; } } bool ImmediateQuery::Output::QueryResult::Result::Select::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""label"" || name == ""path"" || name == ""value"" || name == ""data"") return true; return false; } ResetQuery::ResetQuery() : input(std::make_shared()) { input->parent = this; yang_name = ""reset-query""; yang_parent_name = ""tailf-netconf-query""; is_top_level_class = true; has_list_ancestor = false; } ResetQuery::~ResetQuery() { } bool ResetQuery::has_data() const { if (is_presence_container) return true; return (input != nullptr && input->has_data()); } bool ResetQuery::has_operation() const { return is_set(yfilter) || (input != nullptr && input->has_operation()); } std::string ResetQuery::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:reset-query""; return path_buffer.str(); } std::vector > ResetQuery::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr ResetQuery::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""input"") { if(input == nullptr) { input = std::make_shared(); } return input; } return nullptr; } std::map> ResetQuery::get_children() const { std::map> _children{}; char count_=0; if(input != nullptr) { _children[""input""] = input; } return _children; } void ResetQuery::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void ResetQuery::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr ResetQuery::clone_ptr() const { return std::make_shared(); } std::string ResetQuery::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string ResetQuery::get_bundle_name() const { return ""cisco_ios_xe""; } augment_capabilities_function ResetQuery::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map, std::string> ResetQuery::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool ResetQuery::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""input"") return true; return false; } ResetQuery::Input::Input() : query_handle{YType::uint32, ""query-handle""}, offset{YType::uint32, ""offset""}, timeout{YType::uint32, ""timeout""} { yang_name = ""input""; yang_parent_name = ""reset-query""; is_top_level_class = false; has_list_ancestor = false; } ResetQuery::Input::~Input() { } bool ResetQuery::Input::has_data() const { if (is_presence_container) return true; return query_handle.is_set || offset.is_set || timeout.is_set; } bool ResetQuery::Input::has_operation() const { return is_set(yfilter) || ydk::is_set(query_handle.yfilter) || ydk::is_set(offset.yfilter) || ydk::is_set(timeout.yfilter); } std::string ResetQuery::Input::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:reset-query/"" << get_segment_path(); return path_buffer.str(); } std::string ResetQuery::Input::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""input""; return path_buffer.str(); } std::vector > ResetQuery::Input::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (query_handle.is_set || is_set(query_handle.yfilter)) leaf_name_data.push_back(query_handle.get_name_leafdata()); if (offset.is_set || is_set(offset.yfilter)) leaf_name_data.push_back(offset.get_name_leafdata()); if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata()); return leaf_name_data; } std::shared_ptr ResetQuery::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> ResetQuery::Input::get_children() const { std::map> _children{}; char count_=0; return _children; } void ResetQuery::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""query-handle"") { query_handle = value; query_handle.value_namespace = name_space; query_handle.value_namespace_prefix = name_space_prefix; } if(value_path == ""offset"") { offset = value; offset.value_namespace = name_space; offset.value_namespace_prefix = name_space_prefix; } if(value_path == ""timeout"") { timeout = value; timeout.value_namespace = name_space; timeout.value_namespace_prefix = name_space_prefix; } } void ResetQuery::Input::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""query-handle"") { query_handle.yfilter = yfilter; } if(value_path == ""offset"") { offset.yfilter = yfilter; } if(value_path == ""timeout"") { timeout.yfilter = yfilter; } } bool ResetQuery::Input::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-handle"" || name == ""offset"" || name == ""timeout"") return true; return false; } StopQuery::StopQuery() : input(std::make_shared()) { input->parent = this; yang_name = ""stop-query""; yang_parent_name = ""tailf-netconf-query""; is_top_level_class = true; has_list_ancestor = false; } StopQuery::~StopQuery() { } bool StopQuery::has_data() const { if (is_presence_container) return true; return (input != nullptr && input->has_data()); } bool StopQuery::has_operation() const { return is_set(yfilter) || (input != nullptr && input->has_operation()); } std::string StopQuery::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:stop-query""; return path_buffer.str(); } std::vector > StopQuery::get_name_leaf_data() const { std::vector > leaf_name_data {}; return leaf_name_data; } std::shared_ptr StopQuery::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { if(child_yang_name == ""input"") { if(input == nullptr) { input = std::make_shared(); } return input; } return nullptr; } std::map> StopQuery::get_children() const { std::map> _children{}; char count_=0; if(input != nullptr) { _children[""input""] = input; } return _children; } void StopQuery::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { } void StopQuery::set_filter(const std::string & value_path, YFilter yfilter) { } std::shared_ptr StopQuery::clone_ptr() const { return std::make_shared(); } std::string StopQuery::get_bundle_yang_models_location() const { return ydk_cisco_ios_xe_models_path; } std::string StopQuery::get_bundle_name() const { return ""cisco_ios_xe""; } augment_capabilities_function StopQuery::get_augment_capabilities_function() const { return cisco_ios_xe_augment_lookup_tables; } std::map, std::string> StopQuery::get_namespace_identity_lookup() const { return cisco_ios_xe_namespace_identity_lookup; } bool StopQuery::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""input"") return true; return false; } StopQuery::Input::Input() : query_handle{YType::uint32, ""query-handle""} { yang_name = ""input""; yang_parent_name = ""stop-query""; is_top_level_class = false; has_list_ancestor = false; } StopQuery::Input::~Input() { } bool StopQuery::Input::has_data() const { if (is_presence_container) return true; return query_handle.is_set; } bool StopQuery::Input::has_operation() const { return is_set(yfilter) || ydk::is_set(query_handle.yfilter); } std::string StopQuery::Input::get_absolute_path() const { std::ostringstream path_buffer; path_buffer << ""tailf-netconf-query:stop-query/"" << get_segment_path(); return path_buffer.str(); } std::string StopQuery::Input::get_segment_path() const { std::ostringstream path_buffer; path_buffer << ""input""; return path_buffer.str(); } std::vector > StopQuery::Input::get_name_leaf_data() const { std::vector > leaf_name_data {}; if (query_handle.is_set || is_set(query_handle.yfilter)) leaf_name_data.push_back(query_handle.get_name_leafdata()); return leaf_name_data; } std::shared_ptr StopQuery::Input::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path) { return nullptr; } std::map> StopQuery::Input::get_children() const { std::map> _children{}; char count_=0; return _children; } void StopQuery::Input::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) { if(value_path == ""query-handle"") { query_handle = value; query_handle.value_namespace = name_space; query_handle.value_namespace_prefix = name_space_prefix; } } void StopQuery::Input::set_filter(const std::string & value_path, YFilter yfilter) { if(value_path == ""query-handle"") { query_handle.yfilter = yfilter; } } bool StopQuery::Input::has_leaf_or_child_of_name(const std::string & name) const { if(name == ""query-handle"") return true; return false; } const Enum::YLeaf StartQuery::Input::Select::ResultType::string {0, ""string""}; const Enum::YLeaf StartQuery::Input::Select::ResultType::path {1, ""path""}; const Enum::YLeaf StartQuery::Input::Select::ResultType::leaf_value {2, ""leaf-value""}; const Enum::YLeaf StartQuery::Input::Select::ResultType::inline_ {3, ""inline""}; const Enum::YLeaf ImmediateQuery::Input::Select::ResultType::string {0, ""string""}; const Enum::YLeaf ImmediateQuery::Input::Select::ResultType::path {1, ""path""}; const Enum::YLeaf ImmediateQuery::Input::Select::ResultType::leaf_value {2, ""leaf-value""}; const Enum::YLeaf ImmediateQuery::Input::Select::ResultType::inline_ {3, ""inline""}; } } ",16351,True,5456.10985433385,median "[[features.external-config]] == Externalized Configuration Spring Boot lets you externalize your configuration so that you can work with the same application code in different environments. You can use a variety of external configuration sources, include Java properties files, YAML files, environment variables, and command-line arguments. Property values can be injected directly into your beans by using the `@Value` annotation, accessed through Spring's `Environment` abstraction, or be <> through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones): . Default properties (specified by setting `SpringApplication.setDefaultProperties`). . {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files) . A `RandomValuePropertySource` that has properties only in `+random.*+`. . OS environment variables. . Java System properties (`System.getProperties()`). . JNDI attributes from `java:comp/env`. . `ServletContext` init parameters. . `ServletConfig` init parameters. . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. . {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. . <> in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: . <> packaged inside your jar (`application.properties` and YAML variants). . <> packaged inside your jar (`application-\\{profile}.properties` and YAML variants). . <> outside of your packaged jar (`application.properties` and YAML variants). . <> outside of your packaged jar (`application-\\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and `.yml` format in the same location, `.properties` takes precedence. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/MyBean.java[] ---- On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. For one-off testing, you can launch with a specific command line switch (for example, `java -jar app.jar --name=""Spring""`). TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. See the ""<>"" section for details. [[features.external-config.command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file based property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. [[features.external-config.application-json]] === JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`. For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: [source,shell,indent=0,subs=""verbatim""] ---- $ SPRING_APPLICATION_JSON='{""my"":{""name"":""test""}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: [source,shell,indent=0,subs=""verbatim""] ---- $ java -Dspring.application.json='{""my"":{""name"":""test""}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myapp.jar --spring.application.json='{""my"":{""name"":""test""}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values. This means that the JSON cannot override properties from lower order property sources with a `null` value. [[features.external-config.files]] === External Application Properties [[features.external-config.files]] Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . The classpath root . The classpath `/config` package . The current directory . The `/config` subdirectory in the current directory . Immediate child directories of the `/config` subdirectory The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as `PropertySources` to the Spring `Environment`. If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. You can also refer to an explicit location by using the `spring.config.location` environment property (which is a comma-separated list of directory locations or file paths). The following example shows how to specify a different file name: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.name=myproject ---- The following example shows how to specify two locations: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.location=\\ optional:classpath:/default.properties,\\ optional:classpath:/override.properties ---- TIP: Use the prefix `optional:` if the <> and you don't mind if they don't exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they must end in `/` or the system-dependent `File.separator`. At runtime they will be appended with the names generated from `spring.config.name` before being loaded. If `spring.config.location` contains files, they are used as-is. Whether specified directly or contained in a directory, file references must include a file extension in their name. Typical extensions that are supported out-of-the-box are `.properties`, `.yaml`, and `.yml`. When multiple locations are specified, the later ones can override the values of earlier ones. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:custom-config/` . `optional:file:./custom-config/` If you prefer to add additional locations, rather than replacing them, you can use `spring.config.additional-location`. Properties loaded from additional locations can override those in the default locations. For example, if `spring.config.additional-location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:/` . `optional:classpath:/config/` . `optional:file:./` . `optional:file:./config/` . `optional:file:./config/*/` . `optional:classpath:custom-config/` . `optional:file:./custom-config/` This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). See <> for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. [[features.external-config.files.optional-prefix]] ==== Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you don't mind if it doesn't always exist, you can use the `optional:` prefix. You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable. [[features.external-config.files.wildcard-locations]] ==== Wildcard Locations If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. For example, if you have some Redis configuration and some MySQL configuration, you might want to keep those two pieces of configuration separate, while requiring that both those are present in an `application.properties` file. This might result in two separate `application.properties` files mounted at different locations such as `/config/redis/application.properties` and `/config/mysql/application.properties`. In such a case, having a wildcard location of `config/*/`, will result in both files being processed. By default, Spring Boot includes `config/*/` in the default search locations. It means that all subdirectories of the `/config` directory outside of your jar will be searched. You can use wildcard locations yourself with the `spring.config.location` and `spring.config.additional-location` properties. NOTE: A wildcard location must contain only one `{asterisk}` and end with `{asterisk}/` for search locations that are directories or `*/` for search locations that are files. Locations with wildcards are sorted alphabetically based on the absolute path of the file names. TIP: Wildcard locations only work with external directories. You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] ==== Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific ones. If several profiles are specified, a last-wins strategy applies. For example, if profiles `prod,live` are specified by the configprop:spring.profiles.active[] property, values in `application-prod.properties` can be overridden by those in `application-live.properties`. The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. If you've already directly <> a profile specific property files then it won't be imported a second time. [[features.external-config.files.importing]] ==== Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: application: name: ""myapp"" config: import: ""optional:file:./dev.properties"" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). Values from the imported `dev.properties` will take precedence over the file that triggered the import. In the above example, the `dev.properties` could redefine `spring.application.name` to a different value. An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file doesn't matter. For instance, the two examples below produce the same result: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: config: import: my.properties my: property: value ---- [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: property: value spring: config: import: my.properties ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. By default you can import Java Properties, YAML and ""`<>`"". Third-party jars can offer support for additional technologies (there's no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package. ==== [[features.external-config.files.importing-extensionless]] ==== Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""file:/etc/config/myconfig[.yaml]"" ---- [[features.external-config.files.configtree]] ==== Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It's not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. As an alternative to environment variables, many cloud platforms now allow you to map configuration into mounted data volumes. For example, Kubernetes can volume mount both https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#populate-a-volume-with-data-stored-in-a-configmap[`ConfigMaps`] and https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod[`Secrets`]. There are two common volume mount patterns that can be use: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: [indent=0] ---- etc/ config/ myapp/ username password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/"" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected. If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut. Any `configtree:` location that ends with `/*/` will import all immediate children as config trees. For example, given the following volume: [indent=0] ---- etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ---- You can use `configtree:/etc/config/*/` as the import location: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/*/"" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. NOTE: Directories loaded using a wildcard are sorted alphabetically. If you need a different order, then you should list each location as a separate import Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/run/secrets/"" ---- [[features.external-config.files.property-placeholders]] ==== Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties). The standard `$\\{name}` property-placeholder syntax can be used anywhere within a value. For example, the following file will set `app.description` to ""`MyApp is a Spring Boot application`"": [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- app: name: ""MyApp"" description: ""${app.name} is a Spring Boot application"" ---- TIP: You can also use this technique to create ""`short`"" variants of existing Spring Boot properties. See the _<>_ how-to for details. [[features.external-config.files.multi-document]] ==== Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. For `application.yml` files, the standard YAML multi-document syntax is used. Three consecutive hyphens represent the end of one document, and the start of the next. For example, the following file has two logical documents: [source,yaml,indent=0,subs=""verbatim""] ---- spring.application.name: MyApp --- spring.config.activate.on-cloud-platform: kubernetes spring.application.name: MyCloudApp ---- For `application.properties` files a special `#---` comment is used to mark the document splits: [source,properties,indent=0,subs=""verbatim""] ---- spring.application.name=MyApp #--- spring.config.activate.on-cloud-platform=kubernetes spring.application.name=MyCloudApp ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be comments. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. See the <> for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] ==== Activation Properties It's sometimes useful to only activate a given get of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. You can conditionally activate a properties document using `spring.config.activate.*`. The following activation properties are available: .activation properties [cols=""1,4""] |=== | Property | Note | `on-profile` | A profile expression that must match for the document to be active. | `on-cloud-platform` | The `CloudPlatform` that must be detected for the document to be active. |=== For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the ""`prod`"" or ""`staging`"" profiles are active: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- myprop: always-set --- spring: config: activate: on-cloud-platform: ""kubernetes"" on-profile: ""prod | staging"" myotherprop: sometimes-set ---- [[features.external-config.encrypting]] === Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. See <> for details. If you're looking for a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] === Working with YAML https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. NOTE: If you use ""`Starters`"", SnakeYAML is automatically provided by `spring-boot-starter`. [[features.external-config.yaml.mapping-to-properties]] ==== Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: [source,yaml,indent=0,subs=""verbatim""] ---- environments: dev: url: https://dev.example.com name: Developer Setup prod: url: https://another.example.com name: My Cool App ---- In order to access these properties from the `Environment`, they would be flattened as follows: [source,properties,indent=0,subs=""verbatim""] ---- environments.dev.url=https://dev.example.com environments.dev.name=Developer Setup environments.prod.url=https://another.example.com environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: [source,yaml,indent=0,subs=""verbatim""] ---- my: servers: - dev.example.com - another.example.com ---- The preceding example would be transformed into these properties: [source,properties,indent=0,subs=""verbatim""] ---- my.servers[0]=dev.example.com my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. For more details see the ""`<>`"" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. [[features.external-config.yaml.directly-loading]] [[features.external-config.yaml.directly-loading]] ==== Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. [[features.external-config.random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: secret: ""${random.value}"" number: ""${random.int}"" bignumber: ""${random.long}"" uuid: ""${random.uuid}"" number-less-than-ten: ""${random.int(10)}"" number-in-range: ""${random.int[1024,65536]}"" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). [[features.external-config.system-environment]] === Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. [[features.external-config.typesafe-configuration-properties]] === Type-safe Configuration Properties Using the `@Value(""$\\{property}"")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. TIP: See also the <>. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] ==== JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/javabeanbinding/MyProperties.java[] ---- The preceding POJO defines the following properties: * `my.service.enabled`, with a value of `false` by default. * `my.service.remote-address`, with a type that can be coerced from `String`. * `my.service.security.username`, with a nested ""security"" object whose name is determined by the name of the property. In particular, the return type is not used at all there and could have been `SecurityProperties`. * `my.service.security.password`. * `my.service.security.roles`, with a collection of `String` that defaults to `USER`. NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured via properties files, YAML files, environment variables etc., are public API but the accessors (getters/setters) of the class itself are not meant to be used directly. [NOTE] ==== Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC. A setter may be omitted in the following cases: * Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder. * Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties). In the latter case, a setter is mandatory. We recommend to always add a setter for such types. If you initialize a collection, make sure it is not immutable (as in the preceding example). * If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. Finally, only standard Java Bean properties are considered and binding on static properties is not supported. ==== [[features.external-config.typesafe-configuration-properties.constructor-binding]] ==== Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/constructorbinding/MyProperties.java[] ---- In this setup, the `@ConstructorBinding` annotation is used to indicate that constructor binding should be used. This means that the binder will expect to find a constructor with the parameters that you wish to have bound. Nested members of a `@ConstructorBinding` class (such as `Security` in the example above) will also be bound via their constructor. Default values can be specified using `@DefaultValue` and the same conversion service will be applied to coerce the `String` value to the target type of a missing property. By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/constructorbinding/nonnull/MyProperties.java[tag=*] ---- NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (e.g. `@Component` beans, beans created via `@Bean` methods or beans loaded using `@Import`) TIP: If you have more than one constructor for your class you can also use `@ConstructorBinding` directly on the constructor that should be bound. NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type. As such, it is not well-suited to configuration property injection. For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound. [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] ==== Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/enablingannotatedtypes/MyConfiguration.java[] ---- To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/enablingannotatedtypes/MyApplication.java[] ---- [NOTE] ==== When the `@ConfigurationProperties` bean is registered using configuration property scanning or via `@EnableConfigurationProperties`, the bean has a conventional name: `-`, where `` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. The bean name in the example above is `com.example.app-com.example.app.SomeProperties`. ==== We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context. For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. [[features.external-config.typesafe-configuration-properties.using-annotated-types]] ==== Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: [source,yaml,indent=0,subs=""verbatim""] ---- my: service: remote-address: 192.168.1.1 security: username: admin roles: - USER - ADMIN ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/usingannotatedtypes/MyService.java[] ---- TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. See the <> for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] ==== Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/thirdpartyconfiguration/ThirdPartyConfiguration.java[] ---- Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] ==== Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/relaxedbinding/MyPersonProperties.java[] ---- With the preceding code, the following properties names can all be used: .relaxed binding [cols=""1,4""] |=== | Property | Note | `my.main-project.person.first-name` | Kebab case, which is recommended for use in `.properties` and `.yml` files. | `my.main-project.person.firstName` | Standard camel case syntax. | `my.main-project.person.first_name` | Underscore notation, which is an alternative format for use in `.properties` and `.yml` files. | `MY_MAINPROJECT_PERSON_FIRSTNAME` | Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and separated by `-`, such as `my.main-project.person`). .relaxed binding rules per property source [cols=""2,4,4""] |=== | Property Source | Simple | List | Properties Files | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values | YAML Files | Camel case, kebab case, or underscore notation | Standard YAML list syntax or comma-separated values | Environment Variables | Upper case format with underscore as the delimiter (see <>). | Numeric values surrounded by underscores (see <>) | System properties | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values |=== TIP: We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] ===== Binding Maps When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: [source,properties,indent=0,subs=""verbatim"",role=""primary""] .Properties ---- my.map.[/key1]=value1 my.map.[/key2]=value2 my.map./key3=value3 ---- [source,yaml,indent=0,subs=""verbatim"",role=""secondary""] .Yaml ---- my: map: ""[/key1]"": ""value1"" ""[/key2]"": ""value2"" ""/key3"": ""value3"" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. The slash has been removed from `key3` because it wasn't surrounded by square brackets. You may also occasionally need to use the bracket notation if your `key` contains a `.` and you are binding to non-scalar value. For example, binding `a.b=c` to `Map` will return a Map with the entry `{""a""={""b""=""c""}}` whereas `[a.b]=c` will return a Map with the entry `{""a.b""=""c""}`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] ===== Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. Spring Boot's relaxed binding rules are, as much as possible, designed to be compatible with these naming restrictions. To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (`.`) with underscores (`_`). * Remove any dashes (`-`). * Convert to uppercase. For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`. Environment variables can also be used when binding to object lists. To bind to a `List`, the element number should be surrounded with underscores in the variable name. For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] ==== Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/list/MyProperties.java[] ---- Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" - name: ""another name"" description: ""another description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list. For `Map` properties, you can bind with property values drawn from multiple sources. However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/mergingcomplextypes/map/MyProperties.java[] ---- Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: map: key1: name: ""my name 1"" description: ""my description 1"" --- spring: config: activate: on-profile: ""dev"" my: map: key1: name: ""dev name 1"" key2: name: ""dev name 2"" description: ""dev description 2"" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` (with a name of `dev name 1` and a description of `my description 1`) and `key2` (with a name of `dev name 2` and a description of `dev description 2`). NOTE: The preceding merging rules apply to properties from all property sources, and not just files. [[features.external-config.typesafe-configuration-properties.conversion]] ==== Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. [[features.external-config.typesafe-configuration-properties.conversion.durations]] ===== Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Duration.html#parse-java.lang.CharSequence-[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (e.g. `10s` means 10 seconds) Consider the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/durations/javabeanbinding/MyProperties.java[] ---- To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. You can also use any of the supported units. These are: * `ns` for nanoseconds * `us` for microseconds * `ms` for milliseconds * `s` for seconds * `m` for minutes * `h` for hours * `d` for days The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/durations/constructorbinding/MyProperties.java[] ---- TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it isn't milliseconds. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] ===== Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (e.g. `1y3d` means 1 year and 3 days) The following units are supported with the simple format: * `y` for years * `m` for months * `w` for weeks * `d` for days NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means ""`7 days`"". [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: * A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified) * A more readable format where the value and the unit are coupled (e.g. `10MB` means 10 megabytes) Consider the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/datasizes/javabeanbinding/MyProperties.java[] ---- To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. You can also use any of the supported units. These are: * `B` for bytes * `KB` for kilobytes * `MB` for megabytes * `GB` for gigabytes * `TB` for terabytes The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/conversion/datasizes/constructorbinding/MyProperties.java[] ---- TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it isn't bytes. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] ==== @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/validate/MyProperties.java[] ---- TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: [source,java,indent=0,subs=""verbatim""] ---- include::{docs-java}/features/externalconfig/typesafeconfigurationproperties/validate/nested/MyProperties.java[] ---- You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class. Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. See the ""<>"" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] ==== @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: [cols=""4,2,2""] |=== | Feature |`@ConfigurationProperties` |`@Value` | <> | Yes | Limited (see <>) | <> | Yes | No | `SpEL` evaluation | No | Yes |=== [[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]] NOTE: If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding `@ConfigurationProperties`. For example, `@Value(""{demo.item-price}"")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value(""{demo.itemPrice}"")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. `SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed via `@Value`. ",12127,False,2206.115773727254,median "#ifndef __PRINTQUEUE_HPP__ #define __PRINTQUEUE_HPP__ /*++ Copyright (C) 2002 - 2003 Microsoft Corporation All rights reserved. Module Name: PrintQueue.hpp Abstract: This file includes the declarations of the PrintQueue Author: Khaled Sedky (khaleds) 10-December-2002 Revision History: --*/ #include ""LegacyDevice.hpp"" using namespace System::Windows::Xps; using namespace System::Windows::Xps::Packaging; using namespace System::Windows::Xps::Serialization; using namespace System::Security; using namespace System::Security::Permissions; namespace System { namespace Printing { // // Location, Comment and Share Name are mutualally // exclusive properties. So by introducing both // PrintStringPropertyType & PrinterStringProperty // I am allowing users to exclusively set any one // of the three. // public enum class PrintQueueStringPropertyType { Location = 0x00000000, Comment = 0x00000001, ShareName = 0x00000002 }; public ref struct PrintQueueStringProperty { public: property PrintQueueStringPropertyType Type; property String^ Name; }; /// /// Enumeration of properties of the PrintQueue object. /// /// /// Name /// Printer name. /// /// /// ShareName /// Printer share name. /// /// /// Comment /// Brief description of the printer. /// /// /// Location /// Physical location of the printer. /// /// /// Description /// Windows 95/98/Me: Pointer to a null-terminated string that describes the printer. /// The string contains the printer name, driver name, and comment concatenated and separated by commas. /// /// /// /// Priority /// Priority value that the Print Spooler uses to route print jobs. /// /// /// DefaultPriority /// Default priority value assigned to each print job. /// /// /// StartTimeOfDay /// Earliest time at which the printer will print a job. /// /// /// UntilTimeOfDay /// Latest time at which the printer will print a job. /// /// /// AveragePagesPerMinute /// Average number of pages per minute that have been printed on the printer. /// /// /// NumberOfJobs /// Number of print jobs that have been queued for the printer. /// /// /// QueueAttributes /// Printer attributes of type PrintQueueAttributes. /// /// /// QueueDriver /// Printer driver used by the printer. /// /// /// QueuePort /// Port(s) used to transmit data to the printer. /// /// /// QueuePrintProcessor /// Print Processor used by the printer.. /// /// /// HostingPrintServer /// Print server name. /// /// /// QueueStatus /// Printer status of type PrintQueueStatus. /// /// /// SeparatorFile /// Name of the file used to create the separator page. /// /// /// UserPrintTicket /// Per user PrintTicket. /// /// /// DefaultPrintTicket /// Printer default PrintTicket. /// /// /// /// public enum class PrintQueueIndexedProperty { Name , ShareName , Comment , Location , Description , Priority , DefaultPriority , StartTimeOfDay , UntilTimeOfDay , AveragePagesPerMinute , NumberOfJobs , QueueAttributes , QueueDriver , QueuePort , QueuePrintProcessor , HostingPrintServer , QueueStatus , SeparatorFile , UserPrintTicket , DefaultPrintTicket }; /// /// This class abstracts the functionality of a print queue. /// /// [System::Drawing::Printing::PrintingPermission( SecurityAction::InheritanceDemand, Level=System::Drawing::Printing::PrintingPermissionLevel::DefaultPrinting)] public ref class PrintQueue : public PrintSystemObject { public: /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// /// Desired access defaults to to PrintSystemDesiredAccess::UsePrinter. /// /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// JT schema version. /// /// Desired access defaults to PrintSystemDesiredAccess::UsePrinter. /// /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, Int32 printSchemaVersion ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// Only the properties referenced in the propertyFilter are initialized. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// Array of properties to be initialized. /// /// Desired access defaults to PrintSystemDesiredAccess::UsePrinter. /// /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, array^ propertyFilter ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// Only the properties referenced in the propertyFilter are initialized. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// Array of properties to be initialized. /// /// Desired access defaults to to PrintSystemDesiredAccess::UsePrinter. /// /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, array^ propertyFilter ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// Desired access /// Thrown on failure /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, PrintSystemDesiredAccess desiredAccess ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// JT schema version. /// Desired access /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, Int32 printSchemaVersion, PrintSystemDesiredAccess desiredAccess ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// Array of properties to be initialized. /// Desired access /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, array^ propertyFilter, PrintSystemDesiredAccess desiredAccess ); /// /// Instantiates a PrintQueue object representing a preinstalled print queue /// on the print server identified by the printServer parameter. /// /// PrintServer object that hosts the print queue. /// Name of the print queue. /// Array of properties to be initialized. /// Desired access /// Thrown on failure. /// /// Critical - Sets critical printTicketManager field /// Safe - Set to safe value null /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, String^ printQueueName, array^ propertyFilter, PrintSystemDesiredAccess desiredAccess ); internal: // // This class constructor is intended for // browsable Print Objects. To give an example, // this is instantiated when enumerating // PrintQueues on a PrintServer // /// /// Critical - Sets InPartialTrust property to initialize the SecurityCritical member. /// TreatAsSafe - It sets InPartialTrust to false, which prevents making any elevations in PT /// [SecuritySafeCritical] PrintQueue( array^ propertyFilter ); /// /// Critical - Sets InPartialTrust property to initialize the SecurityCritical member. /// TreatAsSafe - It sets InPartialTrust to false, which prevents making any elevations in PT /// [SecuritySafeCritical] PrintQueue( PrintServer^ printServer, array^ propertyFilter ); internal: /// /// Critical - Returns critical PrintThunkHandlerBase to interact with printer device /// [SecurityCritical] PrinterThunkHandlerBase^ CreatePrintThunkHandler( void ); /// /// Critical - Calls native methods to determine if XPS spooling API's are available /// TreatAsSafe - Does not return critical data, does not change critical state, does not consume untrusted input /// [SecuritySafeCritical] Boolean IsXpsDeviceSimulationSupported( void ); static PrintQueue^ Install( PrintServer^ printServer, String^ printQueueName, String^ driverName, array^ portNames, String^ printProcessorName, PrintQueueAttributes printQueueAttributes ); static PrintQueue^ Install( PrintServer^ printServer, String^ printQueueName, String^ driverName, array^ portNames, String^ printProcessorName, PrintQueueAttributes printQueueAttributes, PrintQueueStringProperty^ requiredPrintQueueProperty, Int32 requiredPriority, Int32 requiredDefaultPriority ); static PrintQueue^ Install( PrintServer^ printServer, String^ printQueueName, String^ driverName, array^ portNames, String^ printProcessorName, PrintQueueAttributes printQueueAttributes, String^ requiredShareName, String^ requiredComment, String^ requiredLocation, String^ requiredSeparatorFile, Int32 requiredPriority, Int32 requiredDefaultPriority ); /// /// Critical - Uses type from non-APTCA Reachframework. /// TreatAsSafe - Type is safe exception type. /// [SecuritySafeCritical] static PrintQueue^ Install( PrintServer^ printServer, String^ printQueueName, String^ driverName, array^ portNames, String^ printProcessorName, PrintPropertyDictionary^ initializationParams ); static bool Delete( String^ printQueueName ); public: /// /// Acquire device capabilities. /// /// /// PrintTicket. /// /// /// Critical - When running in PT, we need to evelate to determine the /// supported capabilities /// PublicOK - Reading the value is considered safe in PT. /// [SecurityCritical] PrintCapabilities^ GetPrintCapabilities( PrintTicket^ printTicket ); /// /// Acquire device capabilities. /// /// /// Critical - Uses type from non-APTCA Reachframework (PrintCapabilities). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] PrintCapabilities^ GetPrintCapabilities( void ); /// /// Acquire device capabilities as an XML stream. /// /// /// PrintTicket. /// /// /// Critical - Uses type from non-APTCA Reachframework (PrintTicket, PrintTicketManager). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] MemoryStream^ GetPrintCapabilitiesAsXml( PrintTicket^ printTicket ); /// /// Acquire device capabilities as an XML stream. /// /// /// Critical - Uses type from non-APTCA Reachframework (PrintTicketManager). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] MemoryStream^ GetPrintCapabilitiesAsXml( void ); /// /// Merge and validate PrintTicket. /// /// /// Base PrintTicket. /// /// /// Delta PrintTicket. /// /// Returns a ValidationResult. /// /// Critical - Uses types from non-APTCA reachframework.dll (ValidationResult, PrintTicket) /// PublicOK - Types use is safe. /// [SecuritySafeCritical] ValidationResult MergeAndValidatePrintTicket( PrintTicket^ basePrintTicket, PrintTicket^ deltaPrintTicket ); /// /// Merge and validate PrintTicket. /// /// /// Base PrintTicket. /// /// /// Delta PrintTicket. /// /// /// Scope that delta PrintTicket and result PrintTicket will be limited to. /// /// Returns a ValidationResult. /// /// Critical - Uses types from non-APTCA reachframework.dll (ValidationResult, PrintTicket, PrintTicketScope) /// PublicOK - Types use is safe. /// [SecuritySafeCritical] ValidationResult MergeAndValidatePrintTicket( PrintTicket^ basePrintTicket, PrintTicket^ deltaPrintTicket, PrintTicketScope scope ); /// /// Pauses printing the print queue. /// virtual void Pause( void ); /// /// Resumes printing on the the print queue. /// virtual void Resume( void ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// PublicOK - Type use is safe. /// [SecuritySafeCritical] PrintSystemJobInfo^ AddJob( void ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// PublicOK - Type use is safe. /// [SecuritySafeCritical] PrintSystemJobInfo^ AddJob( String^ jobName ); /// /// Adds a new print job, specifying the name and the initial print ticket to use. /// /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// PublicOK - Type use is safe. /// [SecuritySafeCritical] PrintSystemJobInfo^ AddJob( String^ jobName, PrintTicket^ printTicket ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// PublicOK - Type use is safe. /// [SecuritySafeCritical] PrintSystemJobInfo^ AddJob( String^ jobName, String^ documentPath, Boolean fastCopy ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// PublicOK - Type use is safe. /// [SecuritySafeCritical] PrintSystemJobInfo^ AddJob( String^ jobName, String^ documentPath, Boolean fastCopy, PrintTicket^ printTicket ); property Boolean PrintingIsCancelled { void set(Boolean isCancelled); Boolean get(); } property PrintJobSettings^ CurrentJobSettings { /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe exception object /// [SecuritySafeCritical] PrintJobSettings^ get(); } PrintSystemJobInfo^ GetJob( Int32 jobId ); PrintJobInfoCollection^ GetPrintJobInfoCollection( void ); /// /// Purges the jobs on the the print queue. /// virtual void Purge( void ); /// /// Priority property the Print Spooler uses to route print jobs. /// property virtual Int32 Priority { Int32 get(); void set(Int32 inPriority); } /// /// Name identifier of this object. /// /// /// Inherited from PrintSystemObject. /// property virtual String^ Name { String^ get() sealed override; void set(String^ objName) sealed override; } /// /// Default priority property the Print Spooler uses to route print jobs. /// property virtual Int32 DefaultPriority { Int32 get(); void set(Int32 inDefaultPriority); } /// /// Specifies the earliest time at which the printer will print a job. /// property virtual Int32 StartTimeOfDay { Int32 get(); void set(Int32 inStartTime); } /// /// Specifies the latest time at which the printer will print a job. /// property virtual Int32 UntilTimeOfDay { Int32 get(); void set(Int32 inUntilTime); } /// /// Specifies the average number of pages per minute that have been printed on the printer. /// property virtual Int32 AveragePagesPerMinute { Int32 get(); } /// /// Specifies the number of print jobs that have been queued for the printer. /// This property cannot be set. /// property virtual Int32 NumberOfJobs { public: Int32 get(); internal: void set(Int32 numOfJobs); } /// /// Share name property. NULL if the printer isn't shared. /// property virtual String^ ShareName { String^ get(); void set(String^ inShareName); } /// /// Comment property. /// property virtual String^ Comment { String^ get(); void set(String^ inComment); } /// /// Physical location property. /// property virtual String^ Location { String^ get(); void set(String^ inLocation); } /// /// Description property. /// property virtual String^ Description { String^ get(); internal: void set(String^ inDescription); } /// /// Specifies the name of the file used to create the separator page. /// This page is used to separate print jobs sent to the printer. /// property virtual String^ SeparatorFile { String^ get(); void set(String^ inSeparatorFile); } /// /// Per user PrintTicket property. /// property virtual PrintTicket^ UserPrintTicket { /// /// Critical - Get needs to elevate to be able to convert the DEVMODE to a PrintTicket /// PublicOK - Enabled only if the printQueue was created in PT, code path controlled by the Avalon Print Dialog /// [SecurityCritical] PrintTicket^ get(); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe /// [SecuritySafeCritical] void set(PrintTicket^ newUserPrintTicket); } /// /// Default PrintTicket property. /// property virtual PrintTicket^ DefaultPrintTicket { /// /// Critical - Get needs to elevate to be able to convert the DEVMODE to a PrintTicket /// PublicOK - Enabled only if the printQueue was created in PT, code path controlled by the Avalon Print Dialog /// [SecurityCritical] PrintTicket^ get(); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe /// [SecuritySafeCritical] void set(PrintTicket^ newDefaultPrintTicket); } /// /// Print queue driver property. /// property virtual PrintDriver^ QueueDriver { PrintDriver^ get(); void set(PrintDriver^ driver); } /// /// Print queue port property. /// property virtual PrintPort^ QueuePort { PrintPort^ get(); void set(PrintPort^ port); } /// /// Print queue print processor property. /// property virtual PrintProcessor^ QueuePrintProcessor { PrintProcessor^ get(); void set(PrintProcessor^ printProcessor); } /// /// Hosting print server property. /// property virtual PrintServer^ HostingPrintServer { public: PrintServer^ get(); protected: void set(PrintServer^ printServer); } /// /// Printer UNC name property. /// property String^ FullName { String^ get(); } /// /// Print Queue status property. /// property PrintQueueStatus QueueStatus { PrintQueueStatus get(); } /// /// Print Queue attributes property. /// property PrintQueueAttributes QueueAttributes { PrintQueueAttributes get(); } /// /// Printer is paused property. /// property Boolean IsPaused { Boolean get(); } /// /// Printer is in error state property. /// property Boolean IsInError { Boolean get(); } /// /// Printer is in pending deletion property. /// property Boolean IsPendingDeletion { Boolean get(); } /// /// Printer is jammed property. /// property Boolean IsPaperJammed { Boolean get(); } /// /// Printer is out of paper property. /// property Boolean IsOutOfPaper { Boolean get(); } /// /// Printer needs manual feed property. /// property Boolean IsManualFeedRequired { Boolean get(); } /// /// The printer has paper problem property. /// property Boolean HasPaperProblem { Boolean get(); } /// /// Printer is offline property. /// property Boolean IsOffline { Boolean get(); } /// /// Printer is IO active property. /// property Boolean IsIOActive { Boolean get(); } /// /// Printer is busy property. /// property Boolean IsBusy { Boolean get(); } /// /// Printer is printing property. /// property Boolean IsPrinting { Boolean get(); } /// /// Print output bin is full property. /// property Boolean IsOutputBinFull { Boolean get(); } /// /// Printer is not available property. /// property Boolean IsNotAvailable { Boolean get(); } /// /// Printer is waiting for data property. /// property Boolean IsWaiting { Boolean get(); } /// /// Printer is processing data property. /// property Boolean IsProcessing { Boolean get(); } /// /// Printer is initializing property. /// property Boolean IsInitializing { Boolean get(); } /// /// Printer is warming up property. /// property Boolean IsWarmingUp { Boolean get(); } /// /// Printer toner is low property. /// property Boolean IsTonerLow { Boolean get(); } /// /// Printer has toner property. /// property Boolean HasToner { Boolean get(); } /// /// Printer does page punt property. /// property Boolean PagePunt { Boolean get(); } /// /// Printer needs user intervention property. /// property Boolean NeedUserIntervention { Boolean get(); } /// /// Printer is out of memory property. /// property Boolean IsOutOfMemory { Boolean get(); } /// /// Printer has door opened property. /// property Boolean IsDoorOpened { Boolean get(); } /// /// Server unknown error state property. /// property Boolean IsServerUnknown { Boolean get(); } /// /// Printer power save is on property. /// property Boolean IsPowerSaveOn { Boolean get(); } /// /// Printer is queued property. /// property Boolean IsQueued { Boolean get(); } /// /// Printer supports direct printing property. /// property Boolean IsDirect { Boolean get(); } /// /// Printer is shared property. /// property Boolean IsShared { Boolean get(); } /// /// Printer is hidden property. /// property Boolean IsHidden { Boolean get(); } /// /// Device query is enabled property. /// property Boolean IsDevQueryEnabled { Boolean get(); } /// /// Printer keeps printed jobs property. /// property Boolean KeepPrintedJobs { Boolean get(); } /// /// Completed jobs are scheduled first property. /// property Boolean ScheduleCompletedJobsFirst { Boolean get(); } /// /// Is bidirectional communication enabled for printer property. /// property Boolean IsBidiEnabled { Boolean get(); } /// /// Is raw printing enabled property. /// property Boolean IsRawOnlyEnabled { Boolean get(); } /// /// Printer is published in Directory services property. /// property Boolean IsPublished { Boolean get(); } /// /// Printer is an xps device or a GDI based device. /// /// /// Critical - Calls GetIsXpsDevice which asserts to determine if the device is Xps enabled /// PublicOK - Not critical in PT. Besides, a PT caller can never get a hold of a printQueue. /// property Boolean IsXpsDevice { public: [SecurityCritical] Boolean get(); internal: void set(Boolean isMetroEnabled); } /// /// Maximum print schema version property. /// property static Int32 MaxPrintSchemaVersion { /// /// Critical - References type from non-APTCA reachframework.dll (PrintTicketManager) /// TreatAsSafe - Use of type is safe /// [SecuritySafeCritical] Int32 get(); } /// /// Client print schema version property. /// property Int32 ClientPrintSchemaVersion { Int32 get(); } property Boolean InPartialTrust { /// /// Critical - When this property is set to True, /// a PremiumPrintStream created for this printQueue asserts /// DefaultPrinting to enable printing in Partial Trust. Access /// to this demands Default Printing Permissions /// [SecurityCritical] void set(Boolean isPT); /// /// Critical - When this property is set to True, /// a PremiumPrintStream created for this printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// PublicOK - Reading the value is considered safe. /// [SecurityCritical] Boolean get(); } /// /// Commits the properties marked as modified to the Print Spooler service. /// /// /// Inherited from PrintSystemObject. /// /// Thrown on failure or partial success. /// /// Critical - Uses type from non-APTCA Reachframework (PrintCommitAttributesException). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] virtual void Commit( void ) override; /// /// Synchronizes the data in the properties with the live data from the Print Spooler service. /// /// /// When calling Refresh, data in uncommitted properties is lost. /// Inherited from PrintSystemObject. /// /// Thrown on failure. virtual void Refresh( void ) override; internal: /// /// Return an implementation ot ILegacyDevice implementation for printing to legacy printers /// /// /// This is only used by XpsFramework.DLL. It should be made internal or using link demand. /// [FriendAccessAllowed] ILegacyDevice ^ GetLegacyDevice( void ); [FriendAccessAllowed] static unsigned GetDpiX( ILegacyDevice ^legacyDevice ); [FriendAccessAllowed] static unsigned GetDpiY( ILegacyDevice ^legacyDevice ); protected: /// /// Critical - Calls Dispose on critical SafeHandles /// [SecurityCritical] virtual void InternalDispose( bool disposing ) override sealed; internal: /* -------------------------------------------------------------- The Longhorn API classes are dealing with both new types and downlovel types thunked to the Win32 APIs. To give an example: The Print Server in win32 == a string The Print Server in LAPI == a PrintServer object and so is the case for many other types like Drivers, Port ... etc. For that reason I am introducing those internal members like HostingPrintServerName and DefaultDevMode to allow this conversion when going to downlevel from LAPI and the other way around. On the level of collections, I have a collection of the LAPI properties and a collection of the Win32 properties and the InternalPropertiesCollection can pick the right collection based on the property name. ---------------------------------------------------------------- */ virtual PrintPropertyDictionary^ get_InternalPropertiesCollection( String^ attributeName ) override; // FIX: remove pragma. done to fix compiler error which will be fixed later. #pragma warning ( disable:4376 ) property String^ HostingPrintServerName { void set(String^ printServerName); } property array^ DefaultDevMode { /// /// Critical - Uses type from non-APTCA Reachframework (PrintTicket). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] void set(array^ devMode); } property array^ UserDevMode { /// /// Critical - Uses type from non-APTCA Reachframework (PrintTicket). /// PublicOK - Types use is safe. /// [SecuritySafeCritical] void set(array^ devMode); } property String^ QueueDriverName { void set(String^ driverName); } property String^ QueuePortName { void set(String^ portName); } property String^ QueuePrintProcessorName { void set(String^ printProcessorName); } property Int32 Status { void set(Int32 status); } property Int32 Attributes { void set(Int32 attributes); } property MS::Internal::PrintWin32Thunk::PrinterThunkHandler^ PrinterThunkHandler { MS::Internal::PrintWin32Thunk::PrinterThunkHandler^ get(); } #pragma warning ( default:4376 ) static array^ GetAllPropertiesFilter( void ); /// /// Critical - Uses types from non-APTCA reachframework.dll (ValidationResult, PrintTicket) /// [SecurityCritical] array^ GetAlteredPropertiesFilter( StringCollection^ collection ); static array^ GetAllPropertiesFilter( array^ propertiesFilter ); static void RegisterAttributesNamesTypes( void ); static PrintSystemObject^ Instantiate( array^ propertiesFilter ); static PrintSystemObject^ InstantiateOptimized( Object^ printServer, array^ propertiesFilter ); static PrintProperty^ CreateAttributeNoValue( String^ ); static PrintProperty^ CreateAttributeValue( String^, Object^ ); static PrintProperty^ CreateAttributeNoValueLinked( String^, MulticastDelegate^ ); static PrintProperty^ CreateAttributeValueLinked( String^, Object^, MulticastDelegate^ ); internal: static String^ GetAttributeNamePerPrintQueueObject( PrintProperty^ attributeValue ); static Object^ GetAttributeValuePerPrintQueueObject( PrintProperty^ attributeValue ); static array^ ConvertPropertyFilterToString( array^ propertiesFilter ); static String^ BuildPortNamesString( array^ portNames ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe /// [SecuritySafeCritical] static Stream^ ClonePrintTicket( Stream^ printTicket ); void ActivateBrowsableQueue( void ); public: // // XPSEmitter Implementation // static XpsDocumentWriter^ CreateXpsDocumentWriter( PrintQueue^ printQueue ); /// /// Critical - Calls ShowDialog which is critical /// PublicOK - A PrintQueue object cannot be created in Partial Trust, as the caller needs DefaultPrinting /// This method is meant to be called in Partial Trust and it invokes Avalon UI dialog which will /// create the PrintQueue object for it. The InPartialTrust property is set on the PrintQueue object /// by this method to indicate that a PremiumPrintStream class created for it /// can elevate permissions to enable printing in PT /// Remark......- Indirectly sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static XpsDocumentWriter^ CreateXpsDocumentWriter( double% width, double% height ); /// /// Critical - Calls ShowDialog which is critical /// PublicOK - A PrintQueue object cannot be created in Partial Trust, as the caller needs DefaultPrinting /// This method is meant to be called in Partial Trust and it invokes Avalon UI dialog which will /// create the PrintQueue object for it. The InPartialTrust property is set on the PrintQueue object /// by this method to indicate that a PremiumPrintStream class created for it /// can elevate permissions to enable printing in PT /// Remark......- Indirectly sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static XpsDocumentWriter^ CreateXpsDocumentWriter( PrintDocumentImageableArea^% documentImageableArea ); /// /// Critical - Calls ShowDialog which is critical /// PublicOK - A PrintQueue object cannot be created in Partial Trust, as the caller needs DefaultPrinting /// This method is meant to be called in Partial Trust and it invokes Avalon UI dialog which will /// create the PrintQueue object for it. The InPartialTrust property is set on the PrintQueue object /// by this method to indicate that a PremiumPrintStream class created for it /// can elevate permissions to enable printing in PT /// Remark......- Indirectly sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static XpsDocumentWriter^ CreateXpsDocumentWriter( PrintDocumentImageableArea^% documentImageableArea, System::Windows::Controls::PageRangeSelection% pageRangeSelection, System::Windows::Controls::PageRange% pageRange ); /// /// Critical - Calls ShowDialog which is critical /// PublicOK - A PrintQueue object cannot be created in Partial Trust, as the caller needs DefaultPrinting /// This method is meant to be called in Partial Trust and it invokes Avalon UI dialog which will /// create the PrintQueue object for it. The InPartialTrust property is set on the PrintQueue object /// by this method to indicate that a PremiumPrintStream class created for it /// can elevate permissions to enable printing in PT /// Remark......- Indirectly sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static XpsDocumentWriter^ CreateXpsDocumentWriter( String^ jobDescription, PrintDocumentImageableArea^% documentImageableArea ); /// /// Critical - Calls ShowDialog which is critical /// PublicOK - A PrintQueue object cannot be created in Partial Trust, as the caller needs DefaultPrinting /// This method is meant to be called in Partial Trust and it invokes Avalon UI dialog which will /// create the PrintQueue object for it. The InPartialTrust property is set on the PrintQueue object /// by this method to indicate that a PremiumPrintStream class created for it /// can elevate permissions to enable printing in PT /// Remark......- Indirectly sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static XpsDocumentWriter^ CreateXpsDocumentWriter( String^ jobDescription, PrintDocumentImageableArea^% documentImageableArea, System::Windows::Controls::PageRangeSelection% pageRangeSelection, System::Windows::Controls::PageRange% pageRange ); internal: /// /// Critical - Returns type from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] PackageSerializationManager^ CreateSerializationManager( bool isBatchMode ); /// /// Critical - Returns type from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] PackageSerializationManager^ CreateSerializationManager( bool isBatchMode, bool mustSetJobIdentifier ); /// /// Critical - Returns type from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] PackageSerializationManager^ CreateSerializationManager( bool isBatchMode, bool mustSetJobIdentifier, PrintTicket^ printTicket ); /// /// Critical - Returns type from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] PackageSerializationManager^ CreateAsyncSerializationManager( bool isBatchMode ); /// /// Critical - Returns type from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] PackageSerializationManager^ CreateAsyncSerializationManager( bool isBatchMode, bool mustSetJobIdentifier ); /// /// Critical - Uses types from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] void DisposeSerializationManager( void ); /// /// Critical - Uses types from non-APTCA reachframework.dll (PackageSerializationManager) /// [SecurityCritical] void DisposeSerializationManager( bool abort ); static String^ defaultXpsJobName; internal: /// /// Critical - Asserts for DefaultPrinting to enable making the Xps DrvDocumentEvent driver notifications /// [SecurityCritical] Int32 PrintQueue:: XpsDocumentEvent( XpsDocumentEventType escape, SafeHandle^ inputBufferSafeHandle ); /// /// Critical - Asserts for DefaultPrinting to enable making the Xps DrvDocumentEvent driver notifications /// [SecurityCritical] Int32 XpsDocumentEventPrintTicket( XpsDocumentEventType preEscape, XpsDocumentEventType postEscape, SafeHandle^ inputBufferSafeHandle, System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Asserts for DefaultPrinting to enable making the Xps DrvDocumentEvent driver notifications /// TreatAsSafe - This is considered safe, because the PrintQueue has the InPartialTrust set only if /// created by the Avalon Print UI /// [SecuritySafeCritical] void XpsDocumentEventCancel( void ); private: /// /// Critical - References type in non-APTCA reachframework.dll (PrintTicket) /// - See primaryAttributeTypes static initializer /// TreatAsSafe - Type is safe /// [SecuritySafeCritical] static PrintQueue( void ) { upLevelToDownLevelMapping = gcnew Hashtable(); attributeNameTypes = gcnew Hashtable(); defaultXpsJobName = gcnew String(""Xps Document""); // // Map upLevel properties to downLevel properties // if(upLevelAttributeName->Length != downLevelAttributeName->Length) { InternalExceptionResourceManager^ manager = gcnew InternalExceptionResourceManager(); String^ resString = manager->GetString(""IndexOutOfRangeException.InvalidSize"", System::Threading::Thread::CurrentThread->CurrentUICulture); String^ exceptionMessage = String::Format(System::Threading::Thread::CurrentThread->CurrentUICulture, resString, ""upLevelAttributeName"", ""downLevelAttributeName""); throw gcnew IndexOutOfRangeException(exceptionMessage); } for(Int32 numOfMappings = 0; numOfMappings < upLevelAttributeName->Length; numOfMappings++) { upLevelToDownLevelMapping->Add(upLevelAttributeName[numOfMappings], downLevelAttributeName[numOfMappings]); } } /// /// Critical - Instantiates type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe /// [SecuritySafeCritical] array^ CreatePropertiesDelegates( void ); void VerifyAccess( void ); void InitializeInternalCollections( void ); /// /// Critical - Uses non-APTCA reachframework.dll type (PrintTicket) to set the user print ticket and default print ticket to null /// TreatAsSafe - Types are safe /// [SecuritySafeCritical] void InitializePrintTickets( void ); /// /// Critical - Sets InPartialTrust property to initialize the SecurityCritical member. /// TreatAsSafe - It sets InPartialTrust to false, which prevents making any elevations in PT /// [SecuritySafeCritical] void Initialize( PrintServer^ printServer, String^ printQueueName, array^ propertiesFilter, PrinterDefaults^ printerDefaults ); void GetUnInitializedData( String^ upLevelPropertyName, String^ downlevelPropertyName ); String^ PrepareNameForDownLevelConnectivity( String^ serverName, String^ printerName ); /// /// Critical - Asserts for DefaultPrinting to determine if the device is Xps enabled /// [SecurityCritical] Boolean GetIsXpsDevice( void ); /// /// Critical - References type from non-APTCA reachframework.dll (XpsDocumentEventType) /// TreatAsSafe - Type is safe enum /// [SecuritySafeCritical] void ForwardXpsDriverDocEvent( Object^ sender, System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ args ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// [SecuritySafeCritical] void PrintQueue:: ForwardXpsFixedDocumentSequenceEvent( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// [SecuritySafeCritical] void ForwardXpsFixedDocumentEvent( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// [SecuritySafeCritical] void ForwardXpsFixedPageEvent( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// The event can carry on a PrintTicket which is considered safe as /// the XML data it contains is validated to be well formed. A PT caller could /// change this data, however that is subject to PrintTicket parser validation. /// Any custom data can only be generated by the print driver and not by the PT caller /// and that is condsidered safe as it's being passed back to the same print driver. /// [SecuritySafeCritical] void ForwardXpsFixedDocumentSequencePrintTicket( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// The event can carry on a PrintTicket which is considered safe as /// the XML data it contains is validated to be well formed. A PT caller could /// change this data, however that is subject to PrintTicket parser validation. /// Any custom data can only be generated by the print driver and not by the PT caller /// and that is condsidered safe as it's being passed back to the same print driver. /// [SecuritySafeCritical] void ForwardXpsFixedDocumentPrintTicket( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Calls XpsDocumentEvent which is critical due the input buffer /// TreatAsSafe - The buffer passed to XpsDocumentEvent is being created in this method /// based on XpsSerializationXpsDriverDocEventArgs which cannot be altered by PT caller. /// The event can carry on a PrintTicket which is considered safe as /// the XML data it contains is validated to be well formed. A PT caller could /// change this data, however that is subject to PrintTicket parser validation. /// Any custom data can only be generated by the print driver and not by the PT caller /// and that is condsidered safe as it's being passed back to the same print driver. /// [SecuritySafeCritical] void ForwardXpsFixedPagePrintTicket( System::Windows::Xps::Serialization::XpsSerializationXpsDriverDocEventArgs^ e ); /// /// Critical - Asserts DefaultPrinting to be able to call IsXpsDocumentEventSupported on the printerThunkHandler /// TreatAsSafe - This is considered safe as the assert is done only if the PrintQueue /// was created by the Avalon PrintDialog. /// [SecuritySafeCritical] Boolean IsXpsDocumentEventSupported( XpsDocumentEventType escape ); ref class PartialTrustPrintTicketEventHandler { public: /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// Safe - Type is safe /// [SecuritySafeCritical] PartialTrustPrintTicketEventHandler( PrintTicket^ printTicket ); /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// [SecurityCritical] void SetPrintTicketInPartialTrust( Object^ sender, WritingPrintTicketRequiredEventArgs^ e ); private: /// /// Critical - PT user input /// [SecurityCritical] PrintTicket^ partialTrustPrintTicket; Boolean isPrintTicketHandedOver; }; /// /// Critical - Calls GatherDataFromPrintDialog and returns print ticket and print queue. /// [SecurityCritical] static bool ShowPrintDialog( XpsDocumentWriter^% xpsDocumentWriter, PrintTicket^% partialTrustPrintTicket, PrintQueue^% partialTrustPrintQueue, double% width, double% height, String^ jobDescription ); /// /// Critical - Calls GatherDataFromPrintDialog and returns print ticket and print queue. /// [SecurityCritical] static bool ShowPrintDialogEnablePageRange( XpsDocumentWriter^% xpsDocumentWriter, PrintTicket^% partialTrustPrintTicket, PrintQueue^% partialTrustPrintQueue, double% width, double% height, System::Windows::Controls::PageRangeSelection% pageRangeSelection, System::Windows::Controls::PageRange% pageRange, String^ jobDescription ); /// /// Critical 1 )Asserts for DefaultPrinting to get print ticket and from /// print dialog. Both are out paameters. /// 2 )Sets the InPartialTrust on a PrintQueue created by invoking the Avalon UI /// When the property is set, a PremiumPrintStream class created for a printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] static bool PrintQueue:: GatherDataFromPrintDialog( System::Windows::Controls::PrintDialog^ printDialog, XpsDocumentWriter^% writer, PrintTicket^% partialTrustPrintTicket, PrintQueue^% partialTrustPrintQueue, double% width, double% height, String^ jobDescription ); /// /// Critical - Asserts for DefaultPrinting to get print capablities /// [SecurityCritical] static PrintDocumentImageableArea^ CalculateImagableArea( PrintTicket^ partialTrustPrintTicket, PrintQueue^ partialTrustPrintQueue, double height, double width ); /// /// Critical - Uses type from non-APTCA reachframework.dll /// Safe - Type is safe /// [SecuritySafeCritical] Exception^ CreatePrintQueueException( int hresult, String^ messageId ); /// /// Critical - Uses type from non-APTCA reachframework.dll /// Safe - Type is safe /// [SecuritySafeCritical] static Exception^ CreatePrintSystemException( int hresult, String^ messageId ); // // The following are the set of propeties mapping // the old Win32 properties of a PrintQueue to the // new object types // bool isDisposed; Int32 priority; Int32 defaultPriority; Int32 startTime; Int32 untilTime; Int32 averagePagesPerMinute; Int32 numberOfJobs; String^ shareName; String^ comment; String^ location; String^ description; String^ separatorFile; /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// [SecurityCritical] PrintTicket^ userPrintTicket; /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// [SecurityCritical] PrintTicket^ defaultPrintTicket; PrintQueueAttributes queueAttributes; PrintQueueStatus queueStatus; PrintPort^ queuePort; PrintDriver^ queueDriver; PrintProcessor^ queuePrintProcessor; PrintServer^ hostingPrintServer; String^ hostingPrintServerName; /// /// Critical - Uses type from non-APTCA reachframework.dll (PrintTicket) /// [SecurityCritical] PrintTicketManager^ printTicketManager; PrintJobSettings^ _currentJobSettings; // // The following set of boolean properties represent // the status of the PrintQueue // Boolean isPaused; Boolean isInError; Boolean isPendingDeletion; Boolean isPaperJammed; Boolean isOutOfPaper; Boolean isManualFeedRequired; Boolean hasPaperProblem; Boolean isOffline; Boolean isIOActive; Boolean isBusy; Boolean isPrinting; Boolean isOutputBinFull; Boolean isNotAvailable; Boolean isWaiting; Boolean isProcessing; Boolean isInitializing; Boolean isWarmingUp; Boolean isTonerLow; Boolean hasNoToner; Boolean doPagePunt; Boolean needUserIntervention; Boolean isOutOfMemory; Boolean isDoorOpened; Boolean isServerUnknown; Boolean isPowerSaveOn; Boolean printingIsCancelled; // // The following set of boolean properties represent // the Attributes of the PrintQueue // Boolean isQueued; Boolean isDirect; Boolean isShared; Boolean isHidden; Boolean isDevQueryEnabled; Boolean arePrintedJobsKept; Boolean areCompletedJobsScheduledFirst; Boolean isBidiEnabled; Boolean isRawOnlyEnabled; Boolean isPublished; Boolean isXpsDevice; /// /// Critical - When this value is set to True, /// a PremiumPrintStream created for this printQueue asserts /// DefaultPrinting to enable printing in Partial Trust /// [SecurityCritical] Boolean runsInPartialTrust; // // The following is the necessary data members to link the // compile time properties with the named properties in the // associated collection // static array^ primaryAttributeNames = { L""ShareName"", L""Comment"", L""Location"", L""Description"", L""Priority"", L""DefaultPriority"", L""StartTimeOfDay"", L""UntilTimeOfDay"", L""AveragePagesPerMinute"", L""NumberOfJobs"", L""QueueAttributes"", L""QueueDriver"", L""QueuePort"", L""QueuePrintProcessor"", L""HostingPrintServer"", L""QueueStatus"", L""SeparatorFile"", L""DefaultPrintTicket"", L""UserPrintTicket"", L""IsXpsEnabled"" }; static array^ primaryAttributeTypes = { String::typeid, String::typeid, String::typeid, String::typeid, Int32::typeid, Int32::typeid, Int32::typeid, Int32::typeid, Int32::typeid, Int32::typeid, PrintQueueAttributes::typeid, PrintDriver::typeid, PrintPort::typeid, PrintProcessor::typeid, PrintServer::typeid, PrintQueueStatus::typeid, String::typeid, PrintTicket::typeid, PrintTicket::typeid, Boolean::typeid }; static array^ secondaryAttributeNames = { L""HostingPrintServerName"", L""QueueDriverName"", L""QueuePrintProcessorName"", L""QueuePortName"", L""DefaultDevMode"", L""UserDevMode"", L""Status"", L""Attributes"" }; static array^ secondaryAttributeTypes= { String::typeid, String::typeid, String::typeid, String::typeid, array::typeid, array::typeid, Int32::typeid, Int32::typeid }; static array^ upLevelAttributeName = { L""HostingPrintServer"", L""QueueDriver"", L""QueuePrintProcessor"", L""QueuePort"", L""DefaultPrintTicket"", L""UserPrintTicket"", L""QueueStatus"", L""QueueAttributes"", }; static array^ downLevelAttributeName = { L""HostingPrintServerName"", L""QueueDriverName"", L""QueuePrintProcessorName"", L""QueuePortName"", L""DefaultDevMode"", L""UserDevMode"", L""Status"", L""Attributes"" }; Hashtable^ collectionsTable; static Hashtable^ attributeNameTypes; static Hashtable^ upLevelToDownLevelMapping; // // I distinct between Print Objects returned from an // object instantiation and those returned from an // enumeration // Boolean isBrowsable; // // I mentain the following internal Properties Filter // list to know at refresh time which properties should // be refreshed // array^ refreshPropertiesFilter; // // The fully qualified printer name is required by PrintTicket // methods and classes // String^ fullQueueName; // // The following are the members required by the PrintQueue to // thunk in the Win32 APIs // MS::Internal::PrintWin32Thunk::PrinterThunkHandler^ printerThunkHandler; PrintPropertyDictionary^ thunkPropertiesCollection; // // PrintTicket client specific version // Int32 clientPrintSchemaVersion; // // Data specific to XpsDocumentWriter // bool isWriterAttached; /// /// Critical - Uses type from non-APTCA reachframework.dll /// [SecurityCritical] XpsDocument^ xpsDocument; PrintQueueStream^ writerStream; array^ userDevMode; array^ defaultDevMode; PrintSystemDispatcherObject^ accessVerifier; Object^ _lockObject; }; public ref class PrintQueueCollection : public PrintSystemObjects, public System::Collections::Generic::IEnumerable, public IEnumerable, public IDisposable { public: PrintQueueCollection( void ); PrintQueueCollection( PrintServer^ printServer, array^ propertyFilter, array^ enumerationFlag ); PrintQueueCollection( PrintServer^ printServer, array^ propertyFilter ); ~PrintQueueCollection( void ); virtual System::Collections::IEnumerator^ GetNonGenericEnumerator() = System::Collections::IEnumerable::GetEnumerator; virtual System:: Collections:: Generic:: IEnumerator^ GetEnumerator( void ); property static Object^ SyncRoot { Object^ get(); } void Add( PrintQueue^ printObject ); private: static PrintQueueCollection( void ) { PrintQueueCollection::syncRoot = gcnew Object(); } array^ AddNameAndHostToProperties( array^ propertyFilter ); void VerifyAccess( void ); static volatile Object^ syncRoot; // // This is only for illustrative purposes. It could be another // specialized collection that we build and the Enumerator of // which would be linked to the PrinterQueuesEnumerator // System::Collections::Generic::Queue^ printQueuesCollection; PrintSystemDispatcherObject^ accessVerifier; }; } } #endif ",16349,True,3212.0522784866903,median "// Copyright (c) 2014-2019, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ""AS IS"" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include #include #include #include #include ""tx_pool.h"" #include ""cryptonote_tx_utils.h"" #include ""cryptonote_basic/cryptonote_boost_serialization.h"" #include ""cryptonote_config.h"" #include ""blockchain.h"" #include ""blockchain_db/locked_txn.h"" #include ""blockchain_db/blockchain_db.h"" #include ""common/boost_serialization_helper.h"" #include ""int-util.h"" #include ""misc_language.h"" #include ""warnings.h"" #include ""common/perf_timer.h"" #include ""crypto/hash.h"" #include ""crypto/duration.h"" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY ""txpool"" DISABLE_VS_WARNINGS(4244 4345 4503) //'boost::foreach_detail_::or_' : decorated name length exceeded, name was truncated using namespace crypto; namespace cryptonote { namespace { /*! The Dandelion++ has formula for calculating the average embargo timeout: (-k*(k-1)*hop)/(2*log(1-ep)) where k is the number of hops before this node and ep is the probability that one of the k hops hits their embargo timer, and hop is the average time taken between hops. So decreasing ep will make it more probable that ""this"" node is the first to expire the embargo timer. Increasing k will increase the number of nodes that will be ""hidden"" as a prior recipient of the tx. As example, k=5 and ep=0.1 means ""this"" embargo timer has a 90% probability of being the first to expire amongst 5 nodes that saw the tx before ""this"" one. These values are independent to the fluff probability, but setting a low k with a low p (fluff probability) is not ideal since a blackhole is more likely to reveal earlier nodes in the chain. This value was calculated with k=10, ep=0.10, and hop = 175 ms. A testrun from a recent Intel laptop took ~80ms to receive+parse+proces+send transaction. At least 50ms will be added to the latency if crossing an ocean. So 175ms is the fudge factor for a single hop with 173s being the embargo timer. */ constexpr const std::chrono::seconds dandelionpp_embargo_average{CRYPTONOTE_DANDELIONPP_EMBARGO_AVERAGE}; //TODO: constants such as these should at least be in the header, // but probably somewhere more accessible to the rest of the // codebase. As it stands, it is at best nontrivial to test // whether or not changing these parameters (or adding new) // will work correctly. time_t const MIN_RELAY_TIME = (60 * 5); // only start re-relaying transactions after that many seconds time_t const MAX_RELAY_TIME = (60 * 60 * 4); // at most that many seconds between resends float const ACCEPT_THRESHOLD = 1.0f; // a kind of increasing backoff within min/max bounds uint64_t get_relay_delay(time_t now, time_t received) { time_t d = (now - received + MIN_RELAY_TIME) / MIN_RELAY_TIME * MIN_RELAY_TIME; if (d > MAX_RELAY_TIME) d = MAX_RELAY_TIME; return d; } uint64_t template_accept_threshold(uint64_t amount) { // XXX: multiplying by ACCEPT_THRESHOLD here was removed because of a need // to accept 0 fee transactions correctly. the cast to float / double and // back again was causing issues estimating the effect of a zero fee tx return amount; } uint64_t get_transaction_weight_limit(uint8_t version) { // from v8, limit a tx to 50% of the minimum block weight if (version >= 8) return get_min_block_weight(version) / 2 - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; else return get_min_block_weight(version) - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; } } //--------------------------------------------------------------------------------- //--------------------------------------------------------------------------------- tx_memory_pool::tx_memory_pool(Blockchain& bchs): m_blockchain(bchs), m_cookie(0), m_txpool_max_weight(DEFAULT_TXPOOL_MAX_WEIGHT), m_txpool_weight(0), m_mine_stem_txes(false) { } //--------------------------------------------------------------------------------- bool tx_memory_pool::have_deregister_tx_already(transaction const &tx) const { if (!tx.is_deregister_tx()) return false; tx_extra_service_node_deregister deregister; if (!get_service_node_deregister_from_tx_extra(tx.extra, deregister)) { MERROR(""Could not get service node deregister from tx v3, possibly corrupt tx in your blockchain""); return false; } std::vector pool_txs; get_transactions(pool_txs); for (const transaction& pool_tx : pool_txs) { if (!pool_tx.is_deregister_tx()) continue; tx_extra_service_node_deregister pool_tx_deregister; if (!get_service_node_deregister_from_tx_extra(pool_tx.extra, pool_tx_deregister)) { MERROR(""Could not get service node deregister from tx v3, possibly corrupt tx in your blockchain""); continue; } if ((pool_tx_deregister.block_height == deregister.block_height) && (pool_tx_deregister.service_node_index == deregister.service_node_index)) { return true; } } return false; } //--------------------------------------------------------------------------------- bool tx_memory_pool::add_tx(transaction &tx, /*const crypto::hash& tx_prefix_hash,*/ const crypto::hash &id, const cryptonote::blobdata &blob, size_t tx_weight, tx_verification_context& tvc, relay_method tx_relay, bool relayed, uint8_t version) { const bool kept_by_block = (tx_relay == relay_method::block); // this should already be called with that lock, but let's make it explicit for clarity CRITICAL_REGION_LOCAL(m_transactions_lock); PERF_TIMER(add_tx); if (tx.version == transaction::version_0) { // v0 never accepted LOG_PRINT_L1(""transaction version 0 is invalid""); tvc.m_verifivation_failed = true; return false; } // we do not accept transactions that timed out before, unless they're // kept_by_block if (!kept_by_block && m_timed_out_transactions.find(id) != m_timed_out_transactions.end()) { // not clear if we should set that, since verifivation (sic) did not fail before, since // the tx was accepted before timing out. tvc.m_verifivation_failed = true; return false; } if(!check_inputs_types_supported(tx)) { tvc.m_verifivation_failed = true; tvc.m_invalid_input = true; return false; } // fee per kilobyte, size rounded up. uint64_t fee; if (tx.version == transaction::version_1) { uint64_t inputs_amount = 0; if(!get_inputs_money_amount(tx, inputs_amount)) { tvc.m_verifivation_failed = true; return false; } uint64_t outputs_amount = get_outs_money_amount(tx); if(outputs_amount > inputs_amount) { LOG_PRINT_L1(""transaction use more money than it has: use "" << print_money(outputs_amount) << "", have "" << print_money(inputs_amount)); tvc.m_verifivation_failed = true; tvc.m_overspend = true; return false; } else if(outputs_amount == inputs_amount) { LOG_PRINT_L1(""transaction fee is zero: outputs_amount == inputs_amount, rejecting.""); tvc.m_verifivation_failed = true; tvc.m_fee_too_low = true; return false; } fee = inputs_amount - outputs_amount; } else { fee = tx.rct_signatures.txnFee; } if (!kept_by_block && !tx.is_deregister_tx() && !m_blockchain.check_fee(tx_weight, fee)) { tvc.m_verifivation_failed = true; tvc.m_fee_too_low = true; return false; } size_t tx_weight_limit = get_transaction_weight_limit(version); if ((!kept_by_block || version >= HF_VERSION_PER_BYTE_FEE) && tx_weight > tx_weight_limit) { LOG_PRINT_L1(""transaction is too heavy: "" << tx_weight << "" bytes, maximum weight: "" << tx_weight_limit); tvc.m_verifivation_failed = true; tvc.m_too_big = true; return false; } // if the transaction came from a block popped from the chain, // don't check if we have its key images as spent. // TODO: Investigate why not? if(!kept_by_block) { if(have_tx_keyimges_as_spent(tx, id)) { mark_double_spend(tx); LOG_PRINT_L1(""Transaction with id= ""<< id << "" used already spent key images""); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; } if (have_deregister_tx_already(tx)) { mark_double_spend(tx); LOG_PRINT_L1(""Transaction version 3 with id= "" << id << "" already has a deregister for height""); tvc.m_verifivation_failed = true; tvc.m_double_spend = true; return false; } } if (!m_blockchain.check_tx_outputs(tx, tvc)) { LOG_PRINT_L1(""Transaction with id= ""<< id << "" has at least one invalid output""); tvc.m_verifivation_failed = true; tvc.m_invalid_output = true; return false; } // assume failure during verification steps until success is certain tvc.m_verifivation_failed = true; time_t receive_time = time(nullptr); crypto::hash max_used_block_id = null_hash; uint64_t max_used_block_height = 0; cryptonote::txpool_tx_meta_t meta{}; bool ch_inp_res = check_tx_inputs([&tx]()->cryptonote::transaction&{ return tx; }, id, max_used_block_height, max_used_block_id, tvc, kept_by_block); if(!ch_inp_res) { // if the transaction was valid before (kept_by_block), then it // may become valid again, so ignore the failed inputs check. if(kept_by_block) { meta.weight = tx_weight; meta.fee = fee; meta.max_used_block_id = null_hash; meta.max_used_block_height = 0; meta.last_failed_height = 0; meta.last_failed_id = null_hash; meta.receive_time = receive_time; meta.last_relayed_time = time(NULL); meta.relayed = relayed; meta.set_relay_method(tx_relay); meta.double_spend_seen = (have_tx_keyimges_as_spent(tx, id) || have_deregister_tx_already(tx)); meta.pruned = tx.pruned; meta.bf_padding = 0; meta.is_deregister = tx.is_deregister_tx(); memset(meta.padding, 0, sizeof(meta.padding)); try { if (kept_by_block) m_parsed_tx_cache.insert(std::make_pair(id, tx)); CRITICAL_REGION_LOCAL1(m_blockchain); LockedTXN lock(m_blockchain.get_db()); if (!insert_key_images(tx, id, tx_relay)) return false; m_blockchain.add_txpool_tx(id, blob, meta); m_txs_by_fee_and_receive_time.emplace(std::tuple(tx.is_deregister_tx(), fee / (double)(tx_weight), receive_time), id); lock.commit(); } catch (const std::exception &e) { MERROR(""Error adding transaction to txpool: "" << e.what()); return false; } tvc.m_verifivation_impossible = true; tvc.m_added_to_pool = true; }else { LOG_PRINT_L1(""tx used wrong inputs, rejected""); tvc.m_verifivation_failed = true; tvc.m_invalid_input = true; return false; } }else { try { if (kept_by_block) m_parsed_tx_cache.insert(std::make_pair(id, tx)); CRITICAL_REGION_LOCAL1(m_blockchain); LockedTXN lock(m_blockchain.get_db()); const bool existing_tx = m_blockchain.get_txpool_tx_meta(id, meta); if (existing_tx) { /* If Dandelion++ loop. Do not use txes in the `local` state in the loop detection - txes in that state should be outgoing over i2p/tor then routed back via public dandelion++ stem. Pretend to be another stem node in that situation, a loop over the public network hasn't been hit yet. */ if (tx_relay == relay_method::stem && meta.dandelionpp_stem) tx_relay = relay_method::fluff; } else meta.set_relay_method(relay_method::none); if (meta.upgrade_relay_method(tx_relay) || !existing_tx) // synchronize with embargo timer or stem/fluff out-of-order messages { //update transactions container meta.last_relayed_time = std::numeric_limits::max(); meta.receive_time = receive_time; meta.weight = tx_weight; meta.fee = fee; meta.max_used_block_id = max_used_block_id; meta.max_used_block_height = max_used_block_height; meta.last_failed_height = 0; meta.last_failed_id = null_hash; meta.relayed = relayed; meta.double_spend_seen = false; meta.pruned = tx.pruned; meta.bf_padding = 0; meta.is_deregister = tx.is_deregister_tx(); memset(meta.padding, 0, sizeof(meta.padding)); if (!insert_key_images(tx, id, tx_relay)) return false; m_blockchain.remove_txpool_tx(id); m_blockchain.add_txpool_tx(id, blob, meta); m_txs_by_fee_and_receive_time.emplace(std::tuple(tx.is_deregister_tx(), fee / (double)(tx_weight), receive_time), id); } lock.commit(); } catch (const std::exception &e) { MERROR(""internal error: error adding transaction to txpool: "" << e.what()); return false; } tvc.m_added_to_pool = true; static_assert(unsigned(relay_method::none) == 0, ""expected relay_method::none value to be zero""); if((meta.fee > 0 || tx.is_deregister_tx())) tvc.m_relay = tx_relay; } tvc.m_verifivation_failed = false; m_txpool_weight += tx_weight; ++m_cookie; MINFO(""Transaction added to pool: txid "" << id << "" weight: "" << tx_weight << "" fee/byte: "" << (fee / (double)(tx_weight ? tx_weight : 1))); prune(m_txpool_max_weight); return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::add_tx(transaction &tx, tx_verification_context& tvc, relay_method tx_relay, bool relayed, uint8_t version) { crypto::hash h = null_hash; size_t blob_size = 0; cryptonote::blobdata bl; t_serializable_object_to_blob(tx, bl); if (bl.size() == 0 || !get_transaction_hash(tx, h)) return false; return add_tx(tx, h, bl, get_transaction_weight(tx, bl.size()), tvc, tx_relay, relayed, version); } //--------------------------------------------------------------------------------- size_t tx_memory_pool::get_txpool_weight() const { CRITICAL_REGION_LOCAL(m_transactions_lock); return m_txpool_weight; } //--------------------------------------------------------------------------------- void tx_memory_pool::set_txpool_max_weight(size_t bytes) { CRITICAL_REGION_LOCAL(m_transactions_lock); m_txpool_max_weight = bytes; } //--------------------------------------------------------------------------------- void tx_memory_pool::prune(size_t bytes) { CRITICAL_REGION_LOCAL(m_transactions_lock); if (bytes == 0) bytes = m_txpool_max_weight; CRITICAL_REGION_LOCAL1(m_blockchain); LockedTXN lock(m_blockchain.get_db()); bool changed = false; // this will never remove the first one, but we don't care auto it = --m_txs_by_fee_and_receive_time.end(); while (it != m_txs_by_fee_and_receive_time.begin()) { const bool is_deregister = std::get<0>(it->first); const time_t receive_time = std::get<2>(it->first); if (!is_deregister || receive_time >= time(nullptr) - MEMPOOL_PRUNE_DEREGISTER_LIFETIME) break; if (m_txpool_weight <= bytes) break; try { const crypto::hash &txid = it->second; txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { MERROR(""Failed to find tx_meta in txpool""); return; } // don't prune the kept_by_block ones, they're likely added because we're adding a block with those if (meta.kept_by_block) { --it; continue; } cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(txid, relay_category::all); cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(txblob, tx)) { MERROR(""Failed to parse tx from txpool""); return; } // remove first, in case this throws, so key images aren't removed MINFO(""Pruning tx "" << txid << "" from txpool: weight: "" << meta.weight << "", fee/byte: "" << std::get<1>(it->first)); m_blockchain.remove_txpool_tx(txid); m_txpool_weight -= meta.weight; remove_transaction_keyimages(tx, txid); MINFO(""Pruned tx "" << txid << "" from txpool: weight: "" << meta.weight << "", fee/byte: "" << std::get<1>(it->first)); m_txs_by_fee_and_receive_time.erase(it--); changed = true; } catch (const std::exception &e) { MERROR(""Error while pruning txpool: "" << e.what()); return; } } lock.commit(); if (changed) ++m_cookie; if (m_txpool_weight > bytes) MINFO(""Pool weight after pruning is larger than limit: "" << m_txpool_weight << ""/"" << bytes); } //--------------------------------------------------------------------------------- bool tx_memory_pool::insert_key_images(const transaction_prefix &tx, const crypto::hash &id, relay_method tx_relay) { for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, txin, false); std::unordered_set& kei_image_set = m_spent_key_images[txin.k_image]; // Only allow multiple txes per key-image if kept-by-block. Only allow // the same txid if going from local/stem->fluff. if (tx_relay != relay_method::block) { const bool one_txid = (kei_image_set.empty() || (kei_image_set.size() == 1 && *(kei_image_set.cbegin()) == id)); CHECK_AND_ASSERT_MES(one_txid, false, ""internal error: tx_relay="" << unsigned(tx_relay) << "", kei_image_set.size()="" << kei_image_set.size() << ENDL << ""txin.k_image="" << txin.k_image << ENDL << ""tx_id="" << id); } const bool new_or_previously_private = kei_image_set.insert(id).second || !m_blockchain.txpool_tx_matches_category(id, relay_category::legacy); CHECK_AND_ASSERT_MES(new_or_previously_private, false, ""internal error: try to insert duplicate iterator in key_image set""); } ++m_cookie; return true; } //--------------------------------------------------------------------------------- //FIXME: Can return early before removal of all of the key images. // At the least, need to make sure that a false return here // is treated properly. Should probably not return early, however. bool tx_memory_pool::remove_transaction_keyimages(const transaction_prefix& tx, const crypto::hash &actual_hash) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); // ND: Speedup for(const txin_v& vi: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(vi, const txin_to_key, txin, false); auto it = m_spent_key_images.find(txin.k_image); CHECK_AND_ASSERT_MES(it != m_spent_key_images.end(), false, ""failed to find transaction input in key images. img="" << txin.k_image << ENDL << ""transaction id = "" << actual_hash); std::unordered_set& key_image_set = it->second; CHECK_AND_ASSERT_MES(key_image_set.size(), false, ""empty key_image set, img="" << txin.k_image << ENDL << ""transaction id = "" << actual_hash); auto it_in_set = key_image_set.find(actual_hash); CHECK_AND_ASSERT_MES(it_in_set != key_image_set.end(), false, ""transaction id not found in key_image set, img="" << txin.k_image << ENDL << ""transaction id = "" << actual_hash); key_image_set.erase(it_in_set); if(!key_image_set.size()) { //it is now empty hash container for this key_image m_spent_key_images.erase(it); } } ++m_cookie; return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::take_tx(const crypto::hash &id, transaction &tx, cryptonote::blobdata &txblob, size_t& tx_weight, uint64_t& fee, bool &relayed, bool &do_not_relay, bool &double_spend_seen, bool &pruned) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); auto sorted_it = find_tx_in_sorted_container(id); try { LockedTXN lock(m_blockchain.get_db()); txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(id, meta)) { MERROR(""Failed to find tx_meta in txpool""); return false; } txblob = m_blockchain.get_txpool_tx_blob(id, relay_category::all); auto ci = m_parsed_tx_cache.find(id); if (ci != m_parsed_tx_cache.end()) { tx = ci->second; } else if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(txblob, tx) : parse_and_validate_tx_from_blob(txblob, tx))) { MERROR(""Failed to parse tx from txpool""); return false; } else { tx.set_hash(id); } tx_weight = meta.weight; fee = meta.fee; relayed = meta.relayed; do_not_relay = meta.do_not_relay; double_spend_seen = meta.double_spend_seen; pruned = meta.pruned; // remove first, in case this throws, so key images aren't removed m_blockchain.remove_txpool_tx(id); m_txpool_weight -= tx_weight; remove_transaction_keyimages(tx, id); lock.commit(); } catch (const std::exception &e) { MERROR(""Failed to remove tx from txpool: "" << e.what()); return false; } if (sorted_it != m_txs_by_fee_and_receive_time.end()) m_txs_by_fee_and_receive_time.erase(sorted_it); ++m_cookie; return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::get_transaction_info(const crypto::hash &txid, tx_details &td) const { PERF_TIMER(get_transaction_info); CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); try { LockedTXN lock(m_blockchain.get_db()); txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { MERROR(""Failed to find tx in txpool""); return false; } cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(txid, relay_category::all); auto ci = m_parsed_tx_cache.find(txid); if (ci != m_parsed_tx_cache.end()) { td.tx = ci->second; } else if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(txblob, td.tx) : parse_and_validate_tx_from_blob(txblob, td.tx))) { MERROR(""Failed to parse tx from txpool""); return false; } else { td.tx.set_hash(txid); } td.blob_size = txblob.size(); td.weight = meta.weight; td.fee = meta.fee; td.max_used_block_id = meta.max_used_block_id; td.max_used_block_height = meta.max_used_block_height; td.kept_by_block = meta.kept_by_block; td.last_failed_height = meta.last_failed_height; td.last_failed_id = meta.last_failed_id; td.receive_time = meta.receive_time; td.last_relayed_time = meta.dandelionpp_stem ? 0 : meta.last_relayed_time; td.relayed = meta.relayed; td.do_not_relay = meta.do_not_relay; td.double_spend_seen = meta.double_spend_seen; } catch (const std::exception &e) { MERROR(""Failed to get tx from txpool: "" << e.what()); return false; } return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::get_complement(const std::vector &hashes, std::vector &txes) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); m_blockchain.for_all_txpool_txes([this, &hashes, &txes](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata*) { const auto tx_relay_method = meta.get_relay_method(); if (tx_relay_method != relay_method::block && tx_relay_method != relay_method::fluff) return true; const auto i = std::find(hashes.begin(), hashes.end(), txid); if (i == hashes.end()) { cryptonote::blobdata bd; try { if (!m_blockchain.get_txpool_tx_blob(txid, bd, cryptonote::relay_category::broadcasted)) { MERROR(""Failed to get blob for txpool transaction "" << txid); return true; } txes.emplace_back(std::move(bd)); } catch (const std::exception &e) { MERROR(""Failed to get blob for txpool transaction "" << txid << "": "" << e.what()); return true; } } return true; }, false); return true; } //--------------------------------------------------------------------------------- void tx_memory_pool::on_idle() { m_remove_stuck_tx_interval.do_call([this](){return remove_stuck_transactions();}); } //--------------------------------------------------------------------------------- sorted_tx_container::iterator tx_memory_pool::find_tx_in_sorted_container(const crypto::hash& id) const { return std::find_if( m_txs_by_fee_and_receive_time.begin(), m_txs_by_fee_and_receive_time.end() , [&](const sorted_tx_container::value_type& a){ return a.second == id; } ); } //--------------------------------------------------------------------------------- //TODO: investigate whether boolean return is appropriate bool tx_memory_pool::remove_stuck_transactions() { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); std::list> remove; m_blockchain.for_all_txpool_txes([this, &remove](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata*) { uint64_t tx_age = time(nullptr) - meta.receive_time; if((tx_age > CRYPTONOTE_MEMPOOL_TX_LIVETIME && !meta.kept_by_block) || (tx_age > CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME && meta.kept_by_block) || (meta.is_deregister && tx_age > MEMPOOL_PRUNE_DEREGISTER_LIFETIME)) { LOG_PRINT_L1(""Tx "" << txid << "" removed from tx pool due to outdated, age: "" << tx_age ); auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { LOG_PRINT_L1(""Removing tx "" << txid << "" from tx pool, but it was not found in the sorted txs container!""); } else { m_txs_by_fee_and_receive_time.erase(sorted_it); } m_timed_out_transactions.insert(txid); remove.push_back(std::make_pair(txid, meta.weight)); } return true; }, false, relay_category::all); if (!remove.empty()) { LockedTXN lock(m_blockchain.get_db()); for (const std::pair &entry: remove) { const crypto::hash &txid = entry.first; try { cryptonote::blobdata bd = m_blockchain.get_txpool_tx_blob(txid, relay_category::all); cryptonote::transaction_prefix tx; if (!parse_and_validate_tx_prefix_from_blob(bd, tx)) { MERROR(""Failed to parse tx from txpool""); // continue } else { // remove first, so we only remove key images if the tx removal succeeds m_blockchain.remove_txpool_tx(txid); m_txpool_weight -= entry.second; remove_transaction_keyimages(tx, txid); } } catch (const std::exception &e) { MWARNING(""Failed to remove stuck transaction: "" << txid); // ignore error } } lock.commit(); ++m_cookie; } return true; } //--------------------------------------------------------------------------------- //TODO: investigate whether boolean return is appropriate bool tx_memory_pool::get_relayable_transactions(std::vector> &txs) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const uint64_t now = time(NULL); txs.reserve(m_blockchain.get_txpool_tx_count()); m_blockchain.for_all_txpool_txes([this, now, &txs](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *){ // 0 fee transactions are never relayed if(!meta.pruned && meta.fee > 0 && !meta.do_not_relay && !meta.is_deregister) { if (!meta.dandelionpp_stem && now - meta.last_relayed_time <= get_relay_delay(now, meta.receive_time)) return true; if (meta.dandelionpp_stem && meta.last_relayed_time < now) // for dandelion++ stem, this value is the embargo timeout return true; // if the tx is older than half the max lifetime, we don't re-relay it, to avoid a problem // mentioned by smooth where nodes would flush txes at slightly different times, causing // flushed txes to be re-added when received from a node which was just about to flush it uint64_t max_age = meta.kept_by_block ? CRYPTONOTE_MEMPOOL_TX_FROM_ALT_BLOCK_LIVETIME : CRYPTONOTE_MEMPOOL_TX_LIVETIME; if (now - meta.receive_time <= max_age / 2) { try { txs.emplace_back(txid, m_blockchain.get_txpool_tx_blob(txid, relay_category::all), meta.get_relay_method()); } catch (const std::exception &e) { MERROR(""Failed to get transaction blob from db""); // ignore error } } } return true; }, false, relay_category::relayable); return true; } //--------------------------------------------------------------------------------- void tx_memory_pool::set_relayed(const epee::span hashes, const relay_method method) { crypto::random_poisson_seconds embargo_duration{dandelionpp_embargo_average}; const auto now = std::chrono::system_clock::now(); CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); LockedTXN lock(m_blockchain.get_db()); for (const auto& hash : hashes) { try { txpool_tx_meta_t meta; if (m_blockchain.get_txpool_tx_meta(hash, meta)) { // txes can be received as ""stem"" or ""fluff"" in either order meta.upgrade_relay_method(method); meta.relayed = true; if (meta.dandelionpp_stem) meta.last_relayed_time = std::chrono::system_clock::to_time_t(now + embargo_duration()); else meta.last_relayed_time = std::chrono::system_clock::to_time_t(now); m_blockchain.update_txpool_tx(hash, meta); } } catch (const std::exception &e) { MERROR(""Failed to update txpool transaction metadata: "" << e.what()); // continue } } lock.commit(); } //--------------------------------------------------------------------------------- size_t tx_memory_pool::get_transactions_count(bool include_sensitive) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); return m_blockchain.get_txpool_tx_count(include_sensitive); } //--------------------------------------------------------------------------------- void tx_memory_pool::get_transactions(std::vector& txs, bool include_sensitive) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted; txs.reserve(m_blockchain.get_txpool_tx_count(include_sensitive)); m_blockchain.for_all_txpool_txes([&txs](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ transaction tx; if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, tx) : parse_and_validate_tx_from_blob(*bd, tx))) { MERROR(""Failed to parse tx from txpool""); // continue return true; } tx.set_hash(txid); txs.push_back(std::move(tx)); return true; }, true, category); } //------------------------------------------------------------------ void tx_memory_pool::get_transaction_hashes(std::vector& txs, bool include_sensitive) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted; txs.reserve(m_blockchain.get_txpool_tx_count(include_sensitive)); m_blockchain.for_all_txpool_txes([&txs](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ txs.push_back(txid); return true; }, false, category); } //------------------------------------------------------------------ void tx_memory_pool::get_transaction_backlog(std::vector& backlog, bool include_sensitive) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const uint64_t now = time(NULL); const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted; backlog.reserve(m_blockchain.get_txpool_tx_count(include_sensitive)); m_blockchain.for_all_txpool_txes([&backlog, now](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ backlog.push_back({meta.weight, meta.fee, meta.receive_time - now}); return true; }, false, category); } //------------------------------------------------------------------ void tx_memory_pool::get_transaction_stats(struct txpool_stats& stats, bool include_sensitive) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const uint64_t now = time(NULL); const relay_category category = include_sensitive ? relay_category::all : relay_category::broadcasted; std::map agebytes; stats.txs_total = m_blockchain.get_txpool_tx_count(include_sensitive); std::vector weights; weights.reserve(stats.txs_total); m_blockchain.for_all_txpool_txes([&stats, &weights, now, &agebytes](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ weights.push_back(meta.weight); stats.bytes_total += meta.weight; if (!stats.bytes_min || meta.weight < stats.bytes_min) stats.bytes_min = meta.weight; if (meta.weight > stats.bytes_max) stats.bytes_max = meta.weight; if (!meta.relayed) stats.num_not_relayed++; stats.fee_total += meta.fee; if (!stats.oldest || meta.receive_time < stats.oldest) stats.oldest = meta.receive_time; if (meta.receive_time < now - 600) stats.num_10m++; if (meta.last_failed_height) stats.num_failing++; uint64_t age = now - meta.receive_time + (now == meta.receive_time); agebytes[age].txs++; agebytes[age].bytes += meta.weight; if (meta.double_spend_seen) ++stats.num_double_spends; return true; }, false, category); stats.bytes_med = epee::misc_utils::median(weights); if (stats.txs_total > 1) { /* looking for 98th percentile */ size_t end = stats.txs_total * 0.02; uint64_t delta, factor; std::map::iterator it, i2; if (end) { /* If enough txs, spread the first 98% of results across * the first 9 bins, drop final 2% in last bin. */ it = agebytes.end(); size_t cumulative_num = 0; /* Since agebytes is not empty and end is nonzero, the * below loop can always run at least once. */ do { --it; cumulative_num += it->second.txs; } while (it != agebytes.begin() && cumulative_num < end); stats.histo_98pc = it->first; factor = 9; delta = it->first; stats.histo.resize(10); } else { /* If not enough txs, don't reserve the last slot; * spread evenly across all 10 bins. */ stats.histo_98pc = 0; it = agebytes.end(); factor = stats.txs_total > 9 ? 10 : stats.txs_total; delta = now - stats.oldest; stats.histo.resize(factor); } if (!delta) delta = 1; for (i2 = agebytes.begin(); i2 != it; i2++) { size_t i = (i2->first * factor - 1) / delta; stats.histo[i].txs += i2->second.txs; stats.histo[i].bytes += i2->second.bytes; } for (; i2 != agebytes.end(); i2++) { stats.histo[factor].txs += i2->second.txs; stats.histo[factor].bytes += i2->second.bytes; } } } //------------------------------------------------------------------ //TODO: investigate whether boolean return is appropriate bool tx_memory_pool::get_transactions_and_spent_keys_info(std::vector& tx_infos, std::vector& key_image_infos, bool include_sensitive_data) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); const relay_category category = include_sensitive_data ? relay_category::all : relay_category::broadcasted; const size_t count = m_blockchain.get_txpool_tx_count(include_sensitive_data); tx_infos.reserve(count); key_image_infos.reserve(count); m_blockchain.for_all_txpool_txes([&tx_infos, key_image_infos, include_sensitive_data](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ tx_info txi; txi.id_hash = epee::string_tools::pod_to_hex(txid); txi.tx_blob = *bd; transaction tx; if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, tx) : parse_and_validate_tx_from_blob(*bd, tx))) { MERROR(""Failed to parse tx from txpool""); // continue return true; } tx.set_hash(txid); txi.tx_json = obj_to_json_str(tx); txi.blob_size = bd->size(); txi.weight = meta.weight; txi.fee = meta.fee; txi.kept_by_block = meta.kept_by_block; txi.max_used_block_height = meta.max_used_block_height; txi.max_used_block_id_hash = epee::string_tools::pod_to_hex(meta.max_used_block_id); txi.last_failed_height = meta.last_failed_height; txi.last_failed_id_hash = epee::string_tools::pod_to_hex(meta.last_failed_id); // In restricted mode we do not include this data: txi.receive_time = include_sensitive_data ? meta.receive_time : 0; txi.relayed = meta.relayed; // In restricted mode we do not include this data: txi.last_relayed_time = (include_sensitive_data && !meta.dandelionpp_stem) ? meta.last_relayed_time : 0; txi.do_not_relay = meta.do_not_relay; txi.double_spend_seen = meta.double_spend_seen; tx_infos.push_back(std::move(txi)); return true; }, true, category); txpool_tx_meta_t meta; for (const key_images_container::value_type& kee : m_spent_key_images) { const crypto::key_image& k_image = kee.first; const std::unordered_set& kei_image_set = kee.second; spent_key_image_info ki; ki.id_hash = epee::string_tools::pod_to_hex(k_image); for (const crypto::hash& tx_id_hash : kei_image_set) { if (m_blockchain.txpool_tx_matches_category(tx_id_hash, category)) ki.txs_hashes.push_back(epee::string_tools::pod_to_hex(tx_id_hash)); } // Only return key images for which we have at least one tx that we can show for them if (!ki.txs_hashes.empty()) key_image_infos.push_back(std::move(ki)); } return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::get_pool_for_rpc(std::vector& tx_infos, cryptonote::rpc::key_images_with_tx_hashes& key_image_infos) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); tx_infos.reserve(m_blockchain.get_txpool_tx_count()); key_image_infos.reserve(m_blockchain.get_txpool_tx_count()); m_blockchain.for_all_txpool_txes([&tx_infos, key_image_infos](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd){ cryptonote::rpc::tx_in_pool txi; txi.tx_hash = txid; if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*bd, txi.tx) : parse_and_validate_tx_from_blob(*bd, txi.tx))) { MERROR(""Failed to parse tx from txpool""); // continue return true; } txi.tx.set_hash(txid); txi.blob_size = bd->size(); txi.weight = meta.weight; txi.fee = meta.fee; txi.kept_by_block = meta.kept_by_block; txi.max_used_block_height = meta.max_used_block_height; txi.max_used_block_hash = meta.max_used_block_id; txi.last_failed_block_height = meta.last_failed_height; txi.last_failed_block_hash = meta.last_failed_id; txi.receive_time = meta.receive_time; txi.relayed = meta.relayed; txi.last_relayed_time = meta.dandelionpp_stem ? 0 : meta.last_relayed_time; txi.do_not_relay = meta.do_not_relay; txi.double_spend_seen = meta.double_spend_seen; tx_infos.push_back(txi); return true; }, true, relay_category::broadcasted); for (const key_images_container::value_type& kee : m_spent_key_images) { std::vector tx_hashes; const std::unordered_set& kei_image_set = kee.second; for (const crypto::hash& tx_id_hash : kei_image_set) { if (m_blockchain.txpool_tx_matches_category(tx_id_hash, relay_category::broadcasted)) tx_hashes.push_back(tx_id_hash); } if (!tx_hashes.empty()) key_image_infos[kee.first] = std::move(tx_hashes); } return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::check_for_key_images(const std::vector& key_images, std::vector& spent) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); spent.clear(); for (const auto& image : key_images) { bool is_spent = false; const auto found = m_spent_key_images.find(image); if (found != m_spent_key_images.end()) { for (const crypto::hash& tx_hash : found->second) is_spent |= m_blockchain.txpool_tx_matches_category(tx_hash, relay_category::broadcasted); } spent.push_back(is_spent); } return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::get_transaction(const crypto::hash& id, cryptonote::blobdata& txblob, relay_category tx_category) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); try { return m_blockchain.get_txpool_tx_blob(id, txblob, tx_category); } catch (const std::exception &e) { return false; } } //--------------------------------------------------------------------------------- bool tx_memory_pool::on_blockchain_inc(uint64_t new_block_height, const crypto::hash& top_block_id) { CRITICAL_REGION_LOCAL(m_transactions_lock); m_input_cache.clear(); m_parsed_tx_cache.clear(); return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::on_blockchain_dec(uint64_t new_block_height, const crypto::hash& top_block_id) { CRITICAL_REGION_LOCAL(m_transactions_lock); m_input_cache.clear(); m_parsed_tx_cache.clear(); return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::have_tx(const crypto::hash &id, relay_category tx_category) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); return m_blockchain.get_db().txpool_has_tx(id, tx_category); } //--------------------------------------------------------------------------------- bool tx_memory_pool::have_tx_keyimges_as_spent(const transaction& tx, const crypto::hash& txid) const { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); for(const auto& in: tx.vin) { CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, tokey_in, true);//should never fail if(have_tx_keyimg_as_spent(tokey_in.k_image, txid)) return true; } return false; } //--------------------------------------------------------------------------------- bool tx_memory_pool::have_tx_keyimg_as_spent(const crypto::key_image& key_im, const crypto::hash& txid) const { CRITICAL_REGION_LOCAL(m_transactions_lock); const auto found = m_spent_key_images.find(key_im); if (found != m_spent_key_images.end() && !found->second.empty()) { // If another tx is using the key image, always return as spent. // See `insert_key_images`. if (1 < found->second.size() || *(found->second.cbegin()) != txid) return true; return m_blockchain.txpool_tx_matches_category(txid, relay_category::legacy); } return false; } //--------------------------------------------------------------------------------- void tx_memory_pool::lock() const { m_transactions_lock.lock(); } //--------------------------------------------------------------------------------- void tx_memory_pool::unlock() const { m_transactions_lock.unlock(); } //--------------------------------------------------------------------------------- bool tx_memory_pool::check_tx_inputs(const std::function &get_tx, const crypto::hash &txid, uint64_t &max_used_block_height, crypto::hash &max_used_block_id, tx_verification_context &tvc, bool kept_by_block) const { if (!kept_by_block) { const std::unordered_map>::const_iterator i = m_input_cache.find(txid); if (i != m_input_cache.end()) { max_used_block_height = std::get<2>(i->second); max_used_block_id = std::get<3>(i->second); tvc = std::get<1>(i->second); return std::get<0>(i->second); } } bool ret = m_blockchain.check_tx_inputs(get_tx(), max_used_block_height, max_used_block_id, tvc, kept_by_block); if (!kept_by_block) m_input_cache.insert(std::make_pair(txid, std::make_tuple(ret, tvc, max_used_block_height, max_used_block_id))); return ret; } //--------------------------------------------------------------------------------- bool tx_memory_pool::is_transaction_ready_to_go(txpool_tx_meta_t& txd, const crypto::hash &txid, const cryptonote::blobdata &txblob, transaction &tx) const { struct transction_parser { transction_parser(const cryptonote::blobdata &txblob, const crypto::hash &txid, transaction &tx): txblob(txblob), txid(txid), tx(tx), parsed(false) {} cryptonote::transaction &operator()() { if (!parsed) { if (!parse_and_validate_tx_from_blob(txblob, tx)) throw std::runtime_error(""failed to parse transaction blob""); tx.set_hash(txid); parsed = true; } return tx; } const cryptonote::blobdata &txblob; const crypto::hash &txid; transaction &tx; bool parsed; } lazy_tx(txblob, txid, tx); //not the best implementation at this time, sorry :( //check is ring_signature already checked ? if(txd.max_used_block_id == null_hash) {//not checked, lets try to check if(txd.last_failed_id != null_hash && m_blockchain.get_current_blockchain_height() > txd.last_failed_height && txd.last_failed_id == m_blockchain.get_block_id_by_height(txd.last_failed_height)) return false;//we already sure that this tx is broken for this height tx_verification_context tvc = AUTO_VAL_INIT(tvc); if(!check_tx_inputs([&lazy_tx]()->cryptonote::transaction&{ return lazy_tx(); }, txid, txd.max_used_block_height, txd.max_used_block_id, tvc)) { txd.last_failed_height = m_blockchain.get_current_blockchain_height()-1; txd.last_failed_id = m_blockchain.get_block_id_by_height(txd.last_failed_height); return false; } }else { if(txd.max_used_block_height >= m_blockchain.get_current_blockchain_height()) return false; if(true) { //if we already failed on this height and id, skip actual ring signature check if(txd.last_failed_id == m_blockchain.get_block_id_by_height(txd.last_failed_height)) return false; //check ring signature again, it is possible (with very small chance) that this transaction become again valid tx_verification_context tvc; if(!check_tx_inputs([&lazy_tx]()->cryptonote::transaction&{ return lazy_tx(); }, txid, txd.max_used_block_height, txd.max_used_block_id, tvc)) { txd.last_failed_height = m_blockchain.get_current_blockchain_height()-1; txd.last_failed_id = m_blockchain.get_block_id_by_height(txd.last_failed_height); return false; } } } //if we here, transaction seems valid, but, anyway, check for key_images collisions with blockchain, just to be sure if(m_blockchain.have_tx_keyimges_as_spent(lazy_tx())) { txd.double_spend_seen = true; return false; } // Check that the deregister hasn't become too old to be included in the block, if so reject. if (tx.is_deregister_tx()) { uint64_t curr_height = m_blockchain.get_current_blockchain_height(); bool failed_ready_check = true; tx_extra_service_node_deregister deregister; if (get_service_node_deregister_from_tx_extra(tx.extra, deregister)) { uint64_t delta_height = curr_height - deregister.block_height; if (delta_height <= italo::service_node_deregister::DEREGISTER_LIFETIME_BY_HEIGHT) { failed_ready_check = false; } } if (failed_ready_check) { // NOTE: This deregistration is too old to be considered, but we can't delete it incase we // pop blocks and they suddenly become valid again. Let them fail to get included in blocks // until they expire. txd.last_failed_height = curr_height - 1; txd.last_failed_id = m_blockchain.get_block_id_by_height(txd.last_failed_height); txd.max_used_block_height = txd.last_failed_height; txd.max_used_block_id = txd.last_failed_id; return false; } } //transaction is ok. return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::have_key_images(const std::unordered_set& k_images, const transaction_prefix& tx) { for(size_t i = 0; i!= tx.vin.size(); i++) { CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, false); if(k_images.count(itk.k_image)) return true; } return false; } //--------------------------------------------------------------------------------- bool tx_memory_pool::append_key_images(std::unordered_set& k_images, const transaction_prefix& tx) { for(size_t i = 0; i!= tx.vin.size(); i++) { CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, false); auto i_res = k_images.insert(itk.k_image); CHECK_AND_ASSERT_MES(i_res.second, false, ""internal error: key images pool cache - inserted duplicate image in set: "" << itk.k_image); } return true; } //--------------------------------------------------------------------------------- void tx_memory_pool::mark_double_spend(const transaction &tx) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); bool changed = false; LockedTXN lock(m_blockchain.get_db()); for(size_t i = 0; i!= tx.vin.size(); i++) { CHECKED_GET_SPECIFIC_VARIANT(tx.vin[i], const txin_to_key, itk, void()); const key_images_container::const_iterator it = m_spent_key_images.find(itk.k_image); if (it != m_spent_key_images.end()) { for (const crypto::hash &txid: it->second) { txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(txid, meta)) { MERROR(""Failed to find tx meta in txpool""); // continue, not fatal continue; } if (!meta.double_spend_seen) { MDEBUG(""Marking "" << txid << "" as double spending "" << itk.k_image); meta.double_spend_seen = true; changed = true; try { m_blockchain.update_txpool_tx(txid, meta); } catch (const std::exception &e) { MERROR(""Failed to update tx meta: "" << e.what()); // continue, not fatal } } } } } lock.commit(); if (changed) ++m_cookie; } //--------------------------------------------------------------------------------- std::string tx_memory_pool::print_pool(bool short_format) const { std::stringstream ss; CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); m_blockchain.for_all_txpool_txes([&ss, short_format](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *txblob) { ss << ""id: "" << txid << std::endl; if (!short_format) { cryptonote::transaction tx; if (!(meta.pruned ? parse_and_validate_tx_base_from_blob(*txblob, tx) : parse_and_validate_tx_from_blob(*txblob, tx))) { MERROR(""Failed to parse tx from txpool""); return true; // continue } ss << obj_to_json_str(tx) << std::endl; } ss << ""blob_size: "" << (short_format ? ""-"" : std::to_string(txblob->size())) << std::endl << ""weight: "" << meta.weight << std::endl << ""fee: "" << print_money(meta.fee) << std::endl << ""kept_by_block: "" << (meta.kept_by_block ? 'T' : 'F') << std::endl << ""is_local"" << (meta.is_local ? 'T' : 'F') << std::endl << ""double_spend_seen: "" << (meta.double_spend_seen ? 'T' : 'F') << std::endl << ""max_used_block_height: "" << meta.max_used_block_height << std::endl << ""max_used_block_id: "" << meta.max_used_block_id << std::endl << ""last_failed_height: "" << meta.last_failed_height << std::endl << ""last_failed_id: "" << meta.last_failed_id << std::endl; return true; }, !short_format, relay_category::all); return ss.str(); } //--------------------------------------------------------------------------------- //TODO: investigate whether boolean return is appropriate bool tx_memory_pool::fill_block_template(block &bl, size_t median_weight, uint64_t already_generated_coins, size_t &total_weight, uint64_t &fee, uint64_t &expected_reward, uint8_t version) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); uint64_t best_coinbase = 0, coinbase = 0; total_weight = 0; fee = 0; //baseline empty block miner_reward_context block_reward_context = {}; block_reward_parts reward_parts = {}; if (! get_italo_block_reward(median_weight, total_weight, already_generated_coins, version, reward_parts, block_reward_context, MAINNET)) { MERROR(""Failed to get block reward for empty block""); return false; } best_coinbase = reward_parts.base_miner; size_t max_total_weight_pre_v5 = (130 * median_weight) / 100 - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; size_t max_total_weight_v5 = 2 * median_weight - CRYPTONOTE_COINBASE_BLOB_RESERVED_SIZE; size_t max_total_weight = version >= 5 ? max_total_weight_v5 : max_total_weight_pre_v5; std::unordered_set k_images; LOG_PRINT_L2(""Filling block template, median weight "" << median_weight << "", "" << m_txs_by_fee_and_receive_time.size() << "" txes in the pool""); LockedTXN lock(m_blockchain.get_db()); auto sorted_it = m_txs_by_fee_and_receive_time.begin(); for (; sorted_it != m_txs_by_fee_and_receive_time.end(); ++sorted_it) { txpool_tx_meta_t meta; if (!m_blockchain.get_txpool_tx_meta(sorted_it->second, meta)) { MERROR("" failed to find tx meta""); continue; } LOG_PRINT_L2(""Considering "" << sorted_it->second << "", weight "" << meta.weight << "", current block weight "" << total_weight << ""/"" << max_total_weight << "", current coinbase "" << print_money(best_coinbase) << "", relay method "" << (unsigned)meta.get_relay_method()); if (!meta.matches(relay_category::legacy) && !(m_mine_stem_txes && meta.get_relay_method() == relay_method::stem)) { LOG_PRINT_L2("" tx relay method is "" << (unsigned)meta.get_relay_method()); continue; } if (meta.pruned) { LOG_PRINT_L2("" tx is pruned""); continue; } // Can not exceed maximum block weight if (max_total_weight < total_weight + meta.weight) { LOG_PRINT_L2("" would exceed maximum block weight""); continue; } // start using the optimal filling algorithm from v5 if (version >= SERVICE_NODE_VERSION) { block_reward_parts reward_parts_other = {}; if (!get_italo_block_reward(median_weight, total_weight + meta.weight, already_generated_coins, version, reward_parts_other, block_reward_context, MAINNET)) { LOG_PRINT_L2("" would exceed maximum block weight""); continue; } uint64_t block_reward = reward_parts_other.base_miner; coinbase = block_reward + fee + meta.fee; if (coinbase < template_accept_threshold(best_coinbase)) { LOG_PRINT_L2("" would decrease coinbase to "" << print_money(coinbase)); continue; } } else { // If we've exceeded the penalty free weight, // stop including more tx if (total_weight > median_weight) { LOG_PRINT_L2("" would exceed median block weight""); break; } } // ""local"" and ""stem"" txes are filtered above cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(sorted_it->second, relay_category::all); cryptonote::transaction tx; // Skip transactions that are not ready to be // included into the blockchain or that are // missing key images const cryptonote::txpool_tx_meta_t original_meta = meta; bool ready = false; try { ready = is_transaction_ready_to_go(meta, sorted_it->second, txblob, tx); } catch (const std::exception &e) { MERROR(""Failed to check transaction readiness: "" << e.what()); // continue, not fatal } if (memcmp(&original_meta, &meta, sizeof(meta))) { try { m_blockchain.update_txpool_tx(sorted_it->second, meta); } catch (const std::exception &e) { MERROR(""Failed to update tx meta: "" << e.what()); // continue, not fatal } } if (!ready) { LOG_PRINT_L2("" not ready to go""); continue; } if (have_key_images(k_images, tx)) { LOG_PRINT_L2("" key images already seen""); continue; } bl.tx_hashes.push_back(sorted_it->second); total_weight += meta.weight; fee += meta.fee; best_coinbase = coinbase; append_key_images(k_images, tx); LOG_PRINT_L2("" added, new block weight "" << total_weight << ""/"" << max_total_weight << "", coinbase "" << print_money(best_coinbase)); } lock.commit(); expected_reward = best_coinbase; LOG_PRINT_L2(""Block template filled with "" << bl.tx_hashes.size() << "" txes, weight "" << total_weight << ""/"" << max_total_weight << "", coinbase "" << print_money(best_coinbase) << "" (including "" << print_money(fee) << "" in fees)""); return true; } //--------------------------------------------------------------------------------- size_t tx_memory_pool::validate(uint8_t version) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); size_t tx_weight_limit = get_transaction_weight_limit(version); std::unordered_set remove; m_txpool_weight = 0; m_blockchain.for_all_txpool_txes([this, &remove, tx_weight_limit](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata*) { m_txpool_weight += meta.weight; if (meta.weight > tx_weight_limit) { LOG_PRINT_L1(""Transaction "" << txid << "" is too big ("" << meta.weight << "" bytes), removing it from pool""); remove.insert(txid); } else if (m_blockchain.have_tx(txid)) { LOG_PRINT_L1(""Transaction "" << txid << "" is in the blockchain, removing it from pool""); remove.insert(txid); } return true; }, false, relay_category::all); size_t n_removed = 0; if (!remove.empty()) { LockedTXN lock(m_blockchain.get_db()); for (const crypto::hash &txid: remove) { try { cryptonote::blobdata txblob = m_blockchain.get_txpool_tx_blob(txid, relay_category::all); cryptonote::transaction tx; if (!parse_and_validate_tx_from_blob(txblob, tx)) // remove pruned ones on startup, they're meant to be temporary { MERROR(""Failed to parse tx from txpool""); continue; } // remove tx from db first m_blockchain.remove_txpool_tx(txid); m_txpool_weight -= get_transaction_weight(tx, txblob.size()); remove_transaction_keyimages(tx, txid); auto sorted_it = find_tx_in_sorted_container(txid); if (sorted_it == m_txs_by_fee_and_receive_time.end()) { LOG_PRINT_L1(""Removing tx "" << txid << "" from tx pool, but it was not found in the sorted txs container!""); } else { m_txs_by_fee_and_receive_time.erase(sorted_it); } ++n_removed; } catch (const std::exception &e) { MERROR(""Failed to remove invalid tx from pool""); // continue } } lock.commit(); } if (n_removed > 0) ++m_cookie; return n_removed; } //--------------------------------------------------------------------------------- bool tx_memory_pool::init(size_t max_txpool_weight, bool mine_stem_txes) { CRITICAL_REGION_LOCAL(m_transactions_lock); CRITICAL_REGION_LOCAL1(m_blockchain); m_txpool_max_weight = max_txpool_weight ? max_txpool_weight : DEFAULT_TXPOOL_MAX_WEIGHT; m_txs_by_fee_and_receive_time.clear(); m_spent_key_images.clear(); m_txpool_weight = 0; std::vector remove; // first add the not kept by block, then the kept by block, // to avoid rejection due to key image collision for (int pass = 0; pass < 2; ++pass) { const bool kept = pass == 1; bool r = m_blockchain.for_all_txpool_txes([this, &remove, kept](const crypto::hash &txid, const txpool_tx_meta_t &meta, const cryptonote::blobdata *bd) { if (!!kept != !!meta.kept_by_block) return true; cryptonote::transaction tx; if (!parse_and_validate_tx_prefix_from_blob(*bd, tx)) { MWARNING(""Failed to parse tx from txpool, removing""); remove.push_back(txid); return true; } if (!insert_key_images(tx, txid, meta.get_relay_method())) { MFATAL(""Failed to insert key images from txpool tx""); return false; } m_txs_by_fee_and_receive_time.emplace(std::tuple(tx.is_deregister_tx(), meta.fee / (double)meta.weight, meta.receive_time), txid); m_txpool_weight += meta.weight; return true; }, true, relay_category::all); if (!r) return false; } if (!remove.empty()) { LockedTXN lock(m_blockchain.get_db()); for (const auto &txid: remove) { try { m_blockchain.remove_txpool_tx(txid); } catch (const std::exception &e) { MWARNING(""Failed to remove corrupt transaction: "" << txid); // ignore error } } lock.commit(); } m_mine_stem_txes = mine_stem_txes; m_cookie = 0; // Ignore deserialization error return true; } //--------------------------------------------------------------------------------- bool tx_memory_pool::deinit() { return true; } } ",16224,True,3301.349514710399,median "[[scoreCalculation]] = Score calculation :doctype: book :imagesdir: .. :sectnums: :toc: left :icons: font :experimental: [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::ScoreCalculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::ScoreCalculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::ScoreCalculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::ScoreCalculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::ScoreCalculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply <>. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::ScoreCalculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we can not weigh them against each other. Yet, despite that we can not compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::ScoreCalculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). To implement pareto scoring in OptaPlanner, <> (and replace the ``BestSolutionRecaller``). Future versions will provide out-of-the-box support. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::ScoreCalculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::ScoreCalculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``). It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::ScoreCalculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see <>. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleDoubleScore` uses a `double` value instead of an `int` value. <> * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftDoubleScore` uses `double` values instead of `int` values. <> * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[customScore]] === Implementing a custom score Internally, each `Score` implementation also has a `ScoreDefinition` implementation. For example: `SimpleScore` is defined by ``SimpleScoreDefinition``. The `ScoreDefinition` interface defines the score representation. To implement a custom ``Score``, also implement such a custom ``ScoreDefinition``. Extend `AbstractScoreDefinition` (preferably by copy pasting ``HardSoftScoreDefinition``) and start from there. Then hook your custom `ScoreDefinition` in the domain: [source,java,options=""nowrap""] ---- @PlanningScore(scoreDefinitionClass = MyCustomScoreDefinition.class) private MyCustomScore score; ---- To have it integrate seamlessly with <>, <>, <>, ..., you'll need to write custom glue code too. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **<>**: Implement each constraint as a separate ConstraintStream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **<>**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an <> is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use <> instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator { Score calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.solver.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the <> can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use <>: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator 1000 ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator` and extend the class ``AbstractIncrementalScoreCalculator``: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score calculateScore(); } ---- image::ScoreCalculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator extends AbstractIncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.solver.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the <> can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use <>: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator 1000 ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreDirector.getConstraintMatchTotals()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreDirector.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection getConstraintMatchTotals(); Map getIndictmentMap(); } ---- For example in machine reassignment, create one ConstraintMatchTotal per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new ConstraintMatchTotal( CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Drools Score Calculation doesn't have this disadvantage, because it is constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable can not unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable can not unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- .../cloudBalancingConstraints.drl ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- .../cloudBalancingConstraints.drl ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the <> in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.solver.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.solver.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, <> is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::ScoreCalculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::ScoreCalculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *Drools score calculation gives you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the Drools rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into <>. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use <> or <> to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not let Drools sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::ScoreCalculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the <> to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::ScoreCalculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::ScoreCalculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the __squared workload__, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they 'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::ScoreCalculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one to one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a <>, there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.solver"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as <>. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with <>, need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.solver`, so the constraint configuration above specifies a `constraintPackage`. Cases with <>, normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in <>: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainBestScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(solver.explainBestScore()); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, reuse the `ScoreDirectorFactory` of the `SolverFactory` to build a separate `ScoreDirector` for that webUI: [source,java,options=""nowrap""] ---- ScoreDirectorFactory scoreDirectorFactory = solverFactory.getScoreDirectorFactory(); try (ScoreDirector guiScoreDirector = scoreDirectorFactory.buildScoreDirector()) { ... } ---- [NOTE] ==== The `try` ARM will call `ScoreDirector.close()` when the `ScoreDirector` becomes useless, to avoid a memory leak, especially with <>. ==== Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- guiScoreDirector.setWorkingSolution(cloudBalance); Score score = guiScoreDirector.calculateScore(); ---- Furthermore, the `ScoreDirector` can explain the score through constraint match totals and/or indictments: image::ScoreCalculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreDirector``: [source,java,options=""nowrap""] ---- Collection constraintMatchTotals = guiScoreDirector.getConstraintMatchTotals(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = (HardSoftScore) constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = (HardSoftScore) constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== <> supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreDirector``: [source,java,options=""nowrap""] ---- Map indictmentMap = guiScoreDirector.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = (HardSoftScore) indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = (HardSoftScore) constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== <> supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see <> or <>. ",12124,False,2106.689533256366,median "/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE 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 3 of the License, or * (at your option) any later version. * * HISE 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 HISE. If not, see . * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ namespace hise { using namespace juce; MARKDOWN_CHAPTER(WavetableHelp) START_MARKDOWN(ReverseWavetables) ML(""## Reverse Wavetable order"") ML(""Only used in FFT Resynthesis mode. If this is enabled, it will store the wavetables in reversed order. "") ML(""This is useful if you have decaying samples and want to use the table index to modulate the decay process"") END_MARKDOWN() START_MARKDOWN(WindowType) ML(""## FFT Window Type"") ML(""Only used in FFT Resynthesis mode. This changes the window function that is applied to the signal before the FFT. "") ML(""The selection of the right window function has a drastic impact on the resulting accuracy and varies between different signal types. "") ML(""Try out different window types and compare the results.""); END_MARKDOWN() START_MARKDOWN(WindowSize) ML(""## FFT Window Size"") ML(""Only used in FFT Resynthesis mode. Changes the size of the chunk that is used for the FFT. "") ML(""Generally, lower values yield more accurate results (and sizes above 2048 tend to smear the wavetables because their range start to overlap). ""); ML(""However lower frequencies can't be detected with small FFT sizes so it might not work. "") ML(""> The recommended approach is to choose the **lowest possible FFT size** that still creates a reasonable harmonic spectrum.""); END_MARKDOWN() END_MARKDOWN_CHAPTER() static bool canConnectToWebsite(const URL& url) { auto in = url.createInputStream(false, nullptr, nullptr, String(), 2000, nullptr); return in != nullptr; } static bool areMajorWebsitesAvailable() { if (canConnectToWebsite(URL(""http://hartinstruments.net""))) return true; return false; } class UpdateChecker : public DialogWindowWithBackgroundThread { public: class ScopedTempFile { public: ScopedTempFile(const File &f_) : f(f_) { f.deleteFile(); jassert(!f.existsAsFile()); f.create(); } ~ScopedTempFile() { jassert(f.existsAsFile()); jassert(f.deleteFile()); } File f; }; UpdateChecker() : DialogWindowWithBackgroundThread(""Checking for newer version.""), updatesAvailable(false), lastUpdate(BUILD_SUB_VERSION) { String changelog = getAllChangelogs(); if (updatesAvailable) { changelogDisplay = new TextEditor(""Changelog""); changelogDisplay->setSize(500, 300); changelogDisplay->setFont(GLOBAL_MONOSPACE_FONT()); changelogDisplay->setMultiLine(true); changelogDisplay->setReadOnly(true); changelogDisplay->setText(changelog); addCustomComponent(changelogDisplay); filePicker = new FilenameComponent(""Download Location"", File::getSpecialLocation(File::SpecialLocationType::userDesktopDirectory), false, true, true, """", """", ""Choose Download Location""); filePicker->setSize(500, 24); addCustomComponent(filePicker); addBasicComponents(); showStatusMessage(""New build available: "" + String(lastUpdate) + "". Press OK to download file to the selected location""); } else { addBasicComponents(false); showStatusMessage(""Your HISE build is up to date.""); } } static bool downloadProgress(void* context, int bytesSent, int totalBytes) { const double downloadedMB = (double)bytesSent / 1024.0 / 1024.0; const double totalMB = (double)totalBytes / 1024.0 / 1024.0; const double percent = downloadedMB / totalMB; static_cast(context)->showStatusMessage(""Downloaded: "" + String(downloadedMB, 2) + "" MB / "" + String(totalMB, 2) + "" MB""); static_cast(context)->setProgress(percent); return !static_cast(context)->threadShouldExit(); } void run() { static String webFolder(""http://hartinstruments.net/hise/download/nightly_builds/""); static String version = ""099""; #if JUCE_WINDOWS String downloadFileName = ""HISE_"" + version + ""_build"" + String(lastUpdate) + "".exe""; #else String downloadFileName = ""HISE_"" + version + ""_build"" + String(lastUpdate) + ""_OSX.dmg""; #endif URL url(webFolder + downloadFileName); auto stream = url.createInputStream(false, &downloadProgress, this); target = File(filePicker->getCurrentFile().getChildFile(downloadFileName)); if (!target.existsAsFile()) { MemoryBlock mb; mb.setSize(8192); tempFile = new ScopedTempFile(File(target.getFullPathName() + ""temp"")); ScopedPointer fos = new FileOutputStream(tempFile->f); const int64 numBytesTotal = stream->getNumBytesRemaining(); int64 numBytesRead = 0; downloadOK = false; while (stream->getNumBytesRemaining() > 0) { const int64 chunkSize = (int64)jmin((int)stream->getNumBytesRemaining(), 8192); downloadProgress(this, (int)numBytesRead, (int)numBytesTotal); if (threadShouldExit()) { fos->flush(); fos = nullptr; tempFile = nullptr; return; } stream->read(mb.getData(), (int)chunkSize); numBytesRead += chunkSize; fos->write(mb.getData(), (size_t)chunkSize); } downloadOK = true; fos->flush(); tempFile->f.copyFileTo(target); } }; void threadFinished() { if (downloadOK) { PresetHandler::showMessageWindow(""Download finished"", ""Quit the app and run the installer to update to the latest version"", PresetHandler::IconType::Info); target.revealToUser(); } } private: String getAllChangelogs() { int latestVersion = BUILD_SUB_VERSION + 1; String completeLog; bool lookFurther = true; while (lookFurther) { String log = getChangelog(latestVersion); if (log == ""404"") { lookFurther = false; continue; } updatesAvailable = true; lastUpdate = latestVersion; completeLog << log; latestVersion++; } return completeLog; } String getChangelog(int i) const { static String webFolder(""http://www.hartinstruments.net/hise/download/nightly_builds/""); String changelogFile(""changelog_"" + String(i) + "".txt""); URL url(webFolder + changelogFile); String content; auto stream = url.createInputStream(false); if (stream != nullptr) { String changes = stream->readEntireStreamAsString(); if (changes.contains(""404"")) { return ""404""; } else if (changes.containsNonWhitespaceChars()) { content = ""Build "" + String(i) + "":\\n\\n"" + changes; return content; } return String(); } else { return ""404""; } } bool updatesAvailable; int lastUpdate; File target; ScopedPointer tempFile; bool downloadOK; ScopedPointer filePicker; ScopedPointer changelogDisplay; }; void XmlBackupFunctions::restoreAllScripts(ValueTree& v, ModulatorSynthChain *masterChain, const String &newId) { static const Identifier pr(""Processor""); static const Identifier scr(""Script""); static const Identifier id(""ID""); static const Identifier typ(""Type""); if (v.getType() == Identifier(pr) && v[typ].toString().contains(""Script"")) { auto fileName = getSanitiziedName(v[id]); File scriptDirectory = getScriptDirectoryFor(masterChain, newId); auto sf = scriptDirectory.getChildFile(fileName).withFileExtension(""js""); if (!sf.existsAsFile()) { jassertfalse; } for(auto f: RangedDirectoryIterator(scriptDirectory, false, ""*.js"", File::findFiles)) { File script = f.getFile(); if (script.getFileNameWithoutExtension() == fileName) { v.setProperty(scr, script.loadFileAsString(), nullptr); break; } } } for (auto c: v) restoreAllScripts(c, masterChain, newId); } class DummyUnlocker : public OnlineUnlockStatus { public: DummyUnlocker(MainController *mc_) : mc(mc_) { } String getProductID() override { return dynamic_cast(mc)->getSettingsObject().getSetting(HiseSettings::Project::Name).toString(); } bool doesProductIDMatch(const String & returnedIDFromServer) { return returnedIDFromServer == getProductID(); } private: MainController* mc; }; class ProjectArchiver : public ThreadWithQuasiModalProgressWindow { public: ProjectArchiver(File &archiveFile_, File &projectDirectory_, ThreadWithQuasiModalProgressWindow::Holder *holder) : ThreadWithQuasiModalProgressWindow(""Archiving Project"", true, true, holder), archiveFile(archiveFile_), projectDirectory(projectDirectory_) { getAlertWindow()->setLookAndFeel(&alaf); } void run() { ZipFile::Builder builder; StringArray ignoredDirectories; ignoredDirectories.add(""Binaries""); ignoredDirectories.add(""git""); for(auto f: RangedDirectoryIterator(projectDirectory, true, ""*"", File::findFilesAndDirectories)) { File currentFile = f.getFile(); if (currentFile.isDirectory() || currentFile.getFullPathName().contains(""git"") || currentFile.getParentDirectory().getFullPathName().contains(""Binaries"")) { continue; } builder.addFile(currentFile, 9, currentFile.getRelativePathFrom(projectDirectory)); } setStatusMessage(""Creating ZIP archive of project folder""); archiveFile.deleteFile(); archiveFile.create(); FileOutputStream fos(archiveFile); builder.writeToStream(fos, getProgressValue()); } void threadComplete(bool userPressedCancel) override { if (!userPressedCancel && PresetHandler::showYesNoWindow(""Successfully exported"", ""Press OK to show the archive"", PresetHandler::IconType::Info)) { archiveFile.revealToUser(); } ThreadWithQuasiModalProgressWindow::threadComplete(userPressedCancel); } private: AlertWindowLookAndFeel alaf; File archiveFile; File projectDirectory; }; class WavetableConverterDialog : public DialogWindowWithBackgroundThread, public ComboBoxListener { enum Mode { Resample, FFTResynthesis, numModes }; enum ButtonIds { Next = 5, Previous, Rescan, Discard, Preview, Original, numButtonIds }; public: WavetableConverterDialog(ModulatorSynthChain* chain_) : DialogWindowWithBackgroundThread(""Convert Samplemaps to Wavetable""), chain(chain_), converter(new SampleMapToWavetableConverter(chain_)), r(Result::ok()) { auto list = chain->getMainController()->getActiveFileHandler()->pool->getSampleMapPool().getIdList(); addComboBox(""samplemap"", list, ""Samplemap""); getComboBoxComponent(""samplemap"")->addListener(this); StringArray windows; windows.add(""Flat Top""); windows.add(""Blackman Harris""); windows.add(""Hann""); windows.add(""Hamming""); windows.add(""Kaiser""); windows.add(""Gaussian""); windows.add(""Triangle""); windows.add(""Rectangle""); StringArray sizes; sizes.add(""Lowest possible""); sizes.add(""128""); sizes.add(""256""); sizes.add(""512""); sizes.add(""1024""); sizes.add(""2048""); sizes.add(""4096""); sizes.add(""8192""); StringArray yesNo; yesNo.add(""Yes""); yesNo.add(""No""); selectors = new AdditionalRow(this); selectors->addComboBox(""mode"", { ""Resample Wavetables"", ""FFT Resynthesis""}, ""Mode"", 130); selectors->addComboBox(""ReverseTables"", {""Yes"", ""No""}, ""Reverse Wavetable order"", 90); selectors->setInfoTextForLastComponent(WavetableHelp::ReverseWavetables()); selectors->addComboBox(""WindowType"", windows, ""FFT Window Type"", 120); selectors->setInfoTextForLastComponent(WavetableHelp::WindowType()); selectors->addComboBox(""FFTSize"", sizes, ""FFT Size""); selectors->setInfoTextForLastComponent(WavetableHelp::WindowSize()); selectors->setSize(512, 40); addCustomComponent(selectors); preview = new CombinedPreview(*converter); preview->setSize(512, 300); addCustomComponent(preview); gainPackData = new SliderPackData(nullptr, nullptr); gainPackData->setNumSliders(64); gainPackData->setRange(0.0, 1.0, 0.01); gainPack = new SliderPack(gainPackData); gainPack->setName(""Gain Values""); gainPack->setSize(512, 40); addCustomComponent(gainPack); additionalButtons = new AdditionalRow(this); additionalButtons->addButton(""Previous"", KeyPress(KeyPress::leftKey)); additionalButtons->addButton(""Next"", KeyPress(KeyPress::rightKey)); additionalButtons->addButton(""Rescan"", KeyPress(KeyPress::F5Key)); additionalButtons->addButton(""Discard""); additionalButtons->addButton(""Preview"", KeyPress(KeyPress('p'))); additionalButtons->addButton(""Original"", KeyPress(KeyPress('o'))); additionalButtons->setSize(512, 32); addCustomComponent(additionalButtons); addBasicComponents(true); if(auto s = ProcessorHelpers::getFirstProcessorWithType(chain)) { auto sampleMapTree = s->getSampleMap()->getValueTree(); converter->parseSampleMap(sampleMapTree); converter->refreshCurrentWavetable(getProgressCounter()); refreshPreview(); showStatusMessage(""Imported samplemap from "" + s->getId()); } else { showStatusMessage(""Choose Samplemap to convert""); } } ~WavetableConverterDialog() { fileHandling = nullptr; preview = nullptr; converter = nullptr; } void resultButtonClicked(const String &name) { if (name == ""Previous"") { converter->moveCurrentSampleIndex(false); r = converter->refreshCurrentWavetable(getProgressCounter(), false); } else if (name == ""Next"") { converter->moveCurrentSampleIndex(true); r = converter->refreshCurrentWavetable(getProgressCounter(), false); } else if (name == ""Rescan"") { r = converter->refreshCurrentWavetable(getProgressCounter(), true); } else if (name == ""Discard"") { r = converter->discardCurrentNoteAndUsePrevious(); } else if (name == ""Original"" || name == ""Preview"") { showStatusMessage(""Preview""); auto b = converter->getPreviewBuffers(name == ""Original""); chain->getMainController()->setBufferToPlay(b); } refreshPreview(); } void refreshPreview() { converter->sendChangeMessage(); if (auto gainData = converter->getCurrentGainValues()) { for (int i = 0; i < 64; i++) { gainPackData->setValue(i, gainData[i]); } gainPackData->sendChangeMessage(); } if (r.failed()) showStatusMessage(""Fail at "" + MidiMessage::getMidiNoteName(converter->getCurrentNoteNumber(), true, true, 3) + "": "" + r.getErrorMessage()); else showStatusMessage(""OK: "" + MidiMessage::getMidiNoteName(converter->getCurrentNoteNumber(), true, true, 3)); } void comboBoxChanged(ComboBox* comboBoxThatHasChanged) override { if (getComboBoxComponent(""samplemap"") == comboBoxThatHasChanged) { auto& spool = chain->getMainController()->getActiveFileHandler()->pool->getSampleMapPool(); PoolReference ref(chain->getMainController(), comboBoxThatHasChanged->getText(), FileHandlerBase::SampleMaps); currentlyLoadedMap = ref.getFile().getFileNameWithoutExtension(); if (auto vData = spool.loadFromReference(ref, PoolHelpers::LoadAndCacheWeak)) { converter->parseSampleMap(*vData.getData()); if (currentMode == FFTResynthesis) { converter->refreshCurrentWavetable(getProgressCounter()); } refreshPreview(); } } if (comboBoxThatHasChanged->getName() == ""mode"") { currentMode = (Mode)comboBoxThatHasChanged->getSelectedItemIndex(); if (currentMode == FFTResynthesis) { converter->refreshCurrentWavetable(getProgressCounter()); refreshPreview(); } } if (comboBoxThatHasChanged->getName() == ""WindowType"") { converter->windowType = (SampleMapToWavetableConverter::WindowType)comboBoxThatHasChanged->getSelectedItemIndex(); } else if (comboBoxThatHasChanged->getName() == ""ReverseTables"") { converter->reverseOrder = comboBoxThatHasChanged->getSelectedItemIndex() == 0; } else { if (comboBoxThatHasChanged->getText() == ""Lowest possible"") { converter->fftSize = -1; } else { auto windowSize = comboBoxThatHasChanged->getText().getIntValue(); converter->fftSize = windowSize; } } } void run() override { if (currentMode == FFTResynthesis) converter->renderAllWavetablesFromHarmonicMaps(getProgressCounter()); else converter->renderAllWavetablesFromSingleWavetables(getProgressCounter()); if (threadShouldExit()) return; auto leftTree = converter->getValueTree(true); auto rightTree = converter->getValueTree(false); auto fileL = currentlyLoadedMap + ""_Left.hwt""; auto fileR = currentlyLoadedMap + ""_Right.hwt""; auto tfl = GET_PROJECT_HANDLER(chain).getSubDirectory(ProjectHandler::SubDirectories::AudioFiles).getChildFile(fileL); auto tfr = GET_PROJECT_HANDLER(chain).getSubDirectory(ProjectHandler::SubDirectories::AudioFiles).getChildFile(fileR); PresetHandler::writeValueTreeAsFile(leftTree, tfl.getFullPathName()); PresetHandler::writeValueTreeAsFile(rightTree, tfr.getFullPathName()); } void threadFinished() override { if (r.failed()) PresetHandler::showMessageWindow(""Conversion failed"", r.getErrorMessage(), PresetHandler::IconType::Error); else PresetHandler::showMessageWindow(""Conversion OK"", ""The wavetables were created sucessfully"", PresetHandler::IconType::Info); } double wavetableProgress = 0.0; int numWavetables = 0; Result r; ScopedPointer preview; ScopedPointer gainPack; ScopedPointer gainPackData; ModulatorSynthChain* chain; Mode currentMode = Resample; ScopedPointer fileHandling; ScopedPointer selectors; ScopedPointer additionalButtons; ScopedPointer converter; String currentlyLoadedMap; File currentFile; }; class MonolithConverter : public MonolithExporter { public: enum ExportOptions { ExportAll, ExportSampleMapsAndJSON, ExportJSON, numExportOptions }; MonolithConverter(BackendRootWindow* bpe_) : MonolithExporter(""Convert samples to Monolith + Samplemap"", bpe_->getMainSynthChain()), bpe(bpe_), chain(bpe_->getMainSynthChain()) { sampler = dynamic_cast(ProcessorHelpers::getFirstProcessorWithName(chain, ""Sampler"")); sampleFolder = GET_PROJECT_HANDLER(chain).getSubDirectory(ProjectHandler::SubDirectories::Samples); jassert(sampler != nullptr); StringArray directoryDepth; directoryDepth.add(""1""); directoryDepth.add(""2""); directoryDepth.add(""3""); directoryDepth.add(""4""); addComboBox(""directoryDepth"", directoryDepth, ""Directory Depth""); StringArray yesNo; yesNo.add(""Yes""); yesNo.add(""No""); // best code I've ever written... addComboBox(""overwriteFiles"", yesNo, ""Overwrite existing files""); StringArray option; option.add(""Export all""); option.add(""Skip monolith file creation""); option.add(""Only create JSON data file""); addComboBox(""option"", option, ""Export Depth""); addTextEditor(""directorySeparator"", ""::"", ""Directory separation character""); StringArray sa2; sa2.add(""No normalisation""); sa2.add(""Normalise every sample""); sa2.add(""Full Dynamics""); addComboBox(""normalise"", sa2, ""Normalization""); addBasicComponents(true); }; void getDepth(const File& rootFile, const File& childFile, int& counter) { jassert(childFile.isAChildOf(rootFile)); if (childFile.getParentDirectory() == rootFile) { return; } counter++; getDepth(rootFile, childFile.getParentDirectory(), counter); } void convertSampleMap(const File& sampleDirectory, bool overwriteExistingData, bool exportSamples, bool exportSampleMap) { if (!exportSamples && !exportSampleMap) return; #if JUCE_WINDOWS const String slash = ""\\\\""; #else const String slash = ""/""; #endif const String sampleMapPath = sampleDirectory.getRelativePathFrom(sampleFolder); const String sampleMapId = sampleMapPath.replace(slash, ""_""); showStatusMessage(""Importing "" + sampleMapId); Array samples; sampleDirectory.findChildFiles(samples, File::findFiles, true, ""*.wav;*.aif;*.aif;*.WAV;*.AIF;*.AIFF""); StringArray fileNames; for (int i = 0; i < samples.size(); i++) { if (samples[i].isHidden() || samples[i].getFileName().startsWith(""."")) continue; fileNames.add(samples[i].getFullPathName()); } auto& tmpBpe = bpe; StringArray fileNamesCopy; fileNamesCopy.addArray(fileNames); auto f = [tmpBpe, fileNamesCopy](Processor* p) { if(auto sampler = dynamic_cast(p)) { sampler->clearSampleMap(dontSendNotification); SampleImporter::loadAudioFilesRaw(tmpBpe, sampler, fileNamesCopy); SampleEditHandler::SampleEditingActions::automapUsingMetadata(sampler); } return SafeFunctionCall::Status::OK; }; sampler->killAllVoicesAndCall(f); Thread::sleep(500); sampler->getSampleMap()->setId(sampleMapId); sampler->getSampleMap()->setIsMonolith(); setSampleMap(sampler->getSampleMap()); auto sampleMapFolder = GET_PROJECT_HANDLER(chain).getSubDirectory(ProjectHandler::SubDirectories::SampleMaps); sampleMapFile = sampleMapFolder.getChildFile(sampleMapPath + "".xml""); //sampleMapFile = sampleMapFolder.getChildFile(sampleMapId + "".xml""); auto& lock = sampler->getMainController()->getSampleManager().getSampleLock(); while (!lock.tryEnter()) Thread::sleep(500); lock.exit(); exportCurrentSampleMap(overwriteExistingData, exportSamples, exportSampleMap); } void run() override { generateDirectoryList(); showStatusMessage(""Writing JSON list""); const String data = JSON::toString(fileNameList); File f = GET_PROJECT_HANDLER(bpe->getMainSynthChain()).getSubDirectory(ProjectHandler::SubDirectories::Scripts).getChildFile(""samplemaps.js""); f.replaceWithText(data); ExportOptions optionIndex = (ExportOptions)getComboBoxComponent(""option"")->getSelectedItemIndex(); const bool exportSamples = (optionIndex == ExportAll); const bool exportSampleMap = (optionIndex == ExportSampleMapsAndJSON) || (optionIndex == ExportAll); const bool overwriteData = getComboBoxComponent(""overwriteFiles"")->getSelectedItemIndex() == 0; for (int i = 0; i < fileList.size(); i++) { if (threadShouldExit()) { break; } setProgress((double)i / (double)fileList.size()); convertSampleMap(fileList[i], overwriteData, exportSamples, exportSampleMap); } } void generateDirectoryList() { sampler->getMainController()->getSampleManager().getModulatorSamplerSoundPool()->setUpdatePool(false); Array allDirectories; const int depth = getComboBoxComponent(""directoryDepth"")->getText().getIntValue(); sampleFolder.findChildFiles(allDirectories, File::findDirectories, true); const String separator = getTextEditor(""directorySeparator"")->getText(); for (int i = 0; i < allDirectories.size(); i++) { int thisDepth = 1; getDepth(sampleFolder, allDirectories[i], thisDepth); if (thisDepth == depth) { fileList.add(allDirectories[i]); } } for (int i = 0; i < fileList.size(); i++) { #if JUCE_WINDOWS const String slash = ""\\\\""; #else const String slash = ""/""; #endif String s = fileList[i].getRelativePathFrom(sampleFolder).replace(slash, separator); fileNameList.add(var(s)); } } void threadFinished() override { }; private: Array fileNameList; Array fileList; File sampleFolder; BackendRootWindow* bpe; ModulatorSampler* sampler; ModulatorSynthChain* chain; }; class PoolExporter : public DialogWindowWithBackgroundThread { public: PoolExporter(MainController* mc_): DialogWindowWithBackgroundThread(""Exporting pool resources""), mc(mc_) { addBasicComponents(false); runThread(); } void run() override { showStatusMessage(""Exporting pools""); auto& handler = mc->getCurrentFileHandler(); handler.exportAllPoolsToTemporaryDirectory(mc->getMainSynthChain(), &logData); } void threadFinished() override { PresetHandler::showMessageWindow(""Sucessfully exported"", ""All pools were successfully exported""); auto& data = dynamic_cast(mc)->getSettingsObject(); auto project = data.getSetting(HiseSettings::Project::Name).toString(); auto company = data.getSetting(HiseSettings::User::Company).toString(); auto targetDirectory = ProjectHandler::getAppDataDirectory().getParentDirectory().getChildFile(company).getChildFile(project); auto& handler = mc->getCurrentFileHandler(); if (!(bool)data.getSetting(HiseSettings::Project::EmbedImageFiles)) { if (PresetHandler::showYesNoWindow(""Copy image pool file to App data directory"", ""Do you want to copy the ImageResources.dat file to the app data directory?\\nThis is required for the compiled plugin to load the new resources on this machine"")) { auto f = handler.getTempFileForPool(FileHandlerBase::Images); jassert(f.existsAsFile()); f.copyFileTo(targetDirectory.getChildFile(f.getFileName())); } } if (!(bool)data.getSetting(HiseSettings::Project::EmbedAudioFiles)) { if (PresetHandler::showYesNoWindow(""Copy audio pool file to App data directory"", ""Do you want to copy the AudioResources.dat file to the app data directory?\\nThis is required for the compiled plugin to load the new resources on this machine"")) { auto f = handler.getTempFileForPool(FileHandlerBase::AudioFiles); jassert(f.existsAsFile()); f.copyFileTo(targetDirectory.getChildFile(f.getFileName())); } } } private: MainController* mc; }; class CyclicReferenceChecker: public DialogWindowWithBackgroundThread { public: CyclicReferenceChecker(BackendProcessorEditor* bpe_) : DialogWindowWithBackgroundThread(""Checking cyclic references""), bpe(bpe_) { StringArray processorList = ProcessorHelpers::getAllIdsForType(bpe->getMainSynthChain()); addComboBox(""scriptProcessor"", processorList, ""ScriptProcessor to analyze""); addBasicComponents(true); } void run() override { setProgress(-1.0); auto id = getComboBoxComponent(""scriptProcessor"")->getText(); auto jsp = dynamic_cast(ProcessorHelpers::getFirstProcessorWithName(bpe->getMainSynthChain(), id)); if (jsp != nullptr) { data.progress = &logData.progress; data.thread = this; showStatusMessage(""Recompiling script""); { // don't bother... MessageManagerLock mm; jsp->compileScriptWithCycleReferenceCheckEnabled(); } showStatusMessage(""Checking Cyclic references""); jsp->getScriptEngine()->checkCyclicReferences(data, Identifier()); } } void threadFinished() { if (data.overflowHit) { PresetHandler::showMessageWindow(""Overflow"", ""The reference check was cancelled due to a stack overflow"", PresetHandler::IconType::Error); } else if (data.cyclicReferenceString.isNotEmpty()) { if (PresetHandler::showYesNoWindow(""Cyclic References found"", ""The "" + data.cyclicReferenceString + "" is a cyclic reference. Your script will be leaking memory.\\nPres OK to copy this message to the clipboard."", PresetHandler::IconType::Error)) { SystemClipboard::copyTextToClipboard(data.cyclicReferenceString); } } else { PresetHandler::showMessageWindow(""No Cyclic References found"", ""Your script does not contain cyclic references.\\n"" + String(data.numChecked) + "" references were checked"", PresetHandler::IconType::Info); } } private: HiseJavascriptEngine::CyclicReferenceCheckBase::ThreadData data; BackendProcessorEditor* bpe; }; class SampleMapPropertySaverWithBackup : public DialogWindowWithBackgroundThread, public ControlledObject { public: enum class Preset { None, All, Positions, Volume, Tables, numPresets }; static Array getPropertyIds(Preset p) { switch (p) { case Preset::None: return {}; case Preset::All: return { SampleIds::GainTable, SampleIds::PitchTable, SampleIds::LowPassTable, SampleIds::SampleStart, SampleIds::SampleEnd, SampleIds::LoopXFade, SampleIds::Volume, SampleIds::Pitch, SampleIds::Normalized }; case Preset::Positions: return { SampleIds::SampleStart, SampleIds::SampleEnd, SampleIds::LoopXFade }; case Preset::Volume: return { SampleIds::Volume, SampleIds::Pitch, SampleIds::Normalized }; case Preset::Tables: return { SampleIds::GainTable, SampleIds::PitchTable, SampleIds::LowPassTable }; default: return {}; } } struct PropertySelector: public Component, public ComboBoxListener { struct Item : public Component { Item(Identifier& id_): id(id_.toString()) { setRepaintsOnMouseActivity(true); } void mouseDown(const MouseEvent& e) override { active = !active; repaint(); } void paint(Graphics& g) override { auto b = getLocalBounds().toFloat().reduced(1.0f); g.setColour(Colours::white.withAlpha(isMouseOver(true) ? 0.3f : 0.2f)); g.fillRect(b); g.drawRect(b, 1.0f); g.setColour(Colours::white.withAlpha(active ? 0.9f : 0.2f)); g.setFont(GLOBAL_MONOSPACE_FONT()); g.drawText(id, b, Justification::centred); } String id; bool active = false; }; PropertySelector() { for (auto id : getPropertyIds(Preset::All)) { auto item = new Item(id); addAndMakeVisible(item); items.add(item); } addAndMakeVisible(presets); presets.addItemList({ ""None"", ""All"", ""Positions"", ""Volume"", ""Tables"" }, 1); presets.addListener(this); presets.setTextWhenNothingSelected(""Presets""); setSize(350, 100); } void comboBoxChanged(ComboBox*) override { Preset p = (Preset)presets.getSelectedItemIndex(); auto selectedIds = getPropertyIds(p); for (auto i : items) { i->active = selectedIds.contains(Identifier(i->id)); i->repaint(); } } void paint(Graphics& g) override { auto b = getLocalBounds().removeFromTop(24).toFloat(); g.setFont(GLOBAL_BOLD_FONT()); g.setColour(Colours::white); g.drawText(""Properties to apply"", b, Justification::centredLeft); } void resized() override { auto b = getLocalBounds(); auto top = b.removeFromTop(24); static constexpr int NumRows = 3; static constexpr int NumCols = 3; auto rowHeight = b.getHeight() / 3; auto colWidth = b.getWidth() / 3; int cellIndex = 0; presets.setBounds(top.removeFromRight(colWidth)); for (int row = 0; row < NumRows; row++) { auto r = b.removeFromTop(rowHeight); for (int col = 0; col < NumCols; col++) { auto cell = r.removeFromLeft(colWidth); items[cellIndex++]->setBounds(cell); } } } OwnedArray items; ComboBox presets; }; SampleMapPropertySaverWithBackup(BackendRootWindow* bpe) : DialogWindowWithBackgroundThread(""Apply Samplemap Properties""), ControlledObject(bpe->getMainController()), result(Result::ok()) { auto samplemapList = getMainController()->getCurrentFileHandler().pool->getSampleMapPool().getIdList(); addComboBox(""samplemapId"", samplemapList, ""SampleMap""); addTextEditor(""backup_postfix"", ""_backup"", ""Backup folder suffix""); sampleMapId = getComboBoxComponent(""samplemapId""); sampleMapId->onChange = BIND_MEMBER_FUNCTION_0(SampleMapPropertySaverWithBackup::refresh); suffix = getTextEditor(""backup_postfix""); suffix->onTextChange = BIND_MEMBER_FUNCTION_0(SampleMapPropertySaverWithBackup::refresh); addCustomComponent(propertySelector = new PropertySelector()); addBasicComponents(true); refresh(); } void refresh() { if (sampleMapId->getSelectedId() == 0) { showStatusMessage(""Select a samplemap you want to apply""); return; } auto bf = getBackupFolder(); auto exists = bf.isDirectory(); if (exists) showStatusMessage(""Press OK to restore the backup from /"" + bf.getFileName()); else showStatusMessage(""Press OK to move the original files to /"" + bf.getFileName() + "" and apply the properties""); } File getBackupFolder() { auto sampleFolder = getMainController()->getCurrentFileHandler().getRootFolder().getChildFile(""SampleBackups""); sampleFolder.createDirectory(); auto t = getComboBoxComponent(""samplemapId"")->getText().fromLastOccurrenceOf(""}"", false, false); t << getTextEditor(""backup_postfix"")->getText(); return sampleFolder.getChildFile(t); } File getSampleFolder() const { return getMainController()->getCurrentFileHandler().getSubDirectory(FileHandlerBase::Samples); } void threadFinished() override { getMainController()->getCurrentFileHandler().pool->getSampleMapPool().refreshPoolAfterUpdate(); if (!result.wasOk()) { PresetHandler::showMessageWindow(""Error at applying properties"", result.getErrorMessage(), PresetHandler::IconType::Error); } else { if (doBackup) { if (PresetHandler::showYesNoWindow(""OK"", ""The backup was successfully restored. Do you want to delete the backup folder?"")) { getBackupFolder().deleteRecursively(); } } else { String m; m << ""The samplemap was applied and saved as backup""; if (wasMonolith) m << "" \\n> The monolith files were also removed, so you can reencode the samplemap""; PresetHandler::showMessageWindow(""OK"", m); } } } struct SampleWithPropertyData: public ReferenceCountedObject { using List = ReferenceCountedArray; SampleWithPropertyData() = default; void addFileFromValueTree(MainController* mc, const ValueTree& v) { if (v.hasProperty(SampleIds::FileName)) { PoolReference sRef(mc, v[SampleIds::FileName].toString(), FileHandlerBase::SubDirectories::Samples); if (sRef.isAbsoluteFile()) { String s; s << ""Absolute file reference detected \\n""; s << ""> "" << sRef.getFile().getFullPathName() << ""\\n""; throw Result::fail(s); } sampleFiles.add(sRef.getFile()); } for (auto c : v) addFileFromValueTree(mc, c); } bool operator==(const SampleWithPropertyData& other) const { for (auto& tf : sampleFiles) { for (auto& otf : other.sampleFiles) { if (tf == otf) return true; } } return false; } void addDelta(int delta, const Array& otherIds) { for (auto i : otherIds) { if (propertyData.hasProperty(i)) { auto newValue = (int)propertyData[i] + delta; propertyData.setProperty(i, newValue, nullptr); } } } void addFactor(double factor, const Array& otherIds) { for (auto i : otherIds) { if (propertyData.hasProperty(i)) { auto newValue = (double)propertyData[i] * factor; propertyData.setProperty(i, (int)(newValue), nullptr); } } } void apply(const Identifier& id) { for (auto f : sampleFiles) { apply(id, f); } } void apply(const Identifier& id, File& fileToUse) { if (!propertyData.hasProperty(id) || propertyData[id].toString().getIntValue() == 0) return; auto value = propertyData[id]; double unused = 0; auto ob = hlac::CompressionHelpers::loadFile(fileToUse, unused); int numChannels = ob.getNumChannels(); int numSamples = ob.getNumSamples(); fileToUse.deleteFile(); AudioSampleBuffer lut; bool isTable = getPropertyIds(Preset::Tables).contains(id); if (isTable) { SampleLookupTable t; t.fromBase64String(propertyData[id].toString()); lut = AudioSampleBuffer(1, numSamples); t.fillExternalLookupTable(lut.getWritePointer(0), numSamples); } if (id == SampleIds::Volume) { float gainFactor = Decibels::decibelsToGain((float)value); ob.applyGain(gainFactor); } else if (id == SampleIds::Normalized) { auto gainFactor = (float)propertyData[SampleIds::NormalizedPeak]; ob.applyGain(gainFactor); propertyData.removeProperty(SampleIds::NormalizedPeak, nullptr); } else if (id == SampleIds::SampleStart) { int offset = (int)value; AudioSampleBuffer nb(numChannels, numSamples - offset); for (int i = 0; i < numChannels; i++) FloatVectorOperations::copy(nb.getWritePointer(i), ob.getReadPointer(i, offset), nb.getNumSamples()); addDelta(-offset, { SampleIds::SampleEnd, SampleIds::LoopStart, SampleIds::LoopEnd }); std::swap(nb, ob); } else if (id == SampleIds::LoopXFade) { int xfadeSize = (int)value; AudioSampleBuffer loopBuffer(numChannels, xfadeSize); loopBuffer.clear(); float fadeOutStart = (int)propertyData[SampleIds::LoopEnd] - xfadeSize; auto fadeInStart = (int)propertyData[SampleIds::LoopStart] - xfadeSize; ob.applyGainRamp(fadeOutStart, xfadeSize, 1.0f, 0.0f); for (int i = 0; i < numChannels; i++) ob.addFromWithRamp(i, fadeOutStart, ob.getReadPointer(i, fadeInStart), xfadeSize, 0.0f, 1.0f); } else if (id == SampleIds::SampleEnd) { int length = (int)value; AudioSampleBuffer nb(numChannels, length); for (int i = 0; i < numChannels; i++) FloatVectorOperations::copy(nb.getWritePointer(i), ob.getReadPointer(i, 0), length); std::swap(nb, ob); } else if (id == SampleIds::Pitch || id == SampleIds::PitchTable) { int newNumSamples = 0; auto getPitchFactor = [&](int index) { if (isTable) return (double)ModulatorSamplerSound::EnvelopeTable::getPitchValue(lut.getSample(0, index)); else return scriptnode::conversion_logic::st2pitch().getValue((double)propertyData[id] / 100.0); }; if (isTable) { double samplesToCalculate = 0.0; for (int i = 0; i < numSamples; i++) samplesToCalculate += 1.0 / getPitchFactor(i); newNumSamples = (int)samplesToCalculate; } else newNumSamples = (int)((double)numSamples / getPitchFactor(0)); AudioSampleBuffer nb(numChannels, newNumSamples); ValueTree tableIndexes; Array sampleRangeIds = { SampleIds::SampleStart, SampleIds::SampleEnd, SampleIds::LoopStart, SampleIds::LoopEnd, SampleIds::LoopXFade, SampleIds::SampleStartMod }; if (isTable) { tableIndexes = ValueTree(""Ranges""); for (auto id : sampleRangeIds) { if (propertyData.hasProperty(id)) tableIndexes.setProperty(id, propertyData[id], nullptr); } } double uptime = 0.0; for (int i = 0; i < newNumSamples; i++) { auto i0 = jmin(numSamples-1, (int)uptime); auto i1 = jmin(numSamples-1, i0 + 1); auto alpha = uptime - (double)i0; for (int c = 0; c < numChannels; c++) { auto v0 = ob.getSample(c, i0); auto v1 = ob.getSample(c, i1); auto v = Interpolator::interpolateLinear(v0, v1, (float)alpha); nb.setSample(c, i, v); } auto uptimeDelta = getPitchFactor(0); if (isTable) { for (int i = 0; i < tableIndexes.getNumProperties(); i++) { auto id = tableIndexes.getPropertyName(i); if ((int)tableIndexes[id] == i) tableIndexes.setProperty(id, (int)uptime, nullptr); } auto pf0 = getPitchFactor(i0); auto pf1 = getPitchFactor(i1); uptimeDelta = Interpolator::interpolateLinear(pf0, pf1, alpha); } uptime += uptimeDelta; } if (isTable) { for (int i = 0; i < tableIndexes.getNumProperties(); i++) { auto id = tableIndexes.getPropertyName(i); propertyData.setProperty(id, tableIndexes[id], nullptr); } } else { // Calculate the static offset addFactor(1.0 / getPitchFactor(0), sampleRangeIds); } std::swap(ob, nb); } else if(id == SampleIds::GainTable) { for (int c = 0; c < numChannels; c++) { for (int i = 0; i < numSamples; i++) { auto gainFactor = ModulatorSamplerSound::EnvelopeTable::getGainValue(lut.getSample(0, i)); auto value = ob.getSample(c, i); ob.setSample(c, i, value * gainFactor); } } } else if (id == SampleIds::LowPassTable) { CascadedEnvelopeLowPass lp(true); PrepareSpecs ps; ps.blockSize = 16; ps.sampleRate = 44100.0; ps.numChannels = numChannels; lp.prepare(ps); snex::PolyHandler::ScopedVoiceSetter svs(lp.polyManager, 0); for (int i = 0; i < numSamples; i+= ps.blockSize) { int numToDo = jmin(ps.blockSize, numSamples - i); auto v = lut.getSample(0, i); auto freq = ModulatorSamplerSound::EnvelopeTable::getFreqValue(v); lp.process(freq, ob, i, numToDo); } } propertyData.removeProperty(id, nullptr); hlac::CompressionHelpers::dump(ob, fileToUse.getFullPathName()); } ValueTree propertyData; Array sampleFiles; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(SampleWithPropertyData); }; File getSampleMapFile(bool fromBackup) { if (fromBackup) return getBackupFolder().getChildFile(sampleMapId->getText()).withFileExtension(""xml""); else { PoolReference ref(getMainController(), sampleMapId->getText(), FileHandlerBase::SampleMaps); return ref.getFile(); } } Array getPropertiesToProcess() { Array ids; for (auto i : propertySelector->items) { if (!i->active) continue; ids.add(Identifier(i->id)); } return ids; } SampleWithPropertyData::List saveToBackup() { SampleWithPropertyData::List fileList; showStatusMessage(""Saving backup""); auto smf = getSampleMapFile(false); auto v = ValueTree::fromXml(smf.loadFileAsString()); if (!v.isValid()) throw Result::fail(""Can't load samplemap""); wasMonolith = (int)v[Identifier(""SaveMode"")] != 0; if (wasMonolith) { getMainController()->getSampleManager().getModulatorSamplerSoundPool2()->clearUnreferencedMonoliths(); auto monolist = getSampleFolder().findChildFiles(File::findFiles, false); for (auto m : monolist) { if (m.getFileExtension().startsWith("".ch"") && m.getFileNameWithoutExtension() == sampleMapId->getText()) { auto ok = m.deleteFile(); if (!ok) throw Result::fail(""Can't delete monolith""); } } } auto bf = getBackupFolder(); auto r = bf.createDirectory(); auto ok = smf.copyFileTo(getSampleMapFile(true)); if (!ok) throw Result::fail(""Can't copy samplemap file""); if (!r.wasOk()) throw r; for (auto c : v) { ReferenceCountedObjectPtr newData = new SampleWithPropertyData(); newData->propertyData = c; newData->addFileFromValueTree(getMainController(), c); fileList.add(newData); } showStatusMessage(""Copying sample files to backup location""); double numTodo = (double)fileList.size(); double numDone = 0.0; for (auto sf : fileList) { setProgress(numDone / numTodo); for (auto sourceFile : sf->sampleFiles) { auto targetFilePath = sourceFile.getRelativePathFrom(getSampleFolder()); auto targetFile = bf.getChildFile(targetFilePath); if (!targetFile.getParentDirectory().isDirectory()) { r = targetFile.getParentDirectory().createDirectory(); if (!r.wasOk()) throw r; } auto ok = sourceFile.copyFileTo(targetFile); if (!ok) throw Result::fail(""Can't copy sample file""); } } return fileList; } void restoreFromBackup() { auto smf = getSampleMapFile(true); if (!smf.existsAsFile()) { throw Result::fail(""Can't find samplemap backup file""); } auto ok = smf.copyFileTo(getSampleMapFile(false)); if (!ok) throw Result::fail(""Can't copy samplemap backup""); auto fileList = getBackupFolder().findChildFiles(File::findFiles, true, ""*""); for (auto f : fileList) { if (f == smf) continue; if (f.isHidden()) continue; auto targetPath = f.getRelativePathFrom(getBackupFolder()); auto targetFile = getSampleFolder().getChildFile(targetPath); if (targetFile.existsAsFile()) { auto ok = targetFile.deleteFile(); if (!ok) throw Result::fail(""Can't delete file \\n> "" + targetFile.getFullPathName()); } auto ok = f.copyFileTo(targetFile); if (!ok) throw Result::fail(""Can't copy file \\n>"" + f.getFullPathName()); } } static void removeProperties(ValueTree v, const Array& properties) { for (auto p : properties) v.removeProperty(p, nullptr); for (auto c : v) removeProperties(c, properties); } void applyChanges(SampleWithPropertyData::List& sampleList) { auto propertiesToProcess = getPropertiesToProcess(); double numTodo = sampleList.size(); double numDone = 0.0; for (auto s : sampleList) { setProgress(numDone / numTodo); numDone += 1.0; for (const auto& p : propertiesToProcess) { s->apply(p); } } auto v = ValueTree::fromXml(getSampleMapFile(true).loadFileAsString()); v.removeAllChildren(nullptr); for (auto s : sampleList) { v.addChild(s->propertyData.createCopy(), -1, nullptr); } if (wasMonolith) { // set it to use the files v.setProperty(""SaveMode"", 0, nullptr); // remove the monolith info removeProperties(v, { Identifier(""MonolithLength""), Identifier(""MonolithOffset"") }); } auto xml = v.createXml(); getSampleMapFile(false).replaceWithText(xml->createDocument("""")); } void run() override { auto bf = getBackupFolder(); try { doBackup = bf.isDirectory(); if (doBackup) { restoreFromBackup(); } else { auto propertiesToProcess = getPropertiesToProcess(); if (propertiesToProcess.isEmpty()) { throw Result::fail(""No properties selected""); } auto sampleList = saveToBackup(); applyChanges(sampleList); } } catch (Result& r) { result = r; } } Result result; bool doBackup = false; bool wasMonolith = false; ComboBox* sampleMapId; TextEditor* suffix; ScopedPointer propertySelector; }; class ProjectDownloader : public DialogWindowWithBackgroundThread, public TextEditor::Listener { public: enum class ErrorCodes { OK = 0, InvalidURL, URLNotFound, DirectoryAlreadyExists, FileNotAnArchive, AbortedByUser, numErrorCodes }; ProjectDownloader(BackendProcessorEditor *bpe_) : DialogWindowWithBackgroundThread(""Download new Project""), bpe(bpe_), result(ErrorCodes::OK) { addTextEditor(""url"", ""http://www."", ""URL""); #if HISE_IOS addTextEditor(""projectName"", ""Project"", ""Project Name""); #else targetFile = new FilenameComponent(""Target folder"", File(), true, true, true, """", """", ""Choose target folder""); targetFile->setSize(300, 24); addCustomComponent(targetFile); #endif addBasicComponents(true); addButton(""Paste URL from Clipboard"", 2); }; void resultButtonClicked(const String &name) { if (name == ""Paste URL from Clipboard"") { getTextEditor(""url"")->setText(SystemClipboard::getTextFromClipboard()); } } void run() override { #if HISE_IOS targetDirectory = File::getSpecialLocation(File::userDocumentsDirectory).getChildFile(getTextEditor(""projectName"")->getText()); if (targetDirectory.isDirectory()) { result = ErrorCodes::DirectoryAlreadyExists; return; } targetDirectory.createDirectory(); #else targetDirectory = targetFile->getCurrentFile(); if (targetDirectory.isDirectory() && targetDirectory.getNumberOfChildFiles(File::findFilesAndDirectories) != 0) { result = ErrorCodes::DirectoryAlreadyExists; return; } #endif const String enteredURL = getTextEditor(""url"")->getText(); const String directURL = replaceHosterLinksWithDirectDownloadURL(enteredURL); URL downloadLocation(directURL); if (!downloadLocation.isWellFormed()) { result = ErrorCodes::InvalidURL; targetDirectory.deleteRecursively(); return; } showStatusMessage(""Downloading the project""); auto stream = downloadLocation.createInputStream(false, &downloadProgress, this, String(), 0, nullptr, &httpStatusCode, 20); if (stream == nullptr || stream->getTotalLength() <= 0) { result = ErrorCodes::URLNotFound; targetDirectory.deleteRecursively(); return; } File tempFile(File::getSpecialLocation(File::tempDirectory).getChildFile(""projectDownload.tmp"")); tempFile.deleteFile(); tempFile.create(); auto fos = tempFile.createOutputStream(); MemoryBlock mb; mb.setSize(8192); const int64 numBytesTotal = stream->getNumBytesRemaining(); int64 numBytesRead = 0; while (stream->getNumBytesRemaining() > 0) { const int64 chunkSize = (int64)jmin((int)stream->getNumBytesRemaining(), 8192); downloadProgress(this, (int)numBytesRead, (int)numBytesTotal); if (threadShouldExit()) { result = ErrorCodes::AbortedByUser; fos->flush(); fos = nullptr; tempFile.deleteFile(); targetDirectory.deleteRecursively(); return; } stream->read(mb.getData(), (int)chunkSize); numBytesRead += chunkSize; fos->write(mb.getData(), (size_t)chunkSize); } fos->flush(); showStatusMessage(""Extracting...""); setProgress(-1.0); FileInputStream fis(tempFile); ZipFile input(&fis, false); if (input.getNumEntries() == 0) { result = ErrorCodes::FileNotAnArchive; tempFile.deleteFile(); targetDirectory.deleteRecursively(); return; } const int numFiles = input.getNumEntries(); for (int i = 0; i < numFiles; i++) { if (threadShouldExit()) { tempFile.deleteFile(); targetDirectory.deleteRecursively(); result = ErrorCodes::AbortedByUser; break; } input.uncompressEntry(i, targetDirectory, true); setProgress((double)i / (double)numFiles); } tempFile.deleteFile(); } static bool downloadProgress(void* context, int bytesSent, int totalBytes) { const double downloadedMB = (double)bytesSent / 1024.0 / 1024.0; const double totalMB = (double)totalBytes / 1024.0 / 1024.0; const double percent = (totalMB > 0.0) ? (downloadedMB / totalMB) : 0.0; static_cast(context)->showStatusMessage(""Downloaded: "" + String(downloadedMB, 1) + "" MB / "" + String(totalMB, 2) + "" MB""); static_cast(context)->setProgress(percent); return !static_cast(context)->threadShouldExit(); } void threadFinished() override { switch (result) { case ProjectDownloader::ErrorCodes::OK: if (PresetHandler::showYesNoWindow(""Switch projects"", ""Do you want to switch to the downloaded project?"", PresetHandler::IconType::Question)) { GET_PROJECT_HANDLER(bpe->getMainSynthChain()).setWorkingProject(targetDirectory); } break; case ProjectDownloader::ErrorCodes::InvalidURL: PresetHandler::showMessageWindow(""Wrong URL"", ""The entered URL is not valid"", PresetHandler::IconType::Error); break; case ProjectDownloader::ErrorCodes::URLNotFound: PresetHandler::showMessageWindow(""Error downloading"", ""The URL could not be opened. HTTP status code: "" + String(httpStatusCode), PresetHandler::IconType::Error); break; case ProjectDownloader::ErrorCodes::DirectoryAlreadyExists: PresetHandler::showMessageWindow(""Project already exists."", ""You'll need to delete the existing project before downloading."", PresetHandler::IconType::Error); break; case ProjectDownloader::ErrorCodes::FileNotAnArchive: PresetHandler::showMessageWindow(""Archive corrupt"", ""The file could not be extracted because it is either corrupt or not an archive."", PresetHandler::IconType::Error); case ProjectDownloader::ErrorCodes::AbortedByUser: PresetHandler::showMessageWindow(""Download cancelled"", ""The project was not downloaded because the progress was aborted."", PresetHandler::IconType::Error); case ProjectDownloader::ErrorCodes::numErrorCodes: break; default: break; } } private: /** A small helper function that replaces links to cloud content with their direct download URL. */ static String replaceHosterLinksWithDirectDownloadURL(const String url) { const bool dropBox = url.containsIgnoreCase(""dropbox""); const bool googleDrive = url.containsIgnoreCase(""drive.google.com""); if (dropBox) { return url.replace(""dl=0"", ""dl=1"");; } else if (googleDrive) { const String downloadID = url.fromFirstOccurrenceOf(""https://drive.google.com/file/d/"", false, true).upToFirstOccurrenceOf(""/"", false, false); const String directLink = ""https://drive.google.com/uc?export=download&id="" + downloadID; return directLink; } else return url; } BackendProcessorEditor *bpe; ScopedPointer targetFile; File targetDirectory; ErrorCodes result; int httpStatusCode; }; struct DeviceTypeSanityCheck : public DialogWindowWithBackgroundThread, public ControlledObject { enum TestIndex { ControlPersistency, DefaultValues, InitState, AllTests }; DeviceTypeSanityCheck(MainController* mc): DialogWindowWithBackgroundThread(""Checking Device type sanity""), ControlledObject(mc) { StringArray options; options.add(""iPad only""); options.add(""iPhone only""); options.add(""iPad / iPhone""); addComboBox(""targets"", options, ""Device Targets""); StringArray tests; tests.add(""Check Control persistency""); tests.add(""Check default values""); tests.add(""Check init state matches default values""); tests.add(""All tests""); addComboBox(""tests"", tests, ""Tests to run""); addBasicComponents(true); } void run() override { ok = true; mp = JavascriptMidiProcessor::getFirstInterfaceScriptProcessor(getMainController()); content = mp->getScriptingContent(); desktopConnections = createArrayForCurrentDevice(); auto testIndex = getComboBoxComponent(""tests"")->getSelectedItemIndex(); auto index = getComboBoxComponent(""targets"")->getSelectedItemIndex(); CompileExporter::BuildOption option = CompileExporter::BuildOption::Cancelled; if (index == 0) option = CompileExporter::BuildOption::StandaloneiPad; if (index == 1) option = CompileExporter::BuildOption::StandaloneiPhone; if (index == 2) option = CompileExporter::BuildOption::StandaloneiOS; if (testIndex == ControlPersistency || testIndex == AllTests) { runTest(option, [this](HiseDeviceSimulator::DeviceType t) {this->checkPersistency(t); }); } if (testIndex == DefaultValues || testIndex == AllTests) { runTest(option, [this](HiseDeviceSimulator::DeviceType t) {this->checkDefaultValues(t); }); } if (testIndex == InitState || testIndex == AllTests) { checkInitState(); } } void threadFinished() override { if (ok) PresetHandler::showMessageWindow(""Tests passed"", ""All tests are passed""); else PresetHandler::showMessageWindow(""Tests failed"", ""Some tests failed. Check the console for more info"", PresetHandler::IconType::Error); } struct ProcessorConnection { bool operator==(const ProcessorConnection& other) const { return other.id == id; } Identifier id; Processor* p = nullptr; int parameterIndex = -1; var defaultValue; }; Array createArrayForCurrentDevice() { Array newList; debugToConsole(mp, "" - "" + HiseDeviceSimulator::getDeviceName()); for (int i = 0; i < content->getNumComponents(); i++) { auto sc = content->getComponent(i); if (!sc->getScriptObjectProperty(ScriptComponent::saveInPreset)) continue; ProcessorConnection pc; pc.id = sc->getName(); pc.p = sc->getConnectedProcessor(); pc.parameterIndex = sc->getConnectedParameterIndex(); pc.defaultValue = sc->getScriptObjectProperty(ScriptComponent::Properties::defaultValue); newList.add(pc); } return newList; } void throwError(const String& message) { String error = HiseDeviceSimulator::getDeviceName() + "": "" + message; throw error; } bool ok = true; void setDeviceType(HiseDeviceSimulator::DeviceType type) { showStatusMessage(""Setting device type "" + HiseDeviceSimulator::getDeviceName()); HiseDeviceSimulator::setDeviceType(type); auto contentData = content->exportAsValueTree(); mp->setDeviceTypeForInterface((int)type); showStatusMessage(""Waiting for compilation""); waitingForCompilation = true; bool* w = &waitingForCompilation; auto& tmp = mp; auto f = [tmp, w]() { auto rf = [w](const JavascriptProcessor::SnippetResult&) { *w = false; return; }; tmp->compileScript(rf); }; MessageManager::callAsync(f); while (waitingForCompilation && !threadShouldExit()) { Thread::sleep(500); } showStatusMessage(""Restoring content values""); mp->getContent()->restoreFromValueTree(contentData); } void log(const String& s) { debugToConsole(mp, s); } Array setAndCreateArray(HiseDeviceSimulator::DeviceType type) { if (threadShouldExit()) return {}; setDeviceType(type); if (!mp->hasUIDataForDeviceType()) { if (HiseDeviceSimulator::isAUv3()) showStatusMessage(""You need to define a interface for AUv3""); return {}; } if (threadShouldExit()) return {}; return createArrayForCurrentDevice(); } void checkDefaultValues(HiseDeviceSimulator::DeviceType type) { auto deviceConnections = setAndCreateArray(type); showStatusMessage(""Checking default values""); for (const auto& item : deviceConnections) { auto dItemIndex = desktopConnections.indexOf(item); if (dItemIndex == -1) { log(""Missing control found. Run persistency check""); ok = false; return; } auto expected = desktopConnections[dItemIndex].defaultValue; auto actual = item.defaultValue; if (expected != actual) { ok = false; log(""Default value mismatch for "" + item.id); } } } void checkInitState() { setDeviceType(HiseDeviceSimulator::DeviceType::Desktop); desktopConnections = createArrayForCurrentDevice(); for (int i = 0; i < content->getNumComponents(); i++) { auto sc = content->getComponent(i); if (!sc->getScriptObjectProperty(ScriptComponent::saveInPreset)) continue; if (sc->getValue() != sc->getScriptObjectProperty(ScriptComponent::defaultValue)) { ok = false; log(""Init value mismatch for "" + sc->getName().toString()); } } } void checkPersistency(HiseDeviceSimulator::DeviceType type) { log(""Testing persistency for "" + HiseDeviceSimulator::getDeviceName((int)type)); auto deviceConnections = setAndCreateArray(type); if(deviceConnections.size() == 0) { return; } showStatusMessage(""Checking UI controls""); StringArray missingInDesktop; StringArray missingInDevice; StringArray connectionErrors; compareArrays(desktopConnections, deviceConnections, missingInDesktop, connectionErrors); compareArrays(deviceConnections, desktopConnections, missingInDevice, connectionErrors); if (!missingInDesktop.isEmpty()) { log(String(""Missing in Desktop: "")); for (const auto& s : missingInDesktop) log(s); } if (!missingInDevice.isEmpty()) { log(""Missing in "" + HiseDeviceSimulator::getDeviceName()); for (const auto& s : missingInDevice) log(s); } if (!connectionErrors.isEmpty()) { log(""Connection errors""); for (const auto& s : connectionErrors) log(s); } } void compareArrays(const Array& testArray, const Array& compareArray, StringArray& missingNames, StringArray& connectionErrors) { for (const auto& item : testArray) { int index = compareArray.indexOf(item); if (index == -1) { missingNames.add(item.id.toString()); ok = false; } else { const bool processorMatches = item.p == compareArray[index].p; const bool parameterMatches = item.parameterIndex == compareArray[index].parameterIndex; if (!processorMatches || !parameterMatches) { ok = false; connectionErrors.add(""Connection mismatch for "" + item.id); } } } } Array desktopConnections; ScriptingApi::Content* content; JavascriptMidiProcessor* mp; public: bool waitingForCompilation = false; using TestFunction = std::function; void runTest(CompileExporter::BuildOption option, const TestFunction& tf) { if (HiseDeviceSimulator::getDeviceType() != HiseDeviceSimulator::DeviceType::Desktop) log(""Device Type must be Desktop for exporting""); try { if (CompileExporter::BuildOptionHelpers::isIPad(option)) { tf(HiseDeviceSimulator::DeviceType::iPad); tf(HiseDeviceSimulator::DeviceType::iPadAUv3); } if (CompileExporter::BuildOptionHelpers::isIPhone(option)) { tf(HiseDeviceSimulator::DeviceType::iPhone); tf(HiseDeviceSimulator::DeviceType::iPhoneAUv3); } } catch (String& s) { setDeviceType(HiseDeviceSimulator::DeviceType::Desktop); log(s); } setDeviceType(HiseDeviceSimulator::DeviceType::Desktop); } }; } // namespace hise ",16235,True,3072.6036809996995,median "//// /** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * ""License""); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an ""AS IS"" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ //// [[upgrading]] = Upgrading :doctype: book :numbered: :toc: left :icons: font :experimental: You cannot skip major versions when upgrading. If you are upgrading from version 0.98.x to 2.x, you must first go from 0.98.x to 1.2.x and then go from 1.2.x to 2.x. Review <>, in particular <>. Familiarize yourself with <>. [[hbase.versioning]] == HBase version number and compatibility [[hbase.versioning.post10]] === Aspirational Semantic Versioning Starting with the 1.0.0 release, HBase is working towards link:http://semver.org/[Semantic Versioning] for its release versioning. In summary: .Given a version number MAJOR.MINOR.PATCH, increment the: * MAJOR version when you make incompatible API changes, * MINOR version when you add functionality in a backwards-compatible manner, and * PATCH version when you make backwards-compatible bug fixes. * Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format. [[hbase.versioning.compat]] .Compatibility Dimensions In addition to the usual API versioning considerations HBase has other compatibility dimensions that we need to consider. .Client-Server wire protocol compatibility * Allows updating client and server out of sync. * We could only allow upgrading the server first. I.e. the server would be backward compatible to an old client, that way new APIs are OK. * Example: A user should be able to use an old client to connect to an upgraded cluster. .Server-Server protocol compatibility * Servers of different versions can co-exist in the same cluster. * The wire protocol between servers is compatible. * Workers for distributed tasks, such as replication and log splitting, can co-exist in the same cluster. * Dependent protocols (such as using ZK for coordination) will also not be changed. * Example: A user can perform a rolling upgrade. .File format compatibility * Support file formats backward and forward compatible * Example: File, ZK encoding, directory layout is upgraded automatically as part of an HBase upgrade. User can downgrade to the older version and everything will continue to work. .Client API compatibility * Allow changing or removing existing client APIs. * An API needs to be deprecated for a major version before we will change/remove it. * APIs available in a patch version will be available in all later patch versions. However, new APIs may be added which will not be available in earlier patch versions. * New APIs introduced in a patch version will only be added in a source compatible way footnote:[See 'Source Compatibility' https://blogs.oracle.com/darcy/entry/kinds_of_compatibility]: i.e. code that implements public APIs will continue to compile. ** Example: A user using a newly deprecated API does not need to modify application code with HBase API calls until the next major version. * .Client Binary compatibility * Client code written to APIs available in a given patch release can run unchanged (no recompilation needed) against the new jars of later patch versions. * Client code written to APIs available in a given patch release might not run against the old jars from an earlier patch version. ** Example: Old compiled client code will work unchanged with the new jars. * If a Client implements an HBase Interface, a recompile MAY be required upgrading to a newer minor version (See release notes for warning about incompatible changes). All effort will be made to provide a default implementation so this case should not arise. .Server-Side Limited API compatibility (taken from Hadoop) * Internal APIs are marked as Stable, Evolving, or Unstable * This implies binary compatibility for coprocessors and plugins (pluggable classes, including replication) as long as these are only using marked interfaces/classes. * Example: Old compiled Coprocessor, Filter, or Plugin code will work unchanged with the new jars. .Dependency Compatibility * An upgrade of HBase will not require an incompatible upgrade of a dependent project, except for Apache Hadoop. * An upgrade of HBase will not require an incompatible upgrade of the Java runtime. * Example: Upgrading HBase to a version that supports _Dependency Compatibility_ won't require that you upgrade your Apache ZooKeeper service. * Example: If your current version of HBase supported running on JDK 8, then an upgrade to a version that supports _Dependency Compatibility_ will also run on JDK 8. .Hadoop Versions [TIP] ==== Previously, we tried to maintain dependency compatibility for the underly Hadoop service but over the last few years this has proven untenable. While the HBase project attempts to maintain support for older versions of Hadoop, we drop the ""supported"" designator for minor versions that fail to continue to see releases. Additionally, the Hadoop project has its own set of compatibility guidelines, which means in some cases having to update to a newer supported minor release might break some of our compatibility promises. ==== .Operational Compatibility * Metric changes * Behavioral changes of services * JMX APIs exposed via the `/jmx/` endpoint .Summary * A patch upgrade is a drop-in replacement. Any change that is not Java binary and source compatible would not be allowed.footnote:[See http://docs.oracle.com/javase/specs/jls/se7/html/jls-13.html.] Downgrading versions within patch releases may not be compatible. * A minor upgrade requires no application/client code modification. Ideally it would be a drop-in replacement but client code, coprocessors, filters, etc might have to be recompiled if new jars are used. * A major upgrade allows the HBase community to make breaking changes. .Compatibility Matrix footnote:[Note that this indicates what could break, not that it will break. We will/should add specifics in our release notes.] [cols=""1,1,1,1""] |=== | | Major | Minor | Patch |Client-Server wire Compatibility| N |Y |Y |Server-Server Compatibility |N |Y |Y |File Format Compatibility | N footnote:[comp_matrix_offline_upgrade_note,Running an offline upgrade tool without downgrade might be needed. We will typically only support migrating data from major version X to major version X+1.] | Y |Y |Client API Compatibility | N | Y |Y |Client Binary Compatibility | N | N |Y 4+|Server-Side Limited API Compatibility >| Stable | N | Y | Y >| Evolving | N |N |Y >| Unstable | N |N |N |Dependency Compatibility | N |Y |Y |Operational Compatibility | N |N |Y |=== [[hbase.client.api.surface]] ==== HBase API Surface HBase has a lot of API points, but for the compatibility matrix above, we differentiate between Client API, Limited Private API, and Private API. HBase uses link:https://yetus.apache.org/documentation/0.5.0/interface-classification/[Apache Yetus Audience Annotations] to guide downstream expectations for stability. * InterfaceAudience (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceAudience.html[javadocs]): captures the intended audience, possible values include: - Public: safe for end users and external projects - LimitedPrivate: used for internals we expect to be pluggable, such as coprocessors - Private: strictly for use within HBase itself Classes which are defined as `IA.Private` may be used as parameters or return values for interfaces which are declared `IA.LimitedPrivate`. Treat the `IA.Private` object as opaque; do not try to access its methods or fields directly. * InterfaceStability (link:https://yetus.apache.org/documentation/0.5.0/audience-annotations-apidocs/org/apache/yetus/audience/InterfaceStability.html[javadocs]): describes what types of interface changes are permitted. Possible values include: - Stable: the interface is fixed and is not expected to change - Evolving: the interface may change in future minor verisons - Unstable: the interface may change at any time Please keep in mind the following interactions between the `InterfaceAudience` and `InterfaceStability` annotations within the HBase project: * `IA.Public` classes are inherently stable and adhere to our stability guarantees relating to the type of upgrade (major, minor, or patch). * `IA.LimitedPrivate` classes should always be annotated with one of the given `InterfaceStability` values. If they are not, you should presume they are `IS.Unstable`. * `IA.Private` classes should be considered implicitly unstable, with no guarantee of stability between releases. [[hbase.client.api]] HBase Client API:: HBase Client API consists of all the classes or methods that are marked with InterfaceAudience.Public interface. All main classes in hbase-client and dependent modules have either InterfaceAudience.Public, InterfaceAudience.LimitedPrivate, or InterfaceAudience.Private marker. Not all classes in other modules (hbase-server, etc) have the marker. If a class is not annotated with one of these, it is assumed to be a InterfaceAudience.Private class. [[hbase.limitetprivate.api]] HBase LimitedPrivate API:: LimitedPrivate annotation comes with a set of target consumers for the interfaces. Those consumers are coprocessors, phoenix, replication endpoint implementations or similar. At this point, HBase only guarantees source and binary compatibility for these interfaces between patch versions. [[hbase.private.api]] HBase Private API:: All classes annotated with InterfaceAudience.Private or all classes that do not have the annotation are for HBase internal use only. The interfaces and method signatures can change at any point in time. If you are relying on a particular interface that is marked Private, you should open a jira to propose changing the interface to be Public or LimitedPrivate, or an interface exposed for this purpose. [[hbase.binary.compatibility]] .Binary Compatibility When we say two HBase versions are compatible, we mean that the versions are wire and binary compatible. Compatible HBase versions means that clients can talk to compatible but differently versioned servers. It means too that you can just swap out the jars of one version and replace them with the jars of another, compatible version and all will just work. Unless otherwise specified, HBase point versions are (mostly) binary compatible. You can safely do rolling upgrades between binary compatible versions; i.e. across maintenance releases: e.g. from 1.2.4 to 1.2.6. See link:[Does compatibility between versions also mean binary compatibility?] discussion on the HBase dev mailing list. [[hbase.rolling.upgrade]] === Rolling Upgrades A rolling upgrade is the process by which you update the servers in your cluster a server at a time. You can rolling upgrade across HBase versions if they are binary or wire compatible. See <> for more on what this means. Coarsely, a rolling upgrade is a graceful stop each server, update the software, and then restart. You do this for each server in the cluster. Usually you upgrade the Master first and then the RegionServers. See <> for tools that can help use the rolling upgrade process. For example, in the below, HBase was symlinked to the actual HBase install. On upgrade, before running a rolling restart over the cluster, we changed the symlink to point at the new HBase software version and then ran [source,bash] ---- $ HADOOP_HOME=~/hadoop-2.6.0-CRC-SNAPSHOT ~/hbase/bin/rolling-restart.sh --config ~/conf_hbase ---- The rolling-restart script will first gracefully stop and restart the master, and then each of the RegionServers in turn. Because the symlink was changed, on restart the server will come up using the new HBase version. Check logs for errors as the rolling upgrade proceeds. [[hbase.rolling.restart]] .Rolling Upgrade Between Versions that are Binary/Wire Compatible Unless otherwise specified, HBase minor versions are binary compatible. You can do a <> between HBase point versions. For example, you can go to 1.2.4 from 1.2.6 by doing a rolling upgrade across the cluster replacing the 1.2.4 binary with a 1.2.6 binary. In the minor version-particular sections below, we call out where the versions are wire/protocol compatible and in this case, it is also possible to do a <>. == Rollback Sometimes things don't go as planned when attempting an upgrade. This section explains how to perform a _rollback_ to an earlier HBase release. Note that this should only be needed between Major and some Minor releases. You should always be able to _downgrade_ between HBase Patch releases within the same Minor version. These instructions may require you to take steps before you start the upgrade process, so be sure to read through this section beforehand. === Caveats .Rollback vs Downgrade This section describes how to perform a _rollback_ on an upgrade between HBase minor and major versions. In this document, rollback refers to the process of taking an upgraded cluster and restoring it to the old version _while losing all changes that have occurred since upgrade_. By contrast, a cluster _downgrade_ would restore an upgraded cluster to the old version while maintaining any data written since the upgrade. We currently only offer instructions to rollback HBase clusters. Further, rollback only works when these instructions are followed prior to performing the upgrade. When these instructions talk about rollback vs downgrade of prerequisite cluster services (i.e. HDFS), you should treat leaving the service version the same as a degenerate case of downgrade. .Replication Unless you are doing an all-service rollback, the HBase cluster will lose any configured peers for HBase replication. If your cluster is configured for HBase replication, then prior to following these instructions you should document all replication peers. After performing the rollback you should then add each documented peer back to the cluster. For more information on enabling HBase replication, listing peers, and adding a peer see <>. Note also that data written to the cluster since the upgrade may or may not have already been replicated to any peers. Determining which, if any, peers have seen replication data as well as rolling back the data in those peers is out of the scope of this guide. .Data Locality Unless you are doing an all-service rollback, going through a rollback procedure will likely destroy all locality for Region Servers. You should expect degraded performance until after the cluster has had time to go through compactions to restore data locality. Optionally, you can force a compaction to speed this process up at the cost of generating cluster load. .Configurable Locations The instructions below assume default locations for the HBase data directory and the HBase znode. Both of these locations are configurable and you should verify the value used in your cluster before proceeding. In the event that you have a different value, just replace the default with the one found in your configuration * HBase data directory is configured via the key 'hbase.rootdir' and has a default value of '/hbase'. * HBase znode is configured via the key 'zookeeper.znode.parent' and has a default value of '/hbase'. === All service rollback If you will be performing a rollback of both the HDFS and ZooKeeper services, then HBase's data will be rolled back in the process. .Requirements * Ability to rollback HDFS and ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS rollback and ZooKeeper downgrade If you will be rolling back HDFS but going through a ZooKeeper downgrade, then HBase will be in an inconsistent state. You must ensure the cluster is not started until you complete this process. .Requirements * Ability to rollback HDFS * Ability to downgrade ZooKeeper .Before upgrade No additional steps are needed pre-upgrade. As an extra precautionary measure, you may wish to use distcp to back up the HBase data off of the cluster to be upgraded. To do so, follow the steps in the 'Before upgrade' section of 'Rollback after HDFS downgrade' but copy to another HDFS instance instead of within the same instance. .Performing a rollback . Stop HBase . Perform a rollback for HDFS and a downgrade for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents—use the HBase shell to list tables and scan some known values. === Rollback after HDFS downgrade If you will be performing an HDFS downgrade, then you'll need to follow these instructions regardless of whether ZooKeeper goes through rollback, downgrade, or reinstallation. .Requirements * Ability to downgrade HDFS * Pre-upgrade cluster must be able to run MapReduce jobs * HDFS super user access * Sufficient space in HDFS for at least two copies of the HBase data directory .Before upgrade Before beginning the upgrade process, you must take a complete backup of HBase's backing data. The following instructions cover backing up the data within the current HDFS instance. Alternatively, you can use the distcp command to copy the data to another HDFS cluster. . Stop the HBase cluster . Copy the HBase data directory to a backup location using the https://hadoop.apache.org/docs/current/hadoop-distcp/DistCp.html[distcp command] as the HDFS super user (shown below on a security enabled cluster) + .Using distcp to backup the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hadoop distcp /hbase /hbase-pre-upgrade-backup ---- . Distcp will launch a mapreduce job to handle copying the files in a distributed fashion. Check the output of the distcp command to ensure this job completed successfully. .Performing a rollback . Stop HBase . Perform a downgrade for HDFS and a downgrade/rollback for ZooKeeper (HBase should remain stopped) . Change the installed version of HBase to the previous version . Restore the HBase data directory from prior to the upgrade as the HDFS super user (shown below on a security enabled cluster). If you backed up your data on another HDFS cluster instead of locally, you will need to use the distcp command to copy it back to the current HDFS cluster. + .Restore the HBase data directory [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ kinit -k -t hdfs.keytab hdfs@EXAMPLE.COM [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase /hbase-upgrade-rollback [hpnewton@gateway_node.example.com ~]$ hdfs dfs -mv /hbase-pre-upgrade-backup /hbase ---- . Clean out ZooKeeper information related to HBase. WARNING: This step will permanently destroy all replication peers. Please see the section on HBase Replication under Caveats for more information. + .Clean HBase information out of ZooKeeper [source,bash] ---- [hpnewton@gateway_node.example.com ~]$ zookeeper-client -server zookeeper1.example.com:2181,zookeeper2.example.com:2181,zookeeper3.example.com:2181 Welcome to ZooKeeper! JLine support is disabled rmr /hbase quit Quitting... ---- . Start HBase . Verify HBase contents–use the HBase shell to list tables and scan some known values. == Upgrade Paths [[upgrade2.2]] === Upgrade from 2.0 or 2.1 to 2.2+ HBase 2.2+ uses a new Procedure form assiging/unassigning/moving Regions. It does not process HBase 2.1 and 2.0's Unassign/Assign Procedure types. Upgrade requires that we first drain the Master Procedure Store of old style Procedures before starting the new 2.2 Master. So you need to make sure that before you kill the old version (2.0 or 2.1) Master, there is no region in transition. And once the new version (2.2+) Master is up, you can rolling upgrade RegionServers one by one. And there is a more safer way if you are running 2.1.1+ or 2.0.3+ cluster. It need four steps to upgrade Master. . Shutdown both active and standby Masters (Your cluster will continue to server reads and writes without interruption). . Set the property hbase.procedure.upgrade-to-2-2 to true in hbase-site.xml for the Master, and start only one Master, still using the 2.1.1+ (or 2.0.3+) version. . Wait until the Master quits. Confirm that there is a 'READY TO ROLLING UPGRADE' message in the Master log as the cause of the shutdown. The Procedure Store is now empty. . Start new Masters with the new 2.2+ version. Then you can rolling upgrade RegionServers one by one. See link:https://issues.apache.org/jira/browse/HBASE-21075[HBASE-21075] for more details. [[upgrade2.0]] === Upgrading from 1.x to 2.x In this section we will first call out significant changes compared to the prior stable HBase release and then go over the upgrade process. Be sure to read the former with care so you avoid suprises. ==== Changes of Note! First we'll cover deployment / operational changes that you might hit when upgrading to HBase 2.0+. After that we'll call out changes for downstream applications. Please note that Coprocessors are covered in the operational section. Also note that this section is not meant to convey information about new features that may be of interest to you. For a complete summary of changes, please see the CHANGES.txt file in the source release artifact for the version you are planning to upgrade to. [[upgrade2.0.basic.requirements]] .Update to basic prerequisite minimums in HBase 2.0+ As noted in the section <>, HBase 2.0+ requires a minimum of Java 8 and Hadoop 2.6. The HBase community recommends ensuring you have already completed any needed upgrades in prerequisites prior to upgrading your HBase version. [[upgrade2.0.hbck]] .HBCK must match HBase server version You *must not* use an HBase 1.x version of HBCK against an HBase 2.0+ cluster. HBCK is strongly tied to the HBase server version. Using the HBCK tool from an earlier release against an HBase 2.0+ cluster will destructively alter said cluster in unrecoverable ways. As of HBase 2.0, HBCK (A.K.A _HBCK1_ or _hbck1_) is a read-only tool that can report the status of some non-public system internals. You should not rely on the format nor content of these internals to remain consistent across HBase releases. To read about HBCK's replacement, see <> in <>. //// Link to a ref guide section on HBCK in 2.0 that explains use and calls out the inability of clients and server sides to detect version of each other. //// [[upgrade2.0.removed.configs]] .Configuration settings no longer in HBase 2.0+ The following configuration settings are no longer applicable or available. For details, please see the detailed release notes. * hbase.config.read.zookeeper.config (see <> for migration details) * hbase.zookeeper.useMulti (HBase now always uses ZK's multi functionality) * hbase.rpc.client.threads.max * hbase.rpc.client.nativetransport * hbase.fs.tmp.dir // These next two seem worth a call out section? * hbase.bucketcache.combinedcache.enabled * hbase.bucketcache.ioengine no longer supports the 'heap' value. * hbase.bulkload.staging.dir * hbase.balancer.tablesOnMaster wasn't removed, strictly speaking, but its meaning has fundamentally changed and users should not set it. See the section <> for details. * hbase.master.distributed.log.replay See the section <> for details * hbase.regionserver.disallow.writes.when.recovering See the section <> for details * hbase.regionserver.wal.logreplay.batch.size See the section <> for details * hbase.master.catalog.timeout * hbase.regionserver.catalog.timeout * hbase.metrics.exposeOperationTimes * hbase.metrics.showTableName * hbase.online.schema.update.enable (HBase now always supports this) * hbase.thrift.htablepool.size.max [[upgrade2.0.renamed.configs]] .Configuration properties that were renamed in HBase 2.0+ The following properties have been renamed. Attempts to set the old property will be ignored at run time. .Renamed properties [options=""header""] |============================================================================================================ |Old name |New name |hbase.rpc.server.nativetransport |hbase.netty.nativetransport |hbase.netty.rpc.server.worker.count |hbase.netty.worker.count |hbase.hfile.compactions.discharger.interval |hbase.hfile.compaction.discharger.interval |hbase.hregion.percolumnfamilyflush.size.lower.bound |hbase.hregion.percolumnfamilyflush.size.lower.bound.min |============================================================================================================ [[upgrade2.0.changed.defaults]] .Configuration settings with different defaults in HBase 2.0+ The following configuration settings changed their default value. Where applicable, the value to set to restore the behavior of HBase 1.2 is given. * hbase.security.authorization now defaults to false. set to true to restore same behavior as previous default. * hbase.client.retries.number is now set to 10. Previously it was 35. Downstream users are advised to use client timeouts as described in section <> instead. * hbase.client.serverside.retries.multiplier is now set to 3. Previously it was 10. Downstream users are advised to use client timesout as describe in section <> instead. * hbase.master.fileSplitTimeout is now set to 10 minutes. Previously it was 30 seconds. * hbase.regionserver.logroll.multiplier is now set to 0.5. Previously it was 0.95. This change is tied with the following doubling of block size. Combined, these two configuration changes should make for WALs of about the same size as those in hbase-1.x but there should be less incidence of small blocks because we fail to roll the WAL before we hit the blocksize threshold. See link:https://issues.apache.org/jira/browse/HBASE-19148[HBASE-19148] for discussion. * hbase.regionserver.hlog.blocksize defaults to 2x the HDFS default block size for the WAL dir. Previously it was equal to the HDFS default block size for the WAL dir. * hbase.client.start.log.errors.counter changed to 5. Previously it was 9. * hbase.ipc.server.callqueue.type changed to 'fifo'. In HBase versions 1.0 - 1.2 it was 'deadline'. In prior and later 1.x versions it already defaults to 'fifo'. * hbase.hregion.memstore.chunkpool.maxsize is 1.0 by default. Previously it was 0.0. Effectively, this means previously we would not use a chunk pool when our memstore is onheap and now we will. See the section <> for more infromation about the MSLAB chunk pool. * hbase.master.cleaner.interval is now set to 10 minutes. Previously it was 1 minute. * hbase.master.procedure.threads will now default to 1/4 of the number of available CPUs, but not less than 16 threads. Previously it would be number of threads equal to number of CPUs. * hbase.hstore.blockingStoreFiles is now 16. Previously it was 10. * hbase.http.max.threads is now 16. Previously it was 10. * hbase.client.max.perserver.tasks is now 2. Previously it was 5. * hbase.normalizer.period is now 5 minutes. Previously it was 30 minutes. * hbase.regionserver.region.split.policy is now SteppingSplitPolicy. Previously it was IncreasingToUpperBoundRegionSplitPolicy. * replication.source.ratio is now 0.5. Previously it was 0.1. [[upgrade2.0.regions.on.master]] .""Master hosting regions"" feature broken and unsupported The feature ""Master acts as region server"" and associated follow-on work available in HBase 1.y is non-functional in HBase 2.y and should not be used in a production setting due to deadlock on Master initialization. Downstream users are advised to treat related configuration settings as experimental and the feature as inappropriate for production settings. A brief summary of related changes: * Master no longer carries regions by default * hbase.balancer.tablesOnMaster is a boolean, default false (if it holds an HBase 1.x list of tables, will default to false) * hbase.balancer.tablesOnMaster.systemTablesOnly is boolean to keep user tables off master. default false * those wishing to replicate old list-of-servers config should deploy a stand-alone RegionServer process and then rely on Region Server Groups [[upgrade2.0.distributed.log.replay]] .""Distributed Log Replay"" feature broken and removed The Distributed Log Replay feature was broken and has been removed from HBase 2.y+. As a consequence all related configs, metrics, RPC fields, and logging have also been removed. Note that this feature was found to be unreliable in the run up to HBase 1.0, defaulted to being unused, and was effectively removed in HBase 1.2.0 when we started ignoring the config that turns it on (link:https://issues.apache.org/jira/browse/HBASE-14465[HBASE-14465]). If you are currently using the feature, be sure to perform a clean shutdown, ensure all DLR work is complete, and disable the feature prior to upgrading. [[upgrade2.0.prefix-tree.removed]] ._prefix-tree_ encoding removed The prefix-tree encoding was removed from HBase 2.0.0 (link:https://issues.apache.org/jira/browse/HBASE-19179[HBASE-19179]). It was (late!) deprecated in hbase-1.2.7, hbase-1.4.0, and hbase-1.3.2. This feature was removed because it as not being actively maintained. If interested in reviving this sweet facility which improved random read latencies at the expensive of slowed writes, write the HBase developers list at _dev at hbase dot apache dot org_. The prefix-tree encoding needs to be removed from all tables before upgrading to HBase 2.0+. To do that first you need to change the encoding from PREFIX_TREE to something else that is supported in HBase 2.0. After that you have to major compact the tables that were using PREFIX_TREE encoding before. To check which column families are using incompatible data block encoding you can use <>. [[upgrade2.0.metrics]] .Changed metrics The following metrics have changed names: * Metrics previously published under the name ""AssignmentManger"" [sic] are now published under the name ""AssignmentManager"" The following metrics have changed their meaning: * The metric 'blockCacheEvictionCount' published on a per-region server basis no longer includes blocks removed from the cache due to the invalidation of the hfiles they are from (e.g. via compaction). * The metric 'totalRequestCount' increments once per request; previously it incremented by the number of `Actions` carried in the request; e.g. if a request was a `multi` made of four Gets and two Puts, we'd increment 'totalRequestCount' by six; now we increment by one regardless. Expect to see lower values for this metric in hbase-2.0.0. * The 'readRequestCount' now counts reads that return a non-empty row where in older hbases, we'd increment 'readRequestCount' whether a Result or not. This change will flatten the profile of the read-requests graphs if requests for non-existent rows. A YCSB read-heavy workload can do this dependent on how the database was loaded. The following metrics have been removed: * Metrics related to the Distributed Log Replay feature are no longer present. They were previsouly found in the region server context under the name 'replay'. See the section <> for details. The following metrics have been added: * 'totalRowActionRequestCount' is a count of region row actions summing reads and writes. [[upgrade2.0.logging]] .Changed logging HBase-2.0.0 now uses link:https://www.slf4j.org/[slf4j] as its logging frontend. Prevously, we used link:http://logging.apache.org/log4j/1.2/[log4j (1.2)]. For most the transition should be seamless; slf4j does a good job interpreting _log4j.properties_ logging configuration files such that you should not notice any difference in your log system emissions. That said, your _log4j.properties_ may need freshening. See link:https://issues.apache.org/jira/browse/HBASE-20351[HBASE-20351] for example, where a stale log configuration file manifest as netty configuration being dumped at DEBUG level as preamble on every shell command invocation. [[upgrade2.0.zkconfig]] .ZooKeeper configs no longer read from zoo.cfg HBase no longer optionally reads the 'zoo.cfg' file for ZooKeeper related configuration settings. If you previously relied on the 'hbase.config.read.zookeeper.config' config for this functionality, you should migrate any needed settings to the hbase-site.xml file while adding the prefix 'hbase.zookeeper.property.' to each property name. [[upgrade2.0.permissions]] .Changes in permissions The following permission related changes either altered semantics or defaults: * Permissions granted to a user now merge with existing permissions for that user, rather than over-writing them. (see link:https://issues.apache.org/jira/browse/HBASE-17472[the release note on HBASE-17472] for details) * Region Server Group commands (added in 1.4.0) now require admin privileges. [[upgrade2.0.admin.commands]] .Most Admin APIs don't work against an HBase 2.0+ cluster from pre-HBase 2.0 clients A number of admin commands are known to not work when used from a pre-HBase 2.0 client. This includes an HBase Shell that has the library jars from pre-HBase 2.0. You will need to plan for an outage of use of admin APIs and commands until you can also update to the needed client version. The following client operations do not work against HBase 2.0+ cluster when executed from a pre-HBase 2.0 client: * list_procedures * split * merge_region * list_quotas * enable_table_replication * disable_table_replication * Snapshot related commands .Deprecated in 1.0 admin commands have been removed. The following commands that were deprecated in 1.0 have been removed. Where applicable the replacement command is listed. * The 'hlog' command has been removed. Downstream users should rely on the 'wal' command instead. [[upgrade2.0.memory]] .Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should read the instructions in section <>. Additionally, HBase 2.0 has changed how memstore memory is tracked for flushing decisions. Previously, both the data size and overhead for storage were used to calculate utilization against the flush threashold. Now, only data size is used to make these per-region decisions. Globally the addition of the storage overhead is used to make decisions about forced flushes. [[upgrade2.0.ui.splitmerge.by.row]] .Web UI for splitting and merging operate on row prefixes Previously, the Web UI included functionality on table status pages to merge or split based on an encoded region name. In HBase 2.0, instead this functionality works by taking a row prefix. [[upgrade2.0.replication]] .Special upgrading for Replication users from pre-HBase 1.4 User running versions of HBase prior to the 1.4.0 release that make use of replication should be sure to read the instructions in the section <>. [[upgrade2.0.shell]] .HBase shell changes The HBase shell command relies on a bundled JRuby instance. This bundled JRuby been updated from version 1.6.8 to version 9.1.10.0. The represents a change from Ruby 1.8 to Ruby 2.3.3, which introduces non-compatible language changes for user scripts. The HBase shell command now ignores the '--return-values' flag that was present in early HBase 1.4 releases. Instead the shell always behaves as though that flag were passed. If you wish to avoid having expression results printed in the console you should alter your IRB configuration as noted in the section <>. [[upgrade2.0.coprocessors]] .Coprocessor APIs have changed in HBase 2.0+ All Coprocessor APIs have been refactored to improve supportability around binary API compatibility for future versions of HBase. If you or applications you rely on have custom HBase coprocessors, you should read link:https://issues.apache.org/jira/browse/HBASE-18169[the release notes for HBASE-18169] for details of changes you will need to make prior to upgrading to HBase 2.0+. For example, if you had a BaseRegionObserver in HBase 1.2 then at a minimum you will need to update it to implement both RegionObserver and RegionCoprocessor and add the method [source,java] ---- ... @Override public Optional getRegionObserver() { return Optional.of(this); } ... ---- //// This would be a good place to link to a coprocessor migration guide //// [[upgrade2.0.hfile3.only]] .HBase 2.0+ can no longer write HFile v2 files. HBase has simplified our internal HFile handling. As a result, we can no longer write HFile versions earlier than the default of version 3. Upgrading users should ensure that hfile.format.version is not set to 2 in hbase-site.xml before upgrading. Failing to do so will cause Region Server failure. HBase can still read HFiles written in the older version 2 format. [[upgrade2.0.pb.wal.only]] .HBase 2.0+ can no longer read Sequence File based WAL file. HBase can no longer read the deprecated WAL files written in the Apache Hadoop Sequence File format. The hbase.regionserver.hlog.reader.impl and hbase.regionserver.hlog.reader.impl configuration entries should be set to use the Protobuf based WAL reader / writer classes. This implementation has been the default since HBase 0.96, so legacy WAL files should not be a concern for most downstream users. A clean cluster shutdown should ensure there are no WAL files. If you are unsure of a given WAL file's format you can use the `hbase wal` command to parse files while the HBase cluster is offline. In HBase 2.0+, this command will not be able to read a Sequence File based WAL. For more information on the tool see the section <>. [[upgrade2.0.filters]] .Change in behavior for filters The Filter ReturnCode NEXT_ROW has been redefined as skipping to next row in current family, not to next row in all family. it’s more reasonable, because ReturnCode is a concept in store level, not in region level. [[upgrade2.0.shaded.client.preferred]] .Downstream HBase 2.0+ users should use the shaded client Downstream users are strongly urged to rely on the Maven coordinates org.apache.hbase:hbase-shaded-client for their runtime use. This artifact contains all the needed implementation details for talking to an HBase cluster while minimizing the number of third party dependencies exposed. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.mapreduce.module]] .Downstream HBase 2.0+ users of MapReduce must switch to new artifact Downstream users of HBase's integration for Apache Hadoop MapReduce must switch to relying on the org.apache.hbase:hbase-shaded-mapreduce module for their runtime use. Historically, downstream users relied on either the org.apache.hbase:hbase-server or org.apache.hbase:hbase-shaded-server artifacts for these classes. Both uses are no longer supported and in the vast majority of cases will fail at runtime. Note that this artifact exposes some classes in the org.apache.hadoop package space (e.g. o.a.h.configuration.Configuration) so that we can maintain source compatibility with our public API. Those classes are included so that they can be altered to use the same relocated third party dependencies as the rest of the HBase client code. In the event that you need to *also* use Hadoop in your code, you should ensure all Hadoop related jars precede the HBase client jar in your classpath. [[upgrade2.0.dependencies]] .Significant changes to runtime classpath A number of internal dependencies for HBase were updated or removed from the runtime classpath. Downstream client users who do not follow the guidance in <> will have to examine the set of dependencies Maven pulls in for impact. Downstream users of LimitedPrivate Coprocessor APIs will need to examine the runtime environment for impact. For details on our new handling of third party libraries that have historically been a problem with respect to harmonizing compatible runtime versions, see the reference guide section <>. [[upgrade2.0.public.api]] .Multiple breaking changes to source and binary compatibility for client API The Java client API for HBase has a number of changes that break both source and binary compatibility for details see the Compatibility Check Report for the release you'll be upgrading to. [[upgrade2.0.tracing]] .Tracing implementation changes The backing implementation of HBase's tracing features was updated from Apache HTrace 3 to HTrace 4, which includes several breaking changes. While HTrace 3 and 4 can coexist in the same runtime, they will not integrate with each other, leading to disjoint trace information. The internal changes to HBase during this upgrade were sufficient for compilation, but it has not been confirmed that there are no regressions in tracing functionality. Please consider this feature expiremental for the immediate future. If you previously relied on client side tracing integrated with HBase operations, it is recommended that you upgrade your usage to HTrace 4 as well. [[upgrade2.0.hfile.compatability]] .HFile lose forward compatability HFiles generated by 2.0.0, 2.0.1, 2.1.0 are not forward compatible to 1.4.6-, 1.3.2.1-, 1.2.6.1-, and other inactive releases. Why HFile lose compatability is hbase in new versions (2.0.0, 2.0.1, 2.1.0) use protobuf to serialize/deserialize TimeRangeTracker (TRT) while old versions use DataInput/DataOutput. To solve this, We have to put link:https://jira.apache.org/jira/browse/HBASE-21012[HBASE-21012] to 2.x and put link:https://jira.apache.org/jira/browse/HBASE-21013[HBASE-21013] in 1.x. For more information, please check link:https://jira.apache.org/jira/browse/HBASE-21008[HBASE-21008]. [[upgrade2.0.perf]] .Performance You will likely see a change in the performance profile on upgrade to hbase-2.0.0 given read and write paths have undergone significant change. On release, writes may be slower with reads about the same or much better, dependent on context. Be prepared to spend time re-tuning (See <>). Performance is also an area that is now under active review so look forward to improvement in coming releases (See link:https://issues.apache.org/jira/browse/HBASE-20188[HBASE-20188 TESTING Performance]). [[upgrade2.0.it.kerberos]] .Integration Tests and Kerberos Integration Tests (`IntegrationTests*`) used to rely on the Kerberos credential cache for authentication against secured clusters. This used to lead to tests failing due to authentication failures when the tickets in the credential cache expired. As of hbase-2.0.0 (and hbase-1.3.0+), the integration test clients will make use of the configuration properties `hbase.client.keytab.file` and `hbase.client.kerberos.principal`. They are required. The clients will perform a login from the configured keytab file and automatically refresh the credentials in the background for the process lifetime (See link:https://issues.apache.org/jira/browse/HBASE-16231[HBASE-16231]). //// This would be a good place to link to an appendix on migrating applications //// [[upgrade2.0.coprocessors]] ==== Upgrading Coprocessors to 2.0 Coprocessors have changed substantially in 2.0 ranging from top level design changes in class hierarchies to changed/removed methods, interfaces, etc. (Parent jira: link:https://issues.apache.org/jira/browse/HBASE-18169[HBASE-18169 Coprocessor fix and cleanup before 2.0.0 release]). Some of the reasons for such widespread changes: . Pass Interfaces instead of Implementations; e.g. TableDescriptor instead of HTableDescriptor and Region instead of HRegion (link:https://issues.apache.org/jira/browse/HBASE-18241[HBASE-18241] Change client.Table and client.Admin to not use HTableDescriptor). . Design refactor so implementers need to fill out less boilerplate and so we can do more compile-time checking (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) . Purge Protocol Buffers from Coprocessor API (link:https://issues.apache.org/jira/browse/HBASE-18859[HBASE-18859], link:https://issues.apache.org/jira/browse/HBASE-16769[HBASE-16769], etc) . Cut back on what we expose to Coprocessors removing hooks on internals that were too private to expose (for eg. link:https://issues.apache.org/jira/browse/HBASE-18453[HBASE-18453] CompactionRequest should not be exposed to user directly; link:https://issues.apache.org/jira/browse/HBASE-18298[HBASE-18298] RegionServerServices Interface cleanup for CP expose; etc) To use coprocessors in 2.0, they should be rebuilt against new API otherwise they will fail to load and HBase processes will die. Suggested order of changes to upgrade the coprocessors: . Directly implement observer interfaces instead of extending Base*Observer classes. Change `Foo extends BaseXXXObserver` to `Foo implements XXXObserver`. (link:https://issues.apache.org/jira/browse/HBASE-17312[HBASE-17312]). . Adapt to design change from Inheritence to Composition (link:https://issues.apache.org/jira/browse/HBASE-17732[HBASE-17732]) by following link:https://github.com/apache/hbase/blob/master/dev-support/design-docs/Coprocessor_Design_Improvements-Use_composition_instead_of_inheritance-HBASE-17732.adoc#migrating-existing-cps-to-new-design[this example]. . getTable() has been removed from the CoprocessorEnvrionment, coprocessors should self-manage Table instances. Some examples of writing coprocessors with new API can be found in hbase-example module link:https://github.com/apache/hbase/tree/branch-2.0/hbase-examples/src/main/java/org/apache/hadoop/hbase/coprocessor/example[here] . Lastly, if an api has been changed/removed that breaks you in an irreparable way, and if there's a good justification to add it back, bring it our notice (dev@hbase.apache.org). [[upgrade2.0.rolling.upgrades]] ==== Rolling Upgrade from 1.x to 2.x Rolling upgrades are currently an experimental feature. They have had limited testing. There are likely corner cases as yet uncovered in our limited experience so you should be careful if you go this route. The stop/upgrade/start described in the next section, <>, is the safest route. That said, the below is a prescription for a rolling upgrade of a 1.4 cluster. .Pre-Requirements * Upgrade to the latest 1.4.x release. Pre 1.4 releases may also work but are not tested, so please upgrade to 1.4.3+ before upgrading to 2.x, unless you are an expert and familiar with the region assignment and crash processing. See the section <> on how to upgrade to 1.4.x. * Make sure that the zk-less assignment is enabled, i.e, set `hbase.assignment.usezk` to `false`. This is the most important thing. It allows the 1.x master to assign/unassign regions to/from 2.x region servers. See the release note section of link:https://issues.apache.org/jira/browse/HBASE-11059[HBASE-11059] on how to migrate from zk based assignment to zk less assignment. * We have tested rolling upgrading from 1.4.3 to 2.1.0, but it should also work if you want to upgrade to 2.0.x. .Instructions . Unload a region server and upgrade it to 2.1.0. With link:https://issues.apache.org/jira/browse/HBASE-17931[HBASE-17931] in place, the meta region and regions for other system tables will be moved to this region server immediately. If not, please move them manually to the new region server. This is very important because ** The schema of meta region is hard coded, if meta is on an old region server, then the new region servers can not access it as it does not have some families, for example, table state. ** Client with lower version can communicate with server with higher version, but not vice versa. If the meta region is on an old region server, the new region server will use a client with higher version to communicate with a server with lower version, this may introduce strange problems. . Rolling upgrade all other region servers. . Upgrading masters. It is OK that during the rolling upgrading there are region server crashes. The 1.x master can assign regions to both 1.x and 2.x region servers, and link:https://issues.apache.org/jira/browse/HBASE-19166[HBASE-19166] fixed a problem so that 1.x region server can also read the WALs written by 2.x region server and split them. NOTE: please read the <> section carefully before rolling upgrading. Make sure that you do not use the removed features in 2.0, for example, the prefix-tree encoding, the old hfile format, etc. They could both fail the upgrading and leave the cluster in an intermediate state and hard to recover. NOTE: If you have success running this prescription, please notify the dev list with a note on your experience and/or update the above with any deviations you may have taken so others going this route can benefit from your efforts. [[upgrade2.0.process]] ==== Upgrade process from 1.x to 2.x To upgrade an existing HBase 1.x cluster, you should: * Clean shutdown of existing 1.x cluster * Update coprocessors * Upgrade Master roles first * Upgrade RegionServers * (Eventually) Upgrade Clients [[upgrade1.4]] === Upgrading from pre-1.4 to 1.4+ [[upgrade1.4.memory]] ==== Region Server memory consumption changes. Users upgrading from versions prior to HBase 1.4 should be aware that the estimates of heap usage by the memstore objects (KeyValue, object and array header sizes, etc) have been made more accurate for heap sizes up to 32G (using CompressedOops), resulting in them dropping by 10-50% in practice. This also results in less number of flushes and compactions due to ""fatter"" flushes. YMMV. As a result, the actual heap usage of the memstore before being flushed may increase by up to 100%. If configured memory limits for the region server had been tuned based on observed usage, this change could result in worse GC behavior or even OutOfMemory errors. Set the environment property (not hbase-site.xml) ""hbase.memorylayout.use.unsafe"" to false to disable. [[upgrade1.4.replication]] ==== Replication peer's TableCFs config Before 1.4, the table name can't include namespace for replication peer's TableCFs config. It was fixed by add TableCFs to ReplicationPeerConfig which was stored on Zookeeper. So when upgrade to 1.4, you have to update the original ReplicationPeerConfig data on Zookeeper firstly. There are four steps to upgrade when your cluster have a replication peer with TableCFs config. * Disable the replication peer. * If master has permission to write replication peer znode, then rolling update master directly. If not, use TableCFsUpdater tool to update the replication peer's config. [source,bash] ---- $ bin/hbase org.apache.hadoop.hbase.replication.master.TableCFsUpdater update ---- * Rolling update regionservers. * Enable the replication peer. Notes: * Can't use the old client(before 1.4) to change the replication peer's config. Because the client will write config to Zookeeper directly, the old client will miss TableCFs config. And the old client write TableCFs config to the old tablecfs znode, it will not work for new version regionserver. [[upgrade1.4.rawscan]] ==== Raw scan now ignores TTL Doing a raw scan will now return results that have expired according to TTL settings. [[upgrade1.3]] === Upgrading from pre-1.3 to 1.3+ If running Integration Tests under Kerberos, see <>. [[upgrade1.0]] === Upgrading to 1.x Please consult the documentation published specifically for the version of HBase that you are upgrading to for details on the upgrade process. ",12485,False,2177.611697587687,median "// Copyright (c) 2012 The Chromium 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 ""base/basictypes.h"" #include ""base/memory/scoped_ptr.h"" #include ""base/shared_memory.h"" #include ""base/timer.h"" #include ""content/browser/browser_thread_impl.h"" #include ""content/browser/renderer_host/backing_store.h"" #include ""content/browser/renderer_host/render_widget_host_delegate.h"" #include ""content/browser/renderer_host/gesture_event_filter.h"" #include ""content/browser/renderer_host/test_render_view_host.h"" #include ""content/browser/renderer_host/touch_event_queue.h"" #include ""content/common/view_messages.h"" #include ""content/port/browser/render_widget_host_view_port.h"" #include ""content/public/browser/notification_details.h"" #include ""content/public/browser/notification_observer.h"" #include ""content/public/browser/notification_registrar.h"" #include ""content/public/browser/notification_source.h"" #include ""content/public/browser/notification_types.h"" #include ""content/public/test/mock_render_process_host.h"" #include ""content/public/test/test_browser_context.h"" #include ""testing/gtest/include/gtest/gtest.h"" #include ""ui/base/keycodes/keyboard_codes.h"" #include ""ui/gfx/canvas.h"" #if defined(USE_AURA) #include ""content/browser/renderer_host/render_widget_host_view_aura.h"" #include ""ui/aura/env.h"" #endif #if defined(OS_WIN) || defined(USE_AURA) #include ""content/browser/renderer_host/ui_events_helper.h"" #include ""ui/base/events/event.h"" #endif using base::TimeDelta; using WebKit::WebGestureEvent; using WebKit::WebInputEvent; using WebKit::WebMouseWheelEvent; using WebKit::WebTouchEvent; using WebKit::WebTouchPoint; namespace content { #if defined(OS_WIN) || defined(USE_AURA) bool TouchEventsAreEquivalent(const ui::TouchEvent& first, const ui::TouchEvent& second) { EXPECT_EQ(second.type(), first.type()); if (first.type() != second.type()) return false; EXPECT_EQ(second.location().ToString(), first.location().ToString()); if (first.location() != second.location()) return false; EXPECT_EQ(second.touch_id(), first.touch_id()); if (first.touch_id() != second.touch_id()) return false; EXPECT_EQ(second.time_stamp().InSeconds(), first.time_stamp().InSeconds()); if (second.time_stamp().InSeconds() != first.time_stamp().InSeconds()) return false; return true; } bool EventListIsSubset(const ScopedVector& subset, const ScopedVector& set) { EXPECT_LE(subset.size(), set.size()); if (subset.size() > set.size()) return false; for (size_t i = 0; i < subset.size(); ++i) { const ui::TouchEvent* first = subset[i]; const ui::TouchEvent* second = set[i]; bool equivalent = TouchEventsAreEquivalent(*first, *second); EXPECT_TRUE(equivalent); if (!equivalent) return false; } return true; } #endif // defined(OS_WIN) || defined(USE_AURA) // RenderWidgetHostProcess ----------------------------------------------------- class RenderWidgetHostProcess : public MockRenderProcessHost { public: explicit RenderWidgetHostProcess(BrowserContext* browser_context) : MockRenderProcessHost(browser_context), current_update_buf_(NULL), update_msg_should_reply_(false), update_msg_reply_flags_(0) { } ~RenderWidgetHostProcess() { delete current_update_buf_; } void set_update_msg_should_reply(bool reply) { update_msg_should_reply_ = reply; } void set_update_msg_reply_flags(int flags) { update_msg_reply_flags_ = flags; } // Fills the given update parameters with resonable default values. void InitUpdateRectParams(ViewHostMsg_UpdateRect_Params* params); virtual bool HasConnection() const { return true; } protected: virtual bool WaitForBackingStoreMsg(int render_widget_id, const base::TimeDelta& max_delay, IPC::Message* msg); TransportDIB* current_update_buf_; // Set to true when WaitForBackingStoreMsg should return a successful update // message reply. False implies timeout. bool update_msg_should_reply_; // Indicates the flags that should be sent with a repaint request. This // only has an effect when update_msg_should_reply_ is true. int update_msg_reply_flags_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostProcess); }; void RenderWidgetHostProcess::InitUpdateRectParams( ViewHostMsg_UpdateRect_Params* params) { // Create the shared backing store. const int w = 100, h = 100; const size_t pixel_size = w * h * 4; if (!current_update_buf_) current_update_buf_ = TransportDIB::Create(pixel_size, 0); params->bitmap = current_update_buf_->id(); params->bitmap_rect = gfx::Rect(0, 0, w, h); params->dx = 0; params->dy = 0; params->copy_rects.push_back(params->bitmap_rect); params->view_size = gfx::Size(w, h); params->flags = update_msg_reply_flags_; params->needs_ack = true; params->scale_factor = 1; } bool RenderWidgetHostProcess::WaitForBackingStoreMsg( int render_widget_id, const base::TimeDelta& max_delay, IPC::Message* msg) { if (!update_msg_should_reply_) return false; // Construct a fake update reply. ViewHostMsg_UpdateRect_Params params; InitUpdateRectParams(¶ms); ViewHostMsg_UpdateRect message(render_widget_id, params); *msg = message; return true; } // TestView -------------------------------------------------------------------- // This test view allows us to specify the size, and keep track of acked // touch-events. class TestView : public TestRenderWidgetHostView { public: explicit TestView(RenderWidgetHostImpl* rwh) : TestRenderWidgetHostView(rwh), acked_event_count_(0) { } // Sets the bounds returned by GetViewBounds. void set_bounds(const gfx::Rect& bounds) { bounds_ = bounds; } const WebTouchEvent& acked_event() const { return acked_event_; } int acked_event_count() const { return acked_event_count_; } void ClearAckedEvent() { acked_event_.type = WebKit::WebInputEvent::Undefined; acked_event_count_ = 0; } // RenderWidgetHostView override. virtual gfx::Rect GetViewBounds() const OVERRIDE { return bounds_; } virtual void ProcessAckedTouchEvent(const WebTouchEvent& touch, bool processed) OVERRIDE { acked_event_ = touch; ++acked_event_count_; } protected: WebTouchEvent acked_event_; int acked_event_count_; gfx::Rect bounds_; DISALLOW_COPY_AND_ASSIGN(TestView); }; // MockRenderWidgetHostDelegate -------------------------------------------- class MockRenderWidgetHostDelegate : public RenderWidgetHostDelegate { public: MockRenderWidgetHostDelegate() : prehandle_keyboard_event_(false), prehandle_keyboard_event_called_(false), prehandle_keyboard_event_type_(WebInputEvent::Undefined), unhandled_keyboard_event_called_(false), unhandled_keyboard_event_type_(WebInputEvent::Undefined) { } virtual ~MockRenderWidgetHostDelegate() {} // Tests that make sure we ignore keyboard event acknowledgments to events we // didn't send work by making sure we didn't call UnhandledKeyboardEvent(). bool unhandled_keyboard_event_called() const { return unhandled_keyboard_event_called_; } WebInputEvent::Type unhandled_keyboard_event_type() const { return unhandled_keyboard_event_type_; } bool prehandle_keyboard_event_called() const { return prehandle_keyboard_event_called_; } WebInputEvent::Type prehandle_keyboard_event_type() const { return prehandle_keyboard_event_type_; } void set_prehandle_keyboard_event(bool handle) { prehandle_keyboard_event_ = handle; } protected: virtual bool PreHandleKeyboardEvent(const NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) OVERRIDE { prehandle_keyboard_event_type_ = event.type; prehandle_keyboard_event_called_ = true; return prehandle_keyboard_event_; } virtual void HandleKeyboardEvent( const NativeWebKeyboardEvent& event) OVERRIDE { unhandled_keyboard_event_type_ = event.type; unhandled_keyboard_event_called_ = true; } private: bool prehandle_keyboard_event_; bool prehandle_keyboard_event_called_; WebInputEvent::Type prehandle_keyboard_event_type_; bool unhandled_keyboard_event_called_; WebInputEvent::Type unhandled_keyboard_event_type_; }; // MockRenderWidgetHost ---------------------------------------------------- class MockRenderWidgetHost : public RenderWidgetHostImpl { public: MockRenderWidgetHost( RenderWidgetHostDelegate* delegate, RenderProcessHost* process, int routing_id) : RenderWidgetHostImpl(delegate, process, routing_id), unresponsive_timer_fired_(false) { } // Allow poking at a few private members. using RenderWidgetHostImpl::OnMsgPaintAtSizeAck; using RenderWidgetHostImpl::OnMsgUpdateRect; using RenderWidgetHostImpl::RendererExited; using RenderWidgetHostImpl::in_flight_size_; using RenderWidgetHostImpl::is_hidden_; using RenderWidgetHostImpl::resize_ack_pending_; using RenderWidgetHostImpl::gesture_event_filter_; using RenderWidgetHostImpl::touch_event_queue_; bool unresponsive_timer_fired() const { return unresponsive_timer_fired_; } void set_hung_renderer_delay_ms(int delay_ms) { hung_renderer_delay_ms_ = delay_ms; } WebGestureEvent GestureEventLastQueueEvent() { return gesture_event_filter_->coalesced_gesture_events_.back(); } unsigned GestureEventLastQueueEventSize() { return gesture_event_filter_->coalesced_gesture_events_.size(); } unsigned GestureEventDebouncingQueueSize() { return gesture_event_filter_->debouncing_deferral_queue_.size(); } WebGestureEvent GestureEventQueueEventAt(int i) { return gesture_event_filter_->coalesced_gesture_events_.at(i); } bool ScrollingInProgress() { return gesture_event_filter_->scrolling_in_progress_; } bool FlingInProgress() { return gesture_event_filter_->fling_in_progress_; } void set_maximum_tap_gap_time_ms(int delay_ms) { gesture_event_filter_->maximum_tap_gap_time_ms_ = delay_ms; } void set_debounce_interval_time_ms(int delay_ms) { gesture_event_filter_->debounce_interval_time_ms_ = delay_ms; } size_t TouchEventQueueSize() { return touch_event_queue_->GetQueueSize(); } const WebTouchEvent& latest_event() const { return touch_event_queue_->GetLatestEvent(); } protected: virtual void NotifyRendererUnresponsive() OVERRIDE { unresponsive_timer_fired_ = true; } private: bool unresponsive_timer_fired_; }; // MockPaintingObserver -------------------------------------------------------- class MockPaintingObserver : public NotificationObserver { public: void WidgetDidReceivePaintAtSizeAck(RenderWidgetHostImpl* host, int tag, const gfx::Size& size) { host_ = reinterpret_cast(host); tag_ = tag; size_ = size; } void Observe(int type, const NotificationSource& source, const NotificationDetails& details) { if (type == NOTIFICATION_RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK) { std::pair* size_ack_details = Details >(details).ptr(); WidgetDidReceivePaintAtSizeAck( RenderWidgetHostImpl::From(Source(source).ptr()), size_ack_details->first, size_ack_details->second); } } MockRenderWidgetHost* host() const { return host_; } int tag() const { return tag_; } gfx::Size size() const { return size_; } private: MockRenderWidgetHost* host_; int tag_; gfx::Size size_; }; // RenderWidgetHostTest -------------------------------------------------------- class RenderWidgetHostTest : public testing::Test { public: RenderWidgetHostTest() : process_(NULL) { } ~RenderWidgetHostTest() { } protected: // testing::Test void SetUp() { browser_context_.reset(new TestBrowserContext()); delegate_.reset(new MockRenderWidgetHostDelegate()); process_ = new RenderWidgetHostProcess(browser_context_.get()); host_.reset( new MockRenderWidgetHost(delegate_.get(), process_, MSG_ROUTING_NONE)); view_.reset(new TestView(host_.get())); host_->SetView(view_.get()); host_->Init(); } void TearDown() { view_.reset(); host_.reset(); delegate_.reset(); process_ = NULL; browser_context_.reset(); #if defined(USE_AURA) aura::Env::DeleteInstance(); #endif // Process all pending tasks to avoid leaks. MessageLoop::current()->RunAllPending(); } void SendInputEventACK(WebInputEvent::Type type, bool processed) { scoped_ptr response( new ViewHostMsg_HandleInputEvent_ACK(0, type, processed)); host_->OnMessageReceived(*response); } void SimulateKeyboardEvent(WebInputEvent::Type type) { NativeWebKeyboardEvent key_event; key_event.type = type; key_event.windowsKeyCode = ui::VKEY_L; // non-null made up value. host_->ForwardKeyboardEvent(key_event); } void SimulateWheelEvent(float dX, float dY, int modifiers) { WebMouseWheelEvent wheel_event; wheel_event.type = WebInputEvent::MouseWheel; wheel_event.deltaX = dX; wheel_event.deltaY = dY; wheel_event.modifiers = modifiers; host_->ForwardWheelEvent(wheel_event); } // Inject simple synthetic WebGestureEvent instances. void SimulateGestureEvent(WebInputEvent::Type type) { WebGestureEvent gesture_event; gesture_event.type = type; host_->ForwardGestureEvent(gesture_event); } void SimulateGestureScrollUpdateEvent(float dX, float dY, int modifiers) { WebGestureEvent gesture_event; gesture_event.type = WebInputEvent::GestureScrollUpdate; gesture_event.data.scrollUpdate.deltaX = dX; gesture_event.data.scrollUpdate.deltaY = dY; gesture_event.modifiers = modifiers; host_->ForwardGestureEvent(gesture_event); } // Inject simple synthetic WebGestureEvent instances. void SimulateGestureFlingStartEvent(float velocityX, float velocityY) { WebGestureEvent gesture_event; gesture_event.type = WebInputEvent::GestureFlingStart; gesture_event.data.flingStart.velocityX = velocityX; gesture_event.data.flingStart.velocityY = velocityY; host_->ForwardGestureEvent(gesture_event); } // Set the timestamp for the touch-event. void SetTouchTimestamp(base::TimeDelta timestamp) { touch_event_.timeStampSeconds = timestamp.InSecondsF(); } // Sends a touch event (irrespective of whether the page has a touch-event // handler or not). void SendTouchEvent() { host_->ForwardTouchEvent(touch_event_); // Mark all the points as stationary. And remove the points that have been // released. int point = 0; for (unsigned int i = 0; i < touch_event_.touchesLength; ++i) { if (touch_event_.touches[i].state == WebKit::WebTouchPoint::StateReleased) continue; touch_event_.touches[point] = touch_event_.touches[i]; touch_event_.touches[point].state = WebKit::WebTouchPoint::StateStationary; ++point; } touch_event_.touchesLength = point; touch_event_.type = WebInputEvent::Undefined; } int PressTouchPoint(int x, int y) { if (touch_event_.touchesLength == touch_event_.touchesLengthCap) return -1; WebKit::WebTouchPoint& point = touch_event_.touches[touch_event_.touchesLength]; point.id = touch_event_.touchesLength; point.position.x = point.screenPosition.x = x; point.position.y = point.screenPosition.y = y; point.state = WebKit::WebTouchPoint::StatePressed; point.radiusX = point.radiusY = 1.f; ++touch_event_.touchesLength; touch_event_.type = WebInputEvent::TouchStart; return point.id; } void MoveTouchPoint(int index, int x, int y) { CHECK(index >= 0 && index < touch_event_.touchesLengthCap); WebKit::WebTouchPoint& point = touch_event_.touches[index]; point.position.x = point.screenPosition.x = x; point.position.y = point.screenPosition.y = y; touch_event_.touches[index].state = WebKit::WebTouchPoint::StateMoved; touch_event_.type = WebInputEvent::TouchMove; } void ReleaseTouchPoint(int index) { CHECK(index >= 0 && index < touch_event_.touchesLengthCap); touch_event_.touches[index].state = WebKit::WebTouchPoint::StateReleased; touch_event_.type = WebInputEvent::TouchEnd; } MessageLoopForUI message_loop_; scoped_ptr browser_context_; RenderWidgetHostProcess* process_; // Deleted automatically by the widget. scoped_ptr delegate_; scoped_ptr host_; scoped_ptr view_; private: WebTouchEvent touch_event_; DISALLOW_COPY_AND_ASSIGN(RenderWidgetHostTest); }; // ----------------------------------------------------------------------------- TEST_F(RenderWidgetHostTest, Resize) { // The initial bounds is the empty rect, so setting it to the same thing // should do nothing. view_->set_bounds(gfx::Rect()); host_->WasResized(); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(), host_->in_flight_size_); EXPECT_FALSE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Setting the bounds to a ""real"" rect should send out the notification. gfx::Rect original_size(0, 0, 100, 100); process_->sink().ClearMessages(); view_->set_bounds(original_size); host_->WasResized(); EXPECT_TRUE(host_->resize_ack_pending_); EXPECT_EQ(original_size.size(), host_->in_flight_size_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Send out a update that's not a resize ack. This should not clean the // resize ack pending flag. ViewHostMsg_UpdateRect_Params params; process_->InitUpdateRectParams(¶ms); host_->OnMsgUpdateRect(params); EXPECT_TRUE(host_->resize_ack_pending_); EXPECT_EQ(original_size.size(), host_->in_flight_size_); // Sending out a new notification should NOT send out a new IPC message since // a resize ACK is pending. gfx::Rect second_size(0, 0, 90, 90); process_->sink().ClearMessages(); view_->set_bounds(second_size); host_->WasResized(); EXPECT_TRUE(host_->resize_ack_pending_); EXPECT_EQ(original_size.size(), host_->in_flight_size_); EXPECT_FALSE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Send a update that's a resize ack, but for the original_size we sent. Since // this isn't the second_size, the message handler should immediately send // a new resize message for the new size to the renderer. process_->sink().ClearMessages(); params.flags = ViewHostMsg_UpdateRect_Flags::IS_RESIZE_ACK; params.view_size = original_size.size(); host_->OnMsgUpdateRect(params); EXPECT_TRUE(host_->resize_ack_pending_); EXPECT_EQ(second_size.size(), host_->in_flight_size_); ASSERT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Send the resize ack for the latest size. process_->sink().ClearMessages(); params.view_size = second_size.size(); host_->OnMsgUpdateRect(params); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(), host_->in_flight_size_); ASSERT_FALSE(process_->sink().GetFirstMessageMatching(ViewMsg_Resize::ID)); // Now clearing the bounds should send out a notification but we shouldn't // expect a resize ack (since the renderer won't ack empty sizes). The message // should contain the new size (0x0) and not the previous one that we skipped process_->sink().ClearMessages(); view_->set_bounds(gfx::Rect()); host_->WasResized(); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(), host_->in_flight_size_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Send a rect that has no area but has either width or height set. process_->sink().ClearMessages(); view_->set_bounds(gfx::Rect(0, 0, 0, 30)); host_->WasResized(); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(0, 30), host_->in_flight_size_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Set the same size again. It should not be sent again. process_->sink().ClearMessages(); host_->WasResized(); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(0, 30), host_->in_flight_size_); EXPECT_FALSE(process_->sink().GetFirstMessageMatching(ViewMsg_Resize::ID)); // A different size should be sent again, however. view_->set_bounds(gfx::Rect(0, 0, 0, 31)); host_->WasResized(); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(0, 31), host_->in_flight_size_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); } // Test for crbug.com/25097. If a renderer crashes between a resize and the // corresponding update message, we must be sure to clear the resize ack logic. TEST_F(RenderWidgetHostTest, ResizeThenCrash) { // Setting the bounds to a ""real"" rect should send out the notification. gfx::Rect original_size(0, 0, 100, 100); view_->set_bounds(original_size); host_->WasResized(); EXPECT_TRUE(host_->resize_ack_pending_); EXPECT_EQ(original_size.size(), host_->in_flight_size_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Resize::ID)); // Simulate a renderer crash before the update message. Ensure all the // resize ack logic is cleared. Must clear the view first so it doesn't get // deleted. host_->SetView(NULL); host_->RendererExited(base::TERMINATION_STATUS_PROCESS_CRASHED, -1); EXPECT_FALSE(host_->resize_ack_pending_); EXPECT_EQ(gfx::Size(), host_->in_flight_size_); // Reset the view so we can exit the test cleanly. host_->SetView(view_.get()); } // Tests setting custom background TEST_F(RenderWidgetHostTest, Background) { #if !defined(OS_MACOSX) scoped_ptr view( RenderWidgetHostView::CreateViewForWidget(host_.get())); #if defined(OS_LINUX) || defined(USE_AURA) // TODO(derat): Call this on all platforms: http://crbug.com/102450. // InitAsChild doesn't seem to work if NULL parent is passed on Windows, // which leads to DCHECK failure in RenderWidgetHostView::Destroy. // When you enable this for OS_WIN, enable |view.release()->Destroy()| // below. view->InitAsChild(NULL); #endif host_->SetView(view.get()); // Create a checkerboard background to test with. gfx::Canvas canvas(gfx::Size(4, 4), ui::SCALE_FACTOR_100P, true); canvas.FillRect(gfx::Rect(0, 0, 2, 2), SK_ColorBLACK); canvas.FillRect(gfx::Rect(2, 0, 2, 2), SK_ColorWHITE); canvas.FillRect(gfx::Rect(0, 2, 2, 2), SK_ColorWHITE); canvas.FillRect(gfx::Rect(2, 2, 2, 2), SK_ColorBLACK); const SkBitmap& background = canvas.sk_canvas()->getDevice()->accessBitmap(false); // Set the background and make sure we get back a copy. view->SetBackground(background); EXPECT_EQ(4, view->GetBackground().width()); EXPECT_EQ(4, view->GetBackground().height()); EXPECT_EQ(background.getSize(), view->GetBackground().getSize()); background.lockPixels(); view->GetBackground().lockPixels(); EXPECT_TRUE(0 == memcmp(background.getPixels(), view->GetBackground().getPixels(), background.getSize())); view->GetBackground().unlockPixels(); background.unlockPixels(); const IPC::Message* set_background = process_->sink().GetUniqueMessageMatching(ViewMsg_SetBackground::ID); ASSERT_TRUE(set_background); Tuple1 sent_background; ViewMsg_SetBackground::Read(set_background, &sent_background); EXPECT_EQ(background.getSize(), sent_background.a.getSize()); background.lockPixels(); sent_background.a.lockPixels(); EXPECT_TRUE(0 == memcmp(background.getPixels(), sent_background.a.getPixels(), background.getSize())); sent_background.a.unlockPixels(); background.unlockPixels(); #if defined(OS_LINUX) || defined(USE_AURA) // See the comment above |InitAsChild(NULL)|. host_->SetView(NULL); static_cast(view.release())->Destroy(); #endif #else // TODO(port): Mac does not have gfx::Canvas. Maybe we can just change this // test to use SkCanvas directly? #endif // TODO(aa): It would be nice to factor out the painting logic so that we // could test that, but it appears that would mean painting everything twice // since windows HDC structures are opaque. } // Tests getting the backing store with the renderer not setting repaint ack // flags. TEST_F(RenderWidgetHostTest, GetBackingStore_NoRepaintAck) { // First set the view size to match what the renderer is rendering. ViewHostMsg_UpdateRect_Params params; process_->InitUpdateRectParams(¶ms); view_->set_bounds(gfx::Rect(params.view_size)); // We don't currently have a backing store, and if the renderer doesn't send // one in time, we should get nothing. process_->set_update_msg_should_reply(false); BackingStore* backing = host_->GetBackingStore(true); EXPECT_FALSE(backing); // The widget host should have sent a request for a repaint, and there should // be no paint ACK. EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Repaint::ID)); EXPECT_FALSE(process_->sink().GetUniqueMessageMatching( ViewMsg_UpdateRect_ACK::ID)); // Allowing the renderer to reply in time should give is a backing store. process_->sink().ClearMessages(); process_->set_update_msg_should_reply(true); process_->set_update_msg_reply_flags(0); backing = host_->GetBackingStore(true); EXPECT_TRUE(backing); // The widget host should NOT have sent a request for a repaint, since there // was an ACK already pending. EXPECT_FALSE(process_->sink().GetUniqueMessageMatching(ViewMsg_Repaint::ID)); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_UpdateRect_ACK::ID)); } // Tests getting the backing store with the renderer sending a repaint ack. TEST_F(RenderWidgetHostTest, GetBackingStore_RepaintAck) { // First set the view size to match what the renderer is rendering. ViewHostMsg_UpdateRect_Params params; process_->InitUpdateRectParams(¶ms); view_->set_bounds(gfx::Rect(params.view_size)); // Doing a request request with the update message allowed should work and // the repaint ack should work. process_->set_update_msg_should_reply(true); process_->set_update_msg_reply_flags( ViewHostMsg_UpdateRect_Flags::IS_REPAINT_ACK); BackingStore* backing = host_->GetBackingStore(true); EXPECT_TRUE(backing); // We still should not have sent out a repaint request since the last flags // didn't have the repaint ack set, and the pending flag will still be set. EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_Repaint::ID)); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_UpdateRect_ACK::ID)); // Asking again for the backing store should just re-use the existing one // and not send any messagse. process_->sink().ClearMessages(); backing = host_->GetBackingStore(true); EXPECT_TRUE(backing); EXPECT_FALSE(process_->sink().GetUniqueMessageMatching(ViewMsg_Repaint::ID)); EXPECT_FALSE(process_->sink().GetUniqueMessageMatching( ViewMsg_UpdateRect_ACK::ID)); } // Test that we don't paint when we're hidden, but we still send the ACK. Most // of the rest of the painting is tested in the GetBackingStore* ones. TEST_F(RenderWidgetHostTest, HiddenPaint) { BrowserThreadImpl ui_thread(BrowserThread::UI, MessageLoop::current()); // Hide the widget, it should have sent out a message to the renderer. EXPECT_FALSE(host_->is_hidden_); host_->WasHidden(); EXPECT_TRUE(host_->is_hidden_); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching(ViewMsg_WasHidden::ID)); // Send it an update as from the renderer. process_->sink().ClearMessages(); ViewHostMsg_UpdateRect_Params params; process_->InitUpdateRectParams(¶ms); host_->OnMsgUpdateRect(params); // It should have sent out the ACK. EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_UpdateRect_ACK::ID)); // Now unhide. process_->sink().ClearMessages(); host_->WasShown(); EXPECT_FALSE(host_->is_hidden_); // It should have sent out a restored message with a request to paint. const IPC::Message* restored = process_->sink().GetUniqueMessageMatching( ViewMsg_WasShown::ID); ASSERT_TRUE(restored); Tuple1 needs_repaint; ViewMsg_WasShown::Read(restored, &needs_repaint); EXPECT_TRUE(needs_repaint.a); } TEST_F(RenderWidgetHostTest, PaintAtSize) { const int kPaintAtSizeTag = 42; host_->PaintAtSize(TransportDIB::GetFakeHandleForTest(), kPaintAtSizeTag, gfx::Size(40, 60), gfx::Size(20, 30)); EXPECT_TRUE( process_->sink().GetUniqueMessageMatching(ViewMsg_PaintAtSize::ID)); NotificationRegistrar registrar; MockPaintingObserver observer; registrar.Add( &observer, NOTIFICATION_RENDER_WIDGET_HOST_DID_RECEIVE_PAINT_AT_SIZE_ACK, Source(host_.get())); host_->OnMsgPaintAtSizeAck(kPaintAtSizeTag, gfx::Size(20, 30)); EXPECT_EQ(host_.get(), observer.host()); EXPECT_EQ(kPaintAtSizeTag, observer.tag()); EXPECT_EQ(20, observer.size().width()); EXPECT_EQ(30, observer.size().height()); } // Fails on Linux Aura, see http://crbug.com/100344 #if defined(USE_AURA) && !defined(OS_WIN) #define MAYBE_HandleKeyEventsWeSent FAILS_HandleKeyEventsWeSent #else #define MAYBE_HandleKeyEventsWeSent HandleKeyEventsWeSent #endif TEST_F(RenderWidgetHostTest, MAYBE_HandleKeyEventsWeSent) { // Simulate a keyboard event. SimulateKeyboardEvent(WebInputEvent::RawKeyDown); // Make sure we sent the input event to the renderer. EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Send the simulated response from the renderer back. SendInputEventACK(WebInputEvent::RawKeyDown, false); EXPECT_TRUE(delegate_->unhandled_keyboard_event_called()); EXPECT_EQ(WebInputEvent::RawKeyDown, delegate_->unhandled_keyboard_event_type()); } TEST_F(RenderWidgetHostTest, IgnoreKeyEventsWeDidntSend) { // Send a simulated, unrequested key response. We should ignore this. SendInputEventACK(WebInputEvent::RawKeyDown, false); EXPECT_FALSE(delegate_->unhandled_keyboard_event_called()); } TEST_F(RenderWidgetHostTest, IgnoreKeyEventsHandledByRenderer) { // Simulate a keyboard event. SimulateKeyboardEvent(WebInputEvent::RawKeyDown); // Make sure we sent the input event to the renderer. EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Send the simulated response from the renderer back. SendInputEventACK(WebInputEvent::RawKeyDown, true); EXPECT_FALSE(delegate_->unhandled_keyboard_event_called()); } TEST_F(RenderWidgetHostTest, PreHandleRawKeyDownEvent) { // Simluate the situation that the browser handled the key down event during // pre-handle phrase. delegate_->set_prehandle_keyboard_event(true); process_->sink().ClearMessages(); // Simulate a keyboard event. SimulateKeyboardEvent(WebInputEvent::RawKeyDown); EXPECT_TRUE(delegate_->prehandle_keyboard_event_called()); EXPECT_EQ(WebInputEvent::RawKeyDown, delegate_->prehandle_keyboard_event_type()); // Make sure the RawKeyDown event is not sent to the renderer. EXPECT_EQ(0U, process_->sink().message_count()); // The browser won't pre-handle a Char event. delegate_->set_prehandle_keyboard_event(false); // Forward the Char event. SimulateKeyboardEvent(WebInputEvent::Char); // Make sure the Char event is suppressed. EXPECT_EQ(0U, process_->sink().message_count()); // Forward the KeyUp event. SimulateKeyboardEvent(WebInputEvent::KeyUp); // Make sure only KeyUp was sent to the renderer. EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(ViewMsg_HandleInputEvent::ID, process_->sink().GetMessageAt(0)->type()); process_->sink().ClearMessages(); // Send the simulated response from the renderer back. SendInputEventACK(WebInputEvent::KeyUp, false); EXPECT_TRUE(delegate_->unhandled_keyboard_event_called()); EXPECT_EQ(WebInputEvent::KeyUp, delegate_->unhandled_keyboard_event_type()); } TEST_F(RenderWidgetHostTest, CoalescesWheelEvents) { process_->sink().ClearMessages(); // Simulate wheel events. SimulateWheelEvent(0, -5, 0); // sent directly SimulateWheelEvent(0, -10, 0); // enqueued SimulateWheelEvent(8, -6, 0); // coalesced into previous event SimulateWheelEvent(9, -7, 1); // enqueued, different modifiers // Check that only the first event was sent. EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Check that the ACK sends the second message. SendInputEventACK(WebInputEvent::MouseWheel, true); // The coalesced events can queue up a delayed ack // so that additional input events can be processed before // we turn off coalescing. MessageLoop::current()->RunAllPending(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // One more time. SendInputEventACK(WebInputEvent::MouseWheel, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // After the final ack, the queue should be empty. SendInputEventACK(WebInputEvent::MouseWheel, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(0U, process_->sink().message_count()); } TEST_F(RenderWidgetHostTest, CoalescesGesturesEvents) { // Turn off debounce handling for test isolation. host_->set_debounce_interval_time_ms(0); process_->sink().ClearMessages(); // Only GestureScrollUpdate events can be coalesced. // Simulate gesture events. // Sent. SimulateGestureEvent(WebInputEvent::GestureScrollBegin); // Enqueued. SimulateGestureScrollUpdateEvent(8, -5, 0); // Make sure that the queue contains what we think it should. WebGestureEvent merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type); // Coalesced. SimulateGestureScrollUpdateEvent(8, -6, 0); // Check that coalescing updated the correct values. merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type); EXPECT_EQ(0, merged_event.modifiers); EXPECT_EQ(16, merged_event.data.scrollUpdate.deltaX); EXPECT_EQ(-11, merged_event.data.scrollUpdate.deltaY); // Enqueued. SimulateGestureScrollUpdateEvent(8, -7, 1); // Check that we didn't wrongly coalesce. merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureScrollUpdate, merged_event.type); EXPECT_EQ(1, merged_event.modifiers); // Different. SimulateGestureEvent(WebInputEvent::GestureScrollEnd); // Check that only the first event was sent. EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Check that the ACK sends the second message. SendInputEventACK(WebInputEvent::GestureScrollBegin, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Ack for queued coalesced event. SendInputEventACK(WebInputEvent::GestureScrollUpdate, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // Ack for queued uncoalesced event. SendInputEventACK(WebInputEvent::GestureScrollUpdate, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_TRUE(process_->sink().GetUniqueMessageMatching( ViewMsg_HandleInputEvent::ID)); process_->sink().ClearMessages(); // After the final ack, the queue should be empty. SendInputEventACK(WebInputEvent::GestureScrollEnd, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(0U, process_->sink().message_count()); } TEST_F(RenderWidgetHostTest, GestureFlingCancelsFiltered) { // Turn off debounce handling for test isolation. host_->set_debounce_interval_time_ms(0); process_->sink().ClearMessages(); // GFC without previous GFS is dropped. SimulateGestureEvent(WebInputEvent::GestureFlingCancel); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); // GFC after previous GFS is dispatched and acked. process_->sink().ClearMessages(); SimulateGestureFlingStartEvent(0, -10); EXPECT_TRUE(host_->FlingInProgress()); SendInputEventACK(WebInputEvent::GestureFlingStart, true); MessageLoop::current()->RunAllPending(); SimulateGestureEvent(WebInputEvent::GestureFlingCancel); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(2U, process_->sink().message_count()); SendInputEventACK(WebInputEvent::GestureFlingCancel, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); // GFC before previous GFS is acked. process_->sink().ClearMessages(); SimulateGestureFlingStartEvent(0, -10); EXPECT_TRUE(host_->FlingInProgress()); SimulateGestureEvent(WebInputEvent::GestureFlingCancel); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); // Advance state realistically. SendInputEventACK(WebInputEvent::GestureFlingStart, true); MessageLoop::current()->RunAllPending(); SendInputEventACK(WebInputEvent::GestureFlingCancel, true); MessageLoop::current()->RunAllPending(); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); // GFS is added to the queue if another event is pending process_->sink().ClearMessages(); SimulateGestureScrollUpdateEvent(8, -7, 0); SimulateGestureFlingStartEvent(0, -10); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(1U, process_->sink().message_count()); WebGestureEvent merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureFlingStart, merged_event.type); EXPECT_TRUE(host_->FlingInProgress()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); // GFS in queue means that a GFC is added to the queue SimulateGestureEvent(WebInputEvent::GestureFlingCancel); merged_event =host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(3U, host_->GestureEventLastQueueEventSize()); // Adding a second GFC is dropped. SimulateGestureEvent(WebInputEvent::GestureFlingCancel); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(3U, host_->GestureEventLastQueueEventSize()); // Adding another GFS will add it to the queue. SimulateGestureFlingStartEvent(0, -10); merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureFlingStart, merged_event.type); EXPECT_TRUE(host_->FlingInProgress()); EXPECT_EQ(4U, host_->GestureEventLastQueueEventSize()); // GFS in queue means that a GFC is added to the queue SimulateGestureEvent(WebInputEvent::GestureFlingCancel); merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(5U, host_->GestureEventLastQueueEventSize()); // Adding another GFC with a GFC already there is dropped. SimulateGestureEvent(WebInputEvent::GestureFlingCancel); merged_event = host_->GestureEventLastQueueEvent(); EXPECT_EQ(WebInputEvent::GestureFlingCancel, merged_event.type); EXPECT_FALSE(host_->FlingInProgress()); EXPECT_EQ(5U, host_->GestureEventLastQueueEventSize()); } // Test that GestureTapDown events are deferred. TEST_F(RenderWidgetHostTest, DeferredGestureTapDown) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureTapDown, host_->GestureEventLastQueueEvent().type); } // Test that GestureTapDown events are sent immediately on GestureTap. TEST_F(RenderWidgetHostTest, DeferredGestureTapDownSentOnTap) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); SimulateGestureEvent(WebInputEvent::GestureTap); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureTap, host_->GestureEventLastQueueEvent().type); MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); // If the deferral timer incorrectly fired, it sent an extra message. EXPECT_EQ(1U, process_->sink().message_count()); } // Test that only a single GestureTapDown event is sent when tap occurs after // the timeout. TEST_F(RenderWidgetHostTest, DeferredGestureTapDownOnlyOnce) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); // Wait long enough for the timeout and verify it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureTapDown, host_->GestureEventLastQueueEvent().type); // Now send the tap gesture and verify we didn't get an extra TapDown. SimulateGestureEvent(WebInputEvent::GestureTap); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureTap, host_->GestureEventLastQueueEvent().type); } // Test that scroll events during the deferral interval drop the GestureTapDown. TEST_F(RenderWidgetHostTest, DeferredGestureTapDownAnulledOnScroll) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); SimulateGestureEvent(WebInputEvent::GestureScrollBegin); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(WebInputEvent::GestureScrollBegin, host_->GestureEventLastQueueEvent().type); MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); // If the deferral timer incorrectly fired, it will send an extra message. EXPECT_EQ(1U, process_->sink().message_count()); } // Test that a tap cancel event during the deferral interval drops the // GestureTapDown. TEST_F(RenderWidgetHostTest, DeferredGestureTapDownAnulledOnTapCancel) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); SimulateGestureEvent(WebInputEvent::GestureTapCancel); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); // If the deferral timer incorrectly fired, it will send an extra message. EXPECT_EQ(0U, process_->sink().message_count()); } // Test that if a GestureTapDown gets sent, any corresponding GestureTapCancel // is also sent. TEST_F(RenderWidgetHostTest, DeferredGestureTapDownTapCancel) { process_->sink().ClearMessages(); // Set some sort of short deferral timeout host_->set_maximum_tap_gap_time_ms(5); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->GestureEventLastQueueEventSize()); MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); SimulateGestureEvent(WebInputEvent::GestureTapCancel); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); } // Test that a GestureScrollEnd | GestureFlingStart are deferred during the // debounce interval, that Scrolls are not and that the deferred events are // sent after that timer fires. TEST_F(RenderWidgetHostTest, DebounceDefersFollowingGestureEvents) { process_->sink().ClearMessages(); host_->set_debounce_interval_time_ms(3); SimulateGestureEvent(WebInputEvent::GestureScrollUpdate); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(0U, host_->GestureEventDebouncingQueueSize()); EXPECT_TRUE(host_->ScrollingInProgress()); SimulateGestureEvent(WebInputEvent::GestureScrollUpdate); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(0U, host_->GestureEventDebouncingQueueSize()); EXPECT_TRUE(host_->ScrollingInProgress()); SimulateGestureEvent(WebInputEvent::GestureScrollEnd); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(1U, host_->GestureEventDebouncingQueueSize()); SimulateGestureEvent(WebInputEvent::GestureFlingStart); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(2U, host_->GestureEventDebouncingQueueSize()); SimulateGestureEvent(WebInputEvent::GestureTapDown); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(3U, host_->GestureEventDebouncingQueueSize()); MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(5)); MessageLoop::current()->Run(); // The deferred events are correctly queued in coalescing queue. EXPECT_EQ(1U, process_->sink().message_count()); // NOTE: The TapDown is still deferred hence not queued. EXPECT_EQ(4U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(0U, host_->GestureEventDebouncingQueueSize()); EXPECT_FALSE(host_->ScrollingInProgress()); // Verify that the coalescing queue contains the correct events. WebInputEvent::Type expected[] = { WebInputEvent::GestureScrollUpdate, WebInputEvent::GestureScrollUpdate, WebInputEvent::GestureScrollEnd, WebInputEvent::GestureFlingStart}; for (unsigned i = 0; i < sizeof(expected) / sizeof(WebInputEvent::Type); i++) { WebGestureEvent merged_event = host_->GestureEventQueueEventAt(i); EXPECT_EQ(expected[i], merged_event.type); } } // Test that non-scroll events are deferred while scrolling during the debounce // interval and are discarded if a GestureScrollUpdate event arrives before the // interval end. TEST_F(RenderWidgetHostTest, DebounceDropsDeferredEvents) { process_->sink().ClearMessages(); host_->set_debounce_interval_time_ms(3); EXPECT_FALSE(host_->ScrollingInProgress()); SimulateGestureEvent(WebInputEvent::GestureScrollUpdate); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(0U, host_->GestureEventDebouncingQueueSize()); EXPECT_TRUE(host_->ScrollingInProgress()); // This event should get discarded. SimulateGestureEvent(WebInputEvent::GestureScrollEnd); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(1U, host_->GestureEventDebouncingQueueSize()); SimulateGestureEvent(WebInputEvent::GestureScrollUpdate); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->GestureEventLastQueueEventSize()); EXPECT_EQ(0U, host_->GestureEventDebouncingQueueSize()); EXPECT_TRUE(host_->ScrollingInProgress()); // Verify that the coalescing queue contains the correct events. WebInputEvent::Type expected[] = { WebInputEvent::GestureScrollUpdate, WebInputEvent::GestureScrollUpdate}; for (unsigned i = 0; i < sizeof(expected) / sizeof(WebInputEvent::Type); i++) { WebGestureEvent merged_event = host_->GestureEventQueueEventAt(i); EXPECT_EQ(expected[i], merged_event.type); } } // Tests that touch-events are queued properly. TEST_F(RenderWidgetHostTest, TouchEventQueue) { process_->sink().ClearMessages(); PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); // The second touch should not be sent since one is already in queue. MoveTouchPoint(0, 5, 5); SendTouchEvent(); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(2U, host_->TouchEventQueueSize()); // Receive an ACK for the first touch-event. SendInputEventACK(WebInputEvent::TouchStart, true); EXPECT_EQ(1U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchStart, view_->acked_event().type); EXPECT_EQ(1, view_->acked_event_count()); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); view_->ClearAckedEvent(); SendInputEventACK(WebInputEvent::TouchMove, true); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchMove, view_->acked_event().type); EXPECT_EQ(1, view_->acked_event_count()); EXPECT_EQ(0U, process_->sink().message_count()); } // Tests that the touch-queue is emptied if a page stops listening for touch // events. TEST_F(RenderWidgetHostTest, TouchEventQueueFlush) { process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); // Send a touch-press event. PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); ReleaseTouchPoint(0); SendTouchEvent(); for (int i = 5; i < 15; ++i) { PressTouchPoint(1, 1); SendTouchEvent(); MoveTouchPoint(0, i, i); SendTouchEvent(); ReleaseTouchPoint(0); SendTouchEvent(); } EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(32U, host_->TouchEventQueueSize()); // Receive an ACK for the first touch-event. One of the queued touch-event // should be forwarded. SendInputEventACK(WebInputEvent::TouchStart, true); EXPECT_EQ(31U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchStart, view_->acked_event().type); EXPECT_EQ(1, view_->acked_event_count()); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); view_->ClearAckedEvent(); // The page stops listening for touch-events. The touch-event queue should now // be emptied, but none of the queued touch-events should be sent to the // renderer. host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, false)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_FALSE(host_->ShouldForwardTouchEvent()); } // Tests that touch-events are coalesced properly in the queue. TEST_F(RenderWidgetHostTest, TouchEventQueueCoalesce) { process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); // Send a touch-press event. PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); // Send a few touch-move events, followed by a touch-release event. All the // touch-move events should be coalesced into a single event. for (int i = 5; i < 15; ++i) { MoveTouchPoint(0, i, i); SendTouchEvent(); } ReleaseTouchPoint(0); SendTouchEvent(); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(3U, host_->TouchEventQueueSize()); // ACK the press. SendInputEventACK(WebInputEvent::TouchStart, true); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(2U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchStart, view_->acked_event().type); EXPECT_EQ(1, view_->acked_event_count()); process_->sink().ClearMessages(); view_->ClearAckedEvent(); // ACK the moves. SendInputEventACK(WebInputEvent::TouchMove, true); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchMove, view_->acked_event().type); EXPECT_EQ(10, view_->acked_event_count()); process_->sink().ClearMessages(); view_->ClearAckedEvent(); // ACK the release. SendInputEventACK(WebInputEvent::TouchEnd, true); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_EQ(WebKit::WebInputEvent::TouchEnd, view_->acked_event().type); EXPECT_EQ(1, view_->acked_event_count()); } // Tests that an event that has already been sent but hasn't been ack'ed yet // doesn't get coalesced with newer events. TEST_F(RenderWidgetHostTest, SentTouchEventDoesNotCoalesce) { process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); // Send a touch-press event. PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); // Send a few touch-move events, followed by a touch-release event. All the // touch-move events should be coalesced into a single event. for (int i = 5; i < 15; ++i) { MoveTouchPoint(0, i, i); SendTouchEvent(); } EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(2U, host_->TouchEventQueueSize()); SendInputEventACK(WebInputEvent::TouchStart, false); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->TouchEventQueueSize()); process_->sink().ClearMessages(); // The coalesced touch-move event has been sent to the renderer. Any new // touch-move event should not be coalesced with the sent event. MoveTouchPoint(0, 5, 5); SendTouchEvent(); EXPECT_EQ(2U, host_->TouchEventQueueSize()); MoveTouchPoint(0, 7, 7); SendTouchEvent(); EXPECT_EQ(2U, host_->TouchEventQueueSize()); } // Tests that coalescing works correctly for multi-touch events. TEST_F(RenderWidgetHostTest, TouchEventQueueMultiTouch) { process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); // Press the first finger. PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); // Move the finger. MoveTouchPoint(0, 5, 5); SendTouchEvent(); EXPECT_EQ(2U, host_->TouchEventQueueSize()); // Now press a second finger. PressTouchPoint(2, 2); SendTouchEvent(); EXPECT_EQ(3U, host_->TouchEventQueueSize()); // Move both fingers. MoveTouchPoint(0, 10, 10); MoveTouchPoint(1, 20, 20); SendTouchEvent(); EXPECT_EQ(4U, host_->TouchEventQueueSize()); // Move only one finger now. MoveTouchPoint(0, 15, 15); SendTouchEvent(); EXPECT_EQ(4U, host_->TouchEventQueueSize()); // Move the other finger. MoveTouchPoint(1, 25, 25); SendTouchEvent(); EXPECT_EQ(4U, host_->TouchEventQueueSize()); // Make sure both fingers are marked as having been moved in the coalesced // event. const WebTouchEvent& event = host_->latest_event(); EXPECT_EQ(WebTouchPoint::StateMoved, event.touches[0].state); EXPECT_EQ(WebTouchPoint::StateMoved, event.touches[1].state); } // Tests that if a touch-event queue is destroyed in response to a touch-event // in the renderer, then there is no crash when the ACK for that touch-event // comes back. TEST_F(RenderWidgetHostTest, TouchEventAckAfterQueueFlushed) { // First, install a touch-event handler and send some touch-events to the // renderer. process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); PressTouchPoint(1, 1); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->TouchEventQueueSize()); process_->sink().ClearMessages(); MoveTouchPoint(0, 10, 10); SendTouchEvent(); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(2U, host_->TouchEventQueueSize()); // Receive an ACK for the press. This should cause the queued touch-move to // be sent to the renderer. SendInputEventACK(WebInputEvent::TouchStart, true); EXPECT_EQ(1U, process_->sink().message_count()); EXPECT_EQ(1U, host_->TouchEventQueueSize()); process_->sink().ClearMessages(); // Uninstall the touch-event handler. This will cause the queue to be flushed. host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, false)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); // Now receive an ACK for the move. SendInputEventACK(WebInputEvent::TouchMove, true); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); } #if defined(OS_WIN) || defined(USE_AURA) // Tests that the acked events have correct state. (ui::Events are used only on // windows and aura) TEST_F(RenderWidgetHostTest, AckedTouchEventState) { process_->sink().ClearMessages(); host_->OnMessageReceived(ViewHostMsg_HasTouchEventHandlers(0, true)); EXPECT_EQ(0U, process_->sink().message_count()); EXPECT_EQ(0U, host_->TouchEventQueueSize()); EXPECT_TRUE(host_->ShouldForwardTouchEvent()); // Send a bunch of events, and make sure the ACKed events are correct. ScopedVector expected_events; // Use a custom timestamp for all the events to test that the acked events // have the same timestamp; base::TimeDelta timestamp = base::Time::NowFromSystemTime() - base::Time(); timestamp -= base::TimeDelta::FromSeconds(600); // Press the first finger. PressTouchPoint(1, 1); SetTouchTimestamp(timestamp); SendTouchEvent(); EXPECT_EQ(1U, process_->sink().message_count()); process_->sink().ClearMessages(); expected_events.push_back(new ui::TouchEvent(ui::ET_TOUCH_PRESSED, gfx::Point(1, 1), 0, timestamp)); // Move the finger. timestamp += base::TimeDelta::FromSeconds(10); MoveTouchPoint(0, 5, 5); SetTouchTimestamp(timestamp); SendTouchEvent(); EXPECT_EQ(2U, host_->TouchEventQueueSize()); expected_events.push_back(new ui::TouchEvent(ui::ET_TOUCH_MOVED, gfx::Point(5, 5), 0, timestamp)); // Now press a second finger. timestamp += base::TimeDelta::FromSeconds(10); PressTouchPoint(2, 2); SetTouchTimestamp(timestamp); SendTouchEvent(); EXPECT_EQ(3U, host_->TouchEventQueueSize()); expected_events.push_back(new ui::TouchEvent(ui::ET_TOUCH_PRESSED, gfx::Point(2, 2), 1, timestamp)); // Move both fingers. timestamp += base::TimeDelta::FromSeconds(10); MoveTouchPoint(0, 10, 10); MoveTouchPoint(1, 20, 20); SetTouchTimestamp(timestamp); SendTouchEvent(); EXPECT_EQ(4U, host_->TouchEventQueueSize()); expected_events.push_back(new ui::TouchEvent(ui::ET_TOUCH_MOVED, gfx::Point(10, 10), 0, timestamp)); expected_events.push_back(new ui::TouchEvent(ui::ET_TOUCH_MOVED, gfx::Point(20, 20), 1, timestamp)); // Receive the ACKs and make sure the generated events from the acked events // are correct. WebInputEvent::Type acks[] = { WebInputEvent::TouchStart, WebInputEvent::TouchMove, WebInputEvent::TouchStart, WebInputEvent::TouchMove }; for (size_t i = 0; i < arraysize(acks); ++i) { SendInputEventACK(acks[i], false); EXPECT_EQ(acks[i], view_->acked_event().type); ScopedVector acked; MakeUITouchEventsFromWebTouchEvents(view_->acked_event(), &acked); bool success = EventListIsSubset(acked, expected_events); EXPECT_TRUE(success) << ""Failed on step: "" << i; if (!success) break; expected_events.erase(expected_events.begin(), expected_events.begin() + acked.size()); } EXPECT_EQ(0U, expected_events.size()); } #endif // defined(OS_WIN) || defined(USE_AURA) // Test that the hang monitor timer expires properly if a new timer is started // while one is in progress (see crbug.com/11007). TEST_F(RenderWidgetHostTest, DontPostponeHangMonitorTimeout) { // Start with a short timeout. host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Immediately try to add a long 30 second timeout. EXPECT_FALSE(host_->unresponsive_timer_fired()); host_->StartHangMonitorTimeout(TimeDelta::FromSeconds(30)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(10)); MessageLoop::current()->Run(); EXPECT_TRUE(host_->unresponsive_timer_fired()); } // Test that the hang monitor timer expires properly if it is started, stopped, // and then started again. TEST_F(RenderWidgetHostTest, StopAndStartHangMonitorTimeout) { // Start with a short timeout, then stop it. host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); host_->StopHangMonitorTimeout(); // Start it again to ensure it still works. EXPECT_FALSE(host_->unresponsive_timer_fired()); host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(10)); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(40)); MessageLoop::current()->Run(); EXPECT_TRUE(host_->unresponsive_timer_fired()); } // Test that the hang monitor timer expires properly if it is started, then // updated to a shorter duration. TEST_F(RenderWidgetHostTest, ShorterDelayHangMonitorTimeout) { // Start with a timeout. host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(100)); // Start it again with shorter delay. EXPECT_FALSE(host_->unresponsive_timer_fired()); host_->StartHangMonitorTimeout(TimeDelta::FromMilliseconds(20)); // Wait long enough for the second timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(25)); MessageLoop::current()->Run(); EXPECT_TRUE(host_->unresponsive_timer_fired()); } // Test that the hang monitor catches two input events but only one ack. // This can happen if the second input event causes the renderer to hang. // This test will catch a regression of crbug.com/111185. TEST_F(RenderWidgetHostTest, MultipleInputEvents) { // Configure the host to wait 10ms before considering // the renderer hung. host_->set_hung_renderer_delay_ms(10); // Send two events but only one ack. SimulateKeyboardEvent(WebInputEvent::RawKeyDown); SimulateKeyboardEvent(WebInputEvent::RawKeyDown); SendInputEventACK(WebInputEvent::RawKeyDown, true); // Wait long enough for first timeout and see if it fired. MessageLoop::current()->PostDelayedTask( FROM_HERE, MessageLoop::QuitClosure(), TimeDelta::FromMilliseconds(40)); MessageLoop::current()->Run(); EXPECT_TRUE(host_->unresponsive_timer_fired()); } // This test is not valid for Windows because getting the shared memory // size doesn't work. #if !defined(OS_WIN) TEST_F(RenderWidgetHostTest, IncorrectBitmapScaleFactor) { ViewHostMsg_UpdateRect_Params params; process_->InitUpdateRectParams(¶ms); params.scale_factor = params.scale_factor * 2; EXPECT_EQ(0, process_->bad_msg_count()); host_->OnMsgUpdateRect(params); EXPECT_EQ(1, process_->bad_msg_count()); } #endif } // namespace content ",16287,True,3049.0680507790657,median "ifdef::env-github[] NOTE: Release notes are best read in our documentation at https://www.elastic.co/guide/en/apm/agent/java/current/release-notes.html[elastic.co] endif::[] //// [[release-notes-x.x.x]] ==== x.x.x - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * Cool new feature: {pull}2526[#2526] [float] ===== Bug fixes //// === Unreleased [[release-notes-1.18.0]] ==== 1.18.0 - YYYY/MM/DD [float] ===== Breaking changes [float] ===== Features * Experimental support for runtime attachment now also for OSGi containers, JBoss, and WildFly * New mitigation of OSGi bootdelegation errors (`NoClassDefFoundError`). You can remove any `org.osgi.framework.bootdelegation` related configuration. This release also removes the configuration option `boot_delegation_packages`. * Overhaul of the `ExecutorService` instrumentation that avoids `ClassCastException` issues - {pull}1206[#1206] * Support for `ForkJoinPool` and `ScheduledExecutorService` (see <>) * Support for `ExecutorService#invokeAny` and `ExecutorService#invokeAll` * Added support for `java.util.TimerTask` - {pull}1235[#1235] * Add capturing of request body in Elasticsearch queries: `_msearch`, `_count`, `_msearch/template`, `_search/template`, `_rollup_search` - {pull}1222[#1222] * Add <> flag * Add experimental support for Scala Futures * The agent now collects heap memory pools metrics - {pull}1228[#1228] * Deprecating `ignore_urls` config in favour of <> to align with other agents, while still allowing the old config name for backward compatibility - {pull}1315[#1315] * Enabling instrumentation of classes compiled with Java 1.4. This is reverting the restriction of instrumenting only bytecode of Java 1.5 or higher ({pull}320[#320]), which was added due to potential `VerifyError`. Such errors should be avoided now by the usage of `TypeConstantAdjustment` - {pull}1317[#1317] * Enabling agent to work without attempting any communication with APM server, by allowing setting `server_urls` with an empty string - {pull}1295[#1295] * Add <> - {pull}1303[#1303] * Add `profiling_inferred_spans_lib_directory` option to override the default temp directory used for exporting the async-profiler library. This is useful for server-hardened environments where `/tmp` is often configured with `noexec`, leading to `java.lang.UnsatisfiedLinkError` errors - {pull}1350[#1350] * Create spans for Servlet dispatches to FORWARD, INCLUDE and ERROR - {pull}1212[#1212] [float] ===== Bug fixes * Fixes error capturing for log4j2 loggers. Version 1.17.0 introduced a regression. * Fixes `NullPointerException` related to JAX-RS and Quartz instrumentation - {pull}1249[#1249] * Expanding k8s pod ID discovery to some formerly non-supported environments * When `recording` is set to `false`, the agent will not send captured errors anymore. * Fixes NPE in Dubbo instrumentation that occurs when the application is acting both as a provider and as a consumer - {pull}1260[#1260] * Adding a delay by default what attaching the agent to Tomcat using the premain route to work around the JUL deadlock issue - {pull}1262[#1262] * Fixes missing `jboss.as:*` MBeans on JBoss - {pull}1257[#1257] * Fixes a `NoClassDefFoundError` in the JMS instrumentation of `MessageListener` - {pull}1287[#1287] * Fix `/ by zero` error message when setting `server_urls` with an empty string - {pull}1295[#1295] * Fix `ClassNotFoundException` or `ClassCastException` in some cases where special log4j configurations are used - {pull}1322[#1322] * Fix `NumberFormatException` when using early access Java version - {pull}1325[#1325] * Fix `service_name` config being ignored when set to the same auto-discovered default value - {pull}1324[#1324] * Fix service name error when updating a web app on a Servlet container - {pull}1326[#1326] * Fix remote attach 'jps' executable not found when 'java' binary is symlinked ot a JRE - {pull}1352[#1352] [[release-notes-1.x]] === Java Agent version 1.x [[release-notes-1.18.0.rc1]] ==== 1.18.0.RC1 - 2020/07/22 This release candidate adds some highly anticipated features: It’s now possible to attach the agent at runtime in more cases than before. Most notably, it enables runtime attachment on JBoss, WildFly, Glassfish/Payara, and other OSGi runtimes such as Atlassian Jira and Confluence. To make this and other significant features, such as https://github.com/elastic/apm-agent-java/issues/937[external plugins], possible, we have implemented major changes to the architecture of the agent. The agent now relies on the `invokedynamic` bytecode instruction to make plugin development easier, safer, and more efficient. As early versions of Java 7 and Java 8 have unreliable support for invokedynamic, we now require a minimum update level of 60 for Java 7 (7u60+) in addition to the existing minimum update level of 40 for Java 8 (8u40+). We’re looking for users who would like to try this out to give feedback. If we see that the `invokedynamic`-based approach (https://github.com/elastic/apm-agent-java/pull/1230[indy plugins]) works well, we can continue and migrate the rest of the plugins. After the migration has completed, we can move forward with external plugins and remove the experimental label from runtime attachment. If all works like in our testing, you would not see `NoClassDefFoundError` s anymore when, for example, trying to attach the agent at runtime to an OSGi container or a JBoss server. Also, non-standard OSGi containers, such as Atlassian Jira and other technologies with restrictive class loading policies, such as MuleSoft ESB, will benefit from this change. In the worst case, there might be JVM crashes due to `invokedynamic`-related JVM bugs. However, we already disable the agent when attached to JVM versions that are known to be problematic. Another potentially problematic area is that we now dynamically raise the bytecode version of instrumented classes to be at least bytecode version 51 (Java 7). This is needed in order to be able to use the `invokedynamic` instruction. This requires re-computation of stack map frames which makes instrumentation a bit slower. We don't anticipate notable slowdowns unless you extensively (over-)use <>. [float] ===== Breaking changes * Early Java 7 versions, prior to update 60, are not supported anymore. When trying to attach to a non-supported version, the agent will disable itself and not apply any instrumentations. [float] ===== Features * Experimental support for runtime attachment now also for OSGi containers, JBoss, and WildFly * New mitigation of OSGi bootdelegation errors (`NoClassDefFoundError`). You can remove any `org.osgi.framework.bootdelegation` related configuration. This release also removes the configuration option `boot_delegation_packages`. * Overhaul of the `ExecutorService` instrumentation that avoids `ClassCastException` issues - {pull}1206[#1206] * Support for `ForkJoinPool` and `ScheduledExecutorService` (see <>) * Support for `ExecutorService#invokeAny` and `ExecutorService#invokeAll` * Added support for `java.util.TimerTask` - {pull}1235[#1235] * Add capturing of request body in Elasticsearch queries: `_msearch`, `_count`, `_msearch/template`, `_search/template`, `_rollup_search` - {pull}1222[#1222] * Add <> flag * Add experimental support for Scala Futures * The agent now collects heap memory pools metrics - {pull}1228[#1228] [float] ===== Bug fixes * Fixes error capturing for log4j2 loggers. Version 1.17.0 introduced a regression. * Fixes `NullPointerException` related to JAX-RS and Quartz instrumentation - {pull}1249[#1249] * Expanding k8s pod ID discovery to some formerly non-supported environments * When `recording` is set to `false`, the agent will not send captured errors anymore. * Fixes NPE in Dubbo instrumentation that occurs when the application is acting both as a provider and as a consumer - {pull}1260[#1260] * Adding a delay by default what attaching the agent to Tomcat using the premain route to work around the JUL deadlock issue - {pull}1262[#1262] * Fixes missing `jboss.as:*` MBeans on JBoss - {pull}1257[#1257] [[release-notes-1.17.0]] ==== 1.17.0 - 2020/06/17 [float] ===== Features * Log files are now rotated after they reach <>. There will always be one history file `${log_file}.1`. * Add <> and <> with the options `PLAIN_TEXT` and `JSON`. The latter uses https://github.com/elastic/ecs-logging-java[ecs-logging-java] to format the logs. * Exposing <> config - {pull}1187[#1187] * Add support for naming transactions based on Grails controllers. Supports Grails 3+ - {pull}1171[#1171] * Add support for the Apache/Alibaba Dubbo RPC framework * Async Profiler version upgraded to 1.7.1, with a new debugging flag for the stack frame recovery mechanism - {pull}1173[#1173] [float] ===== Bug fixes * Fixes `IndexOutOfBoundsException` that can occur when profiler-inferred spans are enabled. This also makes the profiler more resilient by just removing the call tree related to the exception (which might be in an invalid state) as opposed to stopping the profiler when an exception occurs. * Fix `NumberFormatException` when parsing Ingres/Actian JDBC connection strings - {pull}1198[#1198] * Prevent agent from overriding JVM configured truststore when not using HTTPS for communication with APM server - {pull}1203[#1203] * Fix `java.lang.IllegalStateException` with `jps` JVM when using continuous runtime attach - {pull}1205[1205] * Fix agent trying to load log4j2 plugins from application - {pull}1214[1214] * Fix memory leak in gRPC instrumentation plugin - {pull}1196[1196] * Fix HTTPS connection failures when agent is configured to use HTTPS to communicate with APM server {pull}1209[1209] [[release-notes-1.16.0]] ==== 1.16.0 - 2020/05/13 [float] ===== Features * The log correlation feature now adds `error.id` to the MDC. See <> for details. - {pull}1050[#1050] * Deprecating the `incubating` tag in favour of the `experimental` tag. This is not a breaking change, so former <> configuration containing the `incubating` tag will still be respected - {pull}1123[#1123] * Add a `--without-emulated-attach` option for runtime attachment to allow disabling this feature as a workaround. * Add workaround for JDK bug JDK-8236039 with TLS 1.3 {pull}1149[#1149] * Add log level `OFF` to silence agent logging * Adds <> option to exclude fast executing spans. When set together with one of the more specific thresholds - `trace_methods_duration_threshold` or `profiling_inferred_spans_min_duration`, the higher threshold will determine which spans will be discarded. * Automatically instrument quartz jobs from the quartz-jobs artifact {pull}1170[#1170] * Perform re-parenting of regular spans to be a child of profiler-inferred spans. Requires APM Server and Kibana 7.8.0. {pull}1117[#1117] * Upgrade Async Profiler version to 1.7.0 [float] ===== Bug fixes * When Servlet-related Exceptions are handled through exception handlers that return a 200 status code, agent shouldn't override with 500 - {pull}1103[#1103] * Exclude Quartz 1 from instrumentation to avoid `IncompatibleClassChangeError: Found class org.quartz.JobExecutionContext, but interface was expected` - {pull}1108[#1108] * Fix breakdown metrics span sub-types {pull}1113[#1113] * Fix flaky gRPC server instrumentation {pull}1122[#1122] * Fix side effect of calling `Statement.getUpdateCount` more than once {pull}1139[#1139] * Stop capturing JDBC affected rows count using `Statement.getUpdateCount` to prevent unreliable side-effects {pull}1147[#1147] * Fix OpenTracing error tag handling (set transaction error result when tag value is `true`) {pull}1159[#1159] * Due to a bug in the build we didn't include the gRPC plugin in the build so far * `java.lang.ClassNotFoundException: Unable to load class 'jdk.internal...'` is thrown when tracing specific versions of Atlassian systems {pull}1168[#1168] * Make sure spans are kept active during `AsyncHandler` methods in the `AsyncHttpClient` * CPU and memory metrics are sometimes not reported properly when using IBM J9 {pull}1148[#1148] * `NullPointerException` thrown by the agent on WebLogic {pull}1142[#1142] [[release-notes-1.15.0]] ==== 1.15.0 - 2020/03/27 [float] ===== Breaking changes * Ordering of configuration sources has slightly changed, please review <>: ** `elasticapm.properties` file now has higher priority over java system properties and environment variables, + This change allows to change dynamic options values at runtime by editing file, previously values set in java properties or environment variables could not be overridden, even if they were dynamic. * Renamed some configuration options related to the experimental profiler-inferred spans feature ({pull}1084[#1084]): ** `profiling_spans_enabled` -> `profiling_inferred_spans_enabled` ** `profiling_sampling_interval` -> `profiling_inferred_spans_sampling_interval` ** `profiling_spans_min_duration` -> `profiling_inferred_spans_min_duration` ** `profiling_included_classes` -> `profiling_inferred_spans_included_classes` ** `profiling_excluded_classes` -> `profiling_inferred_spans_excluded_classes` ** Removed `profiling_interval` and `profiling_duration` (both are fixed to 5s now) [float] ===== Features * Gracefully abort agent init when running on a known Java 8 buggy JVM {pull}1075[#1075]. * Add support for <> * Makes <>, <>, and <> dynamic. Note that changing these values at runtime can slow down the application temporarily. * Do not instrument Servlet API before 3.0 {pull}1077[#1077] * Add support for API keys for apm backend authentication {pull}1083[#1083] * Add support for <> client & server instrumentation {pull}1019[#1019] * Deprecating `active` configuration option in favor of `recording`. Setting `active` still works as it's now an alias for `recording`. [float] ===== Bug fixes * When JAX-RS-annotated method delegates to another JAX-RS-annotated method, transaction name should include method A - {pull}1062[#1062] * Fixed bug that prevented an APM Error from being created when calling `org.slf4j.Logger#error` - {pull}1049[#1049] * Wrong address in JDBC spans for Oracle, MySQL and MariaDB when multiple hosts are configured - {pull}1082[#1082] * Document and re-order configuration priorities {pull}1087[#1087] * Improve heuristic for `service_name` when not set through config {pull}1097[#1097] [[release-notes-1.14.0]] ==== 1.14.0 - 2020/03/04 [float] ===== Features * Support for the official https://www.w3.org/TR/trace-context[W3C] `traceparent` and `tracestate` headers. + The agent now accepts both the `elastic-apm-traceparent` and the official `traceparent` header. By default, it sends both headers on outgoing requests, unless <> is set to false. * Creating spans for slow methods with the help of the sampling profiler https://github.com/jvm-profiling-tools/async-profiler[async-profiler]. This is a low-overhead way of seeing which methods make your transactions slow and a replacement for the `trace_methods` configuration option. See <> for more details * Adding a Circuit Breaker to pause the agent when stress is detected on the system and resume when the stress is relieved. See <> and {pull}1040[#1040] for more info. * `Span#captureException` and `Transaction#captureException` in public API return reported error id - {pull}1015[#1015] [float] ===== Bug fixes * java.lang.IllegalStateException: Cannot resolve type description for - {pull}1037[#1037] * properly handle `java.sql.SQLException` for unsupported JDBC features {pull}[#1035] https://github.com/elastic/apm-agent-java/issues/1025[#1025] [[release-notes-1.13.0]] ==== 1.13.0 - 2020/02/11 [float] ===== Features * Add support for <> * Add `context.message.age.ms` field for JMS message receiving spans and transactions - {pull}970[#970] * Instrument log4j2 Logger#error(String, Throwable) ({pull}919[#919]) Automatically captures exceptions when calling `logger.error(""message"", exception)` * Add instrumentation for external process execution through `java.lang.Process` and Apache `commons-exec` - {pull}903[#903] * Add `destination` fields to exit span contexts - {pull}976[#976] * Removed `context.message.topic.name` field - {pull}993[#993] * Add support for Kafka clients - {pull}981[#981] * Add support for binary `traceparent` header format (see the https://github.com/elastic/apm/blob/master/docs/agent-development.md#Binary-Fields[spec] for more details) - {pull}1009[#1009] * Add support for log correlation for log4j and log4j2, even when not used in combination with slf4j. See <> for details. [float] ===== Bug Fixes * Fix parsing value of `trace_methods` configuration property {pull}930[#930] * Workaround for `java.util.logging` deadlock {pull}965[#965] * JMS should propagate traceparent header when transactions are not sampled {pull}999[#999] * Spans are not closed if JDBC implementation does not support `getUpdateCount` {pull}1008[#1008] [[release-notes-1.12.0]] ==== 1.12.0 - 2019/11/21 [float] ===== Features * JMS Enhancements {pull}911[#911]: ** Add special handling for temporary queues/topics ** Capture message bodies of text Messages *** Rely on the existing `ELASTIC_APM_CAPTURE_BODY` agent config option (off by default). *** Send as `context.message.body` *** Limit size to 10000 characters. If longer than this size, trim to 9999 and append with ellipsis ** Introduce the `ignore_message_queues` configuration to disable instrumentation (message tagging) for specific queues/topics as suggested in {pull}710[#710] ** Capture predefined message headers and all properties *** Rely on the existing `ELASTIC_APM_CAPTURE_HEADERS` agent config option. *** Send as `context.message.headers` *** Sanitize sensitive headers/properties based on the `sanitize_field_names` config option * Added support for the MongoDB sync driver. See https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[supported data stores]. [float] ===== Bug Fixes * JDBC regression- `PreparedStatement#executeUpdate()` and `PreparedStatement#executeLargeUpdate()` are not traced {pull}918[#918] * When systemd cgroup driver is used, the discovered Kubernetes pod UID contains ""_"" instead of ""-"" {pull}920[#920] * DB2 jcc4 driver is not traced properly {pull}926[#926] [[release-notes-1.11.0]] ==== 1.11.0 - 2019/10/31 [float] ===== Features * Add the ability to configure a unique name for a JVM within a service through the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-node-name[`service_node_name`] config option] * Add ability to ignore some exceptions to be reported as errors https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-ignore-exceptions[ignore_exceptions] * Applying new logic for JMS `javax.jms.MessageConsumer#receive` so that, instead of the transaction created for the polling method itself (ie from `receive` start to end), the agent will create a transaction attempting to capture the code executed during actual message handling. This logic is suitable for environments where polling APIs are invoked within dedicated polling threads. This polling transaction creation strategy can be reversed through a configuration option (`message_polling_transaction_strategy`) that is not exposed in the properties file by default. * Send IP obtained through `javax.servlet.ServletRequest#getRemoteAddr()` in `context.request.socket.remote_address` instead of parsing from headers {pull}889[#889] * Added `ElasticApmAttacher.attach(String propertiesLocation)` to specify a custom properties location * Logs message when `transaction_max_spans` has been exceeded {pull}849[#849] * Report the number of affected rows by a SQL statement (UPDATE,DELETE,INSERT) in 'affected_rows' span attribute {pull}707[#707] * Add https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-traced[`@Traced`] annotation which either creates a span or a transaction, depending on the context * Report JMS destination as a span/transaction context field {pull}906[#906] * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option [float] ===== Bug Fixes * JMS creates polling transactions even when the API invocations return without a message * Support registering MBeans which are added after agent startup [[release-notes-1.10.0]] ==== 1.10.0 - 2019/09/30 [float] ===== Features * Add ability to manually specify reported https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-hostname[hostname] * Add support for https://www.elastic.co/guide/en/apm/agent/java/master/supported-technologies-details.html#supported-databases[Redis Jedis client] * Add support for identifying target JVM to attach apm agent to using JVM property. See also the documentation of the https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-cli.html#setup-attach-cli-usage-list[`--include` and `--exclude` flags] * Added https://www.elastic.co/guide/en/apm/agent/java/master/config-jmx.html#config-capture-jmx-metrics[`capture_jmx_metrics`] configuration option * Improve servlet error capture {pull}812[#812] Among others, now also takes Spring MVC `@ExceptionHandler`s into account * Instrument Logger#error(String, Throwable) {pull}821[#821] Automatically captures exceptions when calling `logger.error(""message"", exception)` * Easier log correlation with https://github.com/elastic/java-ecs-logging. See https://www.elastic.co/guide/en/apm/agent/java/master/log-correlation.html[docs]. * Avoid creating a temp agent file for each attachment {pull}859[#859] * Instrument `View#render` instead of `DispatcherServlet#render` {pull}829[#829] This makes the transaction breakdown graph more useful. Instead of `dispatcher-servlet`, the graph now shows a type which is based on the view name, for example, `FreeMarker` or `Thymeleaf`. [float] ===== Bug Fixes * Error in log when setting https://www.elastic.co/guide/en/apm/agent/java/current/config-reporter.html#config-server-urls[server_urls] to an empty string - `co.elastic.apm.agent.configuration.ApmServerConfigurationSource - Expected previousException not to be null` * Avoid terminating the TCP connection to APM Server when polling for configuration updates {pull}823[#823] [[release-notes-1.9.0]] ==== 1.9.0 - 2019/08/22 [float] ===== Features * Upgrading supported OpenTracing version from 0.31 to 0.33 * Added annotation and meta-annotation matching support for `trace_methods`, for example: ** `public @java.inject.* org.example.*` (for annotation) ** `public @@javax.enterprise.context.NormalScope org.example.*` (for meta-annotation) * The runtime attachment now also works when the `tools.jar` or the `jdk.attach` module is not available. This means you don't need a full JDK installation - the JRE is sufficient. This makes the runtime attachment work in more environments such as minimal Docker containers. Note that the runtime attachment currently does not work for OSGi containers like those used in many application servers such as JBoss and WildFly. See the https://www.elastic.co/guide/en/apm/agent/java/master/setup-attach-cli.html[documentation] for more information. * Support for Hibernate Search [float] ===== Bug Fixes * A warning in logs saying APM server is not available when using 1.8 with APM server 6.x. Due to that, agent 1.8.0 will silently ignore non-string labels, even if used with APM server of versions 6.7.x or 6.8.x that support such. If APM server version is <6.7 or 7.0+, this should have no effect. Otherwise, upgrade the Java agent to 1.9.0+. * `ApacheHttpAsyncClientInstrumentation` matching increases startup time considerably * Log correlation feature is active when `active==false` * Tomcat's memory leak prevention mechanism is causing a... memory leak. JDBC statement map is leaking in Tomcat if the application that first used it is undeployed/redeployed. See https://discuss.elastic.co/t/elastic-apm-agent-jdbchelper-seems-to-use-a-lot-of-memory/195295[this related discussion]. [float] ==== Breaking Changes * The `apm-agent-attach.jar` is not executable anymore. Use `apm-agent-attach-standalone.jar` instead. [[release-notes-1.8.0]] ==== 1.8.0 - 2019/07/30 [float] ===== Features * Added support for tracking https://www.elastic.co/guide/en/kibana/7.3/transactions.html[time spent by span type]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-breakdown-metrics[`breakdown_metrics`] to `false`. * Added support for https://www.elastic.co/guide/en/kibana/7.3/agent-configuration.html[central configuration]. Can be disabled by setting https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-central-config[`central_config`] to `false`. * Added support for Spring's JMS flavor - instrumenting `org.springframework.jms.listener.SessionAwareMessageListener` * Added support to legacy ApacheHttpClient APIs (which adds support to Axis2 configured to use ApacheHttpClient) * Added support for setting https://www.elastic.co/guide/en/apm/agent/java/1.x/config-reporter.html#config-server-urls[`server_urls`] dynamically via properties file {pull}723[#723] * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-config-file[`config_file`] option * Added option to use `@javax.ws.rs.Path` value as transaction name https://www.elastic.co/guide/en/apm/agent/java/current/config-jax-rs.html#config-use-jaxrs-path-as-transaction-name[`use_jaxrs_path_as_transaction_name`] * Instrument quartz jobs https://www.elastic.co/guide/en/apm/agent/java/current/supported-technologies-details.html#supported-scheduling-frameworks[docs] * SQL parsing improvements {pull}696[#696] * Introduce priorities for transaction name {pull}748[#748]. Now uses the path as transaction name if https://www.elastic.co/guide/en/apm/agent/java/current/config-http.html#config-use-path-as-transaction-name[`use_path_as_transaction_name`] is set to `true` rather than `ServletClass#doGet`. But if a name can be determined from a high level framework, like Spring MVC, that takes precedence. User-supplied names from the API always take precedence over any others. * Use JSP path name as transaction name as opposed to the generated servlet class name {pull}751[#751] [float] ===== Bug Fixes * Some JMS Consumers and Producers are filtered due to class name filtering in instrumentation matching * Jetty: When no display name is set and context path is ""/"" transaction service names will now correctly fall back to configured values * JDBC's `executeBatch` is not traced * Drops non-String labels when connected to APM Server < 6.7 to avoid validation errors {pull}687[#687] * Parsing container ID in cloud foundry garden {pull}695[#695] * Automatic instrumentation should not override manual results {pull}752[#752] [float] ===== Breaking changes * The log correlation feature does not add `span.id` to the MDC anymore but only `trace.id` and `transaction.id` {pull}742[#742]. [[release-notes-1.7.0]] ==== 1.7.0 - 2019/06/13 [float] ===== Features * Added the `trace_methods_duration_threshold` config option. When using the `trace_methods` config option with wild cards, this enables considerable reduction of overhead by limiting the number of spans captured and reported (see more details in config documentation). NOTE: Using wildcards is still not the recommended approach for the `trace_methods` feature. * Add `Transaction#addCustomContext(String key, String|Number|boolean value)` to public API * Added support for AsyncHttpClient 2.x * Added https://www.elastic.co/guide/en/apm/agent/java/current/config-core.html#config-global-labels[`global_labels`] configuration option. This requires APM Server 7.2+. * Added basic support for JMS- distributed tracing for basic scenarios of `send`, `receive`, `receiveNoWait` and `onMessage`. Both Queues and Topics are supported. Async `send` APIs are not supported in this version. NOTE: This feature is currently marked as ""experimental"" and is disabled by default. In order to enable, it is required to set the https://www.elastic.co/guide/en/apm/agent/java/1.x/config-core.html#config-disable-instrumentations[`disable_instrumentations`] configuration property to an empty string. * Improved OSGi support: added a configuration option for `bootdelegation` packages {pull}641[#641] * Better span names for SQL spans. For example, `SELECT FROM user` instead of just `SELECT` {pull}633[#633] [float] ===== Bug Fixes * ClassCastException related to async instrumentation of Pilotfish Executor causing thread hang (applied workaround) * NullPointerException when computing Servlet transaction name with null HTTP method name * FileNotFoundException when trying to find implementation version of jar with encoded URL * NullPointerException when closing Apache AsyncHttpClient request producer * Fixes loading of `elasticapm.properties` for Spring Boot applications * Fix startup error on WebLogic 12.2.1.2.0 {pull}649[#649] * Disable metrics reporting and APM Server health check when active=false {pull}653[#653] [[release-notes-1.6.1]] ==== 1.6.1 - 2019/04/26 [float] ===== Bug Fixes * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/581[#581] * Makes log_file option work again https://github.com/elastic/apm-agent-java/issues/594[#594] * Async context propagation fixes ** Fixing some async mechanisms lifecycle issues https://github.com/elastic/apm-agent-java/issues/605[#605] ** Fixes exceptions when using WildFly managed executor services https://github.com/elastic/apm-agent-java/issues/589[#589] ** Exclude glassfish Executor which does not permit wrapped runnables https://github.com/elastic/apm-agent-java/issues/596[#596] ** Exclude DumbExecutor https://github.com/elastic/apm-agent-java/issues/598[#598] * Fixes Manifest version reading error to support `jar:file` protocol https://github.com/elastic/apm-agent-java/issues/601[#601] * Fixes transaction name for non-sampled transactions https://github.com/elastic/apm-agent-java/issues/597[#597] * Fixes potential classloader deadlock by preloading `FileSystems.getDefault()` https://github.com/elastic/apm-agent-java/issues/603[#603] [[release-notes-1.6.0]] ==== 1.6.0 - 2019/04/16 [float] ===== Related Announcements * Java APM Agent became part of the Cloud Foundry Java Buildpack as of https://github.com/cloudfoundry/java-buildpack/releases/tag/v4.19[Release v4.19] [float] ===== Features * Support Apache HttpAsyncClient - span creation and cross-service trace context propagation * Added the `jvm.thread.count` metric, indicating the number of live threads in the JVM (daemon and non-daemon) * Added support for WebLogic * Added support for Spring `@Scheduled` and EJB `@Schedule` annotations - https://github.com/elastic/apm-agent-java/pull/569[#569] [float] ===== Bug Fixes * Avoid that the agent blocks server shutdown in case the APM Server is not available - https://github.com/elastic/apm-agent-java/pull/554[#554] * Public API annotations improper retention prevents it from being used with Groovy - https://github.com/elastic/apm-agent-java/pull/567[#567] * Eliminate side effects of class loading related to Instrumentation matching mechanism [[release-notes-1.5.0]] ==== 1.5.0 - 2019/03/26 [float] ===== Potentially breaking changes * If you didn't explicitly set the https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] previously and you are dealing with a servlet-based application (including Spring Boot), your `service_name` will change. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] and the corresponding section in _Features_ for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. [float] ===== Features * Added property `""allow_path_on_hierarchy""` to JAX-RS plugin, to lookup inherited usage of `@path` * Support for number and boolean labels in the public API {pull}497[497]. This change also renames `tag` to `label` on the API level to be compliant with the https://github.com/elastic/ecs#-base-fields[Elastic Common Schema (ECS)]. The `addTag(String, String)` method is still supported but deprecated in favor of `addLabel(String, String)`. As of version 7.x of the stack, labels will be stored under `labels` in Elasticsearch. Previously, they were stored under `context.tags`. * Support async queries made by Elasticsearch REST client * Added `setStartTimestamp(long epochMicros)` and `end(long epochMicros)` API methods to `Span` and `Transaction`, allowing to set custom start and end timestamps. * Auto-detection of the `service_name` based on the `` element of the `web.xml` with a fallback to the servlet context path. If you are using a spring-based application, the agent will use the setting for `spring.application.name` for its `service_name`. See the documentation for https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-service-name[`service_name`] for more information. Note: this requires APM Server 7.0+. If using previous versions, nothing will change. * Previously, enabling https://www.elastic.co/guide/en/apm/agent/java/master/config-core.html#config-capture-body[`capture_body`] could only capture form parameters. Now it supports all UTF-8 encoded plain-text content types. The option https://www.elastic.co/guide/en/apm/agent/java/master/config-http.html#config-capture-body-content-types[`capture_body_content_types`] controls which `Content-Type`s should be captured. * Support async calls made by OkHttp client (`Call#enqueue`) * Added support for providing config options on agent attach. ** CLI example: `--config server_urls=http://localhost:8200,http://localhost:8201` ** API example: `ElasticApmAttacher.attach(Map.of(""server_urls"", ""http://localhost:8200,http://localhost:8201""));` [float] ===== Bug Fixes * Logging integration through MDC is not working properly - https://github.com/elastic/apm-agent-java/issues/499[#499] * ClassCastException with adoptopenjdk/openjdk11-openj9 - https://github.com/elastic/apm-agent-java/issues/505[#505] * Span count limitation is not working properly - reported https://discuss.elastic.co/t/kibana-apm-not-showing-spans-which-are-visible-in-discover-too-many-spans/171690[in our forum] * Java agent causes Exceptions in Alfresco cluster environment due to failure in the instrumentation of Hazelcast `Executor`s - reported https://discuss.elastic.co/t/cant-run-apm-java-agent-in-alfresco-cluster-environment/172962[in our forum] [[release-notes-1.4.0]] ==== 1.4.0 - 2019/02/14 [float] ===== Features * Added support for sync calls of OkHttp client * Added support for context propagation for `java.util.concurrent.ExecutorService`s * The `trace_methods` configuration now allows to omit the method matcher. Example: `com.example.*` traces all classes and methods within the `com.example` package and sub-packages. * Added support for JSF. Tested on WildFly, WebSphere Liberty and Payara with embedded JSF implementation and on Tomcat and Jetty with MyFaces 2.2 and 2.3 * Introduces a new configuration option `disable_metrics` which disables the collection of metrics via a wildcard expression. * Support for HttpUrlConnection * Adds `subtype` and `action` to spans. This replaces former typing mechanism where type, subtype and action were all set through the type in an hierarchical dotted-syntax. In order to support existing API usages, dotted types are parsed into subtype and action, however `Span.createSpan` and `Span.setType` are deprecated starting this version. Instead, type-less spans can be created using the new `Span.startSpan` API and typed spans can be created using the new `Span.startSpan(String type, String subtype, String action)` API * Support for JBoss EAP 6.4, 7.0, 7.1 and 7.2 * Improved startup times * Support for SOAP (JAX-WS). SOAP client create spans and propagate context. Transactions are created for `@WebService` classes and `@WebMethod` methods. [float] ===== Bug Fixes * Fixes a failure in BitBucket when agent deployed https://github.com/elastic/apm-agent-java/issues/349[#349] * Fixes increased CPU consumption https://github.com/elastic/apm-agent-java/issues/453[#453] and https://github.com/elastic/apm-agent-java/issues/443[#443] * Fixed some OpenTracing bridge functionalities that were not working when auto-instrumentation is disabled * Fixed an error occurring when ending an OpenTracing span before deactivating * Sending proper `null` for metrics that have a NaN value * Fixes JVM crash with Java 7 https://github.com/elastic/apm-agent-java/issues/458[#458] * Fixes an application deployment failure when using EclipseLink and `trace_methods` configuration https://github.com/elastic/apm-agent-java/issues/474[#474] [[release-notes-1.3.0]] ==== 1.3.0 - 2019/01/10 [float] ===== Features * The agent now collects system and JVM metrics https://github.com/elastic/apm-agent-java/pull/360[#360] * Add API methods `ElasticApm#startTransactionWithRemoteParent` and `Span#injectTraceHeaders` to allow for manual context propagation https://github.com/elastic/apm-agent-java/pull/396[#396]. * Added `trace_methods` configuration option which lets you define which methods in your project or 3rd party libraries should be traced. To create spans for all `public` methods of classes whose name ends in `Service` which are in a sub-package of `org.example.services` use this matcher: `public org.example.services.*.*Service#*` https://github.com/elastic/apm-agent-java/pull/398[#398] * Added span for `DispatcherServlet#render` https://github.com/elastic/apm-agent-java/pull/409[#409]. * Flush reporter on shutdown to make sure all recorded Spans are sent to the server before the program exits https://github.com/elastic/apm-agent-java/pull/397[#397] * Adds Kubernetes https://github.com/elastic/apm-agent-java/issues/383[#383] and Docker metadata to, enabling correlation with the Kibana Infra UI. * Improved error handling of the Servlet Async API https://github.com/elastic/apm-agent-java/issues/399[#399] * Support async API’s used with AsyncContext.start https://github.com/elastic/apm-agent-java/issues/388[#388] [float] ===== Bug Fixes * Fixing a potential memory leak when there is no connection with APM server * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 https://github.com/elastic/apm-agent-java/pull/401[#401] [[release-notes-1.2.0]] ==== 1.2.0 - 2018/12/19 [float] ===== Features * Added `capture_headers` configuration option. Set to `false` to disable capturing request and response headers. This will reduce the allocation rate of the agent and can save you network bandwidth and disk space. * Makes the API methods `addTag`, `setName`, `setType`, `setUser` and `setResult` fluent, so that calls can be chained. [float] ===== Bug Fixes * Catch all errors thrown within agent injected code * Enable public APIs and OpenTracing bridge to work properly in OSGi systems, fixes https://github.com/elastic/apm-agent-java/issues/362[this WildFly issue] * Remove module-info.java to enable agent working on early Tomcat 8.5 versions * Fix https://github.com/elastic/apm-agent-java/issues/371[async Servlet API issue] [[release-notes-1.1.0]] ==== 1.1.0 - 2018/11/28 [float] ===== Features * Some memory allocation improvements * Enabling bootdelegation for agent classes in Atlassian OSGI systems [float] ===== Bug Fixes * Update dsl-json which fixes a memory leak. See https://github.com/ngs-doo/dsl-json/pull/102[ngs-doo/dsl-json#102] for details. * Avoid `VerifyError`s by non instrumenting classes compiled for Java 4 or earlier * Enable APM Server URL configuration with path (fixes #339) * Reverse `system.hostname` and `system.platform` order sent to APM server [[release-notes-1.0.1]] ==== 1.0.1 - 2018/11/15 [float] ===== Bug Fixes * Fixes NoSuchMethodError CharBuffer.flip() which occurs when using the Elasticsearch RestClient and Java 7 or 8 {pull}313[#313] [[release-notes-1.0.0]] ==== 1.0.0 - 2018/11/14 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. [float] ===== Features * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Added `Transaction.isSampled()` and `Span.isSampled()` methods to the public API * Added `Transaction#setResult` to the public API {pull}293[#293] [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] * Capturing the username now properly works when using Spring security {pull}183[#183] [[release-notes-1.0.0.rc1]] ==== 1.0.0.RC1 - 2018/11/06 [float] ===== Breaking changes * Remove intake v1 support. This version requires APM Server 6.5.0+ which supports the intake api v2. Until the time the APM Server 6.5.0 is officially released, you can test with docker by pulling the APM Server image via `docker pull docker.elastic.co/apm/apm-server:6.5.0-SNAPSHOT`. * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Support for Distributed Tracing * Adds `@CaptureTransaction` and `@CaptureSpan` annotations which let you declaratively add custom transactions and spans. Note that it is required to configure the `application_packages` for this to work. See the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-annotation[documentation] for more information. * The public API now supports to activate a span on the current thread. This makes the span available via `ElasticApm#currentSpan()` Refer to the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-span-activate[documentation] for more details. * Capturing of Elasticsearch RestClient 5.0.2+ calls. Currently, the `*Async` methods are not supported, only their synchronous counterparts. * Added API methods to enable correlating the spans created from the JavaScrip Real User Monitoring agent with the Java agent transaction. More information can be found in the https://www.elastic.co/guide/en/apm/agent/java/master/public-api.html#api-ensure-parent-id[documentation]. * Microsecond accurate timestamps {pull}261[#261] * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [float] ===== Bug Fixes * Fix for situations where status code is reported as `200`, even though it actually was `500` {pull}225[#225] [[release-notes-0.8.x]] === Java Agent version 0.8.x [[release-notes-0.8.0]] ==== 0.8.0 [float] ===== Breaking changes * Wildcard patterns are case insensitive by default. Prepend `(?-i)` to make the matching case sensitive. [float] ===== Features * Wildcard patterns are now not limited to only one wildcard in the middle and can be arbitrarily complex now. Example: `*foo*bar*baz`. * Support for JAX-RS annotations. Transactions are named based on your resources (`ResourceClass#resourceMethod`). [[release-notes-0.7.x]] === Java Agent version 0.7.x [[release-notes-0.7.1]] ==== 0.7.1 - 2018/10/24 [float] ===== Bug Fixes * Avoid recycling transactions twice {pull}178[#178] [[release-notes-0.7.0]] ==== 0.7.0 - 2018/09/12 [float] ===== Breaking changes * Removed `ElasticApm.startSpan`. Spans can now only be created from their transactions via `Transaction#createSpan`. * `ElasticApm.startTransaction` and `Transaction#createSpan` don't activate the transaction and spans and are thus not available via `ElasticApm.activeTransaction` and `ElasticApm.activeSpan`. [float] ===== Features * Public API ** Add `Span#captureException` and `Transaction#captureException` to public API. `ElasticApm.captureException` is deprecated now. Use `ElasticApm.currentSpan().captureException(exception)` instead. ** Added `Transaction.getId` and `Span.getId` methods * Added support for async servlet requests * Added support for Payara/Glassfish * Incubating support for Apache HttpClient * Support for Spring RestTemplate * Added configuration options `use_path_as_transaction_name` and `url_groups`, which allow to use the URL path as the transaction name. As that could contain path parameters, like `/user/$userId` however, You can set the `url_groups` option to define a wildcard pattern, like `/user/*`, to group those paths together. This is especially helpful when using an unsupported Servlet API-based framework. * Support duration suffixes (`ms`, `s` and `m`) for duration configuration options. Not using the duration suffix logs out a deprecation warning and will not be supported in future versions. * Add ability to add multiple APM server URLs, which enables client-side load balancing. The configuration option `server_url` has been renamed to `server_urls` to reflect this change. However, `server_url` still works for backwards compatibility. * The configuration option `service_name` is now optional. It defaults to the main class name, the name of the executed jar file (removing the version number), or the application server name (for example `tomcat-application`). In a lot of cases, you will still want to set the `service_name` explicitly. But it helps getting started and seeing data easier, as there are no required configuration options anymore. In the future we will most likely determine more useful application names for Servlet API-based applications. ",12350,True,2630.458201712361,median "/****************************************************************************** * * Project: CPL - Common Portability Library * Purpose: Implement VSI large file api for Microsoft Azure Blob Storage * Author: Even Rouault, even.rouault at spatialys.com * ****************************************************************************** * Copyright (c) 2017-2018, Even Rouault * * 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 ""cpl_port.h"" #include ""cpl_http.h"" #include ""cpl_minixml.h"" #include ""cpl_time.h"" #include ""cpl_vsil_curl_priv.h"" #include ""cpl_vsil_curl_class.h"" #include #include #include #include #include #include ""cpl_azure.h"" CPL_CVSID(""$Id$"") #ifndef HAVE_CURL void VSIInstallAzureFileHandler( void ) { // Not supported } #else //! @cond Doxygen_Suppress #ifndef DOXYGEN_SKIP #define ENABLE_DEBUG 0 namespace cpl { const char GDAL_MARKER_FOR_DIR[] = "".gdal_marker_for_dir""; /************************************************************************/ /* VSIDIRAz */ /************************************************************************/ struct VSIDIRAz: public VSIDIR { CPLString osRootPath{}; int nRecurseDepth = 0; CPLString osNextMarker{}; std::vector> aoEntries{}; int nPos = 0; CPLString osBucket{}; CPLString osObjectKey{}; IVSIS3LikeFSHandler* poFS = nullptr; std::unique_ptr poHandleHelper{}; int nMaxFiles = 0; bool bCacheEntries = true; std::string m_osFilterPrefix{}; explicit VSIDIRAz(IVSIS3LikeFSHandler *poFSIn): poFS(poFSIn) {} VSIDIRAz(const VSIDIRAz&) = delete; VSIDIRAz& operator=(const VSIDIRAz&) = delete; const VSIDIREntry* NextDirEntry() override; bool IssueListDir(); bool AnalyseAzureFileList( const CPLString& osBaseURL, const char* pszXML ); void clear(); }; /************************************************************************/ /* clear() */ /************************************************************************/ void VSIDIRAz::clear() { osNextMarker.clear(); nPos = 0; aoEntries.clear(); } /************************************************************************/ /* AnalyseAzureFileList() */ /************************************************************************/ bool VSIDIRAz::AnalyseAzureFileList( const CPLString& osBaseURL, const char* pszXML) { #if DEBUG_VERBOSE CPLDebug(""AZURE"", ""%s"", pszXML); #endif CPLXMLNode* psTree = CPLParseXMLString(pszXML); if( psTree == nullptr ) return false; CPLXMLNode* psEnumerationResults = CPLGetXMLNode(psTree, ""=EnumerationResults""); bool bNonEmpty = false; if( psEnumerationResults ) { CPLString osPrefix = CPLGetXMLValue(psEnumerationResults, ""Prefix"", """"); if( osPrefix.endsWith(m_osFilterPrefix) ) { osPrefix.resize(osPrefix.size() - m_osFilterPrefix.size()); } CPLXMLNode* psBlobs = CPLGetXMLNode(psEnumerationResults, ""Blobs""); if( psBlobs == nullptr ) { psBlobs = CPLGetXMLNode(psEnumerationResults, ""Containers""); if( psBlobs != nullptr ) bNonEmpty = true; } // Count the number of occurrences of a path. Can be 1 or 2. 2 in the case // that both a filename and directory exist std::map aoNameCount; for(CPLXMLNode* psIter = psBlobs ? psBlobs->psChild : nullptr; psIter != nullptr; psIter = psIter->psNext ) { if( psIter->eType != CXT_Element ) continue; if( strcmp(psIter->pszValue, ""Blob"") == 0 ) { const char* pszKey = CPLGetXMLValue(psIter, ""Name"", nullptr); if( pszKey && strstr(pszKey, GDAL_MARKER_FOR_DIR) != nullptr ) { bNonEmpty = true; } else if( pszKey && strlen(pszKey) > osPrefix.size() ) { bNonEmpty = true; aoNameCount[pszKey + osPrefix.size()] ++; } } else if( strcmp(psIter->pszValue, ""BlobPrefix"") == 0 || strcmp(psIter->pszValue, ""Container"") == 0 ) { bNonEmpty = true; const char* pszKey = CPLGetXMLValue(psIter, ""Name"", nullptr); if( pszKey && strncmp(pszKey, osPrefix, osPrefix.size()) == 0 ) { CPLString osKey = pszKey; if( !osKey.empty() && osKey.back() == '/' ) osKey.resize(osKey.size()-1); if( osKey.size() > osPrefix.size() ) { aoNameCount[osKey.c_str() + osPrefix.size()] ++; } } } } for(CPLXMLNode* psIter = psBlobs ? psBlobs->psChild : nullptr; psIter != nullptr; psIter = psIter->psNext ) { if( psIter->eType != CXT_Element ) continue; if( strcmp(psIter->pszValue, ""Blob"") == 0 ) { const char* pszKey = CPLGetXMLValue(psIter, ""Name"", nullptr); if( pszKey && strstr(pszKey, GDAL_MARKER_FOR_DIR) != nullptr ) { if( nRecurseDepth < 0 ) { aoEntries.push_back( std::unique_ptr(new VSIDIREntry())); auto& entry = aoEntries.back(); entry->pszName = CPLStrdup(pszKey + osPrefix.size()); char* pszMarker = strstr(entry->pszName, GDAL_MARKER_FOR_DIR); if( pszMarker ) *pszMarker = '\\0'; entry->nMode = S_IFDIR; entry->bModeKnown = true; } } else if( pszKey && strlen(pszKey) > osPrefix.size() ) { aoEntries.push_back( std::unique_ptr(new VSIDIREntry())); auto& entry = aoEntries.back(); entry->pszName = CPLStrdup(pszKey + osPrefix.size()); entry->nSize = static_cast( CPLAtoGIntBig(CPLGetXMLValue(psIter, ""Properties.Content-Length"", ""0""))); entry->bSizeKnown = true; entry->nMode = S_IFREG; entry->bModeKnown = true; CPLString ETag = CPLGetXMLValue(psIter, ""Etag"", """"); if( !ETag.empty() ) { entry->papszExtra = CSLSetNameValue( entry->papszExtra, ""ETag"", ETag.c_str()); } int nYear, nMonth, nDay, nHour, nMinute, nSecond; if( CPLParseRFC822DateTime( CPLGetXMLValue(psIter, ""Properties.Last-Modified"", """"), &nYear, &nMonth, &nDay, &nHour, &nMinute, &nSecond, nullptr, nullptr ) ) { struct tm brokendowntime; brokendowntime.tm_year = nYear - 1900; brokendowntime.tm_mon = nMonth - 1; brokendowntime.tm_mday = nDay; brokendowntime.tm_hour = nHour; brokendowntime.tm_min = nMinute; brokendowntime.tm_sec = nSecond < 0 ? 0 : nSecond; entry->nMTime = CPLYMDHMSToUnixTime(&brokendowntime); entry->bMTimeKnown = true; } if( bCacheEntries ) { FileProp prop; prop.eExists = EXIST_YES; prop.bHasComputedFileSize = true; prop.fileSize = entry->nSize; prop.bIsDirectory = false; prop.mTime = static_cast(entry->nMTime); prop.ETag = ETag; prop.nMode = entry->nMode; CPLString osCachedFilename = osBaseURL + ""/"" + CPLAWSURLEncode(osPrefix, false) + CPLAWSURLEncode(entry->pszName, false); #if DEBUG_VERBOSE CPLDebug(""AZURE"", ""Cache %s"", osCachedFilename.c_str()); #endif poFS->SetCachedFileProp(osCachedFilename, prop); } } } else if( strcmp(psIter->pszValue, ""BlobPrefix"") == 0 || strcmp(psIter->pszValue, ""Container"") == 0 ) { const char* pszKey = CPLGetXMLValue(psIter, ""Name"", nullptr); if( pszKey && strncmp(pszKey, osPrefix, osPrefix.size()) == 0 ) { CPLString osKey = pszKey; if( !osKey.empty() && osKey.back() == '/' ) osKey.resize(osKey.size()-1); if( osKey.size() > osPrefix.size() ) { aoEntries.push_back( std::unique_ptr(new VSIDIREntry())); auto& entry = aoEntries.back(); entry->pszName = CPLStrdup(osKey.c_str() + osPrefix.size()); if( aoNameCount[entry->pszName] == 2 ) { // Add a / suffix to disambiguish the situation // Normally we don't suffix directories with /, but // we have no alternative here CPLString osTemp(entry->pszName); osTemp += '/'; CPLFree(entry->pszName); entry->pszName = CPLStrdup(osTemp); } entry->nMode = S_IFDIR; entry->bModeKnown = true; if( bCacheEntries ) { FileProp prop; prop.eExists = EXIST_YES; prop.bIsDirectory = true; prop.bHasComputedFileSize = true; prop.fileSize = 0; prop.mTime = 0; prop.nMode = entry->nMode; CPLString osCachedFilename = osBaseURL + ""/"" + CPLAWSURLEncode(osPrefix, false) + CPLAWSURLEncode(entry->pszName, false); #if DEBUG_VERBOSE CPLDebug(""AZURE"", ""Cache %s"", osCachedFilename.c_str()); #endif poFS->SetCachedFileProp(osCachedFilename, prop); } } } } if( nMaxFiles > 0 && aoEntries.size() > static_cast(nMaxFiles) ) break; } osNextMarker = CPLGetXMLValue(psEnumerationResults, ""NextMarker"", """"); } CPLDestroyXMLNode(psTree); return bNonEmpty; } /************************************************************************/ /* IssueListDir() */ /************************************************************************/ bool VSIDIRAz::IssueListDir() { WriteFuncStruct sWriteFuncData; const CPLString l_osNextMarker(osNextMarker); clear(); NetworkStatisticsFileSystem oContextFS(""/vsiaz/""); NetworkStatisticsAction oContextAction(""ListBucket""); CPLString osMaxKeys = CPLGetConfigOption(""AZURE_MAX_RESULTS"", """"); const int AZURE_SERVER_LIMIT_SINGLE_REQUEST = 5000; if( nMaxFiles > 0 && nMaxFiles < AZURE_SERVER_LIMIT_SINGLE_REQUEST && (osMaxKeys.empty() || nMaxFiles < atoi(osMaxKeys)) ) { osMaxKeys.Printf(""%d"", nMaxFiles); } poHandleHelper->ResetQueryParameters(); const CPLString osBaseURL(poHandleHelper->GetURLNoKVP()); CURL* hCurlHandle = curl_easy_init(); poHandleHelper->AddQueryParameter(""comp"", ""list""); if( !l_osNextMarker.empty() ) poHandleHelper->AddQueryParameter(""marker"", l_osNextMarker); if( !osMaxKeys.empty() ) poHandleHelper->AddQueryParameter(""maxresults"", osMaxKeys); if( !osBucket.empty() ) { poHandleHelper->AddQueryParameter(""restype"", ""container""); if( nRecurseDepth == 0 ) poHandleHelper->AddQueryParameter(""delimiter"", ""/""); if( !osObjectKey.empty() ) poHandleHelper->AddQueryParameter(""prefix"", osObjectKey + ""/"" + m_osFilterPrefix); else if( !m_osFilterPrefix.empty() ) poHandleHelper->AddQueryParameter(""prefix"", m_osFilterPrefix); } struct curl_slist* headers = VSICurlSetOptions(hCurlHandle, poHandleHelper->GetURL(), nullptr); headers = VSICurlMergeHeaders(headers, poHandleHelper->GetCurlHeaders(""GET"", headers)); curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, poFS, poHandleHelper.get()); NetworkStatisticsLogger::LogGET(sWriteFuncData.nSize); if( requestHelper.sWriteFuncData.pBuffer == nullptr) { curl_easy_cleanup(hCurlHandle); return false; } bool ret = false; if( response_code != 200 ) { CPLDebug(""AZURE"", ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); } else { ret = AnalyseAzureFileList( osBaseURL, requestHelper.sWriteFuncData.pBuffer ); } curl_easy_cleanup(hCurlHandle); return ret; } /************************************************************************/ /* NextDirEntry() */ /************************************************************************/ const VSIDIREntry* VSIDIRAz::NextDirEntry() { while( true ) { if( nPos < static_cast(aoEntries.size()) ) { auto& entry = aoEntries[nPos]; nPos ++; return entry.get(); } if( osNextMarker.empty() ) { return nullptr; } if( !IssueListDir() ) { return nullptr; } } } /************************************************************************/ /* VSIAzureFSHandler */ /************************************************************************/ class VSIAzureFSHandler final : public IVSIS3LikeFSHandler { CPL_DISALLOW_COPY_ASSIGN(VSIAzureFSHandler) protected: VSICurlHandle* CreateFileHandle( const char* pszFilename ) override; CPLString GetURLFromFilename( const CPLString& osFilename ) override; IVSIS3LikeHandleHelper* CreateHandleHelper( const char* pszURI, bool bAllowNoObject) override; char** GetFileList( const char *pszFilename, int nMaxFiles, bool* pbGotFileList ) override; void InvalidateRecursive( const CPLString& osDirnameIn ); int CopyObject( const char *oldpath, const char *newpath, CSLConstList papszMetadata ) override; int MkdirInternal( const char *pszDirname, long nMode, bool bDoStatCheck ) override; void ClearCache() override; public: VSIAzureFSHandler() = default; ~VSIAzureFSHandler() override = default; CPLString GetFSPrefix() const override { return ""/vsiaz/""; } const char* GetDebugKey() const override { return ""AZURE""; } VSIVirtualHandle *Open( const char *pszFilename, const char *pszAccess, bool bSetError, CSLConstList papszOptions ) override; int Unlink( const char *pszFilename ) override; int Mkdir( const char *, long ) override; int Rmdir( const char * ) override; int Stat( const char *pszFilename, VSIStatBufL *pStatBuf, int nFlags ) override; char** GetFileMetadata( const char * pszFilename, const char* pszDomain, CSLConstList papszOptions ) override; bool SetFileMetadata( const char * pszFilename, CSLConstList papszMetadata, const char* pszDomain, CSLConstList papszOptions ) override; const char* GetOptions() override; char* GetSignedURL( const char* pszFilename, CSLConstList papszOptions ) override; char** GetFileList( const char *pszFilename, int nMaxFiles, bool bCacheEntries, bool* pbGotFileList ); VSIDIR* OpenDir( const char *pszPath, int nRecurseDepth, const char* const *papszOptions) override; // Block list upload CPLString PutBlock(const CPLString& osFilename, int nPartNumber, const void* pabyBuffer, size_t nBufferSize, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay); bool PutBlockList(const CPLString& osFilename, const std::vector& aosBlockIds, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay); // Multipart upload (mapping of S3 interface to PutBlock/PutBlockList) bool SupportsParallelMultipartUpload() const override { return true; } CPLString InitiateMultipartUpload( const std::string& /* osFilename */ , IVSIS3LikeHandleHelper *, int /* nMaxRetry */, double /* dfRetryDelay */, CSLConstList /* papszOptions */) override { return ""dummy""; } CPLString UploadPart(const CPLString& osFilename, int nPartNumber, const std::string& /* osUploadID */, vsi_l_offset /* nPosition */, const void* pabyBuffer, size_t nBufferSize, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay) override { return PutBlock(osFilename, nPartNumber, pabyBuffer, nBufferSize, poS3HandleHelper, nMaxRetry, dfRetryDelay); } bool CompleteMultipart(const CPLString& osFilename, const CPLString& /* osUploadID */, const std::vector& aosEtags, vsi_l_offset /* nTotalSize */, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay) override { return PutBlockList(osFilename, aosEtags, poS3HandleHelper, nMaxRetry, dfRetryDelay); } bool AbortMultipart(const CPLString& /* osFilename */, const CPLString& /* osUploadID */, IVSIS3LikeHandleHelper * /*poS3HandleHelper */, int /* nMaxRetry */, double /* dfRetryDelay */) override { return true; } std::string GetStreamingFilename(const std::string& osFilename) const override; }; /************************************************************************/ /* VSIAzureHandle */ /************************************************************************/ class VSIAzureHandle final : public VSICurlHandle { CPL_DISALLOW_COPY_ASSIGN(VSIAzureHandle) std::unique_ptr m_poHandleHelper{}; protected: virtual struct curl_slist* GetCurlHeaders( const CPLString& osVerb, const struct curl_slist* psExistingHeaders ) override; virtual bool IsDirectoryFromExists( const char* pszVerb, int response_code ) override; public: VSIAzureHandle( VSIAzureFSHandler* poFS, const char* pszFilename, VSIAzureBlobHandleHelper* poHandleHelper); }; /************************************************************************/ /* CreateFileHandle() */ /************************************************************************/ VSICurlHandle* VSIAzureFSHandler::CreateFileHandle(const char* pszFilename) { VSIAzureBlobHandleHelper* poHandleHelper = VSIAzureBlobHandleHelper::BuildFromURI( pszFilename + GetFSPrefix().size(), GetFSPrefix() ); if( poHandleHelper == nullptr ) return nullptr; return new VSIAzureHandle(this, pszFilename, poHandleHelper); } /************************************************************************/ /* Stat() */ /************************************************************************/ int VSIAzureFSHandler::Stat( const char *pszFilename, VSIStatBufL *pStatBuf, int nFlags ) { if( !STARTS_WITH_CI(pszFilename, GetFSPrefix()) ) return -1; if( (nFlags & VSI_STAT_CACHE_ONLY) != 0 ) return VSICurlFilesystemHandlerBase::Stat(pszFilename, pStatBuf, nFlags); CPLString osFilename(pszFilename); if( (osFilename.find('/', GetFSPrefix().size()) == std::string::npos || osFilename.find('/', GetFSPrefix().size()) == osFilename.size() - 1) && CPLGetConfigOption(""AZURE_SAS"", nullptr) != nullptr ) { // On ""/vsiaz/container"", a HEAD or GET request fails to authenticate // when SAS is used, so use directory listing instead. char** papszRet = ReadDirInternal( osFilename, 100, nullptr ); int nRet = papszRet ? 0 : -1; if( nRet == 0 ) { pStatBuf->st_mtime = 0; pStatBuf->st_size = 0; pStatBuf->st_mode = S_IFDIR; FileProp cachedFileProp; GetCachedFileProp(GetURLFromFilename(osFilename), cachedFileProp); cachedFileProp.eExists = EXIST_YES; cachedFileProp.bIsDirectory = true; cachedFileProp.bHasComputedFileSize = true; SetCachedFileProp(GetURLFromFilename(osFilename), cachedFileProp); } CSLDestroy(papszRet); return nRet; } if( osFilename.find('/', GetFSPrefix().size()) == std::string::npos ) { osFilename += ""/""; } return VSICurlFilesystemHandlerBase::Stat(osFilename, pStatBuf, nFlags); } /************************************************************************/ /* GetFileMetadata() */ /************************************************************************/ char** VSIAzureFSHandler::GetFileMetadata( const char* pszFilename, const char* pszDomain, CSLConstList papszOptions ) { if( !STARTS_WITH_CI(pszFilename, GetFSPrefix()) ) return nullptr; if( pszDomain == nullptr || (!EQUAL(pszDomain, ""TAGS"") && !EQUAL(pszDomain, ""METADATA"")) ) { return VSICurlFilesystemHandlerBase::GetFileMetadata( pszFilename, pszDomain, papszOptions); } auto poHandleHelper = std::unique_ptr( CreateHandleHelper(pszFilename + GetFSPrefix().size(), false)); if( poHandleHelper == nullptr ) { return nullptr; } NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""GetFileMetadata""); bool bRetry; // coverity[tainted_data] double dfRetryDelay = CPLAtof(CPLGetConfigOption(""GDAL_HTTP_RETRY_DELAY"", CPLSPrintf(""%f"", CPL_HTTP_RETRY_DELAY))); const int nMaxRetry = atoi(CPLGetConfigOption(""GDAL_HTTP_MAX_RETRY"", CPLSPrintf(""%d"",CPL_HTTP_MAX_RETRY))); int nRetryCount = 0; bool bError = true; CPLStringList aosMetadata; do { bRetry = false; CURL* hCurlHandle = curl_easy_init(); if( EQUAL(pszDomain, ""METADATA"") ) poHandleHelper->AddQueryParameter(""comp"", ""metadata""); else poHandleHelper->AddQueryParameter(""comp"", ""tags""); struct curl_slist* headers = VSICurlSetOptions(hCurlHandle, poHandleHelper->GetURL(), nullptr); headers = VSICurlMergeHeaders(headers, poHandleHelper->GetCurlHeaders(""GET"", headers)); curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, this, poHandleHelper.get()); NetworkStatisticsLogger::LogGET(requestHelper.sWriteFuncData.nSize); if( response_code != 200 || requestHelper.sWriteFuncHeaderData.pBuffer == nullptr ) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), poHandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(GetDebugKey(), ""GetFileMetadata failed on %s: %s"", pszFilename, requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); } } else { if( EQUAL(pszDomain, ""METADATA"") ) { char** papszHeaders = CSLTokenizeString2(requestHelper.sWriteFuncHeaderData.pBuffer, ""\\r\\n"", 0); for( int i = 0; papszHeaders[i]; ++i ) { char* pszKey = nullptr; const char* pszValue = CPLParseNameValue(papszHeaders[i], &pszKey); // Content-Length is returned as 0 if( pszKey && pszValue && !EQUAL(pszKey, ""Content-Length"") ) { aosMetadata.SetNameValue(pszKey, pszValue); } CPLFree(pszKey); } CSLDestroy(papszHeaders); } else { CPLXMLNode* psXML = CPLParseXMLString(requestHelper.sWriteFuncData.pBuffer); if( psXML ) { CPLXMLNode* psTagSet = CPLGetXMLNode(psXML, ""=Tags.TagSet""); if( psTagSet ) { for( CPLXMLNode* psIter = psTagSet->psChild; psIter; psIter = psIter->psNext ) { if( psIter->eType == CXT_Element && strcmp(psIter->pszValue, ""Tag"") == 0 ) { CPLString osKey = CPLGetXMLValue(psIter, ""Key"", """"); CPLString osValue = CPLGetXMLValue(psIter, ""Value"", """"); aosMetadata.SetNameValue(osKey, osValue); } } } CPLDestroyXMLNode(psXML); } } bError = false; } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return bError ? nullptr : CSLDuplicate(aosMetadata.List()); } /************************************************************************/ /* SetFileMetadata() */ /************************************************************************/ bool VSIAzureFSHandler::SetFileMetadata( const char * pszFilename, CSLConstList papszMetadata, const char* pszDomain, CSLConstList /* papszOptions */ ) { if( !STARTS_WITH_CI(pszFilename, GetFSPrefix()) ) return false; if( pszDomain == nullptr || !(EQUAL(pszDomain, ""PROPERTIES"") || EQUAL(pszDomain, ""METADATA"") || EQUAL(pszDomain, ""TAGS"")) ) { CPLError(CE_Failure, CPLE_NotSupported, ""Only PROPERTIES, METADATA and TAGS domain are supported""); return false; } auto poHandleHelper = std::unique_ptr( CreateHandleHelper(pszFilename + GetFSPrefix().size(), false)); if( poHandleHelper == nullptr ) { return false; } NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""SetFileMetadata""); bool bRetry; // coverity[tainted_data] double dfRetryDelay = CPLAtof(CPLGetConfigOption(""GDAL_HTTP_RETRY_DELAY"", CPLSPrintf(""%f"", CPL_HTTP_RETRY_DELAY))); const int nMaxRetry = atoi(CPLGetConfigOption(""GDAL_HTTP_MAX_RETRY"", CPLSPrintf(""%d"",CPL_HTTP_MAX_RETRY))); int nRetryCount = 0; bool bRet = false; // Compose XML content for TAGS CPLString osXML; if( EQUAL(pszDomain, ""TAGS"") ) { CPLXMLNode* psXML = CPLCreateXMLNode(nullptr, CXT_Element, ""?xml""); CPLAddXMLAttributeAndValue(psXML, ""version"", ""1.0""); CPLAddXMLAttributeAndValue(psXML, ""encoding"", ""UTF-8""); CPLXMLNode* psTags = CPLCreateXMLNode(nullptr, CXT_Element, ""Tags""); psXML->psNext = psTags; CPLXMLNode* psTagSet = CPLCreateXMLNode(psTags, CXT_Element, ""TagSet""); for( int i = 0; papszMetadata && papszMetadata[i]; ++i ) { char* pszKey = nullptr; const char* pszValue = CPLParseNameValue(papszMetadata[i], &pszKey); if( pszKey && pszValue ) { CPLXMLNode* psTag = CPLCreateXMLNode(psTagSet, CXT_Element, ""Tag""); CPLCreateXMLElementAndValue(psTag, ""Key"", pszKey); CPLCreateXMLElementAndValue(psTag, ""Value"", pszValue); } CPLFree(pszKey); } char* pszXML = CPLSerializeXMLTree(psXML); osXML = pszXML; CPLFree(pszXML); CPLDestroyXMLNode(psXML); } do { bRetry = false; CURL* hCurlHandle = curl_easy_init(); if( EQUAL(pszDomain, ""PROPERTIES"") ) poHandleHelper->AddQueryParameter(""comp"", ""properties""); else if( EQUAL(pszDomain, ""METADATA"") ) poHandleHelper->AddQueryParameter(""comp"", ""metadata""); else poHandleHelper->AddQueryParameter(""comp"", ""tags""); curl_easy_setopt(hCurlHandle, CURLOPT_CUSTOMREQUEST, ""PUT""); if( !osXML.empty() ) { curl_easy_setopt(hCurlHandle, CURLOPT_POSTFIELDS, osXML.c_str() ); } struct curl_slist* headers = static_cast( CPLHTTPSetOptions(hCurlHandle, poHandleHelper->GetURL().c_str(), nullptr)); CPLStringList aosList; if( EQUAL(pszDomain, ""PROPERTIES"") || EQUAL(pszDomain, ""METADATA"") ) { for( CSLConstList papszIter = papszMetadata; papszIter && *papszIter; ++papszIter ) { char* pszKey = nullptr; const char* pszValue = CPLParseNameValue(*papszIter, &pszKey); if( pszKey && pszValue ) { char* pszHeader = CPLStrdup(CPLSPrintf(""%s: %s"", pszKey, pszValue)); aosList.AddStringDirectly(pszHeader); headers = curl_slist_append(headers, pszHeader); } CPLFree(pszKey); } } CPLString osContentLength; osContentLength.Printf(""Content-Length: %d"", static_cast(osXML.size())); headers = curl_slist_append(headers, osContentLength.c_str()); if( !osXML.empty() ) { headers = curl_slist_append(headers, ""Content-Type: application/xml; charset=UTF-8""); headers = VSICurlMergeHeaders(headers, poHandleHelper->GetCurlHeaders(""PUT"", headers, osXML.c_str(), osXML.size())); } else { headers = VSICurlMergeHeaders(headers, poHandleHelper->GetCurlHeaders(""PUT"", headers)); } curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers); NetworkStatisticsLogger::LogPUT(osXML.size()); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, this, poHandleHelper.get()); if( response_code != 200 && response_code != 204 ) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), poHandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(GetDebugKey(), ""SetFileMetadata on %s failed: %s"", pszFilename, requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); } } else { bRet = true; } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return bRet; } /************************************************************************/ /* GetStreamingFilename() */ /************************************************************************/ std::string VSIAzureFSHandler::GetStreamingFilename(const std::string& osFilename) const { if( STARTS_WITH(osFilename.c_str(), GetFSPrefix().c_str()) ) return ""/vsiaz_streaming/"" + osFilename.substr(GetFSPrefix().size()); return osFilename; } /************************************************************************/ /* VSIAzureWriteHandle */ /************************************************************************/ class VSIAzureWriteHandle final : public VSIAppendWriteHandle { CPL_DISALLOW_COPY_ASSIGN(VSIAzureWriteHandle) std::unique_ptr m_poHandleHelper{}; CPLStringList m_aosOptions{}; bool Send(bool bIsLastBlock) override; bool SendInternal(bool bInitOnly, bool bIsLastBlock); void InvalidateParentDirectory(); public: VSIAzureWriteHandle( VSIAzureFSHandler* poFS, const char* pszFilename, VSIAzureBlobHandleHelper* poHandleHelper, CSLConstList papszOptions ); virtual ~VSIAzureWriteHandle(); }; /************************************************************************/ /* GetAzureBufferSize() */ /************************************************************************/ int GetAzureBufferSize() { int nBufferSize; int nChunkSizeMB = atoi(CPLGetConfigOption(""VSIAZ_CHUNK_SIZE"", ""4"")); if( nChunkSizeMB <= 0 || nChunkSizeMB > 4 ) nBufferSize = 4 * 1024 * 1024; else nBufferSize = nChunkSizeMB * 1024 * 1024; // For testing only ! const char* pszChunkSizeBytes = CPLGetConfigOption(""VSIAZ_CHUNK_SIZE_BYTES"", nullptr); if( pszChunkSizeBytes ) nBufferSize = atoi(pszChunkSizeBytes); if( nBufferSize <= 0 || nBufferSize > 4 * 1024 * 1024 ) nBufferSize = 4 * 1024 * 1024; return nBufferSize; } /************************************************************************/ /* VSIAzureWriteHandle() */ /************************************************************************/ VSIAzureWriteHandle::VSIAzureWriteHandle( VSIAzureFSHandler* poFS, const char* pszFilename, VSIAzureBlobHandleHelper* poHandleHelper, CSLConstList papszOptions) : VSIAppendWriteHandle(poFS, poFS->GetFSPrefix(), pszFilename, GetAzureBufferSize()), m_poHandleHelper(poHandleHelper), m_aosOptions(papszOptions) { } /************************************************************************/ /* ~VSIAzureWriteHandle() */ /************************************************************************/ VSIAzureWriteHandle::~VSIAzureWriteHandle() { Close(); } /************************************************************************/ /* InvalidateParentDirectory() */ /************************************************************************/ void VSIAzureWriteHandle::InvalidateParentDirectory() { m_poFS->InvalidateCachedData( m_poHandleHelper->GetURLNoKVP().c_str() ); CPLString osFilenameWithoutSlash(m_osFilename); if( !osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/' ) osFilenameWithoutSlash.resize( osFilenameWithoutSlash.size() - 1 ); m_poFS->InvalidateDirContent( CPLGetDirname(osFilenameWithoutSlash) ); } /************************************************************************/ /* Send() */ /************************************************************************/ bool VSIAzureWriteHandle::Send(bool bIsLastBlock) { if( !bIsLastBlock ) { CPLAssert( m_nBufferOff == m_nBufferSize ); if( m_nCurOffset == static_cast(m_nBufferSize) ) { // First full buffer ? Then create the blob empty if( !SendInternal( true, false ) ) return false; } } return SendInternal( false, bIsLastBlock ); } /************************************************************************/ /* SendInternal() */ /************************************************************************/ bool VSIAzureWriteHandle::SendInternal(bool bInitOnly, bool bIsLastBlock) { NetworkStatisticsFileSystem oContextFS(""/vsiaz/""); NetworkStatisticsFile oContextFile(m_osFilename); NetworkStatisticsAction oContextAction(""Write""); bool bSuccess = true; const bool bSingleBlock = bIsLastBlock && ( m_nCurOffset <= static_cast(m_nBufferSize) ); // coverity[tainted_data] const int nMaxRetry = atoi(CPLGetConfigOption(""GDAL_HTTP_MAX_RETRY"", CPLSPrintf(""%d"",CPL_HTTP_MAX_RETRY))); // coverity[tainted_data] double dfRetryDelay = CPLAtof(CPLGetConfigOption(""GDAL_HTTP_RETRY_DELAY"", CPLSPrintf(""%f"", CPL_HTTP_RETRY_DELAY))); int nRetryCount = 0; bool bHasAlreadyHandled409 = false; bool bRetry; do { bRetry = false; m_nBufferOffReadCallback = 0; CURL* hCurlHandle = curl_easy_init(); m_poHandleHelper->ResetQueryParameters(); if( !bSingleBlock && !bInitOnly ) { m_poHandleHelper->AddQueryParameter(""comp"", ""appendblock""); } curl_easy_setopt(hCurlHandle, CURLOPT_UPLOAD, 1L); curl_easy_setopt(hCurlHandle, CURLOPT_READFUNCTION, ReadCallBackBuffer); curl_easy_setopt(hCurlHandle, CURLOPT_READDATA, static_cast(this)); struct curl_slist* headers = static_cast( CPLHTTPSetOptions(hCurlHandle, m_poHandleHelper->GetURL().c_str(), nullptr)); headers = VSICurlSetCreationHeadersFromOptions(headers, m_aosOptions.List(), m_osFilename.c_str()); CPLString osContentLength; // leave it in this scope if( bSingleBlock ) { curl_easy_setopt(hCurlHandle, CURLOPT_INFILESIZE, m_nBufferOff); if( m_nBufferOff ) headers = curl_slist_append(headers, ""Expect: 100-continue""); osContentLength.Printf(""Content-Length: %d"", m_nBufferOff); headers = curl_slist_append(headers, osContentLength.c_str()); headers = curl_slist_append(headers, ""x-ms-blob-type: BlockBlob""); } else if( bInitOnly ) { curl_easy_setopt(hCurlHandle, CURLOPT_INFILESIZE, 0); headers = curl_slist_append(headers, ""Content-Length: 0""); headers = curl_slist_append(headers, ""x-ms-blob-type: AppendBlob""); } else { curl_easy_setopt(hCurlHandle, CURLOPT_INFILESIZE, m_nBufferOff); osContentLength.Printf(""Content-Length: %d"", m_nBufferOff); headers = curl_slist_append(headers, osContentLength.c_str()); headers = curl_slist_append(headers, ""x-ms-blob-type: AppendBlob""); CPLString osAppendPos; vsi_l_offset nStartOffset = m_nCurOffset - m_nBufferOff; osAppendPos.Printf(""x-ms-blob-condition-appendpos: "" CPL_FRMT_GUIB, nStartOffset); headers = curl_slist_append(headers, osAppendPos.c_str()); } headers = VSICurlMergeHeaders(headers, m_poHandleHelper->GetCurlHeaders(""PUT"", headers)); curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, m_poFS, m_poHandleHelper.get()); NetworkStatisticsLogger::LogPUT(m_nBufferOff); if( !bHasAlreadyHandled409 && response_code == 409 ) { bHasAlreadyHandled409 = true; CPLDebug(cpl::down_cast(m_poFS)->GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); // The blob type is invalid for this operation // Delete the file, and retry if( cpl::down_cast(m_poFS)-> DeleteObject(m_osFilename) == 0 ) { bRetry = true; } } else if( response_code != 201 ) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), m_poHandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(cpl::down_cast(m_poFS)->GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); CPLError(CE_Failure, CPLE_AppDefined, ""PUT of %s failed"", m_osFilename.c_str()); bSuccess = false; } } else { InvalidateParentDirectory(); } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return bSuccess; } /************************************************************************/ /* ClearCache() */ /************************************************************************/ void VSIAzureFSHandler::ClearCache() { IVSIS3LikeFSHandler::ClearCache(); VSIAzureBlobHandleHelper::ClearCache(); } /************************************************************************/ /* Open() */ /************************************************************************/ VSIVirtualHandle* VSIAzureFSHandler::Open( const char *pszFilename, const char *pszAccess, bool bSetError, CSLConstList papszOptions ) { if( !STARTS_WITH_CI(pszFilename, GetFSPrefix()) ) return nullptr; if( strchr(pszAccess, 'w') != nullptr || strchr(pszAccess, 'a') != nullptr ) { if( strchr(pszAccess, '+') != nullptr && !CPLTestBool(CPLGetConfigOption(""CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE"", ""NO"")) ) { CPLError(CE_Failure, CPLE_AppDefined, ""w+ not supported for /vsiaz, unless "" ""CPL_VSIL_USE_TEMP_FILE_FOR_RANDOM_WRITE is set to YES""); errno = EACCES; return nullptr; } VSIAzureBlobHandleHelper* poHandleHelper = VSIAzureBlobHandleHelper::BuildFromURI(pszFilename + GetFSPrefix().size(), GetFSPrefix().c_str()); if( poHandleHelper == nullptr ) return nullptr; auto poHandle = new VSIAzureWriteHandle(this, pszFilename, poHandleHelper, papszOptions); if( strchr(pszAccess, '+') != nullptr) { return VSICreateUploadOnCloseFile(poHandle); } return poHandle; } return VSICurlFilesystemHandlerBase::Open(pszFilename, pszAccess, bSetError, papszOptions); } /************************************************************************/ /* GetURLFromFilename() */ /************************************************************************/ CPLString VSIAzureFSHandler::GetURLFromFilename( const CPLString& osFilename ) { CPLString osFilenameWithoutPrefix = osFilename.substr(GetFSPrefix().size()); VSIAzureBlobHandleHelper* poHandleHelper = VSIAzureBlobHandleHelper::BuildFromURI( osFilenameWithoutPrefix, GetFSPrefix() ); if( poHandleHelper == nullptr ) return CPLString(); CPLString osURL( poHandleHelper->GetURLNoKVP() ); delete poHandleHelper; return osURL; } /************************************************************************/ /* CreateHandleHelper() */ /************************************************************************/ IVSIS3LikeHandleHelper* VSIAzureFSHandler::CreateHandleHelper(const char* pszURI, bool) { return VSIAzureBlobHandleHelper::BuildFromURI(pszURI, GetFSPrefix().c_str()); } /************************************************************************/ /* InvalidateRecursive() */ /************************************************************************/ void VSIAzureFSHandler::InvalidateRecursive( const CPLString& osDirnameIn ) { // As Azure directories disappear as soon there is no remaining file // we may need to invalidate the whole hierarchy CPLString osDirname(osDirnameIn); while( osDirname.size() > GetFSPrefix().size() ) { InvalidateDirContent(osDirname); InvalidateCachedData( GetURLFromFilename(osDirname) ); osDirname = CPLGetDirname(osDirname); } } /************************************************************************/ /* Unlink() */ /************************************************************************/ int VSIAzureFSHandler::Unlink( const char *pszFilename ) { int ret = IVSIS3LikeFSHandler::Unlink(pszFilename); if( ret != 0 ) return ret; InvalidateRecursive(CPLGetDirname(pszFilename)); return 0; } /************************************************************************/ /* Mkdir() */ /************************************************************************/ int VSIAzureFSHandler::MkdirInternal( const char *pszDirname, long /* nMode */, bool bDoStatCheck ) { if( !STARTS_WITH_CI(pszDirname, GetFSPrefix()) ) return -1; NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""Mkdir""); CPLString osDirname(pszDirname); if( !osDirname.empty() && osDirname.back() != '/' ) osDirname += ""/""; if( bDoStatCheck ) { VSIStatBufL sStat; if( VSIStatL(osDirname, &sStat) == 0 && sStat.st_mode == S_IFDIR ) { CPLDebug(GetDebugKey(), ""Directory %s already exists"", osDirname.c_str()); errno = EEXIST; return -1; } } CPLString osDirnameWithoutEndSlash(osDirname); osDirnameWithoutEndSlash.resize( osDirnameWithoutEndSlash.size() - 1 ); InvalidateCachedData( GetURLFromFilename(osDirname) ); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash) ); InvalidateDirContent( CPLGetDirname(osDirnameWithoutEndSlash) ); VSILFILE* fp = VSIFOpenL((osDirname + GDAL_MARKER_FOR_DIR).c_str(), ""wb""); if( fp != nullptr ) { CPLErrorReset(); VSIFCloseL(fp); return CPLGetLastErrorType() == CPLE_None ? 0 : -1; } else { return -1; } } int VSIAzureFSHandler::Mkdir( const char * pszDirname, long nMode ) { return MkdirInternal(pszDirname, nMode, true); } /************************************************************************/ /* Rmdir() */ /************************************************************************/ int VSIAzureFSHandler::Rmdir( const char * pszDirname ) { if( !STARTS_WITH_CI(pszDirname, GetFSPrefix()) ) return -1; NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""Rmdir""); CPLString osDirname(pszDirname); if( !osDirname.empty() && osDirname.back() != '/' ) osDirname += ""/""; VSIStatBufL sStat; if( VSIStatL(osDirname, &sStat) != 0 ) { InvalidateCachedData( GetURLFromFilename(osDirname.substr(0, osDirname.size() - 1)) ); // The directory might have not been created by GDAL, and thus lacking the // GDAL marker file, so do not turn non-existence as an error return 0; } else if( sStat.st_mode != S_IFDIR ) { CPLDebug(GetDebugKey(), ""%s is not a directory"", pszDirname); errno = ENOTDIR; return -1; } char** papszFileList = ReadDirEx(osDirname, 1); bool bEmptyDir = (papszFileList != nullptr && EQUAL(papszFileList[0], ""."") && papszFileList[1] == nullptr); CSLDestroy(papszFileList); if( !bEmptyDir ) { CPLDebug(GetDebugKey(), ""%s is not empty"", pszDirname); errno = ENOTEMPTY; return -1; } CPLString osDirnameWithoutEndSlash(osDirname); osDirnameWithoutEndSlash.resize( osDirnameWithoutEndSlash.size() - 1 ); InvalidateCachedData( GetURLFromFilename(osDirname) ); InvalidateCachedData( GetURLFromFilename(osDirnameWithoutEndSlash) ); InvalidateRecursive( CPLGetDirname(osDirnameWithoutEndSlash) ); if( osDirnameWithoutEndSlash.find('/', GetFSPrefix().size()) == std::string::npos ) { CPLDebug(GetDebugKey(), ""%s is a container"", pszDirname); errno = ENOTDIR; return -1; } if( DeleteObject((osDirname + GDAL_MARKER_FOR_DIR).c_str()) == 0 ) return 0; // The directory might have not been created by GDAL, and thus lacking the // GDAL marker file, so check if is there, and if not, return success. if( VSIStatL(osDirname, &sStat) != 0 ) return 0; return -1; } /************************************************************************/ /* CopyObject() */ /************************************************************************/ int VSIAzureFSHandler::CopyObject( const char *oldpath, const char *newpath, CSLConstList /* papszMetadata */ ) { NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""CopyObject""); CPLString osTargetNameWithoutPrefix = newpath + GetFSPrefix().size(); auto poS3HandleHelper = std::unique_ptr( CreateHandleHelper(osTargetNameWithoutPrefix, false)); if( poS3HandleHelper == nullptr ) { return -1; } CPLString osSourceNameWithoutPrefix = oldpath + GetFSPrefix().size(); auto poS3HandleHelperSource = std::unique_ptr( CreateHandleHelper(osSourceNameWithoutPrefix, false)); if( poS3HandleHelperSource == nullptr ) { return -1; } CPLString osSourceHeader(""x-ms-copy-source: ""); osSourceHeader += poS3HandleHelperSource->GetURLNoKVP(); int nRet = 0; bool bRetry; const int nMaxRetry = atoi(CPLGetConfigOption(""GDAL_HTTP_MAX_RETRY"", CPLSPrintf(""%d"",CPL_HTTP_MAX_RETRY))); // coverity[tainted_data] double dfRetryDelay = CPLAtof(CPLGetConfigOption(""GDAL_HTTP_RETRY_DELAY"", CPLSPrintf(""%f"", CPL_HTTP_RETRY_DELAY))); int nRetryCount = 0; do { bRetry = false; CURL* hCurlHandle = curl_easy_init(); curl_easy_setopt(hCurlHandle, CURLOPT_CUSTOMREQUEST, ""PUT""); struct curl_slist* headers = static_cast( CPLHTTPSetOptions(hCurlHandle, poS3HandleHelper->GetURL().c_str(), nullptr)); headers = curl_slist_append(headers, osSourceHeader.c_str()); headers = VSICurlSetContentTypeFromExt(headers, newpath); headers = curl_slist_append(headers, ""Content-Length: 0""); headers = VSICurlMergeHeaders(headers, poS3HandleHelper->GetCurlHeaders(""PUT"", headers)); curl_easy_setopt(hCurlHandle, CURLOPT_HTTPHEADER, headers); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, this, poS3HandleHelper.get()); NetworkStatisticsLogger::LogPUT(0); if( response_code != 202) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), poS3HandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); CPLError(CE_Failure, CPLE_AppDefined, ""Copy of %s to %s failed"", oldpath, newpath); nRet = -1; } } else { InvalidateCachedData(poS3HandleHelper->GetURLNoKVP().c_str()); CPLString osFilenameWithoutSlash(newpath); if( !osFilenameWithoutSlash.empty() && osFilenameWithoutSlash.back() == '/' ) osFilenameWithoutSlash.resize( osFilenameWithoutSlash.size() - 1 ); InvalidateDirContent( CPLGetDirname(osFilenameWithoutSlash) ); } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return nRet; } /************************************************************************/ /* PutBlock() */ /************************************************************************/ CPLString VSIAzureFSHandler::PutBlock(const CPLString& osFilename, int nPartNumber, const void* pabyBuffer, size_t nBufferSize, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay) { NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsFile oContextFile(osFilename); NetworkStatisticsAction oContextAction(""PutBlock""); bool bRetry; int nRetryCount = 0; CPLString osBlockId; osBlockId.Printf(""%012d"", nPartNumber); CPLString osContentLength; osContentLength.Printf(""Content-Length: %d"", static_cast(nBufferSize)); bool bHasAlreadyHandled409 = false; do { bRetry = false; poS3HandleHelper->AddQueryParameter(""comp"", ""block""); poS3HandleHelper->AddQueryParameter(""blockid"", osBlockId); CURL* hCurlHandle = curl_easy_init(); curl_easy_setopt(hCurlHandle, CURLOPT_UPLOAD, 1L); curl_easy_setopt(hCurlHandle, CURLOPT_READFUNCTION, PutData::ReadCallBackBuffer); PutData putData; putData.pabyData = static_cast(pabyBuffer); putData.nOff = 0; putData.nTotalSize = nBufferSize; curl_easy_setopt(hCurlHandle, CURLOPT_READDATA, &putData); curl_easy_setopt(hCurlHandle, CURLOPT_INFILESIZE, nBufferSize); struct curl_slist* headers = static_cast( CPLHTTPSetOptions(hCurlHandle, poS3HandleHelper->GetURL().c_str(), nullptr)); headers = curl_slist_append(headers, osContentLength.c_str()); headers = VSICurlMergeHeaders(headers, poS3HandleHelper->GetCurlHeaders(""PUT"", headers, pabyBuffer, nBufferSize)); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, this, poS3HandleHelper); NetworkStatisticsLogger::LogPUT(nBufferSize); if( !bHasAlreadyHandled409 && response_code == 409 ) { bHasAlreadyHandled409 = true; CPLDebug(GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); // The blob type is invalid for this operation // Delete the file, and retry if( DeleteObject(osFilename) == 0 ) { bRetry = true; } } else if( (response_code != 200 && response_code != 201) || requestHelper.sWriteFuncHeaderData.pBuffer == nullptr ) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), poS3HandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); CPLError(CE_Failure, CPLE_AppDefined, ""PutBlock(%d) of %s failed"", nPartNumber, osFilename.c_str()); osBlockId.clear(); } } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return osBlockId; } /************************************************************************/ /* PutBlockList() */ /************************************************************************/ bool VSIAzureFSHandler::PutBlockList(const CPLString& osFilename, const std::vector& aosBlockIds, IVSIS3LikeHandleHelper *poS3HandleHelper, int nMaxRetry, double dfRetryDelay) { bool bSuccess = true; NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsFile oContextFile(osFilename); NetworkStatisticsAction oContextAction(""PutBlockList""); CPLString osXML = ""\\n\\n""; for( const auto& osBlockId: aosBlockIds ) { osXML += """" + osBlockId + ""\\n""; } osXML += ""\\n""; CPLString osContentLength; osContentLength.Printf(""Content-Length: %d"", static_cast(osXML.size())); int nRetryCount = 0; bool bRetry; do { bRetry = false; poS3HandleHelper->AddQueryParameter(""comp"", ""blocklist""); PutData putData; putData.pabyData = reinterpret_cast(osXML.data()); putData.nOff = 0; putData.nTotalSize = osXML.size(); CURL* hCurlHandle = curl_easy_init(); curl_easy_setopt(hCurlHandle, CURLOPT_UPLOAD, 1L); curl_easy_setopt(hCurlHandle, CURLOPT_READFUNCTION, PutData::ReadCallBackBuffer); curl_easy_setopt(hCurlHandle, CURLOPT_READDATA, &putData); curl_easy_setopt(hCurlHandle, CURLOPT_INFILESIZE, static_cast(osXML.size())); curl_easy_setopt(hCurlHandle, CURLOPT_CUSTOMREQUEST, ""PUT""); struct curl_slist* headers = static_cast( CPLHTTPSetOptions(hCurlHandle, poS3HandleHelper->GetURL().c_str(), nullptr)); headers = curl_slist_append(headers, osContentLength.c_str()); headers = VSICurlMergeHeaders(headers, poS3HandleHelper->GetCurlHeaders(""PUT"", headers, osXML.c_str(), osXML.size())); CurlRequestHelper requestHelper; const long response_code = requestHelper.perform(hCurlHandle, headers, this, poS3HandleHelper); NetworkStatisticsLogger::LogPUT(osXML.size()); if( response_code != 201 ) { // Look if we should attempt a retry const double dfNewRetryDelay = CPLHTTPGetNewRetryDelay( static_cast(response_code), dfRetryDelay, requestHelper.sWriteFuncHeaderData.pBuffer, requestHelper.szCurlErrBuf); if( dfNewRetryDelay > 0 && nRetryCount < nMaxRetry ) { CPLError(CE_Warning, CPLE_AppDefined, ""HTTP error code: %d - %s. "" ""Retrying again in %.1f secs"", static_cast(response_code), poS3HandleHelper->GetURL().c_str(), dfRetryDelay); CPLSleep(dfRetryDelay); dfRetryDelay = dfNewRetryDelay; nRetryCount++; bRetry = true; } else { CPLDebug(GetDebugKey(), ""%s"", requestHelper.sWriteFuncData.pBuffer ? requestHelper.sWriteFuncData.pBuffer : ""(null)""); CPLError(CE_Failure, CPLE_AppDefined, ""PutBlockList of %s failed"", osFilename.c_str()); bSuccess = false; } } curl_easy_cleanup(hCurlHandle); } while( bRetry ); return bSuccess; } /************************************************************************/ /* GetFileList() */ /************************************************************************/ char** VSIAzureFSHandler::GetFileList( const char *pszDirname, int nMaxFiles, bool* pbGotFileList ) { return GetFileList(pszDirname, nMaxFiles, true, pbGotFileList); } char** VSIAzureFSHandler::GetFileList( const char *pszDirname, int nMaxFiles, bool bCacheEntries, bool* pbGotFileList ) { if( ENABLE_DEBUG ) CPLDebug(GetDebugKey(), ""GetFileList(%s)"" , pszDirname); *pbGotFileList = false; char** papszOptions = CSLSetNameValue(nullptr, ""MAXFILES"", CPLSPrintf(""%d"", nMaxFiles)); papszOptions = CSLSetNameValue(papszOptions, ""CACHE_ENTRIES"", bCacheEntries ? ""YES"" : ""NO""); auto dir = OpenDir(pszDirname, 0, papszOptions); CSLDestroy(papszOptions); if( !dir ) { return nullptr; } CPLStringList aosFileList; while( true ) { auto entry = dir->NextDirEntry(); if( !entry ) { break; } aosFileList.AddString(entry->pszName); if( nMaxFiles > 0 && aosFileList.size() >= nMaxFiles ) break; } delete dir; *pbGotFileList = true; return aosFileList.StealList(); } /************************************************************************/ /* GetOptions() */ /************************************************************************/ const char* VSIAzureFSHandler::GetOptions() { static CPLString osOptions( CPLString("""") + "" ""); return osOptions.c_str(); } /************************************************************************/ /* GetSignedURL() */ /************************************************************************/ char* VSIAzureFSHandler::GetSignedURL(const char* pszFilename, CSLConstList papszOptions ) { if( !STARTS_WITH_CI(pszFilename, GetFSPrefix()) ) return nullptr; VSIAzureBlobHandleHelper* poHandleHelper = VSIAzureBlobHandleHelper::BuildFromURI(pszFilename + GetFSPrefix().size(), GetFSPrefix().c_str(), papszOptions); if( poHandleHelper == nullptr ) { return nullptr; } CPLString osRet(poHandleHelper->GetSignedURL(papszOptions)); delete poHandleHelper; return CPLStrdup(osRet); } /************************************************************************/ /* OpenDir() */ /************************************************************************/ VSIDIR* VSIAzureFSHandler::OpenDir( const char *pszPath, int nRecurseDepth, const char* const *papszOptions) { if( nRecurseDepth > 0) { return VSIFilesystemHandler::OpenDir(pszPath, nRecurseDepth, papszOptions); } if( !STARTS_WITH_CI(pszPath, GetFSPrefix()) ) return nullptr; NetworkStatisticsFileSystem oContextFS(GetFSPrefix()); NetworkStatisticsAction oContextAction(""OpenDir""); CPLString osDirnameWithoutPrefix = pszPath + GetFSPrefix().size(); if( !osDirnameWithoutPrefix.empty() && osDirnameWithoutPrefix.back() == '/' ) { osDirnameWithoutPrefix.resize(osDirnameWithoutPrefix.size()-1); } CPLString osBucket(osDirnameWithoutPrefix); CPLString osObjectKey; size_t nSlashPos = osDirnameWithoutPrefix.find('/'); if( nSlashPos != std::string::npos ) { osBucket = osDirnameWithoutPrefix.substr(0, nSlashPos); osObjectKey = osDirnameWithoutPrefix.substr(nSlashPos+1); } auto poHandleHelper = std::unique_ptr( CreateHandleHelper(osBucket, true)); if( poHandleHelper == nullptr ) { return nullptr; } VSIDIRAz* dir = new VSIDIRAz(this); dir->nRecurseDepth = nRecurseDepth; dir->poFS = this; dir->poHandleHelper = std::move(poHandleHelper); dir->osBucket = osBucket; dir->osObjectKey = osObjectKey; dir->nMaxFiles = atoi(CSLFetchNameValueDef(papszOptions, ""MAXFILES"", ""0"")); dir->bCacheEntries = CPLTestBool( CSLFetchNameValueDef(papszOptions, ""CACHE_ENTRIES"", ""YES"")); dir->m_osFilterPrefix = CSLFetchNameValueDef(papszOptions, ""PREFIX"", """"); if( !dir->IssueListDir() ) { delete dir; return nullptr; } return dir; } /************************************************************************/ /* VSIAzureHandle() */ /************************************************************************/ VSIAzureHandle::VSIAzureHandle( VSIAzureFSHandler* poFSIn, const char* pszFilename, VSIAzureBlobHandleHelper* poHandleHelper ) : VSICurlHandle(poFSIn, pszFilename, poHandleHelper->GetURLNoKVP()), m_poHandleHelper(poHandleHelper) { m_osQueryString = poHandleHelper->GetSASQueryString(); } /************************************************************************/ /* GetCurlHeaders() */ /************************************************************************/ struct curl_slist* VSIAzureHandle::GetCurlHeaders( const CPLString& osVerb, const struct curl_slist* psExistingHeaders ) { return m_poHandleHelper->GetCurlHeaders( osVerb, psExistingHeaders ); } /************************************************************************/ /* IsDirectoryFromExists() */ /************************************************************************/ bool VSIAzureHandle::IsDirectoryFromExists( const char* /*pszVerb*/, int response_code ) { if( response_code != 404 ) return false; CPLString osDirname(m_osFilename); if( osDirname.size() > poFS->GetFSPrefix().size() && osDirname.back() == '/' ) osDirname.resize(osDirname.size() - 1); bool bIsDir; if( poFS->ExistsInCacheDirList(osDirname, &bIsDir) ) return bIsDir; bool bGotFileList = false; char** papszDirContent = reinterpret_cast(poFS) ->GetFileList( osDirname, 1, false, &bGotFileList ); CSLDestroy(papszDirContent); return bGotFileList; } } /* end of namespace cpl */ #endif // DOXYGEN_SKIP //! @endcond /************************************************************************/ /* VSIInstallAzureFileHandler() */ /************************************************************************/ /*! \\brief Install /vsiaz/ Microsoft Azure Blob file system handler (requires libcurl) \\verbatim embed:rst See :ref:`/vsiaz/ documentation ` \\endverbatim @since GDAL 2.3 */ void VSIInstallAzureFileHandler( void ) { VSIFileManager::InstallHandler( ""/vsiaz/"", new cpl::VSIAzureFSHandler ); } #endif /* HAVE_CURL */ ",16131,True,3356.4041908195436,median "[[Construction-package-dd]] === Construction [cols=""1,4"",frame=none,grid=none] |=== |{nbsp}{nbsp}{nbsp}{nbsp}Description: | The Construction module supports representation of key elements of different types of constructions. These key elements include construction surfaces (e.g floor and ceiling), windows and doors, constructive elements (e.g. beams and slabs), installations, and furniture. |{nbsp}{nbsp}{nbsp}{nbsp}Parent Package: | CityGML |{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: | «ApplicationSchema» |=== ==== Classes [[AbstractConstruction-section]] [cols=""1a""] |=== |*AbstractConstruction* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractConstruction is the abstract superclass for objects that are manufactured by humans from construction materials, are connected to earth, and are intended to be permanent. A connection with the ground also exists when the construction rests by its own weight on the ground or is moveable limited on stationary rails or if the construction is intended to be used mainly stationary. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} boundary !<> [*] !Relates to the surfaces that bound the construction. This relation is inherited from the Core module. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} conditionOfConstruction !<> [0..1] !Indicates the life-cycle status of the construction. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} dateOfConstruction !<> [0..1] !Indicates the date at which the construction was completed. !{set:cellbgcolor:#FFFFFF} dateOfDemolition !<> [0..1] !Indicates the date at which the construction was demolished. !{set:cellbgcolor:#FFFFFF} constructionEvent !<> [0..*] !Describes specific events in the life-time of the construction. !{set:cellbgcolor:#FFFFFF} elevation !<> [0..*] !Specifies qualified elevations of the construction in relation to a well-defined surface which is commonly taken as origin (e.g. geoid or water level). [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} height !<> [0..*] !Specifies qualified heights of the construction above ground or below ground. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} occupancy !<> [0..*] !Provides qualified information on the residency of persons, animals, or other moveable objects in the construction. !{set:cellbgcolor:#FFFFFF} adeOfAbstractConstruction !<> [0..*] !Augments AbstractConstruction with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractConstructionSurface-section]] [cols=""1a""] |=== |*AbstractConstructionSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractConstructionSurface is the abstract superclass for different kinds of surfaces that bound a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} fillingSurface !<> [*] !Relates to the surfaces that seal the openings of the construction surface. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfAbstractConstructionSurface !<> [0..*] !Augments AbstractConstructionSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractConstructiveElement-section]] [cols=""1a""] |=== |*AbstractConstructiveElement* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractConstructiveElement is the abstract superclass for the representation of volumetric elements of a construction. Examples are walls, beams, slabs. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} boundary !<> [*] !Relates to the surfaces that bound the constructive element. This relation is inherited from the Core module. !{set:cellbgcolor:#FFFFFF} filling !<> [*] !Relates to the elements that fill the opening of the constructive element. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} isStructuralElement !<> [0..1] !Indicates whether the constructive element is essential from a structural point of view. A structural element cannot be omitted without collapsing of the construction. Examples are pylons and anchorages of bridges. !{set:cellbgcolor:#FFFFFF} adeOfAbstractConstructiveElement !<> [0..*] !Augments AbstractConstructiveElement with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractFillingElement-section]] [cols=""1a""] |=== |*AbstractFillingElement* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractFillingElement is the abstract superclass for different kinds of elements that fill the openings of a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfAbstractFillingElement !<> [0..*] !Augments AbstractFillingElement with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractFillingSurface-section]] [cols=""1a""] |=== |*AbstractFillingSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractFillingSurface is the abstract superclass for different kinds of surfaces that seal openings filled by filling elements. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfAbstractFillingSurface !<> [0..*] !Augments AbstractFillingSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractFurniture-section]] [cols=""1a""] |=== |*AbstractFurniture* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractFurniture is the abstract superclass for the representation of furniture objects of a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfAbstractFurniture !<> [0..*] !Augments AbstractFurniture with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[AbstractInstallation-section]] [cols=""1a""] |=== |*AbstractInstallation* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! AbstractInstallation is the abstract superclass for the representation of installation objects of a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} boundary !<> [*] !Relates to the surfaces that bound the installation. This relation is inherited from the Core module. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} relationToConstruction !<> [0..1] !Indicates whether the installation is located inside and/or outside of the construction. !{set:cellbgcolor:#FFFFFF} adeOfAbstractInstallation !<> [0..*] !Augments AbstractInstallation with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[CeilingSurface-section]] [cols=""1a""] |=== |*CeilingSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A CeilingSurface is a surface that represents the interior ceiling of a construction. An example is the ceiling of a room. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfCeilingSurface !<> [0..*] !Augments the CeilingSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[Door-section]] [cols=""1a""] |=== |*Door* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A Door is a construction for closing an opening intended primarily for access or egress or both. [cf. ISO 6707-1] !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} address !<> [*] !Relates to the addresses that are assigned to the Door. !{set:cellbgcolor:#FFFFFF} boundary !<> [*] !Relates to the door surfaces that bound the Door. This relation is inherited from the Core module. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} class !<> [0..1] !Indicates the specific type of the Door. !{set:cellbgcolor:#FFFFFF} function !<> [0..*] !Specifies the intended purposes of the Door. !{set:cellbgcolor:#FFFFFF} usage !<> [0..*] !Specifies the actual uses of the Door. !{set:cellbgcolor:#FFFFFF} adeOfDoor !<> [0..*] !Augments the Door with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[DoorSurface-section]] [cols=""1a""] |=== |*DoorSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A DoorSurface is either a boundary surface of a Door feature or a surface that seals an opening filled by a door. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} address !<> [*] !Relates to the addresses that are assigned to the DoorSurface. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfDoorSurface !<> [0..*] !Augments the DoorSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[FloorSurface-section]] [cols=""1a""] |=== |*FloorSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A FloorSurface is surface that represents the interior floor of a construction. An example is the floor of a room. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfFloorSurface !<> [0..*] !Augments the FloorSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[GroundSurface-section]] [cols=""1a""] |=== |*GroundSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A GroundSurface is a surface that represents the ground plate of a construction. The polygon defining the ground plate is congruent with the footprint of the construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfGroundSurface !<> [0..*] !Augments the GroundSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[InteriorWallSurface-section]] [cols=""1a""] |=== |*InteriorWallSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! An InteriorWallSurface is a surface that is visible from inside a construction. An example is the wall of a room. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfInteriorWallSurface !<> [0..*] !Augments the InteriorWallSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[OtherConstruction-section]] [cols=""1a""] |=== |*OtherConstruction* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! An OtherConstruction is a construction that is not covered by any of the other subclasses of AbstractConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «TopLevelFeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} class !<> [0..1] !Indicates the specific type of the OtherConstruction. !{set:cellbgcolor:#FFFFFF} function !<> [0..*] !Specifies the intended purposes of the OtherConstruction. !{set:cellbgcolor:#FFFFFF} usage !<> [0..*] !Specifies the actual uses of the OtherConstruction. !{set:cellbgcolor:#FFFFFF} adeOfOtherConstruction !<> [0..*] !Augments the OtherConstruction with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[OuterCeilingSurface-section]] [cols=""1a""] |=== |*OuterCeilingSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! An OuterCeilingSurface is a surface that belongs to the outer building shell with the orientation pointing downwards. An example is the ceiling of a loggia. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfOuterCeilingSurface !<> [0..*] !Augments the OuterCeilingSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[OuterFloorSurface-section]] [cols=""1a""] |=== |*OuterFloorSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! An OuterFloorSurface is a surface that belongs to the outer construction shell with the orientation pointing upwards. An example is the floor of a loggia. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfOuterFloorSurface !<> [0..*] !Augments the OuterFloorSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[RoofSurface-section]] [cols=""1a""] |=== |*RoofSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A RoofSurface is a surface that delimits major roof parts of a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfRoofSurface !<> [0..*] !Augments the RoofSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[WallSurface-section]] [cols=""1a""] |=== |*WallSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A WallSurface is a surface that is part of the building facade visible from the outside. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfWallSurface !<> [0..*] !Augments the WallSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[Window-section]] [cols=""1a""] |=== |*Window* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A Window is a construction for closing an opening in a wall or roof, primarily intended to admit light and/or provide ventilation. [cf. ISO 6707-1] !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Role name* !*Target class and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} boundary !<> [*] !Relates to the window surfaces that bound the Window. This relation is inherited from the Core module. !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} class !<> [0..1] !Indicates the specific type of the Window. !{set:cellbgcolor:#FFFFFF} function !<> [0..*] !Specifies the intended purposes of the Window. !{set:cellbgcolor:#FFFFFF} usage !<> [0..*] !Specifies the actual uses of the Window. !{set:cellbgcolor:#FFFFFF} adeOfWindow !<> [0..*] !Augments the Window with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[WindowSurface-section]] [cols=""1a""] |=== |*WindowSurface* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A WindowSurface is either a boundary surface of a Window feature or a surface that seals an opening filled by a window. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! <> !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «FeatureType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} adeOfWindowSurface !<> [0..*] !Augments the WindowSurface with properties defined in an ADE. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== ==== Data Types [[ADEOfAbstractConstruction-section]] [cols=""1a""] |=== |*ADEOfAbstractConstruction* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractConstruction acts as a hook to define properties within an ADE that are to be added to AbstractConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractConstructionSurface-section]] [cols=""1a""] |=== |*ADEOfAbstractConstructionSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractConstructionSurface acts as a hook to define properties within an ADE that are to be added to AbstractConstructionSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractConstructiveElement-section]] [cols=""1a""] |=== |*ADEOfAbstractConstructiveElement* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractConstructiveElement acts as a hook to define properties within an ADE that are to be added to AbstractConstructiveElement. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractFillingElement-section]] [cols=""1a""] |=== |*ADEOfAbstractFillingElement* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractFillingElement acts as a hook to define properties within an ADE that are to be added to AbstractFillingElement. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractFillingSurface-section]] [cols=""1a""] |=== |*ADEOfAbstractFillingSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractFillingSurface acts as a hook to define properties within an ADE that are to be added to AbstractFillingSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractFurniture-section]] [cols=""1a""] |=== |*ADEOfAbstractFurniture* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractFurniture acts as a hook to define properties within an ADE that are to be added to AbstractFurniture. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfAbstractInstallation-section]] [cols=""1a""] |=== |*ADEOfAbstractInstallation* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfAbstractInstallation acts as a hook to define properties within an ADE that are to be added to AbstractInstallation. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfCeilingSurface-section]] [cols=""1a""] |=== |*ADEOfCeilingSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfCeilingSurface acts as a hook to define properties within an ADE that are to be added to a CeilingSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfDoor-section]] [cols=""1a""] |=== |*ADEOfDoor* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfDoor acts as a hook to define properties within an ADE that are to be added to a Door. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfDoorSurface-section]] [cols=""1a""] |=== |*ADEOfDoorSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfDoorSurface acts as a hook to define properties within an ADE that are to be added to a DoorSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfFloorSurface-section]] [cols=""1a""] |=== |*ADEOfFloorSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfFloorSurface acts as a hook to define properties within an ADE that are to be added to a FloorSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfGroundSurface-section]] [cols=""1a""] |=== |*ADEOfGroundSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfGroundSurface acts as a hook to define properties within an ADE that are to be added to a GroundSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfInteriorWallSurface-section]] [cols=""1a""] |=== |*ADEOfInteriorWallSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfInteriorWallSurface acts as a hook to define properties within an ADE that are to be added to an InteriorWallSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfOtherConstruction-section]] [cols=""1a""] |=== |*ADEOfOtherConstruction* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfOtherConstruction acts as a hook to define properties within an ADE that are to be added to an OtherConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfOuterCeilingSurface-section]] [cols=""1a""] |=== |*ADEOfOuterCeilingSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfOuterCeilingSurface acts as a hook to define properties within an ADE that are to be added to an OuterCeilingSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfOuterFloorSurface-section]] [cols=""1a""] |=== |*ADEOfOuterFloorSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfOuterFloorSurface acts as a hook to define properties within an ADE that are to be added to an OuterFloorSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfRoofSurface-section]] [cols=""1a""] |=== |*ADEOfRoofSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfRoofSurface acts as a hook to define properties within an ADE that are to be added to a RoofSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfWallSurface-section]] [cols=""1a""] |=== |*ADEOfWallSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfWallSurface acts as a hook to define properties within an ADE that are to be added to a WallSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfWindow-section]] [cols=""1a""] |=== |*ADEOfWindow* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfWindow acts as a hook to define properties within an ADE that are to be added to a Window. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ADEOfWindowSurface-section]] [cols=""1a""] |=== |*ADEOfWindowSurface* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ADEOfWindowSurface acts as a hook to define properties within an ADE that are to be added to a WindowSurface. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |=== [[ConstructionEvent-section]] [cols=""1a""] |=== |*ConstructionEvent* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! A ConstructionEvent is a data type used to describe a specific event that is associated with a construction. Examples are the issuing of a building permit or the renovation of a building. !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} event !<> [1..1] !Indicates the specific event type. !{set:cellbgcolor:#FFFFFF} dateOfEvent !<> [1..1] !Specifies the date at which the event took or will take place. !{set:cellbgcolor:#FFFFFF} description !<> [0..1] !Provides additional information on the event. !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[Elevation-section]] [cols=""1a""] |=== |*Elevation* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! Elevation is a data type that includes the elevation value itself and information on how this elevation was measured. [cf. INSPIRE] !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} elevationReference !<> [1..1] !Specifies the level from which the elevation was measured. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} elevationValue !<> [1..1] !Specifies the value of the elevation. [cf. INSPIRE] !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== [[Height-section]] [cols=""1a""] |=== |*Height* [cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! Height represents a vertical distance (measured or estimated) between a low reference and a high reference. [cf. INSPIRE] !{nbsp}{nbsp}{nbsp}{nbsp}Subclass of: ! None !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «DataType» !=== |[cols=""15,20,60"",frame=none,grid=none,options=""header""] !=== !{set:cellbgcolor:#DDDDDD} *Attribute* !*Value type and multiplicity* !*Definition* !{set:cellbgcolor:#FFFFFF} highReference !<> [1..1] !Indicates the high point used to calculate the value of the height. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} lowReference !<> [1..1] !Indicates the low point used to calculate the value of the height. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} status !<> [1..1] !Indicates the way the height has been captured. [cf. INSPIRE] !{set:cellbgcolor:#FFFFFF} value !<> [1..1] !Specifies the value of the height above or below ground. [cf. INSPIRE] !=== |{set:cellbgcolor:#FFFFFF} Note: Unless otherwise specified, all attributes and role names have the stereotype «Property». |=== ==== Basic Types none ==== Unions none ==== Code Lists [[DoorClassValue-section]] [cols=""1a""] |=== |*DoorClassValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! DoorClassValue is a code list used to further classify a Door. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[DoorFunctionValue-section]] [cols=""1a""] |=== |*DoorFunctionValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! DoorFunctionValue is a code list that enumerates the different purposes of a Door. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[DoorUsageValue-section]] [cols=""1a""] |=== |*DoorUsageValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! DoorUsageValue is a code list that enumerates the different uses of a Door. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[ElevationReferenceValue-section]] [cols=""1a""] |=== |*ElevationReferenceValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! ElevationReferenceValue is a code list that enumerates the different elevation reference levels used to measure construction heights. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[EventValue-section]] [cols=""1a""] |=== |*EventValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! EventValue is a code list that enumerates the different events of a construction. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[OtherConstructionClassValue-section]] [cols=""1a""] |=== |*OtherConstructionClassValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! OtherConstructionClassValue is a code list used to further classify an OtherConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[OtherConstructionFunctionValue-section]] [cols=""1a""] |=== |*OtherConstructionFunctionValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! OtherConstructionFunctionValue is a code list that enumerates the different purposes of an OtherConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[OtherConstructionUsageValue-section]] [cols=""1a""] |=== |*OtherConstructionUsageValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! OtherConstructionUsageValue is a code list that enumerates the different uses of an OtherConstruction. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[WindowClassValue-section]] [cols=""1a""] |=== |*WindowClassValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! WindowClassValue is a code list used to further classify a Window. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[WindowFunctionValue-section]] [cols=""1a""] |=== |*WindowFunctionValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! WindowFunctionValue is a code list that enumerates the different purposes of a Window. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== [[WindowUsageValue-section]] [cols=""1a""] |=== |*WindowUsageValue* |[cols=""1,4"",frame=none,grid=none] !=== !{nbsp}{nbsp}{nbsp}{nbsp}Definition: ! WindowUsageValue is a code list that enumerates the different uses of a Window. !{nbsp}{nbsp}{nbsp}{nbsp}Stereotype: ! «CodeList» !=== |=== ==== Enumerations [[ConditionOfConstructionValue-section]] [cols=""1a""] |=== |*ConditionOfConstructionValue* [cols=""1,4"",frame=none,grid=none] !=== !Definition: ! ConditionOfConstructionValue enumerates different conditions of a construction. [cf. INSPIRE] !StereoType: ! \\<> !=== |[cols=""1,4"",frame=none,grid=none,options=""header""] !=== ^!{set:cellbgcolor:#DDDDDD} *Literal value* !*Definition* ^!{set:cellbgcolor:#FFFFFF} declined !Indicates that the construction cannot be used under normal conditions, though its main elements (walls, roof) are still present. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} demolished !Indicates that the construction has been demolished. There are no more visible remains. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} functional !Indicates that the construction is functional. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} projected !Indicates that the construction is being designed. Construction works have not yet started. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} ruin !Indicates that the construction has been partly demolished and some main elements (roof, walls) have been destroyed. There are some visible remains of the construction. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} underConstruction !Indicates that the construction is under construction and not yet functional. This applies only to the initial construction works of the construction and not to maintenance work. [cf. INSPIRE] !=== |=== [[HeightStatusValue-section]] [cols=""1a""] |=== |*HeightStatusValue* [cols=""1,4"",frame=none,grid=none] !=== !Definition: ! HeightStatusValue enumerates the different methods used to capture a height. [cf. INSPIRE] !StereoType: ! \\<> !=== |[cols=""1,4"",frame=none,grid=none,options=""header""] !=== ^!{set:cellbgcolor:#DDDDDD} *Literal value* !*Definition* ^!{set:cellbgcolor:#FFFFFF} estimated !Indicates that the height has been estimated and not measured. [cf. INSPIRE] ^!{set:cellbgcolor:#FFFFFF} measured !Indicates that the height has been (directly or indirectly) measured. [cf. INSPIRE] !=== |=== [[RelationToConstruction-section]] [cols=""1a""] |=== |*RelationToConstruction* [cols=""1,4"",frame=none,grid=none] !=== !Definition: ! RelationToConstruction is an enumeration used to describe whether an installation is positioned inside and/or outside of a construction. !StereoType: ! \\<> !=== |[cols=""1,4"",frame=none,grid=none,options=""header""] !=== ^!{set:cellbgcolor:#DDDDDD} *Literal value* !*Definition* ^!{set:cellbgcolor:#FFFFFF} inside !Indicates that the installation is positioned inside of the construction. ^!{set:cellbgcolor:#FFFFFF} outside !Indicates that the installation is positioned outside of the construction. ^!{set:cellbgcolor:#FFFFFF} bothInsideAndOutside !Indicates that the installation is positioned inside as well as outside of the construction. !=== |=== ",12192,True,3422.7654960703358,median "--- title: ""FreeBSD/amd64 5.5-RELEASE Release Notes"" sidenav: download --- ++++

The FreeBSD Project

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

$FreeBSD: src/release/doc/en_US.ISO8859-1/relnotes/common/new.sgml,v 1.761.2.59.2.2 2006/05/22 17:05:47 bmah Exp $

FreeBSD is a registered trademark of the FreeBSD Foundation.

IBM, AIX, EtherJet, Netfinity, OS/2, PowerPC, PS/2, S/390, and ThinkPad are trademarks of International Business Machines Corporation in the United States, other countries, or both.

IEEE, POSIX, and 802 are registered trademarks of Institute of Electrical and Electronics Engineers, Inc. in the United States.

Intel, Celeron, EtherExpress, i386, i486, Itanium, Pentium, and Xeon are trademarks or registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries.

Sparc, Sparc64, SPARCEngine, and UltraSPARC are trademarks of SPARC International, Inc in the United States and other countries. Products bearing SPARC trademarks are based upon architecture developed by Sun Microsystems, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this document, and the FreeBSD Project was aware of the trademark claim, the designations have been followed by the ``™'' or the ``®'' symbol.

The release notes for FreeBSD 5.5-RELEASE contain a summary of the changes made to the FreeBSD base system since 5.4-RELEASE. This document lists applicable security advisories that were issued since the last release, as well as significant changes to the FreeBSD kernel and userland. Some brief remarks on upgrading are also presented.


1 Introduction

This document contains the release notes for FreeBSD 5.5-RELEASE on the AMD64 hardware platform. It describes recently added, changed, or deleted features of FreeBSD. It also provides some notes on upgrading from previous versions of FreeBSD.

This distribution of FreeBSD 5.5-RELEASE is a release distribution. It can be found at ftp://ftp.FreeBSD.org/ or any of its mirrors. More information on obtaining this (or other) release distributions of FreeBSD can be found in the ``Obtaining FreeBSD'' appendix to the FreeBSD Handbook.

All users are encouraged to consult the release errata before installing FreeBSD. The errata document is updated with ``late-breaking'' information discovered late in the release cycle or after the release. Typically, it contains information on known bugs, security advisories, and corrections to documentation. An up-to-date copy of the errata for FreeBSD 5.5-RELEASE can be found on the FreeBSD Web site.

FreeBSD 5.5-RELEASE is the last planned release on the 5.5-STABLE branch. The FreeBSD development community is currently focusing its efforts on the 6-STABLE and CURRENT codelines. No new major features are planned for the 5.5-STABLE branch, although minor updates and bugfixes may be merged at the discretion of individual developers. The FreeBSD security team will support the 5.5-RELEASE-based security branch with advisories and security patches until the end-of-life date documented at http://security.freebsd.org/ (as of this writing, 31 May 2008).


2 What's New

This section describes the most user-visible new or changed features in FreeBSD since 5.4-RELEASE.

Typical release note items document recent security advisories issued after 5.4-RELEASE, new drivers or hardware support, new commands or options, major bug fixes, or contributed software upgrades. They may also list changes to major ports/packages or release engineering practices. Clearly the release notes cannot list every single change made to FreeBSD between releases; this document focuses primarily on security advisories, user-visible changes, and major architectural improvements.


2.1 Security Advisories

Because of an information disclosure vulnerability on processors using Hyper-Threading Technology (HTT), the machdep.hyperthreading_allowed sysctl variable has been added. It defaults to 1 (HTT enabled) on FreeBSD CURRENT, and 0 (HTT disabled) on the 4-STABLE and 5-STABLE development branches and supported security fix branches. More information can be found in security advisory FreeBSD-SA-05:09.htt.

A bug in the tcpdump(1) utility which allows a malicious remote user to cause a denial-of-service by using specially crafted packets, has been fixed. For more information, see security advisory FreeBSD-SA-05:10.tcpdump.

Two problems in the gzip(1) utility have been fixed. These may allow a local user to modify permissions of arbitrary files and overwrite arbitrary local files when uncompressing a file. For more information, see security advisory FreeBSD-SA-05:11.gzip.

A bug has been fixed in ipfw(4) that could cause packets to be matched incorrectly against a lookup table. This bug only affects SMP machines or UP machines that have the PREEMPTION kernel option enabled. More information is contained in security advisory FreeBSD-SA-05:13.ipfw.

Two security-related problems have been fixed in bzip2(1). These include a potential denial of service and unauthorized manipulation of file permissions. For more information, see security advisory FreeBSD-SA-05:14.bzip2.

Two problems in FreeBSD's TCP stack have been fixed. They could allow attackers to stall existing TCP connections, creating a denial-of-service situation. More information is contained in security advisory FreeBSD-SA-05:15.tcp.

Two buffer overflows in the zlib library has been corrected. More information can be found in security advisory FreeBSD-SA-05:16.zlib and FreeBSD-SA-05:18.zlib.

A security vulnerability that could allow processes running inside a jail(2) to gain access to hidden devfs(5) file nodes has been corrected, as described in security advisory FreeBSD-SA-05:17.devfs.

A programming error in the ipsec(4) implementation, which resulted in AES-XCBC-MAC authentication using a constant key, has been corrected. More details are in security advisory FreeBSD-SA-05:19.ipsec.

A temporary file vulnerability in cvsbug(8), which could allow an attacker to modify or overwrite files with the permissions of a user running the cvsbug(8) utility, has been fixed. More details can be found in security advisory FreeBSD-SA-05:20.cvsbug.

A bug in OpenSSL that could allow an attacker to force an use older version of the SSL (with known weakensses) has been corrected. Details can be found in security advisory FreeBSD-SA-05:21.openssl.

A temporary file vulnerability in texindex(1), which could allow a local attacker to overwrite files in the context of a user running the texindex(1) utility, has been fixed. For more details see security advisory FreeBSD-SA-06:01.texindex.

A temporary file vulnerability in the ee(1) text editor, which could allow a local attacker to overwrite files in the context of a user running ee(1), has been fixed. For more details see security advisory FreeBSD-SA-06:02.ee.

Several vulnerabilities in the cpio(1) utility have been corrected. For more details see security advisory FreeBSD-SA-06:03.cpio.

Two instances in which portions of kernel memory could be disclosed to users have been fixed. For more details see security advisory FreeBSD-SA-06:06.kmem.

A logic bug in the IP fragment handling in pf(4), which could cause a crash under certain circumstances, has been fixed. For more details see security advisory FreeBSD-SA-06:07.pf.

An error in Selective Acknowledgement (SACK) support in the TCP/IP stack, which could cause an infinite loop upon reception of a particular series of packets, has been corrected. More details are contained in security advisory FreeBSD-SA-06:08.sack.

A logic bug in the OpenSSH performs internal accounting, which could cause the master decides that it is overloaded and stops accepting client connections, has been fixed. For more details see security advisory FreeBSD-SA-06:09.openssh.

A logic bug in the NFS server code, which could cause a crash when the server received a message with a zero-length payload, has been fixed. For more details see security advisory FreeBSD-SA-06:10.nfs.

A programming error in the fast_ipsec(4) implementation results in the sequence number associated with a Security Association not being updated, allowing packets to unconditionally pass sequence number verification checks, has been fixed. For more details see security advisory FreeBSD-SA-06:11.ipsec.

A logic bug that could cause opiepasswd(1) to allow an unprivileged user to configure OPIE authentication for the root user under certain circumstances, has been fixed. For more details see security advisory FreeBSD-SA-06:12.opie.

An asynchronous signal handling vulnerability in sendmail(8), which could allow a remote attacker to execute arbitrary code with the privileges of the user running sendmail, typically root, has been fixed. For more details see security advisory FreeBSD-SA-06:13.sendmail.

An information disclosure issue found in FreeBSD kernel running on 7th and 8th generation of AMD processors has been fixed. For more details see security advisory FreeBSD-SA-06:14.fpu.


2.2 Kernel Changes


2.2.1 Boot Loader Changes

The autoboot command will now prevent the user from interrupting the boot process at all if the autoboot_delay variable is set to -1.


2.2.2 Hardware Support

Dual-core processors (such as the Intel Core Duo) now have both cores available for use by default in SMP-enabled kernels.


2.2.2.1 Multimedia Support

The uaudio(4) driver now has some added functionality, including volume control on more inputs and recording capability on some devices.


2.2.2.2 Network Interface Support

The bge(4) driver now supports the BCM5714 and 5789 chips.

The ixgb(4) driver is now MPSAFE.

Drivers using the ndis(4) device driver wrapper mechanism are now built and loaded differently. The ndis(4) driver can now be pre-built as module or statically compiled into a kernel. Individual drivers can now be built with the ndisgen(8) utility; the result is a kernel module that can be loaded into a running kernel using kldload(8).

Many (but not all) changes to the ndis(4) system were merged from HEAD.

The xl(4) driver now supports polling(4).


2.2.3 Network Protocols

The if_bridge(4) network bridging implementation, originally from NetBSD, has been added. It supports the IEEE 802.1D Spanning Tree Protocol, individual interface devices for each bridge, filtering of bridged packets, and span ports (which transmit a copy of every frame received by the bridge). The ifconfig(8) utility now supports configuration of if_bridge(4).


2.2.4 Disks and Storage

The twa(4) driver has been updated to the 9.3.0.1 release on the 3ware Web site.


2.3 Userland Changes

The bsdiff(1) and bspatch(1) utilities have been added. These are tools for constructing and applying binary patches.

The cmp(1) utility now supports an -h flag to compare the symbolic link itself rather than the file that the link points to.

The gethostbyname(3), gethostbyname2(3), and gethostbyaddr(3) functions are now thread-safe.

The getnetent(3), getnetbyname(3), and getnetbyaddr(3) functions are now thread-safe.

The getprotoent(3), getprotobyname(3), and getprotobynumber(3) functions are now thread-safe.

The getservent(3), getservbyname(3), and getservbyport(3) functions are now thread-safe.

The kdump(1) program now supports a -s flag to suppress the display of I/O data.

The kldstat(8) utility now supports a -m option to return the status of a specific kernel module.

The default stack sizes in libpthread, libthr, and libc_r have been increased. On 32-bit platforms, the main thread receives a 2MB stack size by default, with other threads receiving a 1MB stack size by default. On 64-bit platforms, the default stack sizes are 4MB and 2MB respectively.

The netstat(1) utility now supports an -h flag for interface stats mode, which prints all interface statistics in human readable form.

The ping(8) utility now supports a ``sweeping ping'' in which icmp(4) payload of packets being sent is increased with given step. This is useful for testing problematic channels, MTU issues or traffic policing functions in networks.

The powerd(8) program for managing power consumption has been added.

The rfcomm_sppd(1) program now supports service names in addition to -c option with channel number. The supported names are: DUN (Dial-Up Networking), FAX (Fax), LAN (LAN Access Using PPP), and SP (Serial Port).

The rm(1) utility now supports an -I option that asks for confirmation (once) if recursively removing directories or if more than 3 files are listed in the command line.

sed(1) now supports a -l option to make its output line-buffered.

The sh(1) utility now supports the times built-in command.

The snapinfo(8) utility, which shows snapshot locations on UFS filesystems, has been added.


2.3.1 /etc/rc.d Scripts

The bluetooth script has been added. This script will be called from devd(8) in response to device attachment/detachment events and to stop/start particular device without unplugging it by hand. The configuration parameters are in /etc/defaults/bluetooth.device.conf, and can be overridden by using /etc/bluetooth/$device.conf (where $device is ubt0, btcc0, and so on.) For more details, see bluetooth.conf(5).

The rc.d/jail startup script now supports jail_name_flags variable which allows to specify jail(8) flags.


2.4 Contributed Software

BIND has been updated from 9.3.1 to 9.3.2.

sendmail has been updated from version 8.13.3 to version 8.13.6.

The timezone database has been updated from the tzdata2005g release to the tzdata2006g release.


2.5 Ports/Packages Collection Infrastructure

The pkg_add(1) program now supports an -P flag, which is the same as the -p flag except that the given prefix is also used recursively for the dependency packages if any.

The pkg_add(1) and pkg_create(1) utilities now support a -K flag to save packages to the current directory (or PKGDIR if defined) by default.

The pkg_create(1) program now supports an -x flag to support basic regular expressions for package name, an -E flag for extended regular expressions, and a -G for exact matching.

The pkg_version(1) utility now supports a -I flag, which causes only the INDEX file to be used for determining if a package is out of date.

The pkg_version(1) utility now supports an -o flag to show the origin recorded on package generation instead of the package name, and an -O flag to list packages whose registered origin is origin only.

The portsnap(8) utility (sysutils/portsnap) has been added into the FreeBSD base system. This is a secure, easy to use, fast, lightweight, and generally good way for users to keep their ports trees up to date.

The suffix of startup scripts from the Ports Collection has been removed. This means foo.sh is renamed to foo, and now scripts whose name is something like foo.ORG will also be invoked. You are recommended to reinstall packages which install such scripts and remove extra files in the local_startup directory.

New rc.conf variables, ldconfig_local_dirs and ldconfig_local32_dirs have been added. These hold lists of local ldconfig(8) directories.

The @cwd command in pkg-plist now allows no directory argument. If no directory argument is given, it will set current working directory to the first prefix given by the @cwd command.


2.6 Release Engineering and Integration

The supported version of the GNOME desktop environment (x11/gnome2) has been updated from 2.10.2 to 2.12.3.

The supported version of the KDE desktop environment (x11/kde3) has been updated from 3.4.2 to 3.5.1.

The supported version of the Perl interpreter (lang/perl5.8) has been updated from 5.8.7 to 5.8.8.

The supported version of the Xorg windowing system (x11/xorg) has been updated from 6.8.2 to 6.9.0.


3 Upgrading from previous releases of FreeBSD

If you're upgrading from a previous release of FreeBSD, you generally will have three options:

  • Using the binary upgrade option of sysinstall(8). This option is perhaps the quickest, although it presumes that your installation of FreeBSD uses no special compilation options.

  • Performing a complete reinstall of FreeBSD. Technically, this is not an upgrading method, and in any case is usually less convenient than a binary upgrade, in that it requires you to manually backup and restore the contents of /etc. However, it may be useful in cases where you want (or need) to change the partitioning of your disks.

  • From source code in /usr/src. This route is more flexible, but requires more disk space, time, and technical expertise. More information can be found in the ``Using make world'' section of the FreeBSD Handbook. Upgrading from very old versions of FreeBSD may be problematic; in cases like this, it is usually more effective to perform a binary upgrade or a complete reinstall.



Please read the INSTALL.TXT file for more information, preferably before beginning an upgrade. If you are upgrading from source, please be sure to read /usr/src/UPDATING as well.

Finally, if you want to use one of various means to track the -STABLE or -CURRENT branches of FreeBSD, please be sure to consult the ``-CURRENT vs. -STABLE'' section of the FreeBSD Handbook.

Important: Upgrading FreeBSD should, of course, only be attempted after backing up all data and configuration files.


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

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

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

++++ ",12176,True,2689.760010998324,median "// // Copyright(c) 2014 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // entry_points_gles_2_0.cpp : Implements the GLES 2.0 entry points. #include ""libGLESv2/entry_points_gles_2_0.h"" #include ""libGLESv2/global_state.h"" #include ""libANGLE/formatutils.h"" #include ""libANGLE/Buffer.h"" #include ""libANGLE/Compiler.h"" #include ""libANGLE/Context.h"" #include ""libANGLE/Error.h"" #include ""libANGLE/Framebuffer.h"" #include ""libANGLE/Renderbuffer.h"" #include ""libANGLE/Shader.h"" #include ""libANGLE/Program.h"" #include ""libANGLE/Texture.h"" #include ""libANGLE/VertexArray.h"" #include ""libANGLE/FramebufferAttachment.h"" #include ""libANGLE/validationES.h"" #include ""libANGLE/validationES2.h"" #include ""libANGLE/validationES3.h"" #include ""libANGLE/queryconversions.h"" #include ""libANGLE/queryutils.h"" #include ""common/debug.h"" #include ""common/utilities.h"" namespace gl { void GL_APIENTRY ActiveTexture(GLenum texture) { EVENT(""(GLenum texture = 0x%X)"", texture); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateActiveTexture(context, texture)) { return; } context->activeTexture(texture); } } void GL_APIENTRY AttachShader(GLuint program, GLuint shader) { EVENT(""(GLuint program = %d, GLuint shader = %d)"", program, shader); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateAttachShader(context, program, shader)) { return; } context->attachShader(program, shader); } } void GL_APIENTRY BindAttribLocation(GLuint program, GLuint index, const GLchar* name) { EVENT(""(GLuint program = %d, GLuint index = %d, const GLchar* name = 0x%0.8p)"", program, index, name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBindAttribLocation(context, program, index, name)) { return; } context->bindAttribLocation(program, index, name); } } void GL_APIENTRY BindBuffer(GLenum target, GLuint buffer) { EVENT(""(GLenum target = 0x%X, GLuint buffer = %d)"", target, buffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBindBuffer(context, target, buffer)) { return; } context->bindBuffer(target, buffer); } } void GL_APIENTRY BindFramebuffer(GLenum target, GLuint framebuffer) { EVENT(""(GLenum target = 0x%X, GLuint framebuffer = %d)"", target, framebuffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBindFramebuffer(context, target, framebuffer)) { return; } context->bindFramebuffer(target, framebuffer); } } void GL_APIENTRY BindRenderbuffer(GLenum target, GLuint renderbuffer) { EVENT(""(GLenum target = 0x%X, GLuint renderbuffer = %d)"", target, renderbuffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBindRenderbuffer(context, target, renderbuffer)) { return; } context->bindRenderbuffer(target, renderbuffer); } } void GL_APIENTRY BindTexture(GLenum target, GLuint texture) { EVENT(""(GLenum target = 0x%X, GLuint texture = %d)"", target, texture); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBindTexture(context, target, texture)) { return; } context->bindTexture(target, texture); } } void GL_APIENTRY BlendColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { EVENT(""(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)"", red, green, blue, alpha); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBlendColor(context, red, green, blue, alpha)) { return; } context->blendColor(red, green, blue, alpha); } } void GL_APIENTRY BlendEquation(GLenum mode) { EVENT(""(GLenum mode = 0x%X)"", mode); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBlendEquation(context, mode)) { return; } context->blendEquation(mode); } } void GL_APIENTRY BlendEquationSeparate(GLenum modeRGB, GLenum modeAlpha) { EVENT(""(GLenum modeRGB = 0x%X, GLenum modeAlpha = 0x%X)"", modeRGB, modeAlpha); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBlendEquationSeparate(context, modeRGB, modeAlpha)) { return; } context->blendEquationSeparate(modeRGB, modeAlpha); } } void GL_APIENTRY BlendFunc(GLenum sfactor, GLenum dfactor) { EVENT(""(GLenum sfactor = 0x%X, GLenum dfactor = 0x%X)"", sfactor, dfactor); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBlendFunc(context, sfactor, dfactor)) { return; } context->blendFunc(sfactor, dfactor); } } void GL_APIENTRY BlendFuncSeparate(GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha) { EVENT(""(GLenum srcRGB = 0x%X, GLenum dstRGB = 0x%X, GLenum srcAlpha = 0x%X, GLenum dstAlpha = 0x%X)"", srcRGB, dstRGB, srcAlpha, dstAlpha); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBlendFuncSeparate(context, srcRGB, dstRGB, srcAlpha, dstAlpha)) { return; } context->blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha); } } void GL_APIENTRY BufferData(GLenum target, GLsizeiptr size, const GLvoid* data, GLenum usage) { EVENT(""(GLenum target = 0x%X, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p, GLenum usage = %d)"", target, size, data, usage); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBufferData(context, target, size, data, usage)) { return; } context->bufferData(target, size, data, usage); } } void GL_APIENTRY BufferSubData(GLenum target, GLintptr offset, GLsizeiptr size, const GLvoid* data) { EVENT(""(GLenum target = 0x%X, GLintptr offset = %d, GLsizeiptr size = %d, const GLvoid* data = 0x%0.8p)"", target, offset, size, data); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateBufferSubData(context, target, offset, size, data)) { return; } context->bufferSubData(target, offset, size, data); } } GLenum GL_APIENTRY CheckFramebufferStatus(GLenum target) { EVENT(""(GLenum target = 0x%X)"", target); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCheckFramebufferStatus(context, target)) { return 0; } return context->checkFramebufferStatus(target); } return 0; } void GL_APIENTRY Clear(GLbitfield mask) { EVENT(""(GLbitfield mask = 0x%X)"", mask); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateClear(context, mask)) { return; } context->clear(mask); } } void GL_APIENTRY ClearColor(GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) { EVENT(""(GLclampf red = %f, GLclampf green = %f, GLclampf blue = %f, GLclampf alpha = %f)"", red, green, blue, alpha); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateClearColor(context, red, green, blue, alpha)) { return; } context->clearColor(red, green, blue, alpha); } } void GL_APIENTRY ClearDepthf(GLclampf depth) { EVENT(""(GLclampf depth = %f)"", depth); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateClearDepthf(context, depth)) { return; } context->clearDepthf(depth); } } void GL_APIENTRY ClearStencil(GLint s) { EVENT(""(GLint s = %d)"", s); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateClearStencil(context, s)) { return; } context->clearStencil(s); } } void GL_APIENTRY ColorMask(GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha) { EVENT(""(GLboolean red = %d, GLboolean green = %u, GLboolean blue = %u, GLboolean alpha = %u)"", red, green, blue, alpha); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateColorMask(context, red, green, blue, alpha)) { return; } context->colorMask(red, green, blue, alpha); } } void GL_APIENTRY CompileShader(GLuint shader) { EVENT(""(GLuint shader = %d)"", shader); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCompileShader(context, shader)) { return; } context->compileShader(shader); } } void GL_APIENTRY CompressedTexImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const GLvoid* data) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, GLsizei width = %d, "" ""GLsizei height = %d, GLint border = %d, GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)"", target, level, internalformat, width, height, border, imageSize, data); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCompressedTexImage2D(context, target, level, internalformat, width, height, border, imageSize, data)) { return; } context->compressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } } void GL_APIENTRY CompressedTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const GLvoid* data) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "" ""GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, "" ""GLsizei imageSize = %d, const GLvoid* data = 0x%0.8p)"", target, level, xoffset, yoffset, width, height, format, imageSize, data); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCompressedTexSubImage2D(context, target, level, xoffset, yoffset, width, height, format, imageSize, data)) { return; } context->compressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } } void GL_APIENTRY CopyTexImage2D(GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLenum internalformat = 0x%X, "" ""GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, GLint border = %d)"", target, level, internalformat, x, y, width, height, border); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCopyTexImage2D(context, target, level, internalformat, x, y, width, height, border)) { return; } context->copyTexImage2D(target, level, internalformat, x, y, width, height, border); } } void GL_APIENTRY CopyTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "" ""GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)"", target, level, xoffset, yoffset, x, y, width, height); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCopyTexSubImage2D(context, target, level, xoffset, yoffset, x, y, width, height)) { return; } context->copyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } } GLuint GL_APIENTRY CreateProgram(void) { EVENT(""()""); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCreateProgram(context)) { return 0; } return context->createProgram(); } return 0; } GLuint GL_APIENTRY CreateShader(GLenum type) { EVENT(""(GLenum type = 0x%X)"", type); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCreateShader(context, type)) { return 0; } return context->createShader(type); } return 0; } void GL_APIENTRY CullFace(GLenum mode) { EVENT(""(GLenum mode = 0x%X)"", mode); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateCullFace(context, mode)) { return; } context->cullFace(mode); } } void GL_APIENTRY DeleteBuffers(GLsizei n, const GLuint* buffers) { EVENT(""(GLsizei n = %d, const GLuint* buffers = 0x%0.8p)"", n, buffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteBuffers(context, n, buffers)) { return; } context->deleteBuffers(n, buffers); } } void GL_APIENTRY DeleteFramebuffers(GLsizei n, const GLuint* framebuffers) { EVENT(""(GLsizei n = %d, const GLuint* framebuffers = 0x%0.8p)"", n, framebuffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteFramebuffers(context, n, framebuffers)) { return; } context->deleteFramebuffers(n, framebuffers); } } void GL_APIENTRY DeleteProgram(GLuint program) { EVENT(""(GLuint program = %d)"", program); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteProgram(context, program)) { return; } context->deleteProgram(program); } } void GL_APIENTRY DeleteRenderbuffers(GLsizei n, const GLuint* renderbuffers) { EVENT(""(GLsizei n = %d, const GLuint* renderbuffers = 0x%0.8p)"", n, renderbuffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteRenderbuffers(context, n, renderbuffers)) { return; } context->deleteRenderbuffers(n, renderbuffers); } } void GL_APIENTRY DeleteShader(GLuint shader) { EVENT(""(GLuint shader = %d)"", shader); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteShader(context, shader)) { return; } context->deleteShader(shader); } } void GL_APIENTRY DeleteTextures(GLsizei n, const GLuint* textures) { EVENT(""(GLsizei n = %d, const GLuint* textures = 0x%0.8p)"", n, textures); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDeleteTextures(context, n, textures)) { return; } context->deleteTextures(n, textures); } } void GL_APIENTRY DepthFunc(GLenum func) { EVENT(""(GLenum func = 0x%X)"", func); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDepthFunc(context, func)) { return; } context->depthFunc(func); } } void GL_APIENTRY DepthMask(GLboolean flag) { EVENT(""(GLboolean flag = %u)"", flag); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDepthMask(context, flag)) { return; } context->depthMask(flag); } } void GL_APIENTRY DepthRangef(GLclampf zNear, GLclampf zFar) { EVENT(""(GLclampf zNear = %f, GLclampf zFar = %f)"", zNear, zFar); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDepthRangef(context, zNear, zFar)) { return; } context->depthRangef(zNear, zFar); } } void GL_APIENTRY DetachShader(GLuint program, GLuint shader) { EVENT(""(GLuint program = %d, GLuint shader = %d)"", program, shader); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDetachShader(context, program, shader)) { return; } context->detachShader(program, shader); } } void GL_APIENTRY Disable(GLenum cap) { EVENT(""(GLenum cap = 0x%X)"", cap); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDisable(context, cap)) { return; } context->disable(cap); } } void GL_APIENTRY DisableVertexAttribArray(GLuint index) { EVENT(""(GLuint index = %d)"", index); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDisableVertexAttribArray(context, index)) { return; } context->disableVertexAttribArray(index); } } void GL_APIENTRY DrawArrays(GLenum mode, GLint first, GLsizei count) { EVENT(""(GLenum mode = 0x%X, GLint first = %d, GLsizei count = %d)"", mode, first, count); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateDrawArrays(context, mode, first, count)) { return; } context->drawArrays(mode, first, count); } } void GL_APIENTRY DrawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid* indices) { EVENT(""(GLenum mode = 0x%X, GLsizei count = %d, GLenum type = 0x%X, const GLvoid* indices = 0x%0.8p)"", mode, count, type, indices); Context *context = GetValidGlobalContext(); if (context) { // TODO(jmadill): Cache index range in the context. IndexRange indexRange; if (!ValidateDrawElements(context, mode, count, type, indices, 1, &indexRange)) { return; } context->drawElements(mode, count, type, indices, indexRange); } } void GL_APIENTRY Enable(GLenum cap) { EVENT(""(GLenum cap = 0x%X)"", cap); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateEnable(context, cap)) { return; } context->enable(cap); } } void GL_APIENTRY EnableVertexAttribArray(GLuint index) { EVENT(""(GLuint index = %d)"", index); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateEnableVertexAttribArray(context, index)) { return; } context->enableVertexAttribArray(index); } } void GL_APIENTRY Finish(void) { EVENT(""()""); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateFinish(context)) { return; } context->finish(); } } void GL_APIENTRY Flush(void) { EVENT(""()""); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateFlush(context)) { return; } context->flush(); } } void GL_APIENTRY FramebufferRenderbuffer(GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer) { EVENT(""(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum renderbuffertarget = 0x%X, "" ""GLuint renderbuffer = %d)"", target, attachment, renderbuffertarget, renderbuffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateFramebufferRenderbuffer(context, target, attachment, renderbuffertarget, renderbuffer)) { return; } context->framebufferRenderbuffer(target, attachment, renderbuffertarget, renderbuffer); } } void GL_APIENTRY FramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level) { EVENT(""(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum textarget = 0x%X, "" ""GLuint texture = %d, GLint level = %d)"", target, attachment, textarget, texture, level); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateFramebufferTexture2D(context, target, attachment, textarget, texture, level)) { return; } context->framebufferTexture2D(target, attachment, textarget, texture, level); } } void GL_APIENTRY FrontFace(GLenum mode) { EVENT(""(GLenum mode = 0x%X)"", mode); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateFrontFace(context, mode)) { return; } context->frontFace(mode); } } void GL_APIENTRY GenBuffers(GLsizei n, GLuint* buffers) { EVENT(""(GLsizei n = %d, GLuint* buffers = 0x%0.8p)"", n, buffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGenBuffers(context, n, buffers)) { return; } context->genBuffers(n, buffers); } } void GL_APIENTRY GenerateMipmap(GLenum target) { EVENT(""(GLenum target = 0x%X)"", target); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGenerateMipmap(context, target)) { return; } context->generateMipmap(target); } } void GL_APIENTRY GenFramebuffers(GLsizei n, GLuint* framebuffers) { EVENT(""(GLsizei n = %d, GLuint* framebuffers = 0x%0.8p)"", n, framebuffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGenFramebuffers(context, n, framebuffers)) { return; } context->genFramebuffers(n, framebuffers); } } void GL_APIENTRY GenRenderbuffers(GLsizei n, GLuint* renderbuffers) { EVENT(""(GLsizei n = %d, GLuint* renderbuffers = 0x%0.8p)"", n, renderbuffers); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGenRenderbuffers(context, n, renderbuffers)) { return; } context->genRenderbuffers(n, renderbuffers); } } void GL_APIENTRY GenTextures(GLsizei n, GLuint* textures) { EVENT(""(GLsizei n = %d, GLuint* textures = 0x%0.8p)"", n, textures); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGenTextures(context, n, textures)) { return; } context->genTextures(n, textures); } } void GL_APIENTRY GetActiveAttrib(GLuint program, GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name) { EVENT(""(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, GLsizei *length = 0x%0.8p, "" ""GLint *size = 0x%0.8p, GLenum *type = %0.8p, GLchar *name = %0.8p)"", program, index, bufsize, length, size, type, name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetActiveAttrib(context, program, index, bufsize, length, size, type, name)) { return; } context->getActiveAttrib(program, index, bufsize, length, size, type, name); } } void GL_APIENTRY GetActiveUniform(GLuint program, GLuint index, GLsizei bufsize, GLsizei* length, GLint* size, GLenum* type, GLchar* name) { EVENT(""(GLuint program = %d, GLuint index = %d, GLsizei bufsize = %d, "" ""GLsizei* length = 0x%0.8p, GLint* size = 0x%0.8p, GLenum* type = 0x%0.8p, GLchar* name = 0x%0.8p)"", program, index, bufsize, length, size, type, name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetActiveUniform(context, program, index, bufsize, length, size, type, name)) { return; } context->getActiveUniform(program, index, bufsize, length, size, type, name); } } void GL_APIENTRY GetAttachedShaders(GLuint program, GLsizei maxcount, GLsizei* count, GLuint* shaders) { EVENT(""(GLuint program = %d, GLsizei maxcount = %d, GLsizei* count = 0x%0.8p, GLuint* shaders = 0x%0.8p)"", program, maxcount, count, shaders); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetAttachedShaders(context, program, maxcount, count, shaders)) { return; } context->getAttachedShaders(program, maxcount, count, shaders); } } GLint GL_APIENTRY GetAttribLocation(GLuint program, const GLchar* name) { EVENT(""(GLuint program = %d, const GLchar* name = %s)"", program, name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetAttribLocation(context, program, name)) { return -1; } return context->getAttribLocation(program, name); } return -1; } void GL_APIENTRY GetBooleanv(GLenum pname, GLboolean* params) { EVENT(""(GLenum pname = 0x%X, GLboolean* params = 0x%0.8p)"", pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetBooleanv(context, pname, params)) { return; } context->getBooleanv(pname, params); } } void GL_APIENTRY GetBufferParameteriv(GLenum target, GLenum pname, GLint* params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetBufferParameteriv(context, target, pname, params)) { return; } context->getBufferParameteriv(target, pname, params); } } GLenum GL_APIENTRY GetError(void) { EVENT(""()""); Context *context = GetGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetError(context)) { return GL_NO_ERROR; } return context->getError(); } return GL_NO_ERROR; } void GL_APIENTRY GetFloatv(GLenum pname, GLfloat* params) { EVENT(""(GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)"", pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetFloatv(context, pname, params)) { return; } context->getFloatv(pname, params); } } void GL_APIENTRY GetFramebufferAttachmentParameteriv(GLenum target, GLenum attachment, GLenum pname, GLint* params) { EVENT(""(GLenum target = 0x%X, GLenum attachment = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", target, attachment, pname, params); Context *context = GetValidGlobalContext(); if (context) { GLsizei numParams = 0; if (!context->skipValidation() && !ValidateGetFramebufferAttachmentParameteriv(context, target, attachment, pname, &numParams)) { return; } context->getFramebufferAttachmentParameteriv(target, attachment, pname, params); } } void GL_APIENTRY GetIntegerv(GLenum pname, GLint* params) { EVENT(""(GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetIntegerv(context, pname, params)) { return; } context->getIntegerv(pname, params); } } void GL_APIENTRY GetProgramiv(GLuint program, GLenum pname, GLint* params) { EVENT(""(GLuint program = %d, GLenum pname = %d, GLint* params = 0x%0.8p)"", program, pname, params); Context *context = GetValidGlobalContext(); if (context) { GLsizei numParams = 0; if (!context->skipValidation() && !ValidateGetProgramiv(context, program, pname, &numParams)) { return; } context->getProgramiv(program, pname, params); } } void GL_APIENTRY GetProgramInfoLog(GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog) { EVENT(""(GLuint program = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)"", program, bufsize, length, infolog); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetProgramInfoLog(context, program, bufsize, length, infolog)) { return; } context->getInfoLog(program, bufsize, length, infolog); } } void GL_APIENTRY GetRenderbufferParameteriv(GLenum target, GLenum pname, GLint* params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetRenderbufferParameteriv(context, target, pname, params)) { return; } context->getRenderbufferParameteriv(target, pname, params); } } void GL_APIENTRY GetShaderiv(GLuint shader, GLenum pname, GLint* params) { EVENT(""(GLuint shader = %d, GLenum pname = %d, GLint* params = 0x%0.8p)"", shader, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetShaderiv(context, shader, pname, params)) { return; } context->getShaderiv(shader, pname, params); } } void GL_APIENTRY GetShaderInfoLog(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* infolog) { EVENT(""(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* infolog = 0x%0.8p)"", shader, bufsize, length, infolog); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetShaderInfoLog(context, shader, bufsize, length, infolog)) { return; } context->getShaderInfoLog(shader, bufsize, length, infolog); } } void GL_APIENTRY GetShaderPrecisionFormat(GLenum shadertype, GLenum precisiontype, GLint* range, GLint* precision) { EVENT(""(GLenum shadertype = 0x%X, GLenum precisiontype = 0x%X, GLint* range = 0x%0.8p, GLint* precision = 0x%0.8p)"", shadertype, precisiontype, range, precision); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetShaderPrecisionFormat(context, shadertype, precisiontype, range, precision)) { return; } context->getShaderPrecisionFormat(shadertype, precisiontype, range, precision); } } void GL_APIENTRY GetShaderSource(GLuint shader, GLsizei bufsize, GLsizei* length, GLchar* source) { EVENT(""(GLuint shader = %d, GLsizei bufsize = %d, GLsizei* length = 0x%0.8p, GLchar* source = 0x%0.8p)"", shader, bufsize, length, source); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetShaderSource(context, shader, bufsize, length, source)) { return; } context->getShaderSource(shader, bufsize, length, source); } } const GLubyte *GL_APIENTRY GetString(GLenum name) { EVENT(""(GLenum name = 0x%X)"", name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetString(context, name)) { return nullptr; } return context->getString(name); } return nullptr; } void GL_APIENTRY GetTexParameterfv(GLenum target, GLenum pname, GLfloat* params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetTexParameterfv(context, target, pname, params)) { return; } context->getTexParameterfv(target, pname, params); } } void GL_APIENTRY GetTexParameteriv(GLenum target, GLenum pname, GLint* params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetTexParameteriv(context, target, pname, params)) { return; } context->getTexParameteriv(target, pname, params); } } void GL_APIENTRY GetUniformfv(GLuint program, GLint location, GLfloat* params) { EVENT(""(GLuint program = %d, GLint location = %d, GLfloat* params = 0x%0.8p)"", program, location, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetUniformfv(context, program, location, params)) { return; } context->getUniformfv(program, location, params); } } void GL_APIENTRY GetUniformiv(GLuint program, GLint location, GLint* params) { EVENT(""(GLuint program = %d, GLint location = %d, GLint* params = 0x%0.8p)"", program, location, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetUniformiv(context, program, location, params)) { return; } context->getUniformiv(program, location, params); } } GLint GL_APIENTRY GetUniformLocation(GLuint program, const GLchar* name) { EVENT(""(GLuint program = %d, const GLchar* name = 0x%0.8p)"", program, name); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetUniformLocation(context, program, name)) { return -1; } return context->getUniformLocation(program, name); } return -1; } void GL_APIENTRY GetVertexAttribfv(GLuint index, GLenum pname, GLfloat* params) { EVENT(""(GLuint index = %d, GLenum pname = 0x%X, GLfloat* params = 0x%0.8p)"", index, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetVertexAttribfv(context, index, pname, params)) { return; } context->getVertexAttribfv(index, pname, params); } } void GL_APIENTRY GetVertexAttribiv(GLuint index, GLenum pname, GLint* params) { EVENT(""(GLuint index = %d, GLenum pname = 0x%X, GLint* params = 0x%0.8p)"", index, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetVertexAttribiv(context, index, pname, params)) { return; } context->getVertexAttribiv(index, pname, params); } } void GL_APIENTRY GetVertexAttribPointerv(GLuint index, GLenum pname, GLvoid** pointer) { EVENT(""(GLuint index = %d, GLenum pname = 0x%X, GLvoid** pointer = 0x%0.8p)"", index, pname, pointer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateGetVertexAttribPointerv(context, index, pname, pointer)) { return; } context->getVertexAttribPointerv(index, pname, pointer); } } void GL_APIENTRY Hint(GLenum target, GLenum mode) { EVENT(""(GLenum target = 0x%X, GLenum mode = 0x%X)"", target, mode); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateHint(context, target, mode)) { return; } context->hint(target, mode); } } GLboolean GL_APIENTRY IsBuffer(GLuint buffer) { EVENT(""(GLuint buffer = %d)"", buffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsBuffer(context, buffer)) { return GL_FALSE; } return context->isBuffer(buffer); } return GL_FALSE; } GLboolean GL_APIENTRY IsEnabled(GLenum cap) { EVENT(""(GLenum cap = 0x%X)"", cap); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsEnabled(context, cap)) { return GL_FALSE; } return context->isEnabled(cap); } return GL_FALSE; } GLboolean GL_APIENTRY IsFramebuffer(GLuint framebuffer) { EVENT(""(GLuint framebuffer = %d)"", framebuffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsFramebuffer(context, framebuffer)) { return GL_FALSE; } return context->isFramebuffer(framebuffer); } return GL_FALSE; } GLboolean GL_APIENTRY IsProgram(GLuint program) { EVENT(""(GLuint program = %d)"", program); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsProgram(context, program)) { return GL_FALSE; } return context->isProgram(program); } return GL_FALSE; } GLboolean GL_APIENTRY IsRenderbuffer(GLuint renderbuffer) { EVENT(""(GLuint renderbuffer = %d)"", renderbuffer); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsRenderbuffer(context, renderbuffer)) { return GL_FALSE; } return context->isRenderbuffer(renderbuffer); } return GL_FALSE; } GLboolean GL_APIENTRY IsShader(GLuint shader) { EVENT(""(GLuint shader = %d)"", shader); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsShader(context, shader)) { return GL_FALSE; } return context->isShader(shader); } return GL_FALSE; } GLboolean GL_APIENTRY IsTexture(GLuint texture) { EVENT(""(GLuint texture = %d)"", texture); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateIsTexture(context, texture)) { return GL_FALSE; } return context->isTexture(texture); } return GL_FALSE; } void GL_APIENTRY LineWidth(GLfloat width) { EVENT(""(GLfloat width = %f)"", width); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateLineWidth(context, width)) { return; } context->lineWidth(width); } } void GL_APIENTRY LinkProgram(GLuint program) { EVENT(""(GLuint program = %d)"", program); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateLinkProgram(context, program)) { return; } context->linkProgram(program); } } void GL_APIENTRY PixelStorei(GLenum pname, GLint param) { EVENT(""(GLenum pname = 0x%X, GLint param = %d)"", pname, param); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidatePixelStorei(context, pname, param)) { return; } context->pixelStorei(pname, param); } } void GL_APIENTRY PolygonOffset(GLfloat factor, GLfloat units) { EVENT(""(GLfloat factor = %f, GLfloat units = %f)"", factor, units); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidatePolygonOffset(context, factor, units)) { return; } context->polygonOffset(factor, units); } } void GL_APIENTRY ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid* pixels) { EVENT(""(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d, "" ""GLenum format = 0x%X, GLenum type = 0x%X, GLvoid* pixels = 0x%0.8p)"", x, y, width, height, format, type, pixels); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateReadPixels(context, x, y, width, height, format, type, pixels)) { return; } context->readPixels(x, y, width, height, format, type, pixels); } } void GL_APIENTRY ReleaseShaderCompiler(void) { EVENT(""()""); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateReleaseShaderCompiler(context)) { return; } context->releaseShaderCompiler(); } } void GL_APIENTRY RenderbufferStorage(GLenum target, GLenum internalformat, GLsizei width, GLsizei height) { EVENT(""(GLenum target = 0x%X, GLenum internalformat = 0x%X, GLsizei width = %d, GLsizei height = %d)"", target, internalformat, width, height); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateRenderbufferStorage(context, target, internalformat, width, height)) { return; } context->renderbufferStorage(target, internalformat, width, height); } } void GL_APIENTRY SampleCoverage(GLclampf value, GLboolean invert) { EVENT(""(GLclampf value = %f, GLboolean invert = %u)"", value, invert); Context* context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateSampleCoverage(context, value, invert)) { return; } context->sampleCoverage(value, invert); } } void GL_APIENTRY Scissor(GLint x, GLint y, GLsizei width, GLsizei height) { EVENT(""(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)"", x, y, width, height); Context* context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateScissor(context, x, y, width, height)) { return; } context->scissor(x, y, width, height); } } void GL_APIENTRY ShaderBinary(GLsizei n, const GLuint* shaders, GLenum binaryformat, const GLvoid* binary, GLsizei length) { EVENT(""(GLsizei n = %d, const GLuint* shaders = 0x%0.8p, GLenum binaryformat = 0x%X, "" ""const GLvoid* binary = 0x%0.8p, GLsizei length = %d)"", n, shaders, binaryformat, binary, length); Context* context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateShaderBinary(context, n, shaders, binaryformat, binary, length)) { return; } context->shaderBinary(n, shaders, binaryformat, binary, length); } } void GL_APIENTRY ShaderSource(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length) { EVENT(""(GLuint shader = %d, GLsizei count = %d, const GLchar** string = 0x%0.8p, const GLint* length = 0x%0.8p)"", shader, count, string, length); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateShaderSource(context, shader, count, string, length)) { return; } context->shaderSource(shader, count, string, length); } } void GL_APIENTRY StencilFunc(GLenum func, GLint ref, GLuint mask) { EVENT(""(GLenum func = 0x%X, GLint ref = %d, GLuint mask = %d)"", func, ref, mask); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilFunc(context, func, ref, mask)) { return; } context->stencilFunc(func, ref, mask); } } void GL_APIENTRY StencilFuncSeparate(GLenum face, GLenum func, GLint ref, GLuint mask) { EVENT(""(GLenum face = 0x%X, GLenum func = 0x%X, GLint ref = %d, GLuint mask = %d)"", face, func, ref, mask); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilFuncSeparate(context, face, func, ref, mask)) { return; } context->stencilFuncSeparate(face, func, ref, mask); } } void GL_APIENTRY StencilMask(GLuint mask) { EVENT(""(GLuint mask = %d)"", mask); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilMask(context, mask)) { return; } context->stencilMask(mask); } } void GL_APIENTRY StencilMaskSeparate(GLenum face, GLuint mask) { EVENT(""(GLenum face = 0x%X, GLuint mask = %d)"", face, mask); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilMaskSeparate(context, face, mask)) { return; } context->stencilMaskSeparate(face, mask); } } void GL_APIENTRY StencilOp(GLenum fail, GLenum zfail, GLenum zpass) { EVENT(""(GLenum fail = 0x%X, GLenum zfail = 0x%X, GLenum zpas = 0x%Xs)"", fail, zfail, zpass); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilOp(context, fail, zfail, zpass)) { return; } context->stencilOp(fail, zfail, zpass); } } void GL_APIENTRY StencilOpSeparate(GLenum face, GLenum fail, GLenum zfail, GLenum zpass) { EVENT(""(GLenum face = 0x%X, GLenum fail = 0x%X, GLenum zfail = 0x%X, GLenum zpas = 0x%Xs)"", face, fail, zfail, zpass); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateStencilOpSeparate(context, face, fail, zfail, zpass)) { return; } context->stencilOpSeparate(face, fail, zfail, zpass); } } void GL_APIENTRY TexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const GLvoid* pixels) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLint internalformat = %d, GLsizei width = %d, GLsizei height = %d, "" ""GLint border = %d, GLenum format = 0x%X, GLenum type = 0x%X, const GLvoid* pixels = 0x%0.8p)"", target, level, internalformat, width, height, border, format, type, pixels); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexImage2D(context, target, level, internalformat, width, height, border, format, type, pixels)) { return; } context->texImage2D(target, level, internalformat, width, height, border, format, type, pixels); } } void GL_APIENTRY TexParameterf(GLenum target, GLenum pname, GLfloat param) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %f)"", target, pname, param); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexParameterf(context, target, pname, param)) { return; } context->texParameterf(target, pname, param); } } void GL_APIENTRY TexParameterfv(GLenum target, GLenum pname, const GLfloat *params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, const GLfloat* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexParameterfv(context, target, pname, params)) { return; } context->texParameterfv(target, pname, params); } } void GL_APIENTRY TexParameteri(GLenum target, GLenum pname, GLint param) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, GLint param = %d)"", target, pname, param); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexParameteri(context, target, pname, param)) { return; } context->texParameteri(target, pname, param); } } void GL_APIENTRY TexParameteriv(GLenum target, GLenum pname, const GLint *params) { EVENT(""(GLenum target = 0x%X, GLenum pname = 0x%X, const GLint* params = 0x%0.8p)"", target, pname, params); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexParameteriv(context, target, pname, params)) { return; } context->texParameteriv(target, pname, params); } } void GL_APIENTRY TexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const GLvoid* pixels) { EVENT(""(GLenum target = 0x%X, GLint level = %d, GLint xoffset = %d, GLint yoffset = %d, "" ""GLsizei width = %d, GLsizei height = %d, GLenum format = 0x%X, GLenum type = 0x%X, "" ""const GLvoid* pixels = 0x%0.8p)"", target, level, xoffset, yoffset, width, height, format, type, pixels); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateTexSubImage2D(context, target, level, xoffset, yoffset, width, height, format, type, pixels)) { return; } context->texSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } } void GL_APIENTRY Uniform1f(GLint location, GLfloat x) { EVENT(""(GLint location = %d, GLfloat x = %f)"", location, x); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform1f(context, location, x)) { return; } context->uniform1f(location, x); } } void GL_APIENTRY Uniform1fv(GLint location, GLsizei count, const GLfloat* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform1fv(context, location, count, v)) { return; } context->uniform1fv(location, count, v); } } void GL_APIENTRY Uniform1i(GLint location, GLint x) { EVENT(""(GLint location = %d, GLint x = %d)"", location, x); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform1iv(context, location, 1, &x)) { return; } context->uniform1i(location, x); } } void GL_APIENTRY Uniform1iv(GLint location, GLsizei count, const GLint* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform1iv(context, location, count, v)) { return; } context->uniform1iv(location, count, v); } } void GL_APIENTRY Uniform2f(GLint location, GLfloat x, GLfloat y) { EVENT(""(GLint location = %d, GLfloat x = %f, GLfloat y = %f)"", location, x, y); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform2f(context, location, x, y)) { return; } context->uniform2f(location, x, y); } } void GL_APIENTRY Uniform2fv(GLint location, GLsizei count, const GLfloat* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform2fv(context, location, count, v)) { return; } context->uniform2fv(location, count, v); } } void GL_APIENTRY Uniform2i(GLint location, GLint x, GLint y) { EVENT(""(GLint location = %d, GLint x = %d, GLint y = %d)"", location, x, y); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform2i(context, location, x, y)) { return; } context->uniform2i(location, x, y); } } void GL_APIENTRY Uniform2iv(GLint location, GLsizei count, const GLint* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform2iv(context, location, count, v)) { return; } context->uniform2iv(location, count, v); } } void GL_APIENTRY Uniform3f(GLint location, GLfloat x, GLfloat y, GLfloat z) { EVENT(""(GLint location = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f)"", location, x, y, z); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform3f(context, location, x, y, z)) { return; } context->uniform3f(location, x, y, z); } } void GL_APIENTRY Uniform3fv(GLint location, GLsizei count, const GLfloat* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform3fv(context, location, count, v)) { return; } context->uniform3fv(location, count, v); } } void GL_APIENTRY Uniform3i(GLint location, GLint x, GLint y, GLint z) { EVENT(""(GLint location = %d, GLint x = %d, GLint y = %d, GLint z = %d)"", location, x, y, z); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform3i(context, location, x, y, z)) { return; } context->uniform3i(location, x, y, z); } } void GL_APIENTRY Uniform3iv(GLint location, GLsizei count, const GLint* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform3iv(context, location, count, v)) { return; } context->uniform3iv(location, count, v); } } void GL_APIENTRY Uniform4f(GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { EVENT(""(GLint location = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f, GLfloat w = %f)"", location, x, y, z, w); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform4f(context, location, x, y, z, w)) { return; } context->uniform4f(location, x, y, z, w); } } void GL_APIENTRY Uniform4fv(GLint location, GLsizei count, const GLfloat* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLfloat* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform4fv(context, location, count, v)) { return; } context->uniform4fv(location, count, v); } } void GL_APIENTRY Uniform4i(GLint location, GLint x, GLint y, GLint z, GLint w) { EVENT(""(GLint location = %d, GLint x = %d, GLint y = %d, GLint z = %d, GLint w = %d)"", location, x, y, z, w); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform4i(context, location, x, y, z, w)) { return; } context->uniform4i(location, x, y, z, w); } } void GL_APIENTRY Uniform4iv(GLint location, GLsizei count, const GLint* v) { EVENT(""(GLint location = %d, GLsizei count = %d, const GLint* v = 0x%0.8p)"", location, count, v); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniform4iv(context, location, count, v)) { return; } context->uniform4iv(location, count, v); } } void GL_APIENTRY UniformMatrix2fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { EVENT(""(GLint location = %d, GLsizei count = %d, GLboolean transpose = %u, const GLfloat* value = 0x%0.8p)"", location, count, transpose, value); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniformMatrix2fv(context, location, count, transpose, value)) { return; } context->uniformMatrix2fv(location, count, transpose, value); } } void GL_APIENTRY UniformMatrix3fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { EVENT(""(GLint location = %d, GLsizei count = %d, GLboolean transpose = %u, const GLfloat* value = 0x%0.8p)"", location, count, transpose, value); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniformMatrix3fv(context, location, count, transpose, value)) { return; } context->uniformMatrix3fv(location, count, transpose, value); } } void GL_APIENTRY UniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { EVENT(""(GLint location = %d, GLsizei count = %d, GLboolean transpose = %u, const GLfloat* value = 0x%0.8p)"", location, count, transpose, value); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUniformMatrix4fv(context, location, count, transpose, value)) { return; } context->uniformMatrix4fv(location, count, transpose, value); } } void GL_APIENTRY UseProgram(GLuint program) { EVENT(""(GLuint program = %d)"", program); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateUseProgram(context, program)) { return; } context->useProgram(program); } } void GL_APIENTRY ValidateProgram(GLuint program) { EVENT(""(GLuint program = %d)"", program); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateValidateProgram(context, program)) { return; } context->validateProgram(program); } } void GL_APIENTRY VertexAttrib1f(GLuint index, GLfloat x) { EVENT(""(GLuint index = %d, GLfloat x = %f)"", index, x); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib1f(context, index, x)) { return; } context->vertexAttrib1f(index, x); } } void GL_APIENTRY VertexAttrib1fv(GLuint index, const GLfloat* values) { EVENT(""(GLuint index = %d, const GLfloat* values = 0x%0.8p)"", index, values); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib1fv(context, index, values)) { return; } context->vertexAttrib1fv(index, values); } } void GL_APIENTRY VertexAttrib2f(GLuint index, GLfloat x, GLfloat y) { EVENT(""(GLuint index = %d, GLfloat x = %f, GLfloat y = %f)"", index, x, y); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib2f(context, index, x, y)) { return; } context->vertexAttrib2f(index, x, y); } } void GL_APIENTRY VertexAttrib2fv(GLuint index, const GLfloat* values) { EVENT(""(GLuint index = %d, const GLfloat* values = 0x%0.8p)"", index, values); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib2fv(context, index, values)) { return; } context->vertexAttrib2fv(index, values); } } void GL_APIENTRY VertexAttrib3f(GLuint index, GLfloat x, GLfloat y, GLfloat z) { EVENT(""(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f)"", index, x, y, z); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib3f(context, index, x, y, z)) { return; } context->vertexAttrib3f(index, x, y, z); } } void GL_APIENTRY VertexAttrib3fv(GLuint index, const GLfloat* values) { EVENT(""(GLuint index = %d, const GLfloat* values = 0x%0.8p)"", index, values); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib3fv(context, index, values)) { return; } context->vertexAttrib3fv(index, values); } } void GL_APIENTRY VertexAttrib4f(GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w) { EVENT(""(GLuint index = %d, GLfloat x = %f, GLfloat y = %f, GLfloat z = %f, GLfloat w = %f)"", index, x, y, z, w); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib4f(context, index, x, y, z, w)) { return; } context->vertexAttrib4f(index, x, y, z, w); } } void GL_APIENTRY VertexAttrib4fv(GLuint index, const GLfloat* values) { EVENT(""(GLuint index = %d, const GLfloat* values = 0x%0.8p)"", index, values); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttrib4fv(context, index, values)) { return; } context->vertexAttrib4fv(index, values); } } void GL_APIENTRY VertexAttribPointer(GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* ptr) { EVENT(""(GLuint index = %d, GLint size = %d, GLenum type = 0x%X, "" ""GLboolean normalized = %u, GLsizei stride = %d, const GLvoid* ptr = 0x%0.8p)"", index, size, type, normalized, stride, ptr); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateVertexAttribPointer(context, index, size, type, normalized, stride, ptr)) { return; } context->vertexAttribPointer(index, size, type, normalized, stride, ptr); } } void GL_APIENTRY Viewport(GLint x, GLint y, GLsizei width, GLsizei height) { EVENT(""(GLint x = %d, GLint y = %d, GLsizei width = %d, GLsizei height = %d)"", x, y, width, height); Context *context = GetValidGlobalContext(); if (context) { if (!context->skipValidation() && !ValidateViewport(context, x, y, width, height)) { return; } context->viewport(x, y, width, height); } } } // namespace gl ",16349,True,4449.974328213028,median "/* * Copyright (C) 2012 Google Inc. 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 Google Inc. 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. */ #include ""platform/Decimal.h"" #include ""testing/gtest/include/gtest/gtest.h"" #include ""wtf/MathExtras.h"" #include ""wtf/text/CString.h"" #include namespace blink { // Simulate core/html/forms/StepRange class DecimalStepRange { public: Decimal maximum; Decimal minimum; Decimal step; DecimalStepRange(const Decimal& minimum, const Decimal& maximum, const Decimal& step) : maximum(maximum), minimum(minimum), step(step) {} Decimal clampValue(Decimal value) const { const Decimal result = minimum + ((value - minimum) / step).round() * step; ASSERT(result.isFinite()); return result > maximum ? result - step : result; } }; class DecimalTest : public ::testing::Test { protected: using Sign = Decimal::Sign; static const Sign Positive = Decimal::Positive; static const Sign Negative = Decimal::Negative; Decimal encode(uint64_t coefficient, int exponent, Sign sign) { return Decimal(sign, exponent, coefficient); } Decimal fromString(const String& string) { return Decimal::fromString(string); } Decimal stepDown(const String& minimum, const String& maximum, const String& step, const String& valueString, int numberOfStepTimes) { DecimalStepRange stepRange(fromString(minimum), fromString(maximum), fromString(step)); Decimal value = fromString(valueString); for (int i = 0; i < numberOfStepTimes; ++i) { value -= stepRange.step; value = stepRange.clampValue(value); } return value; } Decimal stepUp(const String& minimum, const String& maximum, const String& step, const String& valueString, int numberOfStepTimes) { DecimalStepRange stepRange(fromString(minimum), fromString(maximum), fromString(step)); Decimal value = fromString(valueString); for (int i = 0; i < numberOfStepTimes; ++i) { value += stepRange.step; value = stepRange.clampValue(value); } return value; } }; // FIXME: We should use expectedSign without ""Decimal::"", however, g++ causes // undefined references for DecimalTest::Positive and Negative. #define EXPECT_DECIMAL_ENCODED_DATA_EQ(expectedCoefficient, expectedExponent, \\ expectedSign, decimal) \\ EXPECT_EQ((expectedCoefficient), (decimal).value().coefficient()); \\ EXPECT_EQ((expectedExponent), (decimal).value().exponent()); \\ EXPECT_EQ(Decimal::expectedSign, (decimal).value().getSign()); #define EXPECT_DECIMAL_STREQ(expected, decimal) \\ EXPECT_STREQ((expected), (decimal).toString().ascii().data()) TEST_F(DecimalTest, Abs) { EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Positive).abs()); EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Negative).abs()); EXPECT_EQ(encode(0, 10, Positive), encode(0, 10, Positive).abs()); EXPECT_EQ(encode(0, 10, Positive), encode(0, 10, Negative).abs()); EXPECT_EQ(encode(0, -10, Positive), encode(0, -10, Positive).abs()); EXPECT_EQ(encode(0, -10, Positive), encode(0, -10, Negative).abs()); EXPECT_EQ(encode(1, 0, Positive), encode(1, 0, Positive).abs()); EXPECT_EQ(encode(1, 0, Positive), encode(1, 0, Negative).abs()); EXPECT_EQ(encode(1, 10, Positive), encode(1, 10, Positive).abs()); EXPECT_EQ(encode(1, 10, Positive), encode(1, 10, Negative).abs()); EXPECT_EQ(encode(1, -10, Positive), encode(1, -10, Positive).abs()); EXPECT_EQ(encode(1, -10, Positive), encode(1, -10, Negative).abs()); } TEST_F(DecimalTest, AbsBigExponent) { EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).abs()); EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Negative).abs()); } TEST_F(DecimalTest, AbsSmallExponent) { EXPECT_EQ(encode(1, -1000, Positive), encode(1, -1000, Positive).abs()); EXPECT_EQ(encode(1, -1000, Positive), encode(1, -1000, Negative).abs()); } TEST_F(DecimalTest, AbsSpecialValues) { EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).abs()); EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).abs()); EXPECT_EQ(Decimal::nan(), Decimal::nan().abs()); } TEST_F(DecimalTest, Add) { EXPECT_EQ(encode(0, 0, Positive), Decimal(0) + Decimal(0)); EXPECT_EQ(Decimal(1), Decimal(2) + Decimal(-1)); EXPECT_EQ(Decimal(1), Decimal(-1) + Decimal(2)); EXPECT_EQ(encode(100, 0, Positive), Decimal(99) + Decimal(1)); EXPECT_EQ(encode(100, 0, Negative), Decimal(-50) + Decimal(-50)); EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), encode(1, 50, Positive) + Decimal(1)); EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), Decimal(1) + encode(1, 50, Positive)); EXPECT_EQ(encode(UINT64_C(10000000001), 0, Positive), encode(1, 10, Positive) + Decimal(1)); EXPECT_EQ(encode(UINT64_C(10000000001), 0, Positive), Decimal(1) + encode(1, 10, Positive)); EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) + encode(1, 0, Positive)); EXPECT_EQ(encode(2, -1022, Positive), encode(1, -1022, Positive) + encode(1, -1022, Positive)); } TEST_F(DecimalTest, AddBigExponent) { EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, 0, Positive)); EXPECT_EQ(encode(2, 1022, Positive), encode(1, 1022, Positive) + encode(1, 1022, Positive)); EXPECT_EQ(Decimal::infinity(Positive), encode(std::numeric_limits::max(), 1022, Positive) + encode(1, 0, Positive)); EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, -1000, Positive)); } TEST_F(DecimalTest, AddSmallExponent) { EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) + encode(1, 0, Positive)); EXPECT_EQ(encode(2, -1022, Positive), encode(1, -1022, Positive) + encode(1, -1022, Positive)); } TEST_F(DecimalTest, AddSpecialValues) { const Decimal Infinity(Decimal::infinity(Positive)); const Decimal MinusInfinity(Decimal::infinity(Negative)); const Decimal NaN(Decimal::nan()); const Decimal Ten(10); EXPECT_EQ(Infinity, Infinity + Infinity); EXPECT_EQ(NaN, Infinity + MinusInfinity); EXPECT_EQ(NaN, MinusInfinity + Infinity); EXPECT_EQ(MinusInfinity, MinusInfinity + MinusInfinity); EXPECT_EQ(Infinity, Infinity + Ten); EXPECT_EQ(Infinity, Ten + Infinity); EXPECT_EQ(MinusInfinity, MinusInfinity + Ten); EXPECT_EQ(MinusInfinity, Ten + MinusInfinity); EXPECT_EQ(NaN, NaN + NaN); EXPECT_EQ(NaN, NaN + Ten); EXPECT_EQ(NaN, Ten + NaN); EXPECT_EQ(NaN, NaN - Infinity); EXPECT_EQ(NaN, NaN - MinusInfinity); EXPECT_EQ(NaN, Infinity - NaN); EXPECT_EQ(NaN, MinusInfinity - NaN); } TEST_F(DecimalTest, Ceil) { EXPECT_EQ(Decimal(1), Decimal(1).ceil()); EXPECT_EQ(Decimal(1), encode(1, -10, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(11, -1, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(13, -1, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(15, -1, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(19, -1, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(151, -2, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(101, -2, Positive).ceil()); EXPECT_EQ(Decimal(1), encode(199, -3, Positive).ceil()); EXPECT_EQ(Decimal(2), encode(199, -2, Positive).ceil()); EXPECT_EQ(Decimal(3), encode(209, -2, Positive).ceil()); EXPECT_EQ(Decimal(-1), Decimal(-1).ceil()); EXPECT_EQ(Decimal(0), encode(1, -10, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(11, -1, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(13, -1, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(15, -1, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(19, -1, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(151, -2, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(101, -2, Negative).ceil()); EXPECT_EQ(Decimal(0), encode(199, -3, Negative).ceil()); EXPECT_EQ(Decimal(-1), encode(199, -2, Negative).ceil()); EXPECT_EQ(Decimal(-2), encode(209, -2, Negative).ceil()); EXPECT_EQ(Decimal(1), encode(UINT64_C(123456789012345678), -18, Positive).ceil()); } TEST_F(DecimalTest, CeilingBigExponent) { EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).ceil()); EXPECT_EQ(encode(1, 1000, Negative), encode(1, 1000, Negative).ceil()); } TEST_F(DecimalTest, CeilingSmallExponent) { EXPECT_EQ(encode(1, 0, Positive), encode(1, -1000, Positive).ceil()); EXPECT_EQ(encode(0, 0, Negative), encode(1, -1000, Negative).ceil()); } TEST_F(DecimalTest, CeilingSpecialValues) { EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).ceil()); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).ceil()); EXPECT_EQ(Decimal::nan(), Decimal::nan().ceil()); } TEST_F(DecimalTest, Compare) { EXPECT_TRUE(Decimal(0) == Decimal(0)); EXPECT_TRUE(Decimal(0) != Decimal(1)); EXPECT_TRUE(Decimal(0) < Decimal(1)); EXPECT_TRUE(Decimal(0) <= Decimal(0)); EXPECT_TRUE(Decimal(0) > Decimal(-1)); EXPECT_TRUE(Decimal(0) >= Decimal(0)); EXPECT_FALSE(Decimal(1) == Decimal(2)); EXPECT_FALSE(Decimal(1) != Decimal(1)); EXPECT_FALSE(Decimal(1) < Decimal(0)); EXPECT_FALSE(Decimal(1) <= Decimal(0)); EXPECT_FALSE(Decimal(1) > Decimal(2)); EXPECT_FALSE(Decimal(1) >= Decimal(2)); } TEST_F(DecimalTest, CompareBigExponent) { EXPECT_TRUE(encode(1, 1000, Positive) == encode(1, 1000, Positive)); EXPECT_FALSE(encode(1, 1000, Positive) != encode(1, 1000, Positive)); EXPECT_FALSE(encode(1, 1000, Positive) < encode(1, 1000, Positive)); EXPECT_TRUE(encode(1, 1000, Positive) <= encode(1, 1000, Positive)); EXPECT_FALSE(encode(1, 1000, Positive) > encode(1, 1000, Positive)); EXPECT_TRUE(encode(1, 1000, Positive) >= encode(1, 1000, Positive)); EXPECT_TRUE(encode(1, 1000, Negative) == encode(1, 1000, Negative)); EXPECT_FALSE(encode(1, 1000, Negative) != encode(1, 1000, Negative)); EXPECT_FALSE(encode(1, 1000, Negative) < encode(1, 1000, Negative)); EXPECT_TRUE(encode(1, 1000, Negative) <= encode(1, 1000, Negative)); EXPECT_FALSE(encode(1, 1000, Negative) > encode(1, 1000, Negative)); EXPECT_TRUE(encode(1, 1000, Negative) >= encode(1, 1000, Negative)); EXPECT_FALSE(encode(2, 1000, Positive) == encode(1, 1000, Positive)); EXPECT_TRUE(encode(2, 1000, Positive) != encode(1, 1000, Positive)); EXPECT_FALSE(encode(2, 1000, Positive) < encode(1, 1000, Positive)); EXPECT_FALSE(encode(2, 1000, Positive) <= encode(1, 1000, Positive)); EXPECT_TRUE(encode(2, 1000, Positive) > encode(1, 1000, Positive)); EXPECT_TRUE(encode(2, 1000, Positive) >= encode(1, 1000, Positive)); EXPECT_FALSE(encode(2, 1000, Negative) == encode(1, 1000, Negative)); EXPECT_TRUE(encode(2, 1000, Negative) != encode(1, 1000, Negative)); EXPECT_TRUE(encode(2, 1000, Negative) < encode(1, 1000, Negative)); EXPECT_TRUE(encode(2, 1000, Negative) <= encode(1, 1000, Negative)); EXPECT_FALSE(encode(2, 1000, Negative) > encode(1, 1000, Negative)); EXPECT_FALSE(encode(2, 1000, Negative) >= encode(1, 1000, Negative)); } TEST_F(DecimalTest, CompareSmallExponent) { EXPECT_TRUE(encode(1, -1000, Positive) == encode(1, -1000, Positive)); EXPECT_FALSE(encode(1, -1000, Positive) != encode(1, -1000, Positive)); EXPECT_FALSE(encode(1, -1000, Positive) < encode(1, -1000, Positive)); EXPECT_TRUE(encode(1, -1000, Positive) <= encode(1, -1000, Positive)); EXPECT_FALSE(encode(1, -1000, Positive) > encode(1, -1000, Positive)); EXPECT_TRUE(encode(1, -1000, Positive) >= encode(1, -1000, Positive)); EXPECT_TRUE(encode(1, -1000, Negative) == encode(1, -1000, Negative)); EXPECT_FALSE(encode(1, -1000, Negative) != encode(1, -1000, Negative)); EXPECT_FALSE(encode(1, -1000, Negative) < encode(1, -1000, Negative)); EXPECT_TRUE(encode(1, -1000, Negative) <= encode(1, -1000, Negative)); EXPECT_FALSE(encode(1, -1000, Negative) > encode(1, -1000, Negative)); EXPECT_TRUE(encode(1, -1000, Negative) >= encode(1, -1000, Negative)); EXPECT_FALSE(encode(2, -1000, Positive) == encode(1, -1000, Positive)); EXPECT_TRUE(encode(2, -1000, Positive) != encode(1, -1000, Positive)); EXPECT_FALSE(encode(2, -1000, Positive) < encode(1, -1000, Positive)); EXPECT_FALSE(encode(2, -1000, Positive) <= encode(1, -1000, Positive)); EXPECT_TRUE(encode(2, -1000, Positive) > encode(1, -1000, Positive)); EXPECT_TRUE(encode(2, -1000, Positive) >= encode(1, -1000, Positive)); EXPECT_FALSE(encode(2, -1000, Negative) == encode(1, -1000, Negative)); EXPECT_TRUE(encode(2, -1000, Negative) != encode(1, -1000, Negative)); EXPECT_TRUE(encode(2, -1000, Negative) < encode(1, -1000, Negative)); EXPECT_TRUE(encode(2, -1000, Negative) <= encode(1, -1000, Negative)); EXPECT_FALSE(encode(2, -1000, Negative) > encode(1, -1000, Negative)); EXPECT_FALSE(encode(2, -1000, Negative) >= encode(1, -1000, Negative)); } TEST_F(DecimalTest, CompareSpecialValues) { const Decimal Infinity(Decimal::infinity(Positive)); const Decimal MinusInfinity(Decimal::infinity(Negative)); const Decimal NaN(Decimal::nan()); const Decimal Zero(Decimal::zero(Positive)); const Decimal MinusZero(Decimal::zero(Negative)); const Decimal Ten(10); EXPECT_TRUE(Zero == Zero); EXPECT_FALSE(Zero != Zero); EXPECT_FALSE(Zero < Zero); EXPECT_TRUE(Zero <= Zero); EXPECT_FALSE(Zero > Zero); EXPECT_TRUE(Zero >= Zero); EXPECT_TRUE(Zero == MinusZero); EXPECT_FALSE(Zero != MinusZero); EXPECT_FALSE(Zero < MinusZero); EXPECT_TRUE(Zero <= MinusZero); EXPECT_FALSE(Zero > MinusZero); EXPECT_TRUE(Zero >= MinusZero); EXPECT_TRUE(MinusZero == Zero); EXPECT_FALSE(MinusZero != Zero); EXPECT_FALSE(MinusZero < Zero); EXPECT_TRUE(MinusZero <= Zero); EXPECT_FALSE(MinusZero > Zero); EXPECT_TRUE(MinusZero >= Zero); EXPECT_TRUE(MinusZero == MinusZero); EXPECT_FALSE(MinusZero != MinusZero); EXPECT_FALSE(MinusZero < MinusZero); EXPECT_TRUE(MinusZero <= MinusZero); EXPECT_FALSE(MinusZero > MinusZero); EXPECT_TRUE(MinusZero >= MinusZero); EXPECT_TRUE(Infinity == Infinity); EXPECT_FALSE(Infinity != Infinity); EXPECT_FALSE(Infinity < Infinity); EXPECT_TRUE(Infinity <= Infinity); EXPECT_FALSE(Infinity > Infinity); EXPECT_TRUE(Infinity >= Infinity); EXPECT_FALSE(Infinity == Ten); EXPECT_TRUE(Infinity != Ten); EXPECT_FALSE(Infinity < Ten); EXPECT_FALSE(Infinity <= Ten); EXPECT_TRUE(Infinity > Ten); EXPECT_TRUE(Infinity >= Ten); EXPECT_FALSE(Infinity == MinusInfinity); EXPECT_TRUE(Infinity != MinusInfinity); EXPECT_FALSE(Infinity < MinusInfinity); EXPECT_FALSE(Infinity <= MinusInfinity); EXPECT_TRUE(Infinity > MinusInfinity); EXPECT_TRUE(Infinity >= MinusInfinity); EXPECT_FALSE(Infinity == NaN); EXPECT_FALSE(Infinity != NaN); EXPECT_FALSE(Infinity < NaN); EXPECT_FALSE(Infinity <= NaN); EXPECT_FALSE(Infinity > NaN); EXPECT_FALSE(Infinity >= NaN); EXPECT_FALSE(MinusInfinity == Infinity); EXPECT_TRUE(MinusInfinity != Infinity); EXPECT_TRUE(MinusInfinity < Infinity); EXPECT_TRUE(MinusInfinity <= Infinity); EXPECT_FALSE(MinusInfinity > Infinity); EXPECT_FALSE(MinusInfinity >= Infinity); EXPECT_FALSE(MinusInfinity == Ten); EXPECT_TRUE(MinusInfinity != Ten); EXPECT_TRUE(MinusInfinity < Ten); EXPECT_TRUE(MinusInfinity <= Ten); EXPECT_FALSE(MinusInfinity > Ten); EXPECT_FALSE(MinusInfinity >= Ten); EXPECT_TRUE(MinusInfinity == MinusInfinity); EXPECT_FALSE(MinusInfinity != MinusInfinity); EXPECT_FALSE(MinusInfinity < MinusInfinity); EXPECT_TRUE(MinusInfinity <= MinusInfinity); EXPECT_FALSE(MinusInfinity > MinusInfinity); EXPECT_TRUE(MinusInfinity >= MinusInfinity); EXPECT_FALSE(MinusInfinity == NaN); EXPECT_FALSE(MinusInfinity != NaN); EXPECT_FALSE(MinusInfinity < NaN); EXPECT_FALSE(MinusInfinity <= NaN); EXPECT_FALSE(MinusInfinity > NaN); EXPECT_FALSE(MinusInfinity >= NaN); EXPECT_FALSE(NaN == Infinity); EXPECT_FALSE(NaN != Infinity); EXPECT_FALSE(NaN < Infinity); EXPECT_FALSE(NaN <= Infinity); EXPECT_FALSE(NaN > Infinity); EXPECT_FALSE(NaN >= Infinity); EXPECT_FALSE(NaN == Ten); EXPECT_FALSE(NaN != Ten); EXPECT_FALSE(NaN < Ten); EXPECT_FALSE(NaN <= Ten); EXPECT_FALSE(NaN > Ten); EXPECT_FALSE(NaN >= Ten); EXPECT_FALSE(NaN == MinusInfinity); EXPECT_FALSE(NaN != MinusInfinity); EXPECT_FALSE(NaN < MinusInfinity); EXPECT_FALSE(NaN <= MinusInfinity); EXPECT_FALSE(NaN > MinusInfinity); EXPECT_FALSE(NaN >= MinusInfinity); EXPECT_TRUE(NaN == NaN); EXPECT_FALSE(NaN != NaN); EXPECT_FALSE(NaN < NaN); EXPECT_TRUE(NaN <= NaN); EXPECT_FALSE(NaN > NaN); EXPECT_TRUE(NaN >= NaN); } TEST_F(DecimalTest, Constructor) { EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Positive, encode(0, 0, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Negative, encode(0, 0, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 0, Positive, encode(1, 0, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 0, Negative, encode(1, 0, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1022, Positive, encode(1, 1022, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1022, Negative, encode(1, 1022, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1023, Positive, encode(1, 1023, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ(1u, 1023, Negative, encode(1, 1023, Negative)); EXPECT_TRUE(encode(1, 2000, Positive).isInfinity()); EXPECT_TRUE(encode(1, 2000, Negative).isInfinity()); EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Positive, encode(1, -2000, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ(0u, 0, Negative, encode(1, -2000, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(99999999999999998), 0, Positive, encode(UINT64_C(99999999999999998), 0, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(99999999999999998), 0, Negative, encode(UINT64_C(99999999999999998), 0, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(99999999999999999), 0, Positive, encode(UINT64_C(99999999999999999), 0, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(99999999999999999), 0, Negative, encode(UINT64_C(99999999999999999), 0, Negative)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(100000000000000000), 0, Positive, encode(UINT64_C(100000000000000000), 0, Positive)); EXPECT_DECIMAL_ENCODED_DATA_EQ( UINT64_C(100000000000000000), 0, Negative, encode(UINT64_C(100000000000000000), 0, Negative)); } TEST_F(DecimalTest, Division) { EXPECT_EQ(encode(0, 0, Positive), Decimal(0) / Decimal(1)); EXPECT_EQ(encode(2, 0, Negative), Decimal(2) / Decimal(-1)); EXPECT_EQ(encode(5, -1, Negative), Decimal(-1) / Decimal(2)); EXPECT_EQ(encode(99, 0, Positive), Decimal(99) / Decimal(1)); EXPECT_EQ(Decimal(1), Decimal(-50) / Decimal(-50)); EXPECT_EQ(encode(UINT64_C(333333333333333333), -18, Positive), Decimal(1) / Decimal(3)); EXPECT_EQ(encode(UINT64_C(12345678901234), -1, Positive), encode(UINT64_C(12345678901234), 0, Positive) / Decimal(10)); EXPECT_EQ(encode(UINT64_C(500005000050000500), -18, Positive), Decimal(50000) / Decimal(99999)); } TEST_F(DecimalTest, DivisionBigExponent) { EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) / encode(1, 0, Positive)); EXPECT_EQ(encode(1, 0, Positive), encode(1, 1022, Positive) / encode(1, 1022, Positive)); EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive) / encode(1, -1000, Positive)); } TEST_F(DecimalTest, DivisionSmallExponent) { EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive) / encode(1, 0, Positive)); EXPECT_EQ(encode(1, 0, Positive), encode(1, -1022, Positive) / encode(1, -1022, Positive)); } TEST_F(DecimalTest, DivisionSpecialValues) { const Decimal Infinity(Decimal::infinity(Positive)); const Decimal MinusInfinity(Decimal::infinity(Negative)); const Decimal NaN(Decimal::nan()); const Decimal Zero(Decimal::zero(Positive)); const Decimal MinusZero(Decimal::zero(Negative)); const Decimal Ten(10); const Decimal MinusTen(-10); EXPECT_EQ(NaN, Zero / Zero); EXPECT_EQ(NaN, Zero / MinusZero); EXPECT_EQ(NaN, MinusZero / Zero); EXPECT_EQ(NaN, MinusZero / MinusZero); EXPECT_EQ(Infinity, Ten / Zero); EXPECT_EQ(MinusInfinity, Ten / MinusZero); EXPECT_EQ(MinusInfinity, MinusTen / Zero); EXPECT_EQ(Infinity, MinusTen / MinusZero); EXPECT_EQ(Infinity, Infinity / Zero); EXPECT_EQ(MinusInfinity, Infinity / MinusZero); EXPECT_EQ(MinusInfinity, MinusInfinity / Zero); EXPECT_EQ(Infinity, MinusInfinity / MinusZero); EXPECT_EQ(NaN, Infinity / Infinity); EXPECT_EQ(NaN, Infinity / MinusInfinity); EXPECT_EQ(NaN, MinusInfinity / Infinity); EXPECT_EQ(NaN, MinusInfinity / MinusInfinity); EXPECT_EQ(Zero, Ten / Infinity); EXPECT_EQ(MinusZero, Ten / MinusInfinity); EXPECT_EQ(MinusZero, MinusTen / Infinity); EXPECT_EQ(Zero, MinusTen / MinusInfinity); EXPECT_EQ(NaN, NaN / NaN); EXPECT_EQ(NaN, NaN / Ten); EXPECT_EQ(NaN, Ten / NaN); EXPECT_EQ(NaN, NaN / Infinity); EXPECT_EQ(NaN, NaN / MinusInfinity); EXPECT_EQ(NaN, Infinity / NaN); EXPECT_EQ(NaN, MinusInfinity / NaN); } TEST_F(DecimalTest, EncodedData) { EXPECT_EQ(encode(0, 0, Positive), encode(0, 0, Positive)); EXPECT_EQ(encode(0, 0, Negative), encode(0, 0, Negative)); EXPECT_EQ(Decimal(1), Decimal(1)); EXPECT_EQ(encode(1, 0, Negative), encode(1, 0, Negative)); EXPECT_EQ(Decimal::infinity(Positive), encode(1, 2000, Positive)); EXPECT_EQ(Decimal::zero(Positive), encode(1, -2000, Positive)); } TEST_F(DecimalTest, Floor) { EXPECT_EQ(Decimal(1), Decimal(1).floor()); EXPECT_EQ(Decimal(0), encode(1, -10, Positive).floor()); EXPECT_EQ(Decimal(1), encode(11, -1, Positive).floor()); EXPECT_EQ(Decimal(1), encode(13, -1, Positive).floor()); EXPECT_EQ(Decimal(1), encode(15, -1, Positive).floor()); EXPECT_EQ(Decimal(1), encode(19, -1, Positive).floor()); EXPECT_EQ(Decimal(1), encode(193332, -5, Positive).floor()); EXPECT_EQ(Decimal(12), encode(12002, -3, Positive).floor()); EXPECT_EQ(Decimal(-1), Decimal(-1).floor()); EXPECT_EQ(Decimal(-1), encode(1, -10, Negative).floor()); EXPECT_EQ(Decimal(-2), encode(11, -1, Negative).floor()); EXPECT_EQ(Decimal(-2), encode(13, -1, Negative).floor()); EXPECT_EQ(Decimal(-2), encode(15, -1, Negative).floor()); EXPECT_EQ(Decimal(-2), encode(19, -1, Negative).floor()); EXPECT_EQ(Decimal(-2), encode(193332, -5, Negative).floor()); EXPECT_EQ(Decimal(-13), encode(12002, -3, Negative).floor()); // crbug.com/572769 EXPECT_EQ(Decimal(-1), encode(992971299197409433, -18, Negative).floor()); } TEST_F(DecimalTest, FloorBigExponent) { EXPECT_EQ(encode(1, 1000, Positive), encode(1, 1000, Positive).floor()); EXPECT_EQ(encode(1, 1000, Negative), encode(1, 1000, Negative).floor()); } TEST_F(DecimalTest, FloorSmallExponent) { EXPECT_EQ(encode(0, 0, Positive), encode(1, -1000, Positive).floor()); EXPECT_EQ(encode(1, 0, Negative), encode(1, -1000, Negative).floor()); } TEST_F(DecimalTest, FloorSpecialValues) { EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).floor()); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).floor()); EXPECT_EQ(Decimal::nan(), Decimal::nan().floor()); } TEST_F(DecimalTest, FromDouble) { EXPECT_EQ(encode(0, 0, Positive), Decimal::fromDouble(0.0)); EXPECT_EQ(encode(0, 0, Negative), Decimal::fromDouble(-0.0)); EXPECT_EQ(encode(1, 0, Positive), Decimal::fromDouble(1)); EXPECT_EQ(encode(1, 0, Negative), Decimal::fromDouble(-1)); EXPECT_EQ(encode(123, 0, Positive), Decimal::fromDouble(123)); EXPECT_EQ(encode(123, 0, Negative), Decimal::fromDouble(-123)); EXPECT_EQ(encode(1, -1, Positive), Decimal::fromDouble(0.1)); EXPECT_EQ(encode(1, -1, Negative), Decimal::fromDouble(-0.1)); } TEST_F(DecimalTest, FromDoubleLimits) { EXPECT_EQ(encode(UINT64_C(2220446049250313), -31, Positive), Decimal::fromDouble(std::numeric_limits::epsilon())); EXPECT_EQ(encode(UINT64_C(2220446049250313), -31, Negative), Decimal::fromDouble(-std::numeric_limits::epsilon())); EXPECT_EQ(encode(UINT64_C(17976931348623157), 292, Positive), Decimal::fromDouble(std::numeric_limits::max())); EXPECT_EQ(encode(UINT64_C(17976931348623157), 292, Negative), Decimal::fromDouble(-std::numeric_limits::max())); EXPECT_EQ(encode(UINT64_C(22250738585072014), -324, Positive), Decimal::fromDouble(std::numeric_limits::min())); EXPECT_EQ(encode(UINT64_C(22250738585072014), -324, Negative), Decimal::fromDouble(-std::numeric_limits::min())); EXPECT_TRUE(Decimal::fromDouble(std::numeric_limits::infinity()) .isInfinity()); EXPECT_TRUE(Decimal::fromDouble(-std::numeric_limits::infinity()) .isInfinity()); EXPECT_TRUE( Decimal::fromDouble(std::numeric_limits::quiet_NaN()).isNaN()); EXPECT_TRUE( Decimal::fromDouble(-std::numeric_limits::quiet_NaN()).isNaN()); } TEST_F(DecimalTest, FromInt32) { EXPECT_EQ(encode(0, 0, Positive), Decimal(0)); EXPECT_EQ(encode(1, 0, Positive), Decimal(1)); EXPECT_EQ(encode(1, 0, Negative), Decimal(-1)); EXPECT_EQ(encode(100, 0, Positive), Decimal(100)); EXPECT_EQ(encode(100, 0, Negative), Decimal(-100)); EXPECT_EQ(encode(0x7FFFFFFF, 0, Positive), Decimal(std::numeric_limits::max())); EXPECT_EQ(encode(0x80000000u, 0, Negative), Decimal(std::numeric_limits::min())); } TEST_F(DecimalTest, FromString) { EXPECT_EQ(encode(0, 0, Positive), fromString(""0"")); EXPECT_EQ(encode(0, 0, Negative), fromString(""-0"")); EXPECT_EQ(Decimal(1), fromString(""1"")); EXPECT_EQ(encode(1, 0, Negative), fromString(""-1"")); EXPECT_EQ(Decimal(1), fromString(""01"")); EXPECT_EQ(encode(3, 0, Positive), fromString(""+3"")); EXPECT_EQ(encode(0, 3, Positive), fromString(""0E3"")); EXPECT_EQ(encode(5, -1, Positive), fromString("".5"")); EXPECT_EQ(encode(100, 0, Positive), fromString(""100"")); EXPECT_EQ(encode(100, 0, Negative), fromString(""-100"")); EXPECT_EQ(encode(123, -2, Positive), fromString(""1.23"")); EXPECT_EQ(encode(123, -2, Negative), fromString(""-1.23"")); EXPECT_EQ(encode(123, 8, Positive), fromString(""1.23E10"")); EXPECT_EQ(encode(123, 8, Negative), fromString(""-1.23E10"")); EXPECT_EQ(encode(123, 8, Positive), fromString(""1.23E+10"")); EXPECT_EQ(encode(123, 8, Negative), fromString(""-1.23E+10"")); EXPECT_EQ(encode(123, -12, Positive), fromString(""1.23E-10"")); EXPECT_EQ(encode(123, -12, Negative), fromString(""-1.23E-10"")); EXPECT_EQ(encode(5, -7, Positive), fromString(""0.0000005"")); EXPECT_EQ(encode(0, 0, Positive), fromString(""0e9999"")); EXPECT_EQ(encode(123, -3, Positive), fromString(""0.123"")); EXPECT_EQ(encode(0, -2, Positive), fromString(""00.00"")); EXPECT_EQ(encode(1, 2, Positive), fromString(""1E2"")); EXPECT_EQ(Decimal::infinity(Positive), fromString(""1E20000"")); EXPECT_EQ(Decimal::zero(Positive), fromString(""1E-20000"")); EXPECT_EQ(encode(1000, 1023, Positive), fromString(""1E1026"")); EXPECT_EQ(Decimal::zero(Positive), fromString(""1E-1026"")); EXPECT_EQ(Decimal::infinity(Positive), fromString(""1234567890E1036"")); // 2^1024 const uint64_t leadingDigitsOf2PowerOf1024 = UINT64_C(17976931348623159); EXPECT_EQ(encode(leadingDigitsOf2PowerOf1024, 292, Positive), fromString(""1797693134862315907729305190789024733617976978942306572"" ""7343008115773267580550096313270847732240753602112011387"" ""9871393357658789768814416622492847430639474124377767893"" ""4248654852763022196012460941194530829520850057688381506"" ""8234246288147391311054082723716335051068458629823994724"" ""5938479716304835356329624224137216"")); } // These strings are look like proper number, but we don't accept them. TEST_F(DecimalTest, FromStringLikeNumber) { EXPECT_EQ(Decimal::nan(), fromString("" 123 "")); EXPECT_EQ(Decimal::nan(), fromString(""1,234"")); } // fromString doesn't support infinity and NaN. TEST_F(DecimalTest, FromStringSpecialValues) { EXPECT_EQ(Decimal::nan(), fromString(""INF"")); EXPECT_EQ(Decimal::nan(), fromString(""Infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""+Infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""+infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""-Infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""-infinity"")); EXPECT_EQ(Decimal::nan(), fromString(""NaN"")); EXPECT_EQ(Decimal::nan(), fromString(""nan"")); EXPECT_EQ(Decimal::nan(), fromString(""+NaN"")); EXPECT_EQ(Decimal::nan(), fromString(""+nan"")); EXPECT_EQ(Decimal::nan(), fromString(""-NaN"")); EXPECT_EQ(Decimal::nan(), fromString(""-nan"")); } TEST_F(DecimalTest, fromStringTruncated) { EXPECT_EQ(Decimal::nan(), fromString(""x"")); EXPECT_EQ(Decimal::nan(), fromString(""0."")); EXPECT_EQ(Decimal::nan(), fromString(""1x"")); EXPECT_EQ(Decimal::nan(), fromString(""1Ex"")); EXPECT_EQ(Decimal::nan(), fromString(""1E2x"")); EXPECT_EQ(Decimal::nan(), fromString(""1E+x"")); } TEST_F(DecimalTest, Multiplication) { EXPECT_EQ(encode(0, 0, Positive), Decimal(0) * Decimal(0)); EXPECT_EQ(encode(2, 0, Negative), Decimal(2) * Decimal(-1)); EXPECT_EQ(encode(2, 0, Negative), Decimal(-1) * Decimal(2)); EXPECT_EQ(encode(99, 0, Positive), Decimal(99) * Decimal(1)); EXPECT_EQ(encode(2500, 0, Positive), Decimal(-50) * Decimal(-50)); EXPECT_EQ(encode(1, 21, Positive), encode(UINT64_C(10000000000), 0, Positive) * encode(UINT64_C(100000000000), 0, Positive)); } TEST_F(DecimalTest, MultiplicationBigExponent) { EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) * encode(1, 0, Positive)); EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive) * encode(1, 1022, Positive)); EXPECT_EQ(encode(1, 22, Positive), encode(1, 1022, Positive) * encode(1, -1000, Positive)); } TEST_F(DecimalTest, MultiplicationSmallExponent) { EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive) * encode(1, 0, Positive)); EXPECT_EQ(encode(0, 0, Positive), encode(1, -1022, Positive) * encode(1, -1022, Positive)); } TEST_F(DecimalTest, MultiplicationSpecialValues) { const Decimal Infinity(Decimal::infinity(Positive)); const Decimal MinusInfinity(Decimal::infinity(Negative)); const Decimal NaN(Decimal::nan()); const Decimal Ten(10); const Decimal MinusTen(-10); const Decimal Zero(Decimal::zero(Positive)); const Decimal MinusZero(Decimal::zero(Negative)); EXPECT_EQ(Infinity, Infinity * Infinity); EXPECT_EQ(MinusInfinity, Infinity * MinusInfinity); EXPECT_EQ(MinusInfinity, MinusInfinity * Infinity); EXPECT_EQ(Infinity, MinusInfinity * MinusInfinity); EXPECT_EQ(NaN, Infinity * Zero); EXPECT_EQ(NaN, Zero * MinusInfinity); EXPECT_EQ(NaN, MinusInfinity * Zero); EXPECT_EQ(NaN, MinusInfinity * Zero); EXPECT_EQ(NaN, Infinity * MinusZero); EXPECT_EQ(NaN, MinusZero * MinusInfinity); EXPECT_EQ(NaN, MinusInfinity * MinusZero); EXPECT_EQ(NaN, MinusInfinity * MinusZero); EXPECT_EQ(Infinity, Infinity * Ten); EXPECT_EQ(Infinity, Ten * Infinity); EXPECT_EQ(MinusInfinity, MinusInfinity * Ten); EXPECT_EQ(MinusInfinity, Ten * MinusInfinity); EXPECT_EQ(MinusInfinity, Infinity * MinusTen); EXPECT_EQ(MinusInfinity, MinusTen * Infinity); EXPECT_EQ(Infinity, MinusInfinity * MinusTen); EXPECT_EQ(Infinity, MinusTen * MinusInfinity); EXPECT_EQ(NaN, NaN * NaN); EXPECT_EQ(NaN, NaN * Ten); EXPECT_EQ(NaN, Ten * NaN); EXPECT_EQ(NaN, NaN * Infinity); EXPECT_EQ(NaN, NaN * MinusInfinity); EXPECT_EQ(NaN, Infinity * NaN); EXPECT_EQ(NaN, MinusInfinity * NaN); } TEST_F(DecimalTest, Negate) { EXPECT_EQ(encode(0, 0, Negative), -encode(0, 0, Positive)); EXPECT_EQ(encode(0, 0, Positive), -encode(0, 0, Negative)); EXPECT_EQ(encode(0, 10, Negative), -encode(0, 10, Positive)); EXPECT_EQ(encode(0, 10, Positive), -encode(0, 10, Negative)); EXPECT_EQ(encode(0, -10, Negative), -encode(0, -10, Positive)); EXPECT_EQ(encode(0, -10, Positive), -encode(0, -10, Negative)); EXPECT_EQ(encode(1, 0, Negative), -encode(1, 0, Positive)); EXPECT_EQ(encode(1, 0, Positive), -encode(1, 0, Negative)); EXPECT_EQ(encode(1, 10, Negative), -encode(1, 10, Positive)); EXPECT_EQ(encode(1, 10, Positive), -encode(1, 10, Negative)); EXPECT_EQ(encode(1, -10, Negative), -encode(1, -10, Positive)); EXPECT_EQ(encode(1, -10, Positive), -encode(1, -10, Negative)); } TEST_F(DecimalTest, NegateBigExponent) { EXPECT_EQ(encode(1, 1000, Negative), -encode(1, 1000, Positive)); EXPECT_EQ(encode(1, 1000, Positive), -encode(1, 1000, Negative)); } TEST_F(DecimalTest, NegateSmallExponent) { EXPECT_EQ(encode(1, -1000, Negative), -encode(1, -1000, Positive)); EXPECT_EQ(encode(1, -1000, Positive), -encode(1, -1000, Negative)); } TEST_F(DecimalTest, NegateSpecialValues) { EXPECT_EQ(Decimal::infinity(Negative), -Decimal::infinity(Positive)); EXPECT_EQ(Decimal::infinity(Positive), -Decimal::infinity(Negative)); EXPECT_EQ(Decimal::nan(), -Decimal::nan()); } TEST_F(DecimalTest, Predicates) { EXPECT_TRUE(Decimal::zero(Positive).isFinite()); EXPECT_FALSE(Decimal::zero(Positive).isInfinity()); EXPECT_FALSE(Decimal::zero(Positive).isNaN()); EXPECT_TRUE(Decimal::zero(Positive).isPositive()); EXPECT_FALSE(Decimal::zero(Positive).isNegative()); EXPECT_FALSE(Decimal::zero(Positive).isSpecial()); EXPECT_TRUE(Decimal::zero(Positive).isZero()); EXPECT_TRUE(Decimal::zero(Negative).isFinite()); EXPECT_FALSE(Decimal::zero(Negative).isInfinity()); EXPECT_FALSE(Decimal::zero(Negative).isNaN()); EXPECT_FALSE(Decimal::zero(Negative).isPositive()); EXPECT_TRUE(Decimal::zero(Negative).isNegative()); EXPECT_FALSE(Decimal::zero(Negative).isSpecial()); EXPECT_TRUE(Decimal::zero(Negative).isZero()); EXPECT_TRUE(Decimal(123).isFinite()); EXPECT_FALSE(Decimal(123).isInfinity()); EXPECT_FALSE(Decimal(123).isNaN()); EXPECT_TRUE(Decimal(123).isPositive()); EXPECT_FALSE(Decimal(123).isNegative()); EXPECT_FALSE(Decimal(123).isSpecial()); EXPECT_FALSE(Decimal(123).isZero()); EXPECT_TRUE(Decimal(-123).isFinite()); EXPECT_FALSE(Decimal(-123).isInfinity()); EXPECT_FALSE(Decimal(-123).isNaN()); EXPECT_FALSE(Decimal(-123).isPositive()); EXPECT_TRUE(Decimal(-123).isNegative()); EXPECT_FALSE(Decimal(-123).isSpecial()); EXPECT_FALSE(Decimal(-123).isZero()); } TEST_F(DecimalTest, PredicatesSpecialValues) { EXPECT_FALSE(Decimal::infinity(Positive).isFinite()); EXPECT_TRUE(Decimal::infinity(Positive).isInfinity()); EXPECT_FALSE(Decimal::infinity(Positive).isNaN()); EXPECT_TRUE(Decimal::infinity(Positive).isPositive()); EXPECT_FALSE(Decimal::infinity(Positive).isNegative()); EXPECT_TRUE(Decimal::infinity(Positive).isSpecial()); EXPECT_FALSE(Decimal::infinity(Positive).isZero()); EXPECT_FALSE(Decimal::infinity(Negative).isFinite()); EXPECT_TRUE(Decimal::infinity(Negative).isInfinity()); EXPECT_FALSE(Decimal::infinity(Negative).isNaN()); EXPECT_FALSE(Decimal::infinity(Negative).isPositive()); EXPECT_TRUE(Decimal::infinity(Negative).isNegative()); EXPECT_TRUE(Decimal::infinity(Negative).isSpecial()); EXPECT_FALSE(Decimal::infinity(Negative).isZero()); EXPECT_FALSE(Decimal::nan().isFinite()); EXPECT_FALSE(Decimal::nan().isInfinity()); EXPECT_TRUE(Decimal::nan().isNaN()); EXPECT_TRUE(Decimal::nan().isSpecial()); EXPECT_FALSE(Decimal::nan().isZero()); } // LayoutTests/fast/forms/number/number-stepup-stepdown-from-renderer TEST_F(DecimalTest, RealWorldExampleNumberStepUpStepDownFromRenderer) { EXPECT_DECIMAL_STREQ(""10"", stepDown(""0"", ""100"", ""10"", ""19"", 1)); EXPECT_DECIMAL_STREQ(""90"", stepUp(""0"", ""99"", ""10"", ""89"", 1)); EXPECT_DECIMAL_STREQ( ""1"", stepUp(""0"", ""1"", ""0.33333333333333333"", ""0"", 3)); // step=1/3 EXPECT_DECIMAL_STREQ(""0.01"", stepUp(""0"", ""0.01"", ""0.0033333333333333333"", ""0"", 3)); // step=1/300 EXPECT_DECIMAL_STREQ( ""1"", stepUp(""0"", ""1"", ""0.003921568627450980"", ""0"", 255)); // step=1/255 EXPECT_DECIMAL_STREQ(""1"", stepUp(""0"", ""1"", ""0.1"", ""0"", 10)); } TEST_F(DecimalTest, RealWorldExampleNumberStepUpStepDownFromRendererRounding) { EXPECT_DECIMAL_STREQ(""5.015"", stepUp(""0"", ""100"", ""0.005"", ""5.005"", 2)); EXPECT_DECIMAL_STREQ(""5.06"", stepUp(""0"", ""100"", ""0.005"", ""5.005"", 11)); EXPECT_DECIMAL_STREQ(""5.065"", stepUp(""0"", ""100"", ""0.005"", ""5.005"", 12)); EXPECT_DECIMAL_STREQ(""5.015"", stepUp(""4"", ""9"", ""0.005"", ""5.005"", 2)); EXPECT_DECIMAL_STREQ(""5.06"", stepUp(""4"", ""9"", ""0.005"", ""5.005"", 11)); EXPECT_DECIMAL_STREQ(""5.065"", stepUp(""4"", ""9"", ""0.005"", ""5.005"", 12)); } TEST_F(DecimalTest, RealWorldExampleRangeStepUpStepDown) { EXPECT_DECIMAL_STREQ(""1e+38"", stepUp(""0"", ""1E38"", ""1"", ""1E38"", 9)); EXPECT_DECIMAL_STREQ(""1e+38"", stepDown(""0"", ""1E38"", ""1"", ""1E38"", 9)); } TEST_F(DecimalTest, Remainder) { EXPECT_EQ(encode(21, -1, Positive), encode(21, -1, Positive).remainder(3)); EXPECT_EQ(Decimal(1), Decimal(10).remainder(3)); EXPECT_EQ(Decimal(1), Decimal(10).remainder(-3)); EXPECT_EQ(encode(1, 0, Negative), Decimal(-10).remainder(3)); EXPECT_EQ(Decimal(-1), Decimal(-10).remainder(-3)); EXPECT_EQ(encode(2, -1, Positive), encode(102, -1, Positive).remainder(1)); EXPECT_EQ(encode(1, -1, Positive), Decimal(10).remainder(encode(3, -1, Positive))); EXPECT_EQ(Decimal(1), encode(36, -1, Positive).remainder(encode(13, -1, Positive))); EXPECT_EQ(encode(1, 86, Positive), (encode(1234, 100, Positive).remainder(Decimal(3)))); EXPECT_EQ(Decimal(500), (Decimal(500).remainder(1000))); EXPECT_EQ(Decimal(-500), (Decimal(-500).remainder(1000))); } TEST_F(DecimalTest, RemainderBigExponent) { EXPECT_EQ(encode(0, 1022, Positive), encode(1, 1022, Positive).remainder(encode(1, 0, Positive))); EXPECT_EQ(encode(0, 1022, Positive), encode(1, 1022, Positive).remainder(encode(1, 1022, Positive))); EXPECT_EQ(Decimal::infinity(Positive), encode(1, 1022, Positive).remainder(encode(1, -1000, Positive))); } TEST_F(DecimalTest, RemainderSmallExponent) { EXPECT_EQ(encode(1, -1022, Positive), encode(1, -1022, Positive).remainder(encode(1, 0, Positive))); EXPECT_EQ(encode(0, -1022, Positive), encode(1, -1022, Positive).remainder(encode(1, -1022, Positive))); } TEST_F(DecimalTest, RemainderSpecialValues) { EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).remainder(1)); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).remainder(1)); EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(1)); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Positive).remainder(-1)); EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).remainder(-1)); EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(-1)); EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).remainder(3)); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).remainder(3)); EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(3)); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Positive).remainder(-1)); EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Negative).remainder(-1)); EXPECT_EQ(Decimal::nan(), Decimal::nan().remainder(-1)); EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::infinity(Positive))); EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::infinity(Negative))); EXPECT_EQ(Decimal::nan(), Decimal(1).remainder(Decimal::nan())); } TEST_F(DecimalTest, Round) { EXPECT_EQ(Decimal(1), (Decimal(9) / Decimal(10)).round()); EXPECT_EQ(Decimal(25), (Decimal(5) / fromString(""0.200"")).round()); EXPECT_EQ(Decimal(3), (Decimal(5) / Decimal(2)).round()); EXPECT_EQ(Decimal(1), (Decimal(2) / Decimal(3)).round()); EXPECT_EQ(Decimal(3), (Decimal(10) / Decimal(3)).round()); EXPECT_EQ(Decimal(3), (Decimal(1) / fromString(""0.3"")).round()); EXPECT_EQ(Decimal(10), (Decimal(1) / fromString(""0.1"")).round()); EXPECT_EQ(Decimal(5), (Decimal(1) / fromString(""0.2"")).round()); EXPECT_EQ(Decimal(10), (fromString(""10.2"") / 1).round()); EXPECT_EQ(encode(1234, 100, Positive), encode(1234, 100, Positive).round()); EXPECT_EQ(Decimal(2), encode(190002, -5, Positive).round()); EXPECT_EQ(Decimal(2), encode(150002, -5, Positive).round()); EXPECT_EQ(Decimal(2), encode(150000, -5, Positive).round()); EXPECT_EQ(Decimal(12), encode(12492, -3, Positive).round()); EXPECT_EQ(Decimal(13), encode(12502, -3, Positive).round()); EXPECT_EQ(Decimal(-2), encode(190002, -5, Negative).round()); EXPECT_EQ(Decimal(-2), encode(150002, -5, Negative).round()); EXPECT_EQ(Decimal(-2), encode(150000, -5, Negative).round()); EXPECT_EQ(Decimal(-12), encode(12492, -3, Negative).round()); EXPECT_EQ(Decimal(-13), encode(12502, -3, Negative).round()); } TEST_F(DecimalTest, RoundSpecialValues) { EXPECT_EQ(Decimal::infinity(Positive), Decimal::infinity(Positive).round()); EXPECT_EQ(Decimal::infinity(Negative), Decimal::infinity(Negative).round()); EXPECT_EQ(Decimal::nan(), Decimal::nan().round()); } TEST_F(DecimalTest, Subtract) { EXPECT_EQ(encode(0, 0, Positive), Decimal(0) - Decimal(0)); EXPECT_EQ(encode(3, 0, Positive), Decimal(2) - Decimal(-1)); EXPECT_EQ(encode(3, 0, Negative), Decimal(-1) - Decimal(2)); EXPECT_EQ(encode(98, 0, Positive), Decimal(99) - Decimal(1)); EXPECT_EQ(encode(0, 0, Positive), Decimal(-50) - Decimal(-50)); EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Positive), encode(1, 50, Positive) - Decimal(1)); EXPECT_EQ(encode(UINT64_C(1000000000000000), 35, Negative), Decimal(1) - encode(1, 50, Positive)); } TEST_F(DecimalTest, SubtractBigExponent) { EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) - encode(1, 0, Positive)); EXPECT_EQ(encode(0, 0, Positive), encode(1, 1022, Positive) - encode(1, 1022, Positive)); EXPECT_EQ(encode(1, 1022, Positive), encode(1, 1022, Positive) + encode(1, -1000, Positive)); } TEST_F(DecimalTest, SubtractSmallExponent) { EXPECT_EQ(encode(UINT64_C(10000000000000000), -16, Negative), encode(1, -1022, Positive) - encode(1, 0, Positive)); EXPECT_EQ(encode(0, 0, Positive), encode(1, -1022, Positive) - encode(1, -1022, Positive)); } TEST_F(DecimalTest, SubtractSpecialValues) { const Decimal Infinity(Decimal::infinity(Positive)); const Decimal MinusInfinity(Decimal::infinity(Negative)); const Decimal NaN(Decimal::nan()); const Decimal Ten(10); EXPECT_EQ(NaN, Infinity - Infinity); EXPECT_EQ(Infinity, Infinity - MinusInfinity); EXPECT_EQ(MinusInfinity, MinusInfinity - Infinity); EXPECT_EQ(NaN, MinusInfinity - MinusInfinity); EXPECT_EQ(Infinity, Infinity - Ten); EXPECT_EQ(MinusInfinity, Ten - Infinity); EXPECT_EQ(MinusInfinity, MinusInfinity - Ten); EXPECT_EQ(Infinity, Ten - MinusInfinity); EXPECT_EQ(NaN, NaN - NaN); EXPECT_EQ(NaN, NaN - Ten); EXPECT_EQ(NaN, Ten - NaN); EXPECT_EQ(NaN, NaN - Infinity); EXPECT_EQ(NaN, NaN - MinusInfinity); EXPECT_EQ(NaN, Infinity - NaN); EXPECT_EQ(NaN, MinusInfinity - NaN); } TEST_F(DecimalTest, ToDouble) { EXPECT_EQ(0.0, encode(0, 0, Positive).toDouble()); EXPECT_EQ(-0.0, encode(0, 0, Negative).toDouble()); EXPECT_EQ(1.0, encode(1, 0, Positive).toDouble()); EXPECT_EQ(-1.0, encode(1, 0, Negative).toDouble()); EXPECT_EQ(0.1, encode(1, -1, Positive).toDouble()); EXPECT_EQ(-0.1, encode(1, -1, Negative).toDouble()); EXPECT_EQ(0.3, encode(3, -1, Positive).toDouble()); EXPECT_EQ(-0.3, encode(3, -1, Negative).toDouble()); EXPECT_EQ(0.6, encode(6, -1, Positive).toDouble()); EXPECT_EQ(-0.6, encode(6, -1, Negative).toDouble()); EXPECT_EQ(0.7, encode(7, -1, Positive).toDouble()); EXPECT_EQ(-0.7, encode(7, -1, Negative).toDouble()); EXPECT_EQ(0.01, encode(1, -2, Positive).toDouble()); EXPECT_EQ(0.001, encode(1, -3, Positive).toDouble()); EXPECT_EQ(0.0001, encode(1, -4, Positive).toDouble()); EXPECT_EQ(0.00001, encode(1, -5, Positive).toDouble()); EXPECT_EQ(1e+308, encode(1, 308, Positive).toDouble()); EXPECT_EQ(1e-307, encode(1, -307, Positive).toDouble()); EXPECT_TRUE(std::isinf(encode(1, 1000, Positive).toDouble())); EXPECT_EQ(0.0, encode(1, -1000, Positive).toDouble()); } TEST_F(DecimalTest, ToDoubleSpecialValues) { EXPECT_TRUE(std::isinf(Decimal::infinity(Decimal::Positive).toDouble())); EXPECT_TRUE(std::isinf(Decimal::infinity(Decimal::Negative).toDouble())); EXPECT_TRUE(std::isnan(Decimal::nan().toDouble())); } TEST_F(DecimalTest, ToString) { EXPECT_DECIMAL_STREQ(""0"", Decimal::zero(Positive)); EXPECT_DECIMAL_STREQ(""-0"", Decimal::zero(Negative)); EXPECT_DECIMAL_STREQ(""1"", Decimal(1)); EXPECT_DECIMAL_STREQ(""-1"", Decimal(-1)); EXPECT_DECIMAL_STREQ(""1234567"", Decimal(1234567)); EXPECT_DECIMAL_STREQ(""-1234567"", Decimal(-1234567)); EXPECT_DECIMAL_STREQ(""0.5"", encode(5, -1, Positive)); EXPECT_DECIMAL_STREQ(""-0.5"", encode(5, -1, Negative)); EXPECT_DECIMAL_STREQ(""12.345"", encode(12345, -3, Positive)); EXPECT_DECIMAL_STREQ(""-12.345"", encode(12345, -3, Negative)); EXPECT_DECIMAL_STREQ(""0.12345"", encode(12345, -5, Positive)); EXPECT_DECIMAL_STREQ(""-0.12345"", encode(12345, -5, Negative)); EXPECT_DECIMAL_STREQ(""50"", encode(50, 0, Positive)); EXPECT_DECIMAL_STREQ(""-50"", encode(50, 0, Negative)); EXPECT_DECIMAL_STREQ(""5e+1"", encode(5, 1, Positive)); EXPECT_DECIMAL_STREQ(""-5e+1"", encode(5, 1, Negative)); EXPECT_DECIMAL_STREQ(""5.678e+103"", encode(5678, 100, Positive)); EXPECT_DECIMAL_STREQ(""-5.678e+103"", encode(5678, 100, Negative)); EXPECT_DECIMAL_STREQ(""5.678e-97"", encode(5678, -100, Positive)); EXPECT_DECIMAL_STREQ(""-5.678e-97"", encode(5678, -100, Negative)); EXPECT_DECIMAL_STREQ(""8639999913600001"", encode(UINT64_C(8639999913600001), 0, Positive)); EXPECT_DECIMAL_STREQ( ""9007199254740991"", encode((static_cast(1) << DBL_MANT_DIG) - 1, 0, Positive)); EXPECT_DECIMAL_STREQ(""99999999999999999"", encode(UINT64_C(99999999999999999), 0, Positive)); EXPECT_DECIMAL_STREQ(""9.9999999999999999e+17"", encode(UINT64_C(99999999999999999), 1, Positive)); EXPECT_DECIMAL_STREQ(""9.9999999999999999e+18"", encode(UINT64_C(99999999999999999), 2, Positive)); EXPECT_DECIMAL_STREQ(""1e+16"", encode(UINT64_C(99999999999999999), -1, Positive)); EXPECT_DECIMAL_STREQ(""1000000000000000"", encode(UINT64_C(99999999999999999), -2, Positive)); EXPECT_DECIMAL_STREQ(""1"", encode(UINT64_C(99999999999999999), -17, Positive)); EXPECT_DECIMAL_STREQ(""0.001"", encode(UINT64_C(99999999999999999), -20, Positive)); EXPECT_DECIMAL_STREQ(""1e-83"", encode(UINT64_C(99999999999999999), -100, Positive)); } TEST_F(DecimalTest, ToStringSpecialValues) { EXPECT_DECIMAL_STREQ(""Infinity"", Decimal::infinity(Positive)); EXPECT_DECIMAL_STREQ(""-Infinity"", Decimal::infinity(Negative)); EXPECT_DECIMAL_STREQ(""NaN"", Decimal::nan()); } } // namespace blink ",16203,True,3474.935228023748,median "/*** * * Copyright (c) 1996-2001, Valve LLC. All rights reserved. * * This product contains software technology licensed from Id * Software, Inc. (""Id Technology""). Id Technology (c) 1996 Id Software, Inc. * All Rights Reserved. * * This source code contains proprietary and confidential information of * Valve LLC and its suppliers. Access to this code is restricted to * persons who have executed a written SDK license with Valve. Any access, * use or distribution of this code by or to any unlicensed person is illegal. * ****/ #if !defined( OEM_BUILD ) && !defined( HLDEMO_BUILD ) #include ""extdll.h"" #include ""util.h"" #include ""cbase.h"" #include ""monsters.h"" #include ""weapons.h"" #include ""nodes.h"" #include ""effects.h"" #define N_SCALE 15 #define N_SPHERES 20 class CNihilanth : public CBaseMonster { public: int Save( CSave &save ); int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; void Spawn( void ); void Precache( void ); int Classify( void ) { return CLASS_ALIEN_MILITARY; }; int BloodColor( void ) { return BLOOD_COLOR_YELLOW; } void Killed( entvars_t *pevAttacker, int iGib ); void GibMonster( void ); void SetObjectCollisionBox( void ) { pev->absmin = pev->origin + Vector( -16 * N_SCALE, -16 * N_SCALE, -48 * N_SCALE ); pev->absmax = pev->origin + Vector( 16 * N_SCALE, 16 * N_SCALE, 28 * N_SCALE ); } void HandleAnimEvent( MonsterEvent_t *pEvent ); void EXPORT StartupThink( void ); void EXPORT HuntThink( void ); void EXPORT CrashTouch( CBaseEntity *pOther ); void EXPORT DyingThink( void ); void EXPORT StartupUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void EXPORT NullThink( void ); void EXPORT CommandUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void FloatSequence( void ); void NextActivity( void ); void Flight( void ); BOOL AbsorbSphere( void ); BOOL EmitSphere( void ); void TargetSphere( USE_TYPE useType, float value ); CBaseEntity *RandomTargetname( const char *szName ); void ShootBalls( void ); void MakeFriend( Vector vecPos ); int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType); void PainSound( void ); void DeathSound( void ); static const char *pAttackSounds[]; // vocalization: play sometimes when he launches an attack static const char *pBallSounds[]; // the sound of the lightening ball launch static const char *pShootSounds[]; // grunting vocalization: play sometimes when he launches an attack static const char *pRechargeSounds[]; // vocalization: play when he recharges static const char *pLaughSounds[]; // vocalization: play sometimes when hit and still has lots of health static const char *pPainSounds[]; // vocalization: play sometimes when hit and has much less health and no more chargers static const char *pDeathSounds[]; // vocalization: play as he dies // x_teleattack1.wav the looping sound of the teleport attack ball. float m_flForce; float m_flNextPainSound; Vector m_velocity; Vector m_avelocity; Vector m_vecTarget; Vector m_posTarget; Vector m_vecDesired; Vector m_posDesired; float m_flMinZ; float m_flMaxZ; Vector m_vecGoal; float m_flLastSeen; float m_flPrevSeen; int m_irritation; int m_iLevel; int m_iTeleport; EHANDLE m_hRecharger; EHANDLE m_hSphere[N_SPHERES]; int m_iActiveSpheres; float m_flAdj; CSprite *m_pBall; char m_szRechargerTarget[64]; char m_szDrawUse[64]; char m_szTeleportUse[64]; char m_szTeleportTouch[64]; char m_szDeadUse[64]; char m_szDeadTouch[64]; float m_flShootEnd; float m_flShootTime; EHANDLE m_hFriend[3]; }; LINK_ENTITY_TO_CLASS( monster_nihilanth, CNihilanth ); TYPEDESCRIPTION CNihilanth::m_SaveData[] = { DEFINE_FIELD( CNihilanth, m_flForce, FIELD_FLOAT ), DEFINE_FIELD( CNihilanth, m_flNextPainSound, FIELD_TIME ), DEFINE_FIELD( CNihilanth, m_velocity, FIELD_VECTOR ), DEFINE_FIELD( CNihilanth, m_avelocity, FIELD_VECTOR ), DEFINE_FIELD( CNihilanth, m_vecTarget, FIELD_VECTOR ), DEFINE_FIELD( CNihilanth, m_posTarget, FIELD_POSITION_VECTOR ), DEFINE_FIELD( CNihilanth, m_vecDesired, FIELD_VECTOR ), DEFINE_FIELD( CNihilanth, m_posDesired, FIELD_POSITION_VECTOR ), DEFINE_FIELD( CNihilanth, m_flMinZ, FIELD_FLOAT ), DEFINE_FIELD( CNihilanth, m_flMaxZ, FIELD_FLOAT ), DEFINE_FIELD( CNihilanth, m_vecGoal, FIELD_VECTOR ), DEFINE_FIELD( CNihilanth, m_flLastSeen, FIELD_TIME ), DEFINE_FIELD( CNihilanth, m_flPrevSeen, FIELD_TIME ), DEFINE_FIELD( CNihilanth, m_irritation, FIELD_INTEGER ), DEFINE_FIELD( CNihilanth, m_iLevel, FIELD_INTEGER ), DEFINE_FIELD( CNihilanth, m_iTeleport, FIELD_INTEGER ), DEFINE_FIELD( CNihilanth, m_hRecharger, FIELD_EHANDLE ), DEFINE_ARRAY( CNihilanth, m_hSphere, FIELD_EHANDLE, N_SPHERES ), DEFINE_FIELD( CNihilanth, m_iActiveSpheres, FIELD_INTEGER ), DEFINE_FIELD( CNihilanth, m_flAdj, FIELD_FLOAT ), DEFINE_FIELD( CNihilanth, m_pBall, FIELD_CLASSPTR ), DEFINE_ARRAY( CNihilanth, m_szRechargerTarget, FIELD_CHARACTER, 64 ), DEFINE_ARRAY( CNihilanth, m_szDrawUse, FIELD_CHARACTER, 64 ), DEFINE_ARRAY( CNihilanth, m_szTeleportUse, FIELD_CHARACTER, 64 ), DEFINE_ARRAY( CNihilanth, m_szTeleportTouch, FIELD_CHARACTER, 64 ), DEFINE_ARRAY( CNihilanth, m_szDeadUse, FIELD_CHARACTER, 64 ), DEFINE_ARRAY( CNihilanth, m_szDeadTouch, FIELD_CHARACTER, 64 ), DEFINE_FIELD( CNihilanth, m_flShootEnd, FIELD_TIME ), DEFINE_FIELD( CNihilanth, m_flShootTime, FIELD_TIME ), DEFINE_ARRAY( CNihilanth, m_hFriend, FIELD_EHANDLE, 3 ), }; IMPLEMENT_SAVERESTORE( CNihilanth, CBaseMonster ); class CNihilanthHVR : public CBaseMonster { public: int Save( CSave &save ); int Restore( CRestore &restore ); static TYPEDESCRIPTION m_SaveData[]; void Spawn( void ); void Precache( void ); void CircleInit( CBaseEntity *pTarget ); void AbsorbInit( void ); void TeleportInit( CNihilanth *pOwner, CBaseEntity *pEnemy, CBaseEntity *pTarget, CBaseEntity *pTouch ); void GreenBallInit( void ); void ZapInit( CBaseEntity *pEnemy ); void EXPORT HoverThink( void ); BOOL CircleTarget( Vector vecTarget ); void EXPORT DissipateThink( void ); void EXPORT ZapThink( void ); void EXPORT TeleportThink( void ); void EXPORT TeleportTouch( CBaseEntity *pOther ); void EXPORT RemoveTouch( CBaseEntity *pOther ); void EXPORT BounceTouch( CBaseEntity *pOther ); void EXPORT ZapTouch( CBaseEntity *pOther ); CBaseEntity *RandomClassname( const char *szName ); // void EXPORT SphereUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); void MovetoTarget( Vector vecTarget ); virtual void Crawl( void ); void Zap( void ); void Teleport( void ); float m_flIdealVel; Vector m_vecIdeal; CNihilanth *m_pNihilanth; EHANDLE m_hTouch; int m_nFrames; }; LINK_ENTITY_TO_CLASS( nihilanth_energy_ball, CNihilanthHVR ); TYPEDESCRIPTION CNihilanthHVR::m_SaveData[] = { DEFINE_FIELD( CNihilanthHVR, m_flIdealVel, FIELD_FLOAT ), DEFINE_FIELD( CNihilanthHVR, m_vecIdeal, FIELD_VECTOR ), DEFINE_FIELD( CNihilanthHVR, m_pNihilanth, FIELD_CLASSPTR ), DEFINE_FIELD( CNihilanthHVR, m_hTouch, FIELD_EHANDLE ), DEFINE_FIELD( CNihilanthHVR, m_nFrames, FIELD_INTEGER ), }; IMPLEMENT_SAVERESTORE( CNihilanthHVR, CBaseMonster ); //========================================================= // Nihilanth, final Boss monster //========================================================= const char *CNihilanth::pAttackSounds[] = { ""X/x_attack1.wav"", ""X/x_attack2.wav"", ""X/x_attack3.wav"", }; const char *CNihilanth::pBallSounds[] = { ""X/x_ballattack1.wav"", }; const char *CNihilanth::pShootSounds[] = { ""X/x_shoot1.wav"", }; const char *CNihilanth::pRechargeSounds[] = { ""X/x_recharge1.wav"", ""X/x_recharge2.wav"", ""X/x_recharge3.wav"", }; const char *CNihilanth::pLaughSounds[] = { ""X/x_laugh1.wav"", ""X/x_laugh2.wav"", }; const char *CNihilanth::pPainSounds[] = { ""X/x_pain1.wav"", ""X/x_pain2.wav"", }; const char *CNihilanth::pDeathSounds[] = { ""X/x_die1.wav"", }; void CNihilanth :: Spawn( void ) { Precache( ); // motor pev->movetype = MOVETYPE_FLY; pev->solid = SOLID_BBOX; SET_MODEL(edict(), ""models/nihilanth.mdl""); // UTIL_SetSize(pev, Vector( -300, -300, 0), Vector(300, 300, 512)); UTIL_SetSize(pev, Vector( -32, -32, 0), Vector(32, 32, 64)); UTIL_SetOrigin( pev, pev->origin ); pev->flags |= FL_MONSTER; pev->takedamage = DAMAGE_AIM; pev->health = gSkillData.nihilanthHealth; pev->view_ofs = Vector( 0, 0, 300 ); m_flFieldOfView = -1; // 360 degrees pev->sequence = 0; ResetSequenceInfo( ); InitBoneControllers(); SetThink( &CNihilanth::StartupThink ); pev->nextthink = gpGlobals->time + 0.1; m_vecDesired = Vector( 1, 0, 0 ); m_posDesired = Vector( pev->origin.x, pev->origin.y, 512 ); m_iLevel = 1; m_iTeleport = 1; if (m_szRechargerTarget[0] == '\\0') strcpy( m_szRechargerTarget, ""n_recharger"" ); if (m_szDrawUse[0] == '\\0') strcpy( m_szDrawUse, ""n_draw"" ); if (m_szTeleportUse[0] == '\\0') strcpy( m_szTeleportUse, ""n_leaving"" ); if (m_szTeleportTouch[0] == '\\0') strcpy( m_szTeleportTouch, ""n_teleport"" ); if (m_szDeadUse[0] == '\\0') strcpy( m_szDeadUse, ""n_dead"" ); if (m_szDeadTouch[0] == '\\0') strcpy( m_szDeadTouch, ""n_ending"" ); // near death /* m_iTeleport = 10; m_iLevel = 10; m_irritation = 2; pev->health = 100; */ } void CNihilanth::Precache( void ) { PRECACHE_MODEL(""models/nihilanth.mdl""); PRECACHE_MODEL(""sprites/lgtning.spr""); UTIL_PrecacheOther( ""nihilanth_energy_ball"" ); UTIL_PrecacheOther( ""monster_alien_controller"" ); UTIL_PrecacheOther( ""monster_alien_slave"" ); PRECACHE_SOUND_ARRAY( pAttackSounds ); PRECACHE_SOUND_ARRAY( pBallSounds ); PRECACHE_SOUND_ARRAY( pShootSounds ); PRECACHE_SOUND_ARRAY( pRechargeSounds ); PRECACHE_SOUND_ARRAY( pLaughSounds ); PRECACHE_SOUND_ARRAY( pPainSounds ); PRECACHE_SOUND_ARRAY( pDeathSounds ); PRECACHE_SOUND(""debris/beamstart7.wav""); } void CNihilanth :: PainSound( void ) { if (m_flNextPainSound > gpGlobals->time) return; m_flNextPainSound = gpGlobals->time + RANDOM_FLOAT( 2, 5 ); if (pev->health > gSkillData.nihilanthHealth / 2) { EMIT_SOUND( edict(), CHAN_VOICE, RANDOM_SOUND_ARRAY( pLaughSounds ), 1.0, 0.2 ); } else if (m_irritation >= 2) { EMIT_SOUND( edict(), CHAN_VOICE, RANDOM_SOUND_ARRAY( pPainSounds ), 1.0, 0.2 ); } } void CNihilanth :: DeathSound( void ) { EMIT_SOUND( edict(), CHAN_VOICE, RANDOM_SOUND_ARRAY( pDeathSounds ), 1.0, 0.1 ); } void CNihilanth::NullThink( void ) { StudioFrameAdvance( ); pev->nextthink = gpGlobals->time + 0.5; } void CNihilanth::StartupUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { SetThink( &CNihilanth::HuntThink ); pev->nextthink = gpGlobals->time + 0.1; SetUse( &CNihilanth::CommandUse ); } void CNihilanth::StartupThink( void ) { m_irritation = 0; m_flAdj = 512; CBaseEntity *pEntity; pEntity = UTIL_FindEntityByTargetname( NULL, ""n_min""); if (pEntity) m_flMinZ = pEntity->pev->origin.z; else m_flMinZ = -4096; pEntity = UTIL_FindEntityByTargetname( NULL, ""n_max""); if (pEntity) m_flMaxZ = pEntity->pev->origin.z; else m_flMaxZ = 4096; m_hRecharger = this; for (int i = 0; i < N_SPHERES; i++) { EmitSphere( ); } m_hRecharger = NULL; SetThink( &CNihilanth::HuntThink); SetUse( &CNihilanth::CommandUse ); pev->nextthink = gpGlobals->time + 0.1; } void CNihilanth :: Killed( entvars_t *pevAttacker, int iGib ) { CBaseMonster::Killed( pevAttacker, iGib ); } void CNihilanth :: DyingThink( void ) { pev->nextthink = gpGlobals->time + 0.1; DispatchAnimEvents( ); StudioFrameAdvance( ); if (pev->deadflag == DEAD_NO) { DeathSound( ); pev->deadflag = DEAD_DYING; m_posDesired.z = m_flMaxZ; } if (pev->deadflag == DEAD_DYING) { Flight( ); if (fabs( pev->origin.z - m_flMaxZ ) < 16) { pev->velocity = Vector( 0, 0, 0 ); FireTargets( m_szDeadUse, this, this, USE_ON, 1.0 ); pev->deadflag = DEAD_DEAD; } } if (m_fSequenceFinished) { pev->avelocity.y += RANDOM_FLOAT( -100, 100 ); if (pev->avelocity.y < -100) pev->avelocity.y = -100; if (pev->avelocity.y > 100) pev->avelocity.y = 100; pev->sequence = LookupSequence( ""die1"" ); } if (m_pBall) { if (m_pBall->pev->renderamt > 0) { m_pBall->pev->renderamt = V_max( 0, m_pBall->pev->renderamt - 2); } else { UTIL_Remove( m_pBall ); m_pBall = NULL; } } Vector vecDir, vecSrc, vecAngles; UTIL_MakeAimVectors( pev->angles ); int iAttachment = RANDOM_LONG( 1, 4 ); do { vecDir = Vector( RANDOM_FLOAT( -1, 1 ), RANDOM_FLOAT( -1, 1 ), RANDOM_FLOAT( -1, 1 )); } while (DotProduct( vecDir, vecDir) > 1.0); switch( RANDOM_LONG( 1, 4 )) { case 1: // head vecDir.z = fabs( vecDir.z ) * 0.5; vecDir = vecDir + 2 * gpGlobals->v_up; break; case 2: // eyes if (DotProduct( vecDir, gpGlobals->v_forward ) < 0) vecDir = vecDir * -1; vecDir = vecDir + 2 * gpGlobals->v_forward; break; case 3: // left hand if (DotProduct( vecDir, gpGlobals->v_right ) > 0) vecDir = vecDir * -1; vecDir = vecDir - 2 * gpGlobals->v_right; break; case 4: // right hand if (DotProduct( vecDir, gpGlobals->v_right ) < 0) vecDir = vecDir * -1; vecDir = vecDir + 2 * gpGlobals->v_right; break; } GetAttachment( iAttachment - 1, vecSrc, vecAngles ); TraceResult tr; UTIL_TraceLine( vecSrc, vecSrc + vecDir * 4096, ignore_monsters, ENT(pev), &tr ); MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTPOINT ); WRITE_SHORT( entindex() + 0x1000 * iAttachment ); WRITE_COORD( tr.vecEndPos.x); WRITE_COORD( tr.vecEndPos.y); WRITE_COORD( tr.vecEndPos.z); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // frame start WRITE_BYTE( 10 ); // framerate WRITE_BYTE( 5 ); // life WRITE_BYTE( 100 ); // width WRITE_BYTE( 120 ); // noise WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 128 ); // r, g, b WRITE_BYTE( 255); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 10 ); // speed MESSAGE_END(); GetAttachment( 0, vecSrc, vecAngles ); CNihilanthHVR *pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = Vector ( RANDOM_FLOAT( -0.7, 0.7 ), RANDOM_FLOAT( -0.7, 0.7 ), 1.0 ) * 600.0; pEntity->GreenBallInit( ); return; } void CNihilanth::CrashTouch( CBaseEntity *pOther ) { // only crash if we hit something solid if ( pOther->pev->solid == SOLID_BSP) { SetTouch( NULL ); pev->nextthink = gpGlobals->time; } } void CNihilanth :: GibMonster( void ) { // EMIT_SOUND_DYN(edict(), CHAN_VOICE, ""common/bodysplat.wav"", 0.75, ATTN_NORM, 0, 200); } void CNihilanth :: FloatSequence( void ) { if (m_irritation >= 2) { pev->sequence = LookupSequence( ""float_open"" ); } else if (m_avelocity.y > 30) { pev->sequence = LookupSequence( ""walk_r"" ); } else if (m_avelocity.y < -30) { pev->sequence = LookupSequence( ""walk_l"" ); } else if (m_velocity.z > 30) { pev->sequence = LookupSequence( ""walk_u"" ); } else if (m_velocity.z < -30) { pev->sequence = LookupSequence( ""walk_d"" ); } else { pev->sequence = LookupSequence( ""float"" ); } } void CNihilanth :: ShootBalls( void ) { if (m_flShootEnd > gpGlobals->time) { Vector vecHand, vecAngle; while (m_flShootTime < m_flShootEnd && m_flShootTime < gpGlobals->time) { if (m_hEnemy != NULL) { Vector vecSrc, vecDir; CNihilanthHVR *pEntity; GetAttachment( 2, vecHand, vecAngle ); vecSrc = vecHand + pev->velocity * (m_flShootTime - gpGlobals->time); // vecDir = (m_posTarget - vecSrc).Normalize( ); vecDir = (m_posTarget - pev->origin).Normalize( ); vecSrc = vecSrc + vecDir * (gpGlobals->time - m_flShootTime); pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = vecDir * 200.0; pEntity->ZapInit( m_hEnemy ); GetAttachment( 3, vecHand, vecAngle ); vecSrc = vecHand + pev->velocity * (m_flShootTime - gpGlobals->time); // vecDir = (m_posTarget - vecSrc).Normalize( ); vecDir = (m_posTarget - pev->origin).Normalize( ); vecSrc = vecSrc + vecDir * (gpGlobals->time - m_flShootTime); pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = vecDir * 200.0; pEntity->ZapInit( m_hEnemy ); } m_flShootTime += 0.2; } } } void CNihilanth :: MakeFriend( Vector vecStart ) { int i; for (i = 0; i < 3; i++) { if (m_hFriend[i] != NULL && !m_hFriend[i]->IsAlive()) { if (pev->rendermode == kRenderNormal) // don't do it if they are already fading m_hFriend[i]->MyMonsterPointer()->FadeMonster( ); m_hFriend[i] = NULL; } if (m_hFriend[i] == NULL) { if (RANDOM_LONG(0, 1) == 0) { int iNode = WorldGraph.FindNearestNode ( vecStart, bits_NODE_AIR ); if (iNode != NO_NODE) { CNode &node = WorldGraph.Node( iNode ); TraceResult tr; UTIL_TraceHull( node.m_vecOrigin + Vector( 0, 0, 32 ), node.m_vecOrigin + Vector( 0, 0, 32 ), dont_ignore_monsters, large_hull, NULL, &tr ); if (tr.fStartSolid == 0) m_hFriend[i] = Create(""monster_alien_controller"", node.m_vecOrigin, pev->angles ); } } else { int iNode = WorldGraph.FindNearestNode ( vecStart, bits_NODE_LAND | bits_NODE_WATER ); if (iNode != NO_NODE) { CNode &node = WorldGraph.Node( iNode ); TraceResult tr; UTIL_TraceHull( node.m_vecOrigin + Vector( 0, 0, 36 ), node.m_vecOrigin + Vector( 0, 0, 36 ), dont_ignore_monsters, human_hull, NULL, &tr ); if (tr.fStartSolid == 0) m_hFriend[i] = Create(""monster_alien_slave"", node.m_vecOrigin, pev->angles ); } } if (m_hFriend[i] != NULL) { EMIT_SOUND( m_hFriend[i]->edict(), CHAN_WEAPON, ""debris/beamstart7.wav"", 1.0, ATTN_NORM ); } return; } } } void CNihilanth :: NextActivity( ) { UTIL_MakeAimVectors( pev->angles ); if (m_irritation >= 2) { if (m_pBall == NULL) { m_pBall = CSprite::SpriteCreate( ""sprites/tele1.spr"", pev->origin, TRUE ); if (m_pBall) { m_pBall->SetTransparency( kRenderTransAdd, 255, 255, 255, 255, kRenderFxNoDissipation ); m_pBall->SetAttachment( edict(), 1 ); m_pBall->SetScale( 4.0 ); m_pBall->pev->framerate = 10.0; m_pBall->TurnOn( ); } } if (m_pBall) { MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) + 0x1000 ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 255 ); // R WRITE_BYTE( 192 ); // G WRITE_BYTE( 64 ); // B WRITE_BYTE( 200 ); // life * 10 WRITE_COORD( 0 ); // decay MESSAGE_END(); } } if ((pev->health < gSkillData.nihilanthHealth / 2 || m_iActiveSpheres < N_SPHERES / 2) && m_hRecharger == NULL && m_iLevel <= 9) { char szName[64]; CBaseEntity *pEnt = NULL; CBaseEntity *pRecharger = NULL; float flDist = 8192; sprintf(szName, ""%s%d"", m_szRechargerTarget, m_iLevel ); while ((pEnt = UTIL_FindEntityByTargetname( pEnt, szName )) != NULL) { float flLocal = (pEnt->pev->origin - pev->origin).Length(); if (flLocal < flDist) { flDist = flLocal; pRecharger = pEnt; } } if (pRecharger) { m_hRecharger = pRecharger; m_posDesired = Vector( pev->origin.x, pev->origin.y, pRecharger->pev->origin.z ); m_vecDesired = (pRecharger->pev->origin - m_posDesired).Normalize( ); m_vecDesired.z = 0; m_vecDesired = m_vecDesired.Normalize(); } else { m_hRecharger = NULL; ALERT( at_aiconsole, ""nihilanth can't find %s\\n"", szName ); m_iLevel++; if (m_iLevel > 9) m_irritation = 2; } } float flDist = (m_posDesired - pev->origin).Length(); float flDot = DotProduct( m_vecDesired, gpGlobals->v_forward ); if (m_hRecharger != NULL) { // at we at power up yet? if (flDist < 128.0) { int iseq = LookupSequence( ""recharge"" ); if (iseq != pev->sequence) { char szText[64]; sprintf( szText, ""%s%d"", m_szDrawUse, m_iLevel ); FireTargets( szText, this, this, USE_ON, 1.0 ); ALERT( at_console, ""fireing %s\\n"", szText ); } pev->sequence = LookupSequence( ""recharge"" ); } else { FloatSequence( ); } return; } if (m_hEnemy != NULL && !m_hEnemy->IsAlive()) { m_hEnemy = NULL; } if (m_flLastSeen + 15 < gpGlobals->time) { m_hEnemy = NULL; } if (m_hEnemy == NULL) { Look( 4096 ); m_hEnemy = BestVisibleEnemy( ); } if (m_hEnemy != NULL && m_irritation != 0) { if (m_flLastSeen + 5 > gpGlobals->time && flDist < 256 && flDot > 0) { if (m_irritation >= 2 && pev->health < gSkillData.nihilanthHealth / 2.0) { pev->sequence = LookupSequence( ""attack1_open"" ); } else { if (RANDOM_LONG(0, 1 ) == 0) { pev->sequence = LookupSequence( ""attack1"" ); // zap } else { char szText[64]; sprintf( szText, ""%s%d"", m_szTeleportTouch, m_iTeleport ); CBaseEntity *pTouch = UTIL_FindEntityByTargetname( NULL, szText ); sprintf( szText, ""%s%d"", m_szTeleportUse, m_iTeleport ); CBaseEntity *pTrigger = UTIL_FindEntityByTargetname( NULL, szText ); if (pTrigger != NULL || pTouch != NULL) { pev->sequence = LookupSequence( ""attack2"" ); // teleport } else { m_iTeleport++; pev->sequence = LookupSequence( ""attack1"" ); // zap } } } return; } } FloatSequence( ); } void CNihilanth :: HuntThink( void ) { pev->nextthink = gpGlobals->time + 0.1; DispatchAnimEvents( ); StudioFrameAdvance( ); ShootBalls( ); // if dead, force cancelation of current animation if (pev->health <= 0) { SetThink( &CNihilanth::DyingThink ); m_fSequenceFinished = TRUE; return; } // ALERT( at_console, ""health %.0f\\n"", pev->health ); // if damaged, try to abosorb some spheres if (pev->health < gSkillData.nihilanthHealth && AbsorbSphere( )) { pev->health += gSkillData.nihilanthHealth / N_SPHERES; } // get new sequence if (m_fSequenceFinished) { // if (!m_fSequenceLoops) pev->frame = 0; NextActivity( ); ResetSequenceInfo( ); pev->framerate = 2.0 - 1.0 * (pev->health / gSkillData.nihilanthHealth); } // look for current enemy if (m_hEnemy != NULL && m_hRecharger == NULL) { if (FVisible( m_hEnemy )) { if (m_flLastSeen < gpGlobals->time - 5) m_flPrevSeen = gpGlobals->time; m_flLastSeen = gpGlobals->time; m_posTarget = m_hEnemy->pev->origin; m_vecTarget = (m_posTarget - pev->origin).Normalize(); m_vecDesired = m_vecTarget; m_posDesired = Vector( pev->origin.x, pev->origin.y, m_posTarget.z + m_flAdj ); } else { m_flAdj = V_min( m_flAdj + 10, 1000 ); } } // don't go too high if (m_posDesired.z > m_flMaxZ) m_posDesired.z = m_flMaxZ; // don't go too low if (m_posDesired.z < m_flMinZ) m_posDesired.z = m_flMinZ; Flight( ); } void CNihilanth :: Flight( void ) { // estimate where I'll be facing in one seconds UTIL_MakeAimVectors( pev->angles + m_avelocity ); // Vector vecEst1 = pev->origin + m_velocity + gpGlobals->v_up * m_flForce - Vector( 0, 0, 384 ); // float flSide = DotProduct( m_posDesired - vecEst1, gpGlobals->v_right ); float flSide = DotProduct( m_vecDesired, gpGlobals->v_right ); if (flSide < 0) { if (m_avelocity.y < 180) { m_avelocity.y += 6; // 9 * (3.0/2.0); } } else { if (m_avelocity.y > -180) { m_avelocity.y -= 6; // 9 * (3.0/2.0); } } m_avelocity.y *= 0.98; // estimate where I'll be in two seconds Vector vecEst = pev->origin + m_velocity * 2.0 + gpGlobals->v_up * m_flForce * 20; // add immediate force UTIL_MakeAimVectors( pev->angles ); m_velocity.x += gpGlobals->v_up.x * m_flForce; m_velocity.y += gpGlobals->v_up.y * m_flForce; m_velocity.z += gpGlobals->v_up.z * m_flForce; float flSpeed = m_velocity.Length(); float flDir = DotProduct( Vector( gpGlobals->v_forward.x, gpGlobals->v_forward.y, 0 ), Vector( m_velocity.x, m_velocity.y, 0 ) ); if (flDir < 0) flSpeed = -flSpeed; float flDist = DotProduct( m_posDesired - vecEst, gpGlobals->v_forward ); // sideways drag m_velocity.x = m_velocity.x * (1.0 - fabs( gpGlobals->v_right.x ) * 0.05); m_velocity.y = m_velocity.y * (1.0 - fabs( gpGlobals->v_right.y ) * 0.05); m_velocity.z = m_velocity.z * (1.0 - fabs( gpGlobals->v_right.z ) * 0.05); // general drag m_velocity = m_velocity * 0.995; // apply power to stay correct height if (m_flForce < 100 && vecEst.z < m_posDesired.z) { m_flForce += 10; } else if (m_flForce > -100 && vecEst.z > m_posDesired.z) { if (vecEst.z > m_posDesired.z) m_flForce -= 10; } UTIL_SetOrigin( pev, pev->origin + m_velocity * 0.1 ); pev->angles = pev->angles + m_avelocity * 0.1; // ALERT( at_console, ""%5.0f %5.0f : %4.0f : %3.0f : %2.0f\\n"", m_posDesired.z, pev->origin.z, m_velocity.z, m_avelocity.y, m_flForce ); } BOOL CNihilanth :: AbsorbSphere( void ) { for (int i = 0; i < N_SPHERES; i++) { if (m_hSphere[i] != NULL) { CNihilanthHVR *pSphere = (CNihilanthHVR *)((CBaseEntity *)m_hSphere[i]); pSphere->AbsorbInit( ); m_hSphere[i] = NULL; m_iActiveSpheres--; return TRUE; } } return FALSE; } BOOL CNihilanth :: EmitSphere( void ) { m_iActiveSpheres = 0; int empty = 0; for (int i = 0; i < N_SPHERES; i++) { if (m_hSphere[i] != NULL) { m_iActiveSpheres++; } else { empty = i; } } if (m_iActiveSpheres >= N_SPHERES) return FALSE; Vector vecSrc = m_hRecharger->pev->origin; CNihilanthHVR *pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = pev->origin - vecSrc; pEntity->CircleInit( this ); m_hSphere[empty] = pEntity; return TRUE; } void CNihilanth :: TargetSphere( USE_TYPE useType, float value ) { CBaseMonster *pSphere; int i; for (i = 0; i < N_SPHERES; i++) { if (m_hSphere[i] != NULL) { pSphere = m_hSphere[i]->MyMonsterPointer(); if (pSphere->m_hEnemy == NULL) break; } } if (i == N_SPHERES) { return; } Vector vecSrc, vecAngles; GetAttachment( 2, vecSrc, vecAngles ); UTIL_SetOrigin( pSphere->pev, vecSrc ); pSphere->Use( this, this, useType, value ); pSphere->pev->velocity = m_vecDesired * RANDOM_FLOAT( 50, 100 ) + Vector( RANDOM_FLOAT( -50, 50 ), RANDOM_FLOAT( -50, 50 ), RANDOM_FLOAT( -50, 50 ) ); } void CNihilanth :: HandleAnimEvent( MonsterEvent_t *pEvent ) { switch( pEvent->event ) { case 1: // shoot break; case 2: // zen if (m_hEnemy != NULL) { if (RANDOM_LONG(0,4) == 0) EMIT_SOUND( edict(), CHAN_VOICE, RANDOM_SOUND_ARRAY( pAttackSounds ), 1.0, 0.2 ); EMIT_SOUND( edict(), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pBallSounds ), 1.0, 0.2 ); MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) + 0x3000 ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 128 ); // R WRITE_BYTE( 128 ); // G WRITE_BYTE( 255 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 128 ); // decay MESSAGE_END(); MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) + 0x4000 ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 128 ); // R WRITE_BYTE( 128 ); // G WRITE_BYTE( 255 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 128 ); // decay MESSAGE_END(); m_flShootTime = gpGlobals->time; m_flShootEnd = gpGlobals->time + 1.0; } break; case 3: // prayer if (m_hEnemy != NULL) { char szText[32]; sprintf( szText, ""%s%d"", m_szTeleportTouch, m_iTeleport ); CBaseEntity *pTouch = UTIL_FindEntityByTargetname( NULL, szText ); sprintf( szText, ""%s%d"", m_szTeleportUse, m_iTeleport ); CBaseEntity *pTrigger = UTIL_FindEntityByTargetname( NULL, szText ); if (pTrigger != NULL || pTouch != NULL) { EMIT_SOUND( edict(), CHAN_VOICE, RANDOM_SOUND_ARRAY( pAttackSounds ), 1.0, 0.2 ); Vector vecSrc, vecAngles; GetAttachment( 2, vecSrc, vecAngles ); CNihilanthHVR *pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = pev->origin - vecSrc; pEntity->TeleportInit( this, m_hEnemy, pTrigger, pTouch ); } else { m_iTeleport++; // unexpected failure EMIT_SOUND( edict(), CHAN_WEAPON, RANDOM_SOUND_ARRAY( pBallSounds ), 1.0, 0.2 ); ALERT( at_aiconsole, ""nihilanth can't target %s\\n"", szText ); MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) + 0x3000 ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 128 ); // R WRITE_BYTE( 128 ); // G WRITE_BYTE( 255 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 128 ); // decay MESSAGE_END(); MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) + 0x4000 ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 128 ); // R WRITE_BYTE( 128 ); // G WRITE_BYTE( 255 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 128 ); // decay MESSAGE_END(); m_flShootTime = gpGlobals->time; m_flShootEnd = gpGlobals->time + 1.0; } } break; case 4: // get a sphere { if (m_hRecharger != NULL) { if (!EmitSphere( )) { m_hRecharger = NULL; } } } break; case 5: // start up sphere machine { EMIT_SOUND( edict(), CHAN_VOICE , RANDOM_SOUND_ARRAY( pRechargeSounds ), 1.0, 0.2 ); } break; case 6: if (m_hEnemy != NULL) { Vector vecSrc, vecAngles; GetAttachment( 2, vecSrc, vecAngles ); CNihilanthHVR *pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = pev->origin - vecSrc; pEntity->ZapInit( m_hEnemy ); } break; case 7: /* Vector vecSrc, vecAngles; GetAttachment( 0, vecSrc, vecAngles ); CNihilanthHVR *pEntity = (CNihilanthHVR *)Create( ""nihilanth_energy_ball"", vecSrc, pev->angles, edict() ); pEntity->pev->velocity = Vector ( RANDOM_FLOAT( -0.7, 0.7 ), RANDOM_FLOAT( -0.7, 0.7 ), 1.0 ) * 600.0; pEntity->GreenBallInit( ); */ break; } } void CNihilanth::CommandUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) { switch (useType) { case USE_OFF: { CBaseEntity *pTouch = UTIL_FindEntityByTargetname( NULL, m_szDeadTouch ); if ( pTouch ) { if ( m_hEnemy != NULL ) { pTouch->Touch( m_hEnemy ); } // if the player is using ""notarget"", the ending sequence won't fire unless we catch it here else { CBaseEntity *pEntity = UTIL_FindEntityByClassname( NULL, ""player"" ); if ( pEntity != NULL && pEntity->IsAlive() ) { pTouch->Touch( pEntity ); } } } } break; case USE_ON: if (m_irritation == 0) { m_irritation = 1; } break; case USE_SET: break; case USE_TOGGLE: break; } } int CNihilanth :: TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ) { if (pevInflictor->owner == edict()) return 0; if (flDamage >= pev->health) { pev->health = 1; if (m_irritation != 3) return 0; } PainSound( ); pev->health -= flDamage; return 0; } void CNihilanth::TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType) { if (m_irritation == 3) m_irritation = 2; if (m_irritation == 2 && ptr->iHitgroup == 2 && flDamage > 2) m_irritation = 3; if (m_irritation != 3) { Vector vecBlood = (ptr->vecEndPos - pev->origin).Normalize( ); UTIL_BloodStream( ptr->vecEndPos, vecBlood, BloodColor(), flDamage + (100 - 100 * (pev->health / gSkillData.nihilanthHealth))); } // SpawnBlood(ptr->vecEndPos, BloodColor(), flDamage * 5.0);// a little surface blood. AddMultiDamage( pevAttacker, this, flDamage, bitsDamageType ); } CBaseEntity *CNihilanth::RandomTargetname( const char *szName ) { int total = 0; CBaseEntity *pEntity = NULL; CBaseEntity *pNewEntity = NULL; while ((pNewEntity = UTIL_FindEntityByTargetname( pNewEntity, szName )) != NULL) { total++; if (RANDOM_LONG(0,total-1) < 1) pEntity = pNewEntity; } return pEntity; } //========================================================= // Controller bouncy ball attack //========================================================= void CNihilanthHVR :: Spawn( void ) { Precache( ); pev->rendermode = kRenderTransAdd; pev->renderamt = 255; pev->scale = 3.0; } void CNihilanthHVR :: Precache( void ) { PRECACHE_MODEL(""sprites/flare6.spr""); PRECACHE_MODEL(""sprites/nhth1.spr""); PRECACHE_MODEL(""sprites/exit1.spr""); PRECACHE_MODEL(""sprites/tele1.spr""); PRECACHE_MODEL(""sprites/animglow01.spr""); PRECACHE_MODEL(""sprites/xspark4.spr""); PRECACHE_MODEL(""sprites/muzzleflash3.spr""); PRECACHE_SOUND(""debris/zap4.wav""); PRECACHE_SOUND(""weapons/electro4.wav""); PRECACHE_SOUND(""x/x_teleattack1.wav""); } void CNihilanthHVR :: CircleInit( CBaseEntity *pTarget ) { pev->movetype = MOVETYPE_NOCLIP; pev->solid = SOLID_NOT; // SET_MODEL(edict(), ""sprites/flare6.spr""); // pev->scale = 3.0; // SET_MODEL(edict(), ""sprites/xspark4.spr""); SET_MODEL(edict(), ""sprites/muzzleflash3.spr""); pev->rendercolor.x = 255; pev->rendercolor.y = 224; pev->rendercolor.z = 192; pev->scale = 2.0; m_nFrames = 1; pev->renderamt = 255; UTIL_SetSize(pev, Vector( 0, 0, 0), Vector(0, 0, 0)); UTIL_SetOrigin( pev, pev->origin ); SetThink( &CNihilanthHVR::HoverThink ); SetTouch( &CNihilanthHVR::BounceTouch ); pev->nextthink = gpGlobals->time + 0.1; m_hTargetEnt = pTarget; } CBaseEntity *CNihilanthHVR::RandomClassname( const char *szName ) { int total = 0; CBaseEntity *pEntity = NULL; CBaseEntity *pNewEntity = NULL; while ((pNewEntity = UTIL_FindEntityByClassname( pNewEntity, szName )) != NULL) { total++; if (RANDOM_LONG(0,total-1) < 1) pEntity = pNewEntity; } return pEntity; } void CNihilanthHVR :: HoverThink( void ) { pev->nextthink = gpGlobals->time + 0.1; if (m_hTargetEnt != NULL) { CircleTarget( m_hTargetEnt->pev->origin + Vector( 0, 0, 16 * N_SCALE ) ); } else { UTIL_Remove( this ); } if (RANDOM_LONG( 0, 99 ) < 5) { /* CBaseEntity *pOther = RandomClassname( STRING(pev->classname) ); if (pOther && pOther != this) { MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTS ); WRITE_SHORT( this->entindex() ); WRITE_SHORT( pOther->entindex() ); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // framestart WRITE_BYTE( 0 ); // framerate WRITE_BYTE( 10 ); // life WRITE_BYTE( 80 ); // width WRITE_BYTE( 80 ); // noise WRITE_BYTE( 255 ); // r, g, b WRITE_BYTE( 128 ); // r, g, b WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 30 ); // speed MESSAGE_END(); } */ /* MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTS ); WRITE_SHORT( this->entindex() ); WRITE_SHORT( m_hTargetEnt->entindex() + 0x1000 ); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // framestart WRITE_BYTE( 0 ); // framerate WRITE_BYTE( 10 ); // life WRITE_BYTE( 80 ); // width WRITE_BYTE( 80 ); // noise WRITE_BYTE( 255 ); // r, g, b WRITE_BYTE( 128 ); // r, g, b WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 30 ); // speed MESSAGE_END(); */ } pev->frame = ((int)pev->frame + 1) % m_nFrames; } void CNihilanthHVR :: ZapInit( CBaseEntity *pEnemy ) { pev->movetype = MOVETYPE_FLY; pev->solid = SOLID_BBOX; SET_MODEL(edict(), ""sprites/nhth1.spr""); pev->rendercolor.x = 255; pev->rendercolor.y = 255; pev->rendercolor.z = 255; pev->scale = 2.0; pev->velocity = (pEnemy->pev->origin - pev->origin).Normalize() * 200; m_hEnemy = pEnemy; SetThink( &CNihilanthHVR::ZapThink ); SetTouch( &CNihilanthHVR::ZapTouch ); pev->nextthink = gpGlobals->time + 0.1; EMIT_SOUND_DYN( edict(), CHAN_WEAPON, ""debris/zap4.wav"", 1, ATTN_NORM, 0, 100 ); } void CNihilanthHVR :: ZapThink( void ) { pev->nextthink = gpGlobals->time + 0.05; // check world boundaries if (m_hEnemy == NULL || !IsInWorld()) { SetTouch( NULL ); UTIL_Remove( this ); return; } if (pev->velocity.Length() < 2000) { pev->velocity = pev->velocity * 1.2; } // MovetoTarget( m_hEnemy->Center( ) ); if ((m_hEnemy->Center() - pev->origin).Length() < 256) { TraceResult tr; UTIL_TraceLine( pev->origin, m_hEnemy->Center(), dont_ignore_monsters, edict(), &tr ); CBaseEntity *pEntity = CBaseEntity::Instance(tr.pHit); if (pEntity != NULL && pEntity->pev->takedamage) { ClearMultiDamage( ); pEntity->TraceAttack( pev, gSkillData.nihilanthZap, pev->velocity, &tr, DMG_SHOCK ); ApplyMultiDamage( pev, pev ); } MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTPOINT ); WRITE_SHORT( entindex() ); WRITE_COORD( tr.vecEndPos.x ); WRITE_COORD( tr.vecEndPos.y ); WRITE_COORD( tr.vecEndPos.z ); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // frame start WRITE_BYTE( 10 ); // framerate WRITE_BYTE( 3 ); // life WRITE_BYTE( 20 ); // width WRITE_BYTE( 20 ); // noise WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 196 ); // r, g, b WRITE_BYTE( 255); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 10 ); // speed MESSAGE_END(); UTIL_EmitAmbientSound( edict(), tr.vecEndPos, ""weapons/electro4.wav"", 0.5, ATTN_NORM, 0, RANDOM_LONG( 140, 160 ) ); SetTouch( NULL ); UTIL_Remove( this ); pev->nextthink = gpGlobals->time + 0.2; return; } pev->frame = (int)(pev->frame + 1) % 11; MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 128 ); // radius WRITE_BYTE( 128 ); // R WRITE_BYTE( 128 ); // G WRITE_BYTE( 255 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 128 ); // decay MESSAGE_END(); // Crawl( ); } void CNihilanthHVR::ZapTouch( CBaseEntity *pOther ) { UTIL_EmitAmbientSound( edict(), pev->origin, ""weapons/electro4.wav"", 1.0, ATTN_NORM, 0, RANDOM_LONG( 90, 95 ) ); RadiusDamage( pev, pev, 50, CLASS_NONE, DMG_SHOCK ); pev->velocity = pev->velocity * 0; /* for (int i = 0; i < 10; i++) { Crawl( ); } */ SetTouch( NULL ); UTIL_Remove( this ); pev->nextthink = gpGlobals->time + 0.2; } void CNihilanthHVR :: TeleportInit( CNihilanth *pOwner, CBaseEntity *pEnemy, CBaseEntity *pTarget, CBaseEntity *pTouch ) { pev->movetype = MOVETYPE_FLY; pev->solid = SOLID_BBOX; pev->rendercolor.x = 255; pev->rendercolor.y = 255; pev->rendercolor.z = 255; pev->velocity.z *= 0.2; SET_MODEL(edict(), ""sprites/exit1.spr""); m_pNihilanth = pOwner; m_hEnemy = pEnemy; m_hTargetEnt = pTarget; m_hTouch = pTouch; SetThink( &CNihilanthHVR::TeleportThink ); SetTouch( &CNihilanthHVR::TeleportTouch ); pev->nextthink = gpGlobals->time + 0.1; EMIT_SOUND_DYN( edict(), CHAN_WEAPON, ""x/x_teleattack1.wav"", 1, 0.2, 0, 100 ); } void CNihilanthHVR :: GreenBallInit( ) { pev->movetype = MOVETYPE_FLY; pev->solid = SOLID_BBOX; pev->rendercolor.x = 255; pev->rendercolor.y = 255; pev->rendercolor.z = 255; pev->scale = 1.0; SET_MODEL(edict(), ""sprites/exit1.spr""); SetTouch( &CNihilanthHVR::RemoveTouch ); } void CNihilanthHVR :: TeleportThink( void ) { pev->nextthink = gpGlobals->time + 0.1; // check world boundaries if (m_hEnemy == NULL || !m_hEnemy->IsAlive() || !IsInWorld()) { STOP_SOUND(edict(), CHAN_WEAPON, ""x/x_teleattack1.wav"" ); UTIL_Remove( this ); return; } if ((m_hEnemy->Center() - pev->origin).Length() < 128) { STOP_SOUND(edict(), CHAN_WEAPON, ""x/x_teleattack1.wav"" ); UTIL_Remove( this ); if (m_hTargetEnt != NULL) m_hTargetEnt->Use( m_hEnemy, m_hEnemy, USE_ON, 1.0 ); if ( m_hTouch != NULL && m_hEnemy != NULL ) m_hTouch->Touch( m_hEnemy ); } else { MovetoTarget( m_hEnemy->Center( ) ); } MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( 256 ); // radius WRITE_BYTE( 0 ); // R WRITE_BYTE( 255 ); // G WRITE_BYTE( 0 ); // B WRITE_BYTE( 10 ); // life * 10 WRITE_COORD( 256 ); // decay MESSAGE_END(); pev->frame = (int)(pev->frame + 1) % 20; } void CNihilanthHVR :: AbsorbInit( void ) { SetThink( &CNihilanthHVR::DissipateThink ); pev->renderamt = 255; MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTS ); WRITE_SHORT( this->entindex() ); WRITE_SHORT( m_hTargetEnt->entindex() + 0x1000 ); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // framestart WRITE_BYTE( 0 ); // framerate WRITE_BYTE( 50 ); // life WRITE_BYTE( 80 ); // width WRITE_BYTE( 80 ); // noise WRITE_BYTE( 255 ); // r, g, b WRITE_BYTE( 128 ); // r, g, b WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 30 ); // speed MESSAGE_END(); } void CNihilanthHVR::TeleportTouch( CBaseEntity *pOther ) { CBaseEntity *pEnemy = m_hEnemy; if (pOther == pEnemy) { if (m_hTargetEnt != NULL) m_hTargetEnt->Use( pEnemy, pEnemy, USE_ON, 1.0 ); if (m_hTouch != NULL && pEnemy != NULL ) m_hTouch->Touch( pEnemy ); } else { m_pNihilanth->MakeFriend( pev->origin ); } SetTouch( NULL ); STOP_SOUND(edict(), CHAN_WEAPON, ""x/x_teleattack1.wav"" ); UTIL_Remove( this ); } void CNihilanthHVR :: DissipateThink( void ) { pev->nextthink = gpGlobals->time + 0.1; if (pev->scale > 5.0) UTIL_Remove( this ); pev->renderamt -= 2; pev->scale += 0.1; if (m_hTargetEnt != NULL) { CircleTarget( m_hTargetEnt->pev->origin + Vector( 0, 0, 4096 ) ); } else { UTIL_Remove( this ); } MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_ELIGHT ); WRITE_SHORT( entindex( ) ); // entity, attachment WRITE_COORD( pev->origin.x ); // origin WRITE_COORD( pev->origin.y ); WRITE_COORD( pev->origin.z ); WRITE_COORD( pev->renderamt ); // radius WRITE_BYTE( 255 ); // R WRITE_BYTE( 192 ); // G WRITE_BYTE( 64 ); // B WRITE_BYTE( 2 ); // life * 10 WRITE_COORD( 0 ); // decay MESSAGE_END(); } BOOL CNihilanthHVR :: CircleTarget( Vector vecTarget ) { BOOL fClose = FALSE; Vector vecDest = vecTarget; Vector vecEst = pev->origin + pev->velocity * 0.5; Vector vecSrc = pev->origin; vecDest.z = 0; vecEst.z = 0; vecSrc.z = 0; float d1 = (vecDest - vecSrc).Length() - 24 * N_SCALE; float d2 = (vecDest - vecEst).Length() - 24 * N_SCALE; if (m_vecIdeal == Vector( 0, 0, 0 )) { m_vecIdeal = pev->velocity; } if (d1 < 0 && d2 <= d1) { // ALERT( at_console, ""too close\\n""); m_vecIdeal = m_vecIdeal - (vecDest - vecSrc).Normalize() * 50; } else if (d1 > 0 && d2 >= d1) { // ALERT( at_console, ""too far\\n""); m_vecIdeal = m_vecIdeal + (vecDest - vecSrc).Normalize() * 50; } pev->avelocity.z = d1 * 20; if (d1 < 32) { fClose = TRUE; } m_vecIdeal = m_vecIdeal + Vector( RANDOM_FLOAT( -2, 2 ), RANDOM_FLOAT( -2, 2 ), RANDOM_FLOAT( -2, 2 )); m_vecIdeal = Vector( m_vecIdeal.x, m_vecIdeal.y, 0 ).Normalize( ) * 200 /* + Vector( -m_vecIdeal.y, m_vecIdeal.x, 0 ).Normalize( ) * 32 */ + Vector( 0, 0, m_vecIdeal.z ); // m_vecIdeal = m_vecIdeal + Vector( -m_vecIdeal.y, m_vecIdeal.x, 0 ).Normalize( ) * 2; // move up/down d1 = vecTarget.z - pev->origin.z; if (d1 > 0 && m_vecIdeal.z < 200) m_vecIdeal.z += 20; else if (d1 < 0 && m_vecIdeal.z > -200) m_vecIdeal.z -= 20; pev->velocity = m_vecIdeal; // ALERT( at_console, ""%.0f %.0f %.0f\\n"", m_vecIdeal.x, m_vecIdeal.y, m_vecIdeal.z ); return fClose; } void CNihilanthHVR :: MovetoTarget( Vector vecTarget ) { if (m_vecIdeal == Vector( 0, 0, 0 )) { m_vecIdeal = pev->velocity; } // accelerate float flSpeed = m_vecIdeal.Length(); if (flSpeed > 300) { m_vecIdeal = m_vecIdeal.Normalize( ) * 300; } m_vecIdeal = m_vecIdeal + (vecTarget - pev->origin).Normalize() * 300; pev->velocity = m_vecIdeal; } void CNihilanthHVR :: Crawl( void ) { Vector vecAim = Vector( RANDOM_FLOAT( -1, 1 ), RANDOM_FLOAT( -1, 1 ), RANDOM_FLOAT( -1, 1 ) ).Normalize( ); Vector vecPnt = pev->origin + pev->velocity * 0.2 + vecAim * 128; MESSAGE_BEGIN( MSG_BROADCAST, SVC_TEMPENTITY ); WRITE_BYTE( TE_BEAMENTPOINT ); WRITE_SHORT( entindex() ); WRITE_COORD( vecPnt.x); WRITE_COORD( vecPnt.y); WRITE_COORD( vecPnt.z); WRITE_SHORT( g_sModelIndexLaser ); WRITE_BYTE( 0 ); // frame start WRITE_BYTE( 10 ); // framerate WRITE_BYTE( 3 ); // life WRITE_BYTE( 20 ); // width WRITE_BYTE( 80 ); // noise WRITE_BYTE( 64 ); // r, g, b WRITE_BYTE( 128 ); // r, g, b WRITE_BYTE( 255); // r, g, b WRITE_BYTE( 255 ); // brightness WRITE_BYTE( 10 ); // speed MESSAGE_END(); } void CNihilanthHVR::RemoveTouch( CBaseEntity *pOther ) { STOP_SOUND(edict(), CHAN_WEAPON, ""x/x_teleattack1.wav"" ); UTIL_Remove( this ); } void CNihilanthHVR::BounceTouch( CBaseEntity *pOther ) { Vector vecDir = m_vecIdeal.Normalize( ); TraceResult tr = UTIL_GetGlobalTrace( ); float n = -DotProduct(tr.vecPlaneNormal, vecDir); vecDir = 2.0 * tr.vecPlaneNormal * n + vecDir; m_vecIdeal = vecDir * m_vecIdeal.Length(); } #endif ",16179,True,3212.4594365378325,median "// // Copyright (c) 2000-2002 // Joerg Walter, Mathias Koch // // Permission to use, copy, modify, distribute and sell this software // and its documentation for any purpose is hereby granted without fee, // provided that the above copyright notice appear in all copies and // that both that copyright notice and this permission notice appear // in supporting documentation. The authors make no representations // about the suitability of this software for any purpose. // It is provided ""as is"" without express or implied warranty. // // The authors gratefully acknowledge the support of // GeNeSys mbH & Co. KG in producing this work. // #ifndef BOOST_UBLAS_CONCEPTS_H #define BOOST_UBLAS_CONCEPTS_H // #define INTERNAL_STORAGE // #define INTERNAL_STORAGE_SPARSE // #define INTERNAL_VECTOR // #define INTERNAL_VECTOR_PROXY // #define INTERNAL_VECTOR_SPARSE // #define INTERNAL_MATRIX // #define INTERNAL_MATRIX_PROXY // #define INTERNAL_BANDED // #define INTERNAL_TRIANGULAR // #define INTERNAL_SYMMETRIC // #define INTERNAL_HERMITIAN // #define INTERNAL_MATRIX_SPARSE // #define INTERNAL_VECTOR_EXPRESSION // #define INTERNAL_MATRIX_EXPRESSION // #define EXTERNAL // Concept checks based on ideas of Jeremy Siek namespace boost { namespace numeric { namespace ublas { template void ignore_unused_variable_warning (const T &t) {} template struct AssignableConcept { typedef T value_type; static void constraints (value_type t) { // Copy Constructor value_type c1 (t); value_type c2 = t; // Assignment value_type a = t; std::swap (c1, c2); ignore_unused_variable_warning (a); } }; template struct EqualityComparableConcept { typedef T value_type; static void constraints (const value_type t) { bool b; // Equality b = t == t; // Inequality b = t != t; ignore_unused_variable_warning (b); } }; template struct LessThanComparableConcept { typedef T value_type; static void constraints (const value_type t) { bool b; b = t < t; b = t <= t; b = t >= t; b = t > t; ignore_unused_variable_warning (b); } }; template struct DefaultConstructibleConcept { typedef T value_type; static void constraints () { // Default Constructor static value_type c1 = value_type (); static value_type c2; ignore_unused_variable_warning (c1); ignore_unused_variable_warning (c2); } }; template struct BidirectionalIteratorConcept { typedef I iterator_type; typedef T value_type; static void constraints () { #define BOOST_UBLAS_ITERATOR_IS_ASSIGNABLE #ifdef BOOST_UBLAS_ITERATOR_IS_ASSIGNABLE AssignableConcept::constraints (iterator_type ()); #endif EqualityComparableConcept::constraints (iterator_type ()); DefaultConstructibleConcept::constraints (); iterator_type it = iterator_type (); value_type t = value_type (); // Dereference t = *it; // Member access // it->m; // Preincrement ++ it; // Postincrement it ++; // Predecrement -- it; // Postdecrement it --; ignore_unused_variable_warning (t); } }; template struct MutableBidirectionalIteratorConcept { typedef I iterator_type; typedef T value_type; static void constraints () { BidirectionalIteratorConcept::constraints (); iterator_type it = iterator_type (); value_type t = value_type (); #ifdef BOOST_UBLAS_NON_STD // Dereference assignment *it = t; #else ignore_unused_variable_warning (it); #endif ignore_unused_variable_warning (t); } }; template struct RandomAccessIteratorConcept { typedef I iterator_type; typedef D difference_type; typedef T value_type; static void constraints () { LessThanComparableConcept::constraints (iterator_type ()); BidirectionalIteratorConcept::constraints (); iterator_type it = iterator_type (), it1 = iterator_type (), it2 = iterator_type (); difference_type n (0); value_type t = value_type (); // Forward motion it += n; // Iterator addition #ifdef BOOST_UBLAS_ITERATOR_IS_ASSIGNABLE it = it + n; #else iterator_type itp (it + n); #endif // Backward motion it -= n; // Iterator subtraction #ifdef BOOST_UBLAS_ITERATOR_IS_ASSIGNABLE it = it - n; #else iterator_type itm (it - n); #endif // Difference n = it1 - it2; // Element operator #ifdef BOOST_UBLAS_ITERATOR_IS_INDEXABLE t = it [n]; #else t = *(it + n); #endif ignore_unused_variable_warning (t); } }; template struct MutableRandomAccessIteratorConcept { typedef I iterator_type; typedef D difference_type; typedef T value_type; static void constraints () { MutableBidirectionalIteratorConcept::constraints (); RandomAccessIteratorConcept::constraints (); iterator_type it = iterator_type (); difference_type n (0); value_type t = value_type (); // Element assignment #ifdef BOOST_UBLAS_ITERATOR_IS_INDEXABLE it [n] = t; #else *(it + n) = t; #endif } }; template struct Indexed1DIteratorConcept { typedef I iterator_type; static void constraints () { iterator_type it = iterator_type (); // Function call it (); // Index it.index (); } }; template struct IndexedBidirectional1DIteratorConcept { typedef I iterator_type; static void constraints () { BidirectionalIteratorConcept::constraints (); Indexed1DIteratorConcept::constraints (); } }; template struct MutableIndexedBidirectional1DIteratorConcept { typedef I iterator_type; static void constraints () { MutableBidirectionalIteratorConcept::constraints (); Indexed1DIteratorConcept::constraints (); } }; template struct IndexedRandomAccess1DIteratorConcept { typedef I iterator_type; static void constraints () { RandomAccessIteratorConcept::constraints (); Indexed1DIteratorConcept::constraints (); } }; template struct MutableIndexedRandomAccess1DIteratorConcept { typedef I iterator_type; static void constraints () { MutableRandomAccessIteratorConcept::constraints (); Indexed1DIteratorConcept::constraints (); } }; template struct Indexed2DIteratorConcept { typedef I iterator_type; typedef typename I::dual_iterator_type dual_iterator_type; typedef typename I::dual_reverse_iterator_type dual_reverse_iterator_type; static void constraints () { iterator_type it = iterator_type (); // Function call it (); // Indices it.index1 (); it.index2 (); // Iterator begin/end dual_iterator_type it_begin (it.begin ()); dual_iterator_type it_end (it.end ()); // Reverse iterator begin/end dual_reverse_iterator_type it_rbegin (it.rbegin ()); dual_reverse_iterator_type it_rend (it.rend ()); ignore_unused_variable_warning (it_begin); ignore_unused_variable_warning (it_end); ignore_unused_variable_warning (it_rbegin); ignore_unused_variable_warning (it_rend); } }; template struct IndexedBidirectional2DIteratorConcept { typedef I1 iterator1_type; typedef I2 iterator2_type; static void constraints () { BidirectionalIteratorConcept::constraints (); BidirectionalIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); } }; template struct MutableIndexedBidirectional2DIteratorConcept { typedef I1 iterator1_type; typedef I2 iterator2_type; static void constraints () { MutableBidirectionalIteratorConcept::constraints (); MutableBidirectionalIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); } }; template struct IndexedRandomAccess2DIteratorConcept { typedef I1 iterator1_type; typedef I2 iterator2_type; static void constraints () { RandomAccessIteratorConcept::constraints (); RandomAccessIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); } }; template struct MutableIndexedRandomAccess2DIteratorConcept { typedef I1 iterator1_type; typedef I2 iterator2_type; static void constraints () { MutableRandomAccessIteratorConcept::constraints (); MutableRandomAccessIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); Indexed2DIteratorConcept::constraints (); } }; template struct ContainerConcept { typedef C container_type; typedef typename C::size_type size_type; typedef typename C::const_iterator const_iterator_type; static void constraints () { DefaultConstructibleConcept::constraints (); container_type c = container_type (); size_type n (0); // Beginning of range const_iterator_type cit_begin (c.begin ()); // End of range const_iterator_type cit_end (c.end ()); // Size n = c.size (); ignore_unused_variable_warning (cit_end); ignore_unused_variable_warning (cit_begin); ignore_unused_variable_warning (n); } }; template struct MutableContainerConcept { typedef C container_type; typedef typename C::iterator iterator_type; static void constraints () { AssignableConcept::constraints (container_type ()); ContainerConcept::constraints (); container_type c = container_type (), c1 = container_type (), c2 = container_type (); // Beginning of range iterator_type it_begin (c.begin ()); // End of range iterator_type it_end (c.end ()); // Swap c1.swap (c2); ignore_unused_variable_warning (it_end); ignore_unused_variable_warning (it_begin); } }; template struct ReversibleContainerConcept { typedef C container_type; typedef typename C::const_reverse_iterator const_reverse_iterator_type; static void constraints () { ContainerConcept::constraints (); #ifndef BOOST_UBLAS_LWG_ISSUE_280 const container_type cc = container_type (); #else container_type c = container_type (); #endif // Beginning of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const_reverse_iterator_type crit_begin (cc.rbegin ()); #else const_reverse_iterator_type crit_begin (c.rbegin ()); #endif // End of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const_reverse_iterator_type crit_end (cc.rend ()); #else const_reverse_iterator_type crit_end (c.rend ()); #endif ignore_unused_variable_warning (crit_end); ignore_unused_variable_warning (crit_begin); } }; template struct MutableReversibleContainerConcept { typedef C container_type; typedef typename C::reverse_iterator reverse_iterator_type; static void constraints () { MutableContainerConcept::constraints (); ReversibleContainerConcept::constraints (); container_type c = container_type (); // Beginning of reverse range reverse_iterator_type rit_begin (c.rbegin ()); // End of reverse range reverse_iterator_type rit_end (c.rend ()); ignore_unused_variable_warning (rit_end); ignore_unused_variable_warning (rit_begin); } }; template struct RandomAccessContainerConcept { typedef C container_type; typedef typename C::size_type size_type; typedef typename C::value_type value_type; static void constraints () { ReversibleContainerConcept::constraints (); container_type c = container_type (); size_type n (0); value_type t = value_type (); // Element access t = c [n]; ignore_unused_variable_warning (t); } }; template struct MutableRandomAccessContainerConcept { typedef C container_type; typedef typename C::size_type size_type; typedef typename C::value_type value_type; static void constraints () { MutableReversibleContainerConcept::constraints (); RandomAccessContainerConcept::constraints (); container_type c = container_type (); size_type n (0); value_type t = value_type (); // Element access c [n] = t; } }; template struct StorageContainerConcept { typedef C container_type; typedef typename C::size_type size_type; static void constraints () { RandomAccessContainerConcept::constraints (); size_type n (0); // Sizing constructor container_type c = container_type (n); ignore_unused_variable_warning (c); } }; template struct MutableStorageContainerConcept { typedef C container_type; typedef typename C::size_type size_type; typedef typename C::value_type value_type; typedef typename C::iterator iterator_type; static void constraints () { MutableRandomAccessContainerConcept::constraints (); size_type n (0); // Sizing constructor container_type c = container_type (n); value_type t = value_type (); iterator_type it = iterator_type (), it1 = iterator_type (), it2 = iterator_type (); // Insert c.insert (it, t); // Range insert c.insert (it, it1, it2); // Erase c.erase (it); // Range erase c.erase (it1, it2); // Clear c.clear (); // Resize c.resize (n); } }; template struct SparseStorageContainerConcept { typedef C container_type; typedef typename C::size_type size_type; static void constraints () { ReversibleContainerConcept::constraints (); } }; template struct MutableSparseStorageContainerConcept { typedef C container_type; typedef typename C::size_type size_type; typedef typename C::value_type value_type; typedef typename C::iterator iterator_type; static void constraints () { MutableReversibleContainerConcept::constraints (); container_type c = container_type (); value_type t = value_type (); iterator_type it = iterator_type (), it1 = iterator_type (), it2 = iterator_type (); // Insert c.insert (it, t); #ifdef BOOST_UBLAS_NON_STD // Range insert c.insert (it, it1, it2); #endif // Erase c.erase (it); // Range erase c.erase (it1, it2); // Clear c.clear (); } }; template struct IndexSetConcept { typedef G generator_type; typedef typename G::size_type size_type; typedef typename G::value_type value_type; static void constraints () { DefaultConstructibleConcept::constraints (); ReversibleContainerConcept::constraints (); generator_type g = generator_type (); size_type n (0); value_type t = value_type (); // Element access t = g (n); ignore_unused_variable_warning (t); } }; template struct ScalarExpressionConcept { typedef S scalar_type; typedef typename S::value_type value_type; static void constraints () { DefaultConstructibleConcept::constraints (); scalar_type s = scalar_type (); value_type t = value_type (); // Conversion t = s; ignore_unused_variable_warning (t); } }; template struct VectorExpressionConcept { typedef V vector_type; typedef typename V::type_category type_category; typedef typename V::size_type size_type; typedef typename V::value_type value_type; typedef typename V::const_iterator const_iterator_type; typedef typename V::const_reverse_iterator const_reverse_iterator_type; static void constraints () { DefaultConstructibleConcept::constraints (); vector_type v = vector_type (); size_type n (0), i (0); value_type t = value_type (); // Find (internal?) const_iterator_type cit_lower (v.find_first (i)); const_iterator_type cit_upper (v.find_last (i)); // Beginning of range const_iterator_type cit_begin (v.begin ()); // End of range const_iterator_type cit_end (v.end ()); // Size n = v.size (); // Beginning of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const vector_type cv = vector_type (); const_reverse_iterator_type crit_begin (cv.rbegin ()); #else const_reverse_iterator_type crit_begin (v.rbegin ()); #endif // End of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const_reverse_iterator_type crit_end (cv.rend ()); #else const_reverse_iterator_type crit_end (v.rend ()); #endif // Element access t = v (i); ignore_unused_variable_warning (n); ignore_unused_variable_warning (cit_lower); ignore_unused_variable_warning (cit_upper); ignore_unused_variable_warning (cit_begin); ignore_unused_variable_warning (cit_end); ignore_unused_variable_warning (crit_begin); ignore_unused_variable_warning (crit_end); ignore_unused_variable_warning (t); } }; template struct MutableVectorExpressionConcept { typedef V vector_type; typedef typename V::size_type size_type; typedef typename V::value_type value_type; typedef typename V::iterator iterator_type; typedef typename V::reverse_iterator reverse_iterator_type; static void constraints () { AssignableConcept::constraints (vector_type ()); VectorExpressionConcept::constraints (); vector_type v = vector_type (), v1 = vector_type (), v2 = vector_type (); size_type i (0); value_type t = value_type (); // Find (internal?) iterator_type it_lower (v.find_first (i)); iterator_type it_upper (v.find_last (i)); // Beginning of range iterator_type it_begin (v.begin ()); // End of range iterator_type it_end (v.end ()); // Swap v1.swap (v2); // Beginning of reverse range reverse_iterator_type rit_begin (v.rbegin ()); // End of reverse range reverse_iterator_type rit_end (v.rend ()); // Assignments v2 = v1; v2.assign (v1); v2 += v1; v2.plus_assign (v1); v2 -= v1; v2.minus_assign (v1); v *= t; ignore_unused_variable_warning (it_lower); ignore_unused_variable_warning (it_upper); ignore_unused_variable_warning (it_begin); ignore_unused_variable_warning (it_end); ignore_unused_variable_warning (rit_begin); ignore_unused_variable_warning (rit_end); } }; template struct MatrixExpressionConcept { typedef M matrix_type; typedef typename M::type_category type_category; typedef typename M::size_type size_type; typedef typename M::value_type value_type; typedef typename M::const_iterator1 const_iterator1_type; typedef typename M::const_iterator2 const_iterator2_type; typedef typename M::const_reverse_iterator1 const_reverse_iterator1_type; typedef typename M::const_reverse_iterator2 const_reverse_iterator2_type; static void constraints () { DefaultConstructibleConcept::constraints (); matrix_type m = matrix_type (); size_type n (0), i (0), j (0); value_type t = value_type (); // Find (internal?) const_iterator1_type cit1_lower (m.find_first1 (0, i, j)); const_iterator1_type cit1_upper (m.find_last1 (0, i, j)); const_iterator2_type cit2_lower (m.find_first2 (0, i, j)); const_iterator2_type cit2_upper (m.find_last2 (0, i, j)); // Beginning of range const_iterator1_type cit1_begin (m.begin1 ()); const_iterator2_type cit2_begin (m.begin2 ()); // End of range const_iterator1_type cit1_end (m.end1 ()); const_iterator2_type cit2_end (m.end2 ()); // Size n = m.size1 (); n = m.size2 (); // Beginning of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const matrix_type cm = matrix_type (); const_reverse_iterator1_type crit1_begin (cm.rbegin1 ()); const_reverse_iterator2_type crit2_begin (cm.rbegin2 ()); #else const_reverse_iterator1_type crit1_begin (m.rbegin1 ()); const_reverse_iterator2_type crit2_begin (m.rbegin2 ()); #endif // End of reverse range #ifndef BOOST_UBLAS_LWG_ISSUE_280 const_reverse_iterator1_type crit1_end (cm.rend1 ()); const_reverse_iterator2_type crit2_end (cm.rend2 ()); #else const_reverse_iterator1_type crit1_end (m.rend1 ()); const_reverse_iterator2_type crit2_end (m.rend2 ()); #endif // Element access t = m (i, j); ignore_unused_variable_warning (n); ignore_unused_variable_warning (cit1_lower); ignore_unused_variable_warning (cit1_upper); ignore_unused_variable_warning (cit2_lower); ignore_unused_variable_warning (cit2_upper); ignore_unused_variable_warning (cit1_begin); ignore_unused_variable_warning (cit2_begin); ignore_unused_variable_warning (cit1_end); ignore_unused_variable_warning (cit2_end); ignore_unused_variable_warning (crit1_begin); ignore_unused_variable_warning (crit2_begin); ignore_unused_variable_warning (crit1_end); ignore_unused_variable_warning (crit2_end); ignore_unused_variable_warning (t); } }; template struct MutableMatrixExpressionConcept { typedef M matrix_type; typedef typename M::size_type size_type; typedef typename M::value_type value_type; typedef typename M::iterator1 iterator1_type; typedef typename M::iterator2 iterator2_type; typedef typename M::reverse_iterator1 reverse_iterator1_type; typedef typename M::reverse_iterator2 reverse_iterator2_type; static void constraints () { AssignableConcept::constraints (matrix_type ()); MatrixExpressionConcept::constraints (); matrix_type m = matrix_type (), m1 = matrix_type (), m2 = matrix_type (); size_type i (0), j (0); value_type t = value_type (); // Find (internal?) iterator1_type it1_lower (m.find_first1 (0, i, j)); iterator1_type it1_upper (m.find_last1 (0, i, j)); iterator2_type it2_lower (m.find_first2 (0, i, j)); iterator2_type it2_upper (m.find_last2 (0, i, j)); // Beginning of range iterator1_type it1_begin (m.begin1 ()); iterator2_type it2_begin (m.begin2 ()); // End of range iterator1_type it1_end (m.end1 ()); iterator2_type it2_end (m.end2 ()); // Swap m1.swap (m2); // Beginning of reverse range reverse_iterator1_type rit1_begin (m.rbegin1 ()); reverse_iterator2_type rit2_begin (m.rbegin2 ()); // End of reverse range reverse_iterator1_type rit1_end (m.rend1 ()); reverse_iterator2_type rit2_end (m.rend2 ()); // Assignments m2 = m1; m2.assign (m1); m2 += m1; m2.plus_assign (m1); m2 -= m1; m2.minus_assign (m1); m *= t; ignore_unused_variable_warning (it1_lower); ignore_unused_variable_warning (it1_upper); ignore_unused_variable_warning (it2_lower); ignore_unused_variable_warning (it2_upper); ignore_unused_variable_warning (it1_begin); ignore_unused_variable_warning (it2_begin); ignore_unused_variable_warning (it1_end); ignore_unused_variable_warning (it2_end); ignore_unused_variable_warning (rit1_begin); ignore_unused_variable_warning (rit2_begin); ignore_unused_variable_warning (rit1_end); ignore_unused_variable_warning (rit2_end); } }; template struct VectorConcept { typedef V vector_type; static void constraints () { VectorExpressionConcept::constraints (); } }; template struct MutableVectorConcept { typedef V vector_type; typedef typename V::size_type size_type; typedef typename V::value_type value_type; static void constraints () { MutableVectorExpressionConcept::constraints (); VectorConcept::constraints (); size_type n (0); // Sizing constructor vector_type v = vector_type (n); value_type t = value_type (); size_type i (0); // Insert v.insert (i, t); // Erase v.erase (i); // Clear v.clear (); // Resize v.resize (n); } }; template struct MatrixConcept { typedef M matrix_type; static void constraints () { MatrixExpressionConcept::constraints (); } }; template struct MutableMatrixConcept { typedef M matrix_type; typedef typename M::size_type size_type; typedef typename M::value_type value_type; static void constraints () { MutableMatrixExpressionConcept::constraints (); MatrixConcept::constraints (); size_type n (0); // Sizing constructor matrix_type m = matrix_type (n, n); value_type t = value_type (); size_type i (0), j (0); // Insert m.insert (i, j, t); // Erase m.erase (i, j); // Clear m.clear (); // Resize m.resize (n, n); } }; template T ZeroElement (T); template<> float ZeroElement (float) { return 0.f; } template<> double ZeroElement (double) { return 0.; } #ifndef BOOST_MSVC template<> std::complex ZeroElement (std::complex) { return std::complex (0.f); } template<> std::complex ZeroElement (std::complex) { return std::complex (0.); } #endif template<> vector ZeroElement (vector) { return zero_vector (); } template<> vector ZeroElement (vector) { return zero_vector (); } #ifndef BOOST_MSVC template<> vector > ZeroElement (vector >) { return zero_vector > (); } template<> vector > ZeroElement (vector >) { return zero_vector > (); } #endif template<> matrix ZeroElement (matrix) { return zero_matrix (); } template<> matrix ZeroElement (matrix) { return zero_matrix (); } #ifndef BOOST_MSVC template<> matrix > ZeroElement (matrix >) { return zero_matrix > (); } template<> matrix > ZeroElement (matrix >) { return zero_matrix > (); } #endif template T OneElement (T); template<> float OneElement (float) { return 1.f; } template<> double OneElement (double) { return 1.; } #ifndef BOOST_MSVC template<> std::complex OneElement (std::complex) { return std::complex (1.f); } template<> std::complex OneElement (std::complex) { return std::complex (1.); } #endif template<> matrix OneElement (matrix) { return identity_matrix (); } template<> matrix OneElement (matrix) { return identity_matrix (); } #ifndef BOOST_MSVC template<> matrix > OneElement (matrix >) { return identity_matrix > (); } template<> matrix > OneElement (matrix >) { return identity_matrix > (); } #endif template bool operator == (const vector_expression &e1, const vector_expression &e2) { typedef BOOST_UBLAS_TYPENAME promote_traits::promote_type value_type; typedef BOOST_UBLAS_TYPENAME type_traits::real_type real_type; return norm_inf (e1 - e2) == real_type (); } template bool operator == (const matrix_expression &e1, const matrix_expression &e2) { typedef BOOST_UBLAS_TYPENAME promote_traits::promote_type value_type; typedef BOOST_UBLAS_TYPENAME type_traits::real_type real_type; return norm_inf (e1 - e2) == real_type (); } template struct AdditiveAbelianGroupConcept { typedef T value_type; static void constraints () { bool r; value_type a = value_type (), b = value_type (), c = value_type (); r = (a + b) + c == a + (b + c); r = ZeroElement (value_type ()) + a == a; r = a + ZeroElement (value_type ()) == a; r = a + (- a) == ZeroElement (value_type ()); r = (- a) + a == ZeroElement (value_type ()); r = a + b == b + a; ignore_unused_variable_warning (r); } }; template struct MultiplicativeAbelianGroupConcept { typedef T value_type; static void constraints () { bool r; value_type a = value_type (), b = value_type (), c = value_type (); r = (a * b) * c == a * (b * c); r = OneElement (value_type ()) * a == a; r = a * OneElement (value_type ()) == a; r = a * (OneElement (value_type ()) / a) == a; r = (OneElement (value_type ()) / a) * a == a; r = a * b == b * a; ignore_unused_variable_warning (r); } }; template struct RingWithIdentityConcept { typedef T value_type; static void constraints () { AdditiveAbelianGroupConcept::constraints (); bool r; value_type a = value_type (), b = value_type (), c = value_type (); r = (a * b) * c == a * (b * c); r = (a + b) * c == a * c + b * c; r = OneElement (value_type ()) * a == a; r = a * OneElement (value_type ()) == a; ignore_unused_variable_warning (r); } static void constraints (int) { AdditiveAbelianGroupConcept::constraints (); bool r; value_type a = value_type (), b = value_type (), c = value_type (); r = prod (prod (a, b), c) == prod (a, prod (b, c)) ; r = prod (a + b, c) == prod (a, c) + prod (b, c); r = prod (OneElement (value_type ()), a) == a; r = prod (a, OneElement (value_type ())) == a; ignore_unused_variable_warning (r); } }; template struct CommutativeRingWithIdentityConcept { typedef T value_type; static void constraints () { RingWithIdentityConcept::constraints (); bool r; value_type a = value_type (), b = value_type (); r = a * b == b * a; ignore_unused_variable_warning (r); } }; template struct FieldConcept { typedef T value_type; static void constraints () { CommutativeRingWithIdentityConcept::constraints (); bool r; value_type a = value_type (); r = a == ZeroElement (value_type ()) || a * (OneElement (value_type ()) / a) == a; r = a == ZeroElement (value_type ()) || (OneElement (value_type ()) / a) * a == a; ignore_unused_variable_warning (r); } }; template struct VectorSpaceConcept { typedef T value_type; typedef V vector_type; static void constraints () { FieldConcept::constraints (); AdditiveAbelianGroupConcept::constraints (); bool r; value_type alpha = value_type (), beta = value_type (); vector_type a = vector_type (), b = vector_type (); r = alpha * (a + b) == alpha * a + alpha * b; r = (alpha + beta) * a == alpha * a + beta * a; r = (alpha * beta) * a == alpha * (beta * a); r = OneElement (value_type ()) * a == a; ignore_unused_variable_warning (r); } }; template struct LinearOperatorConcept { typedef T value_type; typedef V vector_type; typedef M matrix_type; static void constraints () { VectorSpaceConcept::constraints (); bool r; value_type alpha = value_type (), beta = value_type (); vector_type a = vector_type (), b = vector_type (); matrix_type A = matrix_type (); r = prod (A, alpha * a + beta * b) == alpha * prod (A, a) + beta * prod (A, b); ignore_unused_variable_warning (r); } }; void concept_checks () { // Storage #if defined (INTERNAL) || defined (INTERNAL_STORAGE) StorageContainerConcept >::constraints (); MutableStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, double>::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, double>::constraints (); StorageContainerConcept >::constraints (); MutableStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, double>::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, double>::constraints (); StorageContainerConcept >::constraints (); MutableStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, double>::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, double>::constraints (); StorageContainerConcept >::constraints (); MutableStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, double>::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, double>::constraints (); IndexSetConcept::constraints (); RandomAccessIteratorConcept::constraints (); IndexSetConcept::constraints (); RandomAccessIteratorConcept::constraints (); IndexSetConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, std::size_t>::constraints (); #endif // Sparse Storage #if defined (INTERNAL) || defined (INTERNAL_STORAGE_SPARSE) #ifndef BOOST_UBLAS_NON_STD SparseStorageContainerConcept >::constraints (); MutableSparseStorageContainerConcept >::constraints (); BidirectionalIteratorConcept::const_iterator, std::pair >::constraints (); MutableBidirectionalIteratorConcept::iterator, std::pair >::constraints (); #endif SparseStorageContainerConcept >::constraints (); MutableSparseStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, std::pair >::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, std::pair >::constraints (); #ifndef BOOST_UBLAS_NON_STD SparseStorageContainerConcept >::constraints (); MutableSparseStorageContainerConcept >::constraints (); BidirectionalIteratorConcept::const_iterator, std::size_t>::constraints (); MutableBidirectionalIteratorConcept::iterator, std::size_t>::constraints (); #endif SparseStorageContainerConcept >::constraints (); MutableSparseStorageContainerConcept >::constraints (); RandomAccessIteratorConcept::const_iterator, std::ptrdiff_t, std::size_t>::constraints (); MutableRandomAccessIteratorConcept::iterator, std::ptrdiff_t, std::size_t>::constraints (); #endif // Vector #if defined (INTERNAL) || defined (INTERNAL_VECTOR) VectorConcept >::constraints (); MutableVectorConcept >::constraints (); IndexedRandomAccess1DIteratorConcept::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept::reverse_iterator>::constraints (); VectorConcept >::constraints (); IndexedRandomAccess1DIteratorConcept::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept::const_reverse_iterator>::constraints (); VectorConcept >::constraints (); IndexedBidirectional1DIteratorConcept::const_iterator>::constraints (); IndexedBidirectional1DIteratorConcept::const_reverse_iterator>::constraints (); VectorConcept >::constraints (); IndexedRandomAccess1DIteratorConcept::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept::const_reverse_iterator>::constraints (); VectorConcept >::constraints (); MutableVectorConcept >::constraints (); IndexedRandomAccess1DIteratorConcept::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept::reverse_iterator>::constraints (); #endif // Vector Proxies #if defined (INTERNAL) || defined (INTERNAL_VECTOR_PROXY) VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); #endif // Sparse Vector #if defined (INTERNAL) || defined (INTERNAL_VECTOR_SPARSE) VectorConcept >::constraints (); MutableVectorConcept >::constraints (); IndexedBidirectional1DIteratorConcept::const_iterator>::constraints (); MutableIndexedBidirectional1DIteratorConcept::iterator>::constraints (); IndexedBidirectional1DIteratorConcept::const_reverse_iterator>::constraints (); MutableIndexedBidirectional1DIteratorConcept::reverse_iterator>::constraints (); VectorConcept >::constraints (); MutableVectorConcept >::constraints (); IndexedBidirectional1DIteratorConcept::const_iterator>::constraints (); MutableIndexedBidirectional1DIteratorConcept::iterator>::constraints (); IndexedBidirectional1DIteratorConcept::const_reverse_iterator>::constraints (); MutableIndexedBidirectional1DIteratorConcept::reverse_iterator>::constraints (); #endif // Matrix #if defined (INTERNAL) || defined (INTERNAL_MATRIX) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, matrix::reverse_iterator2>::constraints (); MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, vector_of_vector::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, vector_of_vector::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, vector_of_vector::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, vector_of_vector::reverse_iterator2>::constraints (); MatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, identity_matrix::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, identity_matrix::const_reverse_iterator2>::constraints (); MatrixConcept >::constraints (); IndexedBidirectional2DIteratorConcept::const_iterator1, zero_matrix::const_iterator2>::constraints (); IndexedBidirectional2DIteratorConcept::const_reverse_iterator1, zero_matrix::const_reverse_iterator2>::constraints (); MatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, scalar_matrix::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, scalar_matrix::const_reverse_iterator2>::constraints (); MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, c_matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, c_matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, c_matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, c_matrix::reverse_iterator2>::constraints (); #endif // Matrix Proxies #if defined (INTERNAL) || defined (INTERNAL_MATRIX_PROXY) VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); #ifndef BOOST_UBLAS_ITERATOR_IS_INDEXABLE VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); #endif MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, matrix_range >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, matrix_range >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, matrix_range >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, matrix_range >::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, matrix_slice >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, matrix_slice >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, matrix_slice >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, matrix_slice >::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, matrix_indirect >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, matrix_indirect >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, matrix_indirect >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, matrix_indirect >::reverse_iterator2>::constraints (); #endif // Banded Matrix #if defined (INTERNAL) || defined (INTERNAL_BANDED) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, banded_matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, banded_matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, banded_matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, banded_matrix::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, banded_adaptor >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, banded_adaptor >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, banded_adaptor >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, banded_adaptor >::reverse_iterator2>::constraints (); #endif // Triangular Matrix #if defined (INTERNAL) || defined (INTERNAL_TRIANGULAR) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, triangular_matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, triangular_matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, triangular_matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, triangular_matrix::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, triangular_adaptor >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, triangular_adaptor >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, triangular_adaptor >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, triangular_adaptor >::reverse_iterator2>::constraints (); #endif // Symmetric Matrix #if defined (INTERNAL) || defined (INTERNAL_SYMMETRIC) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, symmetric_matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, symmetric_matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, symmetric_matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, symmetric_matrix::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, symmetric_adaptor >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, symmetric_adaptor >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, symmetric_adaptor >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, symmetric_adaptor >::reverse_iterator2>::constraints (); #endif // Hermitian Matrix #if defined (INTERNAL) || defined (INTERNAL_HERMITIAN) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedRandomAccess2DIteratorConcept::const_iterator1, hermitian_matrix::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::iterator1, hermitian_matrix::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept::const_reverse_iterator1, hermitian_matrix::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept::reverse_iterator1, hermitian_matrix::reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, hermitian_adaptor >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, hermitian_adaptor >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, hermitian_adaptor >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, hermitian_adaptor >::reverse_iterator2>::constraints (); #endif // Sparse Matrix #if defined (INTERNAL) || defined (INTERNAL_MATRIX_SPARSE) MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedBidirectional2DIteratorConcept::const_iterator1, sparse_matrix::const_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::iterator1, sparse_matrix::iterator2>::constraints (); IndexedBidirectional2DIteratorConcept::const_reverse_iterator1, sparse_matrix::const_reverse_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::reverse_iterator1, sparse_matrix::reverse_iterator2>::constraints (); MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedBidirectional2DIteratorConcept::const_iterator1, sparse_vector_of_sparse_vector::const_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::iterator1, sparse_vector_of_sparse_vector::iterator2>::constraints (); IndexedBidirectional2DIteratorConcept::const_reverse_iterator1, sparse_vector_of_sparse_vector::const_reverse_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::reverse_iterator1, sparse_vector_of_sparse_vector::reverse_iterator2>::constraints (); MatrixConcept >::constraints (); MutableMatrixConcept >::constraints (); IndexedBidirectional2DIteratorConcept::const_iterator1, compressed_matrix::const_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::iterator1, compressed_matrix::iterator2>::constraints (); IndexedBidirectional2DIteratorConcept::const_reverse_iterator1, compressed_matrix::const_reverse_iterator2>::constraints (); MutableIndexedBidirectional2DIteratorConcept::reverse_iterator1, compressed_matrix::reverse_iterator2>::constraints (); #endif // Scalar Expressions #if defined (INTERNAL) || defined (INTERNAL_VECTOR_EXPRESSION) ScalarExpressionConcept >::constraints (); ScalarExpressionConcept >::constraints (); // Vector Expressions VectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); VectorExpressionConcept > >::constraints (); // MutableVectorExpressionConcept > >::constraints (); IndexedRandomAccess1DIteratorConcept >::const_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::iterator>::constraints (); IndexedRandomAccess1DIteratorConcept >::const_reverse_iterator>::constraints (); MutableIndexedRandomAccess1DIteratorConcept >::reverse_iterator>::constraints (); VectorExpressionConcept, scalar_identity > >::constraints (); IndexedRandomAccess1DIteratorConcept, scalar_identity >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, scalar_identity >::const_reverse_iterator>::constraints (); VectorExpressionConcept, vector, scalar_plus > >::constraints (); IndexedRandomAccess1DIteratorConcept, vector, scalar_plus >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, vector, scalar_plus >::const_reverse_iterator>::constraints (); VectorExpressionConcept, vector, scalar_multiplies > >::constraints (); IndexedRandomAccess1DIteratorConcept, vector, scalar_multiplies >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, vector, scalar_multiplies >::const_reverse_iterator>::constraints (); VectorExpressionConcept, scalar_value, scalar_multiplies > >::constraints (); IndexedRandomAccess1DIteratorConcept, scalar_value, scalar_multiplies >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, scalar_value, scalar_multiplies >::const_reverse_iterator>::constraints (); ScalarExpressionConcept, vector_sum > >::constraints (); ScalarExpressionConcept, vector_norm_1 > >::constraints (); ScalarExpressionConcept, vector_norm_2 > >::constraints (); ScalarExpressionConcept, vector_norm_inf > >::constraints (); ScalarExpressionConcept, vector, vector_inner_prod > >::constraints (); #endif // Matrix Expressions #if defined (INTERNAL) || defined (INTERNAL_MATRIX_EXPRESSION) MatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, matrix_const_reference >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, matrix_const_reference >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept > >::constraints (); // MutableMatrixExpressionConcept > >::constraints (); IndexedRandomAccess2DIteratorConcept >::const_iterator1, matrix_reference >::const_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::iterator1, matrix_reference >::iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept >::const_reverse_iterator1, matrix_reference >::const_reverse_iterator2>::constraints (); MutableIndexedRandomAccess2DIteratorConcept >::reverse_iterator1, matrix_reference >::reverse_iterator2>::constraints (); MatrixExpressionConcept, vector, scalar_multiplies > >::constraints (); IndexedRandomAccess2DIteratorConcept, vector, scalar_multiplies >::const_iterator1, vector_matrix_binary, vector, scalar_multiplies >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, vector, scalar_multiplies >::const_reverse_iterator1, vector_matrix_binary, vector, scalar_multiplies >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept, scalar_identity > >::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_identity >::const_iterator1, matrix_unary1, scalar_identity >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_identity >::const_reverse_iterator1, matrix_unary1, scalar_identity >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept, scalar_identity > >::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_identity >::const_iterator1, matrix_unary2, scalar_identity >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_identity >::const_reverse_iterator1, matrix_unary2, scalar_identity >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept, matrix, scalar_plus > >::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, scalar_plus >::const_iterator1, matrix_binary, matrix, scalar_plus >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, scalar_plus >::const_reverse_iterator1, matrix_binary, matrix, scalar_plus >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept, matrix, scalar_multiplies > >::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, scalar_multiplies >::const_iterator1, matrix_binary_scalar1, matrix, scalar_multiplies >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, scalar_multiplies >::const_reverse_iterator1, matrix_binary_scalar1, matrix, scalar_multiplies >::const_reverse_iterator2>::constraints (); MatrixExpressionConcept, scalar_value, scalar_multiplies > >::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_value, scalar_multiplies >::const_iterator1, matrix_binary_scalar2, scalar_value, scalar_multiplies >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, scalar_value, scalar_multiplies >::const_reverse_iterator1, matrix_binary_scalar2, scalar_value, scalar_multiplies >::const_reverse_iterator2>::constraints (); VectorExpressionConcept, vector, matrix_vector_prod1 > >::constraints (); IndexedRandomAccess1DIteratorConcept, vector, matrix_vector_prod1 >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, vector, matrix_vector_prod1 >::const_reverse_iterator>::constraints (); VectorExpressionConcept, matrix, matrix_vector_prod2 > >::constraints (); IndexedRandomAccess1DIteratorConcept, matrix, matrix_vector_prod2 >::const_iterator>::constraints (); IndexedRandomAccess1DIteratorConcept, matrix, matrix_vector_prod2 >::const_reverse_iterator>::constraints (); MatrixExpressionConcept, matrix, matrix_matrix_prod > >::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, matrix_matrix_prod >::const_iterator1, matrix_matrix_binary, matrix, matrix_matrix_prod >::const_iterator2>::constraints (); IndexedRandomAccess2DIteratorConcept, matrix, matrix_matrix_prod >::const_reverse_iterator1, matrix_matrix_binary, matrix, matrix_matrix_prod >::const_reverse_iterator2>::constraints (); ScalarExpressionConcept, matrix_norm_1 > >::constraints (); ScalarExpressionConcept, matrix_norm_frobenius > >::constraints (); ScalarExpressionConcept, matrix_norm_inf > >::constraints (); #endif #ifdef EXTERNAL AdditiveAbelianGroupConcept::constraints (); CommutativeRingWithIdentityConcept::constraints (); FieldConcept::constraints (); VectorSpaceConcept >::constraints (); RingWithIdentityConcept >::constraints (0); VectorSpaceConcept >::constraints (); LinearOperatorConcept, matrix >::constraints (); AdditiveAbelianGroupConcept::constraints (); CommutativeRingWithIdentityConcept::constraints (); FieldConcept::constraints (); VectorSpaceConcept >::constraints (); RingWithIdentityConcept >::constraints (0); VectorSpaceConcept >::constraints (); LinearOperatorConcept, matrix >::constraints (); #ifndef BOOST_MSVC AdditiveAbelianGroupConcept >::constraints (); CommutativeRingWithIdentityConcept >::constraints (); FieldConcept >::constraints (); VectorSpaceConcept, vector > >::constraints (); RingWithIdentityConcept > >::constraints (0); VectorSpaceConcept, matrix > >::constraints (); LinearOperatorConcept, vector >, matrix > >::constraints (); AdditiveAbelianGroupConcept >::constraints (); CommutativeRingWithIdentityConcept >::constraints (); FieldConcept >::constraints (); VectorSpaceConcept, vector > >::constraints (); RingWithIdentityConcept > >::constraints (0); VectorSpaceConcept, matrix > >::constraints (); LinearOperatorConcept, vector >, matrix > >::constraints (); #endif #endif } }}} #endif ",16227,True,3107.2876749133666,median "/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2016-2019 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the ""Software""), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #include ""../gl_driver.h"" #include ""common/common.h"" #include ""strings/string_utils.h"" #if ENABLED(RDOC_WIN32) && ENABLED(RENDERDOC_DX_GL_INTEROP) struct ID3D11Resource; void *UnwrapDXDevice(void *dxDevice); ID3D11Resource *UnwrapDXResource(void *dxObject); void GetDXTextureProperties(void *dxObject, ResourceFormat &fmt, uint32_t &width, uint32_t &height, uint32_t &depth, uint32_t &mips, uint32_t &layers, uint32_t &samples); BOOL WrappedOpenGL::wglDXSetResourceShareHandleNV(void *dxObject, HANDLE shareHandle) { // no-op return GL.wglDXSetResourceShareHandleNV(dxObject, shareHandle); } HANDLE WrappedOpenGL::wglDXOpenDeviceNV(void *dxDevice) { void *unwrapped = UnwrapDXDevice(dxDevice); if(unwrapped) { HANDLE ret = (HANDLE)GL.wglDXOpenDeviceNV(unwrapped); SetLastError(S_OK); return ret; } SetLastError(ERROR_NOT_SUPPORTED); return 0; } BOOL WrappedOpenGL::wglDXCloseDeviceNV(HANDLE hDevice) { return GL.wglDXCloseDeviceNV(hDevice); } struct WrappedHANDLE { HANDLE real; GLResource res; }; HANDLE Unwrap(HANDLE h) { return ((WrappedHANDLE *)h)->real; } HANDLE WrappedOpenGL::wglDXRegisterObjectNV(HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access) { RDCASSERT(IsCaptureMode(m_State)); ID3D11Resource *real = UnwrapDXResource(dxObject); if(real == NULL) { SetLastError(ERROR_OPEN_FAILED); return 0; } WrappedHANDLE *wrapped = new WrappedHANDLE(); if(type == eGL_RENDERBUFFER) wrapped->res = RenderbufferRes(GetCtx(), name); else if(type == eGL_NONE) wrapped->res = BufferRes(GetCtx(), name); else wrapped->res = TextureRes(GetCtx(), name); GLResourceRecord *record = GetResourceManager()->GetResourceRecord(wrapped->res); if(!record) { RDCERR(""Unrecognised object with type %x and name %u"", type, name); delete wrapped; return NULL; } SERIALISE_TIME_CALL(wrapped->real = GL.wglDXRegisterObjectNV(hDevice, real, name, type, access)); if(wrapped->real == NULL) { delete wrapped; return NULL; } { RDCASSERT(record); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_wglDXRegisterObjectNV(ser, wrapped->res, type, dxObject); record->AddChunk(scope.Get()); } if(type != eGL_NONE) { ResourceFormat fmt; uint32_t width = 0, height = 0, depth = 0, mips = 0, layers = 0, samples = 0; GetDXTextureProperties(dxObject, fmt, width, height, depth, mips, layers, samples); // defined as arrays mostly for Coverity code analysis to stay calm about passing // them to the *TexParameter* functions GLint maxlevel[4] = {GLint(mips - 1), 0, 0, 0}; GL.glTextureParameteriEXT(wrapped->res.name, type, eGL_TEXTURE_MAX_LEVEL, GLint(mips - 1)); ResourceId texId = record->GetResourceID(); m_Textures[texId].resource = wrapped->res; m_Textures[texId].curType = type; m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = RDCMAX(depth, samples); m_Textures[texId].samples = samples; m_Textures[texId].dimension = 2; if(type == eGL_TEXTURE_1D || type == eGL_TEXTURE_1D_ARRAY) m_Textures[texId].dimension = 1; else if(type == eGL_TEXTURE_3D) m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = MakeGLFormat(fmt); m_Textures[texId].mipsValid = (1 << mips) - 1; } return wrapped; } BOOL WrappedOpenGL::wglDXUnregisterObjectNV(HANDLE hDevice, HANDLE hObject) { // don't need to intercept this, as the DX and GL textures will be deleted independently BOOL ret = GL.wglDXUnregisterObjectNV(hDevice, Unwrap(hObject)); delete(WrappedHANDLE *)hObject; return ret; } BOOL WrappedOpenGL::wglDXObjectAccessNV(HANDLE hObject, GLenum access) { // we don't need to care about access return GL.wglDXObjectAccessNV(Unwrap(hObject), access); } BOOL WrappedOpenGL::wglDXLockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { HANDLE *unwrapped = new HANDLE[count]; for(GLint i = 0; i < count; i++) unwrapped[i] = Unwrap(hObjects[i]); BOOL ret; SERIALISE_TIME_CALL(ret = GL.wglDXLockObjectsNV(hDevice, count, unwrapped)); if(IsActiveCapturing(m_State)) { for(GLint i = 0; i < count; i++) { WrappedHANDLE *w = (WrappedHANDLE *)hObjects[i]; USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_wglDXLockObjectsNV(ser, w->res); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(GetResourceManager()->GetID(w->res), eFrameRef_Read); } } SAFE_DELETE_ARRAY(unwrapped); return ret; } BOOL WrappedOpenGL::wglDXUnlockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { HANDLE *unwrapped = new HANDLE[count]; for(GLint i = 0; i < count; i++) unwrapped[i] = Unwrap(hObjects[i]); BOOL ret = GL.wglDXUnlockObjectsNV(hDevice, count, unwrapped); SAFE_DELETE_ARRAY(unwrapped); return ret; } #else BOOL WrappedOpenGL::wglDXSetResourceShareHandleNV(void *dxObject, HANDLE shareHandle) { return 0; } HANDLE WrappedOpenGL::wglDXOpenDeviceNV(void *dxDevice) { return 0; } BOOL WrappedOpenGL::wglDXCloseDeviceNV(HANDLE hDevice) { return 0; } HANDLE WrappedOpenGL::wglDXRegisterObjectNV(HANDLE hDevice, void *dxObject, GLuint name, GLenum type, GLenum access) { return 0; } BOOL WrappedOpenGL::wglDXUnregisterObjectNV(HANDLE hDevice, HANDLE hObject) { return 0; } BOOL WrappedOpenGL::wglDXObjectAccessNV(HANDLE hObject, GLenum access) { return 0; } BOOL WrappedOpenGL::wglDXLockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { return 0; } BOOL WrappedOpenGL::wglDXUnlockObjectsNV(HANDLE hDevice, GLint count, HANDLE *hObjects) { return 0; } #endif template bool WrappedOpenGL::Serialise_wglDXRegisterObjectNV(SerialiserType &ser, GLResource Resource, GLenum type, void *dxObject) { SERIALISE_ELEMENT(Resource); GLenum internalFormat = eGL_NONE; uint32_t width = 0, height = 0, depth = 0, mips = 0, layers = 0, samples = 0; if(ser.IsWriting()) { ResourceFormat format; #if ENABLED(RDOC_WIN32) && ENABLED(RENDERDOC_DX_GL_INTEROP) GetDXTextureProperties(dxObject, format, width, height, depth, mips, layers, samples); if(type != eGL_NONE) internalFormat = MakeGLFormat(format); #else RDCERR(""Should never happen - cannot serialise wglDXRegisterObjectNV, interop is disabled""); #endif } SERIALISE_ELEMENT(type); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT(mips); SERIALISE_ELEMENT(layers); SERIALISE_ELEMENT(samples); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { GLuint name = Resource.name; switch(type) { case eGL_NONE: case eGL_TEXTURE_BUFFER: { GL.glNamedBufferDataEXT(name, width, NULL, eGL_STATIC_DRAW); break; } case eGL_TEXTURE_1D: GL.glTextureStorage1DEXT(name, type, mips, internalFormat, width); break; case eGL_TEXTURE_1D_ARRAY: GL.glTextureStorage2DEXT(name, type, mips, internalFormat, width, layers); break; // treat renderbuffers and texture rects as tex2D just to make things easier case eGL_RENDERBUFFER: case eGL_TEXTURE_RECTANGLE: case eGL_TEXTURE_2D: case eGL_TEXTURE_CUBE_MAP: GL.glTextureStorage2DEXT(name, type, mips, internalFormat, width, height); break; case eGL_TEXTURE_2D_ARRAY: case eGL_TEXTURE_CUBE_MAP_ARRAY: GL.glTextureStorage3DEXT(name, type, mips, internalFormat, width, height, layers); break; case eGL_TEXTURE_2D_MULTISAMPLE: GL.glTextureStorage2DMultisampleEXT(name, type, samples, internalFormat, width, height, GL_TRUE); break; case eGL_TEXTURE_2D_MULTISAMPLE_ARRAY: GL.glTextureStorage3DMultisampleEXT(name, type, samples, internalFormat, width, height, layers, GL_TRUE); break; case eGL_TEXTURE_3D: GL.glTextureStorage3DEXT(name, type, mips, internalFormat, width, height, depth); break; default: RDCERR(""Unexpected type of interop texture: %s"", ToStr(type).c_str()); break; } if(type != eGL_NONE) { ResourceId liveId = GetResourceManager()->GetID(Resource); m_Textures[liveId].curType = type; m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = RDCMAX(depth, samples); m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 2; if(type == eGL_TEXTURE_1D || type == eGL_TEXTURE_1D_ARRAY) m_Textures[liveId].dimension = 1; else if(type == eGL_TEXTURE_3D) m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].mipsValid = (1 << mips) - 1; } AddResourceInitChunk(Resource); } return true; } template bool WrappedOpenGL::Serialise_wglDXLockObjectsNV(SerialiserType &ser, GLResource Resource) { SERIALISE_ELEMENT(Resource); SERIALISE_ELEMENT_LOCAL(textype, Resource.Namespace == eResBuffer ? eGL_NONE : m_Textures[GetResourceManager()->GetID(Resource)].curType) .Hidden(); // buffer contents are easier to save if(textype == eGL_NONE) { byte *Contents = NULL; uint32_t length = 1; // while writing, fetch the buffer's size and contents if(ser.IsWriting()) { GL.glGetNamedBufferParameterivEXT(Resource.name, eGL_BUFFER_SIZE, (GLint *)&length); Contents = new byte[length]; GLuint oldbuf = 0; GL.glGetIntegerv(eGL_COPY_READ_BUFFER_BINDING, (GLint *)&oldbuf); GL.glBindBuffer(eGL_COPY_READ_BUFFER, Resource.name); GL.glGetBufferSubData(eGL_COPY_READ_BUFFER, 0, (GLsizeiptr)length, Contents); GL.glBindBuffer(eGL_COPY_READ_BUFFER, oldbuf); } SERIALISE_ELEMENT_ARRAY(Contents, length); SERIALISE_ELEMENT(length); SERIALISE_CHECK_READ_ERRORS(); // restore on replay if(IsReplayingAndReading()) { uint32_t liveLength = 1; GL.glGetNamedBufferParameterivEXT(Resource.name, eGL_BUFFER_SIZE, (GLint *)&liveLength); GL.glNamedBufferSubData(Resource.name, 0, (GLsizeiptr)RDCMIN(length, liveLength), Contents); } } else { GLuint ppb = 0, pub = 0; PixelPackState pack; PixelUnpackState unpack; // save and restore pixel pack/unpack state. We only need one or the other but for clarity we // push and pop both always. if(ser.IsWriting() || !IsStructuredExporting(m_State)) { GL.glGetIntegerv(eGL_PIXEL_PACK_BUFFER_BINDING, (GLint *)&ppb); GL.glGetIntegerv(eGL_PIXEL_UNPACK_BUFFER_BINDING, (GLint *)&pub); GL.glBindBuffer(eGL_PIXEL_PACK_BUFFER, 0); GL.glBindBuffer(eGL_PIXEL_UNPACK_BUFFER, 0); pack.Fetch(false); unpack.Fetch(false); ResetPixelPackState(false, 1); ResetPixelUnpackState(false, 1); } TextureData &details = m_Textures[GetResourceManager()->GetID(Resource)]; GLuint tex = Resource.name; // serialise the metadata for convenience SERIALISE_ELEMENT_LOCAL(internalFormat, details.internalFormat).Hidden(); SERIALISE_ELEMENT_LOCAL(width, details.width).Hidden(); SERIALISE_ELEMENT_LOCAL(height, details.height).Hidden(); SERIALISE_ELEMENT_LOCAL(depth, details.depth).Hidden(); RDCASSERT(internalFormat == details.internalFormat, internalFormat, details.internalFormat); RDCASSERT(width == details.width, width, details.width); RDCASSERT(height == details.height, height, details.height); RDCASSERT(depth == details.depth, depth, details.depth); GLenum fmt = GetBaseFormat(internalFormat); GLenum type = GetDataType(internalFormat); GLint dim = details.dimension; uint32_t size = (uint32_t)GetByteSize(width, height, depth, fmt, type); int mips = 0; if(!IsStructuredExporting(m_State)) mips = GetNumMips(textype, tex, width, height, depth); SERIALISE_ELEMENT(mips).Hidden(); byte *scratchBuf = NULL; // on read and write, we allocate a single buffer big enough for all mips and re-use it // to avoid repeated new/free. scratchBuf = AllocAlignedBuffer(size); GLuint prevtex = 0; if(!IsStructuredExporting(m_State)) { GL.glGetIntegerv(TextureBinding(details.curType), (GLint *)&prevtex); GL.glBindTexture(textype, tex); } for(int i = 0; i < mips; i++) { int w = RDCMAX(details.width >> i, 1); int h = RDCMAX(details.height >> i, 1); int d = RDCMAX(details.depth >> i, 1); if(textype == eGL_TEXTURE_CUBE_MAP_ARRAY || textype == eGL_TEXTURE_1D_ARRAY || textype == eGL_TEXTURE_2D_ARRAY) d = details.depth; size = (uint32_t)GetByteSize(w, h, d, fmt, type); GLenum targets[] = { eGL_TEXTURE_CUBE_MAP_POSITIVE_X, eGL_TEXTURE_CUBE_MAP_NEGATIVE_X, eGL_TEXTURE_CUBE_MAP_POSITIVE_Y, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Y, eGL_TEXTURE_CUBE_MAP_POSITIVE_Z, eGL_TEXTURE_CUBE_MAP_NEGATIVE_Z, }; int count = ARRAY_COUNT(targets); if(textype != eGL_TEXTURE_CUBE_MAP) { targets[0] = textype; count = 1; } for(int trg = 0; trg < count; trg++) { if(ser.IsWriting()) { // we avoid glGetTextureImageEXT as it seems buggy for cubemap faces GL.glGetTexImage(targets[trg], i, fmt, type, scratchBuf); } // serialise without allocating memory as we already have our scratch buf sized. ser.Serialise(""SubresourceContents""_lit, scratchBuf, size, SerialiserFlags::NoFlags); if(IsReplayingAndReading() && !ser.IsErrored()) { if(dim == 1) GL.glTextureSubImage1DEXT(tex, targets[trg], i, 0, w, fmt, type, scratchBuf); else if(dim == 2) GL.glTextureSubImage2DEXT(tex, targets[trg], i, 0, 0, w, h, fmt, type, scratchBuf); else if(dim == 3) GL.glTextureSubImage3DEXT(tex, targets[trg], i, 0, 0, 0, w, h, d, fmt, type, scratchBuf); } } } FreeAlignedBuffer(scratchBuf); // restore pixel (un)packing state if(ser.IsWriting() || !IsStructuredExporting(m_State)) { GL.glBindBuffer(eGL_PIXEL_PACK_BUFFER, ppb); GL.glBindBuffer(eGL_PIXEL_UNPACK_BUFFER, pub); pack.Apply(false); unpack.Apply(false); } if(!IsStructuredExporting(m_State)) GL.glBindTexture(textype, prevtex); SERIALISE_CHECK_READ_ERRORS(); } return true; } #pragma region Memory Objects template bool WrappedOpenGL::Serialise_glCreateMemoryObjectsEXT(SerialiserType &ser, GLsizei n, GLuint *memoryObjects) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(memory, GetResourceManager()->GetID(ExtMemRes(GetCtx(), *memoryObjects))) .TypedAs(""GLResource""_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(GL.glCreateMemoryObjectsEXT); GLuint real = 0; GL.glCreateMemoryObjectsEXT(1, &real); GLResource res = ExtMemRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(memory, res); AddResource(memory, ResourceType::Memory, ""Memory Object""); } return true; } void WrappedOpenGL::glCreateMemoryObjectsEXT(GLsizei n, GLuint *memoryObjects) { SERIALISE_TIME_CALL(GL.glCreateMemoryObjectsEXT(n, memoryObjects)); for(GLsizei i = 0; i < n; i++) { GLResource res = ExtMemRes(GetCtx(), memoryObjects[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glCreateMemoryObjectsEXT(ser, 1, memoryObjects + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteMemoryObjectsEXT(GLsizei n, const GLuint *memoryObjects) { for(GLsizei i = 0; i < n; i++) { GLResource res = ExtMemRes(GetCtx(), memoryObjects[i]); if(GetResourceManager()->HasCurrentResource(res)) { if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } GL.glDeleteMemoryObjectsEXT(n, memoryObjects); } template bool WrappedOpenGL::Serialise_glMemoryObjectParameterivEXT(SerialiserType &ser, GLuint memoryObjectHandle, GLenum pname, const GLint *params) { SERIALISE_ELEMENT_LOCAL(memoryObject, ExtMemRes(GetCtx(), memoryObjectHandle)); SERIALISE_ELEMENT(pname); // if other parameters are added in future that take more than one value, change the array count // here. SERIALISE_ELEMENT_ARRAY(params, 1U); SERIALISE_CHECK_READ_ERRORS(); RDCASSERT(pname == eGL_DEDICATED_MEMORY_OBJECT_EXT || pname == eGL_PROTECTED_MEMORY_OBJECT_EXT); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(GL.glMemoryObjectParameterivEXT); GL.glMemoryObjectParameterivEXT(memoryObject.name, pname, params); AddResourceInitChunk(memoryObject); } return true; } void WrappedOpenGL::glMemoryObjectParameterivEXT(GLuint memoryObject, GLenum pname, const GLint *params) { SERIALISE_TIME_CALL(GL.glMemoryObjectParameterivEXT(memoryObject, pname, params)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memoryObject)); if(!record) { RDCERR(""Called glMemoryObjectParameterivEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glMemoryObjectParameterivEXT(ser, memoryObject, pname, params); if(IsActiveCapturing(m_State)) { GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } else { record->AddChunk(scope.Get()); } } } template bool WrappedOpenGL::Serialise_glImportMemoryFdEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, GLint fd) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT(fd); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryFdEXT(GLuint memory, GLuint64 size, GLenum handleType, GLint fd) { SERIALISE_TIME_CALL(GL.glImportMemoryFdEXT(memory, size, handleType, fd)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryFdEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryFdEXT(ser, memory, size, handleType, fd); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportMemoryWin32HandleEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, void *handlePtr) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(handle, uint64_t(handlePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryWin32HandleEXT(GLuint memory, GLuint64 size, GLenum handleType, void *handle) { SERIALISE_TIME_CALL(GL.glImportMemoryWin32HandleEXT(memory, size, handleType, handle)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryWin32HandleEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryWin32HandleEXT(ser, memory, size, handleType, handle); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportMemoryWin32NameEXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 size, GLenum handleType, const void *namePtr) { SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(size); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(name, StringFormat::Wide2UTF8((const wchar_t *)namePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay external memory we just allocate textures/buffers with their // own backing store. Keep this around for tracking purposes AddResourceInitChunk(memory); } return true; } void WrappedOpenGL::glImportMemoryWin32NameEXT(GLuint memory, GLuint64 size, GLenum handleType, const void *name) { SERIALISE_TIME_CALL(GL.glImportMemoryWin32NameEXT(memory, size, handleType, name)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!record) { RDCERR(""Called glImportMemoryWin32NameEXT with invalid/unrecognised memory object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportMemoryWin32NameEXT(ser, memory, size, handleType, name); record->AddChunk(scope.Get()); } } #pragma endregion #pragma region Semaphores template bool WrappedOpenGL::Serialise_glGenSemaphoresEXT(SerialiserType &ser, GLsizei n, GLuint *semaphores) { SERIALISE_ELEMENT(n); SERIALISE_ELEMENT_LOCAL(semaphore, GetResourceManager()->GetID(ExtSemRes(GetCtx(), *semaphores))) .TypedAs(""GLResource""_lit); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(GL.glGenSemaphoresEXT); GLuint real = 0; GL.glGenSemaphoresEXT(1, &real); GLResource res = ExtSemRes(GetCtx(), real); ResourceId live = m_ResourceManager->RegisterResource(res); GetResourceManager()->AddLiveResource(semaphore, res); AddResource(semaphore, ResourceType::Sync, ""Semaphore""); } return true; } void WrappedOpenGL::glGenSemaphoresEXT(GLsizei n, GLuint *semaphores) { SERIALISE_TIME_CALL(GL.glGenSemaphoresEXT(n, semaphores)); for(GLsizei i = 0; i < n; i++) { GLResource res = ExtSemRes(GetCtx(), semaphores[i]); ResourceId id = GetResourceManager()->RegisterResource(res); if(IsCaptureMode(m_State)) { Chunk *chunk = NULL; { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glGenSemaphoresEXT(ser, 1, semaphores + i); chunk = scope.Get(); } GLResourceRecord *record = GetResourceManager()->AddResourceRecord(id); RDCASSERT(record); record->AddChunk(chunk); } else { GetResourceManager()->AddLiveResource(id, res); } } } void WrappedOpenGL::glDeleteSemaphoresEXT(GLsizei n, const GLuint *semaphores) { for(GLsizei i = 0; i < n; i++) { GLResource res = ExtSemRes(GetCtx(), semaphores[i]); if(GetResourceManager()->HasCurrentResource(res)) { if(GetResourceManager()->HasResourceRecord(res)) GetResourceManager()->GetResourceRecord(res)->Delete(GetResourceManager()); GetResourceManager()->UnregisterResource(res); } } GL.glDeleteSemaphoresEXT(n, semaphores); } template bool WrappedOpenGL::Serialise_glSemaphoreParameterui64vEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum pname, const GLuint64 *params) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(pname); // if other parameters are added in future that take more than one value, change the array count // here. SERIALISE_ELEMENT_ARRAY(params, 1U); SERIALISE_CHECK_READ_ERRORS(); RDCASSERT(pname == eGL_D3D12_FENCE_VALUE_EXT); if(IsReplayingAndReading()) { CheckReplayFunctionPresent(GL.glSemaphoreParameterui64vEXT); GL.glSemaphoreParameterui64vEXT(semaphore.name, pname, params); AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glSemaphoreParameterui64vEXT(GLuint semaphore, GLenum pname, const GLuint64 *params) { SERIALISE_TIME_CALL(GL.glSemaphoreParameterui64vEXT(semaphore, pname, params)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glSemaphoreParameterui64vEXT with invalid/unrecognised semaphore""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glSemaphoreParameterui64vEXT(ser, semaphore, pname, params); if(IsActiveCapturing(m_State)) { GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(record->GetResourceID(), eFrameRef_Read); } else { record->AddChunk(scope.Get()); } } } template bool WrappedOpenGL::Serialise_glImportSemaphoreFdEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, GLint fd) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT(fd); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreFdEXT(GLuint semaphore, GLenum handleType, GLint fd) { SERIALISE_TIME_CALL(GL.glImportSemaphoreFdEXT(semaphore, handleType, fd)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreFdEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreFdEXT(ser, semaphore, handleType, fd); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportSemaphoreWin32HandleEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, void *handlePtr) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(handle, uint64_t(handlePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreWin32HandleEXT(GLuint semaphore, GLenum handleType, void *handle) { SERIALISE_TIME_CALL(GL.glImportSemaphoreWin32HandleEXT(semaphore, handleType, handle)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreWin32HandleEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreWin32HandleEXT(ser, semaphore, handleType, handle); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glImportSemaphoreWin32NameEXT(SerialiserType &ser, GLuint semaphoreHandle, GLenum handleType, const void *namePtr) { SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(handleType); SERIALISE_ELEMENT_LOCAL(name, StringFormat::Wide2UTF8((const wchar_t *)namePtr)); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). AddResourceInitChunk(semaphore); } return true; } void WrappedOpenGL::glImportSemaphoreWin32NameEXT(GLuint semaphore, GLenum handleType, const void *name) { SERIALISE_TIME_CALL(GL.glImportSemaphoreWin32NameEXT(semaphore, handleType, name)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(ExtSemRes(GetCtx(), semaphore)); if(!record) { RDCERR(""Called glImportSemaphoreWin32NameEXT with invalid/unrecognised semaphore object""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glImportSemaphoreWin32NameEXT(ser, semaphore, handleType, name); record->AddChunk(scope.Get()); } } template bool WrappedOpenGL::Serialise_glWaitSemaphoreEXT(SerialiserType &ser, GLuint semaphoreHandle, GLuint numBufferBarriers, const GLuint *bufferHandles, GLuint numTextureBarriers, const GLuint *textureHandles, const GLenum *srcLayouts) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. rdcarray buffers, textures; if(ser.IsWriting()) { buffers.reserve(numBufferBarriers); for(GLuint i = 0; i < numBufferBarriers; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles ? bufferHandles[i] : 0)); textures.reserve(numTextureBarriers); for(GLuint i = 0; i < numTextureBarriers; i++) textures.push_back(TextureRes(GetCtx(), textureHandles ? textureHandles[i] : 0)); } SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(numBufferBarriers); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(numTextureBarriers); SERIALISE_ELEMENT(textures); SERIALISE_ELEMENT_ARRAY(srcLayouts, numTextureBarriers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). GL.glFinish(); } return true; } void WrappedOpenGL::glWaitSemaphoreEXT(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts) { SERIALISE_TIME_CALL(GL.glWaitSemaphoreEXT(semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, srcLayouts)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glWaitSemaphoreEXT(ser, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, srcLayouts); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtSemRes(GetCtx(), semaphore), eFrameRef_Read); for(GLuint b = 0; buffers && b < numBufferBarriers; b++) GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffers[b]), eFrameRef_Read); for(GLuint t = 0; textures && t < numTextureBarriers; t++) GetResourceManager()->MarkResourceFrameReferenced(TextureRes(GetCtx(), textures[t]), eFrameRef_Read); } } template bool WrappedOpenGL::Serialise_glSignalSemaphoreEXT(SerialiserType &ser, GLuint semaphoreHandle, GLuint numBufferBarriers, const GLuint *bufferHandles, GLuint numTextureBarriers, const GLuint *textureHandles, const GLenum *dstLayouts) { // can't serialise arrays of GL handles since they're not wrapped or typed :(. rdcarray buffers, textures; if(ser.IsWriting()) { buffers.reserve(numBufferBarriers); for(GLuint i = 0; i < numBufferBarriers; i++) buffers.push_back(BufferRes(GetCtx(), bufferHandles ? bufferHandles[i] : 0)); textures.reserve(numTextureBarriers); for(GLuint i = 0; i < numTextureBarriers; i++) textures.push_back(TextureRes(GetCtx(), textureHandles ? textureHandles[i] : 0)); } SERIALISE_ELEMENT_LOCAL(semaphore, ExtSemRes(GetCtx(), semaphoreHandle)); SERIALISE_ELEMENT(numBufferBarriers); SERIALISE_ELEMENT(buffers); SERIALISE_ELEMENT(numTextureBarriers); SERIALISE_ELEMENT(textures); SERIALISE_ELEMENT_ARRAY(dstLayouts, numTextureBarriers); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay semaphores we just fully glFinish() when we need to wait on // them (just in case). } return true; } void WrappedOpenGL::glSignalSemaphoreEXT(GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts) { SERIALISE_TIME_CALL(GL.glSignalSemaphoreEXT(semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, dstLayouts)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glSignalSemaphoreEXT(ser, semaphore, numBufferBarriers, buffers, numTextureBarriers, textures, dstLayouts); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtSemRes(GetCtx(), semaphore), eFrameRef_Read); for(GLuint b = 0; buffers && b < numBufferBarriers; b++) GetResourceManager()->MarkResourceFrameReferenced(BufferRes(GetCtx(), buffers[b]), eFrameRef_Read); for(GLuint t = 0; textures && t < numTextureBarriers; t++) GetResourceManager()->MarkResourceFrameReferenced(TextureRes(GetCtx(), textures[t]), eFrameRef_Read); } } #pragma endregion #pragma region Keyed Mutexes template bool WrappedOpenGL::Serialise_glAcquireKeyedMutexWin32EXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 key, GLuint timeout) { SERIALISE_ELEMENT_LOCAL(memory, ExtSemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(key); SERIALISE_ELEMENT(timeout); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay keyed mutexes as we don't create external memory } return true; } GLboolean WrappedOpenGL::glAcquireKeyedMutexWin32EXT(GLuint memory, GLuint64 key, GLuint timeout) { GLboolean ret; SERIALISE_TIME_CALL(ret = GL.glAcquireKeyedMutexWin32EXT(memory, key, timeout)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glAcquireKeyedMutexWin32EXT(ser, memory, key, timeout); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtMemRes(GetCtx(), memory), eFrameRef_Read); } return ret; } template bool WrappedOpenGL::Serialise_glReleaseKeyedMutexWin32EXT(SerialiserType &ser, GLuint memoryHandle, GLuint64 key) { SERIALISE_ELEMENT_LOCAL(memory, ExtSemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(key); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // nothing to do - we don't replay keyed mutexes as we don't create external memory } return true; } GLboolean WrappedOpenGL::glReleaseKeyedMutexWin32EXT(GLuint memory, GLuint64 key) { GLboolean ret; SERIALISE_TIME_CALL(ret = GL.glReleaseKeyedMutexWin32EXT(memory, key)); if(IsActiveCapturing(m_State)) { USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glReleaseKeyedMutexWin32EXT(ser, memory, key); GetContextRecord()->AddChunk(scope.Get()); GetResourceManager()->MarkResourceFrameReferenced(ExtMemRes(GetCtx(), memory), eFrameRef_Read); } return ret; } #pragma endregion #pragma region Buffers template bool WrappedOpenGL::Serialise_glNamedBufferStorageMemEXT(SerialiserType &ser, GLuint bufferHandle, GLsizeiptr sizeptr, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(buffer, BufferRes(GetCtx(), bufferHandle)); SERIALISE_ELEMENT_LOCAL(size, (uint64_t)sizeptr); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external buffer storage backed by external memory as just a plain buffer. // we have to come up with flags that will work regardless, so we're conservative here. // The spec says memory object backed buffers can't be mapped, but we set DYNAMIC_STORAGE as // it's unclear if they can be updated with glBufferSubData or not. GLbitfield flags = eGL_DYNAMIC_STORAGE_BIT; GL.glNamedBufferStorageEXT(buffer.name, (GLsizeiptr)size, NULL, flags); ResourceId id = GetResourceManager()->GetID(buffer); m_Buffers[id].size = size; AddResourceInitChunk(buffer); DerivedResource(memory, GetResourceManager()->GetOriginalID(id)); } return true; } void WrappedOpenGL::glNamedBufferStorageMemEXT(GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glNamedBufferStorageMemEXT(buffer, size, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetResourceManager()->GetResourceRecord(BufferRes(GetCtx(), buffer)); GLResourceRecord *memrecord = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!bufrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid buffer""); return; } if(!memrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid memory object""); return; } // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(bufrecord->Resource); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageMemEXT(ser, buffer, size, memory, offset); bufrecord->AddChunk(scope.Get()); bufrecord->AddParent(memrecord); bufrecord->Length = (int32_t)size; } } void WrappedOpenGL::glBufferStorageMemEXT(GLenum target, GLsizeiptr size, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glBufferStorageMemEXT(target, size, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *bufrecord = GetCtxData().m_BufferRecord[BufferIdx(target)]; GLResourceRecord *memrecord = GetResourceManager()->GetResourceRecord(ExtMemRes(GetCtx(), memory)); if(!bufrecord) { RDCERR(""Called glBufferStorageMemEXT with no buffer bound to %s"", ToStr(target).c_str()); return; } if(!memrecord) { RDCERR(""Called glNamedBufferStorageMemEXT with invalid memory object""); return; } // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(bufrecord->Resource); USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glNamedBufferStorageMemEXT(ser, bufrecord->Resource.name, size, memory, offset); bufrecord->AddChunk(scope.Get()); bufrecord->AddParent(memrecord); bufrecord->Length = (int32_t)size; } } #pragma endregion #pragma region Textures template bool WrappedOpenGL::Serialise_glTextureStorageMem1DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = 1; m_Textures[liveId].depth = 1; m_Textures[liveId].dimension = 1; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage1DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem1DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTextureStorageMem1DEXT(texture, levels, internalFormat, width, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem1DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem1DEXT(ser, texture, levels, internalFormat, width, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = 1; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 1; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem1DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem1DEXT(target, levels, internalFormat, width, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem1DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem1DEXT(ser, record->Resource.name, levels, internalFormat, width, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = 1; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 1; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem2DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = 1; m_Textures[liveId].dimension = 2; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage2DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width, height); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem2DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTextureStorageMem2DEXT(texture, levels, internalFormat, width, height, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem2DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DEXT(ser, texture, levels, internalFormat, width, height, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem2DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL( GL.glTexStorageMem2DEXT(target, levels, internalFormat, width, height, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem2DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DEXT(ser, record->Resource.name, levels, internalFormat, width, height, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem2DMultisampleEXT( SerialiserType &ser, GLuint textureHandle, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(samples); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT_TYPED(bool, fixedSampleLocations); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // the DSA function is emulated if not present, but we need to check the underlying function is // present CheckReplayFunctionPresent(GL.glTexStorage2DMultisample); // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = 1; m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 2; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = 1; GL.glTextureStorage2DMultisampleEXT(texture.name, m_Textures[liveId].curType, samples, internalFormat, width, height, fixedSampleLocations); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem2DMultisampleEXT(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem2DMultisampleEXT( texture, samples, internalFormat, width, height, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem2DMultisampleEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DMultisampleEXT(ser, texture, samples, internalFormat, width, height, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); // when bound to external memory, immediately consider dirty GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } void WrappedOpenGL::glTexStorageMem2DMultisampleEXT(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem2DMultisampleEXT( target, samples, internalFormat, width, height, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTexStorageMem2DMultisampleEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem2DMultisampleEXT(ser, record->Resource.name, samples, internalFormat, width, height, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = 1; m_Textures[texId].dimension = 2; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem3DEXT(SerialiserType &ser, GLuint textureHandle, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(levels); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = depth; m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = (1 << levels) - 1; GL.glTextureStorage3DEXT(texture.name, m_Textures[liveId].curType, levels, internalFormat, width, height, depth); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem3DEXT(GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem3DEXT(texture, levels, internalFormat, width, height, depth, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem3DEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DEXT(ser, texture, levels, internalFormat, width, height, depth, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } void WrappedOpenGL::glTexStorageMem3DEXT(GLenum target, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem3DEXT(target, levels, internalFormat, width, height, depth, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTextureStorageMem3DEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DEXT(ser, record->Resource.name, levels, internalFormat, width, height, depth, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = (1 << levels) - 1; } } template bool WrappedOpenGL::Serialise_glTextureStorageMem3DMultisampleEXT( SerialiserType &ser, GLuint textureHandle, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memoryHandle, GLuint64 offset) { SERIALISE_ELEMENT_LOCAL(texture, TextureRes(GetCtx(), textureHandle)); SERIALISE_ELEMENT(samples); SERIALISE_ELEMENT(internalFormat); SERIALISE_ELEMENT(width); SERIALISE_ELEMENT(height); SERIALISE_ELEMENT(depth); SERIALISE_ELEMENT_TYPED(bool, fixedSampleLocations); SERIALISE_ELEMENT_LOCAL(memory, ExtMemRes(GetCtx(), memoryHandle)); SERIALISE_ELEMENT(offset); SERIALISE_CHECK_READ_ERRORS(); if(IsReplayingAndReading()) { // Replay external texture storage backed by external memory as just a plain texture. ResourceId liveId = GetResourceManager()->GetID(texture); m_Textures[liveId].width = width; m_Textures[liveId].height = height; m_Textures[liveId].depth = depth; m_Textures[liveId].samples = samples; m_Textures[liveId].dimension = 3; m_Textures[liveId].internalFormat = internalFormat; m_Textures[liveId].emulated = false; m_Textures[liveId].mipsValid = 1; GL.glTextureStorage3DMultisampleEXT(texture.name, m_Textures[liveId].curType, samples, internalFormat, width, height, depth, fixedSampleLocations); AddResourceInitChunk(texture); DerivedResource(memory, GetResourceManager()->GetOriginalID(liveId)); } return true; } void WrappedOpenGL::glTextureStorageMem3DMultisampleEXT(GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTextureStorageMem3DMultisampleEXT( texture, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State)) { GLResourceRecord *record = GetResourceManager()->GetResourceRecord(TextureRes(GetCtx(), texture)); if(!record) { RDCERR(""Calling glTextureStorageMem3DMultisampleEXT with unrecognised texture""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DMultisampleEXT(ser, texture, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } void WrappedOpenGL::glTexStorageMem3DMultisampleEXT(GLenum target, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset) { SERIALISE_TIME_CALL(GL.glTexStorageMem3DMultisampleEXT( target, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset)); if(IsCaptureMode(m_State) && !IsProxyTarget(target)) { GLResourceRecord *record = GetCtxData().GetActiveTexRecord(target); if(!record) { RDCERR(""Calling glTexStorageMem3DMultisampleEXT with no texture bound""); return; } USE_SCRATCH_SERIALISER(); SCOPED_SERIALISE_CHUNK(gl_CurChunk); Serialise_glTextureStorageMem3DMultisampleEXT(ser, record->Resource.name, samples, internalFormat, width, height, depth, fixedSampleLocations, memory, offset); record->AddChunk(scope.Get()); GetResourceManager()->MarkDirtyResource(record->Resource); ResourceId texId = record->GetResourceID(); m_Textures[texId].width = width; m_Textures[texId].height = height; m_Textures[texId].samples = samples; m_Textures[texId].depth = depth; m_Textures[texId].dimension = 3; m_Textures[texId].internalFormat = internalFormat; m_Textures[texId].mipsValid = 1; } } #pragma endregion INSTANTIATE_FUNCTION_SERIALISED(void, wglDXRegisterObjectNV, GLResource Resource, GLenum type, void *dxObject); INSTANTIATE_FUNCTION_SERIALISED(void, wglDXLockObjectsNV, GLResource Resource); INSTANTIATE_FUNCTION_SERIALISED(void, glCreateMemoryObjectsEXT, GLsizei n, GLuint *memoryObjects); INSTANTIATE_FUNCTION_SERIALISED(void, glMemoryObjectParameterivEXT, GLuint memoryObject, GLenum pname, const GLint *params); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem1DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem2DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem2DMultisampleEXT, GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem3DEXT, GLuint texture, GLsizei levels, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glTextureStorageMem3DMultisampleEXT, GLuint texture, GLsizei samples, GLenum internalFormat, GLsizei width, GLsizei height, GLsizei depth, GLboolean fixedSampleLocations, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glNamedBufferStorageMemEXT, GLuint buffer, GLsizeiptr size, GLuint memory, GLuint64 offset); INSTANTIATE_FUNCTION_SERIALISED(void, glGenSemaphoresEXT, GLsizei n, GLuint *semaphores); INSTANTIATE_FUNCTION_SERIALISED(void, glSemaphoreParameterui64vEXT, GLuint semaphore, GLenum pname, const GLuint64 *params); INSTANTIATE_FUNCTION_SERIALISED(void, glWaitSemaphoreEXT, GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *srcLayouts); INSTANTIATE_FUNCTION_SERIALISED(void, glSignalSemaphoreEXT, GLuint semaphore, GLuint numBufferBarriers, const GLuint *buffers, GLuint numTextureBarriers, const GLuint *textures, const GLenum *dstLayouts); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryFdEXT, GLuint memory, GLuint64 size, GLenum handleType, GLint fd); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreFdEXT, GLuint semaphore, GLenum handleType, GLint fd); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryWin32HandleEXT, GLuint memory, GLuint64 size, GLenum handleType, void *handle); INSTANTIATE_FUNCTION_SERIALISED(void, glImportMemoryWin32NameEXT, GLuint memory, GLuint64 size, GLenum handleType, const void *name); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreWin32HandleEXT, GLuint semaphore, GLenum handleType, void *handle); INSTANTIATE_FUNCTION_SERIALISED(void, glImportSemaphoreWin32NameEXT, GLuint semaphore, GLenum handleType, const void *name); INSTANTIATE_FUNCTION_SERIALISED(GLboolean, glAcquireKeyedMutexWin32EXT, GLuint memory, GLuint64 key, GLuint timeout); INSTANTIATE_FUNCTION_SERIALISED(GLboolean, glReleaseKeyedMutexWin32EXT, GLuint memory, GLuint64 key); ",16165,True,3577.879524433292,median "// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // FRAMES.CPP #include ""common.h"" #include ""log.h"" #include ""frames.h"" #include ""threads.h"" #include ""object.h"" #include ""method.hpp"" #include ""class.h"" #include ""excep.h"" #include ""stublink.h"" #include ""fieldmarshaler.h"" #include ""siginfo.hpp"" #include ""gcheaputilities.h"" #include ""dllimportcallback.h"" #include ""stackwalk.h"" #include ""dbginterface.h"" #include ""gms.h"" #include ""eeconfig.h"" #include ""ecall.h"" #include ""clsload.hpp"" #include ""cgensys.h"" #include ""virtualcallstub.h"" #include ""dllimport.h"" #include ""gcrefmap.h"" #include ""asmconstants.h"" #ifdef FEATURE_COMINTEROP #include ""comtoclrcall.h"" #endif // FEATURE_COMINTEROP #ifdef FEATURE_INTERPRETER #include ""interpreter.h"" #endif // FEATURE_INTERPRETER #include ""argdestination.h"" #define CHECK_APP_DOMAIN 0 //----------------------------------------------------------------------- #if _DEBUG //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE unsigned dbgStubCtr = 0; unsigned dbgStubTrip = 0xFFFFFFFF; void Frame::Log() { WRAPPER_NO_CONTRACT; if (!LoggingOn(LF_STUBS, LL_INFO1000000)) return; dbgStubCtr++; if (dbgStubCtr > dbgStubTrip) { dbgStubCtr++; // basicly a nop to put a breakpoint on. } MethodDesc* method = GetFunction(); #ifdef TARGET_X86 if (GetVTablePtr() == UMThkCallFrame::GetMethodFrameVPtr()) method = ((UMThkCallFrame*) this)->GetUMEntryThunk()->GetMethod(); #endif STRESS_LOG3(LF_STUBS, LL_INFO1000000, ""STUBS: In Stub with Frame %p assoc Method %pM FrameType = %pV\\n"", this, method, *((void**) this)); char buff[64]; const char* frameType; if (GetVTablePtr() == PrestubMethodFrame::GetMethodFrameVPtr()) frameType = ""PreStub""; #ifdef TARGET_X86 else if (GetVTablePtr() == UMThkCallFrame::GetMethodFrameVPtr()) frameType = ""UMThkCallFrame""; #endif else if (GetVTablePtr() == PInvokeCalliFrame::GetMethodFrameVPtr()) { sprintf_s(buff, COUNTOF(buff), ""PInvoke CALLI target"" FMT_ADDR, DBG_ADDR(((PInvokeCalliFrame*)this)->GetPInvokeCalliTarget())); frameType = buff; } else if (GetVTablePtr() == StubDispatchFrame::GetMethodFrameVPtr()) frameType = ""StubDispatch""; else if (GetVTablePtr() == ExternalMethodFrame::GetMethodFrameVPtr()) frameType = ""ExternalMethod""; else frameType = ""Unknown""; if (method != 0) LOG((LF_STUBS, LL_INFO1000000, ""IN %s Stub Method = %s::%s SIG %s ESP of return"" FMT_ADDR ""\\n"", frameType, method->m_pszDebugClassName, method->m_pszDebugMethodName, method->m_pszDebugMethodSignature, DBG_ADDR(GetReturnAddressPtr()))); else LOG((LF_STUBS, LL_INFO1000000, ""IN %s Stub Method UNKNOWN ESP of return"" FMT_ADDR ""\\n"", frameType, DBG_ADDR(GetReturnAddressPtr()) )); _ASSERTE(GetThread()->PreemptiveGCDisabled()); } //----------------------------------------------------------------------- // This function is used to log transitions in either direction // between unmanaged code and CLR/managed code. // This is typically done in a stub that sets up a Frame, which is // passed as an argument to this function. void __stdcall Frame::LogTransition(Frame* frame) { CONTRACTL { DEBUG_ONLY; NOTHROW; ENTRY_POINT; GC_NOTRIGGER; } CONTRACTL_END; BEGIN_ENTRYPOINT_VOIDRET; #ifdef TARGET_X86 // On x86, StubLinkerCPU::EmitMethodStubProlog calls Frame::LogTransition // but the caller of EmitMethodStubProlog sets the GSCookie later on. // So the cookie is not initialized by the point we get here. #else _ASSERTE(*frame->GetGSCookiePtr() == GetProcessGSCookie()); #endif if (Frame::ShouldLogTransitions()) frame->Log(); END_ENTRYPOINT_VOIDRET; } // void Frame::Log() #endif // #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- #endif // _DEBUG //----------------------------------------------------------------------- // TODO [DAVBR]: For the full fix for VsWhidbey 450273, all the below // may be uncommented once isLegalManagedCodeCaller works properly // with non-return address inputs, and with non-DEBUG builds #if 0 //----------------------------------------------------------------------- // returns TRUE if retAddr, is a return address that can call managed code bool isLegalManagedCodeCaller(PCODE retAddr) { WRAPPER_NO_CONTRACT; #ifdef TARGET_X86 // we expect to be called from JITTED code or from special code sites inside // mscorwks like callDescr which we have put a NOP (0x90) so we know that they // are specially blessed. if (!ExecutionManager::IsManagedCode(retAddr) && ( #ifdef DACCESS_COMPILE !(PTR_BYTE(retAddr).IsValid()) || #endif ((*PTR_BYTE(retAddr) != 0x90) && (*PTR_BYTE(retAddr) != 0xcc)))) { LOG((LF_GC, LL_INFO10, ""Bad caller to managed code: retAddr=0x%08x, *retAddr=0x%x\\n"", retAddr, *(BYTE*)PTR_BYTE(retAddr))); return false; } // it better be a return address of some kind TADDR dummy; if (isRetAddr(retAddr, &dummy)) return true; #ifndef DACCESS_COMPILE #ifdef DEBUGGING_SUPPORTED // The debugger could have dropped an INT3 on the instruction that made the call // Calls can be 2 to 7 bytes long if (CORDebuggerAttached()) { PTR_BYTE ptr = PTR_BYTE(retAddr); for (int i = -2; i >= -7; --i) if (ptr[i] == 0xCC) return true; return false; } #endif // DEBUGGING_SUPPORTED #endif // #ifndef DACCESS_COMPILE _ASSERTE(!""Bad return address on stack""); return false; #else // TARGET_X86 return true; #endif // TARGET_X86 } #endif //0 //----------------------------------------------------------------------- // Count of the number of frame types const size_t FRAME_TYPES_COUNT = #define FRAME_TYPE_NAME(frameType) +1 #include ""frames.h"" ; #if defined (_DEBUG_IMPL) // _DEBUG and !DAC //----------------------------------------------------------------------- // Implementation of the global table of names. On the DAC side, just the global pointer. // On the runtime side, the array of names. #define FRAME_TYPE_NAME(x) {x::GetMethodFrameVPtr(), #x} , static FrameTypeName FrameTypeNameTable[] = { #include ""frames.h"" }; /* static */ PTR_CSTR Frame::GetFrameTypeName(TADDR vtbl) { LIMITED_METHOD_CONTRACT; for (size_t i=0; iLogFrame(LF, LL); pFrame = pFrame->m_Next; } } // void Frame::LogFrameChain() //----------------------------------------------------------------------- #endif // _DEBUG_IMPL //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE // This hashtable contains the vtable value of every Frame type. static PtrHashMap* s_pFrameVTables = NULL; // static void Frame::Init() { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // create a table big enough for all the frame types, not in asynchronous mode, and with no lock owner s_pFrameVTables = ::new PtrHashMap; s_pFrameVTables->Init(2 * FRAME_TYPES_COUNT, FALSE, &g_lockTrustMeIAmThreadSafe); #define FRAME_TYPE_NAME(frameType) \\ s_pFrameVTables->InsertValue(frameType::GetMethodFrameVPtr(), \\ (LPVOID) frameType::GetMethodFrameVPtr()); #include ""frames.h"" } // void Frame::Init() #endif // DACCESS_COMPILE // Returns true if the Frame's VTablePtr is valid // static bool Frame::HasValidVTablePtr(Frame * pFrame) { WRAPPER_NO_CONTRACT; if (pFrame == NULL || pFrame == FRAME_TOP) return false; #ifndef DACCESS_COMPILE TADDR vptr = pFrame->GetVTablePtr(); // // Helper MethodFrame,GCFrame,DebuggerSecurityCodeMarkFrame are the most // common frame types, explicitly check for them. // if (vptr == HelperMethodFrame::GetMethodFrameVPtr()) return true; if (vptr == DebuggerSecurityCodeMarkFrame::GetMethodFrameVPtr()) return true; // // otherwise consult the hashtable // if (s_pFrameVTables->LookupValue(vptr, (LPVOID) vptr) == (LPVOID) INVALIDENTRY) return false; #endif return true; } // Returns the location of the expected GSCookie, // Return NULL if the frame's vtable pointer is corrupt // // Note that Frame::GetGSCookiePtr is a virtual method, // and so it cannot be used without first checking if // the vtable is valid. // static PTR_GSCookie Frame::SafeGetGSCookiePtr(Frame * pFrame) { WRAPPER_NO_CONTRACT; _ASSERTE(pFrame != FRAME_TOP); if (Frame::HasValidVTablePtr(pFrame)) return pFrame->GetGSCookiePtr(); else return NULL; } //----------------------------------------------------------------------- #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- // Link and Unlink this frame. //----------------------------------------------------------------------- VOID Frame::Push() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; Push(GetThread()); } VOID Frame::Push(Thread *pThread) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(*GetGSCookiePtr() == GetProcessGSCookie()); m_Next = pThread->GetFrame(); // GetOsPageSize() is used to relax the assert for cases where two Frames are // declared in the same source function. We cannot predict the order // in which the C compiler will lay them out in the stack frame. // So GetOsPageSize() is a guess of the maximum stack frame size of any method // with multiple Frames in mscorwks.dll _ASSERTE((pThread->IsExecutingOnAltStack() || (m_Next == FRAME_TOP) || (PBYTE(m_Next) + (2 * GetOsPageSize())) > PBYTE(this)) && ""Pushing a frame out of order ?""); _ASSERTE(// If AssertOnFailFast is set, the test expects to do stack overrun // corruptions. In that case, the Frame chain may be corrupted, // and the rest of the assert is not valid. // Note that the corrupted Frame chain will be detected // during stack-walking. !g_pConfig->fAssertOnFailFast() || (m_Next == FRAME_TOP) || (*m_Next->GetGSCookiePtr() == GetProcessGSCookie())); pThread->SetFrame(this); } VOID Frame::Pop() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; Pop(GetThread()); } VOID Frame::Pop(Thread *pThread) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(pThread->GetFrame() == this && ""Popping a frame out of order ?""); _ASSERTE(*GetGSCookiePtr() == GetProcessGSCookie()); _ASSERTE(// If AssertOnFailFast is set, the test expects to do stack overrun // corruptions. In that case, the Frame chain may be corrupted, // and the rest of the assert is not valid. // Note that the corrupted Frame chain will be detected // during stack-walking. !g_pConfig->fAssertOnFailFast() || (m_Next == FRAME_TOP) || (*m_Next->GetGSCookiePtr() == GetProcessGSCookie())); pThread->SetFrame(m_Next); m_Next = NULL; } #if defined(TARGET_UNIX) && !defined(DACCESS_COMPILE) void Frame::PopIfChained() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; if (m_Next != NULL) { GCX_COOP(); // When the frame is destroyed, make sure it is no longer in the // frame chain managed by the Thread. Pop(); } } #endif // TARGET_UNIX && !DACCESS_COMPILE //----------------------------------------------------------------------- #endif // #ifndef DACCESS_COMPILE //--------------------------------------------------------------- // Get the extra param for shared generic code. //--------------------------------------------------------------- PTR_VOID TransitionFrame::GetParamTypeArg() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; SUPPORTS_DAC; } CONTRACTL_END; // This gets called while creating stack traces during exception handling. // Using the ArgIterator constructor calls ArgIterator::Init which calls GetInitialOfsAdjust // which calls SizeOfArgStack, which thinks it may load value types. // However all these will have previously been loaded. // // I'm not entirely convinced this is the best places to put this: CrawlFrame::GetExactGenericArgsToken // may be another option. ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE(); MethodDesc *pFunction = GetFunction(); _ASSERTE (pFunction->RequiresInstArg()); MetaSig msig(pFunction); ArgIterator argit (&msig); INT offs = argit.GetParamTypeArgOffset(); TADDR taParamTypeArg = *PTR_TADDR(GetTransitionBlock() + offs); return PTR_VOID(taParamTypeArg); } TADDR TransitionFrame::GetAddrOfThis() { WRAPPER_NO_CONTRACT; return GetTransitionBlock() + ArgIterator::GetThisOffset(); } VASigCookie * TransitionFrame::GetVASigCookie() { #if defined(TARGET_X86) LIMITED_METHOD_CONTRACT; return dac_cast( *dac_cast(GetTransitionBlock() + sizeof(TransitionBlock))); #else WRAPPER_NO_CONTRACT; MetaSig msig(GetFunction()); ArgIterator argit(&msig); return PTR_VASigCookie( *dac_cast(GetTransitionBlock() + argit.GetVASigCookieOffset())); #endif } #ifndef DACCESS_COMPILE PrestubMethodFrame::PrestubMethodFrame(TransitionBlock * pTransitionBlock, MethodDesc * pMD) : FramedMethodFrame(pTransitionBlock, pMD) { LIMITED_METHOD_CONTRACT; } #endif // #ifndef DACCESS_COMPILE BOOL PrestubMethodFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // // We want to set a frame patch, unless we're already at the // frame patch, in which case we'll trace the method entrypoint. // if (fromPatch) { // In between the time where the Prestub read the method entry point from the slot and the time it reached // ThePrestubPatchLabel, GetMethodEntryPoint() could have been updated due to code versioning. This will result in the // debugger getting some version of the code or the prestub, but not necessarily the exact code pointer that winds up // getting executed. The debugger has code that handles this ambiguity by placing a breakpoint at the start of all // native code versions, even if they aren't the one that was reported by this trace, see // DebuggerController::PatchTrace() under case TRACE_MANAGED. This alleviates the StubManager from having to prevent the // race that occurs here. trace->InitForStub(GetFunction()->GetMethodEntryPoint()); } else { trace->InitForStub(GetPreStubEntryPoint()); } LOG((LF_CORDB, LL_INFO10000, ""PrestubMethodFrame::TraceFrame: ip="" FMT_ADDR ""\\n"", DBG_ADDR(trace->GetAddress()) )); return TRUE; } #ifndef DACCESS_COMPILE //----------------------------------------------------------------------- // A rather specialized routine for the exclusive use of StubDispatch. //----------------------------------------------------------------------- StubDispatchFrame::StubDispatchFrame(TransitionBlock * pTransitionBlock) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pRepresentativeMT = NULL; m_representativeSlot = 0; m_pZapModule = NULL; m_pIndirection = NULL; m_pGCRefMap = NULL; } #endif // #ifndef DACCESS_COMPILE MethodDesc* StubDispatchFrame::GetFunction() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; MethodDesc * pMD = m_pMD; if (m_pMD == NULL) { if (m_pRepresentativeMT != NULL) { pMD = m_pRepresentativeMT->GetMethodDescForSlot(m_representativeSlot); #ifndef DACCESS_COMPILE m_pMD = pMD; #endif } } return pMD; } static PTR_BYTE FindGCRefMap(PTR_Module pZapModule, TADDR ptr) { LIMITED_METHOD_DAC_CONTRACT; PEImageLayout *pNativeImage = pZapModule->GetReadyToRunImage(); RVA rva = pNativeImage->GetDataRva(ptr); PTR_CORCOMPILE_IMPORT_SECTION pImportSection = pZapModule->GetImportSectionForRVA(rva); if (pImportSection == NULL) return NULL; COUNT_T index = (rva - pImportSection->Section.VirtualAddress) / pImportSection->EntrySize; PTR_BYTE pGCRefMap = dac_cast(pNativeImage->GetRvaData(pImportSection->AuxiliaryData)); _ASSERTE(pGCRefMap != NULL); // GCRefMap starts with lookup index to limit size of linear scan that follows. PTR_BYTE p = pGCRefMap + dac_cast(pGCRefMap)[index / GCREFMAP_LOOKUP_STRIDE]; COUNT_T remaining = index % GCREFMAP_LOOKUP_STRIDE; while (remaining > 0) { while ((*p & 0x80) != 0) p++; p++; remaining--; } return p; } PTR_BYTE StubDispatchFrame::GetGCRefMap() { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END; PTR_BYTE pGCRefMap = m_pGCRefMap; if (pGCRefMap == NULL) { if (m_pIndirection != NULL) { if (m_pZapModule == NULL) { m_pZapModule = ExecutionManager::FindModuleForGCRefMap(m_pIndirection); } if (m_pZapModule != NULL) { pGCRefMap = FindGCRefMap(m_pZapModule, m_pIndirection); } #ifndef DACCESS_COMPILE if (pGCRefMap != NULL) { m_pGCRefMap = pGCRefMap; } else { // Clear the indirection to avoid retrying m_pIndirection = NULL; } #endif } } return pGCRefMap; } void StubDispatchFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PTR_BYTE pGCRefMap = GetGCRefMap(); if (pGCRefMap != NULL) { PromoteCallerStackUsingGCRefMap(fn, sc, pGCRefMap); } else { PromoteCallerStack(fn, sc); } } BOOL StubDispatchFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // StubDispatchFixupWorker and VSD_ResolveWorker never directly call managed code. Returning false instructs the debugger to // step out of the call that erected this frame and continuing trying to trace execution from there. LOG((LF_CORDB, LL_INFO1000, ""StubDispatchFrame::TraceFrame: return FALSE\\n"")); return FALSE; } Frame::Interception StubDispatchFrame::GetInterception() { LIMITED_METHOD_CONTRACT; return INTERCEPTION_NONE; } #ifndef DACCESS_COMPILE CallCountingHelperFrame::CallCountingHelperFrame(TransitionBlock *pTransitionBlock, MethodDesc *pMD) : FramedMethodFrame(pTransitionBlock, pMD) { WRAPPER_NO_CONTRACT; } #endif void CallCountingHelperFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { WRAPPER_NO_CONTRACT; FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStack(fn, sc); } BOOL CallCountingHelperFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { WRAPPER_NO_CONTRACT; // OnCallCountThresholdReached never directly calls managed code. Returning false instructs the debugger to step out of the // call that erected this frame and continuing trying to trace execution from there. LOG((LF_CORDB, LL_INFO1000, ""CallCountingHelperFrame::TraceFrame: return FALSE\\n"")); return FALSE; } #ifndef DACCESS_COMPILE ExternalMethodFrame::ExternalMethodFrame(TransitionBlock * pTransitionBlock) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pIndirection = NULL; m_pZapModule = NULL; m_pGCRefMap = NULL; } #endif // !DACCESS_COMPILE void ExternalMethodFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStackUsingGCRefMap(fn, sc, GetGCRefMap()); } PTR_BYTE ExternalMethodFrame::GetGCRefMap() { LIMITED_METHOD_DAC_CONTRACT; PTR_BYTE pGCRefMap = m_pGCRefMap; if (pGCRefMap == NULL) { if (m_pIndirection != NULL) { pGCRefMap = FindGCRefMap(m_pZapModule, m_pIndirection); #ifndef DACCESS_COMPILE m_pGCRefMap = pGCRefMap; #endif } } _ASSERTE(pGCRefMap != NULL); return pGCRefMap; } Frame::Interception ExternalMethodFrame::GetInterception() { LIMITED_METHOD_CONTRACT; return INTERCEPTION_NONE; } Frame::Interception PrestubMethodFrame::GetInterception() { LIMITED_METHOD_DAC_CONTRACT; // // The only direct kind of interception done by the prestub // is class initialization. // return INTERCEPTION_PRESTUB; } #ifdef FEATURE_READYTORUN #ifndef DACCESS_COMPILE DynamicHelperFrame::DynamicHelperFrame(TransitionBlock * pTransitionBlock, int dynamicHelperFrameFlags) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_dynamicHelperFrameFlags = dynamicHelperFrameFlags; } #endif // !DACCESS_COMPILE void DynamicHelperFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END FramedMethodFrame::GcScanRoots(fn, sc); PTR_PTR_Object pArgumentRegisters = dac_cast(GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters()); if (m_dynamicHelperFrameFlags & DynamicHelperFrameFlags_ObjectArg) { TADDR pArgument = GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters(); #ifdef TARGET_X86 // x86 is special as always pArgument += offsetof(ArgumentRegisters, ECX); #endif (*fn)(dac_cast(pArgument), sc, CHECK_APP_DOMAIN); } if (m_dynamicHelperFrameFlags & DynamicHelperFrameFlags_ObjectArg2) { TADDR pArgument = GetTransitionBlock() + TransitionBlock::GetOffsetOfArgumentRegisters(); #ifdef TARGET_X86 // x86 is special as always pArgument += offsetof(ArgumentRegisters, EDX); #else pArgument += sizeof(TADDR); #endif (*fn)(dac_cast(pArgument), sc, CHECK_APP_DOMAIN); } } #endif // FEATURE_READYTORUN #ifndef DACCESS_COMPILE #ifdef FEATURE_COMINTEROP //----------------------------------------------------------------------- // A rather specialized routine for the exclusive use of the COM PreStub. //----------------------------------------------------------------------- VOID ComPrestubMethodFrame::Init() { WRAPPER_NO_CONTRACT; // Initializes the frame's VPTR. This assumes C++ puts the vptr // at offset 0 for a class not using MI, but this is no different // than the assumption that COM Classic makes. *((TADDR*)this) = GetMethodFrameVPtr(); *GetGSCookiePtr() = GetProcessGSCookie(); } #endif // FEATURE_COMINTEROP //----------------------------------------------------------------------- // GCFrames //----------------------------------------------------------------------- //-------------------------------------------------------------------- // This constructor pushes a new GCFrame on the frame chain. //-------------------------------------------------------------------- GCFrame::GCFrame(Thread *pThread, OBJECTREF *pObjRefs, UINT numObjRefs, BOOL maybeInterior) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; #ifdef USE_CHECKED_OBJECTREFS if (!maybeInterior) { UINT i; for(i = 0; i < numObjRefs; i++) Thread::ObjectRefProtected(&pObjRefs[i]); for (i = 0; i < numObjRefs; i++) { pObjRefs[i].Validate(); } } #if 0 // We'll want to restore this goodness check at some time. For now, the fact that we use // this as temporary backstops in our loader exception conversions means we're highly // exposed to infinite stack recursion should the loader be invoked during a stackwalk. // So we'll do without. if (g_pConfig->GetGCStressLevel() != 0 && IsProtectedByGCFrame(pObjRefs)) { _ASSERTE(!""This objectref is already protected by a GCFrame. Protecting it twice will corrupt the GC.""); } #endif #endif // USE_CHECKED_OBJECTREFS m_pObjRefs = pObjRefs; m_numObjRefs = numObjRefs; m_pCurThread = pThread; m_MaybeInterior = maybeInterior; // Push the GC frame to the per-thread list m_Next = pThread->GetGCFrame(); // GetOsPageSize() is used to relax the assert for cases where two Frames are // declared in the same source function. We cannot predict the order // in which the C compiler will lay them out in the stack frame. // So GetOsPageSize() is a guess of the maximum stack frame size of any method // with multiple Frames in mscorwks.dll _ASSERTE(((m_Next == NULL) || (PBYTE(m_Next) + (2 * GetOsPageSize())) > PBYTE(this)) && ""Pushing a GCFrame out of order ?""); pThread->SetGCFrame(this); } GCFrame::~GCFrame() { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; // Do a manual switch to the GC cooperative mode instead of using the GCX_COOP_THREAD_EXISTS // macro so that this function isn't slowed down by having to deal with FS:0 chain on x86 Windows. BOOL wasCoop = m_pCurThread->PreemptiveGCDisabled(); if (!wasCoop) { m_pCurThread->DisablePreemptiveGC(); } // When the frame is destroyed, make sure it is no longer in the // frame chain managed by the Thread. // It also cancels the GC protection provided by the frame. _ASSERTE(m_pCurThread->GetGCFrame() == this && ""Popping a GCFrame out of order ?""); m_pCurThread->SetGCFrame(m_Next); m_Next = NULL; #ifdef _DEBUG m_pCurThread->EnableStressHeap(); for(UINT i = 0; i < m_numObjRefs; i++) Thread::ObjectRefNew(&m_pObjRefs[i]); // Unprotect them #endif if (!wasCoop) { m_pCurThread->EnablePreemptiveGC(); } } // // GCFrame Object Scanning // // This handles scanning/promotion of GC objects that were // protected by the programmer explicitly protecting it in a GC Frame // via the GCPROTECTBEGIN / GCPROTECTEND facility... // #endif // !DACCESS_COMPILE void GCFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; PTR_PTR_Object pRefs = dac_cast(m_pObjRefs); for (UINT i = 0; i < m_numObjRefs; i++) { auto fromAddress = OBJECTREF_TO_UNCHECKED_OBJECTREF(m_pObjRefs[i]); if (m_MaybeInterior) { PromoteCarefully(fn, pRefs + i, sc, GC_CALL_INTERIOR | CHECK_APP_DOMAIN); } else { (*fn)(pRefs + i, sc, 0); } auto toAddress = OBJECTREF_TO_UNCHECKED_OBJECTREF(m_pObjRefs[i]); LOG((LF_GC, INFO3, ""GC Protection Frame promoted"" FMT_ADDR ""to"" FMT_ADDR ""\\n"", DBG_ADDR(fromAddress), DBG_ADDR(toAddress))); } } #ifndef DACCESS_COMPILE #ifdef FEATURE_INTERPRETER // Methods of IntepreterFrame. InterpreterFrame::InterpreterFrame(Interpreter* interp) : Frame(), m_interp(interp) { Push(); } MethodDesc* InterpreterFrame::GetFunction() { return m_interp->GetMethodDesc(); } void InterpreterFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { return m_interp->GCScanRoots(fn, sc); } #endif // FEATURE_INTERPRETER #if defined(_DEBUG) && !defined (DACCESS_COMPILE) struct IsProtectedByGCFrameStruct { OBJECTREF *ppObjectRef; UINT count; }; static StackWalkAction IsProtectedByGCFrameStackWalkFramesCallback( CrawlFrame *pCF, VOID *pData ) { DEBUG_ONLY_FUNCTION; WRAPPER_NO_CONTRACT; IsProtectedByGCFrameStruct *pd = (IsProtectedByGCFrameStruct*)pData; Frame *pFrame = pCF->GetFrame(); if (pFrame) { if (pFrame->Protects(pd->ppObjectRef)) { pd->count++; } } return SWA_CONTINUE; } BOOL IsProtectedByGCFrame(OBJECTREF *ppObjectRef) { DEBUG_ONLY_FUNCTION; WRAPPER_NO_CONTRACT; // Just report TRUE if GCStress is not on. This satisfies the asserts that use this // code without the cost of actually determining it. if (!GCStress::IsEnabled()) return TRUE; if (ppObjectRef == NULL) { return TRUE; } CONTRACT_VIOLATION(ThrowsViolation); ENABLE_FORBID_GC_LOADER_USE_IN_THIS_SCOPE (); IsProtectedByGCFrameStruct d = {ppObjectRef, 0}; GetThread()->StackWalkFrames(IsProtectedByGCFrameStackWalkFramesCallback, &d); GCFrame* pGCFrame = GetThread()->GetGCFrame(); while (pGCFrame != NULL) { if (pGCFrame->Protects(ppObjectRef)) { d.count++; } pGCFrame = pGCFrame->PtrNextFrame(); } if (d.count > 1) { _ASSERTE(!""Multiple GCFrames protecting the same pointer. This will cause GC corruption!""); } return d.count != 0; } #endif // _DEBUG #endif //!DACCESS_COMPILE #ifdef FEATURE_HIJACK void HijackFrame::GcScanRoots(promote_func *fn, ScanContext* sc) { LIMITED_METHOD_CONTRACT; ReturnKind returnKind = m_Thread->GetHijackReturnKind(); _ASSERTE(IsValidReturnKind(returnKind)); int regNo = 0; bool moreRegisters = false; do { ReturnKind r = ExtractRegReturnKind(returnKind, regNo, moreRegisters); PTR_PTR_Object objPtr = dac_cast(&m_Args->ReturnValue[regNo]); switch (r) { #ifdef TARGET_X86 case RT_Float: // Fall through #endif case RT_Scalar: // nothing to report break; case RT_Object: LOG((LF_GC, INFO3, ""Hijack Frame Promoting Object"" FMT_ADDR ""to"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); (*fn)(objPtr, sc, CHECK_APP_DOMAIN); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); break; case RT_ByRef: LOG((LF_GC, INFO3, ""Hijack Frame Carefully Promoting pointer"" FMT_ADDR ""to"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); PromoteCarefully(fn, objPtr, sc, GC_CALL_INTERIOR); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(OBJECTREF_TO_UNCHECKED_OBJECTREF(*objPtr)))); break; default: _ASSERTE(!""Impossible two bit encoding""); } regNo++; } while (moreRegisters); } #endif // FEATURE_HIJACK void ProtectByRefsFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END ByRefInfo *pByRefInfos = m_brInfo; while (pByRefInfos) { if (!CorIsPrimitiveType(pByRefInfos->typ)) { TADDR pData = PTR_HOST_MEMBER_TADDR(ByRefInfo, pByRefInfos, data); if (pByRefInfos->typeHandle.IsValueType()) { ReportPointersFromValueType(fn, sc, pByRefInfos->typeHandle.GetMethodTable(), PTR_VOID(pData)); } else { PTR_PTR_Object ppObject = PTR_PTR_Object(pData); LOG((LF_GC, INFO3, ""ProtectByRefs Frame Promoting"" FMT_ADDR ""to "", DBG_ADDR(*ppObject))); (*fn)(ppObject, sc, CHECK_APP_DOMAIN); LOG((LF_GC, INFO3, FMT_ADDR ""\\n"", DBG_ADDR(*ppObject) )); } } pByRefInfos = pByRefInfos->pNext; } } void ProtectValueClassFrame::GcScanRoots(promote_func *fn, ScanContext *sc) { CONTRACTL { NOTHROW; GC_NOTRIGGER; } CONTRACTL_END ValueClassInfo *pVCInfo = m_pVCInfo; while (pVCInfo != NULL) { _ASSERTE(pVCInfo->pMT->IsValueType()); ReportPointersFromValueType(fn, sc, pVCInfo->pMT, pVCInfo->pData); pVCInfo = pVCInfo->pNext; } } // // Promote Caller Stack // // void TransitionFrame::PromoteCallerStack(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; // I believe this is the contract: //CONTRACTL //{ // INSTANCE_CHECK; // NOTHROW; // GC_NOTRIGGER; // FORBID_FAULT; // MODE_ANY; //} //CONTRACTL_END MethodDesc *pFunction; LOG((LF_GC, INFO3, "" Promoting method caller Arguments\\n"" )); // We're going to have to look at the signature to determine // which arguments a are pointers....First we need the function pFunction = GetFunction(); if (pFunction == NULL) return; // Now get the signature... Signature callSignature = pFunction->GetSignature(); if (callSignature.IsEmpty()) { return; } //If not ""vararg"" calling convention, assume ""default"" calling convention if (!MetaSig::IsVarArg(callSignature)) { SigTypeContext typeContext(pFunction); PCCOR_SIGNATURE pSig; DWORD cbSigSize; pFunction->GetSig(&pSig, &cbSigSize); MetaSig msig(pSig, cbSigSize, pFunction->GetModule(), &typeContext); if (pFunction->RequiresInstArg() && !SuppressParamTypeArg()) msig.SetHasParamTypeArg(); PromoteCallerStackHelper (fn, sc, pFunction, &msig); } else { VASigCookie *varArgSig = GetVASigCookie(); //Note: no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper (fn, sc, pFunction, &msig); } } void TransitionFrame::PromoteCallerStackHelper(promote_func* fn, ScanContext* sc, MethodDesc *pFunction, MetaSig *pmsig) { WRAPPER_NO_CONTRACT; // I believe this is the contract: //CONTRACTL //{ // INSTANCE_CHECK; // NOTHROW; // GC_NOTRIGGER; // FORBID_FAULT; // MODE_ANY; //} //CONTRACTL_END ArgIterator argit(pmsig); TADDR pTransitionBlock = GetTransitionBlock(); // promote 'this' for non-static methods if (argit.HasThis() && pFunction != NULL) { BOOL interior = pFunction->GetMethodTable()->IsValueType() && !pFunction->IsUnboxingStub(); PTR_PTR_VOID pThis = dac_cast(pTransitionBlock + argit.GetThisOffset()); LOG((LF_GC, INFO3, "" 'this' Argument at "" FMT_ADDR ""promoted from"" FMT_ADDR ""\\n"", DBG_ADDR(pThis), DBG_ADDR(*pThis) )); if (interior) PromoteCarefully(fn, PTR_PTR_Object(pThis), sc, GC_CALL_INTERIOR|CHECK_APP_DOMAIN); else (fn)(PTR_PTR_Object(pThis), sc, CHECK_APP_DOMAIN); } if (argit.HasRetBuffArg()) { PTR_PTR_VOID pRetBuffArg = dac_cast(pTransitionBlock + argit.GetRetBuffArgOffset()); LOG((LF_GC, INFO3, "" ret buf Argument promoted from"" FMT_ADDR ""\\n"", DBG_ADDR(*pRetBuffArg) )); PromoteCarefully(fn, PTR_PTR_Object(pRetBuffArg), sc, GC_CALL_INTERIOR|CHECK_APP_DOMAIN); } int argOffset; while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset) { ArgDestination argDest(dac_cast(pTransitionBlock), argOffset, argit.GetArgLocDescForStructInRegs()); pmsig->GcScanRoots(&argDest, fn, sc); } } #ifdef TARGET_X86 UINT TransitionFrame::CbStackPopUsingGCRefMap(PTR_BYTE pGCRefMap) { LIMITED_METHOD_CONTRACT; GCRefMapDecoder decoder(pGCRefMap); return decoder.ReadStackPop() * sizeof(TADDR); } #endif void TransitionFrame::PromoteCallerStackUsingGCRefMap(promote_func* fn, ScanContext* sc, PTR_BYTE pGCRefMap) { WRAPPER_NO_CONTRACT; GCRefMapDecoder decoder(pGCRefMap); #ifdef TARGET_X86 // Skip StackPop decoder.ReadStackPop(); #endif TADDR pTransitionBlock = GetTransitionBlock(); while (!decoder.AtEnd()) { int pos = decoder.CurrentPos(); int token = decoder.ReadToken(); int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * sizeof(TADDR); #endif PTR_TADDR ppObj = dac_cast(pTransitionBlock + ofs); switch (token) { case GCREFMAP_SKIP: break; case GCREFMAP_REF: fn(dac_cast(ppObj), sc, CHECK_APP_DOMAIN); break; case GCREFMAP_INTERIOR: PromoteCarefully(fn, dac_cast(ppObj), sc, GC_CALL_INTERIOR); break; case GCREFMAP_METHOD_PARAM: if (sc->promotion) { #ifndef DACCESS_COMPILE MethodDesc *pMDReal = dac_cast(*ppObj); if (pMDReal != NULL) GcReportLoaderAllocator(fn, sc, pMDReal->GetLoaderAllocator()); #endif } break; case GCREFMAP_TYPE_PARAM: if (sc->promotion) { #ifndef DACCESS_COMPILE MethodTable *pMTReal = dac_cast(*ppObj); if (pMTReal != NULL) GcReportLoaderAllocator(fn, sc, pMTReal->GetLoaderAllocator()); #endif } break; case GCREFMAP_VASIG_COOKIE: { VASigCookie *varArgSig = dac_cast(*ppObj); //Note: no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper (fn, sc, NULL, &msig); } break; default: _ASSERTE(!""Unknown GCREFMAP token""); break; } } } void PInvokeCalliFrame::PromoteCallerStack(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; LOG((LF_GC, INFO3, "" Promoting CALLI caller Arguments\\n"" )); // get the signature VASigCookie *varArgSig = GetVASigCookie(); if (varArgSig->signature.IsEmpty()) { return; } // no instantiations needed for varargs MetaSig msig(varArgSig->signature, varArgSig->pModule, NULL); PromoteCallerStackHelper(fn, sc, NULL, &msig); } #ifndef DACCESS_COMPILE PInvokeCalliFrame::PInvokeCalliFrame(TransitionBlock * pTransitionBlock, VASigCookie * pVASigCookie, PCODE pUnmanagedTarget) : FramedMethodFrame(pTransitionBlock, NULL) { LIMITED_METHOD_CONTRACT; m_pVASigCookie = pVASigCookie; m_pUnmanagedTarget = pUnmanagedTarget; } #endif // #ifndef DACCESS_COMPILE #ifdef FEATURE_COMINTEROP #ifndef DACCESS_COMPILE ComPlusMethodFrame::ComPlusMethodFrame(TransitionBlock * pTransitionBlock, MethodDesc * pMD) : FramedMethodFrame(pTransitionBlock, pMD) { LIMITED_METHOD_CONTRACT; } #endif // #ifndef DACCESS_COMPILE //virtual void ComPlusMethodFrame::GcScanRoots(promote_func* fn, ScanContext* sc) { WRAPPER_NO_CONTRACT; // ComPlusMethodFrame is only used in the event call / late bound call code path where we do not have IL stub // so we need to promote the arguments and return value manually. FramedMethodFrame::GcScanRoots(fn, sc); PromoteCallerStack(fn, sc); // Promote the returned object MethodDesc* methodDesc = GetFunction(); ReturnKind returnKind = methodDesc->GetReturnKind(); if (returnKind == RT_Object) { (*fn)(GetReturnObjectPtr(), sc, CHECK_APP_DOMAIN); } else if (returnKind == RT_ByRef) { PromoteCarefully(fn, GetReturnObjectPtr(), sc, GC_CALL_INTERIOR | CHECK_APP_DOMAIN); } else { _ASSERTE_MSG(!IsStructReturnKind(returnKind), ""NYI: We can't promote multiregs struct returns""); _ASSERTE_MSG(IsScalarReturnKind(returnKind), ""Non-scalar types must be promoted.""); } } #endif // FEATURE_COMINTEROP #if defined (_DEBUG) && !defined (DACCESS_COMPILE) // For IsProtectedByGCFrame, we need to know whether a given object ref is protected // by a ComPlusMethodFrame or a ComMethodFrame. Since GCScanRoots for those frames are // quite complicated, we don't want to duplicate their logic so we call GCScanRoots with // IsObjRefProtected (a fake promote function) and an extended ScanContext to do the checking. struct IsObjRefProtectedScanContext : public ScanContext { OBJECTREF * oref_to_check; BOOL oref_protected; IsObjRefProtectedScanContext (OBJECTREF * oref) { thread_under_crawl = GetThread(); promotion = TRUE; oref_to_check = oref; oref_protected = FALSE; } }; void IsObjRefProtected (Object** ppObj, ScanContext* sc, uint32_t) { LIMITED_METHOD_CONTRACT; IsObjRefProtectedScanContext * orefProtectedSc = (IsObjRefProtectedScanContext *)sc; if (ppObj == (Object **)(orefProtectedSc->oref_to_check)) orefProtectedSc->oref_protected = TRUE; } BOOL TransitionFrame::Protects(OBJECTREF * ppORef) { WRAPPER_NO_CONTRACT; IsObjRefProtectedScanContext sc (ppORef); // Set the stack limit for the scan to the SP of the managed frame above the transition frame sc.stack_limit = GetSP(); GcScanRoots (IsObjRefProtected, &sc); return sc.oref_protected; } #endif //defined (_DEBUG) && !defined (DACCESS_COMPILE) //+---------------------------------------------------------------------------- // // Method: TPMethodFrame::GcScanRoots public // // Synopsis: GC protects arguments on the stack // // //+---------------------------------------------------------------------------- #ifdef FEATURE_COMINTEROP #ifdef TARGET_X86 // Return the # of stack bytes pushed by the unmanaged caller. UINT ComMethodFrame::GetNumCallerStackBytes() { WRAPPER_NO_CONTRACT; SUPPORTS_DAC; ComCallMethodDesc* pCMD = PTR_ComCallMethodDesc((TADDR)GetDatum()); PREFIX_ASSUME(pCMD != NULL); // assumes __stdcall // compute the callee pop stack bytes return pCMD->GetNumStackBytes(); } #endif // TARGET_X86 #ifndef DACCESS_COMPILE void ComMethodFrame::DoSecondPassHandlerCleanup(Frame * pCurFrame) { LIMITED_METHOD_CONTRACT; // Find ComMethodFrame while ((pCurFrame != FRAME_TOP) && (pCurFrame->GetVTablePtr() != ComMethodFrame::GetMethodFrameVPtr())) { pCurFrame = pCurFrame->PtrNextFrame(); } if (pCurFrame == FRAME_TOP) return; ComMethodFrame * pComMethodFrame = (ComMethodFrame *)pCurFrame; _ASSERTE(pComMethodFrame != NULL); Thread * pThread = GetThread(); GCX_COOP_THREAD_EXISTS(pThread); // Unwind the frames till the entry frame (which was ComMethodFrame) pCurFrame = pThread->GetFrame(); while ((pCurFrame != NULL) && (pCurFrame <= pComMethodFrame)) { pCurFrame->ExceptionUnwind(); pCurFrame = pCurFrame->PtrNextFrame(); } // At this point, pCurFrame would be the ComMethodFrame's predecessor frame // that we need to reset to. _ASSERTE((pCurFrame != NULL) && (pComMethodFrame->PtrNextFrame() == pCurFrame)); pThread->SetFrame(pCurFrame); } #endif // !DACCESS_COMPILE #endif // FEATURE_COMINTEROP #ifdef TARGET_X86 PTR_UMEntryThunk UMThkCallFrame::GetUMEntryThunk() { LIMITED_METHOD_DAC_CONTRACT; return dac_cast(GetDatum()); } #ifdef DACCESS_COMPILE void UMThkCallFrame::EnumMemoryRegions(CLRDataEnumMemoryFlags flags) { WRAPPER_NO_CONTRACT; UnmanagedToManagedFrame::EnumMemoryRegions(flags); // Pieces of the UMEntryThunk need to be saved. UMEntryThunk *pThunk = GetUMEntryThunk(); DacEnumMemoryRegion(dac_cast(pThunk), sizeof(UMEntryThunk)); UMThunkMarshInfo *pMarshInfo = pThunk->GetUMThunkMarshInfo(); DacEnumMemoryRegion(dac_cast(pMarshInfo), sizeof(UMThunkMarshInfo)); } #endif #endif // TARGET_X86 #ifndef DACCESS_COMPILE #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize(""y"", on) // Small critical routines, don't put in EBP frame #endif // Initialization of HelperMethodFrame. void HelperMethodFrame::Push() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; // // Finish initialization // // Compiler would not inline GetGSCookiePtr() because of it is virtual method. // Inline it manually and verify that it gives same result. _ASSERTE(GetGSCookiePtr() == (((GSCookie *)(this)) - 1)); *(((GSCookie *)(this)) - 1) = GetProcessGSCookie(); _ASSERTE(!m_MachState.isValid()); Thread * pThread = ::GetThread(); m_pThread = pThread; // Push the frame Frame::Push(pThread); if (!pThread->HasThreadStateOpportunistic(Thread::TS_AbortRequested)) return; // Outline the slow path for better perf PushSlowHelper(); } void HelperMethodFrame::Pop() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; Thread * pThread = m_pThread; if ((m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) || !pThread->HasThreadStateOpportunistic(Thread::TS_AbortInitiated)) { Frame::Pop(pThread); return; } // Outline the slow path for better perf PopSlowHelper(); } #if defined(_MSC_VER) && defined(TARGET_X86) #pragma optimize("""", on) // Go back to command line default optimizations #endif NOINLINE void HelperMethodFrame::PushSlowHelper() { CONTRACTL { if (m_Attribs & FRAME_ATTR_NO_THREAD_ABORT) NOTHROW; else THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; if (!(m_Attribs & FRAME_ATTR_NO_THREAD_ABORT)) { if (m_pThread->IsAbortRequested()) { m_pThread->HandleThreadAbort(); } } } NOINLINE void HelperMethodFrame::PopSlowHelper() { CONTRACTL { THROWS; GC_TRIGGERS; MODE_COOPERATIVE; } CONTRACTL_END; m_pThread->HandleThreadAbort(); Frame::Pop(m_pThread); } #endif // #ifndef DACCESS_COMPILE MethodDesc* HelperMethodFrame::GetFunction() { WRAPPER_NO_CONTRACT; #ifndef DACCESS_COMPILE InsureInit(false, NULL); return m_pMD; #else if (m_MachState.isValid()) { return m_pMD; } else { return ECall::MapTargetBackToMethod(m_FCallEntry); } #endif } //--------------------------------------------------------------------------------------- // // Ensures the HelperMethodFrame gets initialized, if not already. // // Arguments: // * initialInit - // * true: ensure the simple, first stage of initialization has been completed. // This is used when the HelperMethodFrame is first created. // * false: complete any initialization that was left to do, if any. // * unwindState - [out] DAC builds use this to return the unwound machine state. // * hostCallPreference - (See code:HelperMethodFrame::HostCallPreference.) // // Return Value: // Normally, the function always returns TRUE meaning the initialization succeeded. // // However, if hostCallPreference is NoHostCalls, AND if a callee (like // LazyMachState::unwindLazyState) needed to acquire a JIT reader lock and was unable // to do so (lest it re-enter the host), then InsureInit will abort and return FALSE. // So any callers that specify hostCallPreference = NoHostCalls (which is not the // default), should check for FALSE return, and refuse to use the HMF in that case. // Currently only asynchronous calls made by profilers use that code path. // BOOL HelperMethodFrame::InsureInit(bool initialInit, MachState * unwindState, HostCallPreference hostCallPreference /* = AllowHostCalls */) { CONTRACTL { NOTHROW; GC_NOTRIGGER; if ((hostCallPreference == AllowHostCalls) && !m_MachState.isValid()) { HOST_CALLS; } else { HOST_NOCALLS; } SUPPORTS_DAC; } CONTRACTL_END; if (m_MachState.isValid()) { return TRUE; } _ASSERTE(m_Attribs != 0xCCCCCCCC); #ifndef DACCESS_COMPILE if (!initialInit) { m_pMD = ECall::MapTargetBackToMethod(m_FCallEntry); // if this is an FCall, we should find it _ASSERTE(m_FCallEntry == 0 || m_pMD != 0); } #endif // Because TRUE FCalls can be called from via reflection, com-interop, etc., // we can't rely on the fact that we are called from jitted code to find the // caller of the FCALL. Thus FCalls must erect the frame directly in the // FCall. For JIT helpers, however, we can rely on this, and so they can // be sneakier and defer the HelperMethodFrame setup to a called worker method. // Work with a copy so that we only write the values once. // this avoids race conditions. LazyMachState* lazy = &m_MachState; DWORD threadId = m_pThread->GetOSThreadId(); MachState unwound; if (!initialInit && m_FCallEntry == 0 && !(m_Attribs & Frame::FRAME_ATTR_EXACT_DEPTH)) // Jit Helper { LazyMachState::unwindLazyState( lazy, &unwound, threadId, 0, hostCallPreference); #if !defined(DACCESS_COMPILE) if (!unwound.isValid()) { // This only happens if LazyMachState::unwindLazyState had to abort as a // result of failing to take a reader lock (because we told it not to yield, // but the writer lock was already held). Since we've not yet updated // m_MachState, this HelperMethodFrame will still be considered not fully // initialized (so a future call into InsureInit() will attempt to complete // initialization again). // // Note that, in DAC builds, the contract with LazyMachState::unwindLazyState // is a bit different, and it's expected that LazyMachState::unwindLazyState // will commonly return an unwound state with _pRetAddr==NULL (which counts // as an ""invalid"" MachState). So have DAC builds deliberately fall through // rather than aborting when unwound is invalid. _ASSERTE(hostCallPreference == NoHostCalls); return FALSE; } #endif // !defined(DACCESS_COMPILE) } else if (!initialInit && (m_Attribs & Frame::FRAME_ATTR_CAPTURE_DEPTH_2) != 0) { // explictly told depth LazyMachState::unwindLazyState(lazy, &unwound, threadId, 2); } else { // True FCall LazyMachState::unwindLazyState(lazy, &unwound, threadId, 1); } _ASSERTE(unwound.isValid()); #if !defined(DACCESS_COMPILE) lazy->setLazyStateFromUnwind(&unwound); #else // DACCESS_COMPILE if (unwindState) { *unwindState = unwound; } #endif // DACCESS_COMPILE return TRUE; } #include ""comdelegate.h"" BOOL MulticastFrame::TraceFrame(Thread *thread, BOOL fromPatch, TraceDestination *trace, REGDISPLAY *regs) { CONTRACTL { THROWS; GC_NOTRIGGER; MODE_COOPERATIVE; } CONTRACTL_END; _ASSERTE(!fromPatch); #ifdef DACCESS_COMPILE return FALSE; #else // !DACCESS_COMPILE LOG((LF_CORDB,LL_INFO10000, ""MulticastFrame::TF FromPatch:0x%x, at 0x%x\\n"", fromPatch, GetControlPC(regs))); // At this point we have no way to recover the Stub object from the control pc. We can't use the MD stored // in the MulticastFrame because it points to the dummy Invoke() method, not the method we want to call. BYTE *pbDel = NULL; int delegateCount = 0; #if defined(TARGET_X86) // At this point the counter hasn't been incremented yet. delegateCount = *regs->GetEdiLocation() + 1; pbDel = *(BYTE **)( (size_t)*regs->GetEsiLocation() + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #elif defined(TARGET_AMD64) // At this point the counter hasn't been incremented yet. delegateCount = (int)regs->pCurrentContext->Rdi + 1; pbDel = *(BYTE **)( (size_t)(regs->pCurrentContext->Rsi) + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #elif defined(TARGET_ARM) // At this point the counter has not yet been incremented. Counter is in R7, frame pointer in R4. delegateCount = regs->pCurrentContext->R7 + 1; pbDel = *(BYTE **)( (size_t)(regs->pCurrentContext->R4) + GetOffsetOfTransitionBlock() + ArgIterator::GetThisOffset()); #else delegateCount = 0; PORTABILITY_ASSERT(""MulticastFrame::TraceFrame (frames.cpp)""); #endif int totalDelegateCount = (int)*(size_t*)(pbDel + DelegateObject::GetOffsetOfInvocationCount()); _ASSERTE( COMDelegate::IsTrueMulticastDelegate( ObjectToOBJECTREF((Object*)pbDel) ) ); if (delegateCount == totalDelegateCount) { LOG((LF_CORDB, LL_INFO1000, ""MF::TF: Executed all stubs, should return\\n"")); // We've executed all the stubs, so we should return return FALSE; } else { // We're going to execute stub delegateCount next, so go and grab it. BYTE *pbDelInvocationList = *(BYTE **)(pbDel + DelegateObject::GetOffsetOfInvocationList()); pbDel = *(BYTE**)( ((ArrayBase *)pbDelInvocationList)->GetDataPtr() + ((ArrayBase *)pbDelInvocationList)->GetComponentSize()*delegateCount); _ASSERTE(pbDel); return DelegateInvokeStubManager::TraceDelegateObject(pbDel, trace); } #endif // !DACCESS_COMPILE } #ifndef DACCESS_COMPILE VOID InlinedCallFrame::Init() { WRAPPER_NO_CONTRACT; *((TADDR *)this) = GetMethodFrameVPtr(); // GetGSCookiePtr contains a virtual call and this is a perf critical method so we don't want to call it in ret builds GSCookie *ptrGS = (GSCookie *)((BYTE *)this - sizeof(GSCookie)); _ASSERTE(ptrGS == GetGSCookiePtr()); *ptrGS = GetProcessGSCookie(); m_Datum = NULL; m_pCallSiteSP = NULL; m_pCallerReturnAddress = NULL; } void UnmanagedToManagedFrame::ExceptionUnwind() { WRAPPER_NO_CONTRACT; AppDomain::ExceptionUnwind(this); } #endif // !DACCESS_COMPILE PCODE UnmanagedToManagedFrame::GetReturnAddress() { WRAPPER_NO_CONTRACT; PCODE pRetAddr = Frame::GetReturnAddress(); if (InlinedCallFrame::FrameHasActiveCall(m_Next) && pRetAddr == m_Next->GetReturnAddress()) { // there's actually no unmanaged code involved - we were called directly // from managed code using an InlinedCallFrame return NULL; } else { return pRetAddr; } } #ifndef DACCESS_COMPILE //================================================================================= void FakePromote(PTR_PTR_Object ppObj, ScanContext *pSC, uint32_t dwFlags) { CONTRACTL { NOTHROW; GC_NOTRIGGER; MODE_ANY; } CONTRACTL_END; CORCOMPILE_GCREFMAP_TOKENS newToken = (dwFlags & GC_CALL_INTERIOR) ? GCREFMAP_INTERIOR : GCREFMAP_REF; _ASSERTE((*(CORCOMPILE_GCREFMAP_TOKENS *)ppObj == NULL) || (*(CORCOMPILE_GCREFMAP_TOKENS *)ppObj == newToken)); *(CORCOMPILE_GCREFMAP_TOKENS *)ppObj = newToken; } //================================================================================= void FakePromoteCarefully(promote_func *fn, Object **ppObj, ScanContext *pSC, uint32_t dwFlags) { (*fn)(ppObj, pSC, dwFlags); } //================================================================================= void FakeGcScanRoots(MetaSig& msig, ArgIterator& argit, MethodDesc * pMD, BYTE * pFrame) { STANDARD_VM_CONTRACT; ScanContext sc; // Encode generic instantiation arg if (argit.HasParamType()) { // Note that intrinsic array methods have hidden instantiation arg too, but it is not reported to GC if (pMD->RequiresInstMethodDescArg()) *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_METHOD_PARAM; else if (pMD->RequiresInstMethodTableArg()) *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetParamTypeArgOffset()) = GCREFMAP_TYPE_PARAM; } // If the function has a this pointer, add it to the mask if (argit.HasThis()) { BOOL interior = pMD->GetMethodTable()->IsValueType() && !pMD->IsUnboxingStub(); FakePromote((Object **)(pFrame + argit.GetThisOffset()), &sc, interior ? GC_CALL_INTERIOR : 0); } if (argit.IsVarArg()) { *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + argit.GetVASigCookieOffset()) = GCREFMAP_VASIG_COOKIE; // We are done for varargs - the remaining arguments are reported via vasig cookie return; } // Also if the method has a return buffer, then it is the first argument, and could be an interior ref, // so always promote it. if (argit.HasRetBuffArg()) { FakePromote((Object **)(pFrame + argit.GetRetBuffArgOffset()), &sc, GC_CALL_INTERIOR); } // // Now iterate the arguments // // Cycle through the arguments, and call msig.GcScanRoots for each int argOffset; while ((argOffset = argit.GetNextOffset()) != TransitionBlock::InvalidOffset) { ArgDestination argDest(pFrame, argOffset, argit.GetArgLocDescForStructInRegs()); msig.GcScanRoots(&argDest, &FakePromote, &sc, &FakePromoteCarefully); } } bool CheckGCRefMapEqual(PTR_BYTE pGCRefMap, MethodDesc* pMD, bool isDispatchCell) { #ifdef _DEBUG GCRefMapBuilder gcRefMapNew; ComputeCallRefMap(pMD, &gcRefMapNew, isDispatchCell); DWORD dwFinalLength; PVOID pBlob = gcRefMapNew.GetBlob(&dwFinalLength); UINT nTokensDecoded = 0; GCRefMapDecoder decoderNew((BYTE *)pBlob); GCRefMapDecoder decoderExisting(pGCRefMap); #ifdef TARGET_X86 _ASSERTE(decoderNew.ReadStackPop() == decoderExisting.ReadStackPop()); #endif _ASSERTE(decoderNew.AtEnd() == decoderExisting.AtEnd()); while (!decoderNew.AtEnd()) { _ASSERTE(decoderNew.CurrentPos() == decoderExisting.CurrentPos()); _ASSERTE(decoderNew.ReadToken() == decoderExisting.ReadToken()); _ASSERTE(decoderNew.AtEnd() == decoderExisting.AtEnd()); } #endif return true; } void ComputeCallRefMap(MethodDesc* pMD, GCRefMapBuilder * pBuilder, bool isDispatchCell) { #ifdef _DEBUG DWORD dwInitialLength = pBuilder->GetBlobLength(); UINT nTokensWritten = 0; #endif SigTypeContext typeContext(pMD); PCCOR_SIGNATURE pSig; DWORD cbSigSize; pMD->GetSig(&pSig, &cbSigSize); MetaSig msig(pSig, cbSigSize, pMD->GetModule(), &typeContext); // // Shared default interface methods (i.e. virtual interface methods with an implementation) require // an instantiation argument. But if we're in a situation where we haven't resolved the method yet // we need to pretent that unresolved default interface methods are like any other interface // methods and don't have an instantiation argument. // See code:CEEInfo::getMethodSigInternal // assert(!isDispatchCell || !pMD->RequiresInstArg() || pMD->GetMethodTable()->IsInterface()); if (pMD->RequiresInstArg() && !isDispatchCell) { msig.SetHasParamTypeArg(); } ArgIterator argit(&msig); UINT nStackBytes = argit.SizeOfFrameArgumentArray(); // Allocate a fake stack CQuickBytes qbFakeStack; qbFakeStack.AllocThrows(sizeof(TransitionBlock) + nStackBytes); memset(qbFakeStack.Ptr(), 0, qbFakeStack.Size()); BYTE * pFrame = (BYTE *)qbFakeStack.Ptr(); // Fill it in FakeGcScanRoots(msig, argit, pMD, pFrame); // // Encode the ref map // UINT nStackSlots; #ifdef TARGET_X86 UINT cbStackPop = argit.CbStackPop(); pBuilder->WriteStackPop(cbStackPop / sizeof(TADDR)); nStackSlots = nStackBytes / sizeof(TADDR) + NUM_ARGUMENT_REGISTERS; #else nStackSlots = (sizeof(TransitionBlock) + nStackBytes - TransitionBlock::GetOffsetOfFirstGCRefMapSlot()) / TARGET_POINTER_SIZE; #endif for (UINT pos = 0; pos < nStackSlots; pos++) { int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * TARGET_POINTER_SIZE; #endif CORCOMPILE_GCREFMAP_TOKENS token = *(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs); if (token != 0) { INDEBUG(nTokensWritten++;) pBuilder->WriteToken(pos, token); } } // We are done pBuilder->Flush(); #ifdef _DEBUG // // Verify that decoder produces what got encoded // DWORD dwFinalLength; PVOID pBlob = pBuilder->GetBlob(&dwFinalLength); UINT nTokensDecoded = 0; GCRefMapDecoder decoder((BYTE *)pBlob + dwInitialLength); #ifdef TARGET_X86 _ASSERTE(decoder.ReadStackPop() * sizeof(TADDR) == cbStackPop); #endif while (!decoder.AtEnd()) { int pos = decoder.CurrentPos(); int token = decoder.ReadToken(); int ofs; #ifdef TARGET_X86 ofs = (pos < NUM_ARGUMENT_REGISTERS) ? (TransitionBlock::GetOffsetOfArgumentRegisters() + ARGUMENTREGISTERS_SIZE - (pos + 1) * sizeof(TADDR)) : (TransitionBlock::GetOffsetOfArgs() + (pos - NUM_ARGUMENT_REGISTERS) * sizeof(TADDR)); #else ofs = TransitionBlock::GetOffsetOfFirstGCRefMapSlot() + pos * TARGET_POINTER_SIZE; #endif if (token != 0) { _ASSERTE(*(CORCOMPILE_GCREFMAP_TOKENS *)(pFrame + ofs) == token); nTokensDecoded++; } } // Verify that all tokens got decoded. _ASSERTE(nTokensWritten == nTokensDecoded); #endif // _DEBUG } #endif // !DACCESS_COMPILE ",16173,True,2892.9003520302754,median "/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include ""tensorflow/compiler/plugin/poplar/driver/compiler_annotations.h"" #include ""tensorflow/compiler/plugin/poplar/driver/passes/convolution_classifier.h"" #include ""tensorflow/compiler/plugin/poplar/driver/passes/custom_op_replacer.h"" #include ""tensorflow/compiler/plugin/poplar/driver/passes/module_flatten.h"" #include ""tensorflow/compiler/plugin/poplar/driver/passes/recompute_instructions.h"" #include ""tensorflow/compiler/plugin/poplar/driver/tools/matcher_predicates.h"" #include ""tensorflow/compiler/xla/service/hlo_parser.h"" #include ""tensorflow/compiler/xla/test.h"" #include ""tensorflow/compiler/xla/tests/hlo_test_base.h"" #include ""tensorflow/core/lib/core/status_test_util.h"" namespace xla { namespace poplarplugin { namespace { using NormInputRecomputationTest = HloTestBase; const std::string hlo_string = R""( HloModule top Sum-reduction.38 (x.39: f32[], y.40: f32[]) -> f32[] { y.40 = f32[] parameter(1) x.39 = f32[] parameter(0) ROOT add.41 = f32[] add(f32[] x.39, f32[] y.40) } _pop_op_conv_with_reverse (arg_0: f32[1,4,4,2], arg_1: f32[1,1,2,2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2]{3,2,1,0} parameter(0) arg_1 = f32[1,1,2,2]{3,2,1,0} parameter(1) reverse.64.clone = f32[1,1,2,2]{3,2,1,0} reverse(f32[1,1,2,2]{3,2,1,0} arg_1), dimensions={0,1} ROOT convolution.65.clone = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_0, f32[1,1,2,2]{3,2,1,0} reverse.64.clone), window={size=1x1}, dim_labels=b01f_01oi->b01f } _pop_op_relu (arg_0.1: f32[1,4,4,2]) -> f32[1,4,4,2] { arg_0.1 = f32[1,4,4,2]{3,2,1,0} parameter(0) constant.20.clone = f32[] constant(0) broadcast.21.clone = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.20.clone), dimensions={} ROOT maximum.34.clone = f32[1,4,4,2]{3,2,1,0} maximum(f32[1,4,4,2]{3,2,1,0} arg_0.1, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone) } _pop_op_relu.1 (arg_0.2: f32[1,4,4,2]) -> f32[1,4,4,2] { arg_0.2 = f32[1,4,4,2]{3,2,1,0} parameter(0) constant.20.clone.1 = f32[] constant(0) broadcast.21.clone.1 = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.20.clone.1), dimensions={} ROOT maximum.22.clone = f32[1,4,4,2]{3,2,1,0} maximum(f32[1,4,4,2]{3,2,1,0} arg_0.2, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone.1) } _pop_op_relugrad (arg_0.3: f32[1,4,4,2], arg_1.1: f32[1,4,4,2]) -> f32[1,4,4,2] { arg_0.3 = f32[1,4,4,2]{3,2,1,0} parameter(0) constant.20.clone.2 = f32[] constant(0) broadcast.21.clone.2 = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.20.clone.2), dimensions={} compare.72.clone = pred[1,4,4,2]{3,2,1,0} compare(f32[1,4,4,2]{3,2,1,0} arg_0.3, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone.2), direction=GT arg_1.1 = f32[1,4,4,2]{3,2,1,0} parameter(1) ROOT select.73.clone = f32[1,4,4,2]{3,2,1,0} select(pred[1,4,4,2]{3,2,1,0} compare.72.clone, f32[1,4,4,2]{3,2,1,0} arg_1.1, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone.2) } _pop_op_relugrad.1 (arg_0.4: f32[1,4,4,2], arg_1.2: f32[1,4,4,2]) -> f32[1,4,4,2] { arg_0.4 = f32[1,4,4,2]{3,2,1,0} parameter(0) constant.20.clone.3 = f32[] constant(0) broadcast.21.clone.3 = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.20.clone.3), dimensions={} compare.46.clone = pred[1,4,4,2]{3,2,1,0} compare(f32[1,4,4,2]{3,2,1,0} arg_0.4, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone.3), direction=GT arg_1.2 = f32[1,4,4,2]{3,2,1,0} parameter(1) ROOT select.47.clone = f32[1,4,4,2]{3,2,1,0} select(pred[1,4,4,2]{3,2,1,0} compare.46.clone, f32[1,4,4,2]{3,2,1,0} arg_1.2, f32[1,4,4,2]{3,2,1,0} broadcast.21.clone.3) } _pop_op_conv_scaled_inplace (arg_0.5: f32[1,1,2,2], arg_1.3: f32[1,4,4,2], arg_2: f32[1,4,4,2]) -> f32[1,1,2,2] { arg_0.5 = f32[1,1,2,2]{3,2,1,0} parameter(0) arg_1.3 = f32[1,4,4,2]{3,2,1,0} parameter(1) arg_2 = f32[1,4,4,2]{3,2,1,0} parameter(2) convolution.89.clone = f32[1,1,2,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_1.3, f32[1,4,4,2]{3,2,1,0} arg_2), window={size=4x4}, dim_labels=f01b_i01o->01bf constant.55.clone = f32[] constant(0.1) broadcast.67.clone = f32[1,1,2,2]{3,2,1,0} broadcast(f32[] constant.55.clone), dimensions={} multiply.92.clone = f32[1,1,2,2]{3,2,1,0} multiply(f32[1,1,2,2]{3,2,1,0} convolution.89.clone, f32[1,1,2,2]{3,2,1,0} broadcast.67.clone) ROOT subtract.93.clone = f32[1,1,2,2]{3,2,1,0} subtract(f32[1,1,2,2]{3,2,1,0} arg_0.5, f32[1,1,2,2]{3,2,1,0} multiply.92.clone) } _pop_op_conv_scaled_inplace.1 (arg_0.6: f32[1,1,2,2], arg_1.4: f32[1,4,4,2], arg_2.1: f32[1,4,4,2]) -> f32[1,1,2,2] { arg_0.6 = f32[1,1,2,2]{3,2,1,0} parameter(0) arg_1.4 = f32[1,4,4,2]{3,2,1,0} parameter(1) arg_2.1 = f32[1,4,4,2]{3,2,1,0} parameter(2) convolution.63.clone = f32[1,1,2,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_1.4, f32[1,4,4,2]{3,2,1,0} arg_2.1), window={size=4x4}, dim_labels=f01b_i01o->01bf constant.55.clone.1 = f32[] constant(0.1) broadcast.67.clone.1 = f32[1,1,2,2]{3,2,1,0} broadcast(f32[] constant.55.clone.1), dimensions={} multiply.68.clone = f32[1,1,2,2]{3,2,1,0} multiply(f32[1,1,2,2]{3,2,1,0} convolution.63.clone, f32[1,1,2,2]{3,2,1,0} broadcast.67.clone.1) ROOT subtract.69.clone = f32[1,1,2,2]{3,2,1,0} subtract(f32[1,1,2,2]{3,2,1,0} arg_0.6, f32[1,1,2,2]{3,2,1,0} multiply.68.clone) } _pop_op_scaled_inplace (arg_0.7: f32[2], arg_1.5: f32[2]) -> f32[2] { arg_0.7 = f32[2]{0} parameter(0) arg_1.5 = f32[2]{0} parameter(1) constant.55.clone.2 = f32[] constant(0.1) broadcast.56.clone = f32[2]{0} broadcast(f32[] constant.55.clone.2), dimensions={} multiply.87.clone = f32[2]{0} multiply(f32[2]{0} arg_1.5, f32[2]{0} broadcast.56.clone) ROOT subtract.88.clone = f32[2]{0} subtract(f32[2]{0} arg_0.7, f32[2]{0} multiply.87.clone) } _pop_op_scaled_inplace.1 (arg_0.8: f32[2], arg_1.6: f32[2]) -> f32[2] { arg_0.8 = f32[2]{0} parameter(0) arg_1.6 = f32[2]{0} parameter(1) constant.55.clone.3 = f32[] constant(0.1) broadcast.56.clone.1 = f32[2]{0} broadcast(f32[] constant.55.clone.3), dimensions={} multiply.83.clone = f32[2]{0} multiply(f32[2]{0} arg_1.6, f32[2]{0} broadcast.56.clone.1) ROOT subtract.84.clone = f32[2]{0} subtract(f32[2]{0} arg_0.8, f32[2]{0} multiply.83.clone) } _pop_op_scaled_inplace.2 (arg_0.9: f32[2], arg_1.7: f32[2]) -> f32[2] { arg_0.9 = f32[2]{0} parameter(0) arg_1.7 = f32[2]{0} parameter(1) constant.55.clone.4 = f32[] constant(0.1) broadcast.56.clone.2 = f32[2]{0} broadcast(f32[] constant.55.clone.4), dimensions={} multiply.61.clone = f32[2]{0} multiply(f32[2]{0} arg_1.7, f32[2]{0} broadcast.56.clone.2) ROOT subtract.62.clone = f32[2]{0} subtract(f32[2]{0} arg_0.9, f32[2]{0} multiply.61.clone) } _pop_op_scaled_inplace.3 (arg_0.10: f32[2], arg_1.8: f32[2]) -> f32[2] { arg_0.10 = f32[2]{0} parameter(0) arg_1.8 = f32[2]{0} parameter(1) constant.55.clone.5 = f32[] constant(0.1) broadcast.56.clone.3 = f32[2]{0} broadcast(f32[] constant.55.clone.5), dimensions={} multiply.57.clone = f32[2]{0} multiply(f32[2]{0} arg_1.8, f32[2]{0} broadcast.56.clone.3) ROOT subtract.58.clone = f32[2]{0} subtract(f32[2]{0} arg_0.10, f32[2]{0} multiply.57.clone) } _pop_op_wide_const () -> f32[1,4,4,2] { constant.9.clone = f32[] constant(1) ROOT broadcast.10.clone = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.9.clone), dimensions={} } ENTRY top (arg0.1: f32[1,4,4,2], arg1.2: f32[2], arg2.3: f32[2], arg3.4: f32[1,1,2,2], arg4.5: f32[2], arg5.6: f32[2], arg6.7: f32[1,1,2,2]) -> (f32[], f32[2], f32[2], f32[1,1,2,2], f32[2], f32[2], f32[1,1,2,2]) { arg0.1 = f32[1,4,4,2]{3,2,1,0} parameter(0), metadata={op_name=""XLA_Args""} arg6.7 = f32[1,1,2,2]{3,2,1,0} parameter(6), metadata={op_name=""XLA_Args""} convolution.11 = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg0.1, f32[1,1,2,2]{3,2,1,0} arg6.7), window={size=1x1}, dim_labels=b01f_01io->b01f arg5.6 = f32[2]{0} parameter(5), control-predecessors={convolution.11}, metadata={op_name=""XLA_Args""} arg4.5 = f32[2]{0} parameter(4), control-predecessors={convolution.11}, metadata={op_name=""XLA_Args""} batch-norm-training.13 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training(f32[1,4,4,2]{3,2,1,0} convolution.11, f32[2]{0} arg5.6, f32[2]{0} arg4.5), epsilon=0.001, feature_index=3 get-tuple-element.14 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.13), index=0 fusion.2 = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} get-tuple-element.14), kind=kCustom, calls=_pop_op_relu.1, backend_config=""{}"" arg3.4 = f32[1,1,2,2]{3,2,1,0} parameter(3), metadata={op_name=""XLA_Args""} convolution.23 = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} fusion.2, f32[1,1,2,2]{3,2,1,0} arg3.4), window={size=1x1}, dim_labels=b01f_01io->b01f arg2.3 = f32[2]{0} parameter(2), control-predecessors={convolution.23}, metadata={op_name=""XLA_Args""} arg1.2 = f32[2]{0} parameter(1), control-predecessors={convolution.23}, metadata={op_name=""XLA_Args""} batch-norm-training.25 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training(f32[1,4,4,2]{3,2,1,0} convolution.23, f32[2]{0} arg2.3, f32[2]{0} arg1.2), epsilon=0.001, feature_index=3 get-tuple-element.26 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.25), index=0 fusion.1 = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} get-tuple-element.26), kind=kCustom, calls=_pop_op_relu, backend_config=""{}"" constant.20 = f32[] constant(0) reduce.42 = f32[] reduce(f32[1,4,4,2]{3,2,1,0} fusion.1, f32[] constant.20), dimensions={0,1,2,3}, to_apply=Sum-reduction.38 get-tuple-element.28 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.25), index=1 get-tuple-element.29 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.25), index=2 fusion.11 = f32[1,4,4,2]{3,2,1,0} fusion(), kind=kCustom, calls=_pop_op_wide_const, backend_config=""{}"" fusion.4 = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} fusion.1, f32[1,4,4,2]{3,2,1,0} fusion.11), kind=kCustom, calls=_pop_op_relugrad.1, backend_config=""{}"" batch-norm-grad.50 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad(f32[1,4,4,2]{3,2,1,0} convolution.23, f32[2]{0} arg2.3, f32[2]{0} get-tuple-element.28, f32[2]{0} get-tuple-element.29, f32[1,4,4,2]{3,2,1,0} fusion.4), epsilon=0.001, feature_index=3 get-tuple-element.53 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.50), index=2 fusion.10 = f32[2]{0} fusion(f32[2]{0} arg1.2, f32[2]{0} get-tuple-element.53), kind=kCustom, calls=_pop_op_scaled_inplace.3, backend_config=""{}"" get-tuple-element.52 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.50), index=1 fusion.9 = f32[2]{0} fusion(f32[2]{0} arg2.3, f32[2]{0} get-tuple-element.52), kind=kCustom, calls=_pop_op_scaled_inplace.2, backend_config=""{}"" get-tuple-element.51 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.50), index=0 fusion = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} get-tuple-element.51, f32[1,1,2,2]{3,2,1,0} arg3.4), kind=kCustom, calls=_pop_op_conv_with_reverse, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""1\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""1\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelInputFeatureDimension\\"":\\""3\\"",\\""kernelOutputFeatureDimension\\"":\\""2\\"",\\""kernelSpatialDimensions\\"":[\\""0\\"",\\""1\\""],\\""inputFeatureDimension\\"":\\""3\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""1\\"",\\""2\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" fusion.6 = f32[1,1,2,2]{3,2,1,0} fusion(f32[1,1,2,2]{3,2,1,0} arg3.4, f32[1,4,4,2]{3,2,1,0} fusion.2, f32[1,4,4,2]{3,2,1,0} get-tuple-element.51), kind=kCustom, calls=_pop_op_conv_scaled_inplace.1, control-predecessors={fusion}, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelOutputFeatureDimension\\"":\\""3\\"",\\""kernelSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""inputBatchDimension\\"":\\""3\\"",\\""outputBatchDimension\\"":\\""2\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""0\\"",\\""1\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" get-tuple-element.16 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.13), index=1 get-tuple-element.17 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training.13), index=2 fusion.3 = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} fusion.2, f32[1,4,4,2]{3,2,1,0} fusion), kind=kCustom, calls=_pop_op_relugrad, backend_config=""{}"" batch-norm-grad.76 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad(f32[1,4,4,2]{3,2,1,0} convolution.11, f32[2]{0} arg5.6, f32[2]{0} get-tuple-element.16, f32[2]{0} get-tuple-element.17, f32[1,4,4,2]{3,2,1,0} fusion.3), epsilon=0.001, feature_index=3 get-tuple-element.79 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.76), index=2 fusion.8 = f32[2]{0} fusion(f32[2]{0} arg4.5, f32[2]{0} get-tuple-element.79), kind=kCustom, calls=_pop_op_scaled_inplace.1, backend_config=""{}"" get-tuple-element.78 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.76), index=1 fusion.7 = f32[2]{0} fusion(f32[2]{0} arg5.6, f32[2]{0} get-tuple-element.78), kind=kCustom, calls=_pop_op_scaled_inplace, backend_config=""{}"" get-tuple-element.77 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad.76), index=0 fusion.5 = f32[1,1,2,2]{3,2,1,0} fusion(f32[1,1,2,2]{3,2,1,0} arg6.7, f32[1,4,4,2]{3,2,1,0} arg0.1, f32[1,4,4,2]{3,2,1,0} get-tuple-element.77), kind=kCustom, calls=_pop_op_conv_scaled_inplace, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelOutputFeatureDimension\\"":\\""3\\"",\\""kernelSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""inputBatchDimension\\"":\\""3\\"",\\""outputBatchDimension\\"":\\""2\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""0\\"",\\""1\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" ROOT tuple.107 = (f32[], f32[2]{0}, f32[2]{0}, f32[1,1,2,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}, f32[1,1,2,2]{3,2,1,0}) tuple(f32[] reduce.42, f32[2]{0} fusion.10, f32[2]{0} fusion.9, f32[1,1,2,2]{3,2,1,0} fusion.6, f32[2]{0} fusion.8, f32[2]{0} fusion.7, f32[1,1,2,2]{3,2,1,0} fusion.5), metadata={op_name=""XLA_Retvals""} } )""; TEST_F(NormInputRecomputationTest, RecomputeInput) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); config.set_resource_update_to_input_index({1, 2, 3, 4, 5, 6}); auto module_or_status = ParseAndReturnVerifiedModule(hlo_string, config); EXPECT_TRUE(module_or_status.ok()); auto* module = module_or_status.ValueOrDie().get(); HloInstruction* input1 = FindInstruction(module, ""convolution.11""); HloInstruction* bn1 = FindInstruction(module, ""batch-norm-training.13""); HloInstruction* bn_grad1 = FindInstruction(module, ""batch-norm-grad.76""); HloInstruction* input2 = FindInstruction(module, ""convolution.23""); HloInstruction* bn2 = FindInstruction(module, ""batch-norm-training.25""); HloInstruction* bn_grad2 = FindInstruction(module, ""batch-norm-grad.50""); ASSERT_EQ(input1->users().size(), 2); ASSERT_EQ(bn1->operand(0), input1); ASSERT_EQ(bn_grad1->operand(0), input1); ASSERT_EQ(input2->users().size(), 2); ASSERT_EQ(bn2->operand(0), input2); ASSERT_EQ(bn_grad2->operand(0), input2); CompilerAnnotations annotations(module); ModuleFlatten flatten(annotations); ConvolutionClassifier classifier(annotations); EXPECT_TRUE(flatten.Run(module).ValueOrDie()); auto res = classifier.Run(module); EXPECT_TRUE(res.ok()); EXPECT_TRUE(res.ValueOrDie()); ASSERT_TRUE(RecomputeInstructions(true).Run(module).ValueOrDie()); ASSERT_EQ(bn1->operand(0), input1); ASSERT_NE(bn1->operand(0), bn_grad1->operand(0)); ASSERT_TRUE(bn1->operand(0)->Identical(*bn_grad1->operand(0))); ASSERT_EQ(bn2->operand(0), input2); ASSERT_NE(bn2->operand(0), bn_grad2->operand(0)); ASSERT_TRUE(bn2->operand(0)->Identical(*bn_grad2->operand(0))); } TEST_F(NormInputRecomputationTest, RecomputeInputOff) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); config.set_resource_update_to_input_index({1, 2, 3, 4, 5, 6}); auto module_or_status = ParseAndReturnVerifiedModule(hlo_string, config); EXPECT_TRUE(module_or_status.ok()); auto* module = module_or_status.ValueOrDie().get(); CompilerAnnotations annotations(module); ModuleFlatten flatten(annotations); ConvolutionClassifier classifier(annotations); EXPECT_TRUE(flatten.Run(module).ValueOrDie()); auto res = classifier.Run(module); EXPECT_TRUE(res.ok()); EXPECT_TRUE(res.ValueOrDie()); ASSERT_FALSE(RecomputeInstructions(false).Run(module).ValueOrDie()); } const std::string hlo_string_relu = R""( HloModule top Sum-reduction.38 (x.39: f32[], y.40: f32[]) -> f32[] { y.40 = f32[] parameter(1) x.39 = f32[] parameter(0) ROOT add.41 = f32[] add(f32[] x.39, f32[] y.40) } _pop_op_conv_with_reverse (arg_0: f32[1,4,4,2], arg_1: f32[1,1,2,2]) -> f32[1,4,4,2] { arg_0 = f32[1,4,4,2]{3,2,1,0} parameter(0) arg_1 = f32[1,1,2,2]{3,2,1,0} parameter(1) reverse.64.clone = f32[1,1,2,2]{3,2,1,0} reverse(f32[1,1,2,2]{3,2,1,0} arg_1), dimensions={0,1} ROOT convolution.65.clone = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_0, f32[1,1,2,2]{3,2,1,0} reverse.64.clone), window={size=1x1}, dim_labels=b01f_01oi->b01f } _pop_op_conv_scaled_inplace (arg_0.5: f32[1,1,2,2], arg_1.3: f32[1,4,4,2], arg_2: f32[1,4,4,2]) -> f32[1,1,2,2] { arg_0.5 = f32[1,1,2,2]{3,2,1,0} parameter(0) arg_1.3 = f32[1,4,4,2]{3,2,1,0} parameter(1) arg_2 = f32[1,4,4,2]{3,2,1,0} parameter(2) convolution.89.clone = f32[1,1,2,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_1.3, f32[1,4,4,2]{3,2,1,0} arg_2), window={size=4x4}, dim_labels=f01b_i01o->01bf constant.55.clone = f32[] constant(0.1) broadcast.67.clone = f32[1,1,2,2]{3,2,1,0} broadcast(f32[] constant.55.clone), dimensions={} multiply.92.clone = f32[1,1,2,2]{3,2,1,0} multiply(f32[1,1,2,2]{3,2,1,0} convolution.89.clone, f32[1,1,2,2]{3,2,1,0} broadcast.67.clone) ROOT subtract.93.clone = f32[1,1,2,2]{3,2,1,0} subtract(f32[1,1,2,2]{3,2,1,0} arg_0.5, f32[1,1,2,2]{3,2,1,0} multiply.92.clone) } _pop_op_conv_scaled_inplace.1 (arg_0.6: f32[1,1,2,2], arg_1.4: f32[1,4,4,2], arg_2.1: f32[1,4,4,2]) -> f32[1,1,2,2] { arg_0.6 = f32[1,1,2,2]{3,2,1,0} parameter(0) arg_1.4 = f32[1,4,4,2]{3,2,1,0} parameter(1) arg_2.1 = f32[1,4,4,2]{3,2,1,0} parameter(2) convolution.63.clone = f32[1,1,2,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} arg_1.4, f32[1,4,4,2]{3,2,1,0} arg_2.1), window={size=4x4}, dim_labels=f01b_i01o->01bf constant.55.clone.1 = f32[] constant(0.1) broadcast.67.clone.1 = f32[1,1,2,2]{3,2,1,0} broadcast(f32[] constant.55.clone.1), dimensions={} multiply.68.clone = f32[1,1,2,2]{3,2,1,0} multiply(f32[1,1,2,2]{3,2,1,0} convolution.63.clone, f32[1,1,2,2]{3,2,1,0} broadcast.67.clone.1) ROOT subtract.69.clone = f32[1,1,2,2]{3,2,1,0} subtract(f32[1,1,2,2]{3,2,1,0} arg_0.6, f32[1,1,2,2]{3,2,1,0} multiply.68.clone) } _pop_op_scaled_inplace (arg_0.7: f32[2], arg_1.5: f32[2]) -> f32[2] { arg_0.7 = f32[2]{0} parameter(0) arg_1.5 = f32[2]{0} parameter(1) constant.55.clone.2 = f32[] constant(0.1) broadcast.56.clone = f32[2]{0} broadcast(f32[] constant.55.clone.2), dimensions={} multiply.87.clone = f32[2]{0} multiply(f32[2]{0} arg_1.5, f32[2]{0} broadcast.56.clone) ROOT subtract.88.clone = f32[2]{0} subtract(f32[2]{0} arg_0.7, f32[2]{0} multiply.87.clone) } _pop_op_scaled_inplace.1 (arg_0.8: f32[2], arg_1.6: f32[2]) -> f32[2] { arg_0.8 = f32[2]{0} parameter(0) arg_1.6 = f32[2]{0} parameter(1) constant.55.clone.3 = f32[] constant(0.1) broadcast.56.clone.1 = f32[2]{0} broadcast(f32[] constant.55.clone.3), dimensions={} multiply.83.clone = f32[2]{0} multiply(f32[2]{0} arg_1.6, f32[2]{0} broadcast.56.clone.1) ROOT subtract.84.clone = f32[2]{0} subtract(f32[2]{0} arg_0.8, f32[2]{0} multiply.83.clone) } _pop_op_scaled_inplace.2 (arg_0.9: f32[2], arg_1.7: f32[2]) -> f32[2] { arg_0.9 = f32[2]{0} parameter(0) arg_1.7 = f32[2]{0} parameter(1) constant.55.clone.4 = f32[] constant(0.1) broadcast.56.clone.2 = f32[2]{0} broadcast(f32[] constant.55.clone.4), dimensions={} multiply.61.clone = f32[2]{0} multiply(f32[2]{0} arg_1.7, f32[2]{0} broadcast.56.clone.2) ROOT subtract.62.clone = f32[2]{0} subtract(f32[2]{0} arg_0.9, f32[2]{0} multiply.61.clone) } _pop_op_scaled_inplace.3 (arg_0.10: f32[2], arg_1.8: f32[2]) -> f32[2] { arg_0.10 = f32[2]{0} parameter(0) arg_1.8 = f32[2]{0} parameter(1) constant.55.clone.5 = f32[] constant(0.1) broadcast.56.clone.3 = f32[2]{0} broadcast(f32[] constant.55.clone.5), dimensions={} multiply.57.clone = f32[2]{0} multiply(f32[2]{0} arg_1.8, f32[2]{0} broadcast.56.clone.3) ROOT subtract.58.clone = f32[2]{0} subtract(f32[2]{0} arg_0.10, f32[2]{0} multiply.57.clone) } _pop_op_wide_const () -> f32[1,4,4,2] { constant.9.clone = f32[] constant(1) ROOT broadcast.10.clone = f32[1,4,4,2]{3,2,1,0} broadcast(f32[] constant.9.clone), dimensions={} } ENTRY top (arg0.1: f32[1,4,4,2], arg1.2: f32[2], arg2.3: f32[2], arg3.4: f32[1,1,2,2], arg4.5: f32[2], arg5.6: f32[2], arg6.7: f32[1,1,2,2]) -> (f32[], f32[2], f32[2], f32[1,1,2,2], f32[2], f32[2], f32[1,1,2,2]) { arg0.1 = f32[1,4,4,2]{3,2,1,0} parameter(0), metadata={op_name=""XLA_Args""} arg6.7 = f32[1,1,2,2]{3,2,1,0} parameter(6), metadata={op_name=""XLA_Args""} convolution.11 = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} %arg0.1, f32[1,1,2,2]{3,2,1,0} %arg6.7), window={size=1x1}, dim_labels=b01f_01io->b01f arg5.6 = f32[2]{0} parameter(5), control-predecessors={%convolution.11}, metadata={op_name=""XLA_Args""} arg4.5 = f32[2]{0} parameter(4), control-predecessors={%convolution.11}, metadata={op_name=""XLA_Args""} batch-norm-training.13 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training(f32[1,4,4,2]{3,2,1,0} %convolution.11, f32[2]{0} %arg5.6, f32[2]{0} %arg4.5), epsilon=0.001, feature_index=3 get-tuple-element.14 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.13), index=0 relu.1 = f32[1,4,4,2]{3,2,1,0} custom-call(f32[1,4,4,2]{3,2,1,0} %get-tuple-element.14), custom_call_target=""Relu"", backend_config=""{}"" arg3.4 = f32[1,1,2,2]{3,2,1,0} parameter(3), metadata={op_name=""XLA_Args""} convolution.23 = f32[1,4,4,2]{3,2,1,0} convolution(f32[1,4,4,2]{3,2,1,0} %relu.1, f32[1,1,2,2]{3,2,1,0} %arg3.4), window={size=1x1}, dim_labels=b01f_01io->b01f arg2.3 = f32[2]{0} parameter(2), control-predecessors={%convolution.23}, metadata={op_name=""XLA_Args""} arg1.2 = f32[2]{0} parameter(1), control-predecessors={%convolution.23}, metadata={op_name=""XLA_Args""} batch-norm-training.25 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-training(f32[1,4,4,2]{3,2,1,0} %convolution.23, f32[2]{0} %arg2.3, f32[2]{0} %arg1.2), epsilon=0.001, feature_index=3 get-tuple-element.26 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.25), index=0 relu.2 = f32[1,4,4,2]{3,2,1,0} custom-call(f32[1,4,4,2]{3,2,1,0} %get-tuple-element.26), custom_call_target=""Relu"", backend_config=""{}"" constant.20 = f32[] constant(0) reduce.42 = f32[] reduce(f32[1,4,4,2]{3,2,1,0} %relu.2, f32[] %constant.20), dimensions={0,1,2,3}, to_apply=%Sum-reduction.38 get-tuple-element.28 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.25), index=1 get-tuple-element.29 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.25), index=2 fusion.11 = f32[1,4,4,2]{3,2,1,0} fusion(), kind=kCustom, calls=%_pop_op_wide_const, backend_config=""{}"" relugrad.1 = f32[1,4,4,2]{3,2,1,0} custom-call(f32[1,4,4,2]{3,2,1,0} %relu.2, f32[1,4,4,2]{3,2,1,0} %fusion.11), custom_call_target=""ReluGrad"", backend_config=""{}"" batch-norm-grad.50 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad(f32[1,4,4,2]{3,2,1,0} %convolution.23, f32[2]{0} %arg2.3, f32[2]{0} %get-tuple-element.28, f32[2]{0} %get-tuple-element.29, f32[1,4,4,2]{3,2,1,0} %relugrad.1), epsilon=0.001, feature_index=3 get-tuple-element.53 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.50), index=2 fusion.10 = f32[2]{0} fusion(f32[2]{0} %arg1.2, f32[2]{0} %get-tuple-element.53), kind=kCustom, calls=%_pop_op_scaled_inplace.3, backend_config=""{}"" get-tuple-element.52 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.50), index=1 fusion.9 = f32[2]{0} fusion(f32[2]{0} %arg2.3, f32[2]{0} %get-tuple-element.52), kind=kCustom, calls=%_pop_op_scaled_inplace.2, backend_config=""{}"" get-tuple-element.51 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.50), index=0 fusion = f32[1,4,4,2]{3,2,1,0} fusion(f32[1,4,4,2]{3,2,1,0} %get-tuple-element.51, f32[1,1,2,2]{3,2,1,0} %arg3.4), kind=kCustom, calls=%_pop_op_conv_with_reverse, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""1\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""1\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelInputFeatureDimension\\"":\\""3\\"",\\""kernelOutputFeatureDimension\\"":\\""2\\"",\\""kernelSpatialDimensions\\"":[\\""0\\"",\\""1\\""],\\""inputFeatureDimension\\"":\\""3\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""1\\"",\\""2\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" fusion.6 = f32[1,1,2,2]{3,2,1,0} fusion(f32[1,1,2,2]{3,2,1,0} %arg3.4, f32[1,4,4,2]{3,2,1,0} %relu.1, f32[1,4,4,2]{3,2,1,0} %get-tuple-element.51), kind=kCustom, calls=%_pop_op_conv_scaled_inplace.1, control-predecessors={%fusion}, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelOutputFeatureDimension\\"":\\""3\\"",\\""kernelSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""inputBatchDimension\\"":\\""3\\"",\\""outputBatchDimension\\"":\\""2\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""0\\"",\\""1\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" get-tuple-element.16 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.13), index=1 get-tuple-element.17 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-training.13), index=2 relugrad.2 = f32[1,4,4,2]{3,2,1,0} custom-call(f32[1,4,4,2]{3,2,1,0} %relu.1, f32[1,4,4,2]{3,2,1,0} %fusion), custom_call_target=""ReluGrad"", backend_config=""{}"" batch-norm-grad.76 = (f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) batch-norm-grad(f32[1,4,4,2]{3,2,1,0} %convolution.11, f32[2]{0} %arg5.6, f32[2]{0} %get-tuple-element.16, f32[2]{0} %get-tuple-element.17, f32[1,4,4,2]{3,2,1,0} %relugrad.2), epsilon=0.001, feature_index=3 get-tuple-element.79 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.76), index=2 fusion.8 = f32[2]{0} fusion(f32[2]{0} %arg4.5, f32[2]{0} %get-tuple-element.79), kind=kCustom, calls=%_pop_op_scaled_inplace.1, backend_config=""{}"" get-tuple-element.78 = f32[2]{0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.76), index=1 fusion.7 = f32[2]{0} fusion(f32[2]{0} %arg5.6, f32[2]{0} %get-tuple-element.78), kind=kCustom, calls=%_pop_op_scaled_inplace, backend_config=""{}"" get-tuple-element.77 = f32[1,4,4,2]{3,2,1,0} get-tuple-element((f32[1,4,4,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}) %batch-norm-grad.76), index=0 fusion.5 = f32[1,1,2,2]{3,2,1,0} fusion(f32[1,1,2,2]{3,2,1,0} %arg6.7, f32[1,4,4,2]{3,2,1,0} %arg0.1, f32[1,4,4,2]{3,2,1,0} %get-tuple-element.77), kind=kCustom, calls=%_pop_op_conv_scaled_inplace, backend_config=""{\\""fusionConfig\\"":{\\""window\\"":{\\""dimensions\\"":[{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""},{\\""size\\"":\\""4\\"",\\""stride\\"":\\""1\\"",\\""windowDilation\\"":\\""1\\"",\\""baseDilation\\"":\\""1\\""}]},\\""dimensionNumbers\\"":{\\""kernelOutputFeatureDimension\\"":\\""3\\"",\\""kernelSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""inputBatchDimension\\"":\\""3\\"",\\""outputBatchDimension\\"":\\""2\\"",\\""outputFeatureDimension\\"":\\""3\\"",\\""inputSpatialDimensions\\"":[\\""1\\"",\\""2\\""],\\""outputSpatialDimensions\\"":[\\""0\\"",\\""1\\""]},\\""featureGroupCount\\"":\\""1\\"",\\""batchGroupCount\\"":\\""1\\""}}"" ROOT %tuple.107 = (f32[], f32[2]{0}, f32[2]{0}, f32[1,1,2,2]{3,2,1,0}, f32[2]{0}, f32[2]{0}, f32[1,1,2,2]{3,2,1,0}) tuple(f32[] %reduce.42, f32[2]{0} %fusion.10, f32[2]{0} %fusion.9, f32[1,1,2,2]{3,2,1,0} %fusion.6, f32[2]{0} %fusion.8, f32[2]{0} %fusion.7, f32[1,1,2,2]{3,2,1,0} %fusion.5), metadata={op_name=""XLA_Retvals""}} )""; TEST_F(NormInputRecomputationTest, RecomputeRelu) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); config.set_resource_update_to_input_index({1, 2, 3, 4, 5, 6}); auto module_or_status = ParseAndReturnVerifiedModule(hlo_string_relu, config); EXPECT_TRUE(module_or_status.ok()); auto* module = module_or_status.ValueOrDie().get(); CompilerAnnotations annotations(module); ModuleFlatten flatten(annotations); ConvolutionClassifier classifier(annotations); CustomOpReplacer replacer{}; auto replacer_res = replacer.Run(module); EXPECT_TRUE(replacer_res.ok()); EXPECT_TRUE(replacer_res.ValueOrDie()); HloInstruction* input1 = FindInstruction(module, ""convolution.11""); HloInstruction* input2 = FindInstruction(module, ""convolution.23""); HloInstruction* bn1 = FindInstruction(module, ""batch-norm-training.13""); HloInstruction* bn2 = FindInstruction(module, ""batch-norm-training.25""); HloInstruction* bn_grad1 = FindInstruction(module, ""batch-norm-grad.76""); HloInstruction* bn_grad2 = FindInstruction(module, ""batch-norm-grad.50""); HloInstruction* relu1 = input2->mutable_operand(0); EXPECT_TRUE(IsPoplarInstruction(PoplarOp::Relu)(relu1)); HloInstruction* relu_grad2 = bn_grad1->mutable_operand(4); EXPECT_TRUE(IsPoplarInstruction(PoplarOp::ReluGrad)(relu_grad2)); ASSERT_EQ(input1->users().size(), 2); ASSERT_EQ(bn1->operand(0), input1); ASSERT_EQ(bn_grad1->operand(0), input1); ASSERT_EQ(input2->users().size(), 2); ASSERT_EQ(bn2->operand(0), input2); ASSERT_EQ(bn_grad2->operand(0), input2); ASSERT_EQ(relu_grad2->operand(0), relu1); EXPECT_TRUE(flatten.Run(module).ValueOrDie()); auto res = classifier.Run(module); EXPECT_TRUE(res.ok()); EXPECT_TRUE(res.ValueOrDie()); ASSERT_TRUE(RecomputeInstructions(true).Run(module).ValueOrDie()); ASSERT_EQ(bn1->operand(0), input1); ASSERT_NE(bn1->operand(0), bn_grad1->operand(0)); ASSERT_TRUE(bn1->operand(0)->Identical(*bn_grad1->operand(0))); ASSERT_EQ(bn2->operand(0), input2); ASSERT_NE(bn2->operand(0), bn_grad2->operand(0)); ASSERT_TRUE(bn2->operand(0)->Identical(*bn_grad2->operand(0))); // Check that the relu has been replaced ASSERT_NE(relu_grad2->operand(0), relu1); } TEST_F(NormInputRecomputationTest, RecomputeReluOff) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); config.set_resource_update_to_input_index({1, 2, 3, 4, 5, 6}); auto module_or_status = ParseAndReturnVerifiedModule(hlo_string_relu, config); EXPECT_TRUE(module_or_status.ok()); auto* module = module_or_status.ValueOrDie().get(); CompilerAnnotations annotations(module); ModuleFlatten flatten(annotations); ConvolutionClassifier classifier(annotations); EXPECT_TRUE(flatten.Run(module).ValueOrDie()); auto res = classifier.Run(module); EXPECT_TRUE(res.ok()); EXPECT_TRUE(res.ValueOrDie()); ASSERT_FALSE(RecomputeInstructions(false).Run(module).ValueOrDie()); } TEST_F(NormInputRecomputationTest, RecomputeF16WithCast) { HloModuleConfig config; config.set_debug_options(GetDebugOptionsForTest()); std::string module_string = R""( HloModule top _pop_op_wide_const () -> f16[32,32,32,1] { singleconst = f16[] constant(1) ROOT broadcastconst = f16[32,32,32,1] broadcast(f16[] singleconst), dimensions={} } ENTRY top (arg0: f16[32,32,32,3], arg1: f16[1,1,3,1], arg2: f32[1], arg3: f16[1]) -> (f16[32,32,32,1]) { arg0 = f16[32,32,32,3] parameter(0) arg1 = f16[1,1,3,1] parameter(1) arg2 = f32[1] parameter(2) arg3 = f16[1] parameter(3) gamma16 = f16[1] convert(f32[1] %arg2), metadata={op_type=""Cast"" op_name=""gamma_cast""} convolution = f16[32,32,32,1]{3,2,1,0} convolution(f16[32,32,32,3]{3,2,1,0} %arg0, f16[1,1,3,1]{3,2,1,0} %arg1), window={size=1x1}, dim_labels=b01f_01io->b01f batch-norm-training = (f16[32,32,32,1], f16[1], f16[1]) batch-norm-training(f16[32,32,32,1] %convolution, f16[1] %gamma16, f16[1] %arg3), epsilon=0.001, feature_index=3 gte0 = f16[32,32,32,1] get-tuple-element((f16[32,32,32,1], f16[1], f16[1]) %batch-norm-training), index=0 relu = f16[32,32,32,1] custom-call(f16[32,32,32,1] %gte0), custom_call_target=""Relu"", backend_config=""{}"" gte1 = f16[1] get-tuple-element((f16[32,32,32,1], f16[1], f16[1]) %batch-norm-training), index=1 gte2 = f16[1] get-tuple-element((f16[32,32,32,1], f16[1], f16[1]) %batch-norm-training), index=2 zeros = f16[32,32,32,1] fusion(), kind=kCustom, calls=%_pop_op_wide_const, backend_config=""{}"" relugrad = f16[32,32,32,1] custom-call(f16[32,32,32,1] relu, f16[32,32,32,1] %zeros), custom_call_target=""ReluGrad"", backend_config=""{}"" batch-norm-grad = (f16[32,32,32,1], f16[1], f16[1]) batch-norm-grad(f16[32,32,32,1] %convolution, f16[1] %gamma16, f16[1] %gte1, f16[1] %gte2, f16[32,32,32,1] %relugrad), epsilon=0.001, feature_index=3 gte-grad0 = f16[32,32,32,1] get-tuple-element((f16[32,32,32,1], f16[1], f16[1]) %batch-norm-grad), index=0 ROOT %tuple = (f16[32,32,32,1]) tuple(f16[32,32,32,1] %gte-grad0), metadata={op_name=""XLA_Retvals""}} )""; auto module_or_status = ParseAndReturnVerifiedModule(module_string, config); EXPECT_TRUE(module_or_status.ok()); auto* module = module_or_status.ValueOrDie().get(); CompilerAnnotations annotations(module); ModuleFlatten flatten(annotations); ConvolutionClassifier classifier(annotations); EXPECT_TRUE(flatten.Run(module).ValueOrDie()); auto res = classifier.Run(module); EXPECT_TRUE(res.ok()); EXPECT_TRUE(res.ValueOrDie()); ASSERT_TRUE(RecomputeInstructions(true).Run(module).ValueOrDie()); } } // namespace } // namespace poplarplugin } // namespace xla ",16243,True,3709.7315754579254,median "= v1beta1.ValidatingWebhookConfiguration {product-author} {product-version} :data-uri: :icons: :toc: macro :toc-title: :toclevels: 2 toc::[] == Description [%hardbreaks] ValidatingWebhookConfiguration describes the configuration of and admission webhook that accept or reject and object without changing it. == Object Schema Expand or mouse-over a field for more information about it. ++++
apiVersion:
kind:
metadata:
annotations:
[string]:
clusterName:
creationTimestamp:
deletionGracePeriodSeconds:
deletionTimestamp:
finalizers:
- [string]:
generateName:
generation:
:
pending:
- name:
result:
apiVersion:
code:
details:
causes:
- field:
message:
reason:
group:
kind:
name:
retryAfterSeconds:
uid:
kind:
message:
metadata:
continue:
resourceVersion:
selfLink:
reason:
status:
labels:
[string]:
name:
namespace:
ownerReferences:
- apiVersion:
blockOwnerDeletion:
controller:
kind:
name:
uid:
resourceVersion:
selfLink:
uid:
webhooks:
- clientConfig:
- caBundle:
service:
name:
namespace:
path:
url:
failurePolicy:
name:
namespaceSelector:
matchExpressions:
- key:
operator:
values:
- [string]:
matchLabels:
[string]:
rules:
- apiGroups:
- - [string]:
apiVersions:
- [string]:
operations:
- [string]:
resources:
- [string]:
++++ == Operations [[Post-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Create a ValidatingWebhookConfiguration Create a ValidatingWebhookConfiguration ==== HTTP request ---- POST /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X POST \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations <<'EOF' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |201 Created|v1beta1.ValidatingWebhookConfiguration |202 Accepted|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Get a ValidatingWebhookConfiguration Read the specified ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |exact|Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. |export|Should this value be exported. Export strips fields that a user can not specify. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Get-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Get all ValidatingWebhookConfigurations List or watch objects of kind ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfigurationList |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-admissionregistration.k8s.io-v1beta1-watch-validatingwebhookconfigurations-name]] === Watch a ValidatingWebhookConfiguration Watch changes to an object of kind ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations/$NAME ---- ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Get-apis-admissionregistration.k8s.io-v1beta1-watch-validatingwebhookconfigurations]] === Watch all ValidatingWebhookConfigurations Watch individual changes to a list of ValidatingWebhookConfiguration ==== HTTP request ---- GET /apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/watch/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |pretty|If 'true', then the output is pretty printed. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.WatchEvent |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf * application/json;stream=watch * application/vnd.kubernetes.protobuf;stream=watch [[Put-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Update a ValidatingWebhookConfiguration Replace the specified ValidatingWebhookConfiguration ==== HTTP request ---- PUT /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } ---- ==== Curl request ---- $ curl -k \\ -X PUT \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ""kind"": ""ValidatingWebhookConfiguration"", ""apiVersion"": ""admissionregistration.k8s.io/v1beta1"", ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1beta1.ValidatingWebhookConfiguration |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |201 Created|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Patch-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Patch a ValidatingWebhookConfiguration Partially update the specified ValidatingWebhookConfiguration ==== HTTP request ---- PATCH /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json-patch+json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X PATCH \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json-patch+json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.Patch |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1beta1.ValidatingWebhookConfiguration |401 Unauthorized| |=== ==== Consumes * application/json-patch+json * application/merge-patch+json * application/strategic-merge-patch+json ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations-name]] === Delete a ValidatingWebhookConfiguration Delete a ValidatingWebhookConfiguration ==== HTTP request ---- DELETE /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close Content-Type: application/json' { ... } ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -d @- \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ -H 'Content-Type: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations/$NAME <<'EOF' { ... } EOF ---- ==== HTTP body [cols=""1,5"", options=""header""] |=== |Parameter|Schema |body|v1.DeleteOptions |=== ==== Path parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |name|name of the ValidatingWebhookConfiguration |=== ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |gracePeriodSeconds|The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. |orphanDependents|Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the ""orphan"" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. |propagationPolicy|Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf [[Delete-apis-admissionregistration.k8s.io-v1beta1-validatingwebhookconfigurations]] === Delete all ValidatingWebhookConfigurations Delete collection of ValidatingWebhookConfiguration ==== HTTP request ---- DELETE /apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations HTTP/1.1 Authorization: Bearer $TOKEN Accept: application/json Connection: close ---- ==== Curl request ---- $ curl -k \\ -X DELETE \\ -H ""Authorization: Bearer $TOKEN"" \\ -H 'Accept: application/json' \\ https://$ENDPOINT/apis/admissionregistration.k8s.io/v1beta1/validatingwebhookconfigurations ---- ==== Query parameters [cols=""1,5"", options=""header""] |=== |Parameter|Description |pretty|If 'true', then the output is pretty printed. |continue|The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server the server will respond with a 410 ResourceExpired error indicating the client must restart their list without the continue field. This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. |fieldSelector|A selector to restrict the list of returned objects by their fields. Defaults to everything. |includeUninitialized|If true, partially initialized resources are included in the response. |labelSelector|A selector to restrict the list of returned objects by their labels. Defaults to everything. |limit|limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. |resourceVersion|When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. |timeoutSeconds|Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. |watch|Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. |=== ==== Responses [cols=""1,5"", options=""header""] |=== |HTTP Code|Schema |200 OK|v1.Status |401 Unauthorized| |=== ==== Consumes * \\*/* ==== Produces * application/json * application/yaml * application/vnd.kubernetes.protobuf ",12169,False,2070.589130303987,median "// Generated by the protocol buffer compiler. DO NOT EDIT! // source: error_code.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include ""error_code.pb.h"" #include #include #include #include #include #include #include #include #include // @@protoc_insertion_point(includes) namespace protoc { namespace error_code { namespace { const ::google::protobuf::EnumDescriptor* ERROR_CODE_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_error_5fcode_2eproto() { protobuf_AddDesc_error_5fcode_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( ""error_code.proto""); GOOGLE_CHECK(file != NULL); ERROR_CODE_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_error_5fcode_2eproto); } void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); } } // namespace void protobuf_ShutdownFile_error_5fcode_2eproto() { } void protobuf_AddDesc_error_5fcode_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( ""\\n\\020error_code.proto\\022\\021protoc.error_code*\\246E"" ""\\n\\nERROR_CODE\\022\\017\\n\\013ERR_SUCCESS\\020\\000\\022,\\n\\037ERR_USE"" ""R_ONLINE_GATE_REQ_REPEAT\\020\\377\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022E"" ""RR_LOGIN_TIME_OUT\\020\\376\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022!\\n\\024ERR_LOGI"" ""N_CHECK_FAIL\\020\\375\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_CANT_NOT_"" ""FIND_GAME_SERVER\\020\\374\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022.\\n!ERR_REACH"" ""_THE_LIMIT_PLAYER_NUMBER\\020\\373\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\033\\n\\016E"" ""RR_LOGIN_BUSY\\020\\372\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_ID_CANNO"" ""T_FIND_LOGIN_LOG\\020\\371\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_CANT_"" ""NOT_FIND_GATE_SERVER\\020\\370\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022!\\n\\024ERR_K"" ""ICK_OUT_OFFLINE\\020\\367\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_NET_ER"" ""ROR_KICK_OUT\\020\\366\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_PLAYER_GA"" ""ME_DATA_ERROR\\020\\365\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022-\\n ERR_GAMESERV"" ""ER_DISCONNECT_CLIENT\\020\\364\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036ERR_D"" ""BSERVER_FIND_REPEAT_LOGIN\\020\\363\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037"" ""ERR_DBSERVER_GET_USER_DATA_FAIL\\020\\362\\377\\377\\377\\377\\377\\377\\377"" ""\\377\\001\\022$\\n\\027ERR_NOT_FIND_THE_GM_CMD\\020\\361\\377\\377\\377\\377\\377\\377\\377\\377\\001"" ""\\022)\\n\\034ERR_NOT_FIND_THE_GM_FUNCTION\\020\\360\\377\\377\\377\\377\\377\\377"" ""\\377\\377\\001\\022 \\n\\023ERR_EXECUTE_GM_FAIL\\020\\357\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n"" ""\\031ERR_NOT_HAVE_LIMITS_OF_GM\\020\\356\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n"" ""\\035ERR_LOGIN_AND_LOGOUT_TOO_FAST\\020\\355\\377\\377\\377\\377\\377\\377\\377\\377"" ""\\001\\022*\\n\\035ERR_PLAYER_CREATE_NAME_REPEAT\\020\\354\\377\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022.\\n!ERR_PLAYER_CREATE_NAME_NOT_LAWF"" ""UL\\020\\353\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022-\\n ERR_CAN_NOT_FIND_KICK_O"" ""UT_PLAYER\\020\\347\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_SERVER_IS_BU"" ""SY_NOW\\020\\346\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_CAN_NOT_FIND_DB"" ""SERVER\\020\\345\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\032\\n\\rERR_SQL_ERROR\\020\\344\\377\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022\\036\\n\\021ERR_TEXT_TOO_LONG\\020\\343\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\032\\n"" ""\\rERR_TEXT_FAIL\\020\\342\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_ACCOUNT"" ""_HAS_BE_USE\\020\\341\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0227\\n*ERR_CAN_NOT_SE"" ""ND_CHAT_MSG_PLAYER_LEFT_GAME\\020\\340\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""\\036\\n\\021ERR_CHAT_TOO_FAST\\020\\337\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_U"" ""NIQUE_ID_NOT_ENOUGH\\020\\336\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_WA"" ""IT_KICK_OUT_TIME_OUT\\020\\335\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_A"" ""WARD_KEY_NO_TOO_LONG\\020\\334\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_A"" ""WARD_KEY_NO_ERROR\\020\\333\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_AWAR"" ""D_KEY_NO_HAS_USE\\020\\332\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_AWARD"" ""_KEY_INPUT_ERROR_TOO_MUCH\\020\\331\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\033\\n\\016"" ""ERR_AWARD_FAIL\\020\\330\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_CD_KEY_"" ""BU_NENG_YONG\\020\\327\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_RELOAD_GM"" ""_LIST_FAIL\\020\\326\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_CAN_NOT_FIN"" ""D_THE_PLAYER\\020\\325\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022!\\n\\024ERR_RELOGIN_T"" ""IME_OUT\\020\\324\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022-\\n ERR_PLSYERID_OR_AC"" ""COUNT_IS_WRONG\\020\\323\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_ACCOUNT"" ""_OR_PASSWORD_ERROR\\020\\322\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n\\025ERR_ACC"" ""OUNT_NOT_EXIST\\020\\321\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_SESSION"" ""_TIME_ERROR\\020\\320\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_MEI_YOU_TE"" ""_BIE_JIANG_LI\\020\\317\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_PLAYER_O"" ""FFLINE\\020\\316\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_SWITCH_GS_FAIL\\020"" ""\\315\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_LOGIN_AGAIN_TIME_OUT\\020\\314"" ""\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_INIT_PLAYER_BASE_FAIL\\020\\313"" ""\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_SELECT_PET_NOT_EXIST\\020\\312\\377"" ""\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_HAS_SELECT_PET\\020\\311\\377\\377\\377\\377\\377\\377\\377\\377"" ""\\001\\022)\\n\\034ERR_EMAIL_NOT_EXIST_THE_USER\\020\\310\\377\\377\\377\\377\\377"" ""\\377\\377\\377\\001\\022\\'\\n\\032ERR_EMAIL_THEME_IS_ILLEGAL\\020\\307\\377\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022)\\n\\034ERR_EMAIL_CONTENT_IS_ILLEGAL\\020\\306\\377"" ""\\377\\377\\377\\377\\377\\377\\377\\001\\022 \\n\\023ERR_NOT_ENOUGH_GOLD\\020\\305\\377\\377\\377\\377\\377\\377\\377"" ""\\377\\001\\022\\""\\n\\025ERR_DELETE_MSG_FAILED\\020\\304\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0220"" ""\\n#ERR_TODAY_SEND_EMIAL_COUNTS_IS_FULL\\020\\303\\377"" ""\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_QUEUE_NAME_IS_NOT_ILLEGA"" ""L\\020\\302\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0220\\n#ERR_QUEUE_ADMIN_PET_CAN_"" ""NOT_BE_NULL\\020\\301\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036ERR_CAN_NOT_FI"" ""ND_CURRENT_QUEUE\\020\\300\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_QUEUE"" ""_NUMBER_IS_FULL\\020\\277\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_NOT_EN"" ""OUGH_YUANBAO\\020\\276\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_NOT_ADD_N"" ""EW_QUEUE_IS_FAIL\\020\\275\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_PET_N"" ""UMBER_IS_FULL\\020\\274\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037ERR_PET_IS_N"" ""OT_IN_CURRENT_QUEUE\\020\\273\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_PE"" ""TS_IS_CAN_NOT_REPEATED\\020\\272\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR"" ""_MAIN_ID_CAN_NOT_MOVE\\020\\271\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037ERR_"" ""MOVE_PET_FROM_QUEUE_IS_FAIL\\020\\270\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$"" ""\\n\\027ERR_LEVEL_IS_NOT_ENOUGH\\020\\267\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030"" ""ERR_PET_IN_CURRENT_QUEUE\\020\\266\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036E"" ""RR_CAN_NOT_FIND_THE_QUEUE_IDX\\020\\265\\377\\377\\377\\377\\377\\377\\377\\377\\001"" ""\\022#\\n\\026ERR_PET_IN_THE_PROTECT\\020\\264\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022!\\n"" ""\\024ERR_PET_IN_THE_QUEUE\\020\\263\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022!\\n\\024ERR_"" ""TAKE_PET_IS_FAIL\\020\\262\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_PET_I"" ""DX_IS_NOT_ILLEGAL\\020\\261\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_FRIE"" ""NDSHIP_NOT_ENOUGH\\020\\260\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_PET_"" ""SPACE_NOT_ENOUGH\\020\\257\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_ACTIO"" ""N_COUNT_IS_FULL\\020\\256\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_PET_NU"" ""MBER_IS_TOO_LARGER\\020\\255\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_CAN"" ""_NOT_FIND_GOODS\\020\\254\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036ERR_SHOPPI"" ""NG_THIS_GOODS_FAILED\\020\\253\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_C"" ""HONGZHI_IS_FAILED\\020\\252\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_HAS_"" ""OVER_FIANL_DATE\\020\\251\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_CAN_NO"" ""T_FIND_PLAYER\\020\\250\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_CAN_NOT_"" ""FIND_FRIEND\\020\\247\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_PLAYER_FRI"" ""END_NUMBER_MAX\\020\\246\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_CAN_NOT"" ""_FIND_SEARCH\\020\\245\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_YOU_ARE_F"" ""RIEND\\020\\244\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_CAN_NOT_ADD_SF_F"" ""RIEND\\020\\243\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_TODAY_ADD_FRIEND"" ""_FULL\\020\\242\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022.\\n!ERR_PLAYER_SET_CAN_N"" ""OT_ADD_FRIEND\\020\\241\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022 \\n\\023ERR_ADD_FRIE"" ""ND_FAIL\\020\\240\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n\\025ERR_FRIEND_NUMBER_"" ""MAX\\020\\237\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_DELETE_FRIEND_FAIL"" ""\\020\\236\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_CANNOT_FIND_THE_SELEC"" ""T\\020\\234\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_CAN_NOT_TONSHI_SELF\\020"" ""\\233\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0220\\n#ERR_UPGRADE_TONGSHI_NUMBER"" ""_IS_WRONG\\020\\232\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_UPGRADE_PET_"" ""IS_FULL\\020\\231\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_EVOLVE_CONDTIO"" ""N_IS_NOT_CORRECT\\020\\230\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022 \\n\\023ERR_ADD_P"" ""ET_IS_FAIL\\020\\227\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_EVOLVE_LEVE"" ""L_IS_NOT_FULL\\020\\226\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_SELECT_P"" ""ET_CAN_NOT_EVOLVE\\020\\225\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_THE_"" ""POINT_NOT_EXIST\\020\\224\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_CAN_NO"" ""T_SELECT_THE_POINT\\020\\223\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_YOU"" ""R_HAVE_ASK_FRIEND\\020\\222\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_CAN_"" ""NOT_FIRE_NOT_ENOUGH_ACTION\\020\\221\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n"" ""\\032ERR_GET_CHENJIU_AWARD_FAIL\\020\\220\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022&"" ""\\n\\031ERR_WAR_RESULT_CHECK_FAIL\\020\\217\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\035"" ""\\n\\020ERR_WAR_TOO_FAST\\020\\216\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_GET"" ""_QUEST_AWARD_FAIL\\020\\215\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037ERR_CHON"" ""GZHI_SERVER_IS_BUSY_NOW\\020\\214\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n\\025ER"" ""R_CLEAR_PVP_CD_FAIL\\020\\213\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_YO"" ""U_HAVE_GET_PVP_AWARD\\020\\212\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_Y"" ""OU_TODAY_COUNT_IS_ZERO\\020\\211\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR"" ""_YOU_ARE_NOT_BEAIN_PVP_WAR\\020\\210\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n"" ""\\037ERR_CAN_NOT_FIND_A_MATCH_PLAYER\\020\\207\\377\\377\\377\\377\\377\\377"" ""\\377\\377\\001\\022(\\n\\033ERR_YOU_DONT_HAVE_THIS_PAGE\\020\\206\\377\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022\\034\\n\\017ERR_SKILL_ERROR\\020\\205\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0220\\n#E"" ""RR_YOU_DONT_HAVE_ENOUGH_SKILLPOINT\\020\\204\\377\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022*\\n\\035ERR_YOU_DONT_LEARN_THIS_SKILL\\020\\203"" ""\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_SECOND_SKILL_IS_LOCKED\\020"" ""\\202\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_YOU_DONT_REACH_THE_LEV"" ""EL\\020\\201\\377\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_HAVE_NOT_ARRIVE_SHO"" ""P_TIME\\020\\200\\377\\377\\377\\377\\377\\377\\377\\377\\001\\0220\\n#ERR_NOT_ENOUGH_GET_"" ""AWARD_CONDDITION\\020\\377\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_CAN_N"" ""OT_FIND_THIS_ACTIVE\\020\\376\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_YO"" ""U_HAVE_GET_THIS_ACTIVE_AWARD\\020\\375\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""&\\n\\031ERR_NOT_IN_GET_AWARD_TIME\\020\\374\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""$\\n\\027ERR_GUIDE_STEP_HAS_DONE\\020\\373\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n"" ""\\033ERR_ALL_GUIDE_STEP_HAS_DONE\\020\\372\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""\\""\\n\\025ERR_UNKOWN_GUIDE_STEP\\020\\371\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034E"" ""RR_PLAYER_LEVEL_IS_NOT_FULL\\020\\370\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022*"" ""\\n\\035ERR_REACH_MAX_CHALLENGE_COUNT\\020\\367\\376\\377\\377\\377\\377\\377\\377"" ""\\377\\001\\022$\\n\\027ERR_REACH_MAX_BUY_COUNT\\020\\366\\376\\377\\377\\377\\377\\377\\377\\377\\001"" ""\\022#\\n\\026ERR_CAN_NOT_FIND_EQUIP\\020\\365\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n"" ""\\032ERR_CAN_NOT_FIND_THE_GOODS\\020\\364\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022%"" ""\\n\\030ERR_EQUIP_HAS_SET_IN_PET\\020\\363\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n"" ""\\025ERR_EQUIP_PKG_IS_FULL\\020\\362\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR"" ""_TAKE_EQUIP_IS_WRONG\\020\\361\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_Y"" ""OU_GOODS_IS_NOT_ENOUGH\\020\\360\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR"" ""_TAKE_GOODS_IS_FAIL\\020\\357\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_EQ"" ""UIP_HAS_PUT_NO_PET\\020\\356\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022#\\n\\026ERR_EQU"" ""IP_IS_MAX_LEVEL\\020\\355\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_TS_EQU"" ""IP_HAS_PUT_ON\\020\\354\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_EQUIP_LE"" ""VEL_IS_TOO_LOW\\020\\353\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_EQUIP_P"" ""INZHI_IS_MAX\\020\\352\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022-\\n ERR_CAN_NOT_F"" ""IND_JINJIE_GOODS_ID\\020\\351\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n\\025ERR_ER"" ""R_HE_CHENG_TYPE\\020\\350\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022.\\n!ERR_HE_CHE"" ""NG_NUMBER_IS_NOT_ENOUGH\\020\\347\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\""\\n\\025ER"" ""R_ADD_GOODS_IS_FAIL\\020\\346\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_CA"" ""N_NOT_FIND_COVER_ID\\020\\345\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022*\\n\\035ERR_XI"" ""ANG_QUAN_NUMBER_IS_FULL\\020\\344\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022.\\n!ER"" ""R_JINJIE_MATERIAL_IS_NOT_ENOUGH\\020\\343\\376\\377\\377\\377\\377\\377\\377"" ""\\377\\001\\022*\\n\\035ERR_EQUIP_CAN_NOT_STRENG_SELF\\020\\342\\376\\377\\377"" ""\\377\\377\\377\\377\\377\\001\\022+\\n\\036ERR_PUT_ON_EQUIP_TPE_LEVEL_LOE"" ""\\020\\341\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_CAN_NOT_HAVE_SAME_PET"" ""_IN_QUEUE\\020\\340\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_TODAY_USE_AC"" ""TION_COUNT_IS_FULL\\020\\337\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037ERR_YOU"" ""_TODAY_BUY_COUNT_IS_ZERO\\020\\336\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034E"" ""RR_YOU_QUEUE_SPIRIT_IS_FULL\\020\\335\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'"" ""\\n\\032ERR_SET_CUR_QUEUE_IDX_FAIL\\020\\334\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""*\\n\\035ERR_ADD_PET_TO_CUR_QUEUE_FAIL\\020\\333\\376\\377\\377\\377\\377\\377"" ""\\377\\377\\001\\022(\\n\\033ERR_FIRST_QUEUE_CAN_NOT_SUB\\020\\332\\376\\377\\377\\377"" ""\\377\\377\\377\\377\\001\\022,\\n\\037ERR_PET_NUMBER_IS_FULL_IN_QUEUE"" ""\\020\\331\\376\\377\\377\\377\\377\\377\\377\\377\\001\\0222\\n%ERR_SUB_QUEUE_PET_NUMBER_"" ""CAN_NOT_ZERO\\020\\330\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_SUB_QUEUE"" ""_IDX_ERROR\\020\\327\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ERR_SUB_QUEUE_P"" ""ET_REPEATED\\020\\326\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR_SUB_QUEUE_"" ""PET_TYPE_IS_REPEATED\\020\\325\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022)\\n\\034ERR_S"" ""UB_QUEUE_SPIRIT_IS_FULL\\020\\324\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036ER"" ""R_EQUIP_TONSHI_NUMBER_IS_MAX\\020\\323\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""%\\n\\030ERR_EUQIP_CAN_NOT_PUT_ON\\020\\322\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022%"" ""\\n\\030ERR_EUQIP_CAN_NOT_STRENG\\020\\321\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n"" ""\\031ERR_EUQIP_CAN_NOT_JINGJIE\\020\\320\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n"" ""\\031ERR_EUQIP_CAN_NOT_HE_CHEN\\020\\317\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n"" ""\\033ERR_EUQIP_CAN_NOT_STRENG_TS\\020\\316\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""!\\n\\024ERR_NOT_IN_OPEN_TIME\\020\\315\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022\\'\\n\\032ER"" ""R_EQUIP_SPACE_NOT_ENOUGH\\020\\314\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031E"" ""RR_MAX_ACCUMULATE_ACTION\\020\\313\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027E"" ""RR_EUQIP_IS_NOT_PUT_ON\\020\\312\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022/\\n\\""ERR"" ""_STRENG_EUQIP_MATERIAL_IS_WRONG\\020\\311\\376\\377\\377\\377\\377\\377\\377"" ""\\377\\001\\0221\\n$ERR_STRENG_EUQIP_MATERIAL_NUMBER_L"" ""OW\\020\\310\\376\\377\\377\\377\\377\\377\\377\\377\\001\\0224\\n\\'ERR_STRENG_EUQIP_GOODS_"" ""KIND_CANNOT_SAME\\020\\307\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022+\\n\\036ERR_OVER_"" ""BUFF_LIMIT_BUY_NUMBER\\020\\306\\376\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_"" ""SERVER_UNKNOW_ERROR\\020\\360\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022\\036\\n\\021ERR_De"" ""ny_MUILogin\\020\\357\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022\\036\\n\\021ERR_WAITING_UP"" ""PER\\020\\356\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_JIN_ZHI_JIN_RU\\020\\355\\261\\377"" ""\\377\\377\\377\\377\\377\\377\\001\\022\\036\\n\\021ERR_ONLY_GM_LOGIN\\020\\354\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022"" ""#\\n\\026ERR_ONLY_LIMIT_ACCOUNT\\020\\353\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022\\036\\n\\021"" ""ERR_REPEATE_LOGIN\\020\\352\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_LOGI"" ""N_TOO_MORE_TIME\\020\\351\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_ACCOUN"" ""T_SIZE_TOO_LONG\\020\\350\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022.\\n!ERR_JIN_ZH"" ""I_JIN_RU_BY_FAST_ATTACK\\020\\347\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022 \\n\\023ER"" ""R_LOGIN_KEY_ERROR\\020\\346\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_CLIE"" ""NT_VERSION_ERROR\\020\\345\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_FRONT"" ""_PLAYER_IS_LEAVING\\020\\344\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_HAS"" ""_NOT_INVITATION_CODE\\020\\343\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022(\\n\\033ERR_H"" ""AS_USE_INVITATION_CODE\\020\\342\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR"" ""_ACCOUNT_HAS_ACTIVED\\020\\341\\261\\377\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_A"" ""CCOUNT_NEED_ACTIVE\\020\\340\\261\\377\\377\\377\\377\\377\\377\\377\\001\\0221\\n$ERR_TRS"" ""_FILE_CAN_NOT_FIND_SERVER_DIR\\020\\337\\343\\376\\377\\377\\377\\377\\377\\377\\001"" ""\\022$\\n\\027ERR_TRS_FILE_UNZIP_FILE\\020\\336\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022\\'"" ""\\n\\032ERR_TRS_FILE_MD5_NOT_MATCH\\020\\335\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022"" ""+\\n\\036ERR_TRS_FILE_CAN_NOT_OPEN_FILE\\020\\334\\343\\376\\377\\377\\377"" ""\\377\\377\\377\\001\\022)\\n\\034ERR_TRS_FILE_WRIT_FILE_ERROR\\020\\333\\343\\376"" ""\\377\\377\\377\\377\\377\\377\\001\\022,\\n\\037ERR_TRS_FILE_NOT_READY_TRAN_L"" ""OG\\020\\332\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_TRANS_FILE_TOO_LARG"" ""E\\020\\331\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022!\\n\\024ERR_RANK_CHECK_ERROR\\020\\330\\343\\376"" ""\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_FILE_MD5_CHECK_FAIL\\020\\327\\343\\376\\377\\377"" ""\\377\\377\\377\\377\\001\\022&\\n\\031ERR_PROTOC_ID_OUTOF_RANGE\\020\\326\\343\\376\\377\\377"" ""\\377\\377\\377\\377\\001\\022&\\n\\031ERR_NO_FUN_FOR_THE_PROTOC\\020\\325\\343\\376\\377\\377"" ""\\377\\377\\377\\377\\001\\022$\\n\\027ERR_GATE_KEY_CHECK_FAIL\\020\\324\\343\\376\\377\\377\\377\\377"" ""\\377\\377\\001\\022-\\n ERR_THIS_SESSION_NOT_BIND_PLAYER\\020"" ""\\323\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022&\\n\\031ERR_GAMESERVER_IS_CLOSING\\020"" ""\\322\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022$\\n\\027ERR_ID_MANAGER_NOT_INIT\\020\\321\\343"" ""\\376\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_YOU_ARE_LEAVING_GAME\\020\\320\\343\\376"" ""\\377\\377\\377\\377\\377\\377\\001\\022\\037\\n\\022ERR_YOU_ARE_LOCKED\\020\\317\\343\\376\\377\\377\\377\\377\\377\\377\\001"" ""\\022\\035\\n\\020ERR_DATA_LOADING\\020\\316\\343\\376\\377\\377\\377\\377\\377\\377\\001\\022%\\n\\030ERR_S"" ""END_PACKET_TOO_FAST\\020\\315\\343\\376\\377\\377\\377\\377\\377\\377\\001"", 8910); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( ""error_code.proto"", &protobuf_RegisterTypes); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_error_5fcode_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_error_5fcode_2eproto { StaticDescriptorInitializer_error_5fcode_2eproto() { protobuf_AddDesc_error_5fcode_2eproto(); } } static_descriptor_initializer_error_5fcode_2eproto_; const ::google::protobuf::EnumDescriptor* ERROR_CODE_descriptor() { protobuf_AssignDescriptorsOnce(); return ERROR_CODE_descriptor_; } bool ERROR_CODE_IsValid(int value) { switch(value) { case -20019: case -20018: case -20017: case -20016: case -20015: case -20014: case -20013: case -20012: case -20011: case -20010: case -20009: case -20008: case -20007: case -20006: case -20005: case -20004: case -20003: case -20002: case -20001: case -10016: case -10015: case -10014: case -10013: case -10012: case -10011: case -10010: case -10009: case -10008: case -10007: case -10006: case -10005: case -10004: case -10003: case -10002: case -10001: case -10000: case -186: case -185: case -184: case -183: case -182: case -181: case -180: case -179: case -178: case -177: case -176: case -175: case -174: case -173: case -172: case -171: case -170: case -169: case -168: case -167: case -166: case -165: case -164: case -163: case -162: case -161: case -160: case -159: case -158: case -157: case -156: case -155: case -154: case -153: case -152: case -151: case -150: case -149: case -148: case -147: case -146: case -145: case -144: case -143: case -142: case -141: case -140: case -139: case -138: case -137: case -136: case -135: case -134: case -133: case -132: case -131: case -130: case -129: case -128: case -127: case -126: case -125: case -124: case -123: case -122: case -121: case -120: case -119: case -118: case -117: case -116: case -115: case -114: case -113: case -112: case -111: case -110: case -109: case -108: case -107: case -106: case -105: case -104: case -103: case -102: case -101: case -100: case -98: case -97: case -96: case -95: case -94: case -93: case -92: case -91: case -90: case -89: case -88: case -87: case -86: case -85: case -84: case -83: case -82: case -81: case -80: case -79: case -78: case -77: case -76: case -75: case -74: case -73: case -72: case -71: case -70: case -69: case -68: case -67: case -66: case -65: case -64: case -63: case -62: case -61: case -60: case -59: case -58: case -57: case -56: case -55: case -54: case -53: case -52: case -51: case -50: case -49: case -48: case -47: case -46: case -45: case -44: case -43: case -42: case -41: case -40: case -39: case -38: case -37: case -36: case -35: case -34: case -33: case -32: case -31: case -30: case -29: case -28: case -27: case -26: case -25: case -21: case -20: case -19: case -18: case -17: case -16: case -15: case -14: case -13: case -12: case -11: case -10: case -9: case -8: case -7: case -6: case -5: case -4: case -3: case -2: case -1: case 0: return true; default: return false; } } // @@protoc_insertion_point(namespace_scope) } // namespace error_code } // namespace protoc // @@protoc_insertion_point(global_scope) ",16210,True,5038.619864931088,median "// Use these for links to issue and pulls. Note issues and pulls redirect one to // each other on Github, so don't worry too much on using the right prefix. :issue: https://github.com/elastic/beats/issues/ :pull: https://github.com/elastic/beats/pull/ === Beats version HEAD https://github.com/elastic/beats/compare/v7.0.0-alpha2...master[Check the HEAD diff] ==== Breaking changes *Affecting all Beats* - Update to Golang 1.12.1. {pull}11330[11330] - Update to Golang 1.12.4. {pull}11782[11782] - Update to ECS 1.0.1. {pull}12284[12284] {pull}12317[12317] - Default of output.kafka.metadata.full is set to false by now. This reduced the amount of metadata to be queried from a kafka cluster. {pull}12738[12738] - Fixed a crash under Windows when fetching processes information. {pull}12833[12833] - Update to Golang 1.12.7. {pull}12931[12931] - Remove `in_cluster` configuration parameter for Kuberentes, now in-cluster configuration is used only if no other kubeconfig is specified {pull}13051[13051] - Disable Alibaba Cloud and Tencent Cloud metadata providers by default. {pull}13812[12812] - Libbeat HTTP's Server can listen to a unix socket using the `unix:///tmp/hello.sock` syntax. {pull}13655[13655] - Libbeat HTTP's Server can listen to a Windows named pipe using the `npipe:///hello` syntax. {pull}13655[13655] *Auditbeat* - Auditd module: Normalized value of `event.category` field from `user-login` to `authentication`. {pull}11432[11432] - Auditd module: Unset `auditd.session` and `user.audit.id` fields are removed from audit events. {issue}11431[11431] {pull}11815[11815] - Socket dataset: Exclude localhost by default {pull}11993[11993] - Socket dataset: New implementation using Kprobes for finer-grained monitoring and UDP support. {pull}13058[13058] *Filebeat* - Add read_buffer configuration option. {pull}11739[11739] - `convert_timezone` option is removed and locale is always added to the event so timezone is used when parsing the timestamp, this behaviour can be overriden with processors. {pull}12410[12410] - Fix a race condition in the TCP input when close the client socket. {pull}13038[13038] - cisco/asa fileset: Renamed log.original to event.original and cisco.asa.list_id to cisco.asa.rule_name. {pull}13286[13286] - cisco/asa fileset: Fix parsing of 302021 message code. {pull}13476[13476] - Add support for gzipped files in S3 input {pull}13980[13980] - Add support for all the ObjectCreated events in S3 input. {pull}14077[14077] *Heartbeat* - Removed the `add_host_metadata` and `add_cloud_metadata` processors from the default config. These don't fit well with ECS for Heartbeat and were rarely used. *Journalbeat* *Metricbeat* - Add new dashboards for Azure vms, vm guest metrics, vm scale sets {pull}14000[14000] - Add new Dashboard for PostgreSQL database stats {pull}13187[13187] - Add new dashboard for CouchDB database {pull}13198[13198] - Add new dashboard for Ceph cluster stats {pull}13216[13216] - Add new dashboard for Aerospike database stats {pull}13217[13217] - Add new dashboard for Couchbase cluster stats {pull}13212[13212] - Add new dashboard for Prometheus server stats {pull}13126[13126] - Add new option `OpMultiplyBuckets` to scale histogram buckets to avoid decimal points in final events {pull}10994[10994] - system/raid metricset now uses /sys/block instead of /proc/mdstat for data. {pull}11613[11613] - kubernetes.container.cpu.limit.cores and kubernetes.container.cpu.requests.cores are now floats. {issue}11975[11975] - Add statistic option into cloudwatch metricset. If there is no statistic method specified, default is to collect Average, Sum, Maximum, Minimum and SampleCount. {issue}12370[12370] {pull}12840[12840] *Packetbeat* - Add support for mongodb opcode 2013 (OP_MSG). {issue}6191[6191] {pull}8594[8594] - NFSv4: Always use opname `ILLEGAL` when failed to match request to a valid nfs operation. {pull}11503[11503] *Winlogbeat* *Functionbeat* - Separate management and functions in Functionbeat. {pull}12939[12939] ==== Bugfixes *Affecting all Beats* - Fix typo in TLS renegotiation configuration and setting the option correctly {issue}10871[10871], {pull}12354[12354] - Ensure all beat commands respect configured settings. {pull}10721[10721] - Add missing fields and test cases for libbeat add_kubernetes_metadata processor. {issue}11133[11133], {pull}11134[11134] - decode_json_field: process objects and arrays only {pull}11312[11312] - decode_json_field: do not process arrays when flag not set. {pull}11318[11318] - Report faulting file when config reload fails. {pull}11304[11304] - Fix a typo in libbeat/outputs/transport/client.go by updating `c.conn.LocalAddr()` to `c.conn.RemoteAddr()`. {pull}11242[11242] - Management configuration backup file will now have a timestamps in their name. {pull}11034[11034] - [CM] Parse enrollment_token response correctly {pull}11648[11648] - Not hiding error in case of http failure using elastic fetcher {pull}11604[11604] - Escape BOM on JsonReader before trying to decode line {pull}11661[11661] - Fix matching of string arrays in contains condition. {pull}11691[11691] - Replace wmi queries with win32 api calls as they were consuming CPU resources {issue}3249[3249] and {issue}11840[11840] - Fix a race condition with the Kafka pipeline client, it is possible that `Close()` get called before `Connect()` . {issue}11945[11945] - Fix queue.spool.write.flush.events config type. {pull}12080[12080] - Fixed a memory leak when using the add_process_metadata processor under Windows. {pull}12100[12100] - Fix of docker json parser for missing ""log"" jsonkey in docker container's log {issue}11464[11464] - Fixed Beat ID being reported by GET / API. {pull}12180[12180] - Fixed setting bulk max size in kafka output. {pull}12254[12254] - Add host.os.codename to fields.yml. {pull}12261[12261] - Fix `@timestamp` being duplicated in events if `@timestamp` is set in a processor (or by any code utilizing `PutValue()` on a `beat.Event`). - Fix leak in script processor when using Javascript functions in a processor chain. {pull}12600[12600] - Add additional nil pointer checks to Docker client code to deal with vSphere Integrated Containers {pull}12628[12628] - Fixed `json.add_error_key` property setting for delivering error messages from beat events {pull}11298[11298] - Fix Central Management enroll under Windows {issue}12797[12797] {pull}12799[12799] - ILM: Use GET instead of HEAD when checking for alias to expose detailed error message. {pull}12886[12886] - Fix seccomp policy preventing some features to function properly on 32bit Linux systems. {issue}12990[12990] {pull}13008[13008] - Fix unexpected stops on docker autodiscover when a container is restarted before `cleanup_timeout`. {issue}12962[12962] {pull}13127[13127] - Fix install-service.ps1's ability to set Windows service's delay start configuration. {pull}13173[13173] - Fix some incorrect types and formats in field.yml files. {pull}13188[13188] - Load DLLs only from Windows system directory. {pull}13234[13234] {pull}13384[13384] - Fix mapping for kubernetes.labels and kubernetes.annotations in add_kubernetes_metadata. {issue}12638[12638] {pull}13226[13226] - Fix case insensitive regular expressions not working correctly. {pull}13250[13250] - Disable `add_kubernetes_metadata` if no matchers found. {pull}13709[13709] - Better wording for xpack beats when the _xpack endpoint is not reachable. {pull}13771[13771] - Recover from panics in the javascript process and log details about the failure to aid in future debugging. {pull}13690[13690] - Make the script processor concurrency-safe. {issue}13690[13690] {pull}13857[13857] - Kubernetes watcher at `add_kubernetes_metadata` fails with StatefulSets {pull}13905[13905] *Auditbeat* - Process dataset: Fixed a memory leak under Windows. {pull}12100[12100] - Login dataset: Fix re-read of utmp files. {pull}12028[12028] - Package dataset: Fixed a crash inside librpm after Auditbeat has been running for a while. {issue}12147[12147] {pull}12168[12168] - Fix formatting of config files on macOS and Windows. {pull}12148[12148] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Package dataset: Close librpm handle. {pull}12215[12215] - Package dataset: Auto-detect package directories. {pull}12289[12289] - Package dataset: Improve dpkg parsing. {pull}12325[12325] - System module: Start system module without host ID. {pull}12373[12373] - Host dataset: Fix reboot detection logic. {pull}12591[12591] - Add syscalls used by librpm for the system/package dataset to the default Auditbeat seccomp policy. {issue}12578[12578] {pull}12617[12617] - Process dataset: Do not show non-root warning on Windows. {pull}12740[12740] - Host dataset: Export Host fields to gob encoder. {pull}12940[12940] - Socket dataset: Fix start errors when IPv6 is disabled on the kernel. {issue}13953[13953] {pull}13966[13966] *Filebeat* - Add support for Cisco syslog format used by their switch. {pull}10760[10760] - Cover empty request data, url and version in Apache2 module{pull}10730[10730] - Fix registry entries not being cleaned due to race conditions. {pull}10747[10747] - Improve detection of file deletion on Windows. {pull}10747[10747] - Add missing Kubernetes metadata fields to Filebeat CoreDNS module, and fix a documentation error. {pull}11591[11591] - Reduce memory usage if long lines are truncated to fit `max_bytes` limit. The line buffer is copied into a smaller buffer now. This allows the runtime to release unused memory earlier. {pull}11524[11524] - Fix memory leak in Filebeat pipeline acker. {pull}12063[12063] - Fix goroutine leak caused on initialization failures of log input. {pull}12125[12125] - Fix goroutine leak on non-explicit finalization of log input. {pull}12164[12164] - Skipping unparsable log entries from docker json reader {pull}12268[12268] - Parse timezone in PostgreSQL logs as part of the timestamp {pull}12338[12338] - Load correct pipelines when system module is configured in modules.d. {pull}12340[12340] - Fix timezone offset parsing in system/syslog. {pull}12529[12529] - When TLS is configured for the TCP input and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Apply `max_message_size` to incoming message buffer. {pull}11966[11966] - Syslog input will now omit the `process` object from events if it is empty. {pull}12700[12700] - Fix multiline pattern in Postgres which was too permissive {issue}12078[12078] {pull}13069[13069] - Allow path variables to be used in files loaded from modules.d. {issue}13184[13184] - Fix filebeat autodiscover fileset hint for container input. {pull}13296[13296] - Fix incorrect references to index patterns in AWS and CoreDNS dashboards. {pull}13303[13303] - Fix timezone parsing of system module ingest pipelines. {pull}13308[13308] - Fix timezone parsing of elasticsearch module ingest pipelines. {pull}13367[13367] - Change iis url path grok pattern from URIPATH to NOTSPACE. {issue}12710[12710] {pull}13225[13225] {issue}7951[7951] {pull}13378[13378] - Fix timezone parsing of nginx module ingest pipelines. {pull}13369[13369] - Fix incorrect field references in envoyproxy dashboard {issue}13420[13420] {pull}13421[13421] - Fixed early expiration of templates (Netflow v9 and IPFIX). {pull}13821[13821] - Fixed bad handling of sequence numbers when multiple observation domains were exported by a single device (Netflow V9 and IPFIX). {pull}13821[13821] - Fix timezone parsing of rabbitmq module ingest pipelines. {pull}13879[13879] - Fix conditions and error checking of date processors in ingest pipelines that use `event.timezone` to parse dates. {pull}13883[13883] - Fix timezone parsing of Cisco module ingest pipelines. {pull}13893[13893] - Fix timezone parsing of logstash module ingest pipelines. {pull}13890[13890] - cisco asa and ftd filesets: Fix parsing of message 106001. {issue}13891[13891] {pull}13903[13903] - Fix timezone parsing of iptables, mssql and panw module ingest pipelines. {pull}13926[13926] - Fix merging of fields specified in global scope with fields specified under an input's scope. {issue}3628[3628] {pull}13909[13909] - Fix delay in enforcing close_renamed and close_removed options. {issue}13488[13488] {pull}13907[13907] - Fix missing netflow fields in index template. {issue}13768[13768] {pull}13914[13914] - Fix cisco module's asa and ftd filesets parsing of domain names where an IP address is expected. {issue}14034[14034] - Fixed increased memory usage with large files when multiline pattern does not match. {issue}14068[14068] - panw module: Use geo.name instead of geo.country_iso_code for free-form location. {issue}13272[13272] - Fix azure fields names. {pull}14098[14098] - Fix calculation of `network.bytes` and `network.packets` for bi-directional netflow events. {pull}14111[14111] - Fix timezone parsing of MySQL module ingest pipelines. {pull}14130[14130] *Heartbeat* - Fix NPEs / resource leaks when executing config checks. {pull}11165[11165] - Fix duplicated IPs on `mode: all` monitors. {pull}12458[12458] - Fix integer comparison on JSON responses. {pull}13348[13348] *Journalbeat* - Use backoff when no new events are found. {pull}11861[11861] - Iterate over journal correctly, so no duplicate entries are sent. {pull}12716[12716] - Preserve host name when reading from remote journal. {pull}12714[12714] *Metricbeat* - Change diskio metrics retrieval method (only for Windows) from wmi query to DeviceIOControl function using the IOCTL_DISK_PERFORMANCE control code {pull}11635[11635] - Call GetMetricData api per region instead of per instance. {issue}11820[11820] {pull}11882[11882] - Update documentation with cloudwatch:ListMetrics permission. {pull}11987[11987] - Check permissions in system socket metricset based on capabilities. {pull}12039[12039] - Get process information from sockets owned by current user when system socket metricset is run without privileges. {pull}12039[12039] - Avoid generating hints-based configuration with empty hosts when no exposed port is suitable for the hosts hint. {issue}8264[8264] {pull}12086[12086] - Fixed a socket leak in the postgresql module under Windows when SSL is disabled on the server. {pull}11393[11393] - Change some field type from scaled_float to long in aws module. {pull}11982[11982] - Fixed RabbitMQ `queue` metricset gathering when `consumer_utilisation` is set empty at the metrics source {pull}12089[12089] - Fix direction of incoming IPv6 sockets. {pull}12248[12248] - Refactored Windows perfmon metricset: replaced method to retrieve counter paths with PdhExpandWildCardPathW, separated code by responsibility, removed unused functions {pull}12212[12212] - Validate that kibana/status metricset cannot be used when xpack is enabled. {pull}12264[12264] - Ignore prometheus metrics when their values are NaN or Inf. {pull}12084[12084] {issue}10849[10849] - In the kibana/stats metricset, only log error (don't also index it) if xpack is enabled. {pull}12265[12265] - Fix an issue listing all processes when run under Windows as a non-privileged user. {issue}12301[12301] {pull}12475[12475] - The `elasticsearch/index_summary` metricset gracefully handles an empty Elasticsearch cluster when `xpack.enabled: true` is set. {pull}12489[12489] {issue}12487[12487] - When TLS is configured for the http metricset and a `certificate_authorities` is configured we now default to `required` for the `client_authentication`. {pull}12584[12584] - Reuse connections in PostgreSQL metricsets. {issue}12504[12504] {pull}12603[12603] - PdhExpandWildCardPathW will not expand counter paths in 32 bit windows systems, workaround will use a different function. {issue}12590[12590] {pull}12622[12622] - In the elasticsearch/node_stats metricset, if xpack is enabled, make parsing of ES node load average optional as ES on Windows doesn't report load average. {pull}12866[12866] - Ramdisk is not filtered out when collecting disk performance counters in diskio metricset {issue}12814[12814] {pull}12829[12829] - Fix incoherent behaviour in redis key metricset when keyspace is specified both in host URL and key pattern {pull}12913[12913] - Fix connections leak in redis module {pull}12914[12914] {pull}12950[12950] - Fix wrong uptime reporting by system/uptime metricset under Windows. {pull}12915[12915] - Print errors that were being omitted in vSphere metricsets. {pull}12816[12816] - Fix redis key metricset dashboard references to index pattern. {pull}13303[13303] - Check if fields in DBInstance is nil in rds metricset. {pull}13294[13294] {issue}13037[13037] - Fix silent failures in kafka and prometheus module. {pull}13353[13353] {issue}13252[13252] - Fix issue with aws cloudwatch module where dimensions and/or namespaces that contain space are not being parsed correctly {pull}13389[13389] - Fix panic in Redis Key metricset when collecting information from a removed key. {pull}13426[13426] - Fix module-level fields in Kubernetes metricsets. {pull}13433[13433] {pull}13544[13544] - Fix reporting empty events in cloudwatch metricset. {pull}13458[13458] - Fix `docker.cpu.system.pct` calculation by using the reported number online cpus instead of the number of metrics per cpu. {pull}13691[13691] - Fix rds metricset dashboard. {pull}13721[13721] - Ignore prometheus untyped metrics with NaN value. {issue}13750[13750] {pull}13790[13790] - Change kubernetes.event.message to text {pull}13964[13964] - Fix performance counter values for windows/perfmon metricset.{issue}14036[14036] {pull}14039[14039] *Packetbeat* - Prevent duplicate packet loss error messages in HTTP events. {pull}10709[10709] - Fixed a memory leak when using process monitoring under Windows. {pull}12100[12100] - Improved debug logging efficiency in PGQSL module. {issue}12150[12150] - Limit memory usage of Redis replication sessions. {issue}12657[12657] - Fix parsing the extended RCODE in the DNS parser. {pull}12805[12805] *Winlogbeat* - Fix data race affecting config validation at startup. {issue}13005[13005] *Functionbeat* - Fix function name reference for Kinesis streams in CloudFormation templates {pull}11646[11646] - Fix Cloudwatch logs timestamp to use timestamp of the log record instead of when the record was processed {pull}13291[13291] - Look for the keystore under the correct path. {pull}13332[13332] ==== Added *Affecting all Beats* - Decouple Debug logging from fail_on_error logic for rename, copy, truncate processors {pull}12451[12451] - Add an option to append to existing logs rather than always rotate on start. {pull}11953[11953] - Add `network` condition to processors for matching IP addresses against CIDRs. {pull}10743[10743] - Add if/then/else support to processors. {pull}10744[10744] - Add `community_id` processor for computing network flow hashes. {pull}10745[10745] - Add output test to kafka output {pull}10834[10834] - Gracefully shut down on SIGHUP {pull}10704[10704] - New processor: `copy_fields`. {pull}11303[11303] - Add `error.message` to events when `fail_on_error` is set in `rename` and `copy_fields` processors. {pull}11303[11303] - New processor: `truncate_fields`. {pull}11297[11297] - Allow a beat to ship monitoring data directly to an Elasticsearch monitoring cluster. {pull}9260[9260] - Updated go-seccomp-bpf library to v1.1.0 which updates syscall lists for Linux v5.0. {pull}11394[11394] - Add `add_observer_metadata` processor. {pull}11394[11394] - Add `decode_csv_fields` processor. {pull}11753[11753] - Add `convert` processor for converting data types of fields. {issue}8124[8124] {pull}11686[11686] - New `extract_array` processor. {pull}11761[11761] - Add number of goroutines to reported metrics. {pull}12135[12135] - Add `proxy_disable` output flag to explicitly ignore proxy environment variables. {issue}11713[11713] {pull}12243[12243] - Processor `add_cloud_metadata` adds fields `cloud.account.id` and `cloud.image.id` for AWS EC2. {pull}12307[12307] - Add configurable bulk_flush_frequency in kafka output. {pull}12254[12254] - Add `decode_base64_field` processor for decoding base64 field. {pull}11914[11914] - Add support for reading the `network.iana_number` field by default to the community_id processor. {pull}12701[12701] - Add aws overview dashboard. {issue}11007[11007] {pull}12175[12175] - Add `decompress_gzip_field` processor. {pull}12733[12733] - Add `timestamp` processor for parsing time fields. {pull}12699[12699] - Fail with error when autodiscover providers have no defined configs. {pull}13078[13078] - Add a check so alias creation explicitely fails if there is an index with the same name. {pull}13070[13070] - Update kubernetes watcher to use official client-go libraries. {pull}13051[13051] - Add support for unix epoch time values in the `timestamp` processor. {pull}13319[13319] - add_host_metadata is now GA. {pull}13148[13148] - Add an `ignore_missing` configuration option the `drop_fields` processor. {pull}13318[13318] - add_host_metadata is no GA. {pull}13148[13148] - Add `registered_domain` processor for deriving the registered domain from a given FQDN. {pull}13326[13326] - Add support for RFC3339 time zone offsets in JSON output. {pull}13227[13227] - Add autodetection mode for add_docker_metadata and enable it by default in included configuration files{pull}13374[13374] - Added `monitoring.cluster_uuid` setting to associate Beat data with specified ES cluster in Stack Monitoring UI. {pull}13182[13182] - Add autodetection mode for add_kubernetes_metadata and enable it by default in included configuration files. {pull}13473[13473] - Add `providers` setting to `add_cloud_metadata` processor. {pull}13812[13812] - Use less restrictive API to check if template exists. {pull}13847[13847] - Do not check for alias when setup.ilm.check_exists is false. {pull}13848[13848] - Add support for numeric time zone offsets in timestamp processor. {pull}13902[13902] - Add condition to the config file template for add_kubernetes_metadata {pull}14056[14056] - Marking Central Management deprecated. {pull}14018[14018] - Add `keep_null` setting to allow Beats to publish null values in events. {issue}5522[5522] {pull}13928[13928] *Auditbeat* - Auditd module: Add `event.outcome` and `event.type` for ECS. {pull}11432[11432] - Process: Add file hash of process executable. {pull}11722[11722] - Socket: Add network.transport and network.community_id. {pull}12231[12231] - Host: Fill top-level host fields. {pull}12259[12259] - Socket: Add DNS enrichment. {pull}14004[14004] *Filebeat* - Add more info to message logged when a duplicated symlink file is found {pull}10845[10845] - Add option to configure docker input with paths {pull}10687[10687] - Add Netflow module to enrich flow events with geoip data. {pull}10877[10877] - Set `event.category: network_traffic` for Suricata. {pull}10882[10882] - Allow custom default settings with autodiscover (for example, use of CRI paths for logs). {pull}12193[12193] - Allow to disable hints based autodiscover default behavior (fetching all logs). {pull}12193[12193] - Change Suricata module pipeline to handle `destination.domain` being set if a reverse DNS processor is used. {issue}10510[10510] - Add the `network.community_id` flow identifier to field to the IPTables, Suricata, and Zeek modules. {pull}11005[11005] - New Filebeat coredns module to ingest coredns logs. It supports both native coredns deployment and coredns deployment in kubernetes. {pull}11200[11200] - New module for Cisco ASA logs. {issue}9200[9200] {pull}11171[11171] - Added support for Cisco ASA fields to the netflow input. {pull}11201[11201] - Configurable line terminator. {pull}11015[11015] - Add Filebeat envoyproxy module. {pull}11700[11700] - Add apache2(httpd) log path (`/var/log/httpd`) to make apache2 module work out of the box on Redhat-family OSes. {issue}11887[11887] {pull}11888[11888] - Add support to new MongoDB additional diagnostic information {pull}11952[11952] - New module `panw` for Palo Alto Networks PAN-OS logs. {pull}11999[11999] - Add RabbitMQ module. {pull}12032[12032] - Add new `container` input. {pull}12162[12162] - Add timeouts on communication with docker daemon. {pull}12310[12310] - `container` and `docker` inputs now support reading of labels and env vars written by docker JSON file logging driver. {issue}8358[8358] - Add specific date processor to convert timezones so same pipeline can be used when convert_timezone is enabled or disabled. {pull}12253[12253] - Add MSSQL module {pull}12079[12079] - Add ISO8601 date parsing support for system module. {pull}12568[12568] {pull}12578[12579] - Update Kubernetes deployment manifest to use `container` input. {pull}12632[12632] - Use correct OS path separator in `add_kubernetes_metadata` to support Windows nodes. {pull}9205[9205] - Add support for virtual host in Apache access logs {pull}12778[12778] - Add support for client addresses with port in Apache error logs {pull}12695[12695] - Add `google-pubsub` input type for consuming messages from a Google Cloud Pub/Sub topic subscription. {pull}12746[12746] - Add module for ingesting Cisco IOS logs over syslog. {pull}12748[12748] - Add module for ingesting Google Cloud VPC flow logs. {pull}12747[12747] - Report host metadata for Filebeat logs in Kubernetes. {pull}12790[12790] - Add netflow dashboards based on Logstash netflow. {pull}12857[12857] - Parse more fields from Elasticsearch slowlogs. {pull}11939[11939] - Update module pipelines to enrich events with autonomous system fields. {pull}13036[13036] - Add module for ingesting IBM MQ logs. {pull}8782[8782] - Add S3 input to retrieve logs from AWS S3 buckets. {pull}12640[12640] {issue}12582[12582] - Add aws module s3access metricset. {pull}13170[13170] {issue}12880[12880] - Update Suricata module to populate ECS DNS fields and handle EVE DNS version 2. {issue}13320[13320] {pull}13329[13329] - Update PAN-OS fileset to use the ECS NAT fields. {issue}13320[13320] {pull}13330[13330] - Add fields to the Zeek DNS fileset for ECS DNS. {issue}13320[13320] {pull}13324[13324] - Add container image in Kubernetes metadata {pull}13356[13356] {issue}12688[12688] - Add timezone information to apache error fileset. {issue}12772[12772] {pull}13304[13304] - Add module for ingesting Cisco FTD logs over syslog. {pull}13286[13286] - Update CoreDNS module to populate ECS DNS fields. {issue}13320[13320] {pull}13505[13505] - Parse query steps in PostgreSQL slowlogs. {issue}13496[13496] {pull}13701[13701] - Add filebeat azure module with activitylogs, auditlogs, signinlogs filesets. {pull}13776[13776] {pull}14033[14033] - Add support to set the document id in the json reader. {pull}5844[5844] - Add input httpjson. {issue}13545[13545] {pull}13546[13546] - Filebeat Netflow input: Remove beta label. {pull}13858[13858] - Remove `event.timezone` from events that don't need it in some modules that support log formats with and without timezones. {pull}13918[13918] - Add ExpandEventListFromField config option in the kafka input. {pull}13965[13965] - Add ELB fileset to AWS module. {pull}14020[14020] - Add module for MISP (Malware Information Sharing Platform). {pull}13805[13805] - Add `source.bytes` and `source.packets` for uni-directional netflow events. {pull}14111[14111] *Heartbeat* - Add non-privileged icmp on linux and darwin(mac). {pull}13795[13795] {issue}11498[11498] - Enable `add_observer_metadata` processor in default config. {pull}11394[11394] - Record HTTP body metadata and optionally contents in `http.response.body.*` fields. {pull}13022[13022] - Allow `hosts` to be used to configure http monitors {pull}13703[13703] *Journalbeat* *Metricbeat* - Add AWS SQS metricset. {pull}10684[10684] {issue}10053[10053] - Add AWS s3_request metricset. {pull}10949[10949] {issue}10055[10055] - Add s3_daily_storage metricset. {pull}10940[10940] {issue}10055[10055] - Add `coredns` metricbeat module. {pull}10585[10585] - Add SSL support for Metricbeat HTTP server. {pull}11482[11482] {issue}11457[11457] - The `elasticsearch.index` metricset (with `xpack.enabled: true`) now collects `refresh.external_total_time_in_millis` fields from Elasticsearch. {pull}11616[11616] - Allow module configurations to have variants {pull}9118[9118] - Add `timeseries.instance` field calculation. {pull}10293[10293] - Added new disk states and raid level to the system/raid metricset. {pull}11613[11613] - Added `path_name` and `start_name` to service metricset on windows module {issue}8364[8364] {pull}11877[11877] - Add check on object name in the counter path if the instance name is missing {issue}6528[6528] {pull}11878[11878] - Add AWS cloudwatch metricset. {pull}11798[11798] {issue}11734[11734] - Add `regions` in aws module config to specify target regions for querying cloudwatch metrics. {issue}11932[11932] {pull}11956[11956] - Keep `etcd` followers members from reporting `leader` metricset events {pull}12004[12004] - Add overview dashboard to Consul module {pull}10665[10665] - New fields were added in the mysql/status metricset. {pull}12227[12227] - Add Kubernetes metricset `proxy`. {pull}12312[12312] - Add Kubernetes proxy dashboard to Kubernetes module {pull}12734[12734] - Always report Pod UID in the `pod` metricset. {pull}12345[12345] - Add Vsphere Virtual Machine operating system to `os` field in Vsphere virtualmachine module. {pull}12391[12391] - Add validation for elasticsearch and kibana modules' metricsets when xpack.enabled is set to true. {pull}12386[12386] - Add CockroachDB module. {pull}12467[12467] - Add support for metricbeat modules based on existing modules (a.k.a. light modules) {issue}12270[12270] {pull}12465[12465] - Add a system/entropy metricset {pull}12450[12450] - Add kubernetes metricset `controllermanager` {pull}12409[12409] - Add Kubernetes controller manager dashboard to Kubernetes module {pull}12744[12744] - Allow redis URL format in redis hosts config. {pull}12408[12408] - Add tags into ec2 metricset. {issue}[12263]12263 {pull}12372[12372] - Add metrics to kubernetes apiserver metricset. {pull}12922[12922] - Add kubernetes metricset `scheduler` {pull}12521[12521] - Add Kubernetes scheduler dashboard to Kubernetes module {pull}12749[12749] - Add `beat` module. {pull}12181[12181] {pull}12615[12615] - Collect tags for cloudwatch metricset in aws module. {issue}[12263]12263 {pull}12480[12480] - Add AWS RDS metricset. {pull}11620[11620] {issue}10054[10054] - Add Oracle Module {pull}11890[11890] - Add Oracle Tablespaces Dashboard {pull}12736[12736] - Collect client provided name for rabbitmq connection. {issue}12851[12851] {pull}12852[12852] - Add support to load default aws config file to get credentials. {pull}12727[12727] {issue}12708[12708] - Add statistic option into cloudwatch metricset. {issue}12370[12370] {pull}12840[12840] - Add support for kubernetes cronjobs {pull}13001[13001] - Add cgroup memory stats to docker/memory metricset {pull}12916[12916] - Add AWS elb metricset. {pull}12952[12952] {issue}11701[11701] - Add AWS ebs metricset. {pull}13167[13167] {issue}11699[11699] - Add `metricset.period` field with the configured fetching period. {pull}13242[13242] {issue}12616[12616] - Add rate metrics for ec2 metricset. {pull}13203[13203] - Add refresh list of perf counters at every fetch {issue}13091[13091] - Add Performance metricset to Oracle module {pull}12547[12547] - Add proc/vmstat data to the system/memory metricset on linux {pull}13322[13322] - Use DefaultMetaGeneratorConfig in MetadataEnrichers to initialize configurations {pull}13414[13414] - Add module for statsd. {pull}13109[13109] - Add support for NATS version 2. {pull}13601[13601] - Add `docker.cpu.*.norm.pct` metrics for `cpu` metricset of Docker Metricbeat module. {pull}13695[13695] - Add `instance` label by default when using Prometheus collector. {pull}13737[13737] - Add azure module. {pull}13196[13196] {pull}13859[13859] {pull}13988[13988] - Add Apache Tomcat module {pull}13491[13491] - Add ECS `container.id` and `container.runtime` to kubernetes `state_container` metricset. {pull}13884[13884] - Add `job` label by default when using Prometheus collector. {pull}13878[13878] - Add `state_resourcequota` metricset for Kubernetes module. {pull}13693[13693] - Add tags filter in ec2 metricset. {pull}13872[13872] {issue}13145[13145] - Add cloud.account.id and cloud.account.name into events from aws module. {issue}13551[13551] {pull}13558[13558] - Add `metrics_path` as known hint for autodiscovery {pull}13996[13996] - Leverage KUBECONFIG when creating k8s client. {pull}13916[13916] - Add ability to filter by tags for cloudwatch metricset. {pull}13758[13758] {issue}13145[13145] - Add Oracle overview dashboard {pull}14021[14021] *Packetbeat* - Update DNS protocol plugin to produce events with ECS fields for DNS. {issue}13320[13320] {pull}13354[13354] *Functionbeat* - New options to configure roles and VPC. {pull}11779[11779] - Export automation templates used to create functions. {pull}11923[11923] - Configurable Amazon endpoint. {pull}12369[12369] - Add timeout option to reference configuration. {pull}13351[13351] - Configurable tags for Lambda functions. {pull}13352[13352] - Add input for Cloudwatch logs through Kinesis. {pull}13317[13317] - Enable Logstash output. {pull}13345[13345] - Make `bulk_max_size` configurable in outputs. {pull}13493[13493] *Winlogbeat* - Add support for reading from .evtx files. {issue}4450[4450] - Add support for event ID 4634 and 4647 to the Security module. {pull}12906[12906] - Add `network.community_id` to Sysmon network events (event ID 3). {pull}13034[13034] - Add `event.module` to Winlogbeat modules. {pull}13047[13047] - Add `event.category: process` and `event.type: process_start/process_end` to Sysmon process events (event ID 1 and 5). {pull}13047[13047] - Add support for event ID 4672 to the Security module. {pull}12975[12975] - Add support for event ID 22 (DNS query) to the Sysmon module. {pull}12960[12960] - Add certain winlog.event_data.* fields to the index template. {issue}13700[13700] {pull}13704[13704] - Fill `event.provider`. {pull}13937[13937] - Add support for user management events to the Security module. {pull}13530[13530] ==== Deprecated *Affecting all Beats* *Filebeat* - `docker` input is deprecated in favour `container`. {pull}12162[12162] - `postgresql.log.timestamp` field is deprecated in favour of `@timestamp`. {pull}12338[12338] *Heartbeat* *Journalbeat* *Metricbeat* - `kubernetes.container.id` field for `state_container` is deprecated in favour of ECS `container.id` and `container.runtime`. {pull}13884[13884] *Packetbeat* *Winlogbeat* *Functionbeat* ==== Known Issue *Journalbeat* ",12449,True,2865.9426630606904,median "= DataGrid ++++ ++++ `DataGrid`, similarly to the xref:vcl/components/table.adoc[Table] component, is designed to display and sort tabular data and provides means to manipulate rows and columns with greater performance due to the lazy loading of data while scrolling. In addition to this, `DataGrid` has the following features: * <>; * <>; * Advanced configuration of <>; * <>. However, `DataGrid` has no corresponding implementation with grouping capabilities (but `Table` xref:vcl/components/group-table.adoc[has]). Component’s XML-name: `dataGrid`. [[basics]] == Basics A typical `dataGrid` is shown below: image::vcl/components/data-grid-anatomy.png[align=""center""] . Buttons panel . Sort button . Pagination . Column control button . Rows . Header row An example of `dataGrid` declaration in the XML screen descriptor is shown below: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;collection-customers;data-end;layout-start;data-grid-simple;layout-end;] ---- In the example, there is a xref:data/collection-container.adoc[collection container] for the `Customer` entity. The `DataGrid` component is bound to the container using the `dataContainer` attribute, while its `columns` element defines which entity attributes are shown in the data grid columns. [[data-binding]] == Data Binding [[declarative-binding]] === Declarative Binding Usually, you bind `dataGrid` to data declaratively in the screen XML descriptor using the `dataContainer` attribute. It should refer to a xref:data/collection-container.adoc[collection container]. [[using-key-value-containers]] === Using Key-Value Containers You can bind the data grid to a xref:data/key-value-containers.adoc[key-value container] to display the results of a query that returns scalar values and/or aggregates. For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;key-value-collection-sales;data-end;layout-start;key-value-grid;layout-end;] ---- [[meta-class]] === Programmatic Binding If you need to define a data container programmatically in the screen controller, set the xref:vcl/xml.adoc#meta-class[metaClass] attribute instead of xref:vcl/xml.adoc#data-container[dataContainer] in XML descriptor: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=meta-class-data-grid] ---- In the screen controller, use `ContainerDataGridItems` class to bind the data grid to a data container: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-customersDataGrid;inject-customersDc;init-start;programmatic-binding;init-end] ---- [[columns]] == Columns The set of columns for a data grid is defined in the `columns` element. If it is not specified, columns will be automatically determined by the xref:data-access:fetching.adoc#fetch-plan[fetch plan] defined in `dataContainer`. The `columns` element can have the following attributes: [[include-all]] * `includeAll` includes all the attributes from `fetchPlan` that is defined in `dataContainer`. + In the example below, we will show all the attributes from the fetch plan used in `customersDc`: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=columns-include-all] ---- + If the entity fetch plan contains a reference attribute, this attribute will be displayed according to its xref:data-model:entities.adoc#instance-name[instance name]. If you want to show a specific nested attribute, define it in the fetch plan as well as in the `column` element: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=data-start;collection-customers-with-country;data-end;layout-start;columns-include-all-reference;layout-end] ---- [[exclude]] * `exclude` contains a comma-separated list of attributes that should not be displayed in the data grid. + In the example below, we will show all the attributes excluding `id`, `maritalStatus`, and `email`: + [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=columns-exclude] ---- [[column]] === Column Each column is described in a nested `column` element. [[column-id]] `id` - an optional attribute specifying the column identifier. If not set, the value of the `property` attribute is used as the column identifier. If neither `id` nor `property` attribute is specified, the `GuiDevelopmentException` exception is thrown at runtime. The `id` attribute is mandatory for <>. [[column-property]] `property` specifies the name of an entity attribute displayed in the column. It can be either an attribute of the entity from the data container or a linked entity (use dot notation to traverse the object graph). For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-column] ---- [[column-caption-options]] === Column Caption [[column-caption]] `caption` - an optional attribute containing the column caption. If not specified, a xref:localization:message-bundles.adoc#localizing-data-model[localized name] of the entity attribute is used. This caption is also used as the hiding toggle caption unless explicitly set via the <> attribute. [[column-collapsing]] === Column Collapsing [[column-collapsed]] `collapsed` - an optional attribute; hides the column by default when set to `true`. Users can control the column’s visibility using the menu available via the image:vcl/components/table-column-control-button.png[] button in the top right corner of the data grid when the <> attribute is `true`. By default, `collapsed` is `false`. [[column-collapsible]] The `collapsible` attribute defines whether a user can hide or show columns using the column control button. The default value is `true`. [[collapsing-toggle-caption]] The `collapsingToggleCaption` attribute sets the column’s caption in the column control menu. By default, its value is `null`; in this case, the caption remains the same as the column’s <>. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-collapsed] ---- image::vcl/components/data-grid-collapse.gif[align=""center""] As you can see, the `age` column is collapsed by default, but users can expand it from the image:vcl/components/table-column-control-button.png[] button's drop-down menu. At the same time, the `firstName` and `lastName` columns cannot be collapsed by the user. The custom caption for the `hobby` column is shown in the drop-down menu of the column control button. The column collapsing can be tracked with <>. [[column-width]] === Column Width `width` - an optional attribute controlling the default column width. It may contain only numeric values in pixels. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-width] ---- image::vcl/components/data-grid-column-width.png[align=""center""] [[column-expand-ratio]] `expandRatio` - an optional attribute that specifies the expand ratio for each column. The ratio must be greater than or equal to 0. If some value is set for at least one column, all implicit values are ignored, and only explicitly assigned values are considered. By default, all columns expand equally (treated as if all of them had the expand ratio of `1`). If you set `width` and `expandRatio` attributes simultaneously, the `expandRatio` attribute will be ignored. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-expandRatio-column] ---- image::vcl/components/data-grid-ratio.png[align=""center""] In the example above, the `DataGrid` component has three columns, with expand ratios `0`, `1`, and `2`, respectively. The column with a ratio of `0` is exactly as wide as its contents require. The column with a ratio of `1` is as wide as it needs, plus a third of any excess space, because we have three parts total, and this column reserves only one of those. The column with a ratio of `2` is as wide as it needs to be, plus two thirds of the excess width. To clear the expand value, set a negative number to an `expandRatio` attribute. [[column-minimum-width]] The `minimumWidth` attribute defines the minimum guaranteed pixel width of the column when it is set to expand. The default value of minimum column width is specified in the xref:app-properties.adoc#jmix.ui.data-grid.default-column-min-width[jmix.ui.data-grid.default-column-min-width] property. [[column-maximum-width]] The `maximumWidth` attribute defines the maximum allowed pixel width of the column when it is set to expand. The default value of maximum column width is specified in the xref:app-properties.adoc#jmix.ui.data-grid.default-column-max-width[jmix.ui.data-grid.default-column-max-width] property. [[column-resizable]] === Column Resizing Users can resize data grid columns: image::vcl/components/data-grid-resize.gif[align=""center""] The `resizable` attribute defines whether users can resize this column. By default, all columns are resizable. [[column-resize-mode]] Use the `columnResizeMode` attribute to specify the resize mode. Two modes are supported: * In the `ANIMATED` mode, the grid redraws its columns continuously when users resize columns. * In the `SIMPLE` mode, the grid redraws columns only when the user releases the mouse button. The column size changes can be tracked with <>. [[reordering-allowed]] === Column Reordering `DataGrid` provides the drag-and-drop functionality allowing users to change the order in which columns are displayed within the data grid. // TODO: поменять тут скриншот. Этот от компонента Table. Жду решения тикета https://github.com/Haulmont/jmix-ui/issues/623 image::vcl/components/table-columns-reordering.gif[align=""center""] The column reordering functionality is enabled by default. To disable it, set the `reorderingAllowed` attribute to `false`. The column order changes can be tracked with <>. [[column-freezing]] === Column Freezing `DataGrid` allows you to anchor columns to its left side. It can help keep the essential columns always visible in a grid with a large number of columns. Frozen columns are not scrolled when you scroll the grid horizontally. The `frozenColumnCount` attribute sets the number of fixed columns. The `0` value means that no columns will be fixed except the predefined column with checkboxes for multiple-choice if the <> is used. The `-1` value makes even a multi-select column not fixed. The default value is `0`. Let's consider an example with a data grid where the first two columns are frozen. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-frozen-column] ---- image::vcl/components/data-grid-frozen.gif[align=""center""] == Sizes === Grid Sizing In addition to the xref:vcl/xml.adoc#height[height] and xref:vcl/xml.adoc#width[width] attributes, `DataGrid` has the `minHeight` and `minWidth` optional attributes: [[min-height]] * `minHeight` is used to set the minimum height of the `DataGrid` component. [[min-width]] * `minWidth` is used to set the minimum width of the `DataGrid` component. === Column Sizing See the `width`, `expandRatio`, `minimumWidth` and `maximumWidth` attributes in the <> section. === Row Sizing To set the header row height, use the <> attribute. [[body-row-height]] Use the `bodyRowHeight` attribute to set the height of a body rows in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. To set the footer row height, use the <> attribute. In the example below, we will show the `DataGrid` component with a custom height of a header and body rows: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=sized-grid] ---- image::vcl/components/data-grid-custom-row-height.png[align=""center""] [[selection]] == Selection The `DataGrid` component allows users to select single or multiple rows. [[selection-mode]] The `selectionMode` attribute sets the rows selection mode. There are 4 predefined selection modes: * `SINGLE`; * `MULTI`; * `MULTI_CHECK`; * `NONE`. Rows selection events can be tracked by <>. [[single-selection]] === Single Selection Mode Set the `selectionMode` attribute to the `SINGLE` value to allow users to select a single row at a time. Single selection mode is enabled by default. [[multi-selection]] === Multi Selection Mode If the `selectionMode` attribute is set to `MULTI`, users can select multiple rows in the grid using a keyboard or mouse and holding *Ctrl* or *Shift* keys. [[checkbox-selection]] === Checkbox Selection Mode If the `selectionMode` attribute is set to `MULTI_CHECK`, users can select multiple rows using the leftmost column with checkboxes. image::vcl/components/data-grid-checkbox-select.png[align=""center""] [[none-selection]] === Disabling Selection If the `selectionMode` attribute is set to `NONE`, the selection is disabled. [[text-selection-enabled]] === Text Selection The `textSelectionEnabled` attribute defines if text selection is enabled in grid cells. The default value is `false`. == Placeholder `DataGrid` allows you to set a placeholder message and/or link, shown when the data container is empty or not set at all. [[empty-state-message]] The placeholder message is defined using the `emptyStateMessage` attribute. It should contain information about why the grid is empty. [[empty-state-link-message]] The placeholder link is defined using the `emptyStateLinkMessage` attribute. It should describe the action that needs to be performed to fill the grid. For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=placeholder-grid] ---- image::vcl/components/data-grid-placeholder.png[align=""center""] Both `emptyStateMessage` and `emptyStateLinkMessage` can load messages from the xref:localization:message-bundles.adoc#using-messages-in-ui[message bundle]. To handle clicks on the link, use <>. [[column-collapsing-allowed]] == Column Control Visibility Users can select which columns are <> using the column control button image:vcl/components/table-column-control-button.png[] in the right part of the data grid header. Currently displayed columns are marked in the drop-down menu. There are additional menu items: * `Select all` - shows all data grid columns; * `Deselect all` - hides all columns that are possible. image::vcl/components/data-grid-column-collapsing-allowed.png[align=""center""] If the `columnsCollapsingAllowed` attribute is set to `false`, users cannot collapse columns. The default value is `true`. [[headers-footers]] == Headers and Footers [[header-visible]] The `headerVisible` attribute defines whether the `DataGrid` header is visible. The default value is `true`. [[header-row-height]] Use the `headerRowHeight` attribute to set the height of a header row in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. The default value is `-1`. [[footer-visible]] The `footerVisible` attribute defines whether the `DataGrid` footer is visible. The default value is `true`. [[footer-row-height]] Use the `footerRowHeight` attribute to set the height of a footer row in pixels. If the value is `-1`, the row height is calculated based on the theme for an empty row before the `DataGrid` is displayed. The default value is `-1`. `HeaderRow` and `FooterRow` interfaces are used to represent header and footer cells respectively. These cells may be merged for multiple columns. The following methods of `DataGrid` allow you to create and manage the `DataGrid` header and footer: * `appendHeaderRow()`, `appendFooterRow()` - adds a new row at the bottom of the header/footer section. * `prependHeaderRow()`, `prependFooterRow()` - adds a new row at the top of the header/footer section. * `addHeaderRowAt()`, `addFooterRowAt()` - inserts a new row at the given position to the header/footer section. Shifts the row currently at that position and any subsequent rows down incrementing their indices. * `removeHeaderRow()`, `removeFooterRow()` - removes the given row from the header/footer section. * `getHeaderRowCount()`, `getFooterRowCount()` - gets the row count for the header/footer section. * `setDefaultHeaderRow()` - sets the default row of the header. The default row is a special header row providing a user interface for sorting columns. `HeaderCell` and `FooterCell` interfaces provide means of customization of static `DataGrid` cells: * `setStyleName()` - sets a custom style name for this cell. * `getCellType()` - returns the type of content stored in this cell. There are 3 types of `DataGridStaticCellType` enumeration available: ** `TEXT` ** `HTML` ** `COMPONENT` * `getComponent()`, `getHtml()`, `getText()` - returns the content displayed in this cell depending on its type. Below is an example of `DataGrid` with the header that contains merged cells and the footer displaying calculated values. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-header-footer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=init-footer-header-var;init-start;init-footer-header;init-end;init-footer;init-header;get-average;calculate-member-count] ---- image::vcl/components/data-grid-header-footer.png[align=""center""] [[aggregatable]] == Aggregating `DataGrid` supports the aggregation of values in rows. The following operations are supported: * `SUM` - calculate the sum; * `AVG` - calculate the average value; * `COUNT` - calculate the total number; * `MIN` - find the minimum value; * `MAX` - find the maximum value. To enable aggregation for a data grid, you should: . Set the `aggregatable` attribute to `true`. . Set the `aggregation` element for aggregated grid columns. + [[aggregation-type]] . Set the `type` attribute for the `aggregation` element, which defines the aggregation function. The aggregated values are shown in an additional row. [[aggregation-position]] The `aggregationPosition` attribute allows you to specify the location of the aggregation row: `TOP` or `BOTTOM`. `TOP` is used by default. [NOTE] ==== By default, only numeric data types are supported in aggregated columns, such as `Integer`, `Double`, `Long`, and `BigDecimal`. ==== An example of an aggregated data grid description: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=aggregation-grid] ---- image::vcl/components/data-grid-aggregation.png[align=""center""] [[aggregation-value-description]] The `valueDescription` attribute defines a hint displayed in a popup when a user hovers the mouse cursor on the aggregated value. For the operations listed above (`SUM`, `AVG`, `COUNT`, `MIN`, `MAX`), popup hints are already available by default. [[aggregation-formatter]] You can specify xref:vcl/miscellaneous/formatter.adoc[formatter] to display the aggregated value in the format other than the standard for this `Datatype`: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-aggregation-format] ---- [[aggregation-strategy-class]] The `aggregation` element can also contain the `strategyClass` attribute specifying a class implementing the `AggregationStrategy` interface. [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/CustomerHobbyAggregation.java[tags=aggregation-strategy] ---- [source,xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-aggregation-strategy] ---- [[grid-sorting]] == Sorting `DataGrid` allows users to sort column data. Sorting functionality is enabled by default. The `sortable` attribute enables sorting data in the grid. By default, it is set to `true`. If sorting is allowed, clicking a column header will show a image:vcl/components/table-sortable-down.png[]/image:vcl/components/table-sortable-up.png[] icon to the right of the column name. [[column-sortable]] You can disable sorting for a particular <> by using its `sortable` attribute. In the example below, we disable sorting by the `lastName` column: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-sorting] ---- [[column-sort]] The `sort` attribute of the `column` element allows you to set the initial sorting direction of the data grid by this `column`. Possible values: * `ASCENDING` - ascending order (0 -> 9 -> A -> Z). * `DESCENDING` - descending order (Z -> A -> 9 -> 0). For example: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-sort] ---- [CAUTION] ==== `DataGrid` can be sorted only by one column at a time. If you set the `sort` attribute for multiple columns or set `sort` and `sortable=""false""` attributes simultaneously, the screen will fail. ==== The `DataGrid` sorting events can be tracked by <>. [[paging]] == Paging The xref:vcl/components/simple-pagination.adoc[] component can be used inside `dataGrid` to provide pagination: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-paging] ---- image::vcl/components/data-grid-pagination.png[align=""center""] Alternatively, you can use the standalone xref:vcl/components/pagination.adoc[] component. [[actions]] == DataGrid Actions The `DataGrid` component implements the `ActionsHolder` interface and can contain custom actions, as well as xref:actions/standard-actions.adoc#list-actions[standard list actions]. Data grid actions are defined in the nested `actions` element. If an action has a caption, it is displayed as an item of the data grid <>. Additionally, a data grid action can be assigned to a button located anywhere on the screen. [[buttons-panel]] You can use the xref:vcl/containers/buttons-panel.adoc[ButtonsPanel] container to show action buttons above the data grid. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-actions-buttons-panel] ---- <1> Define the `create` standard action. <2> Define the `about` custom action. <3> Define a `ButtonsPanel` container inside a data grid. image::vcl/components/data-grid-actions.png[align=""center""] [[data-grid-column-generation]] == Column Generation The `ColumnGeneratorEvent` handler allows you to add generated, or calculated, columns and define a custom representation of data in a column. The handler is invoked by the framework for each cell when rendering the data grid. `ColumnGeneratorEvent` contains information on the entity, displayed in the current `DataGrid` row, and the column identifier. You can create the `ColumnGeneratorEvent` handler for a data grid column using Studio. To do this, you should choose a generated type from the list suggested by Studio and the corresponding type of <>. As an example, let's create a generated column containing the full name of the customer. First, create a column with the `fullName` id: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=text-renderer] ---- Then create the `ColumnGeneratorEvent` handler for the `fullName` column using Studio and implement it as follows: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-generator] ---- The result: image::vcl/components/data-grid-generated-column.png[align=""center""] The `fullName` column is a generated column with <>. To register the column generator handler programmatically, use the `addGeneratedColumn()` method of the `DataGrid` component. [[renderers]] == Renderers The way the data is displayed in columns can be customized using parameterized declarative renderers. Some `DataGrid` renderers are set by special XML elements with parameters defined in the corresponding attributes. Renderers can be declared both for regular and generated columns. The framework provides the following renderers: * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> [[button-renderer]] === ButtonRenderer `ButtonRenderer` displays string values as a button caption. `ButtonRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ButtonRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-gridButtonRenderer;inject-notifications;init-start;button-renderer;init-end] ---- image::vcl/components/data-grid-button-renderer.png[align=""center""] [[image-renderer]] === ImageRenderer `ImageRenderer` is a renderer for presenting images. The value of the corresponding property is used as the image location. Location can be a theme resource or URL. `ImageRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ImageRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-imageGrid;inject-notifications;init-start;image-renderer;init-end] ---- The result: image::vcl/components/data-grid-image-renderer.png[align=""center""] [[check-box-renderer]] === CheckBoxRenderer `CheckBoxRenderer` displays boolean values as a checkbox icon. The `column` element of `DataGrid` has a child `checkBoxRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-check-box-renderer] ---- [[number-renderer]] === NumberRenderer `NumberRenderer` displays numbers in the defined format. The `column` element of `DataGrid` has a child `numberRenderer` element with the optional `nullRepresentation` attribute and required `format` string attribute. [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-number-renderer] ---- `formatString` is the format string describing the number format which will be used to create the `NumberFormat` instance. [[local-date-time-renderer]] === LocalDateTimeRenderer `LocalDateTimeRenderer` displays dates as `LocalDateTime` values. The `column` element of `DataGrid` has a child `localDateTimeRenderer` element with the optional `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-local-date-time-renderer] ---- [[local-date-renderer]] === LocalDateRenderer `LocalDateRenderer` displays dates as `LocalDate` values. The `column` element of `DataGrid` has a child `localDateRenderer` element with the optional `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-local-date-renderer] ---- The result: image::vcl/components/data-grid-local-date-renderer.png[align=""center""] [[date-renderer]] === DateRenderer `DateRenderer` displays dates in the defined format. The `column` element of `DataGrid` has a child `dateRenderer` element with the optional `nullRepresentation` attribute and required `format` string attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-date-renderer] ---- `formatString` is the format string describing the date and time format used to create the `DateFormat` instance. image::vcl/components/data-grid-date-renderer.png[align=""center""] Please notice that the `startDate` field has a `DateRenderer`, and the `endDate` field has not. [[progress-bar-renderer]] === ProgressBarRenderer `ProgressBarRenderer` displays `double` values between 0 and 1 as a `ProgressBar` component. The `column` element of `DataGrid` has a child `progressBarRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-progress-bar-renderer] ---- The result: image::vcl/components/data-grid-progress-bar-renderer.png[align=""center""] [[html-renderer]] === HtmlRenderer `HtmlRenderer` displays HTML layout. The `column` element of `DataGrid` has a child `htmlRenderer` element with the optional `nullRepresentation` attribute. Below is an example of rendering the `endDate` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-html-renderer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=html-renderer] ---- The result: image::vcl/components/data-grid-html-renderer.png[align=""center""] [[clickable-text-renderer]] === ClickableTextRenderer `ClickableTextRenderer` displays simple plain-text string values as a link with a click listener. `ClickableTextRenderer` cannot be declared in the XML descriptor because it is not possible to define a renderer click listener in the XML descriptor. Studio will generate the `ClickableTextRenderer` declaration code in the `onInit()` screen controller method, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-gridClick;inject-notifications;init-start;clickable-text-renderer;init-end] ---- The result: image::vcl/components/data-grid-click-text-renderer.gif[align=""center""] [[text-renderer]] === TextRenderer `TextRenderer` is a renderer for presenting simple plain-text string values. The `column` element of `DataGrid` has a child `textRenderer` element with non-required `nullRepresentation` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=text-renderer] ---- [[component-renderer]] === ComponentRenderer `ComponentRenderer` is a renderer for UI components. The `column` element of `DataGrid` has a child `componentRenderer` element: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-component-renderer] ---- In the example below, we will display the `age` value in the `Slider` component. [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=component-renderer] ---- The result: image::vcl/components/data-grid-component-renderer.png[align=""center""] [[icon-renderer]] === IconRenderer `IconRenderer` is a renderer that represents `JmixIcon`. The `column` element of `DataGrid` has a child `iconRenderer` element. Below is an example of rendering a generated `hasEmail` attribute: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-icon-renderer] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=icon-renderer] ---- The result: image::vcl/components/data-grid-icon-renderer.png[align=""center""] [[item-details-generator]] == Item Details Generator Item details are expandable content areas used to display more information for a specific row. The `DetailsGenerator` interface allows you to create a custom component to display item details. You can create the `DetailsGenerator` handler for `DataGrid` using Studio (see <>) and implement it as follows: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-detailsGrid;details-generator;create-close-button;get-content] ---- To handle showing and hiding the details you should implement your own listener. For instance, in this sample, we handle opening the details in the `ItemClickAction` of the `DataGrid` component: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=item-click-event] ---- The result: image::vcl/components/data-grid-detail-generator.png[align=""center""] [[editing]] == Editing Values [[editor-enabled]] `DataGrid` provides inline editing that allows users to manipulate grid data. To enable inline editing, set the `editorEnabled` attribute to `true`. === Usage * Inline editing can be instantiated by double-clicking on the field to be edited or pressing *Enter* when an editable cell is focused. [[column-editable]] * The columns with `editable = true` attribute show components to edit the attributes of the corresponding entity. Non-editable fields will be disabled. * The component type for each editable column is selected automatically based on the type of the corresponding entity attribute. For example, for string and numeric attributes, the application will use xref:vcl/components/text-field.adoc[TextField], for `Date` - xref:vcl/components/date-field.adoc[DateField], for enumerations - xref:vcl/components/combo-box.adoc[ComboBox], for links to other entities - xref:vcl/components/entity-picker.adoc[EntityPicker]. * Once a row becomes editable, default *OK* and *Cancel* buttons will appear near the row allowing users to commit or cancel the edit. * To save the changes and exit edit mode, click the *OK* button or press *Enter*. * To discard the changes and exit edit mode, click the *Cancel* button or press *Esc*. image::vcl/components/data-grid-editing.png[align=""center""] [[editor-buffered]] === Modes Editing can be either buffered and non-buffered. * In the buffered mode, changes must be explicitly committed. * Non-buffered editing automatically commits changes when a field loses focus. The `editorBuffered` attribute sets the buffered editor mode. The default value is `true`. The changes are committed to the data container only. Saving of changes to the database is usually performed by xref:data/data-context.adoc[] on the screen commit. === Inline Editor Customizing [[editor-cancel-caption]] The `editorCancelCaption` attribute sets the caption on the cancel button in the `DataGrid` editor. [[editor-save-caption]] The `editorSaveCaption` attribute sets the caption on the save button in the `DataGrid` inline editor. [[edit-field-generator]] The editor field can be customized with the help of `EditorFieldGenerationContext` class. You should create an edit field generator that generates a component for this column in `DataGrid` editor, for example: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=inject-citiesDc;edit-field-generator] ---- The result: image::vcl/components/data-grid-edit-field-generator.png[align=""center""] There is also a declarative way of defining what component to use for selecting an entity in generic mechanisms. It is based on the xref:app-properties.adoc#jmix.ui.component.entity-field-type[jmix.ui.component.entity-field-type] and xref:app-properties.adoc#jmix.ui.component.entity-field-actions[jmix.ui.component.entity-field-actions] properties. For example, if you add the following lines to the `application.properties` file: [source,properties] ---- jmix.ui.component.entity-field-type.uiex1_City = entityComboBox jmix.ui.component.entity-field-actions.uiex1_City = entity_lookup, entity_open, entity_clear ---- Then the `EntityComboBox` component will be generated for the `City` entity: image::vcl/components/data-grid-editable-custom-field.png[align=""center""] [[editor-cross-field-validate]] === Cross Field Validation `DataGrid` inline editor can take into account entity constraints (cross-field validation). If there are validation errors, `DataGrid` will show an error message. To enable or disable validation, use the `editorCrossFieldValidate` attribute. The default value is `true`. === Editor Events Editor events provide access to the components used in the editor, allowing you to change or use their values. [[editor-open-event]] * `EditorOpenEvent` is an event that is fired before the `DataGrid` editor is opened. + For example: + [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=editor-open-event] ---- [[editor-close-event]] * `EditorCloseEvent` is an event that is fired when the `DataGrid` editor is closed. [[editor-pre-commit-event]] * `EditorPreCommitEvent` is an event that is fired before the item is updated. [[editor-post-commit-event]] * `EditorPostCommitEvent` is an event that is fired after the item is updated. === Methods of Inline Editor [[method-get-edited-item]] * `getEditedItem()` returns the item that is currently being edited or `null` if no item is being edited at the moment. [[method-is-editor-active]] * `isEditorActive()` returns whether an item is currently being edited in the editor. [[method-edit]] * The `edit()` method opens the editor interface for the provided entity. Scrolls `DataGrid` to bring the entity to view if it is not already visible. [[context-menu-enabled]] == Context Menu The context menu is activated by right-clicking within the data grid. The `contextMenuEnabled` attribute enables the context menu. By default, this attribute is set to `true`. The context menu shows <> (if any). The right mouse clicks on the data grid can be tracked with <>. [[stylename]] == Styling You can set predefined styles to the `DataGrid` component using the `stylename` attribute either in the XML descriptor or in the screen controller: [source, xml,indent=0] ---- include::example$/ex1/src/main/resources/ui/ex1/screen/component/datagrid/data-grid-screen.xml[tags=grid-stylename] ---- [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=set-style-name] ---- Predefined styles: * `borderless` - removes the outer border of the data grid; * `no-horizontal-lines` - removes the horizontal divider lines between the data grid rows; * `no-vertical-lines` - remove the vertical divider lines between the data grid columns. * `no-stripes` - removes the alternating row colors. The appearance of the `DataGrid` component can be customized using SCSS variables with the `$jmix-datagrid-*` prefix. You can change these variables in the visual editor after creating a xref:themes/custom_theme.adoc[custom theme]. See also <>. [[methods]] == Methods of DataGrid Interface [[methods-get-columns]] * `getColumns()` returns a copy of currently configured columns in their current visual order in this `DataGrid`. [[methods-get-visible-columns]] * `getVisibleColumns()` returns a copy of columns not hidden by security permissions. [[methods-sort]] * The `sort()` method <> the `DataGrid` data for the specified column in the chosen sort direction. [[methods-scroll-to]] * `scrollTo()` allows you to scroll the `DataGrid` to the specified row. It takes an entity instance identifying the row as a parameter. Besides the entity instance, an overloaded method can take a `ScrollDestination` parameter with the following possible values: ** `ANY` - scroll as little as possible to show the target element. If the element fits into view, this works as `START` or `END`, depending on the current scroll position. If the element does not fit into view, this works as `START`. ** `START` - scrolls so that the element is shown at the start of the viewport. The viewport will, however, not scroll beyond its contents. ** `MIDDLE` - scrolls so that the element is shown in the middle of the viewport. However, the viewport will not scroll beyond its contents, given more elements than what the viewport can show at once. Under no circumstances will the viewport scroll before its first element. ** `END` - scrolls so that the element is shown at the end of the viewport. The viewport will, however, not scroll before its first element. [[methods-scroll-to-start-end]] * `scrollToStart()` and `scrollToEnd()` - scroll `DataGrid` to the first data item and to last data item respectively. [[methods-get-aggregation-results]] * The `getAggregationResults()` method returns a map with <> results, where map keys are data grid column identifiers and values are aggregation values. [[handlers]] == Events and Handlers include::../events-hanlers-generation-tip.adoc[] [[column-collapsing-change-event]] === ColumnCollapsingChangeEvent `ColumnCollapsingChangeEvent` is sent when a column's <> changes. Example of subscribing to the event for the data grid defined in the screen XML with the `collapseGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-collapsing-change-event] ---- To register the event handler programmatically, use the `addColumnCollapsingChangeListener()` component method. [[column-reorder-event]] === ColumnReorderEvent See xref:vcl/components/table.adoc#column-reorder-event[ColumnReorderEvent]. [[column-resize-event]] === ColumnResizeEvent `ColumnResizeEvent` is sent when a column is <>. Example of subscribing to the event for the data grid defined in the screen XML with the `resizedEventGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=column-resize-event] ---- To register the event handler programmatically, use the `addColumnResizeListener()` component method. [[context-click-event]] === ContextClickEvent `ContextClickEvent` happens when a context-click occurs on the client-side inside `DataGrid`. `ContextClickEvent` contains information about mouse event details. Example of subscribing to the event for the data grid defined in the screen XML with the `contextGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=context-click-event] ---- To register the event handler programmatically, use the `addContextClickListener()` component method. === EditorCloseEvent See <>. === EditorOpenEvent See <>. === EditorPostCommitEvent See <>. === EditorPreCommitEvent See <>. [[item-click-event]] === ItemClickEvent `ItemClickEvent` is sent when the user clicks on a data grid. `ItemClickEvent` contains information about: * Mouse event details; * An entity instance represented by the clicked row; * An item `id`; * `id` of the clicked `DataGrid` column. As an example, we will give the user to begin <> by single-clicking on an editable cell: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=item-click-event2] ---- To register the event handler programmatically, use the `addItemClickListener()` component method. [[selection-event]] === SelectionEvent See xref:vcl/components/table.adoc#selection-event[SelectionEvent]. [[sort-event]] === SortEvent `SortEvent` is sent when a <> order is changed. Example of subscribing to the event for the data grid defined in the screen XML with the `sortGrid` id: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=sort-event] ---- To register the event handler programmatically, use the `addSortListener()` component method. [[context-help-icon-click-handler]] === ContextHelpIconClickHandler See xref:vcl/api.adoc#context-help-icon-click-handler[ContextHelpIconClickHandler]. [[details-generator]] === DetailsGenerator See <>. [[empty-state-link-click-handler]] === EmptyStateLinkClickHandler See xref:vcl/components/table.adoc#empty-state-click-event[EmptyStateLinkClickHandler]. [[lookup-select-handler]] === LookupSelectHandler See xref:vcl/components/table.adoc#lookup-select-handler[LookupSelectHandler]. [[row-description-provider]] === RowDescriptionProvider `RowDescriptionProvider` generates optional descriptions (tooltips) when the user hovers over a `DataGrid` row. If `DescriptionProvider` for a column is also set, the row description generated by `RowDescriptionProvider` is used for cells for which the cell description provider returns `null`. In the example below, we will show a `RowDescriptionProvider` usage for the `rowDescGrid`: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=row-description-provider] ---- The result: image::vcl/components/data-grid-row-description.gif[align=""center""] To register the provider programmatically, use the `setRowDescriptionProvider()` component method. [[row-style-provider]] === RowStyleProvider `RowStyleProvider` allows style providers for the `DataGrid` rows. `DataGrid` can use several providers to obtain many style names for rows. Example of setting a style: [source,java,indent=0] ---- include::example$/ex1/src/main/java/ui/ex1/screen/component/datagrid/DataGridScreen.java[tags=row-style-provider] ---- Then you should define row styles in the application theme. Detailed information on creating a theme is available in xref:themes.adoc[Themes]. Style names returned by the provider in the screen controller should be used as CSS selectors. For example: [source,css,indent=0] ---- include::example$/ex1/src/main/themes/helium-extended/helium-extended.scss[tags=grid-rows-style] ---- The result: image::vcl/components/data-grid-row-style.png[align=""center""] [[xml]] == All XML Attributes include::../xml-studio-tip.adoc[] === DataGrid XML Attributes <> - <> - xref:vcl/xml.adoc#align[align] - <> - xref:vcl/xml.adoc#box-expand-ratio[box.expandRatio] - xref:vcl/xml.adoc#caption[caption] - xref:vcl/xml.adoc#caption-as-html[captionAsHtml] - xref:vcl/xml.adoc#colspan[colspan] - <> - <> - xref:vcl/xml.adoc#context-help-text[contextHelpText] - xref:vcl/xml.adoc#context-help-text-html-enabled[contextHelpTextHtmlEnabled] - <> - xref:vcl/xml.adoc#css[css] - xref:vcl/xml.adoc#data-container[dataContainer] - xref:vcl/xml.adoc#description[description] - xref:vcl/xml.adoc#description-as-html[descriptionAsHtml] - <> - <> - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#enable[enable] - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#height[height] - xref:vcl/xml.adoc#html-sanitizer-enabled[htmlSanitizerEnabled] - xref:vcl/xml.adoc#icon[icon] - xref:vcl/xml.adoc#id[id] - <> - <> - <> - <> - xref:vcl/xml.adoc#responsive[responsive] - xref:vcl/xml.adoc#rowspan[rowspan] - <> - <> - <> - xref:vcl/xml.adoc#tab-index[tabIndex] - <> - xref:vcl/xml.adoc#visible[visible] - xref:vcl/xml.adoc#width[width] [[xml-data-grid-elements]] === DataGrid XML Elements <> - <> - <> - <> === Columns XML Attributes <> - <> === Column XML Attributes xref:vcl/xml.adoc#box-expand-ratio[box.expandRatio] - <> - <> - <> - <> - xref:vcl/xml.adoc#colspan[colspan] - <> - <> - <> - <> - <> - <> - <> - xref:vcl/xml.adoc#rowspan[rowspan] - <> - <> - <> === Column XML Elements <> - <> - <> - <> - <> - <> - <> - <> - <> - <> - <> === Aggregation XML Attributes <> - <> - <> === Aggregation XML Element <> == API <> - <> - <> - <> - <> - <> - <> - <> - <> - xref:vcl/components/table.adoc#methods-set-enter-press-action[setEnterPressAction] - xref:vcl/components/table.adoc#methods-set-item-click-action[setItemClickAction] - <>",12050,False,2499.3066848920203,median "TYPES: BEGIN OF t_input, row TYPE string, END OF t_input. * Input declaration DATA: lv_input TYPE TABLE OF t_input, wa_input LIKE LINE OF lv_input. * Assign with the puzzle input. lv_input = VALUE #( ( row = 'acc +15' ) ( row = 'jmp +461' ) ( row = 'acc +6' ) ( row = 'nop +445' ) ( row = 'jmp +324' ) ( row = 'jmp +253' ) ( row = 'acc -4' ) ( row = 'acc +22' ) ( row = 'acc +11' ) ( row = 'jmp +471' ) ( row = 'jmp +145' ) ( row = 'acc +19' ) ( row = 'jmp -7' ) ( row = 'jmp +431' ) ( row = 'nop +66' ) ( row = 'acc +48' ) ( row = 'jmp +409' ) ( row = 'jmp +514' ) ( row = 'jmp +1' ) ( row = 'acc +32' ) ( row = 'jmp +552' ) ( row = 'acc +21' ) ( row = 'jmp +317' ) ( row = 'nop +488' ) ( row = 'jmp +500' ) ( row = 'jmp +214' ) ( row = 'acc +41' ) ( row = 'jmp +17' ) ( row = 'acc +19' ) ( row = 'jmp +1' ) ( row = 'acc +28' ) ( row = 'jmp +74' ) ( row = 'acc +37' ) ( row = 'acc +46' ) ( row = 'acc -10' ) ( row = 'jmp +455' ) ( row = 'acc +33' ) ( row = 'jmp +585' ) ( row = 'acc -13' ) ( row = 'acc +18' ) ( row = 'jmp +19' ) ( row = 'jmp +601' ) ( row = 'acc +30' ) ( row = 'jmp +272' ) ( row = 'acc +18' ) ( row = 'acc +50' ) ( row = 'acc +1' ) ( row = 'acc +29' ) ( row = 'jmp +50' ) ( row = 'nop +573' ) ( row = 'jmp +562' ) ( row = 'nop +274' ) ( row = 'jmp +1' ) ( row = 'acc +6' ) ( row = 'jmp +1' ) ( row = 'jmp +64' ) ( row = 'jmp +1' ) ( row = 'acc +37' ) ( row = 'jmp +161' ) ( row = 'nop +549' ) ( row = 'acc +21' ) ( row = 'jmp +1' ) ( row = 'nop +325' ) ( row = 'jmp +331' ) ( row = 'acc +0' ) ( row = 'acc +25' ) ( row = 'jmp +431' ) ( row = 'nop +349' ) ( row = 'jmp +45' ) ( row = 'acc +37' ) ( row = 'acc +9' ) ( row = 'jmp +354' ) ( row = 'jmp +132' ) ( row = 'jmp +307' ) ( row = 'jmp +1' ) ( row = 'nop +465' ) ( row = 'jmp +386' ) ( row = 'acc +13' ) ( row = 'acc +20' ) ( row = 'jmp -20' ) ( row = 'acc -15' ) ( row = 'nop +158' ) ( row = 'jmp +415' ) ( row = 'acc +33' ) ( row = 'acc +40' ) ( row = 'acc +38' ) ( row = 'acc -2' ) ( row = 'jmp +81' ) ( row = 'acc +44' ) ( row = 'acc +9' ) ( row = 'acc +15' ) ( row = 'nop +139' ) ( row = 'jmp -18' ) ( row = 'nop +187' ) ( row = 'acc +47' ) ( row = 'acc +45' ) ( row = 'acc +40' ) ( row = 'jmp +456' ) ( row = 'acc +48' ) ( row = 'jmp +1' ) ( row = 'jmp -75' ) ( row = 'acc +11' ) ( row = 'acc -13' ) ( row = 'nop +222' ) ( row = 'jmp +202' ) ( row = 'acc +38' ) ( row = 'acc +31' ) ( row = 'acc -11' ) ( row = 'acc +1' ) ( row = 'jmp +431' ) ( row = 'acc +37' ) ( row = 'nop +195' ) ( row = 'jmp +118' ) ( row = 'acc -8' ) ( row = 'jmp +1' ) ( row = 'jmp +154' ) ( row = 'acc +7' ) ( row = 'acc +13' ) ( row = 'jmp +43' ) ( row = 'jmp +507' ) ( row = 'acc -2' ) ( row = 'acc +11' ) ( row = 'jmp +465' ) ( row = 'acc -12' ) ( row = 'nop -103' ) ( row = 'jmp +50' ) ( row = 'acc +2' ) ( row = 'nop +4' ) ( row = 'acc +46' ) ( row = 'acc +17' ) ( row = 'jmp +100' ) ( row = 'nop +149' ) ( row = 'jmp +397' ) ( row = 'nop -28' ) ( row = 'jmp +236' ) ( row = 'acc +0' ) ( row = 'nop +465' ) ( row = 'acc +19' ) ( row = 'acc -5' ) ( row = 'jmp +91' ) ( row = 'jmp +118' ) ( row = 'acc -3' ) ( row = 'nop +176' ) ( row = 'acc +8' ) ( row = 'jmp +24' ) ( row = 'jmp +235' ) ( row = 'acc -7' ) ( row = 'nop -1' ) ( row = 'nop +347' ) ( row = 'acc +33' ) ( row = 'jmp +165' ) ( row = 'acc -18' ) ( row = 'acc +9' ) ( row = 'acc -8' ) ( row = 'jmp +179' ) ( row = 'acc -3' ) ( row = 'acc +40' ) ( row = 'jmp +1' ) ( row = 'acc +5' ) ( row = 'jmp +475' ) ( row = 'jmp +70' ) ( row = 'acc +50' ) ( row = 'acc -1' ) ( row = 'acc -11' ) ( row = 'acc +43' ) ( row = 'jmp +283' ) ( row = 'nop +114' ) ( row = 'jmp +161' ) ( row = 'acc -19' ) ( row = 'acc +50' ) ( row = 'acc +47' ) ( row = 'acc +49' ) ( row = 'jmp +381' ) ( row = 'jmp +1' ) ( row = 'jmp -94' ) ( row = 'nop +373' ) ( row = 'acc +26' ) ( row = 'acc +7' ) ( row = 'jmp +41' ) ( row = 'acc -7' ) ( row = 'jmp +264' ) ( row = 'nop -40' ) ( row = 'acc +23' ) ( row = 'jmp -60' ) ( row = 'acc +15' ) ( row = 'acc +19' ) ( row = 'acc +39' ) ( row = 'acc -16' ) ( row = 'jmp +283' ) ( row = 'acc +4' ) ( row = 'jmp +258' ) ( row = 'acc +0' ) ( row = 'acc +38' ) ( row = 'acc -6' ) ( row = 'jmp +32' ) ( row = 'acc +33' ) ( row = 'jmp +1' ) ( row = 'acc -4' ) ( row = 'acc +17' ) ( row = 'jmp +149' ) ( row = 'acc -17' ) ( row = 'acc +39' ) ( row = 'nop +75' ) ( row = 'jmp -136' ) ( row = 'acc +6' ) ( row = 'acc +10' ) ( row = 'jmp +1' ) ( row = 'acc +9' ) ( row = 'jmp +390' ) ( row = 'jmp +363' ) ( row = 'acc +32' ) ( row = 'jmp +95' ) ( row = 'jmp -71' ) ( row = 'acc +12' ) ( row = 'jmp +86' ) ( row = 'acc +49' ) ( row = 'acc +2' ) ( row = 'acc +0' ) ( row = 'jmp +139' ) ( row = 'nop +363' ) ( row = 'acc +21' ) ( row = 'jmp +366' ) ( row = 'jmp +1' ) ( row = 'acc +16' ) ( row = 'acc -13' ) ( row = 'jmp +55' ) ( row = 'jmp -159' ) ( row = 'acc +46' ) ( row = 'acc +50' ) ( row = 'jmp +266' ) ( row = 'acc +2' ) ( row = 'jmp -180' ) ( row = 'jmp -181' ) ( row = 'acc +41' ) ( row = 'acc -3' ) ( row = 'nop -176' ) ( row = 'jmp +121' ) ( row = 'acc +23' ) ( row = 'jmp +281' ) ( row = 'acc +5' ) ( row = 'acc +14' ) ( row = 'acc -8' ) ( row = 'jmp +128' ) ( row = 'jmp +281' ) ( row = 'nop +81' ) ( row = 'jmp +1' ) ( row = 'acc +36' ) ( row = 'acc +34' ) ( row = 'jmp -176' ) ( row = 'acc +8' ) ( row = 'jmp +309' ) ( row = 'acc +11' ) ( row = 'nop -77' ) ( row = 'jmp -40' ) ( row = 'acc +0' ) ( row = 'acc +8' ) ( row = 'acc +14' ) ( row = 'jmp +296' ) ( row = 'nop +197' ) ( row = 'nop -124' ) ( row = 'acc +38' ) ( row = 'acc +9' ) ( row = 'jmp +310' ) ( row = 'jmp -183' ) ( row = 'jmp +353' ) ( row = 'acc +28' ) ( row = 'acc -18' ) ( row = 'nop +120' ) ( row = 'jmp -217' ) ( row = 'acc +49' ) ( row = 'acc +38' ) ( row = 'jmp -243' ) ( row = 'nop -68' ) ( row = 'acc +9' ) ( row = 'acc +15' ) ( row = 'nop +43' ) ( row = 'jmp -46' ) ( row = 'acc -4' ) ( row = 'jmp +262' ) ( row = 'jmp +176' ) ( row = 'nop -139' ) ( row = 'acc +38' ) ( row = 'acc +35' ) ( row = 'acc -8' ) ( row = 'jmp -225' ) ( row = 'acc +37' ) ( row = 'acc +49' ) ( row = 'acc +42' ) ( row = 'nop +278' ) ( row = 'jmp +264' ) ( row = 'acc -11' ) ( row = 'nop +291' ) ( row = 'acc +21' ) ( row = 'nop -221' ) ( row = 'jmp +80' ) ( row = 'acc +15' ) ( row = 'acc +13' ) ( row = 'acc +2' ) ( row = 'nop -40' ) ( row = 'jmp +309' ) ( row = 'acc -18' ) ( row = 'acc -5' ) ( row = 'acc +24' ) ( row = 'jmp -70' ) ( row = 'acc +12' ) ( row = 'jmp -261' ) ( row = 'acc +4' ) ( row = 'acc -2' ) ( row = 'acc +3' ) ( row = 'jmp +1' ) ( row = 'jmp +302' ) ( row = 'acc -7' ) ( row = 'jmp +1' ) ( row = 'acc +39' ) ( row = 'jmp +73' ) ( row = 'jmp +18' ) ( row = 'acc +3' ) ( row = 'jmp +277' ) ( row = 'acc +4' ) ( row = 'nop +125' ) ( row = 'nop -284' ) ( row = 'acc +41' ) ( row = 'jmp -312' ) ( row = 'acc +13' ) ( row = 'jmp -183' ) ( row = 'nop -35' ) ( row = 'jmp -137' ) ( row = 'jmp -76' ) ( row = 'acc +1' ) ( row = 'acc +31' ) ( row = 'acc +39' ) ( row = 'jmp +56' ) ( row = 'jmp +290' ) ( row = 'jmp +1' ) ( row = 'acc +12' ) ( row = 'nop +71' ) ( row = 'acc +43' ) ( row = 'jmp -296' ) ( row = 'jmp +68' ) ( row = 'acc -14' ) ( row = 'acc +35' ) ( row = 'nop -290' ) ( row = 'jmp -24' ) ( row = 'acc +39' ) ( row = 'acc -8' ) ( row = 'nop +110' ) ( row = 'jmp +1' ) ( row = 'jmp +78' ) ( row = 'acc +11' ) ( row = 'acc +9' ) ( row = 'acc -11' ) ( row = 'acc +50' ) ( row = 'jmp +167' ) ( row = 'acc +50' ) ( row = 'acc +19' ) ( row = 'acc +0' ) ( row = 'jmp -221' ) ( row = 'acc -4' ) ( row = 'acc -6' ) ( row = 'nop +11' ) ( row = 'acc +49' ) ( row = 'jmp -348' ) ( row = 'nop +197' ) ( row = 'acc +6' ) ( row = 'jmp -196' ) ( row = 'nop -155' ) ( row = 'jmp -76' ) ( row = 'acc +50' ) ( row = 'acc -8' ) ( row = 'jmp -89' ) ( row = 'acc +9' ) ( row = 'jmp +255' ) ( row = 'acc +25' ) ( row = 'jmp +199' ) ( row = 'jmp -35' ) ( row = 'acc +46' ) ( row = 'acc +25' ) ( row = 'jmp +1' ) ( row = 'acc +32' ) ( row = 'jmp -31' ) ( row = 'acc -3' ) ( row = 'acc -5' ) ( row = 'jmp +73' ) ( row = 'acc +7' ) ( row = 'acc +22' ) ( row = 'acc -15' ) ( row = 'jmp +145' ) ( row = 'nop -97' ) ( row = 'acc +47' ) ( row = 'acc +22' ) ( row = 'jmp -110' ) ( row = 'acc +44' ) ( row = 'acc +4' ) ( row = 'jmp -383' ) ( row = 'acc +34' ) ( row = 'jmp +1' ) ( row = 'jmp +16' ) ( row = 'nop -128' ) ( row = 'acc +43' ) ( row = 'jmp -34' ) ( row = 'nop +95' ) ( row = 'acc +3' ) ( row = 'jmp +4' ) ( row = 'acc +13' ) ( row = 'acc -2' ) ( row = 'jmp -90' ) ( row = 'acc +39' ) ( row = 'jmp +187' ) ( row = 'acc +24' ) ( row = 'acc +23' ) ( row = 'acc +42' ) ( row = 'jmp -11' ) ( row = 'jmp -281' ) ( row = 'jmp +1' ) ( row = 'acc +25' ) ( row = 'jmp -157' ) ( row = 'acc +3' ) ( row = 'acc -3' ) ( row = 'nop -24' ) ( row = 'acc -13' ) ( row = 'jmp -46' ) ( row = 'acc +10' ) ( row = 'acc +16' ) ( row = 'nop -7' ) ( row = 'jmp -289' ) ( row = 'nop -408' ) ( row = 'acc -5' ) ( row = 'acc +23' ) ( row = 'nop +91' ) ( row = 'jmp -234' ) ( row = 'acc +0' ) ( row = 'acc +4' ) ( row = 'acc +15' ) ( row = 'acc -15' ) ( row = 'jmp -367' ) ( row = 'acc +32' ) ( row = 'acc -9' ) ( row = 'acc +13' ) ( row = 'jmp -194' ) ( row = 'acc +38' ) ( row = 'nop +126' ) ( row = 'acc +1' ) ( row = 'nop +124' ) ( row = 'jmp -275' ) ( row = 'acc -14' ) ( row = 'acc +26' ) ( row = 'jmp +55' ) ( row = 'jmp -388' ) ( row = 'acc +3' ) ( row = 'acc +8' ) ( row = 'acc +31' ) ( row = 'acc +34' ) ( row = 'jmp -372' ) ( row = 'acc +45' ) ( row = 'jmp -115' ) ( row = 'acc -6' ) ( row = 'acc +47' ) ( row = 'acc -17' ) ( row = 'acc +29' ) ( row = 'jmp -438' ) ( row = 'acc +33' ) ( row = 'jmp -113' ) ( row = 'jmp -301' ) ( row = 'jmp -396' ) ( row = 'acc +46' ) ( row = 'jmp -284' ) ( row = 'acc -14' ) ( row = 'acc +11' ) ( row = 'acc +20' ) ( row = 'nop -356' ) ( row = 'jmp -445' ) ( row = 'acc +20' ) ( row = 'acc -6' ) ( row = 'acc -8' ) ( row = 'jmp +134' ) ( row = 'nop +54' ) ( row = 'acc +33' ) ( row = 'jmp +1' ) ( row = 'acc +3' ) ( row = 'jmp +108' ) ( row = 'acc +14' ) ( row = 'nop +67' ) ( row = 'nop -66' ) ( row = 'acc +45' ) ( row = 'jmp +117' ) ( row = 'acc +45' ) ( row = 'acc +42' ) ( row = 'acc +25' ) ( row = 'acc -18' ) ( row = 'jmp -354' ) ( row = 'acc +8' ) ( row = 'jmp -240' ) ( row = 'nop -373' ) ( row = 'acc -8' ) ( row = 'jmp +72' ) ( row = 'jmp -95' ) ( row = 'jmp -350' ) ( row = 'jmp -62' ) ( row = 'acc +6' ) ( row = 'acc -18' ) ( row = 'jmp +108' ) ( row = 'acc +14' ) ( row = 'acc +11' ) ( row = 'nop -164' ) ( row = 'acc +4' ) ( row = 'jmp +6' ) ( row = 'acc +24' ) ( row = 'acc +11' ) ( row = 'acc -7' ) ( row = 'acc +27' ) ( row = 'jmp -171' ) ( row = 'acc +23' ) ( row = 'acc +36' ) ( row = 'acc +20' ) ( row = 'acc +42' ) ( row = 'jmp -51' ) ( row = 'acc +28' ) ( row = 'acc +10' ) ( row = 'jmp -218' ) ( row = 'nop +63' ) ( row = 'jmp -294' ) ( row = 'acc -10' ) ( row = 'nop +44' ) ( row = 'jmp +43' ) ( row = 'jmp -444' ) ( row = 'acc +20' ) ( row = 'acc +39' ) ( row = 'acc +29' ) ( row = 'jmp -507' ) ( row = 'jmp -265' ) ( row = 'jmp -471' ) ( row = 'nop +17' ) ( row = 'acc +39' ) ( row = 'acc +4' ) ( row = 'jmp -54' ) ( row = 'acc +1' ) ( row = 'nop -448' ) ( row = 'acc -18' ) ( row = 'acc +3' ) ( row = 'jmp -495' ) ( row = 'acc +17' ) ( row = 'acc +16' ) ( row = 'jmp +6' ) ( row = 'acc +6' ) ( row = 'acc +0' ) ( row = 'jmp +1' ) ( row = 'acc -15' ) ( row = 'jmp -317' ) ( row = 'jmp -77' ) ( row = 'acc +4' ) ( row = 'acc +30' ) ( row = 'acc -3' ) ( row = 'jmp -187' ) ( row = 'acc -11' ) ( row = 'nop -189' ) ( row = 'nop -488' ) ( row = 'jmp -140' ) ( row = 'acc +50' ) ( row = 'jmp -142' ) ( row = 'nop -211' ) ( row = 'jmp -166' ) ( row = 'acc -12' ) ( row = 'acc +7' ) ( row = 'acc +32' ) ( row = 'acc +40' ) ( row = 'jmp -384' ) ( row = 'jmp -186' ) ( row = 'nop -261' ) ( row = 'acc +32' ) ( row = 'acc +19' ) ( row = 'acc +44' ) ( row = 'jmp +16' ) ( row = 'acc +15' ) ( row = 'acc +30' ) ( row = 'nop -476' ) ( row = 'acc +9' ) ( row = 'jmp -299' ) ( row = 'acc -17' ) ( row = 'acc -17' ) ( row = 'acc -4' ) ( row = 'acc +44' ) ( row = 'jmp -133' ) ( row = 'jmp -58' ) ( row = 'acc +21' ) ( row = 'acc +4' ) ( row = 'acc -19' ) ( row = 'jmp -170' ) ( row = 'acc +32' ) ( row = 'acc -3' ) ( row = 'jmp -363' ) ( row = 'acc +48' ) ( row = 'acc +9' ) ( row = 'acc +48' ) ( row = 'jmp +5' ) ( row = 'acc +30' ) ( row = 'acc +40' ) ( row = 'jmp -450' ) ( row = 'jmp -282' ) ( row = 'jmp -388' ) ( row = 'acc +12' ) ( row = 'jmp -361' ) ( row = 'acc -6' ) ( row = 'jmp -237' ) ( row = 'acc +27' ) ( row = 'acc +16' ) ( row = 'acc -19' ) ( row = 'acc -5' ) ( row = 'jmp -145' ) ( row = 'acc +38' ) ( row = 'jmp -565' ) ( row = 'nop -341' ) ( row = 'jmp +11' ) ( row = 'acc +22' ) ( row = 'nop -219' ) ( row = 'jmp -597' ) ( row = 'acc +33' ) ( row = 'jmp -572' ) ( row = 'jmp -292' ) ( row = 'acc +7' ) ( row = 'acc -14' ) ( row = 'acc +33' ) ( row = 'jmp -432' ) ( row = 'acc +47' ) ( row = 'jmp -41' ) ( row = 'nop -306' ) ( row = 'jmp -85' ) ( row = 'jmp +1' ) ( row = 'nop -215' ) ( row = 'acc +30' ) ( row = 'acc +9' ) ( row = 'jmp -71' ) ( row = 'acc +42' ) ( row = 'acc +49' ) ( row = 'jmp -553' ) ( row = 'acc +28' ) ( row = 'acc +43' ) ( row = 'jmp +1' ) ( row = 'jmp -147' ) ( row = 'acc +44' ) ( row = 'acc +26' ) ( row = 'nop -176' ) ( row = 'jmp -582' ) ( row = 'acc +7' ) ( row = 'acc -14' ) ( row = 'acc +16' ) ( row = 'acc +34' ) ( row = 'jmp +1' ) ). TYPES: BEGIN OF t_checklist, instruction_index TYPE i, END OF t_checklist. DATA: lv_cur_position TYPE i VALUE 1, lv_accumulator TYPE i VALUE 0, lt_checklist TYPE TABLE OF t_checklist, lv_prefix TYPE string, wa_checklist LIKE LINE OF lt_checklist, wa_g_input LIKE wa_input, "" Global work area wa_t_input LIKE wa_input, "" Temporary work area lv_end TYPE abap_bool VALUE abap_false, lv_last_index TYPE i. LOOP AT lv_input INTO wa_g_input. lv_accumulator = 0. lv_cur_position = 1. CLEAR lt_checklist. FIND ALL OCCURRENCES OF 'nop' IN wa_g_input-row RESULTS DATA(lv_check). IF sy-subrc EQ 0. REPLACE 'nop' WITH 'jmp' INTO wa_g_input-row. MODIFY lv_input INDEX sy-tabix FROM wa_g_input TRANSPORTING row. ELSE. FIND ALL OCCURRENCES OF 'jmp' IN wa_g_input-row RESULTS DATA(lv_check_2). IF sy-subrc EQ 0. REPLACE 'jmp' WITH 'nop' INTO wa_g_input-row. MODIFY lv_input INDEX sy-tabix FROM wa_g_input TRANSPORTING row. ENDIF. ENDIF. "" Revert back the change IF sy-tabix NE 1. lv_last_index = sy-tabix - 1. READ TABLE lv_input INTO wa_t_input INDEX lv_last_index. FIND ALL OCCURRENCES OF 'nop' IN wa_t_input-row RESULTS DATA(lv_check_3). IF sy-subrc EQ 0. REPLACE 'nop' WITH 'jmp' INTO wa_t_input-row. MODIFY lv_input INDEX lv_last_index FROM wa_t_input TRANSPORTING row. ELSE. FIND ALL OCCURRENCES OF 'jmp' IN wa_t_input-row RESULTS DATA(lv_check_4). IF sy-subrc EQ 0. REPLACE 'jmp' WITH 'nop' INTO wa_t_input-row. MODIFY lv_input INDEX lv_last_index FROM wa_t_input TRANSPORTING row. ENDIF. ENDIF. ENDIF. DO. READ TABLE lv_input INTO wa_input INDEX lv_cur_position. IF lv_cur_position > lines( lv_input ). "" Checks if the boot code has been terminated. lv_end = abap_true. EXIT. ENDIF. IF line_exists( lt_checklist[ instruction_index = lv_cur_position ] ). EXIT. ELSE. "" Store the instruction as executed. wa_checklist-instruction_index = lv_cur_position. APPEND wa_checklist TO lt_checklist. ENDIF. SPLIT wa_input-row AT ' ' INTO TABLE DATA(lv_instruction). READ TABLE lv_instruction INTO DATA(lv_operation) INDEX 1. READ TABLE lv_instruction INTO DATA(lv_argument) INDEX 2. CASE lv_operation. WHEN 'jmp'. "" Jump to a position lv_prefix = lv_argument+0(1). REPLACE '+' WITH '' INTO lv_argument. REPLACE '-' WITH '' INTO lv_argument. CONDENSE lv_argument NO-GAPS. CASE lv_prefix. WHEN '+'. lv_cur_position = lv_cur_position + lv_argument. "" Adds the argument number WHEN '-'. lv_cur_position = lv_cur_position - lv_argument. "" Subs the argument number ENDCASE. WHEN 'acc'. "" Add / Sub value to the accumulator and goes to the next line lv_prefix = lv_argument+0(1). REPLACE '+' WITH '' INTO lv_argument. REPLACE '-' WITH '' INTO lv_argument. CONDENSE lv_argument NO-GAPS. CASE lv_prefix. WHEN '+'. lv_accumulator = lv_accumulator + lv_argument. "" Adds the argument number WHEN '-'. lv_accumulator = lv_accumulator - lv_argument. "" Subs the argument number ENDCASE. lv_cur_position = lv_cur_position + 1. WHEN 'nop'. "" No Operation, just go to the next line. lv_cur_position = lv_cur_position + 1. ENDCASE. ENDDO. IF lv_end EQ abap_true. EXIT. ENDIF. ENDLOOP. WRITE: 'Result accumulator: ' && lv_accumulator. ",7528,True,2572.2966182637224,median "CLASS zcl_abapgit_objects_program DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_super. PUBLIC SECTION. TYPES: BEGIN OF ty_progdir, name TYPE progdir-name, state TYPE progdir-state, sqlx TYPE progdir-sqlx, edtx TYPE progdir-edtx, varcl TYPE progdir-varcl, dbapl TYPE progdir-dbapl, dbna TYPE progdir-dbna, clas TYPE progdir-clas, type TYPE progdir-type, occurs TYPE progdir-occurs, subc TYPE progdir-subc, appl TYPE progdir-appl, secu TYPE progdir-secu, cnam TYPE progdir-cnam, cdat TYPE progdir-cdat, unam TYPE progdir-unam, udat TYPE progdir-udat, vern TYPE progdir-vern, levl TYPE progdir-levl, rstat TYPE progdir-rstat, rmand TYPE progdir-rmand, rload TYPE progdir-rload, fixpt TYPE progdir-fixpt, sset TYPE progdir-sset, sdate TYPE progdir-sdate, stime TYPE progdir-stime, idate TYPE progdir-idate, itime TYPE progdir-itime, ldbname TYPE progdir-ldbname, uccheck TYPE progdir-uccheck, END OF ty_progdir. METHODS serialize_program IMPORTING io_xml TYPE REF TO zcl_abapgit_xml_output OPTIONAL is_item TYPE zif_abapgit_definitions=>ty_item io_files TYPE REF TO zcl_abapgit_objects_files iv_program TYPE programm OPTIONAL iv_extra TYPE clike OPTIONAL RAISING zcx_abapgit_exception. METHODS read_progdir IMPORTING iv_program TYPE programm RETURNING VALUE(rs_progdir) TYPE ty_progdir. METHODS deserialize_program IMPORTING is_progdir TYPE ty_progdir it_source TYPE abaptxt255_tab it_tpool TYPE textpool_table iv_package TYPE devclass RAISING zcx_abapgit_exception. PROTECTED SECTION. TYPES: ty_spaces_tt TYPE STANDARD TABLE OF i WITH DEFAULT KEY. TYPES: BEGIN OF ty_dynpro, header TYPE rpy_dyhead, containers TYPE dycatt_tab, fields TYPE dyfatc_tab, flow_logic TYPE swydyflow, spaces TYPE ty_spaces_tt, END OF ty_dynpro. TYPES: ty_dynpro_tt TYPE STANDARD TABLE OF ty_dynpro WITH DEFAULT KEY. TYPES: BEGIN OF ty_cua, adm TYPE rsmpe_adm, sta TYPE STANDARD TABLE OF rsmpe_stat WITH DEFAULT KEY, fun TYPE STANDARD TABLE OF rsmpe_funt WITH DEFAULT KEY, men TYPE STANDARD TABLE OF rsmpe_men WITH DEFAULT KEY, mtx TYPE STANDARD TABLE OF rsmpe_mnlt WITH DEFAULT KEY, act TYPE STANDARD TABLE OF rsmpe_act WITH DEFAULT KEY, but TYPE STANDARD TABLE OF rsmpe_but WITH DEFAULT KEY, pfk TYPE STANDARD TABLE OF rsmpe_pfk WITH DEFAULT KEY, set TYPE STANDARD TABLE OF rsmpe_staf WITH DEFAULT KEY, doc TYPE STANDARD TABLE OF rsmpe_atrt WITH DEFAULT KEY, tit TYPE STANDARD TABLE OF rsmpe_titt WITH DEFAULT KEY, biv TYPE STANDARD TABLE OF rsmpe_buts WITH DEFAULT KEY, END OF ty_cua. METHODS serialize_dynpros IMPORTING iv_program_name TYPE programm RETURNING VALUE(rt_dynpro) TYPE ty_dynpro_tt RAISING zcx_abapgit_exception. METHODS serialize_cua IMPORTING iv_program_name TYPE programm RETURNING VALUE(rs_cua) TYPE ty_cua RAISING zcx_abapgit_exception. METHODS deserialize_dynpros IMPORTING it_dynpros TYPE ty_dynpro_tt RAISING zcx_abapgit_exception. METHODS deserialize_textpool IMPORTING iv_program TYPE programm it_tpool TYPE textpool_table iv_language TYPE langu OPTIONAL iv_is_include TYPE abap_bool DEFAULT abap_false RAISING zcx_abapgit_exception. METHODS deserialize_cua IMPORTING iv_program_name TYPE programm is_cua TYPE ty_cua RAISING zcx_abapgit_exception. METHODS check_prog_changed_since IMPORTING iv_program TYPE programm iv_timestamp TYPE timestamp iv_skip_gui TYPE abap_bool DEFAULT abap_false RETURNING VALUE(rv_changed) TYPE abap_bool. METHODS is_any_dynpro_locked IMPORTING iv_program TYPE programm RETURNING VALUE(rv_is_any_dynpro_locked) TYPE abap_bool RAISING zcx_abapgit_exception. METHODS is_cua_locked IMPORTING iv_program TYPE programm RETURNING VALUE(rv_is_cua_locked) TYPE abap_bool RAISING zcx_abapgit_exception. METHODS is_text_locked IMPORTING iv_program TYPE programm RETURNING VALUE(rv_is_text_locked) TYPE abap_bool RAISING zcx_abapgit_exception. CLASS-METHODS: add_tpool IMPORTING it_tpool TYPE textpool_table RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt, read_tpool IMPORTING it_tpool TYPE zif_abapgit_definitions=>ty_tpool_tt RETURNING VALUE(rt_tpool) TYPE zif_abapgit_definitions=>ty_tpool_tt. PRIVATE SECTION. METHODS: condense_flow EXPORTING et_spaces TYPE ty_spaces_tt CHANGING ct_flow TYPE swydyflow, uncondense_flow IMPORTING it_flow TYPE swydyflow it_spaces TYPE ty_spaces_tt RETURNING VALUE(rt_flow) TYPE swydyflow. CLASS-METHODS auto_correct_cua_adm IMPORTING is_cua TYPE zcl_abapgit_objects_program=>ty_cua CHANGING cs_adm TYPE rsmpe_adm. ENDCLASS. CLASS zcl_abapgit_objects_program IMPLEMENTATION. METHOD is_text_locked. DATA: lv_object TYPE eqegraarg. lv_object = |*{ iv_program }|. rv_is_text_locked = exists_a_lock_entry_for( iv_lock_object = 'EABAPTEXTE' iv_argument = lv_object ). ENDMETHOD. METHOD is_cua_locked. DATA: lv_object TYPE eqegraarg, ls_cua TYPE zcl_abapgit_objects_program=>ty_cua. lv_object = |CU{ iv_program }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_cua_locked = exists_a_lock_entry_for( iv_lock_object = 'ESCUAPAINT' iv_argument = lv_object ). ENDMETHOD. METHOD is_any_dynpro_locked. DATA: lt_dynpros TYPE zcl_abapgit_objects_program=>ty_dynpro_tt, lv_object TYPE seqg3-garg. FIELD-SYMBOLS: TYPE zcl_abapgit_objects_program=>ty_dynpro. lt_dynpros = serialize_dynpros( iv_program ). LOOP AT lt_dynpros ASSIGNING . lv_object = |{ -header-screen }{ -header-program }|. IF exists_a_lock_entry_for( iv_lock_object = 'ESCRP' iv_argument = lv_object ) = abap_true. rv_is_any_dynpro_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD condense_flow. DATA: lv_spaces LIKE LINE OF et_spaces. FIELD-SYMBOLS: LIKE LINE OF ct_flow. CLEAR et_spaces. LOOP AT ct_flow ASSIGNING . lv_spaces = 0. WHILE NOT -line IS INITIAL AND -line(1) = space. lv_spaces = lv_spaces + 1. -line = -line+1. ENDWHILE. APPEND lv_spaces TO et_spaces. ENDLOOP. ENDMETHOD. METHOD uncondense_flow. DATA: lv_spaces LIKE LINE OF it_spaces. FIELD-SYMBOLS: LIKE LINE OF it_flow, LIKE LINE OF rt_flow. LOOP AT it_flow ASSIGNING . APPEND INITIAL LINE TO rt_flow ASSIGNING . -line = -line. READ TABLE it_spaces INDEX sy-tabix INTO lv_spaces. IF sy-subrc = 0. SHIFT -line RIGHT BY lv_spaces PLACES IN CHARACTER MODE. ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_program. DATA: ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua, lt_source TYPE TABLE OF abaptxt255, lt_tpool TYPE textpool_table, ls_tpool LIKE LINE OF lt_tpool, lo_xml TYPE REF TO zcl_abapgit_xml_output. IF iv_program IS INITIAL. lv_program_name = is_item-obj_name. ELSE. lv_program_name = iv_program. ENDIF. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_READ' EXPORTING program_name = lv_program_name with_lowercase = abap_true TABLES source_extended = lt_source textelements = lt_tpool EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc = 2. zcl_abapgit_language=>restore_login_language( ). RETURN. ELSEIF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). zcx_abapgit_exception=>raise( 'Error reading program' ). ENDIF. zcl_abapgit_language=>restore_login_language( ). ls_progdir = read_progdir( lv_program_name ). IF io_xml IS BOUND. lo_xml = io_xml. ELSE. CREATE OBJECT lo_xml. ENDIF. lo_xml->add( iv_name = 'PROGDIR' ig_data = ls_progdir ). IF ls_progdir-subc = '1' OR ls_progdir-subc = 'M'. lt_dynpros = serialize_dynpros( lv_program_name ). lo_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). IF NOT ls_cua IS INITIAL. lo_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDIF. READ TABLE lt_tpool WITH KEY id = 'R' INTO ls_tpool. IF sy-subrc = 0 AND ls_tpool-key = '' AND ls_tpool-length = 0. DELETE lt_tpool INDEX sy-tabix. ENDIF. lo_xml->add( iv_name = 'TPOOL' ig_data = add_tpool( lt_tpool ) ). IF NOT io_xml IS BOUND. io_files->add_xml( iv_extra = iv_extra io_xml = lo_xml ). ENDIF. io_files->add_abap( iv_extra = iv_extra it_abap = lt_source ). ENDMETHOD. METHOD deserialize_program. DATA: lv_exists TYPE sap_bool, lv_progname TYPE reposrc-progname, ls_tpool LIKE LINE OF it_tpool, lv_title TYPE rglif-title, ls_progdir_new TYPE progdir. FIELD-SYMBOLS: TYPE any. CALL FUNCTION 'RS_CORR_INSERT' EXPORTING object = is_progdir-name object_class = 'ABAP' devclass = iv_package master_language = mv_language mode = 'INSERT' EXCEPTIONS cancelled = 1 permission_failure = 2 unknown_objectclass = 3 OTHERS = 4. IF sy-subrc = 1. zcx_abapgit_exception=>raise( 'Cancelled' ). ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from RS_CORR_INSERT' ). ENDIF. READ TABLE it_tpool INTO ls_tpool WITH KEY id = 'R'. ""#EC CI_SUBRC IF sy-subrc = 0. * there is a bug in RPY_PROGRAM_UPDATE, the header line of TTAB is not * cleared, so the title length might be inherited from a different program. ASSIGN ('(SAPLSIFP)TTAB') TO . IF sy-subrc = 0. CLEAR . ENDIF. lv_title = ls_tpool-entry. ENDIF. SELECT SINGLE progname FROM reposrc INTO lv_progname WHERE progname = is_progdir-name AND r3state = 'A'. IF sy-subrc = 0. lv_exists = abap_true. ELSE. lv_exists = abap_false. ENDIF. IF lv_exists = abap_true. zcl_abapgit_language=>set_current_language( mv_language ). CALL FUNCTION 'RPY_PROGRAM_UPDATE' EXPORTING program_name = is_progdir-name title_string = lv_title save_inactive = 'I' TABLES source_extended = it_source EXCEPTIONS cancelled = 1 permission_error = 2 not_found = 3 OTHERS = 4. IF sy-subrc <> 0. zcl_abapgit_language=>restore_login_language( ). IF sy-msgid = 'EU' AND sy-msgno = '510'. zcx_abapgit_exception=>raise( 'User is currently editing program' ). ELSE. zcx_abapgit_exception=>raise( 'PROG, error updating' ). ENDIF. ENDIF. zcl_abapgit_language=>restore_login_language( ). ELSEIF strlen( is_progdir-name ) > 30. * function module RPY_PROGRAM_INSERT cannot handle function group includes "" special treatment for extensions "" if the program name exceeds 30 characters it is not a usual "" ABAP program but might be some extension, which requires the internal "" addition EXTENSION TYPE, see "" http://help.sap.com/abapdocu_751/en/abapinsert_report_internal.htm#!ABAP_ADDITION_1@1@ "" This e.g. occurs in case of transportable Code Inspector variants (ending with ===VC) INSERT REPORT is_progdir-name FROM it_source STATE 'I' EXTENSION TYPE is_progdir-name+30. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT .. EXTENSION TYPE' ). ENDIF. ELSE. INSERT REPORT is_progdir-name FROM it_source STATE 'I' PROGRAM TYPE is_progdir-subc. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT REPORT' ). ENDIF. ENDIF. IF NOT it_tpool[] IS INITIAL. INSERT TEXTPOOL is_progdir-name FROM it_tpool LANGUAGE mv_language STATE 'I'. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = is_progdir-name i_state = 'I' IMPORTING e_progdir = ls_progdir_new EXCEPTIONS not_exists = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'not found in PROGDIR' ). ENDIF. * todo, package? ls_progdir_new-ldbname = is_progdir-ldbname. ls_progdir_new-dbna = is_progdir-dbna. ls_progdir_new-dbapl = is_progdir-dbapl. ls_progdir_new-rload = is_progdir-rload. ls_progdir_new-fixpt = is_progdir-fixpt. ls_progdir_new-varcl = is_progdir-varcl. ls_progdir_new-appl = is_progdir-appl. ls_progdir_new-rstat = is_progdir-rstat. CALL FUNCTION 'UPDATE_PROGDIR' EXPORTING i_progdir = ls_progdir_new i_progname = ls_progdir_new-name i_state = ls_progdir_new-state EXCEPTIONS not_executed = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'PROG, error inserting' ). ENDIF. SELECT SINGLE * FROM progdir INTO ls_progdir_new WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. IF sy-subrc = 0 AND is_progdir-varcl = space AND ls_progdir_new-varcl = abap_true. * function module UPDATE_PROGDIR does not update VARCL UPDATE progdir SET varcl = is_progdir-varcl WHERE name = ls_progdir_new-name AND state = ls_progdir_new-state. ""#EC CI_SUBRC ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'REPS' iv_name = is_progdir-name ). ENDMETHOD. METHOD read_progdir. DATA: ls_sapdir TYPE progdir. CALL FUNCTION 'READ_PROGDIR' EXPORTING i_progname = iv_program i_state = 'A' IMPORTING e_progdir = ls_sapdir. MOVE-CORRESPONDING ls_sapdir TO rs_progdir. CLEAR: rs_progdir-edtx, rs_progdir-cnam, rs_progdir-cdat, rs_progdir-unam, rs_progdir-udat, rs_progdir-levl, rs_progdir-vern, rs_progdir-rmand, rs_progdir-sdate, rs_progdir-stime, rs_progdir-idate, rs_progdir-itime. ENDMETHOD. METHOD serialize_cua. CALL FUNCTION 'RS_CUA_INTERNAL_FETCH' EXPORTING program = iv_program_name language = mv_language state = 'A' IMPORTING adm = rs_cua-adm TABLES sta = rs_cua-sta fun = rs_cua-fun men = rs_cua-men mtx = rs_cua-mtx act = rs_cua-act but = rs_cua-but pfk = rs_cua-pfk set = rs_cua-set doc = rs_cua-doc tit = rs_cua-tit biv = rs_cua-biv EXCEPTIONS not_found = 1 unknown_version = 2 OTHERS = 3. IF sy-subrc > 1. zcx_abapgit_exception=>raise( |error from RS_CUA_INTERNAL_FETCH, { sy-subrc }| ). ENDIF. ENDMETHOD. METHOD serialize_dynpros. DATA: ls_header TYPE rpy_dyhead, lt_containers TYPE dycatt_tab, lt_fields_to_containers TYPE dyfatc_tab, lt_flow_logic TYPE swydyflow, lt_d020s TYPE TABLE OF d020s. FIELD-SYMBOLS: LIKE LINE OF lt_d020s, TYPE scrpostyle, LIKE LINE OF lt_containers, LIKE LINE OF lt_fields_to_containers, LIKE LINE OF rt_dynpro. CALL FUNCTION 'RS_SCREEN_LIST' EXPORTING dynnr = '' progname = iv_program_name TABLES dynpros = lt_d020s EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc = 2. zcx_abapgit_exception=>raise( 'error from screen_list' ). ENDIF. SORT lt_d020s BY dnum ASCENDING. * loop dynpros and skip generated selection screens LOOP AT lt_d020s ASSIGNING WHERE type <> 'S' AND type <> 'W' AND type <> 'J' AND NOT dnum IS INITIAL. CALL FUNCTION 'RPY_DYNPRO_READ' EXPORTING progname = iv_program_name dynnr = -dnum IMPORTING header = ls_header TABLES containers = lt_containers fields_to_containers = lt_fields_to_containers flow_logic = lt_flow_logic EXCEPTIONS cancelled = 1 not_found = 2 permission_error = 3 OTHERS = 4. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( |Error while reading dynpro: { sy-subrc }| ). ENDIF. LOOP AT lt_fields_to_containers ASSIGNING . * output style is a NUMC field, the XML conversion will fail if it contains invalid value * field does not exist in all versions ASSIGN COMPONENT 'OUTPUTSTYLE' OF STRUCTURE TO . IF sy-subrc = 0 AND = ' '. CLEAR . ENDIF. ENDLOOP. LOOP AT lt_containers ASSIGNING . IF -c_resize_v = abap_false. CLEAR -c_line_min. ENDIF. IF -c_resize_h = abap_false. CLEAR -c_coln_min. ENDIF. ENDLOOP. APPEND INITIAL LINE TO rt_dynpro ASSIGNING . -header = ls_header. -containers = lt_containers. -fields = lt_fields_to_containers. condense_flow( IMPORTING et_spaces = -spaces CHANGING ct_flow = lt_flow_logic ). -flow_logic = lt_flow_logic. ENDLOOP. ENDMETHOD. METHOD deserialize_dynpros. DATA: lv_name TYPE dwinactiv-obj_name, ls_dynpro LIKE LINE OF it_dynpros. * ls_dynpro is changed by the function module, a field-symbol will cause * the program to dump since it_dynpros cannot be changed LOOP AT it_dynpros INTO ls_dynpro. ls_dynpro-flow_logic = uncondense_flow( it_flow = ls_dynpro-flow_logic it_spaces = ls_dynpro-spaces ). CALL FUNCTION 'RPY_DYNPRO_INSERT' EXPORTING header = ls_dynpro-header suppress_exist_checks = abap_true TABLES containers = ls_dynpro-containers fields_to_containers = ls_dynpro-fields flow_logic = ls_dynpro-flow_logic EXCEPTIONS cancelled = 1 already_exists = 2 program_not_exists = 3 not_executed = 4 missing_required_field = 5 illegal_field_value = 6 field_not_allowed = 7 not_generated = 8 illegal_field_position = 9 OTHERS = 10. IF sy-subrc <> 2 AND sy-subrc <> 0. zcx_abapgit_exception=>raise( |error from RPY_DYNPRO_INSERT: { sy-subrc }| ). ENDIF. * todo, RPY_DYNPRO_UPDATE? CONCATENATE ls_dynpro-header-program ls_dynpro-header-screen INTO lv_name RESPECTING BLANKS. ASSERT NOT lv_name IS INITIAL. zcl_abapgit_objects_activation=>add( iv_type = 'DYNP' iv_name = lv_name ). ENDLOOP. ENDMETHOD. METHOD add_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. -split = -entry. -entry = -entry+8. ENDIF. ENDLOOP. ENDMETHOD. METHOD read_tpool. FIELD-SYMBOLS: LIKE LINE OF it_tpool, LIKE LINE OF rt_tpool. LOOP AT it_tpool ASSIGNING . APPEND INITIAL LINE TO rt_tpool ASSIGNING . MOVE-CORRESPONDING TO . IF -id = 'S'. CONCATENATE -split -entry INTO -entry RESPECTING BLANKS. ENDIF. ENDLOOP. ENDMETHOD. METHOD deserialize_textpool. DATA lv_language TYPE langu. DATA lv_state TYPE c. DATA lv_delete TYPE abap_bool. IF iv_language IS INITIAL. lv_language = mv_language. ELSE. lv_language = iv_language. ENDIF. IF lv_language = mv_language. lv_state = 'I'. ""Textpool in master language needs to be activated ELSE. lv_state = 'A'. ""Translations are always active ENDIF. IF it_tpool IS INITIAL. IF iv_is_include = abap_false OR lv_state = 'A'. DELETE TEXTPOOL iv_program ""Remove initial description from textpool if LANGUAGE iv_program ""original program does not have a textpool STATE lv_state. lv_delete = abap_true. ELSE. INSERT TEXTPOOL iv_program ""In case of includes: Deletion of textpool in FROM it_tpool ""master language cannot be activated because LANGUAGE lv_language ""this woul activate the deletion of the textpool STATE lv_state. ""of the mail program -> insert empty textpool ENDIF. ELSE. IF lines( it_tpool ) = 1 AND lv_language = mv_language. READ TABLE it_tpool WITH KEY id = 'R' TRANSPORTING NO FIELDS. IF sy-subrc = 0. RETURN. ""No action because description in master language is already there ENDIF. ENDIF. INSERT TEXTPOOL iv_program FROM it_tpool LANGUAGE lv_language STATE lv_state. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'error from INSERT TEXTPOOL' ). ENDIF. ENDIF. IF lv_state = 'I'. ""Textpool in master language needs to be activated zcl_abapgit_objects_activation=>add( iv_type = 'REPT' iv_name = iv_program iv_delete = lv_delete ). ENDIF. ENDMETHOD. METHOD deserialize_cua. DATA: ls_tr_key TYPE trkey, ls_adm TYPE rsmpe_adm. IF lines( is_cua-sta ) = 0 AND lines( is_cua-fun ) = 0 AND lines( is_cua-men ) = 0 AND lines( is_cua-mtx ) = 0 AND lines( is_cua-act ) = 0 AND lines( is_cua-but ) = 0 AND lines( is_cua-pfk ) = 0 AND lines( is_cua-set ) = 0 AND lines( is_cua-doc ) = 0 AND lines( is_cua-tit ) = 0 AND lines( is_cua-biv ) = 0. RETURN. ENDIF. SELECT SINGLE devclass INTO ls_tr_key-devclass FROM tadir WHERE pgmid = 'R3TR' AND object = ms_item-obj_type AND obj_name = ms_item-obj_name. ""#EC CI_GENBUFF IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'not found in tadir' ). ENDIF. ls_tr_key-obj_type = ms_item-obj_type. ls_tr_key-obj_name = ms_item-obj_name. ls_tr_key-sub_type = 'CUAD'. ls_tr_key-sub_name = iv_program_name. ls_adm = is_cua-adm. auto_correct_cua_adm( EXPORTING is_cua = is_cua CHANGING cs_adm = ls_adm ). sy-tcode = 'SE41' ##write_ok. "" evil hack, workaround to handle fixes in note 2159455 CALL FUNCTION 'RS_CUA_INTERNAL_WRITE' EXPORTING program = iv_program_name language = mv_language tr_key = ls_tr_key adm = ls_adm state = 'I' TABLES sta = is_cua-sta fun = is_cua-fun men = is_cua-men mtx = is_cua-mtx act = is_cua-act but = is_cua-but pfk = is_cua-pfk set = is_cua-set doc = is_cua-doc tit = is_cua-tit biv = is_cua-biv EXCEPTIONS not_found = 1 OTHERS = 2. IF sy-subrc <> 0. * if moving code from SAPlink, see https://github.com/larshp/abapGit/issues/562 zcx_abapgit_exception=>raise( 'error from RS_CUA_INTERNAL_WRITE' ). ENDIF. zcl_abapgit_objects_activation=>add( iv_type = 'CUAD' iv_name = iv_program_name ). ENDMETHOD. METHOD check_prog_changed_since. DATA: lv_date TYPE dats, lv_time TYPE tims, lt_screens TYPE STANDARD TABLE OF d020s, lt_eudb TYPE STANDARD TABLE OF eudb. FIELD-SYMBOLS: LIKE LINE OF lt_screens, LIKE LINE OF lt_eudb. SELECT SINGLE udat utime FROM reposrc "" Program INTO (lv_date, lv_time) WHERE progname = iv_program AND r3state = 'A'. rv_changed = check_timestamp( iv_timestamp = iv_timestamp iv_date = lv_date iv_time = lv_time ). IF rv_changed = abap_true. RETURN. ENDIF. SELECT SINGLE udat utime FROM repotext "" Program text pool INTO (lv_date, lv_time) WHERE progname = iv_program AND r3state = 'A'. IF sy-subrc = 0. "" Text not found ? Assuming no changes, see #404 rv_changed = check_timestamp( iv_timestamp = iv_timestamp iv_date = lv_date iv_time = lv_time ). IF rv_changed = abap_true. RETURN. ENDIF. ENDIF. IF iv_skip_gui = abap_true. RETURN. ENDIF. SELECT dgen tgen FROM d020s "" Screens INTO CORRESPONDING FIELDS OF TABLE lt_screens WHERE prog = iv_program ORDER BY PRIMARY KEY ##TOO_MANY_ITAB_FIELDS. ""#EC CI_SUBRC LOOP AT lt_screens ASSIGNING . rv_changed = check_timestamp( iv_timestamp = iv_timestamp iv_date = -dgen iv_time = -tgen ). IF rv_changed = abap_true. RETURN. ENDIF. ENDLOOP. SELECT vdatum vzeit FROM eudb "" GUI INTO CORRESPONDING FIELDS OF TABLE lt_eudb WHERE relid = 'CU' AND name = iv_program AND srtf2 = 0 ORDER BY PRIMARY KEY ##TOO_MANY_ITAB_FIELDS. ""#EC CI_SUBRC LOOP AT lt_eudb ASSIGNING . rv_changed = check_timestamp( iv_timestamp = iv_timestamp iv_date = -vdatum iv_time = -vzeit ). IF rv_changed = abap_true. RETURN. ENDIF. ENDLOOP. ENDMETHOD. METHOD auto_correct_cua_adm. "" issue #1807 automatic correction of CUA interfaces saved incorrectly in the past (ADM was not saved in the XML) FIELD-SYMBOLS: TYPE rsmpe_pfk, TYPE rsmpe_act, TYPE rsmpe_men. IF cs_adm IS NOT INITIAL. RETURN. ENDIF. LOOP AT is_cua-act ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO '0123456789'. cs_adm-actcode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-men ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO '0123456789'. cs_adm-mencode = -code. ENDIF. ENDLOOP. LOOP AT is_cua-pfk ASSIGNING . IF -code+6(14) IS INITIAL AND -code(6) CO '0123456789'. cs_adm-pfkcode = -code. ENDIF. ENDLOOP. ENDMETHOD. ENDCLASS. ",7919,False,1559.7149481875872,median "/* * Copyright (c) 2020, 2021, Oracle and/or its affiliates. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * 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, version 2.0, 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., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include ""modules/util/dump/compatibility.h"" #include ""mysqlshdk/libs/utils/utils_lexing.h"" #include ""unittest/gtest_clean.h"" #include ""unittest/test_utils.h"" #include ""unittest/test_utils/test_combo_utilities.h"" namespace mysqlsh { namespace compatibility { class Compatibility_test : public tests::Shell_base_test { protected: const std::vector multiline = { R""(CREATE TABLE t(i int) ENCRYPTION = 'N' DATA DIRECTORY = '\\tmp' INDEX DIRECTORY = '\\tmp', ENGINE = MyISAM)"", R""(CREATE TABLE t (i int PRIMARY KEY) ENGINE = MyISAM DATA DIRECTORY = '/tmp' ENCRYPTION = 'y' PARTITION BY LIST (i) ( PARTITION p0 VALUES IN (0) ENGINE = MyISAM, PARTITION p1 VALUES IN (1) DATA DIRECTORY = '/tmp', ENGINE = BLACKHOLE ))"", R""(CREATE TABLE `tmq` ( `i` int(11) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 DATA DIRECTORY='/tmp/' INDEX DIRECTORY='/tmp/')"", R""(CREATE TABLE `tmq` ( `i` int(11) DEFAULT NULL ) /*!50100 TABLESPACE `t s 1` */ ENGINE=InnoDB DEFAULT CHARSET=latin1 ENCRYPTION='N')"", R""(CREATE TABLE `tmq` ( `i` int(11) NOT NULL, PRIMARY KEY (`i`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 /*!50100 PARTITION BY LIST (i) (PARTITION p0 VALUES IN (0) ENGINE = MyISAM, PARTITION p1 VALUES IN (1) DATA DIRECTORY = '/tmp' ENGINE = MyISAM) */)"", R""(CREATE TABLE `tmq` ( `i` int NOT NULL, PRIMARY KEY (`i`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci /*!50100 PARTITION BY LIST (`i`) (PARTITION p0 VALUES IN (0) DATA DIRECTORY = '/tmp/' ENGINE = InnoDB, PARTITION p1 VALUES IN (1) DATA DIRECTORY = '/tmp/' ENGINE = InnoDB) */)"", R""(CREATE TABLE `tmq` ( `i` int(11) NOT NULL, PRIMARY KEY (`i`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 /*!50100 PARTITION BY LIST (i) (PARTITION p0 VALUES IN (0) TABLESPACE = `t s 1` ENGINE = MyISAM, PARTITION p1 VALUES IN (1) TABLESPACE = `t s 1` ENGINE = MyISAM) */)"", ""CREATE DATABASE `dcs` /*!40100 DEFAULT CHARACTER SET latin1 COLLATE "" ""latin1_danish_ci */ /*!80016 DEFAULT ENCRYPTION='N' */""}; const std::vector rogue = { R""(CREATE TABLE `rogue` ( `data` int DEFAULT NULL, `index` int DEFAULT NULL, `directory` int DEFAULT NULL, `encryption` int DEFAULT NULL, `engine` int DEFAULT NULL, `tablespace` int DEFAULT NULL, `collate` int DEFAULT NULL, `charset` int DEFAULT NULL, `character` int DEFAULT NULL, `definer` int DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", "" create table rogue (data int, `index` int, directory int, encryption "" ""int, engine int, tablespace int, `collate` int, charset int, "" ""`character` int, definer int);""}; }; TEST_F(Compatibility_test, check_privileges) { std::string rewritten; EXPECT_TRUE( check_privileges( ""GRANT `app_delete`@`%`,`app_read`@`%`,`app_write`@`%`,`combz`@`%` "" ""TO `combined`@`%`"", &rewritten) .empty()); EXPECT_EQ(1, check_privileges( ""GRANT SUPER, LOCK TABLES ON *.* TO 'superfirst'@'localhost';"", &rewritten) .size()); EXPECT_EQ(""GRANT LOCK TABLES ON *.* TO 'superfirst'@'localhost';"", rewritten); EXPECT_EQ( 1, check_privileges( ""GRANT INSERT,super, UPDATE ON *.* TO 'superafter'@'localhost';"", &rewritten) .size()); EXPECT_EQ(""GRANT INSERT, UPDATE ON *.* TO 'superafter'@'localhost';"", rewritten); EXPECT_EQ(1, check_privileges(""GRANT SUPER ON *.* TO 'superonly'@'localhost';"", &rewritten) .size()); EXPECT_TRUE(rewritten.empty()); EXPECT_EQ(4, check_privileges(""GRANT SUPER,FILE, reload, BINLOG_ADMIN ON *.* "" ""TO 'empty'@'localhost';"", &rewritten) .size()); EXPECT_TRUE(rewritten.empty()); EXPECT_EQ(4, check_privileges(""GRANT INSERT,SUPER,FILE,LOCK TABLES , reload, "" ""BINLOG_ADMIN, SELECT ON *.* "" ""TO 'empty'@'localhost';"", &rewritten) .size()); EXPECT_EQ(""GRANT INSERT,LOCK TABLES , SELECT ON *.* TO 'empty'@'localhost';"", rewritten); EXPECT_EQ(4, check_privileges(""GRANT BINLOG_ADMIN, INSERT , SUPER "" "",`app_delete`@`%`, LOCK TABLES , reload, "" ""UPDATE,FILE, SELECT ON *.* "" ""TO 'empty'@'localhost';"", &rewritten) .size()); EXPECT_EQ( ""GRANT INSERT ,`app_delete`@`%`, LOCK TABLES , UPDATE, SELECT ON *.* "" ""TO 'empty'@'localhost';"", rewritten); EXPECT_EQ(0, check_privileges( ""REVOKE CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE "" ""TEMPORARY TABLES, LOCK TABLES, CREATE VIEW, CREATE ROUTINE, "" ""ALTER ROUTINE, EVENT, TRIGGER ON `sys`.* FROM `root`@`%`"") .size()); EXPECT_EQ(3, check_privileges( ""REVOKE SUPER, DROP, REFERENCES, INDEX, FILE, CREATE "" ""TEMPORARY TABLES, LOCK TABLES, BINLOG_ADMIN, CREATE ROUTINE, "" ""ALTER ROUTINE, EVENT, TRIGGER ON `sys`.* FROM `root`@`%`"", &rewritten) .size()); EXPECT_EQ( ""REVOKE DROP, REFERENCES, INDEX, CREATE TEMPORARY TABLES, LOCK TABLES, "" ""CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON `sys`.* FROM "" ""`root`@`%`"", rewritten); } TEST_F(Compatibility_test, data_index_dir_option) { std::string rewritten; EXPECT_FALSE(check_create_table_for_data_index_dir_option( ""CREATE TABLE t(i int) ENGINE=MyIsam"", &rewritten)); EXPECT_TRUE(check_create_table_for_data_index_dir_option( ""CREATE TABLE t(i int) DATA DIRECTORY = 'c:/temporary directory'"", &rewritten)); EXPECT_EQ( ""CREATE TABLE t(i int) /* DATA DIRECTORY = 'c:/temporary directory'*/ "", rewritten); EXPECT_TRUE(check_create_table_for_data_index_dir_option( ""CREATE TABLE t(i int) index DIRECTORY = '\\\\tmp\\\\one\\\\t w o\\\\3'"", &rewritten)); EXPECT_EQ( ""CREATE TABLE t(i int) /* index DIRECTORY = '\\\\tmp\\\\one\\\\t w o\\\\3'*/ "", rewritten); EXPECT_TRUE( check_create_table_for_data_index_dir_option(multiline[0], &rewritten)); EXPECT_EQ( ""CREATE TABLE t(i int)\\n"" ""ENCRYPTION = 'N' \\n"" ""/* DATA DIRECTORY = '\\\\tmp' INDEX DIRECTORY = '\\\\tmp',*/ \\n"" ""ENGINE = MyISAM"", rewritten); EXPECT_TRUE( check_create_table_for_data_index_dir_option(multiline[1], &rewritten)); EXPECT_EQ( ""CREATE TABLE t (i int PRIMARY KEY) ENGINE = MyISAM\\n"" "" /* DATA DIRECTORY = '/tmp'*/ \\n"" "" ENCRYPTION = 'y'\\n"" "" PARTITION BY LIST (i) (\\n"" "" PARTITION p0 VALUES IN (0) ENGINE = MyISAM,\\n"" "" PARTITION p1 VALUES IN (1)\\n"" "" /* DATA DIRECTORY = '/tmp',*/ \\n"" "" ENGINE = BLACKHOLE\\n"" "" )"", rewritten); EXPECT_TRUE( check_create_table_for_data_index_dir_option(multiline[4], &rewritten)); EXPECT_EQ( ""CREATE TABLE `tmq` (\\n"" "" `i` int(11) NOT NULL,\\n"" "" PRIMARY KEY (`i`)\\n"" "") ENGINE=MyISAM DEFAULT CHARSET=latin1\\n"" ""/*!50100 PARTITION BY LIST (i)\\n"" ""(PARTITION p0 VALUES IN (0) ENGINE = MyISAM,\\n"" "" PARTITION p1 VALUES IN (1) -- DATA DIRECTORY = '/tmp'\\n"" "" ENGINE = MyISAM) */"", rewritten); EXPECT_TRUE( check_create_table_for_data_index_dir_option(multiline[5], &rewritten)); EXPECT_EQ(R""(CREATE TABLE `tmq` ( `i` int NOT NULL, PRIMARY KEY (`i`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci /*!50100 PARTITION BY LIST (`i`) (PARTITION p0 VALUES IN (0) -- DATA DIRECTORY = '/tmp/' ENGINE = InnoDB, PARTITION p1 VALUES IN (1) -- DATA DIRECTORY = '/tmp/' ENGINE = InnoDB) */)"", rewritten); } TEST_F(Compatibility_test, encryption_option) { std::string rewritten; auto ct = ""CREATE TABLE t(i int) ENCRYPTION 'N'""; EXPECT_TRUE(check_create_table_for_encryption_option(ct, &rewritten)); EXPECT_EQ(""CREATE TABLE t(i int) /* ENCRYPTION 'N'*/ "", rewritten); EXPECT_TRUE( check_create_table_for_encryption_option(multiline[0], &rewritten)); EXPECT_EQ( ""CREATE TABLE t(i int)\\n"" ""/* ENCRYPTION = 'N'*/ \\n"" ""DATA DIRECTORY = '\\\\tmp' INDEX DIRECTORY = '\\\\tmp',\\n"" ""ENGINE = MyISAM"", rewritten); EXPECT_TRUE( check_create_table_for_encryption_option(multiline[1], &rewritten)); EXPECT_EQ( ""CREATE TABLE t (i int PRIMARY KEY) ENGINE = MyISAM\\n"" "" DATA DIRECTORY = '/tmp'\\n"" "" /* ENCRYPTION = 'y'*/ \\n"" "" PARTITION BY LIST (i) (\\n"" "" PARTITION p0 VALUES IN (0) ENGINE = MyISAM,\\n"" "" PARTITION p1 VALUES IN (1)\\n"" "" DATA DIRECTORY = '/tmp',\\n"" "" ENGINE = BLACKHOLE\\n"" "" )"", rewritten); EXPECT_TRUE(compatibility::check_create_table_for_encryption_option( multiline[7], &rewritten)); EXPECT_EQ( ""CREATE DATABASE `dcs` /*!40100 DEFAULT CHARACTER SET latin1 COLLATE "" ""latin1_danish_ci */ /*!80016 -- DEFAULT ENCRYPTION='N'\\n"" "" */"", rewritten); } TEST_F(Compatibility_test, engine_change) { std::string rewritten; EXPECT_EQ(""MyISAM"", check_create_table_for_engine_option(multiline[0], &rewritten)); EXPECT_EQ(R""(CREATE TABLE t(i int) ENCRYPTION = 'N' DATA DIRECTORY = '\\tmp' INDEX DIRECTORY = '\\tmp', ENGINE = InnoDB)"", rewritten); EXPECT_EQ(""BLACKHOLE"", check_create_table_for_engine_option(multiline[1], &rewritten)); EXPECT_EQ(R""(CREATE TABLE t (i int PRIMARY KEY) ENGINE = InnoDB DATA DIRECTORY = '/tmp' ENCRYPTION = 'y' PARTITION BY LIST (i) ( PARTITION p0 VALUES IN (0) ENGINE = InnoDB, PARTITION p1 VALUES IN (1) DATA DIRECTORY = '/tmp', ENGINE = InnoDB ))"", rewritten); } TEST_F(Compatibility_test, tablespace_removal) { std::string rewritten; EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t1 (c1 INT, c2 INT) TABLESPACE ts_1 ENGINE NDB;"", &rewritten)); EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t1 (c1 INT, c2 INT) TABLESPACE `ts 1`;"", &rewritten)); EXPECT_EQ(""CREATE TABLE t1 (c1 INT, c2 INT) ;"", rewritten); EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t1 (c1 INT) TABLESPACE=`ts_1` ENGINE NDB"", &rewritten)); EXPECT_EQ(""CREATE TABLE t1 (c1 INT) ENGINE NDB"", rewritten); EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t1 (c1 INT) ENGINE NDB, TABLESPACE= ts_1"", &rewritten)); EXPECT_EQ(""CREATE TABLE t1 (c1 INT) ENGINE NDB"", rewritten); EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t1 (c1 INT) TABLESPACE =ts_1"", &rewritten)); EXPECT_EQ(""CREATE TABLE t1 (c1 INT) "", rewritten); EXPECT_TRUE(check_create_table_for_tablespace_option( ""CREATE TABLE t(i int) ENCRYPTION = 'N' DATA DIRECTORY = '\\tmp', "" ""/*!50100 TABLESPACE `t s 1` */ ENGINE = InnoDB;"", &rewritten)); EXPECT_EQ( ""CREATE TABLE t(i int) ENCRYPTION = 'N' DATA DIRECTORY = '\\tmp' ENGINE = "" ""InnoDB;"", rewritten); EXPECT_TRUE( check_create_table_for_tablespace_option(multiline[6], &rewritten)); EXPECT_EQ(R""(CREATE TABLE `tmq` ( `i` int(11) NOT NULL, PRIMARY KEY (`i`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 /*!50100 PARTITION BY LIST (i) (PARTITION p0 VALUES IN (0) ENGINE = MyISAM, PARTITION p1 VALUES IN (1) ENGINE = MyISAM) */)"", rewritten); } TEST_F(Compatibility_test, charset_option) { std::string rewritten; EXPECT_EQ(2, compatibility::check_statement_for_charset_option( R""(CREATE TABLE `dsc` ( `v` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `v1` varchar(10) COLLATE latin1_danish_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1 COLLATE=latin1_danish_ci)"", &rewritten) .size()); EXPECT_EQ(R""(CREATE TABLE `dsc` ( `v` varchar(20) DEFAULT NULL, `v1` varchar(10) DEFAULT NULL ) ENGINE=InnoDB )"", rewritten); EXPECT_EQ(1, compatibility::check_statement_for_charset_option(multiline[7], &rewritten) .size()); EXPECT_EQ(""CREATE DATABASE `dcs` /*!80016 DEFAULT ENCRYPTION='N' */"", rewritten); } TEST_F(Compatibility_test, definer_option) { std::string rewritten; EXPECT_EQ( ""`root`@`localhost`"", compatibility::check_statement_for_definer_clause( R""(CREATE DEFINER=`root`@`localhost` PROCEDURE `bug9056_proc2`(OUT a INT) BEGIN select sum(id) from tr1 into a; END ;;)"", &rewritten)); EXPECT_EQ(R""(CREATE PROCEDURE `bug9056_proc2`(OUT a INT) BEGIN select sum(id) from tr1 into a; END ;;)"", rewritten); EXPECT_EQ( ""`root`@`localhost`"", compatibility::check_statement_for_definer_clause( R""(CREATE DEFINER = `root`@`localhost` FUNCTION `bug9056_func2`(f1 char binary) RETURNS char(1) CHARSET utf8mb4 begin set f1= concat( 'hello', f1 ); return f1; end ;;)"", &rewritten)); EXPECT_EQ( R""(CREATE FUNCTION `bug9056_func2`(f1 char binary) RETURNS char(1) CHARSET utf8mb4 begin set f1= concat( 'hello', f1 ); return f1; end ;;)"", rewritten); EXPECT_EQ(""`root`@`localhost`"", compatibility::check_statement_for_definer_clause( ""/*!50106 CREATE DEFINER=`root` @ `localhost` EVENT IF NOT "" ""EXISTS `ee1` "" ""ON "" ""SCHEDULE AT '2035-12-31 20:01:23' ON COMPLETION NOT PRESERVE "" ""ENABLE DO "" ""set @a=5 */ ;;"", &rewritten)); EXPECT_EQ( ""/*!50106 CREATE EVENT IF NOT EXISTS `ee1` ON "" ""SCHEDULE AT '2035-12-31 "" ""20:01:23' ON COMPLETION NOT PRESERVE ENABLE DO set @a=5 */ ;;"", rewritten); EXPECT_EQ( ""`root`@`localhost`"", compatibility::check_statement_for_definer_clause( ""/*!50001 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL "" ""SECURITY DEFINER VIEW `v3` AS select `tv1`.`a` AS `a`,`tv1`.`b` AS "" ""`b`,`tv1`.`c` AS `c` from `tv1` */;"", &rewritten)); EXPECT_EQ( ""/*!50001 CREATE ALGORITHM=UNDEFINED SQL SECURITY "" ""DEFINER VIEW `v3` AS "" ""select `tv1`.`a` AS `a`,`tv1`.`b` AS `b`,`tv1`.`c` AS `c` from `tv1` "" ""*/;"", rewritten); EXPECT_EQ( ""`root`@`localhost`"", compatibility::check_statement_for_definer_clause( R""(/*!50003 CREATE DEFINER=`root`@`localhost` TRIGGER `trg4` BEFORE INSERT ON `t2` FOR EACH ROW begin if new.a > 10 then set @fired:= ""No""; end if; end */;;)"", &rewritten)); EXPECT_EQ( R""(/*!50003 CREATE TRIGGER `trg4` BEFORE INSERT ON `t2` FOR EACH ROW begin if new.a > 10 then set @fired:= ""No""; end if; end */;;)"", rewritten); } TEST_F(Compatibility_test, sql_security_clause) { std::string rewritten; EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE DEFINER = `root`@`localhost` FUNCTION `bug9056_func2`(f1 char binary) RETURNS char(1) SQL SECURITY DEFINER CHARSET utf8mb4 begin set f1= concat( 'hello', f1 ); return f1; end ;;)"", &rewritten)); EXPECT_EQ( R""(CREATE DEFINER = `root`@`localhost` FUNCTION `bug9056_func2`(f1 char binary) RETURNS char(1) SQL SECURITY INVOKER CHARSET utf8mb4 begin set f1= concat( 'hello', f1 ); return f1; end ;;)"", rewritten); EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE procedure test.for_loop_example() wholeblock:BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = -5; SET str = ''; loop_label: LOOP IF x > 0 THEN LEAVE loop_label; END IF; SET str = CONCAT(str,x,','); SET x = x + 1; ITERATE loop_label; END LOOP; SELECT str; END//)"", &rewritten)); EXPECT_EQ(R""(CREATE procedure test.for_loop_example() SQL SECURITY INVOKER wholeblock:BEGIN DECLARE x INT; DECLARE str VARCHAR(255); SET x = -5; SET str = ''; loop_label: LOOP IF x > 0 THEN LEAVE loop_label; END IF; SET str = CONCAT(str,x,','); SET x = x + 1; ITERATE loop_label; END LOOP; SELECT str; END//)"", rewritten); EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( ""/*!50001 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL "" ""SECURITY DEFINER VIEW `v3` AS select `tv1`.`a` AS `a`,`tv1`.`b` AS "" ""`b`,`tv1`.`c` AS `c` from `tv1` */;"", &rewritten)); EXPECT_EQ( ""/*!50001 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL "" ""SECURITY INVOKER VIEW `v3` AS select `tv1`.`a` AS `a`,`tv1`.`b` AS "" ""`b`,`tv1`.`c` AS `c` from `tv1` */;"", rewritten); EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8mb4 DETERMINISTIC RETURN CONCAT('Hello, ',s,'!'))"", &rewritten)); EXPECT_EQ( R""(CREATE DEFINER=`root`@`localhost` FUNCTION `hello`(s CHAR(20)) RETURNS char(50) CHARSET utf8mb4 DETERMINISTIC SQL SECURITY INVOKER RETURN CONCAT('Hello, ',s,'!'))"", rewritten); EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE DEFINER=`root`@`localhost` PROCEDURE `p1`() BEGIN UPDATE t1 SET counter = counter + 1; END)"", &rewritten)); EXPECT_EQ(R""(CREATE DEFINER=`root`@`localhost` PROCEDURE `p1`() SQL SECURITY INVOKER BEGIN UPDATE t1 SET counter = counter + 1; END)"", rewritten); EXPECT_TRUE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE FUNCTION `func1`() RETURNS int(11) NO SQL RETURN 0)"", &rewritten)); EXPECT_EQ(R""(CREATE FUNCTION `func1`() RETURNS int(11) NO SQL SQL SECURITY INVOKER RETURN 0)"", rewritten); EXPECT_FALSE(compatibility::check_statement_for_sqlsecurity_clause( R""(CREATE FUNCTION `func2`() RETURNS int(11) NO SQL SQL SECURITY INVOKER RETURN 0)"", &rewritten)); EXPECT_FALSE(compatibility::check_statement_for_sqlsecurity_clause( ""/*!50001 CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL "" ""SECURITY INVOKER VIEW `v3` AS select `tv1`.`a` AS `a`,`tv1`.`b` AS "" ""`b`,`tv1`.`c` AS `c` from `tv1` */;"", &rewritten)); } TEST_F(Compatibility_test, create_table_combo) { const auto EXPECT_MLE = [&](size_t i, const char *res) { std::string rewritten; check_create_table_for_data_index_dir_option(multiline[i], &rewritten); check_create_table_for_encryption_option(rewritten, &rewritten); check_create_table_for_engine_option(rewritten, &rewritten); check_create_table_for_tablespace_option(rewritten, &rewritten); check_statement_for_charset_option(rewritten, &rewritten); if (res) EXPECT_EQ(res, rewritten); else puts(rewritten.c_str()); }; const auto EXPECT_UNCHANGED = [&](size_t i) { std::string rewritten; check_create_table_for_data_index_dir_option(rogue[i], &rewritten); check_create_table_for_encryption_option(rewritten, &rewritten); check_create_table_for_engine_option(rewritten, &rewritten); check_create_table_for_tablespace_option(rewritten, &rewritten); check_statement_for_charset_option(rewritten, &rewritten); EXPECT_EQ(rogue[i], rewritten); }; EXPECT_MLE(0, ""CREATE TABLE t(i int)\\n"" ""/* ENCRYPTION = 'N'*/ \\n"" ""/* DATA DIRECTORY = '\\\\tmp' INDEX DIRECTORY = '\\\\tmp',*/ \\n"" ""ENGINE = InnoDB""); EXPECT_MLE(1, ""CREATE TABLE t (i int PRIMARY KEY) ENGINE = InnoDB\\n"" "" /* DATA DIRECTORY = '/tmp'*/ \\n"" "" /* ENCRYPTION = 'y'*/ \\n"" "" PARTITION BY LIST (i) (\\n"" "" PARTITION p0 VALUES IN (0) ENGINE = InnoDB,\\n"" "" PARTITION p1 VALUES IN (1)\\n"" "" /* DATA DIRECTORY = '/tmp',*/ \\n"" "" ENGINE = InnoDB"" ""\\n )""); EXPECT_MLE( 2, ""CREATE TABLE `tmq` (\\n"" "" `i` int(11) DEFAULT NULL\\n"" "") ENGINE=InnoDB /* DATA DIRECTORY='/tmp/' INDEX DIRECTORY='/tmp/'*/ ""); EXPECT_MLE(3, ""CREATE TABLE `tmq` (\\n"" "" `i` int(11) DEFAULT NULL\\n"" "") ENGINE=InnoDB /* ENCRYPTION='N'*/ ""); EXPECT_MLE(4, ""CREATE TABLE `tmq` (\\n"" "" `i` int(11) NOT NULL,\\n"" "" PRIMARY KEY (`i`)\\n"" "") ENGINE=InnoDB \\n"" ""/*!50100 PARTITION BY LIST (i)\\n"" ""(PARTITION p0 VALUES IN (0) ENGINE = InnoDB,\\n"" "" PARTITION p1 VALUES IN (1) -- DATA DIRECTORY = '/tmp'\\n"" "" ENGINE = InnoDB) */""); EXPECT_MLE( 5, ""CREATE TABLE `tmq` (\\n"" "" `i` int NOT NULL,\\n"" "" PRIMARY KEY (`i`)\\n"" "") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci\\n"" ""/*!50100 PARTITION BY LIST (`i`)\\n"" ""(PARTITION p0 VALUES IN (0) -- DATA DIRECTORY = '/tmp/'\\n"" "" ENGINE = InnoDB,\\n"" "" PARTITION p1 VALUES IN (1) -- DATA DIRECTORY = '/tmp/'\\n"" "" ENGINE = InnoDB) */""); EXPECT_MLE(6, ""CREATE TABLE `tmq` (\\n"" "" `i` int(11) NOT NULL,\\n"" "" PRIMARY KEY (`i`)\\n"" "") ENGINE=InnoDB \\n"" ""/*!50100 PARTITION BY LIST (i)\\n"" ""(PARTITION p0 VALUES IN (0) ENGINE = InnoDB,\\n"" "" PARTITION p1 VALUES IN (1) ENGINE = InnoDB) */""); std::string rewritten; compatibility::check_statement_for_charset_option(multiline[7], &rewritten); compatibility::check_create_table_for_encryption_option(rewritten, &rewritten); EXPECT_EQ( ""CREATE DATABASE `dcs` /*!80016 -- DEFAULT ENCRYPTION='N'\\n"" "" */"", rewritten); EXPECT_UNCHANGED(0); EXPECT_UNCHANGED(1); } TEST_F(Compatibility_test, indexes) { std::string rewritten; std::vector idxs; EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE `author` ( `author` varchar(200) DEFAULT NULL, `age` int DEFAULT NULL, FULLTEXT KEY `author` (`author`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", false, &rewritten)); ASSERT_EQ(1, idxs.size()); EXPECT_EQ(""FULLTEXT KEY `author` (`author`)"", idxs[0]); EXPECT_EQ(rewritten, R""(CREATE TABLE `author` ( `author` varchar(200) DEFAULT NULL, `age` int DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)""); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE `opening_lines` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`), FULLTEXT INDEX `idx` (`opening_line`), FULLTEXT key `idx2` (`author`,`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", false, &rewritten, true)); ASSERT_EQ(2, idxs.size()); EXPECT_EQ( ""ALTER TABLE `opening_lines` ADD FULLTEXT INDEX `idx` (`opening_line`);"", idxs[0]); EXPECT_EQ( ""ALTER TABLE `opening_lines` ADD FULLTEXT key `idx2` "" ""(`author`,`title`);"", idxs[1]); EXPECT_EQ(rewritten, R""(CREATE TABLE `opening_lines` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)""); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE `opening_lines` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`), FULLTEXT INDEX `idx` (`opening_line`), FULLTEXT key `idx2` (`author`,`title`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", true, &rewritten, true)); ASSERT_EQ(2, idxs.size()); EXPECT_EQ( ""ALTER TABLE `opening_lines` ADD FULLTEXT INDEX `idx` (`opening_line`);"", idxs[0]); EXPECT_EQ( ""ALTER TABLE `opening_lines` ADD FULLTEXT key `idx2` "" ""(`author`,`title`);"", idxs[1]); EXPECT_EQ(rewritten, R""(CREATE TABLE `opening_lines` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)""); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE IF NOT EXISTS `films` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, `oli` int unsigned NOT NULL, PRIMARY KEY (`id`), KEY `oli` (`oli`), FULLTEXT KEY (`opening_line`), CONSTRAINT `films_ibfk_1` FOREIGN KEY (`oli`) REFERENCES `opening_lines` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", false, &rewritten, true)); ASSERT_EQ(3, idxs.size()); EXPECT_EQ(""ALTER TABLE `films` ADD KEY `oli` (`oli`);"", idxs[0]); EXPECT_EQ(""ALTER TABLE `films` ADD FULLTEXT KEY (`opening_line`);"", idxs[1]); EXPECT_EQ( ""ALTER TABLE `films` ADD CONSTRAINT `films_ibfk_1` FOREIGN KEY (`oli`) "" ""REFERENCES `opening_lines` (`id`);"", idxs[2]); EXPECT_EQ(rewritten, R""(CREATE TABLE IF NOT EXISTS `films` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, `oli` int unsigned NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)""); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE IF NOT EXISTS `films` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, `oli` int unsigned NOT NULL, PRIMARY KEY (`id`), KEY `oli` (`oli`), FULLTEXT KEY (`opening_line`), CONSTRAINT `films_ibfk_1` FOREIGN KEY (`oli`) REFERENCES `opening_lines` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", true, &rewritten, true)); ASSERT_EQ(1, idxs.size()); EXPECT_EQ(""ALTER TABLE `films` ADD FULLTEXT KEY (`opening_line`);"", idxs[0]); EXPECT_EQ(rewritten, R""(CREATE TABLE IF NOT EXISTS `films` ( `id` int unsigned NOT NULL AUTO_INCREMENT, `opening_line` text, `author` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, `oli` int unsigned NOT NULL, PRIMARY KEY (`id`), KEY `oli` (`oli`), CONSTRAINT `films_ibfk_1` FOREIGN KEY (`oli`) REFERENCES `opening_lines` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)""); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE part_tbl2 ( pk INT PRIMARY KEY, xx INT GENERATED ALWAYS AS (pk+2) ) PARTITION BY HASH(pk) ( PARTITION p1 DATA DIRECTORY = '${TMPDIR}/test datadir', PARTITION p2 DATA DIRECTORY = '${TMPDIR}/test datadir2' );)"", false)); EXPECT_TRUE(idxs.empty()); // auto_increment key should not be extracted EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE `aik` ( `id` int NOT NULL, `uai` int NOT NULL AUTO_INCREMENT, `data` text, PRIMARY KEY (`id`), KEY `uai` (`uai`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci)"", false, &rewritten, true)); EXPECT_TRUE(idxs.empty()); EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( R""(CREATE TABLE IF NOT EXISTS `page_restrictions` ( `pr_page` int NOT NULL DEFAULT '0', `pr_type` varbinary(255) NOT NULL DEFAULT '', `pr_level` varbinary(255) NOT NULL DEFAULT '', `pr_cascade` tinyint NOT NULL DEFAULT '0', `pr_user` int unsigned DEFAULT NULL, `pr_expiry` varbinary(14) DEFAULT NULL, `pr_id` int unsigned NOT NULL AUTO_INCREMENT, PRIMARY KEY (`pr_page`,`pr_type`), UNIQUE KEY `pr_id` (`pr_id`), KEY `pr_page` (`pr_page`), KEY `pr_typelevel` (`pr_type`,`pr_level`), KEY `pr_level` (`pr_level`), KEY `pr_cascade` (`pr_cascade`) ) ENGINE=InnoDB AUTO_INCREMENT=854046 DEFAULT CHARSET=binary;)"", false, &rewritten, true)); ASSERT_EQ(4, idxs.size()); EXPECT_EQ(""ALTER TABLE `page_restrictions` ADD KEY `pr_page` (`pr_page`);"", idxs[0]); EXPECT_EQ( ""ALTER TABLE `page_restrictions` ADD KEY `pr_typelevel` "" ""(`pr_type`,`pr_level`);"", idxs[1]); EXPECT_EQ(""ALTER TABLE `page_restrictions` ADD KEY `pr_level` (`pr_level`);"", idxs[2]); EXPECT_EQ( ""ALTER TABLE `page_restrictions` ADD KEY `pr_cascade` (`pr_cascade`);"", idxs[3]); } TEST_F(Compatibility_test, indexes_recreation) { auto session = mysqlshdk::db::mysql::Session::create(); session->connect(shcore::get_connection_options(_mysql_uri)); session->execute(""drop database if exists index_recreation_test""); session->execute(""create database index_recreation_test""); session->execute(""use index_recreation_test""); const auto check_recreation_one = [&](const std::string &table_name, const char *ddl, int index_count, bool fulltext_only) { SCOPED_TRACE(table_name); ASSERT_NO_THROW(session->execute(ddl)); auto create_table = session->query(""show create table "" + table_name) ->fetch_one() ->get_string(1); std::string rewritten; std::vector idxs; EXPECT_NO_THROW(idxs = compatibility::check_create_table_for_indexes( create_table, fulltext_only, &rewritten, true)); EXPECT_EQ(index_count, idxs.size()); if (idxs.size() == 0) return; ASSERT_NO_THROW(session->execute(""drop table "" + table_name)); ASSERT_NO_THROW(session->execute(rewritten)); for (const auto &q : idxs) { ASSERT_NO_THROW(session->execute(q)); } EXPECT_EQ(create_table, session->query(""show create table "" + table_name) ->fetch_one() ->get_string(1)); }; const auto check_recreation = [&](const std::string &table_name, const char *ddl, int index_count, int ft_index_count) { check_recreation_one(table_name, ddl, index_count, false); ASSERT_NO_THROW(session->execute(""drop table "" + table_name)); check_recreation_one(table_name, ddl, ft_index_count, true); ASSERT_NO_THROW(session->execute(""drop table "" + table_name)); }; check_recreation(""t1"", ""create table t1 (i int primary key, j int unique)"", 1, 0); check_recreation( ""t2"", ""create table t2 (i int, j int, t text, fulltext (t), primary key (i,j))"", 1, 1); check_recreation(""t3"", R""(CREATE TABLE t3 ( id INT NOT NULL, `SPATIAL` TEXT, `FULLTEXT` LONGTEXT, FULLTEXT `UNIQUE` (`SPATIAL`), FULLTEXT `SPATIAL` (`SPATIAL`, `FULLTEXT`), PRIMARY KEY (id) ) ENGINE=INNODB;)"", 2, 2); check_recreation(""t4"", R""(CREATE TABLE t4 ( id INT NOT NULL, t1 TEXT, `fulltext` VARCHAR(32), FULLTEXT KEY `fulltext` (t1), UNIQUE (`fulltext`), PRIMARY KEY (id) ) ENGINE=INNODB;)"", 2, 1); check_recreation_one(""parent"", R""(CREATE TABLE parent ( id INT NOT NULL, PRIMARY KEY (id) ) ENGINE=INNODB;)"", 0, false); check_recreation_one(""child"", R""(CREATE TABLE child ( id INT, category INT NOT NULL, parent_id INT CHECK (parent_id <> 666), first_words TEXT, PRIMARY KEY(category, id), INDEX par_ind (parent_id), FULLTEXT(first_words), FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE ) ENGINE=INNODB;)"", 3, false); check_recreation_one(""parentf"", R""(CREATE TABLE parentf ( id INT NOT NULL, PRIMARY KEY (id) ) ENGINE=INNODB;)"", 0, true); check_recreation_one(""childf"", R""(CREATE TABLE childf ( id INT, category INT NOT NULL, parent_id INT CHECK (parent_id <> 666), first_words TEXT, PRIMARY KEY(category, id), INDEX par_ind (parent_id), FULLTEXT(first_words), FOREIGN KEY (parent_id) REFERENCES parentf(id) ON DELETE CASCADE ) ENGINE=INNODB;)"", 1, true); check_recreation(""pair"", R""(CREATE TABLE pair ( no INT NOT NULL AUTO_INCREMENT, product_category INT NOT NULL, product_id INT NOT NULL, customer_id INT NOT NULL UNIQUE, customer_hash INT NOT NULL, CHECK (customer_id >= customer_hash), PRIMARY KEY(no), INDEX (product_category, product_id), INDEX (customer_id), FOREIGN KEY (product_category, product_id) REFERENCES child(category, id) ON UPDATE CASCADE ON DELETE RESTRICT, FOREIGN KEY (customer_id) REFERENCES parent(id) ) ENGINE=INNODB;)"", 5, 0); check_recreation(""jemp"", R""(CREATE TABLE jemp ( c JSON, g INT GENERATED ALWAYS AS (c->""$.id""), geo GEOMETRY NOT NULL, SPATIAL INDEX(geo), INDEX i (g) );)"", 2, 0); check_recreation(""part_tbl2"", R""(CREATE TABLE part_tbl2 ( pk INT PRIMARY KEY, idx INT, xx INT GENERATED ALWAYS AS (pk+2), INDEX (idx) ) PARTITION BY HASH(pk) ( PARTITION p1, PARTITION p2 );)"", 1, 0); session->execute(""drop database index_recreation_test""); } std::vector tokenize(const std::string &s) { std::vector tokens; mysqlshdk::utils::SQL_iterator it(s, 0, false); while (it.valid()) { tokens.push_back(it.get_next_token()); } return tokens; } TEST_F(Compatibility_test, filter_revoke_parsing) { // this just checks parsing of revoke stmts tests::String_combinator combinator( ""REVOKE {grants} ON {type} {level} FROM {user}""); std::vector grant_test_cases = { ""SELECT"", ""SELECT, INSERT, DELETE"", ""CREATE TEMPORARY TABLES, EVENT"", ""SELECT (col1, col2) ,INSERT(col)""}; combinator.add(""grants"", grant_test_cases); combinator.add(""type"", {"""", ""TABLE"", ""FUNCTION"", ""PROCEDURE""}); combinator.add(""level"", {""*"", ""*.*"", ""bla.*"", ""`FROM`.`TO`"", ""bla.` `""}); combinator.add(""user"", {""root@localhost"", ""root@'%'"", ""`FROM`@localhost"", ""'FROM'@localhost"", ""\\""FROM\\""@localhost""}); std::string stmt = combinator.get(); while (!stmt.empty()) { SCOPED_TRACE(stmt); std::string expected_grants = combinator.get(""grants""); expected_grants = shcore::str_replace(expected_grants, "" "", """"); auto filter = [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_TRUE(is_revoke); // strip privs we've seen from the expected list std::string r = shcore::str_replace( expected_grants, shcore::str_replace(priv_type, "" "", """") + column_list, """"); EXPECT_NE(r, expected_grants) << priv_type << ""/"" << column_list; expected_grants = r; EXPECT_EQ(combinator.get(""type""), object_type); EXPECT_EQ(combinator.get(""level""), priv_level); return true; }; EXPECT_EQ(tokenize(stmt), tokenize(filter_grant_or_revoke(stmt, filter))); // this should be empty now expected_grants = shcore::str_replace(expected_grants, "","", """"); EXPECT_EQ("""", expected_grants); stmt = combinator.get(); } EXPECT_EQ( ""REVOKE role@'%' FROM 'admin'@'%';"", filter_grant_or_revoke( ""REVOKE role@'%' FROM 'admin'@'%';"", [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_TRUE(is_revoke); EXPECT_EQ(priv_type, ""role@'%'""); EXPECT_EQ(column_list, """"); EXPECT_EQ(object_type, """"); EXPECT_EQ(priv_level, """"); return true; })); EXPECT_EQ( ""REVOKE PROXY ON ''@'' FROM 'admin'@'%';"", filter_grant_or_revoke( ""REVOKE PROXY ON ''@'' FROM 'admin'@'%';"", [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_TRUE(is_revoke); EXPECT_EQ(priv_type, ""PROXY""); EXPECT_EQ(column_list, """"); EXPECT_EQ(object_type, """"); EXPECT_EQ(priv_level, """"); return true; })); } TEST_F(Compatibility_test, filter_grant_parsing) { tests::String_combinator combinator( ""GRANT {grants} ON {type} {level} TO {user}{extras}""); std::vector grant_test_cases = { ""SELECT"", ""SELECT, INSERT, DELETE"", ""CREATE TEMPORARY TABLES, EVENT"", ""SELECT (col1, col2) ,INSERT(col)""}; combinator.add(""grants"", grant_test_cases); combinator.add(""type"", {"""", ""TABLE"", ""FUNCTION"", ""PROCEDURE""}); combinator.add(""level"", {""*"", ""*.*"", ""bla.*"", ""a.b"", ""`FROM`.`TO`"", ""bla.` `""}); combinator.add(""user"", {""root@localhost"", ""root@'%'"", ""`FROM`@localhost"", ""'FROM'@localhost"", ""\\""FROM\\""@localhost"", ""`aaa`@`bbbb`""}); combinator.add(""extras"", {"" WITH GRANT OPTION"", """"}); std::string stmt = combinator.get(); while (!stmt.empty()) { SCOPED_TRACE(stmt); std::string expected_grants = combinator.get(""grants""); expected_grants = shcore::str_replace(expected_grants, "" "", """"); auto filter = [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_FALSE(is_revoke); // strip privs we've seen from the expected list std::string r = shcore::str_replace( expected_grants, shcore::str_replace(priv_type, "" "", """") + column_list, """"); EXPECT_NE(r, expected_grants) << priv_type << ""/"" << column_list << ""/""; expected_grants = r; EXPECT_EQ(combinator.get(""type""), object_type); EXPECT_EQ(combinator.get(""level""), priv_level); return true; }; EXPECT_EQ(tokenize(stmt), tokenize(filter_grant_or_revoke(stmt, filter))); // this should be empty now expected_grants = shcore::str_replace(expected_grants, "","", """"); EXPECT_EQ("""", expected_grants); stmt = combinator.get(); } EXPECT_EQ( ""GRANT PROXY ON ''@'' TO 'admin'@'%' WITH GRANT OPTION;"", filter_grant_or_revoke( ""GRANT PROXY ON ''@'' TO 'admin'@'%' WITH GRANT OPTION;"", [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_FALSE(is_revoke); EXPECT_EQ(priv_type, ""PROXY""); EXPECT_EQ(column_list, """"); EXPECT_EQ(object_type, """"); EXPECT_EQ(priv_level, """"); return true; })); EXPECT_EQ( ""GRANT `administrator`@`%` TO `admin`@`%` WITH ADMIN OPTION;"", filter_grant_or_revoke( ""GRANT `administrator`@`%` TO `admin`@`%` WITH ADMIN OPTION;"", [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_FALSE(is_revoke); EXPECT_EQ(priv_type, ""`administrator`@`%`""); EXPECT_EQ(column_list, """"); EXPECT_EQ(object_type, """"); EXPECT_EQ(priv_level, """"); return true; })); EXPECT_EQ( ""GRANT administrator TO `admin`@`%` WITH ADMIN OPTION;"", filter_grant_or_revoke( ""GRANT administrator TO `admin`@`%` WITH ADMIN OPTION;"", [&](bool is_revoke, const std::string &priv_type, const std::string &column_list, const std::string &object_type, const std::string &priv_level) { EXPECT_FALSE(is_revoke); EXPECT_EQ(priv_type, ""administrator""); EXPECT_EQ(column_list, """"); EXPECT_EQ(object_type, """"); EXPECT_EQ(priv_level, """"); return true; })); } TEST_F(Compatibility_test, filter_revoke) { auto update_filter = [](bool is_revoke, const std::string &priv_type, const std::string &, const std::string &, const std::string &priv_level) { EXPECT_TRUE(is_revoke); if (priv_level == ""mysql.*"") { if (priv_type == ""insert"" || priv_type == ""delete"" || priv_type == ""update"") return false; } return true; }; EXPECT_EQ(""REVOKE select on mysql.* from root@localhost"", filter_grant_or_revoke(""REVOKE select, insert, update, delete on "" ""mysql.* from root@localhost"", update_filter)); EXPECT_EQ( ""REVOKE select, insert, update, delete on mysqlx.* from root@localhost"", filter_grant_or_revoke(""REVOKE select, insert, update, delete on "" ""mysqlx.* from root@localhost"", update_filter)); EXPECT_EQ(""revoke select(col1) on mysql.* from root@localhost"", filter_grant_or_revoke( ""revoke select (col1), insert (col2), update, delete on "" ""mysql.* from root@localhost"", update_filter)); EXPECT_EQ("""", filter_grant_or_revoke(""revoke insert, update, delete on "" ""mysql.* from root@localhost"", update_filter)); } TEST_F(Compatibility_test, filter_grant) { auto update_filter = [](bool is_revoke, const std::string &priv_type, const std::string &, const std::string &, const std::string &priv_level) { EXPECT_FALSE(is_revoke); if (priv_level == ""mysql.*"") { if (priv_type == ""insert"" || priv_type == ""delete"" || priv_type == ""update"") return false; } return true; }; EXPECT_EQ(""GRANT select on mysql.* to root@localhost"", filter_grant_or_revoke(""GRANT select, insert, update, delete on "" ""mysql.* to root@localhost"", update_filter)); EXPECT_EQ( ""GRANT select, insert, update, delete on mysqlx.* to root@localhost"", filter_grant_or_revoke(""GRANT select, insert, update, delete on "" ""mysqlx.* to root@localhost"", update_filter)); EXPECT_EQ(""GRANT select(col1) on mysql.* to root@localhost"", filter_grant_or_revoke( ""GRANT select (col1), insert (col2), update, delete on "" ""mysql.* to root@localhost"", update_filter)); EXPECT_EQ("""", filter_grant_or_revoke(""grant insert, update, delete on "" ""mysql.* to root@localhost"", update_filter)); } TEST_F(Compatibility_test, filter_grant_malformed) { auto filter = [](bool, const std::string &, const std::string &, const std::string &, const std::string &) { return true; }; EXPECT_THROW(filter_grant_or_revoke(""grant"", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""grant on"", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""grant on table"", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""revoke *.*"", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""revoke from"", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""revoke from ("", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""revoke x ("", filter), std::runtime_error); EXPECT_THROW(filter_grant_or_revoke(""revoke on all on bla"", filter), std::runtime_error); } TEST_F(Compatibility_test, create_user) { const std::string exception = ""Authentication plugin check can be only performed on CREATE USER "" ""statements""; // unsupported statements EXPECT_THROW_LIKE(check_create_user_for_authentication_plugin(""""), std::runtime_error, exception); EXPECT_THROW_LIKE(check_create_user_for_authentication_plugin(""CREATE""), std::runtime_error, exception); EXPECT_THROW_LIKE(check_create_user_for_authentication_plugin(""create Table""), std::runtime_error, exception); // statements without authentication plugin EXPECT_EQ("""", check_create_user_for_authentication_plugin(""CREATE USER r@l;"")); EXPECT_EQ( """", check_create_user_for_authentication_plugin(""CREATE USER 'r'@'l';"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin(""CREATE USER 'r'@l;"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin(""CREATE USER r@'l';"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER if not exists 'r'@'l';"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED BY 'pass';"")); // unknown plugin not in the default list EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED with 'plugin';"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER 'r'@'l' identified WITH 'plugin';"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER r@'l' identified WITH 'plugin';"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER 'r'@l identified WITH 'plugin';"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER if NOT Exists 'r'@'l' IDENTIFIED WITH 'plugin';"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH \\""plugin\\"""")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH `plugin`"")); EXPECT_EQ(""plugin"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH plugin"")); // plugins on the default list EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'caching_sha2_password'"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'mysql_native_password'"")); EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'sha256_password'"")); // disallowed plugins EXPECT_EQ(""authentication_ldap_sasl"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'authentication_ldap_sasl'"")); EXPECT_EQ( ""authentication_ldap_simple"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'authentication_ldap_simple'"")); EXPECT_EQ(""authentication_pam"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'authentication_pam'"")); EXPECT_EQ(""authentication_windows"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'authentication_windows'"")); // plugins which are not enabled EXPECT_EQ(""auth_socket"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'auth_socket'"")); EXPECT_EQ(""mysql_no_login"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'mysql_no_login'"")); // non-default list EXPECT_EQ("""", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'plugin_a'"", {""plugin_a""})); EXPECT_EQ(""PLUGIN_A"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'PLUGIN_A'"", {""plugin_a""})); EXPECT_EQ(""plugin_b"", check_create_user_for_authentication_plugin( ""CREATE USER r@l IDENTIFIED WITH 'plugin_b'"", {""plugin_a""})); } TEST_F(Compatibility_test, add_invisible_pk) { const auto EXPECT_PK = [](const std::string &statement) { SCOPED_TRACE(statement); std::string result; EXPECT_NO_THROW(add_pk_to_create_table(statement, &result)); const std::string pk = "",`my_row_id` BIGINT UNSIGNED AUTO_INCREMENT INVISIBLE PRIMARY KEY""; const auto pos = statement.find_last_of(')'); const auto expected = statement.substr(0, pos) + pk + statement.substr(pos); EXPECT_EQ(expected, result) << ""PK should be added""; }; { const std::string exception = ""Invisible primary key can be only added to CREATE TABLE statements""; std::string result; // unsupported statements EXPECT_THROW_LIKE(add_pk_to_create_table("""", &result), std::runtime_error, exception); EXPECT_THROW_LIKE(add_pk_to_create_table(""CREATE"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE(add_pk_to_create_table(""create User"", &result), std::runtime_error, exception); } { const std::string exception = ""Unsupported CREATE TABLE statement""; std::string result; EXPECT_THROW_LIKE( add_pk_to_create_table(""create table s.t2 like s.t1"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table( ""CREATE TABLE new_tbl AS SELECT * FROM orig_tbl;"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table(""CREATE TABLE new_tbl SELECT * FROM orig_tbl;"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table(""CREATE TABLE bar (m INT) AS SELECT n FROM foo"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table(""CREATE TABLE bar (m INT) SELECT n FROM foo"", &result), std::runtime_error, exception); } EXPECT_PK(""create table s.t (c int)""); EXPECT_PK(""CREATE TABLE IF NOT EXISTS s.t (c int) Engine = InnoDB;""); EXPECT_PK(""create table s.t (c int, Index i (c))""); EXPECT_PK( ""create table s.t (key USING BTREE (d, c) COMMENT 'string', c int, d "" ""int)""); EXPECT_PK( ""create table t (FULLTEXT x (c), c int, spatial (d, (expr)), d int)""); EXPECT_PK(""create table t (CONSTRAINT FOREIGN KEY (x.t), c int)""); EXPECT_PK(""create table t (c int, CONSTRAINT symbol FOREIGN KEY (x.t))""); EXPECT_PK(""create table t (FOREIGN KEY (x.t), c int)""); EXPECT_PK(""create table t (c int, CONSTRAINT CHECK (expr (expr)))""); EXPECT_PK( ""create table t (CONSTRAINT symbol CHECK (expr (expr)) ENFORCED,c int)""); EXPECT_PK(""create table t (c int, CHECK ((expr) expr))""); EXPECT_PK(""create table t (c int, CONSTRAINT PRIMARY KEY USING BTREE (c))""); EXPECT_PK( ""create table t (CONSTRAINT symbol PRIMARY KEY (c) USING BTREE, c int)""); EXPECT_PK(""create table t (c int, PRIMARY KEY (c, d), d int)""); EXPECT_PK(""create table t (CONSTRAINT UNIQUE KEY (c), `c` int NOT NULL)""); EXPECT_PK( ""create table t (c int NULL, CONSTRAINT symbol UNIQUE INDEX (`c`) "" ""KEY_BLOCK_SIZE = 7)""); EXPECT_PK(""create table t (UNIQUE (`c`), c int DEFAULT 1 NOT NULL)""); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u (`c`(7), d DESC), c int "" ""DEFAULT 1 NOT NULL)""); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u ((expr), d, (expr) ASC, c "" ""(1)), c int DEFAULT 1 NOT NULL)""); } TEST_F(Compatibility_test, add_invisible_pk_if_missing) { const auto EXPECT_PK = [](const std::string &statement, bool pk_added, bool ignore_pke = true) { SCOPED_TRACE(statement); std::string result; EXPECT_EQ(pk_added, add_pk_to_create_table_if_missing(statement, &result, ignore_pke)); if (pk_added) { const std::string pk = "",`my_row_id` BIGINT UNSIGNED AUTO_INCREMENT INVISIBLE PRIMARY KEY""; const auto pos = statement.find_last_of(')'); const auto expected = statement.substr(0, pos) + pk + statement.substr(pos); EXPECT_EQ(expected, result) << ""PK should be added""; } else { EXPECT_EQ("""", result) << ""Result should be empty""; } }; { const std::string exception = ""Invisible primary key can be only added to CREATE TABLE statements""; std::string result; // unsupported statements EXPECT_THROW_LIKE(add_pk_to_create_table_if_missing("""", &result), std::runtime_error, exception); EXPECT_THROW_LIKE(add_pk_to_create_table_if_missing(""CREATE"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE(add_pk_to_create_table_if_missing(""create User"", &result), std::runtime_error, exception); } { const std::string exception = ""Unsupported CREATE TABLE statement""; std::string result; EXPECT_THROW_LIKE(add_pk_to_create_table_if_missing( ""create table s.t2 like s.t1"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE(add_pk_to_create_table_if_missing( ""create table s.t2 (like s.t1)"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table_if_missing( ""CREATE TABLE new_tbl AS SELECT * FROM orig_tbl;"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table_if_missing( ""CREATE TABLE new_tbl SELECT * FROM orig_tbl;"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table_if_missing( ""CREATE TABLE bar (m INT) AS SELECT n FROM foo"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table_if_missing( ""CREATE TABLE bar (m INT) SELECT n FROM foo"", &result), std::runtime_error, exception); EXPECT_THROW_LIKE( add_pk_to_create_table_if_missing( ""CREATE TABLE bar (m INT NOT NULL, Unique (m)) SELECT n FROM foo"", &result), std::runtime_error, exception); } EXPECT_PK(""create table s.t (c int)"", true); EXPECT_PK(""CREATE TABLE IF NOT EXISTS s.t (c int) Engine = InnoDB;"", true); EXPECT_PK(""create table s.t (c int, Index i (c))"", true); EXPECT_PK( ""create table s.t (key USING BTREE (d, c) COMMENT 'string', c int, d "" ""int)"", true); EXPECT_PK( ""create table t (FULLTEXT x (c), c int, spatial (d, (expr)), d int)"", true); EXPECT_PK(""create table t (CONSTRAINT FOREIGN KEY (x.t), c int)"", true); EXPECT_PK(""create table t (c int, CONSTRAINT symbol FOREIGN KEY (x.t))"", true); EXPECT_PK(""create table t (FOREIGN KEY (x.t), c int)"", true); EXPECT_PK(""create table t (c int, CONSTRAINT CHECK (expr (expr)))"", true); EXPECT_PK( ""create table t (CONSTRAINT symbol CHECK (expr (expr)) ENFORCED,c int)"", true); EXPECT_PK(""create table t (c int, CHECK ((expr) expr))"", true); EXPECT_PK(""create table t (c int, CONSTRAINT PRIMARY KEY USING BTREE (c))"", false); EXPECT_PK( ""create table t (CONSTRAINT symbol PRIMARY KEY (c) USING BTREE, c int)"", false); EXPECT_PK(""create table t (c int, PRIMARY KEY (c, d), d int)"", false); EXPECT_PK(""create table t (CONSTRAINT UNIQUE KEY (c), `c` int NOT NULL)"", true); EXPECT_PK( ""create table t (c int NULL, CONSTRAINT symbol UNIQUE INDEX (`c`) "" ""KEY_BLOCK_SIZE = 7)"", true); EXPECT_PK(""create table t (UNIQUE (`c`), c int DEFAULT 1 NOT NULL)"", true); EXPECT_PK(""create table t (CONSTRAINT UNIQUE KEY (c), `c` int NOT NULL)"", false, false); EXPECT_PK( ""create table t (c int NULL, CONSTRAINT symbol UNIQUE INDEX (`c`) "" ""KEY_BLOCK_SIZE = 7)"", true, false); EXPECT_PK(""create table t (UNIQUE (`c`), c int DEFAULT 1 NOT NULL)"", false, false); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u (`c`(7), d DESC), c int "" ""DEFAULT 1 NOT NULL)"", true); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u (`c`(7), d DESC), c int "" ""DEFAULT 1 NOT NULL)"", false, false); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u ((expr), d, (expr) ASC, c "" ""(1)), c int DEFAULT 1 NOT NULL)"", true); EXPECT_PK( ""create table t (d varchar NOT NULL, UNIQUE u ((expr (expr)), d, ((expr) "" ""expr (expr)) ASC), c int DEFAULT 1 NOT NULL)"", true, false); EXPECT_PK(""create table t (c int, d bigint NULL, e varchar UNIQUE)"", true); EXPECT_PK(""create table t (c int, d bigint NULL, e varchar UNIQUE)"", true, false); EXPECT_PK(R""*(create table t ( c int REFERENCES x (a, b) ON DELETE CASCADE, d bigint NULL CHECK (expr), e varchar UNIQUE CONSTRAINT symbol CHECK (expr) ))*"", true); EXPECT_PK( ""create table t (c int REFERENCES x (a, b) ON DELETE CASCADE, d bigint "" ""NULL CHECK (expr), e varchar UNIQUE CONSTRAINT symbol CHECK (expr))"", true, false); EXPECT_PK(""create table t (c int NOT NULL PRIMARY)"", false); EXPECT_PK(""create table t (c int PRIMARY NULL)"", false); EXPECT_PK(""create table t (c int PRIMARY NULL, d varchar)"", false); EXPECT_PK(""create table t (c int PRIMARY NULL, PRIMARY KEY c)"", false); EXPECT_PK(""create table t (PRIMARY KEY c, c int PRIMARY NULL)"", false); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int PRIMARY KEY)"", false); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int PRIMARY KEY)"", false, false); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int)"", true); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int)"", false, false); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int, UNIQUE (c))"", true); EXPECT_PK(""create table t (d varchar UNIQUE NOT NULL, c int, UNIQUE (c))"", false, false); EXPECT_PK( ""create table t (d varchar UNIQUE NULL, c int NOT NULL, UNIQUE (`c`))"", true); EXPECT_PK( ""create table t (d varchar UNIQUE NULL, c int NOT NULL, UNIQUE (`c`))"", false, false); EXPECT_PK( ""create table t (d varchar UNIQUE NOT NULL, c int NOT NULL, UNIQUE (c))"", true); EXPECT_PK( ""create table t (d varchar UNIQUE NOT NULL, c int NOT NULL, UNIQUE (c))"", false, false); EXPECT_PK( ""create table t (`d` varchar NOT NULL, c int NOT NULL, UNIQUE (c, d))"", true); EXPECT_PK( ""create table t (`d` varchar NOT NULL, c int NOT NULL, UNIQUE (c, d))"", false, false); EXPECT_PK(""create table t (`d` varchar NULL, UNIQUE (c, d), c int NOT NULL)"", true); EXPECT_PK(""create table t (`d` varchar NULL, UNIQUE (d, c), c int NOT NULL)"", true, false); EXPECT_PK(""create table t (UNIQUE (c, d),`d` varchar NOT NULL, c int)"", true); EXPECT_PK(""create table t (UNIQUE (c, d),`d` varchar NOT NULL, c int)"", true, false); EXPECT_PK(""CREATE TABLE bar (m INT PRIMARY) SELECT n FROM foo"", false); EXPECT_PK(""CREATE TABLE bar (m INT, primary KEY m) SELECT n FROM foo"", false); EXPECT_PK(""CREATE TABLE bar (m INT NOT NULL, Unique (m)) SELECT n FROM foo"", false, false); } } // namespace compatibility } // namespace mysqlsh ",16235,True,2599.218478952826,median "CLASS zcl_abapgit_object_fugr DEFINITION PUBLIC INHERITING FROM zcl_abapgit_objects_program FINAL. PUBLIC SECTION. INTERFACES zif_abapgit_object. ALIASES mo_files FOR zif_abapgit_object~mo_files. PROTECTED SECTION. PRIVATE SECTION. TYPES: ty_rs38l_incl_tt TYPE STANDARD TABLE OF rs38l_incl WITH DEFAULT KEY . TYPES: BEGIN OF ty_function, funcname TYPE rs38l_fnam, global_flag TYPE rs38l-global, remote_call TYPE rs38l-remote, update_task TYPE rs38l-utask, short_text TYPE tftit-stext, remote_basxml TYPE rs38l-basxml_enabled, import TYPE STANDARD TABLE OF rsimp WITH DEFAULT KEY, changing TYPE STANDARD TABLE OF rscha WITH DEFAULT KEY, export TYPE STANDARD TABLE OF rsexp WITH DEFAULT KEY, tables TYPE STANDARD TABLE OF rstbl WITH DEFAULT KEY, exception TYPE STANDARD TABLE OF rsexc WITH DEFAULT KEY, documentation TYPE STANDARD TABLE OF rsfdo WITH DEFAULT KEY, exception_classes TYPE abap_bool, END OF ty_function . TYPES: ty_function_tt TYPE STANDARD TABLE OF ty_function WITH DEFAULT KEY . TYPES: ty_sobj_name_tt TYPE STANDARD TABLE OF sobj_name WITH DEFAULT KEY . TYPES: BEGIN OF ty_tpool_i18n, language TYPE langu, textpool TYPE zif_abapgit_definitions=>ty_tpool_tt, END OF ty_tpool_i18n . TYPES: ty_tpools_i18n TYPE STANDARD TABLE OF ty_tpool_i18n . DATA mt_includes_cache TYPE ty_sobj_name_tt . DATA mt_includes_all TYPE ty_sobj_name_tt . METHODS check_rfc_parameters IMPORTING !is_function TYPE ty_function RAISING zcx_abapgit_exception . METHODS update_where_used IMPORTING !it_includes TYPE ty_sobj_name_tt . METHODS main_name RETURNING VALUE(rv_program) TYPE program RAISING zcx_abapgit_exception . METHODS functions RETURNING VALUE(rt_functab) TYPE ty_rs38l_incl_tt RAISING zcx_abapgit_exception . METHODS includes RETURNING VALUE(rt_includes) TYPE ty_sobj_name_tt RAISING zcx_abapgit_exception . METHODS serialize_functions RETURNING VALUE(rt_functions) TYPE ty_function_tt RAISING zcx_abapgit_exception . METHODS deserialize_functions IMPORTING !it_functions TYPE ty_function_tt !ii_log TYPE REF TO zif_abapgit_log !iv_transport TYPE trkorr RAISING zcx_abapgit_exception . METHODS serialize_xml IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_xml IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_input !iv_package TYPE devclass !iv_transport TYPE trkorr RAISING zcx_abapgit_exception . METHODS serialize_includes RAISING zcx_abapgit_exception . METHODS deserialize_includes IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_input !iv_package TYPE devclass !ii_log TYPE REF TO zif_abapgit_log RAISING zcx_abapgit_exception . METHODS is_function_group_locked RETURNING VALUE(rv_is_functions_group_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_include_locked RETURNING VALUE(rv_is_any_include_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS is_any_function_module_locked RETURNING VALUE(rv_any_function_module_locked) TYPE abap_bool RAISING zcx_abapgit_exception . METHODS get_abap_version IMPORTING !ii_xml TYPE REF TO zif_abapgit_xml_input RETURNING VALUE(rv_abap_version) TYPE progdir-uccheck RAISING zcx_abapgit_exception . METHODS update_func_group_short_text IMPORTING !iv_group TYPE rs38l-area !iv_short_text TYPE tftit-stext . METHODS serialize_texts IMPORTING !iv_prog_name TYPE programm !ii_xml TYPE REF TO zif_abapgit_xml_output RAISING zcx_abapgit_exception . METHODS deserialize_texts IMPORTING !iv_prog_name TYPE programm !ii_xml TYPE REF TO zif_abapgit_xml_input RAISING zcx_abapgit_exception . METHODS belongs_incl_to_other_fugr IMPORTING !iv_include TYPE sobj_name RETURNING VALUE(rv_belongs_to_other_fugr) TYPE abap_bool. ENDCLASS. CLASS zcl_abapgit_object_fugr IMPLEMENTATION. METHOD belongs_incl_to_other_fugr. "" make sure that the include belongs to the function group "" like in LSEAPFAP Form TADIR_MAINTENANCE DATA ls_tadir TYPE tadir. DATA lv_namespace TYPE rs38l-namespace. DATA lv_area TYPE rs38l-area. DATA lv_include TYPE rs38l-include. rv_belongs_to_other_fugr = abap_false. IF iv_include(1) = 'L' OR iv_include+1 CS '/L'. lv_include = iv_include. ls_tadir-object = 'FUGR'. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' IMPORTING namespace = lv_namespace group = lv_area CHANGING include = lv_include EXCEPTIONS OTHERS = 1. IF lv_area(1) = 'X'. "" ""EXIT""-function-module ls_tadir-object = 'FUGS'. ENDIF. IF sy-subrc = 0. CONCATENATE lv_namespace lv_area INTO ls_tadir-obj_name. IF ls_tadir-obj_name <> ms_item-obj_name. rv_belongs_to_other_fugr = abap_true. ENDIF. ENDIF. ENDIF. ENDMETHOD. METHOD check_rfc_parameters. * function module RS_FUNCTIONMODULE_INSERT does the same deep down, but the right error * message is not returned to the user, this is a workaround to give a proper error * message to the user DATA: ls_parameter TYPE rsfbpara, lt_fupa TYPE rsfb_param, ls_fupa LIKE LINE OF lt_fupa. IF is_function-remote_call = 'R'. cl_fb_parameter_conversion=>convert_parameter_old_to_fupa( EXPORTING functionname = is_function-funcname import = is_function-import export = is_function-export change = is_function-changing tables = is_function-tables except = is_function-exception IMPORTING fupararef = lt_fupa ). LOOP AT lt_fupa INTO ls_fupa WHERE paramtype = 'I' OR paramtype = 'E' OR paramtype = 'C' OR paramtype = 'T'. cl_fb_parameter_conversion=>convert_intern_to_extern( EXPORTING parameter_db = ls_fupa IMPORTING parameter_vis = ls_parameter ). CALL FUNCTION 'RS_FB_CHECK_PARAMETER_REMOTE' EXPORTING parameter = ls_parameter basxml_enabled = is_function-remote_basxml EXCEPTIONS not_remote_compatible = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ENDLOOP. ENDIF. ENDMETHOD. METHOD deserialize_functions. DATA: lv_include TYPE rs38l-include, lv_area TYPE rs38l-area, lv_group TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lt_source TYPE TABLE OF abaptxt255, lv_msg TYPE string, lx_error TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF it_functions. LOOP AT it_functions ASSIGNING . lt_source = mo_files->read_abap( iv_extra = -funcname ). lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS OTHERS = 12. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. CALL FUNCTION 'FUNCTION_EXISTS' EXPORTING funcname = -funcname IMPORTING include = lv_include EXCEPTIONS function_not_exist = 1. IF sy-subrc = 0. * delete the function module to make sure the parameters are updated * havent found a nice way to update the paramters CALL FUNCTION 'FUNCTION_DELETE' EXPORTING funcname = -funcname suppress_success_message = abap_true EXCEPTIONS error_message = 1 OTHERS = 2. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. ENDIF. TRY. check_rfc_parameters( ). CATCH zcx_abapgit_exception INTO lx_error. ii_log->add_error( iv_msg = |Function module { -funcname }: { lx_error->get_text( ) }| is_item = ms_item ). CONTINUE. ""with next function module ENDTRY. CALL FUNCTION 'RS_FUNCTIONMODULE_INSERT' EXPORTING funcname = -funcname function_pool = lv_group interface_global = -global_flag remote_call = -remote_call short_text = -short_text update_task = -update_task exception_class = -exception_classes namespace = lv_namespace remote_basxml_supported = -remote_basxml corrnum = iv_transport IMPORTING function_include = lv_include TABLES import_parameter = -import export_parameter = -export tables_parameter = -tables changing_parameter = -changing exception_list = -exception parameter_docu = -documentation EXCEPTIONS double_task = 1 error_message = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 OTHERS = 11. IF sy-subrc <> 0. MESSAGE ID sy-msgid TYPE 'S' NUMBER sy-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4 INTO lv_msg. ii_log->add_error( iv_msg = |Function module { -funcname }: { lv_msg }| is_item = ms_item ). CONTINUE. ""with next function module ENDIF. INSERT REPORT lv_include FROM lt_source. ii_log->add_success( iv_msg = |Function module { -funcname } imported| is_item = ms_item ). ENDLOOP. ENDMETHOD. METHOD deserialize_includes. DATA: lo_xml TYPE REF TO zif_abapgit_xml_input, ls_progdir TYPE ty_progdir, lt_includes TYPE ty_sobj_name_tt, lt_tpool TYPE textpool_table, lt_tpool_ext TYPE zif_abapgit_definitions=>ty_tpool_tt, lt_source TYPE TABLE OF abaptxt255, lx_exc TYPE REF TO zcx_abapgit_exception. FIELD-SYMBOLS: LIKE LINE OF lt_includes. tadir_insert( iv_package ). ii_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . ""ignore simple transformation includes (as long as they remain in existing repositories) IF strlen( ) = 33 AND +30(3) = 'XTI'. ii_log->add_warning( iv_msg = |Simple Transformation include { } ignored| is_item = ms_item ). CONTINUE. ENDIF. TRY. lt_source = mo_files->read_abap( iv_extra = ). lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). lo_xml->read( EXPORTING iv_name = 'TPOOL' CHANGING cg_data = lt_tpool_ext ). lt_tpool = read_tpool( lt_tpool_ext ). deserialize_program( is_progdir = ls_progdir it_source = lt_source it_tpool = lt_tpool iv_package = iv_package ). deserialize_textpool( iv_program = it_tpool = lt_tpool iv_is_include = abap_true ). ii_log->add_success( iv_msg = |Include { ls_progdir-name } imported| is_item = ms_item ). CATCH zcx_abapgit_exception INTO lx_exc. ii_log->add_exception( ix_exc = lx_exc is_item = ms_item ). CONTINUE. ENDTRY. ENDLOOP. ENDMETHOD. METHOD deserialize_texts. DATA: lt_tpool_i18n TYPE ty_tpools_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. ii_xml->read( EXPORTING iv_name = 'I18N_TPOOL' CHANGING cg_data = lt_tpool_i18n ). LOOP AT lt_tpool_i18n ASSIGNING . lt_tpool = read_tpool( -textpool ). deserialize_textpool( iv_program = iv_prog_name iv_language = -language it_tpool = lt_tpool ). ENDLOOP. ENDMETHOD. METHOD deserialize_xml. DATA: lv_complete TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_areat TYPE tlibt-areat, lv_stext TYPE tftit-stext, lv_group TYPE rs38l-area, lv_abap_version TYPE trdir-uccheck. lv_abap_version = get_abap_version( ii_xml ). lv_complete = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_complete IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. ii_xml->read( EXPORTING iv_name = 'AREAT' CHANGING cg_data = lv_areat ). lv_stext = lv_areat. CALL FUNCTION 'RS_FUNCTION_POOL_INSERT' EXPORTING function_pool = lv_group short_text = lv_stext namespace = lv_namespace devclass = iv_package unicode_checks = lv_abap_version corrnum = iv_transport suppress_corr_check = abap_false EXCEPTIONS name_already_exists = 1 name_not_correct = 2 function_already_exists = 3 invalid_function_pool = 4 invalid_name = 5 too_many_functions = 6 no_modify_permission = 7 no_show_permission = 8 enqueue_system_failure = 9 canceled_in_corr = 10 undefined_error = 11 OTHERS = 12. CASE sy-subrc. WHEN 0. "" Everything is ok WHEN 1 OR 3. "" If the function group exists we need to manually update the short text update_func_group_short_text( iv_group = lv_group iv_short_text = lv_stext ). WHEN OTHERS. zcx_abapgit_exception=>raise_t100( ). ENDCASE. ENDMETHOD. METHOD functions. DATA: lv_area TYPE rs38l-area. FIELD-SYMBOLS: TYPE LINE OF ty_rs38l_incl_tt. lv_area = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_CONTENTS' EXPORTING function_pool = lv_area TABLES functab = rt_functab EXCEPTIONS function_pool_not_found = 1 OTHERS = 2. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. * The result can also contain function which are lowercase. LOOP AT rt_functab ASSIGNING . TRANSLATE TO UPPER CASE. ENDLOOP. SORT rt_functab BY funcname ASCENDING. DELETE ADJACENT DUPLICATES FROM rt_functab COMPARING funcname. ENDMETHOD. METHOD get_abap_version. DATA: lt_includes TYPE ty_sobj_name_tt, ls_progdir TYPE ty_progdir, lo_xml TYPE REF TO zif_abapgit_xml_input. FIELD-SYMBOLS: LIKE LINE OF lt_includes. ii_xml->read( EXPORTING iv_name = 'INCLUDES' CHANGING cg_data = lt_includes ). LOOP AT lt_includes ASSIGNING . lo_xml = mo_files->read_xml( ). lo_xml->read( EXPORTING iv_name = 'PROGDIR' CHANGING cg_data = ls_progdir ). IF ls_progdir-uccheck IS INITIAL. CONTINUE. ELSEIF rv_abap_version IS INITIAL. rv_abap_version = ls_progdir-uccheck. CONTINUE. ELSEIF rv_abap_version <> ls_progdir-uccheck. *** All includes need to have the same ABAP language version zcx_abapgit_exception=>raise( 'different ABAP Language Versions' ). ENDIF. ENDLOOP. IF rv_abap_version IS INITIAL. rv_abap_version = 'X'. ENDIF. ENDMETHOD. METHOD includes. TYPES: BEGIN OF ty_reposrc, progname TYPE reposrc-progname, END OF ty_reposrc. DATA: lt_reposrc TYPE STANDARD TABLE OF ty_reposrc WITH DEFAULT KEY, ls_reposrc LIKE LINE OF lt_reposrc, lv_program TYPE program, lv_maintviewname LIKE LINE OF rt_includes, lv_offset_ns TYPE i, lv_tabix LIKE sy-tabix, lt_functab TYPE ty_rs38l_incl_tt, lt_tadir_includes TYPE HASHED TABLE OF objname WITH UNIQUE KEY table_line. FIELD-SYMBOLS: LIKE LINE OF rt_includes, LIKE LINE OF lt_functab. IF lines( mt_includes_cache ) > 0. rt_includes = mt_includes_cache. RETURN. ENDIF. lv_program = main_name( ). lt_functab = functions( ). CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program TABLES includetab = rt_includes EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. LOOP AT lt_functab ASSIGNING . DELETE TABLE rt_includes FROM -include. ENDLOOP. * handle generated maintenance views IF ms_item-obj_name(1) <> '/'. ""FGroup name does not contain a namespace lv_maintviewname = |L{ ms_item-obj_name }T00|. ELSE. ""FGroup name contains a namespace lv_offset_ns = find( val = ms_item-obj_name+1 sub = '/' ). lv_offset_ns = lv_offset_ns + 2. lv_maintviewname = |{ ms_item-obj_name(lv_offset_ns) }L{ ms_item-obj_name+lv_offset_ns }T00|. ENDIF. READ TABLE rt_includes WITH KEY table_line = lv_maintviewname TRANSPORTING NO FIELDS. IF sy-subrc <> 0. APPEND lv_maintviewname TO rt_includes. ENDIF. IF lines( rt_includes ) > 0. "" check which includes have their own tadir entry "" these includes might reside in a different package or might be shared between multiple function groups "" or other programs and are hence no part of the to serialized FUGR object "" they will be handled as individual objects when serializing their package "" in addition, referenced XTI includes referencing (simple) transformations must be ignored SELECT obj_name INTO TABLE lt_tadir_includes FROM tadir FOR ALL ENTRIES IN rt_includes WHERE pgmid = 'R3TR' AND object = 'PROG' AND obj_name = rt_includes-table_line. LOOP AT rt_includes ASSIGNING . "" skip autogenerated includes from Table Maintenance Generator IF CP 'LSVIM*'. DELETE rt_includes INDEX sy-tabix. CONTINUE. ENDIF. READ TABLE lt_tadir_includes WITH KEY table_line = TRANSPORTING NO FIELDS. IF sy-subrc = 0. DELETE rt_includes. CONTINUE. ENDIF. IF strlen( ) = 33 AND +30(3) = 'XTI'. ""ignore referenced (simple) transformation includes DELETE rt_includes. CONTINUE. ENDIF. ENDLOOP. IF lines( rt_includes ) > 0. SELECT progname FROM reposrc INTO TABLE lt_reposrc FOR ALL ENTRIES IN rt_includes WHERE progname = rt_includes-table_line AND r3state = 'A'. ENDIF. SORT lt_reposrc BY progname ASCENDING. ENDIF. LOOP AT rt_includes ASSIGNING . lv_tabix = sy-tabix. * make sure the include exists READ TABLE lt_reposrc INTO ls_reposrc WITH KEY progname = BINARY SEARCH. IF sy-subrc <> 0. DELETE rt_includes INDEX lv_tabix. CONTINUE. ENDIF. ""Make sure that the include does not belong to another function group IF belongs_incl_to_other_fugr( iv_include = ) = abap_true. DELETE rt_includes. ENDIF. ENDLOOP. APPEND lv_program TO rt_includes. mt_includes_cache = rt_includes. ENDMETHOD. METHOD is_any_function_module_locked. DATA: lt_functions TYPE ty_rs38l_incl_tt. FIELD-SYMBOLS: TYPE rs38l_incl. TRY. lt_functions = functions( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_functions ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESFUNCTION' iv_argument = |{ -funcname }| ) = abap_true. rv_any_function_module_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_any_include_locked. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: TYPE sobj_name. TRY. lt_includes = includes( ). CATCH zcx_abapgit_exception. RETURN. ENDTRY. LOOP AT lt_includes ASSIGNING . IF exists_a_lock_entry_for( iv_lock_object = 'ESRDIRE' iv_argument = |{ }| ) = abap_true. rv_is_any_include_locked = abap_true. EXIT. ENDIF. ENDLOOP. ENDMETHOD. METHOD is_function_group_locked. DATA: lv_object TYPE eqegraarg. lv_object = |FG{ ms_item-obj_name }|. OVERLAY lv_object WITH ' '. lv_object = lv_object && '*'. rv_is_functions_group_locked = exists_a_lock_entry_for( iv_lock_object = 'EEUDB' iv_argument = lv_object ). ENDMETHOD. METHOD main_name. DATA: lv_area TYPE rs38l-area, lv_namespace TYPE rs38l-namespace, lv_group TYPE rs38l-area. lv_area = ms_item-obj_name. CALL FUNCTION 'FUNCTION_INCLUDE_SPLIT' EXPORTING complete_area = lv_area IMPORTING namespace = lv_namespace group = lv_group EXCEPTIONS include_not_exists = 1 group_not_exists = 2 no_selections = 3 no_function_include = 4 no_function_pool = 5 delimiter_wrong_position = 6 no_customer_function_group = 7 no_customer_function_include = 8 reserved_name_customer = 9 namespace_too_long = 10 area_length_error = 11 OTHERS = 12. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. CONCATENATE lv_namespace 'SAPL' lv_group INTO rv_program. ENDMETHOD. METHOD serialize_functions. DATA: lt_source TYPE TABLE OF rssource, lt_functab TYPE ty_rs38l_incl_tt, lt_new_source TYPE rsfb_source, ls_function LIKE LINE OF rt_functions. FIELD-SYMBOLS: LIKE LINE OF lt_functab, TYPE LINE OF ty_function-documentation. lt_functab = functions( ). LOOP AT lt_functab ASSIGNING . * fm RPY_FUNCTIONMODULE_READ does not support source code * lines longer than 72 characters CLEAR ls_function. MOVE-CORRESPONDING TO ls_function. CLEAR lt_new_source. CLEAR lt_source. CALL FUNCTION 'RPY_FUNCTIONMODULE_READ_NEW' EXPORTING functionname = -funcname IMPORTING global_flag = ls_function-global_flag remote_call = ls_function-remote_call update_task = ls_function-update_task short_text = ls_function-short_text remote_basxml_supported = ls_function-remote_basxml TABLES import_parameter = ls_function-import changing_parameter = ls_function-changing export_parameter = ls_function-export tables_parameter = ls_function-tables exception_list = ls_function-exception documentation = ls_function-documentation source = lt_source CHANGING new_source = lt_new_source EXCEPTIONS error_message = 1 function_not_found = 2 invalid_name = 3 OTHERS = 4. IF sy-subrc = 2. CONTINUE. ELSEIF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RPY_FUNCTIONMODULE_READ_NEW' ). ENDIF. LOOP AT ls_function-documentation ASSIGNING . CLEAR -index. ENDLOOP. SELECT SINGLE exten3 INTO ls_function-exception_classes FROM enlfdir WHERE funcname = -funcname. ""#EC CI_SUBRC APPEND ls_function TO rt_functions. IF NOT lt_new_source IS INITIAL. mo_files->add_abap( iv_extra = -funcname it_abap = lt_new_source ). ELSE. mo_files->add_abap( iv_extra = -funcname it_abap = lt_source ). ENDIF. ENDLOOP. ENDMETHOD. METHOD serialize_includes. DATA: lt_includes TYPE ty_sobj_name_tt. FIELD-SYMBOLS: LIKE LINE OF lt_includes. lt_includes = includes( ). LOOP AT lt_includes ASSIGNING . * todo, filename is not correct, a include can be used in several programs serialize_program( is_item = ms_item io_files = mo_files iv_program = iv_extra = ). ENDLOOP. ENDMETHOD. METHOD serialize_texts. DATA: lt_tpool_i18n TYPE ty_tpools_i18n, lt_tpool TYPE textpool_table. FIELD-SYMBOLS LIKE LINE OF lt_tpool_i18n. IF ii_xml->i18n_params( )-main_language_only = abap_true. RETURN. ENDIF. "" Table d010tinf stores info. on languages in which program is maintained "" Select all active translations of program texts "" Skip main language - it was already serialized SELECT DISTINCT language INTO CORRESPONDING FIELDS OF TABLE lt_tpool_i18n FROM d010tinf WHERE r3state = 'A' AND prog = iv_prog_name AND language <> mv_language ##TOO_MANY_ITAB_FIELDS. SORT lt_tpool_i18n BY language ASCENDING. LOOP AT lt_tpool_i18n ASSIGNING . READ TEXTPOOL iv_prog_name LANGUAGE -language INTO lt_tpool. -textpool = add_tpool( lt_tpool ). ENDLOOP. IF lines( lt_tpool_i18n ) > 0. ii_xml->add( iv_name = 'I18N_TPOOL' ig_data = lt_tpool_i18n ). ENDIF. ENDMETHOD. METHOD serialize_xml. DATA: lt_includes TYPE ty_sobj_name_tt, lv_areat TYPE tlibt-areat. SELECT SINGLE areat INTO lv_areat FROM tlibt WHERE spras = mv_language AND area = ms_item-obj_name. ""#EC CI_GENBUFF ""#EC CI_SUBRC lt_includes = includes( ). ii_xml->add( iv_name = 'AREAT' ig_data = lv_areat ). ii_xml->add( iv_name = 'INCLUDES' ig_data = lt_includes ). ENDMETHOD. METHOD update_func_group_short_text. "" We update the short text directly. "" SE80 does the same in "" Program SAPLSEUF / LSEUFF07 "" FORM GROUP_CHANGE UPDATE tlibt SET areat = iv_short_text WHERE spras = mv_language AND area = iv_group. ENDMETHOD. METHOD update_where_used. * make extra sure the where-used list is updated after deletion * Experienced some problems with the T00 include * this method just tries to update everything DATA: lv_include LIKE LINE OF it_includes, lo_cross TYPE REF TO cl_wb_crossreference. LOOP AT it_includes INTO lv_include. CREATE OBJECT lo_cross EXPORTING p_name = lv_include p_include = lv_include. lo_cross->index_actualize( ). ENDLOOP. ENDMETHOD. METHOD zif_abapgit_object~changed_by. TYPES: BEGIN OF ty_stamps, user TYPE syuname, date TYPE d, time TYPE t, END OF ty_stamps. DATA: lt_stamps TYPE STANDARD TABLE OF ty_stamps WITH DEFAULT KEY, lv_program TYPE program. FIELD-SYMBOLS: LIKE LINE OF lt_stamps. lv_program = main_name( ). IF mt_includes_all IS INITIAL. CALL FUNCTION 'RS_GET_ALL_INCLUDES' EXPORTING program = lv_program TABLES includetab = mt_includes_all EXCEPTIONS not_existent = 1 no_program = 2 OTHERS = 3. IF sy-subrc <> 0. zcx_abapgit_exception=>raise( 'Error from RS_GET_ALL_INCLUDES' ). ENDIF. ENDIF. SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC IF mt_includes_all IS NOT INITIAL. SELECT unam AS user udat AS date utime AS time FROM reposrc APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps FOR ALL ENTRIES IN mt_includes_all WHERE progname = mt_includes_all-table_line AND r3state = 'A'. ""#EC CI_SUBRC ENDIF. SELECT unam AS user udat AS date utime AS time FROM repotext "" Program text pool APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE progname = lv_program AND r3state = 'A'. ""#EC CI_SUBRC SELECT vautor AS user vdatum AS date vzeit AS time FROM eudb "" GUI APPENDING CORRESPONDING FIELDS OF TABLE lt_stamps WHERE relid = 'CU' AND name = lv_program AND srtf2 = 0 ##TOO_MANY_ITAB_FIELDS. * Screens: username not stored in D020S database table SORT lt_stamps BY date DESCENDING time DESCENDING. READ TABLE lt_stamps INDEX 1 ASSIGNING . IF sy-subrc = 0. rv_user = -user. ELSE. rv_user = c_user_unknown. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~delete. DATA: lv_area TYPE rs38l-area, lt_includes TYPE ty_sobj_name_tt. lt_includes = includes( ). lv_area = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_DELETE' EXPORTING area = lv_area suppress_popups = abap_true skip_progress_ind = abap_true corrnum = iv_transport EXCEPTIONS canceled_in_corr = 1 enqueue_system_failure = 2 function_exist = 3 not_executed = 4 no_modify_permission = 5 no_show_permission = 6 permission_failure = 7 pool_not_exist = 8 cancelled = 9 OTHERS = 10. IF sy-subrc <> 0. zcx_abapgit_exception=>raise_t100( ). ENDIF. update_where_used( lt_includes ). ENDMETHOD. METHOD zif_abapgit_object~deserialize. DATA: lv_program_name TYPE programm, lt_functions TYPE ty_function_tt, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. deserialize_xml( ii_xml = io_xml iv_package = iv_package iv_transport = iv_transport ). io_xml->read( EXPORTING iv_name = 'FUNCTIONS' CHANGING cg_data = lt_functions ). deserialize_functions( it_functions = lt_functions ii_log = ii_log iv_transport = iv_transport ). deserialize_includes( ii_xml = io_xml iv_package = iv_package ii_log = ii_log ). lv_program_name = main_name( ). deserialize_texts( iv_prog_name = lv_program_name ii_xml = io_xml ). deserialize_lxe_texts( io_xml ). io_xml->read( EXPORTING iv_name = 'DYNPROS' CHANGING cg_data = lt_dynpros ). deserialize_dynpros( lt_dynpros ). io_xml->read( EXPORTING iv_name = 'CUA' CHANGING cg_data = ls_cua ). deserialize_cua( iv_program_name = lv_program_name is_cua = ls_cua ). ENDMETHOD. METHOD zif_abapgit_object~exists. DATA: lv_pool TYPE tlibg-area. lv_pool = ms_item-obj_name. CALL FUNCTION 'RS_FUNCTION_POOL_EXISTS' EXPORTING function_pool = lv_pool EXCEPTIONS pool_not_exists = 1. rv_bool = boolc( sy-subrc <> 1 ). ENDMETHOD. METHOD zif_abapgit_object~get_comparator. RETURN. ENDMETHOD. METHOD zif_abapgit_object~get_deserialize_steps. APPEND zif_abapgit_object=>gc_step_id-abap TO rt_steps. ENDMETHOD. METHOD zif_abapgit_object~get_metadata. rs_metadata = get_metadata( ). ENDMETHOD. METHOD zif_abapgit_object~is_active. rv_active = is_active( ). ENDMETHOD. METHOD zif_abapgit_object~is_locked. DATA: lv_program TYPE program. lv_program = main_name( ). IF is_function_group_locked( ) = abap_true OR is_any_include_locked( ) = abap_true OR is_any_function_module_locked( ) = abap_true OR is_any_dynpro_locked( lv_program ) = abap_true OR is_cua_locked( lv_program ) = abap_true OR is_text_locked( lv_program ) = abap_true. rv_is_locked = abap_true. ENDIF. ENDMETHOD. METHOD zif_abapgit_object~jump. "" Covered by ZCL_ABAPGIT_OBJECTS=>JUMP ENDMETHOD. METHOD zif_abapgit_object~serialize. * function group SEUF * function group SIFP * function group SUNI DATA: lt_functions TYPE ty_function_tt, ls_progdir TYPE ty_progdir, lv_program_name TYPE programm, lt_dynpros TYPE ty_dynpro_tt, ls_cua TYPE ty_cua. IF zif_abapgit_object~exists( ) = abap_false. RETURN. ENDIF. serialize_xml( io_xml ). lt_functions = serialize_functions( ). io_xml->add( iv_name = 'FUNCTIONS' ig_data = lt_functions ). serialize_includes( ). lv_program_name = main_name( ). ls_progdir = read_progdir( lv_program_name ). IF io_xml->i18n_params( )-translation_languages IS INITIAL. "" Old I18N option serialize_texts( iv_prog_name = lv_program_name ii_xml = io_xml ). ELSE. "" New LXE option serialize_lxe_texts( io_xml ). ENDIF. IF ls_progdir-subc = 'F'. lt_dynpros = serialize_dynpros( lv_program_name ). io_xml->add( iv_name = 'DYNPROS' ig_data = lt_dynpros ). ls_cua = serialize_cua( lv_program_name ). io_xml->add( iv_name = 'CUA' ig_data = ls_cua ). ENDIF. ENDMETHOD. ENDCLASS. ",9385,False,1897.028727679839,median "/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2008 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library 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 * OpenSceneGraph Public License for more details. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace osg; #if (!defined(OSG_GLES2_AVAILABLE) && !defined(OSG_GLES3_AVAILABLE)) #define GLSL_VERSION_STR ""330 core"" #else #define GLSL_VERSION_STR ""300 es"" #endif static const char* gl3_VertexShader = { ""#version "" GLSL_VERSION_STR ""\\n"" ""// gl3_VertexShader\\n"" ""#ifdef GL_ES\\n"" "" precision highp float;\\n"" ""#endif\\n"" ""in vec4 osg_Vertex;\\n"" ""in vec4 osg_Color;\\n"" ""in vec4 osg_MultiTexCoord0;\\n"" ""uniform mat4 osg_ModelViewProjectionMatrix;\\n"" ""out vec2 texCoord;\\n"" ""out vec4 vertexColor;\\n"" ""void main(void)\\n"" ""{\\n"" "" gl_Position = osg_ModelViewProjectionMatrix * osg_Vertex;\\n"" "" texCoord = osg_MultiTexCoord0.xy;\\n"" "" vertexColor = osg_Color; \\n"" ""}\\n"" }; static const char* gl3_FragmentShader = { ""#version "" GLSL_VERSION_STR ""\\n"" ""// gl3_FragmentShader\\n"" ""#ifdef GL_ES\\n"" "" precision highp float;\\n"" ""#endif\\n"" ""uniform sampler2D baseTexture;\\n"" ""in vec2 texCoord;\\n"" ""in vec4 vertexColor;\\n"" ""out vec4 color;\\n"" ""void main(void)\\n"" ""{\\n"" "" color = vertexColor * texture(baseTexture, texCoord);\\n"" ""}\\n"" }; static const char* gl2_VertexShader = { ""// gl2_VertexShader\\n"" ""#ifdef GL_ES\\n"" "" precision highp float;\\n"" ""#endif\\n"" ""varying vec2 texCoord;\\n"" ""varying vec4 vertexColor;\\n"" ""void main(void)\\n"" ""{\\n"" "" gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\\n"" "" texCoord = gl_MultiTexCoord0.xy;\\n"" "" vertexColor = gl_Color; \\n"" ""}\\n"" }; static const char* gl2_FragmentShader = { ""// gl2_FragmentShader\\n"" ""#ifdef GL_ES\\n"" "" precision highp float;\\n"" ""#endif\\n"" ""uniform sampler2D baseTexture;\\n"" ""varying vec2 texCoord;\\n"" ""varying vec4 vertexColor;\\n"" ""void main(void)\\n"" ""{\\n"" "" gl_FragColor = vertexColor * texture2D(baseTexture, texCoord);\\n"" ""}\\n"" }; extern osg::Texture2D* createDefaultTexture() { osg::ref_ptr image = new osg::Image; image->allocateImage(1, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE); image->setColor(osg::Vec4(1.0,1.0,1.0,1.0), 0, 0, 0); osg::ref_ptr texture = new osg::Texture2D(image.get()); return texture.release(); } // local class to help porting from OSG0.8.x to 0.9.x class TextureGLModeSet { public: TextureGLModeSet() { _textureModeSet.insert(GL_TEXTURE_1D); _textureModeSet.insert(GL_TEXTURE_2D); _textureModeSet.insert(GL_TEXTURE_3D); _textureModeSet.insert(GL_TEXTURE_BUFFER); _textureModeSet.insert(GL_TEXTURE_CUBE_MAP); _textureModeSet.insert(GL_TEXTURE_RECTANGLE_NV); _textureModeSet.insert(GL_TEXTURE_2D_ARRAY); _textureModeSet.insert(GL_TEXTURE_2D_MULTISAMPLE); _textureModeSet.insert(GL_TEXTURE_GEN_Q); _textureModeSet.insert(GL_TEXTURE_GEN_R); _textureModeSet.insert(GL_TEXTURE_GEN_S); _textureModeSet.insert(GL_TEXTURE_GEN_T); } bool isTextureMode(StateAttribute::GLMode mode) const { return _textureModeSet.find(mode)!=_textureModeSet.end(); } protected: std::set _textureModeSet; }; static TextureGLModeSet& getTextureGLModeSet() { static TextureGLModeSet s_textureGLModeSet; return s_textureGLModeSet; } bool osg::isTextureMode(StateAttribute::GLMode mode) { return getTextureGLModeSet().isTextureMode(mode); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // StateAttributeCallback // bool StateSet::Callback::run(osg::Object* object, osg::Object* data) { osg::StateSet* ss = object->asStateSet(); osg::NodeVisitor* nv = data->asNodeVisitor(); if (ss && nv) { operator()(ss, nv); return true; } else { return traverse(object, data); } } StateSet::StateSet(): Object(true), _nestRenderBins(true) { _renderingHint = DEFAULT_BIN; _numChildrenRequiringUpdateTraversal = 0; _numChildrenRequiringEventTraversal = 0; setRenderBinToInherit(); } StateSet::StateSet(const StateSet& rhs,const CopyOp& copyop):Object(rhs,copyop), _nestRenderBins(rhs._nestRenderBins) { _modeList = rhs._modeList; for(AttributeList::const_iterator itr=rhs._attributeList.begin(); itr!=rhs._attributeList.end(); ++itr) { const StateAttribute::TypeMemberPair& typemember = itr->first; const RefAttributePair& rap = itr->second; StateAttribute* attr = copyop(rap.first.get()); if (attr) { _attributeList[typemember]=RefAttributePair(attr,rap.second); attr->addParent(this); } } // copy texture related modes. _textureModeList = rhs._textureModeList; // set up the size of the texture attribute list. _textureAttributeList.resize(rhs._textureAttributeList.size()); // copy the contents across. for(unsigned int i=0;ifirst; const RefAttributePair& rap = itr->second; StateAttribute* attr = copyop(rap.first.get()); if (attr) { lhs_attributeList[typemember]=RefAttributePair(attr,rap.second); attr->addParent(this); } } } // copy uniform values for(UniformList::const_iterator rhs_uitr = rhs._uniformList.begin(); rhs_uitr != rhs._uniformList.end(); ++rhs_uitr) { const std::string& name = rhs_uitr->first; const RefUniformPair& rup = rhs_uitr->second; Uniform* uni = copyop(rup.first.get()); if (uni) { _uniformList[name] = RefUniformPair(uni, rup.second); uni->addParent(this); } } _defineList = rhs._defineList; _renderingHint = rhs._renderingHint; _binMode = rhs._binMode; _binNum = rhs._binNum; _binName = rhs._binName; _updateCallback = rhs._updateCallback; _numChildrenRequiringUpdateTraversal = rhs._numChildrenRequiringUpdateTraversal; _eventCallback = rhs._eventCallback; _numChildrenRequiringEventTraversal = rhs._numChildrenRequiringEventTraversal; } StateSet::~StateSet() { clear(); } void StateSet::computeDataVariance() { bool dynamic = false; if (_updateCallback.valid() || _eventCallback.valid()) { dynamic = true; } // run attribute callbacks for(AttributeList::iterator itr=_attributeList.begin(); itr!=_attributeList.end(); ++itr) { if (itr->second.first->getDataVariance()==UNSPECIFIED && (itr->second.first->getUpdateCallback() || itr->second.first->getEventCallback())) { itr->second.first->setDataVariance(DYNAMIC); } if (itr->second.first->getDataVariance()==DYNAMIC) dynamic = true; } // run texture attribute callbacks. for(unsigned int i=0;i<_textureAttributeList.size();++i) { AttributeList& attributeList = _textureAttributeList[i]; for(AttributeList::iterator itr=attributeList.begin(); itr!=attributeList.end(); ++itr) { if (itr->second.first->getDataVariance()==UNSPECIFIED && (itr->second.first->getUpdateCallback() || itr->second.first->getEventCallback())) { itr->second.first->setDataVariance(DYNAMIC); } if (itr->second.first->getDataVariance()==DYNAMIC) dynamic = true; } } // run uniform callbacks. for(UniformList::iterator uitr = _uniformList.begin(); uitr != _uniformList.end(); ++uitr) { if (uitr->second.first->getDataVariance()==UNSPECIFIED && (uitr->second.first->getUpdateCallback() || uitr->second.first->getEventCallback())) { uitr->second.first->setDataVariance(DYNAMIC); } if (uitr->second.first->getDataVariance()==DYNAMIC) dynamic = true; } #if 0 if (dynamic) { OSG_NOTICE<<""StateSet::computeDataVariance setting to DYNAMIC""< lock(getRefMutex()); _parents.push_back(node); } void StateSet::removeParent(osg::Node* node) { OpenThreads::ScopedPointerLock lock(getRefMutex()); ParentList::iterator pitr = std::find(_parents.begin(),_parents.end(),node); if (pitr!=_parents.end()) _parents.erase(pitr); } int StateSet::compare(const StateSet& rhs,bool compareAttributeContents) const { if (_textureAttributeList.size()rhs._textureAttributeList.size()) return 1; if (_textureModeList.size()rhs._textureModeList.size()) return 1; if (_attributeList.size()rhs._attributeList.size()) return 1; if (_modeList.size()rhs._modeList.size()) return 1; if (_uniformList.size()rhs._uniformList.size()) return 1; if (_defineList.size()rhs._defineList.size()) return 1; // check render bin details if ( _binMode < rhs._binMode ) return -1; else if ( _binMode > rhs._binMode ) return 1; if ( _binMode != INHERIT_RENDERBIN_DETAILS ) { if ( _binNum < rhs._binNum ) return -1; else if ( _binNum > rhs._binNum ) return 1; if ( _binName < rhs._binName ) return -1; else if ( _binName > rhs._binName ) return 1; } for(unsigned int ai=0;ai<_textureAttributeList.size();++ai) { const AttributeList& rhs_attributeList = _textureAttributeList[ai]; const AttributeList& lhs_attributeList = rhs._textureAttributeList[ai]; if (compareAttributeContents) { // now check to see how the attributes compare. AttributeList::const_iterator lhs_attr_itr = lhs_attributeList.begin(); AttributeList::const_iterator rhs_attr_itr = rhs_attributeList.begin(); while (lhs_attr_itr!=lhs_attributeList.end() && rhs_attr_itr!=rhs_attributeList.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (*(lhs_attr_itr->second.first)<*(rhs_attr_itr->second.first)) return -1; else if (*(rhs_attr_itr->second.first)<*(lhs_attr_itr->second.first)) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==lhs_attributeList.end()) { if (rhs_attr_itr!=rhs_attributeList.end()) return -1; } else if (rhs_attr_itr == rhs_attributeList.end()) return 1; } else // just compare pointers. { // now check to see how the attributes compare. AttributeList::const_iterator lhs_attr_itr = lhs_attributeList.begin(); AttributeList::const_iterator rhs_attr_itr = rhs_attributeList.begin(); while (lhs_attr_itr!=lhs_attributeList.end() && rhs_attr_itr!=rhs_attributeList.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (lhs_attr_itr->second.firstsecond.first) return -1; else if (rhs_attr_itr->second.firstsecond.first) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==lhs_attributeList.end()) { if (rhs_attr_itr!=rhs_attributeList.end()) return -1; } else if (rhs_attr_itr == rhs_attributeList.end()) return 1; } } // now check the rest of the non texture attributes if (compareAttributeContents) { // now check to see how the attributes compare. AttributeList::const_iterator lhs_attr_itr = _attributeList.begin(); AttributeList::const_iterator rhs_attr_itr = rhs._attributeList.begin(); while (lhs_attr_itr!=_attributeList.end() && rhs_attr_itr!=rhs._attributeList.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (*(lhs_attr_itr->second.first)<*(rhs_attr_itr->second.first)) return -1; else if (*(rhs_attr_itr->second.first)<*(lhs_attr_itr->second.first)) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==_attributeList.end()) { if (rhs_attr_itr!=rhs._attributeList.end()) return -1; } else if (rhs_attr_itr == rhs._attributeList.end()) return 1; } else // just compare pointers. { // now check to see how the attributes compare. AttributeList::const_iterator lhs_attr_itr = _attributeList.begin(); AttributeList::const_iterator rhs_attr_itr = rhs._attributeList.begin(); while (lhs_attr_itr!=_attributeList.end() && rhs_attr_itr!=rhs._attributeList.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (lhs_attr_itr->second.firstsecond.first) return -1; else if (rhs_attr_itr->second.firstsecond.first) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==_attributeList.end()) { if (rhs_attr_itr!=rhs._attributeList.end()) return -1; } else if (rhs_attr_itr == rhs._attributeList.end()) return 1; } // we've got here so attributes must be equal... // check to see how the modes compare. // first check the rest of the texture modes for(unsigned int ti=0;ti<_textureModeList.size();++ti) { const ModeList& lhs_modeList = _textureModeList[ti]; const ModeList& rhs_modeList = rhs._textureModeList[ti]; ModeList::const_iterator lhs_mode_itr = lhs_modeList.begin(); ModeList::const_iterator rhs_mode_itr = rhs_modeList.begin(); while (lhs_mode_itr!=lhs_modeList.end() && rhs_mode_itr!=rhs_modeList.end()) { if (lhs_mode_itr->firstfirst) return -1; else if (rhs_mode_itr->firstfirst) return 1; if (lhs_mode_itr->secondsecond) return -1; else if (rhs_mode_itr->secondsecond) return 1; ++lhs_mode_itr; ++rhs_mode_itr; } if (lhs_mode_itr==lhs_modeList.end()) { if (rhs_mode_itr!=rhs_modeList.end()) return -1; } else if (rhs_mode_itr == rhs_modeList.end()) return 1; } // check non texture modes. ModeList::const_iterator lhs_mode_itr = _modeList.begin(); ModeList::const_iterator rhs_mode_itr = rhs._modeList.begin(); while (lhs_mode_itr!=_modeList.end() && rhs_mode_itr!=rhs._modeList.end()) { if (lhs_mode_itr->firstfirst) return -1; else if (rhs_mode_itr->firstfirst) return 1; if (lhs_mode_itr->secondsecond) return -1; else if (rhs_mode_itr->secondsecond) return 1; ++lhs_mode_itr; ++rhs_mode_itr; } if (lhs_mode_itr==_modeList.end()) { if (rhs_mode_itr!=rhs._modeList.end()) return -1; } else if (rhs_mode_itr == rhs._modeList.end()) return 1; // check uniforms. UniformList::const_iterator lhs_uniform_itr = _uniformList.begin(); UniformList::const_iterator rhs_uniform_itr = rhs._uniformList.begin(); while (lhs_uniform_itr!=_uniformList.end() && rhs_uniform_itr!=rhs._uniformList.end()) { if (lhs_uniform_itr->firstfirst) return -1; else if (rhs_uniform_itr->firstfirst) return 1; if (*lhs_uniform_itr->second.first<*rhs_uniform_itr->second.first) return -1; else if (*rhs_uniform_itr->second.first<*lhs_uniform_itr->second.first) return 1; if (lhs_uniform_itr->second.secondsecond.second) return -1; else if (rhs_uniform_itr->second.secondsecond.second) return 1; ++lhs_uniform_itr; ++rhs_uniform_itr; } if (lhs_uniform_itr==_uniformList.end()) { if (rhs_uniform_itr!=rhs._uniformList.end()) return -1; } else if (rhs_uniform_itr == rhs._uniformList.end()) return 1; // check defines. DefineList::const_iterator lhs_define_itr = _defineList.begin(); DefineList::const_iterator rhs_define_itr = rhs._defineList.begin(); while (lhs_define_itr!=_defineList.end() && rhs_define_itr!=rhs._defineList.end()) { if (lhs_define_itr->firstfirst) return -1; else if (rhs_define_itr->firstfirst) return 1; if (lhs_define_itr->second.firstsecond.first) return -1; else if (rhs_define_itr->second.firstsecond.first) return 1; if (lhs_define_itr->second.secondsecond.second) return -1; else if (rhs_define_itr->second.secondsecond.second) return 1; ++lhs_define_itr; ++rhs_define_itr; } if (lhs_define_itr==_defineList.end()) { if (rhs_define_itr!=rhs._defineList.end()) return -1; } else if (rhs_define_itr == rhs._defineList.end()) return 1; return 0; } int StateSet::compareModes(const ModeList& lhs,const ModeList& rhs) { ModeList::const_iterator lhs_mode_itr = lhs.begin(); ModeList::const_iterator rhs_mode_itr = rhs.begin(); while (lhs_mode_itr!=lhs.end() && rhs_mode_itr!=rhs.end()) { if (lhs_mode_itr->firstfirst) return -1; else if (rhs_mode_itr->firstfirst) return 1; if (lhs_mode_itr->secondsecond) return -1; else if (rhs_mode_itr->secondsecond) return 1; ++lhs_mode_itr; ++rhs_mode_itr; } if (lhs_mode_itr==lhs.end()) { if (rhs_mode_itr!=rhs.end()) return -1; } else if (rhs_mode_itr == rhs.end()) return 1; return 0; } int StateSet::compareAttributePtrs(const AttributeList& lhs,const AttributeList& rhs) { AttributeList::const_iterator lhs_attr_itr = lhs.begin(); AttributeList::const_iterator rhs_attr_itr = rhs.begin(); while (lhs_attr_itr!=lhs.end() && rhs_attr_itr!=rhs.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (lhs_attr_itr->second.firstsecond.first) return -1; else if (rhs_attr_itr->second.firstsecond.first) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==lhs.end()) { if (rhs_attr_itr!=rhs.end()) return -1; } else if (rhs_attr_itr == rhs.end()) return 1; return 0; } int StateSet::compareAttributeContents(const AttributeList& lhs,const AttributeList& rhs) { AttributeList::const_iterator lhs_attr_itr = lhs.begin(); AttributeList::const_iterator rhs_attr_itr = rhs.begin(); while (lhs_attr_itr!=lhs.end() && rhs_attr_itr!=rhs.end()) { if (lhs_attr_itr->firstfirst) return -1; else if (rhs_attr_itr->firstfirst) return 1; if (*(lhs_attr_itr->second.first)<*(rhs_attr_itr->second.first)) return -1; else if (*(rhs_attr_itr->second.first)<*(lhs_attr_itr->second.first)) return 1; if (lhs_attr_itr->second.secondsecond.second) return -1; else if (rhs_attr_itr->second.secondsecond.second) return 1; ++lhs_attr_itr; ++rhs_attr_itr; } if (lhs_attr_itr==lhs.end()) { if (rhs_attr_itr!=rhs.end()) return -1; } else if (rhs_attr_itr == rhs.end()) return 1; return 0; } void StateSet::setGlobalDefaults() { _renderingHint = DEFAULT_BIN; setRenderBinToInherit(); setMode(GL_DEPTH_TEST,StateAttribute::ON); setAttributeAndModes(new BlendFunc,StateAttribute::OFF); #if defined(OSG_GL_FIXED_FUNCTION_AVAILABLE) // setAttributeAndModes(new AlphaFunc,StateAttribute::OFF); Material *material = new Material; material->setColorMode(Material::AMBIENT_AND_DIFFUSE); setAttributeAndModes(material,StateAttribute::ON); #endif OSG_INFO<<""void StateSet::setGlobalDefaults()""<getShaderHint(); if (shaderHint==osg::DisplaySettings::SHADER_GL3 || shaderHint==osg::DisplaySettings::SHADER_GLES3) { OSG_INFO<<"" StateSet::setGlobalDefaults() Setting up GL3 compatible shaders""< program = new osg::Program; program->addShader(new osg::Shader(osg::Shader::VERTEX, gl3_VertexShader)); program->addShader(new osg::Shader(osg::Shader::FRAGMENT, gl3_FragmentShader)); setAttributeAndModes(program.get()); setTextureAttribute(0, createDefaultTexture()); addUniform(new osg::Uniform(""baseTexture"", 0)); } else if (shaderHint==osg::DisplaySettings::SHADER_GL2 || shaderHint==osg::DisplaySettings::SHADER_GLES2) { OSG_INFO<<"" StateSet::setGlobalDefaults() Setting up GL2 compatible shaders""< program = new osg::Program; program->addShader(new osg::Shader(osg::Shader::VERTEX, gl2_VertexShader)); program->addShader(new osg::Shader(osg::Shader::FRAGMENT, gl2_FragmentShader)); setAttributeAndModes(program.get()); setTextureAttribute(0, createDefaultTexture()); addUniform(new osg::Uniform(""baseTexture"", 0)); } } void StateSet::clear() { _renderingHint = DEFAULT_BIN; setRenderBinToInherit(); // remove self from as attributes parent for(AttributeList::iterator itr=_attributeList.begin(); itr!=_attributeList.end(); ++itr) { itr->second.first->removeParent(this); } _modeList.clear(); _attributeList.clear(); // remove self from as texture attributes parent for(unsigned int i=0;i<_textureAttributeList.size();++i) { AttributeList& attributeList = _textureAttributeList[i]; for(AttributeList::iterator itr=attributeList.begin(); itr!=attributeList.end(); ++itr) { itr->second.first->removeParent(this); } } _textureModeList.clear(); _textureAttributeList.clear(); // remove self from uniforms parent for(UniformList::iterator uitr = _uniformList.begin(); uitr != _uniformList.end(); ++uitr) { uitr->second.first->removeParent(this); } _uniformList.clear(); } void StateSet::merge(const StateSet& rhs) { // merge the modes of rhs into this, // this overrides rhs if OVERRIDE defined in this. for(ModeList::const_iterator rhs_mitr = rhs._modeList.begin(); rhs_mitr != rhs._modeList.end(); ++rhs_mitr) { ModeList::iterator lhs_mitr = _modeList.find(rhs_mitr->first); if (lhs_mitr!=_modeList.end()) { // take the rhs mode unless the lhs is override and the rhs is not protected if (!(lhs_mitr->second & StateAttribute::OVERRIDE ) || (rhs_mitr->second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. lhs_mitr->second = rhs_mitr->second; } } else { // entry doesn't exist so insert it. _modeList.insert(*rhs_mitr); } } // merge the attributes of rhs into this, // this overrides rhs if OVERRIDE defined in this. for(AttributeList::const_iterator rhs_aitr = rhs._attributeList.begin(); rhs_aitr != rhs._attributeList.end(); ++rhs_aitr) { AttributeList::iterator lhs_aitr = _attributeList.find(rhs_aitr->first); if (lhs_aitr!=_attributeList.end()) { // take the rhs attribute unless the lhs is override and the rhs is not protected if (!(lhs_aitr->second.second & StateAttribute::OVERRIDE) || (rhs_aitr->second.second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. if (lhs_aitr->second.first!=rhs_aitr->second.first) { // new attribute so need to remove self from outgoing attribute lhs_aitr->second.first->removeParent(this); // override isn't on in rhs, so override it with incoming // value. lhs_aitr->second = rhs_aitr->second; lhs_aitr->second.first->addParent(this); } else { // same attribute but with override to set. lhs_aitr->second = rhs_aitr->second; } } } else { // entry doesn't exist so insert it, and then tell it about self by adding self as parent. _attributeList.insert(*rhs_aitr).first->second.first->addParent(this); } } if (_textureModeList.size()first); if (lhs_mitr!=lhs_modeList.end()) { // take the rhs mode unless the lhs is override and the rhs is not protected if (!(lhs_mitr->second & StateAttribute::OVERRIDE) || (rhs_mitr->second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. lhs_mitr->second = rhs_mitr->second; } } else { // entry doesn't exist so insert it. lhs_modeList.insert(*rhs_mitr); } } } if (_textureAttributeList.size()first); if (lhs_aitr!=lhs_attributeList.end()) { // take the rhs attribute unless the lhs is override and the rhs is not protected if (!(lhs_aitr->second.second & StateAttribute::OVERRIDE) || (rhs_aitr->second.second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. if (lhs_aitr->second.first!=rhs_aitr->second.first) { lhs_aitr->second.first->removeParent(this); lhs_aitr->second = rhs_aitr->second; lhs_aitr->second.first->addParent(this); } else { lhs_aitr->second = rhs_aitr->second; } } } else { // entry doesn't exist so insert it and add self as parent lhs_attributeList.insert(*rhs_aitr).first->second.first->addParent(this); } } } // merge the uniforms of rhs into this, // this overrides rhs if OVERRIDE defined in this. for(UniformList::const_iterator rhs_uitr = rhs._uniformList.begin(); rhs_uitr != rhs._uniformList.end(); ++rhs_uitr) { UniformList::iterator lhs_uitr = _uniformList.find(rhs_uitr->first); if (lhs_uitr!=_uniformList.end()) { // take the rhs uniform unless the lhs is override and the rhs is not protected if (!(lhs_uitr->second.second & StateAttribute::OVERRIDE) || (rhs_uitr->second.second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. if (lhs_uitr->second.first!=rhs_uitr->second.first) { lhs_uitr->second.first->removeParent(this); lhs_uitr->second = rhs_uitr->second; lhs_uitr->second.first->addParent(this); } else { lhs_uitr->second = rhs_uitr->second; } } } else { // entry doesn't exist so insert it and add self as parent _uniformList.insert(*rhs_uitr).first->second.first->addParent(this); } } // merge the defines of rhs into this, // this overrides rhs if OVERRIDE defined in this. for(DefineList::const_iterator rhs_mitr = rhs._defineList.begin(); rhs_mitr != rhs._defineList.end(); ++rhs_mitr) { DefineList::iterator lhs_mitr = _defineList.find(rhs_mitr->first); if (lhs_mitr!=_defineList.end()) { // take the rhs mode unless the lhs is override and the rhs is not protected if (!(lhs_mitr->second.second & StateAttribute::OVERRIDE ) || (rhs_mitr->second.second & StateAttribute::PROTECTED)) { // override isn't on in rhs, so override it with incoming // value. lhs_mitr->second = rhs_mitr->second; } } else { // entry doesn't exist so insert it. _defineList.insert(*rhs_mitr); } } // Merge RenderBin state from rhs into this. // Only do so if this's RenderBinMode is INHERIT. if (getRenderBinMode() == INHERIT_RENDERBIN_DETAILS) { setRenderingHint( rhs.getRenderingHint() ); setRenderBinMode( rhs.getRenderBinMode() ); setBinNumber( rhs.getBinNumber() ); setBinName( rhs.getBinName() ); } } void StateSet::setMode(StateAttribute::GLMode mode, StateAttribute::GLModeValue value) { if (getTextureGLModeSet().isTextureMode(mode)) { OSG_NOTICE<<""Warning: texture mode '""<isTextureAttribute()) { setAttribute(_attributeList,attribute,value); } else { OSG_NOTICE<<""Warning: texture attribute '""<className()<<""'passed to setAttribute(attr,value), ""<isTextureAttribute()) { if (value&StateAttribute::INHERIT) { removeAttribute(attribute->getType()); } else { setAttribute(_attributeList,attribute,value); setAssociatedModes(attribute,value); } } else { OSG_NOTICE<<""Warning: texture attribute '""<className()<<""' passed to setAttributeAndModes(attr,value), ""<second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); setAssociatedModes(itr->second.first.get(),StateAttribute::INHERIT); _attributeList.erase(itr); } } void StateSet::removeAttribute(StateAttribute* attribute) { if (!attribute) return; AttributeList::iterator itr = _attributeList.find(attribute->getTypeMemberPair()); if (itr!=_attributeList.end()) { if (itr->second.first != attribute) return; if (itr->second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); setAssociatedModes(itr->second.first.get(),StateAttribute::INHERIT); _attributeList.erase(itr); } } StateAttribute* StateSet::getAttribute(StateAttribute::Type type, unsigned int member) { return getAttribute(_attributeList,type,member); } const StateAttribute* StateSet::getAttribute(StateAttribute::Type type, unsigned int member) const { return getAttribute(_attributeList,type,member); } StateSet::RefAttributePair* StateSet::getAttributePair(StateAttribute::Type type, unsigned int member) { return getAttributePair(_attributeList,type,member); } const StateSet::RefAttributePair* StateSet::getAttributePair(StateAttribute::Type type, unsigned int member) const { return getAttributePair(_attributeList,type,member); } void StateSet::addUniform(Uniform* uniform, StateAttribute::OverrideValue value) { if (uniform) { int delta_update = 0; int delta_event = 0; UniformList::iterator itr=_uniformList.find(uniform->getName()); if (itr==_uniformList.end()) { // new entry. RefUniformPair& up = _uniformList[uniform->getName()]; up.first = uniform; up.second = value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED); uniform->addParent(this); if (uniform->getUpdateCallback()) { delta_update = 1; } if (uniform->getEventCallback()) { delta_event = 1; } } else { if (itr->second.first==uniform) { // changing just override itr->second.second = value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED); } else { itr->second.first->removeParent(this); if (itr->second.first->getUpdateCallback()) --delta_update; if (itr->second.first->getEventCallback()) --delta_event; uniform->addParent(this); itr->second.first = uniform; if (itr->second.first->getUpdateCallback()) ++delta_update; if (itr->second.first->getEventCallback()) ++delta_event; itr->second.second = value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED); } } if (delta_update!=0) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()+delta_update); } if (delta_event!=0) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()+delta_event); } } } void StateSet::removeUniform(const std::string& name) { UniformList::iterator itr = _uniformList.find(name); if (itr!=_uniformList.end()) { if (itr->second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); _uniformList.erase(itr); } } void StateSet::removeUniform(Uniform* uniform) { if (!uniform) return; UniformList::iterator itr = _uniformList.find(uniform->getName()); if (itr!=_uniformList.end()) { if (itr->second.first != uniform) return; if (itr->second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); _uniformList.erase(itr); } } Uniform* StateSet::getUniform(const std::string& name) { UniformList::iterator itr = _uniformList.find(name); if (itr!=_uniformList.end()) return itr->second.first.get(); else return 0; } Uniform* StateSet::getOrCreateUniform(const std::string& name, Uniform::Type type, unsigned int numElements) { // for look for an appropriate uniform. UniformList::iterator itr = _uniformList.find(name); if (itr!=_uniformList.end() && itr->second.first->getType()==type) { return itr->second.first.get(); } // no uniform found matching name so create it.. Uniform* uniform = new Uniform(type,name,numElements); addUniform(uniform); return uniform; } const Uniform* StateSet::getUniform(const std::string& name) const { UniformList::const_iterator itr = _uniformList.find(name); if (itr!=_uniformList.end()) return itr->second.first.get(); else return 0; } const StateSet::RefUniformPair* StateSet::getUniformPair(const std::string& name) const { UniformList::const_iterator itr = _uniformList.find(name); if (itr!=_uniformList.end()) return &(itr->second); else return 0; } void StateSet::setDefine(const std::string& defineName, StateAttribute::OverrideValue value) { DefinePair& dp = _defineList[defineName]; dp.first = """"; dp.second = value; } void StateSet::setDefine(const std::string& defineName, const std::string& defineValue, StateAttribute::OverrideValue value) { DefinePair& dp = _defineList[defineName]; dp.first = defineValue; dp.second = value; } void StateSet::removeDefine(const std::string& defineName) { DefineList::iterator itr = _defineList.find(defineName); if (itr != _defineList.end()) _defineList.erase(itr); } void StateSet::setTextureMode(unsigned int unit,StateAttribute::GLMode mode, StateAttribute::GLModeValue value) { if (getTextureGLModeSet().isTextureMode(mode)) { setMode(getOrCreateTextureModeList(unit),mode,value); } else { OSG_NOTICE<<""Warning: non-texture mode '""<=_textureModeList.size()) return; setModeToInherit(_textureModeList[unit],mode); } else { OSG_NOTICE<<""Warning: non-texture mode '""<=_textureModeList.size()) return StateAttribute::INHERIT; return getMode(_textureModeList[unit],mode); } else { OSG_NOTICE<<""Warning: non-texture mode '""<isTextureAttribute()) { setAttribute(getOrCreateTextureAttributeList(unit),attribute,value); } else { OSG_NOTICE<<""Warning: texture attribute '""<className()<<""' passed to setTextureAttribute(unit,attr,value), ""<isTextureAttribute()) { if (value&StateAttribute::INHERIT) { removeTextureAttribute(unit,attribute->getType()); } else { setAttribute(getOrCreateTextureAttributeList(unit),attribute,value); setAssociatedTextureModes(unit,attribute,value); } } else { OSG_NOTICE<<""Warning: non texture attribute '""<className()<<""' passed to setTextureAttributeAndModes(unit,attr,value), ""<=_textureAttributeList.size()) return; AttributeList& attributeList = _textureAttributeList[unit]; AttributeList::iterator itr = attributeList.find(StateAttribute::TypeMemberPair(type,0)); if (itr!=attributeList.end()) { if (unit<_textureModeList.size()) { setAssociatedTextureModes(unit,itr->second.first.get(),StateAttribute::INHERIT); } if (itr->second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); attributeList.erase(itr); } } void StateSet::removeTextureAttribute(unsigned int unit, StateAttribute* attribute) { if (!attribute) return; if (unit>=_textureAttributeList.size()) return; AttributeList& attributeList = _textureAttributeList[unit]; AttributeList::iterator itr = attributeList.find(attribute->getTypeMemberPair()); if (itr!=attributeList.end()) { if (itr->second.first != attribute) return; setAssociatedTextureModes(unit,itr->second.first.get(),StateAttribute::INHERIT); if (itr->second.first->getUpdateCallback()) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()-1); } if (itr->second.first->getEventCallback()) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()-1); } itr->second.first->removeParent(this); attributeList.erase(itr); } } StateAttribute* StateSet::getTextureAttribute(unsigned int unit,StateAttribute::Type type) { if (unit>=_textureAttributeList.size()) return 0; return getAttribute(_textureAttributeList[unit],type,0); } const StateAttribute* StateSet::getTextureAttribute(unsigned int unit,StateAttribute::Type type) const { if (unit>=_textureAttributeList.size()) return 0; return getAttribute(_textureAttributeList[unit],type,0); } StateSet::RefAttributePair* StateSet::getTextureAttributePair(unsigned int unit, StateAttribute::Type type) { if (unit>=_textureAttributeList.size()) return 0; return getAttributePair(_textureAttributeList[unit],type,0); } const StateSet::RefAttributePair* StateSet::getTextureAttributePair(unsigned int unit, StateAttribute::Type type) const { if (unit>=_textureAttributeList.size()) return 0; return getAttributePair(_textureAttributeList[unit],type,0); } bool StateSet::checkValidityOfAssociatedModes(osg::State& state) const { bool modesValid = true; for(AttributeList::const_iterator itr = _attributeList.begin(); itr!=_attributeList.end(); ++itr) { if (!itr->second.first->checkValidityOfAssociatedModes(state)) modesValid = false; } for(TextureAttributeList::const_iterator taitr=_textureAttributeList.begin(); taitr!=_textureAttributeList.end(); ++taitr) { for(AttributeList::const_iterator itr = taitr->begin(); itr!=taitr->end(); ++itr) { if (!itr->second.first->checkValidityOfAssociatedModes(state)) modesValid = false; } } return modesValid; } void StateSet::setThreadSafeRefUnref(bool threadSafe) { Object::setThreadSafeRefUnref(threadSafe); for(AttributeList::const_iterator itr = _attributeList.begin(); itr!=_attributeList.end(); ++itr) { itr->second.first->setThreadSafeRefUnref(threadSafe); } for(TextureAttributeList::const_iterator taitr=_textureAttributeList.begin(); taitr!=_textureAttributeList.end(); ++taitr) { for(AttributeList::const_iterator itr = taitr->begin(); itr!=taitr->end(); ++itr) { itr->second.first->setThreadSafeRefUnref(threadSafe); } } } void StateSet::compileGLObjects(State& state) const { bool checkForGLErrors = state.getCheckForGLErrors()==osg::State::ONCE_PER_ATTRIBUTE; if (checkForGLErrors) state.checkGLErrors(""before StateSet::compileGLObejcts()""); for(AttributeList::const_iterator itr = _attributeList.begin(); itr!=_attributeList.end(); ++itr) { itr->second.first->compileGLObjects(state); if (checkForGLErrors) state.checkGLErrors(""StateSet::compileGLObejcts() compiling "", itr->second.first->className()); } for(TextureAttributeList::const_iterator taitr=_textureAttributeList.begin(); taitr!=_textureAttributeList.end(); ++taitr) { for(AttributeList::const_iterator itr = taitr->begin(); itr!=taitr->end(); ++itr) { itr->second.first->compileGLObjects(state); if (checkForGLErrors) state.checkGLErrors(""StateSet::compileGLObejcts() compiling texture attribute"", itr->second.first->className()); } } } void StateSet::resizeGLObjectBuffers(unsigned int maxSize) { for(AttributeList::const_iterator itr = _attributeList.begin(); itr!=_attributeList.end(); ++itr) { itr->second.first->resizeGLObjectBuffers(maxSize); } for(TextureAttributeList::const_iterator taitr=_textureAttributeList.begin(); taitr!=_textureAttributeList.end(); ++taitr) { for(AttributeList::const_iterator itr = taitr->begin(); itr!=taitr->end(); ++itr) { itr->second.first->resizeGLObjectBuffers(maxSize); } } } void StateSet::releaseGLObjects(State* state) const { for(AttributeList::const_iterator itr = _attributeList.begin(); itr!=_attributeList.end(); ++itr) { itr->second.first->releaseGLObjects(state); } for(TextureAttributeList::const_iterator taitr=_textureAttributeList.begin(); taitr!=_textureAttributeList.end(); ++taitr) { for(AttributeList::const_iterator itr = taitr->begin(); itr!=taitr->end(); ++itr) { itr->second.first->releaseGLObjects(state); } } } void StateSet::setRenderingHint(int hint) { _renderingHint = hint; // temporary hack to get new render bins working. switch(_renderingHint) { case(TRANSPARENT_BIN): { _binMode = USE_RENDERBIN_DETAILS; _binNum = 10; _binName = ""DepthSortedBin""; break; } case(OPAQUE_BIN): { _binMode = USE_RENDERBIN_DETAILS; _binNum = 0; _binName = ""RenderBin""; break; } default: // DEFAULT_BIN { setRenderBinToInherit(); break; } } } void StateSet::setRenderBinDetails(int binNum,const std::string& binName,RenderBinMode mode) { _binMode = mode; _binNum = binNum; _binName = binName; } void StateSet::setRenderBinToInherit() { _binMode = INHERIT_RENDERBIN_DETAILS; _binNum = 0; _binName = """"; } void StateSet::setMode(ModeList& modeList,StateAttribute::GLMode mode, StateAttribute::GLModeValue value) { if ((value&StateAttribute::INHERIT)) setModeToInherit(modeList,mode); else modeList[mode] = value; } void StateSet::setModeToInherit(ModeList& modeList, StateAttribute::GLMode mode) { ModeList::iterator itr = modeList.find(mode); if (itr!=modeList.end()) { modeList.erase(itr); } } StateAttribute::GLModeValue StateSet::getMode(const ModeList& modeList, StateAttribute::GLMode mode) const { ModeList::const_iterator itr = modeList.find(mode); if (itr!=modeList.end()) { return itr->second; } else return StateAttribute::INHERIT; } class SetAssociateModesHelper : public StateAttribute::ModeUsage { public: SetAssociateModesHelper(StateSet* stateset, StateAttribute::GLModeValue value,unsigned int unit=0): _stateset(stateset), _value(value), _unit(unit) {} virtual ~SetAssociateModesHelper() {} virtual void usesMode(StateAttribute::GLMode mode) { _stateset->setMode(mode,_value); } virtual void usesTextureMode(StateAttribute::GLMode mode) { _stateset->setTextureMode(_unit,mode,_value); } StateSet* _stateset; StateAttribute::GLModeValue _value; unsigned int _unit; }; class RemoveAssociateModesHelper : public StateAttribute::ModeUsage { public: RemoveAssociateModesHelper(StateSet* stateset, unsigned int unit=0): _stateset(stateset), _unit(unit) {} virtual ~RemoveAssociateModesHelper() {} virtual void usesMode(StateAttribute::GLMode mode) { _stateset->removeMode(mode); } virtual void usesTextureMode(StateAttribute::GLMode mode) { _stateset->removeTextureMode(_unit, mode); } StateSet* _stateset; unsigned int _unit; }; void StateSet::setAssociatedModes(const StateAttribute* attribute, StateAttribute::GLModeValue value) { SetAssociateModesHelper helper(this,value); attribute->getModeUsage(helper); } void StateSet::removeAssociatedModes(const StateAttribute* attribute) { RemoveAssociateModesHelper helper(this); attribute->getModeUsage(helper); } void StateSet::setAssociatedTextureModes(unsigned int unit, const StateAttribute* attribute, StateAttribute::GLModeValue value) { SetAssociateModesHelper helper(this,value,unit); attribute->getModeUsage(helper); } void StateSet::removeAssociatedTextureModes(unsigned int unit, const StateAttribute* attribute) { RemoveAssociateModesHelper helper(this,unit); attribute->getModeUsage(helper); } void StateSet::setAttribute(AttributeList& attributeList,StateAttribute *attribute, StateAttribute::OverrideValue value) { if (attribute) { int delta_update = 0; int delta_event = 0; AttributeList::iterator itr=attributeList.find(attribute->getTypeMemberPair()); if (itr==attributeList.end()) { // new entry. attributeList[attribute->getTypeMemberPair()] = RefAttributePair(attribute,value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED)); attribute->addParent(this); if (attribute->getUpdateCallback()) { delta_update = 1; } if (attribute->getEventCallback()) { delta_event = 1; } } else { if (itr->second.first==attribute) { // changing just override itr->second.second = value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED); } else { itr->second.first->removeParent(this); if (itr->second.first->getUpdateCallback()) --delta_update; if (itr->second.first->getEventCallback()) --delta_event; attribute->addParent(this); itr->second.first = attribute; if (itr->second.first->getUpdateCallback()) ++delta_update; if (itr->second.first->getEventCallback()) ++delta_event; itr->second.second = value&(StateAttribute::OVERRIDE|StateAttribute::PROTECTED); } } if (delta_update!=0) { setNumChildrenRequiringUpdateTraversal(getNumChildrenRequiringUpdateTraversal()+delta_update); } if (delta_event!=0) { setNumChildrenRequiringEventTraversal(getNumChildrenRequiringEventTraversal()+delta_event); } } } StateAttribute* StateSet::getAttribute(AttributeList& attributeList, StateAttribute::Type type, unsigned int member) { AttributeList::iterator itr = attributeList.find(StateAttribute::TypeMemberPair(type,member)); if (itr!=attributeList.end()) { return itr->second.first.get(); } else return NULL; } const StateAttribute* StateSet::getAttribute(const AttributeList& attributeList, StateAttribute::Type type, unsigned int member) const { AttributeList::const_iterator itr = attributeList.find(StateAttribute::TypeMemberPair(type,member)); if (itr!=attributeList.end()) { return itr->second.first.get(); } else return NULL; } StateSet::RefAttributePair* StateSet::getAttributePair(AttributeList& attributeList, StateAttribute::Type type, unsigned int member) { AttributeList::iterator itr = attributeList.find(StateAttribute::TypeMemberPair(type,member)); if (itr!=attributeList.end()) { return &(itr->second); } else return NULL; } const StateSet::RefAttributePair* StateSet::getAttributePair(const AttributeList& attributeList, StateAttribute::Type type, unsigned int member) const { AttributeList::const_iterator itr = attributeList.find(StateAttribute::TypeMemberPair(type,member)); if (itr!=attributeList.end()) { return &(itr->second); } else return NULL; } void StateSet::setUpdateCallback(Callback* ac) { //OSG_INFO<<""Setting StateSet callbacks""<setNumChildrenRequiringUpdateTraversal(node->getNumChildrenRequiringUpdateTraversal()+delta); } } } void StateSet::runUpdateCallbacks(osg::NodeVisitor* nv) { //OSG_INFO<<""Running StateSet callbacks""<second.first->getUpdateCallback(); if (callback) (*callback)(itr->second.first.get(),nv); } // run texture attribute callbacks. for(unsigned int i=0;i<_textureAttributeList.size();++i) { AttributeList& attributeList = _textureAttributeList[i]; for(AttributeList::iterator itr=attributeList.begin(); itr!=attributeList.end(); ++itr) { StateAttributeCallback* callback = itr->second.first->getUpdateCallback(); if (callback) (*callback)(itr->second.first.get(),nv); } } // run uniform callbacks. for(UniformList::iterator uitr = _uniformList.begin(); uitr != _uniformList.end(); ++uitr) { UniformCallback* callback = uitr->second.first->getUpdateCallback(); if (callback) (*callback)(uitr->second.first.get(),nv); } } } void StateSet::setEventCallback(Callback* ac) { if (_eventCallback==ac) return; int delta = 0; if (_eventCallback.valid()) --delta; if (ac) ++delta; _eventCallback = ac; if (delta!=0 && _numChildrenRequiringEventTraversal==0) { for(ParentList::iterator itr=_parents.begin(); itr!=_parents.end(); ++itr) { osg::Node* node = *itr; node->setNumChildrenRequiringEventTraversal(node->getNumChildrenRequiringEventTraversal()+delta); } } } void StateSet::runEventCallbacks(osg::NodeVisitor* nv) { if (_eventCallback.valid()) (*_eventCallback)(this,nv); if (_numChildrenRequiringEventTraversal!=0) { // run attribute callbacks for(AttributeList::iterator itr=_attributeList.begin(); itr!=_attributeList.end(); ++itr) { StateAttributeCallback* callback = itr->second.first->getEventCallback(); if (callback) (*callback)(itr->second.first.get(),nv); } // run texture attribute callbacks. for(unsigned int i=0;i<_textureAttributeList.size();++i) { AttributeList& attributeList = _textureAttributeList[i]; for(AttributeList::iterator itr=attributeList.begin(); itr!=attributeList.end(); ++itr) { StateAttributeCallback* callback = itr->second.first->getEventCallback(); if (callback) (*callback)(itr->second.first.get(),nv); } } // run uniform callbacks. for(UniformList::iterator uitr = _uniformList.begin(); uitr != _uniformList.end(); ++uitr) { UniformCallback* callback = uitr->second.first->getEventCallback(); if (callback) (*callback)(uitr->second.first.get(),nv); } } } void StateSet::setNumChildrenRequiringUpdateTraversal(unsigned int num) { // if no changes just return. if (_numChildrenRequiringUpdateTraversal==num) return; // note, if _updateCallback is set then the // parents won't be affected by any changes to // _numChildrenRequiringUpdateTraversal so no need to inform them. if (!_updateCallback && !_parents.empty()) { // need to pass on changes to parents. int delta = 0; if (_numChildrenRequiringUpdateTraversal>0) --delta; if (num>0) ++delta; if (delta!=0) { // the number of callbacks has changed, need to pass this // on to parents so they know whether app traversal is // required on this subgraph. for(ParentList::iterator itr =_parents.begin(); itr != _parents.end(); ++itr) { osg::Node* node = *itr; node->setNumChildrenRequiringUpdateTraversal(node->getNumChildrenRequiringUpdateTraversal()+delta); } } } // finally update this objects value. _numChildrenRequiringUpdateTraversal=num; } void StateSet::setNumChildrenRequiringEventTraversal(unsigned int num) { // if no changes just return. if (_numChildrenRequiringEventTraversal==num) return; // note, if _EventCallback is set then the // parents won't be affected by any changes to // _numChildrenRequiringEventTraversal so no need to inform them. if (!_eventCallback && !_parents.empty()) { // need to pass on changes to parents. int delta = 0; if (_numChildrenRequiringEventTraversal>0) --delta; if (num>0) ++delta; if (delta!=0) { // the number of callbacks has changed, need to pass this // on to parents so they know whether app traversal is // required on this subgraph. for(ParentList::iterator itr =_parents.begin(); itr != _parents.end(); ++itr) { osg::Node* node = *itr; node->setNumChildrenRequiringEventTraversal(node->getNumChildrenRequiringEventTraversal()+delta); } } } // finally Event this objects value. _numChildrenRequiringEventTraversal=num; } ",16163,True,3125.287656089953,median "// Copyright 2012 the V8 project authors. 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 Google Inc. 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. // Check that we can traverse very deep stacks of ConsStrings using // StringCharacterStram. Check that Get(int) works on very deep stacks // of ConsStrings. These operations may not be very fast, but they // should be possible without getting errors due to too deep recursion. #include #include ""src/v8.h"" #include ""src/api.h"" #include ""src/heap/factory.h"" #include ""src/messages.h"" #include ""src/objects-inl.h"" #include ""src/unicode-decoder.h"" #include ""test/cctest/cctest.h"" #include ""test/cctest/heap/heap-utils.h"" // Adapted from http://en.wikipedia.org/wiki/Multiply-with-carry class MyRandomNumberGenerator { public: MyRandomNumberGenerator() { init(); } void init(uint32_t seed = 0x5688C73E) { static const uint32_t phi = 0x9E3779B9; c = 362436; i = kQSize-1; Q[0] = seed; Q[1] = seed + phi; Q[2] = seed + phi + phi; for (unsigned j = 3; j < kQSize; j++) { Q[j] = Q[j - 3] ^ Q[j - 2] ^ phi ^ j; } } uint32_t next() { uint64_t a = 18782; uint32_t r = 0xFFFFFFFE; i = (i + 1) & (kQSize-1); uint64_t t = a * Q[i] + c; c = (t >> 32); uint32_t x = static_cast(t + c); if (x < c) { x++; c++; } return (Q[i] = r - x); } uint32_t next(int max) { return next() % max; } bool next(double threshold) { CHECK(threshold >= 0.0 && threshold <= 1.0); if (threshold == 1.0) return true; if (threshold == 0.0) return false; uint32_t value = next() % 100000; return threshold > static_cast(value)/100000.0; } private: static const uint32_t kQSize = 4096; uint32_t Q[kQSize]; uint32_t c; uint32_t i; }; namespace v8 { namespace internal { namespace test_strings { static const int DEEP_DEPTH = 8 * 1024; static const int SUPER_DEEP_DEPTH = 80 * 1024; class Resource: public v8::String::ExternalStringResource { public: Resource(const uc16* data, size_t length): data_(data), length_(length) {} ~Resource() { i::DeleteArray(data_); } virtual const uint16_t* data() const { return data_; } virtual size_t length() const { return length_; } private: const uc16* data_; size_t length_; }; class OneByteResource : public v8::String::ExternalOneByteStringResource { public: OneByteResource(const char* data, size_t length) : data_(data), length_(length) {} ~OneByteResource() { i::DeleteArray(data_); } virtual const char* data() const { return data_; } virtual size_t length() const { return length_; } private: const char* data_; size_t length_; }; static void InitializeBuildingBlocks(Handle* building_blocks, int bb_length, bool long_blocks, MyRandomNumberGenerator* rng) { // A list of pointers that we don't have any interest in cleaning up. // If they are reachable from a root then leak detection won't complain. Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); for (int i = 0; i < bb_length; i++) { int len = rng->next(16); int slice_head_chars = 0; int slice_tail_chars = 0; int slice_depth = 0; for (int j = 0; j < 3; j++) { if (rng->next(0.35)) slice_depth++; } // Must truncate something for a slice string. Loop until // at least one end will be sliced. while (slice_head_chars == 0 && slice_tail_chars == 0) { slice_head_chars = rng->next(15); slice_tail_chars = rng->next(12); } if (long_blocks) { // Generate building blocks which will never be merged len += ConsString::kMinLength + 1; } else if (len > 14) { len += 1234; } // Don't slice 0 length strings. if (len == 0) slice_depth = 0; int slice_length = slice_depth*(slice_head_chars + slice_tail_chars); len += slice_length; switch (rng->next(4)) { case 0: { uc16 buf[2000]; for (int j = 0; j < len; j++) { buf[j] = rng->next(0x10000); } building_blocks[i] = factory->NewStringFromTwoByte( Vector(buf, len)).ToHandleChecked(); for (int j = 0; j < len; j++) { CHECK_EQ(buf[j], building_blocks[i]->Get(j)); } break; } case 1: { char buf[2000]; for (int j = 0; j < len; j++) { buf[j] = rng->next(0x80); } building_blocks[i] = factory->NewStringFromOneByte(OneByteVector(buf, len)) .ToHandleChecked(); for (int j = 0; j < len; j++) { CHECK_EQ(buf[j], building_blocks[i]->Get(j)); } break; } case 2: { uc16* buf = NewArray(len); for (int j = 0; j < len; j++) { buf[j] = rng->next(0x10000); } Resource* resource = new Resource(buf, len); building_blocks[i] = v8::Utils::OpenHandle( *v8::String::NewExternalTwoByte(CcTest::isolate(), resource) .ToLocalChecked()); for (int j = 0; j < len; j++) { CHECK_EQ(buf[j], building_blocks[i]->Get(j)); } break; } case 3: { char* buf = NewArray(len); for (int j = 0; j < len; j++) { buf[j] = rng->next(0x80); } OneByteResource* resource = new OneByteResource(buf, len); building_blocks[i] = v8::Utils::OpenHandle( *v8::String::NewExternalOneByte(CcTest::isolate(), resource) .ToLocalChecked()); for (int j = 0; j < len; j++) { CHECK_EQ(buf[j], building_blocks[i]->Get(j)); } break; } } for (int j = slice_depth; j > 0; j--) { building_blocks[i] = factory->NewSubString( building_blocks[i], slice_head_chars, building_blocks[i]->length() - slice_tail_chars); } CHECK(len == building_blocks[i]->length() + slice_length); } } class ConsStringStats { public: ConsStringStats() { Reset(); } void Reset(); void VerifyEqual(const ConsStringStats& that) const; int leaves_; int empty_leaves_; int chars_; int left_traversals_; int right_traversals_; private: DISALLOW_COPY_AND_ASSIGN(ConsStringStats); }; void ConsStringStats::Reset() { leaves_ = 0; empty_leaves_ = 0; chars_ = 0; left_traversals_ = 0; right_traversals_ = 0; } void ConsStringStats::VerifyEqual(const ConsStringStats& that) const { CHECK_EQ(this->leaves_, that.leaves_); CHECK_EQ(this->empty_leaves_, that.empty_leaves_); CHECK_EQ(this->chars_, that.chars_); CHECK_EQ(this->left_traversals_, that.left_traversals_); CHECK_EQ(this->right_traversals_, that.right_traversals_); } class ConsStringGenerationData { public: static const int kNumberOfBuildingBlocks = 256; explicit ConsStringGenerationData(bool long_blocks); void Reset(); inline Handle block(int offset); inline Handle block(uint32_t offset); // Input variables. double early_termination_threshold_; double leftness_; double rightness_; double empty_leaf_threshold_; int max_leaves_; // Cached data. Handle building_blocks_[kNumberOfBuildingBlocks]; String* empty_string_; MyRandomNumberGenerator rng_; // Stats. ConsStringStats stats_; int early_terminations_; private: DISALLOW_COPY_AND_ASSIGN(ConsStringGenerationData); }; ConsStringGenerationData::ConsStringGenerationData(bool long_blocks) { rng_.init(); InitializeBuildingBlocks( building_blocks_, kNumberOfBuildingBlocks, long_blocks, &rng_); empty_string_ = ReadOnlyRoots(CcTest::heap()).empty_string(); Reset(); } Handle ConsStringGenerationData::block(uint32_t offset) { return building_blocks_[offset % kNumberOfBuildingBlocks ]; } Handle ConsStringGenerationData::block(int offset) { CHECK_GE(offset, 0); return building_blocks_[offset % kNumberOfBuildingBlocks]; } void ConsStringGenerationData::Reset() { early_termination_threshold_ = 0.01; leftness_ = 0.75; rightness_ = 0.75; empty_leaf_threshold_ = 0.02; max_leaves_ = 1000; stats_.Reset(); early_terminations_ = 0; rng_.init(); } void AccumulateStats(ConsString* cons_string, ConsStringStats* stats) { int left_length = cons_string->first()->length(); int right_length = cons_string->second()->length(); CHECK(cons_string->length() == left_length + right_length); // Check left side. bool left_is_cons = cons_string->first()->IsConsString(); if (left_is_cons) { stats->left_traversals_++; AccumulateStats(ConsString::cast(cons_string->first()), stats); } else { CHECK_NE(left_length, 0); stats->leaves_++; stats->chars_ += left_length; } // Check right side. if (cons_string->second()->IsConsString()) { stats->right_traversals_++; AccumulateStats(ConsString::cast(cons_string->second()), stats); } else { if (right_length == 0) { stats->empty_leaves_++; CHECK(!left_is_cons); } stats->leaves_++; stats->chars_ += right_length; } } void AccumulateStats(Handle cons_string, ConsStringStats* stats) { DisallowHeapAllocation no_allocation; if (cons_string->IsConsString()) { return AccumulateStats(ConsString::cast(*cons_string), stats); } // This string got flattened by gc. stats->chars_ += cons_string->length(); } void AccumulateStatsWithOperator( ConsString* cons_string, ConsStringStats* stats) { ConsStringIterator iter(cons_string); String* string; int offset; while (nullptr != (string = iter.Next(&offset))) { // Accumulate stats. CHECK_EQ(0, offset); stats->leaves_++; stats->chars_ += string->length(); } } void VerifyConsString(Handle root, ConsStringGenerationData* data) { // Verify basic data. CHECK(root->IsConsString()); CHECK_EQ(root->length(), data->stats_.chars_); // Recursive verify. ConsStringStats stats; AccumulateStats(ConsString::cast(*root), &stats); stats.VerifyEqual(data->stats_); // Iteratively verify. stats.Reset(); AccumulateStatsWithOperator(ConsString::cast(*root), &stats); // Don't see these. Must copy over. stats.empty_leaves_ = data->stats_.empty_leaves_; stats.left_traversals_ = data->stats_.left_traversals_; stats.right_traversals_ = data->stats_.right_traversals_; // Adjust total leaves to compensate. stats.leaves_ += stats.empty_leaves_; stats.VerifyEqual(data->stats_); } static Handle ConstructRandomString(ConsStringGenerationData* data, unsigned max_recursion) { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); // Compute termination characteristics. bool terminate = false; bool flat = data->rng_.next(data->empty_leaf_threshold_); bool terminate_early = data->rng_.next(data->early_termination_threshold_); if (terminate_early) data->early_terminations_++; // The obvious condition. terminate |= max_recursion == 0; // Flat cons string terminate by definition. terminate |= flat; // Cap for max leaves. terminate |= data->stats_.leaves_ >= data->max_leaves_; // Roll the dice. terminate |= terminate_early; // Compute termination characteristics for each side. bool terminate_left = terminate || !data->rng_.next(data->leftness_); bool terminate_right = terminate || !data->rng_.next(data->rightness_); // Generate left string. Handle left; if (terminate_left) { left = data->block(data->rng_.next()); data->stats_.leaves_++; data->stats_.chars_ += left->length(); } else { data->stats_.left_traversals_++; } // Generate right string. Handle right; if (terminate_right) { right = data->block(data->rng_.next()); data->stats_.leaves_++; data->stats_.chars_ += right->length(); } else { data->stats_.right_traversals_++; } // Generate the necessary sub-nodes recursively. if (!terminate_right) { // Need to balance generation fairly. if (!terminate_left && data->rng_.next(0.5)) { left = ConstructRandomString(data, max_recursion - 1); } right = ConstructRandomString(data, max_recursion - 1); } if (!terminate_left && left.is_null()) { left = ConstructRandomString(data, max_recursion - 1); } // Build the cons string. Handle root = factory->NewConsString(left, right).ToHandleChecked(); CHECK(root->IsConsString() && !root->IsFlat()); // Special work needed for flat string. if (flat) { data->stats_.empty_leaves_++; String::Flatten(isolate, root); CHECK(root->IsConsString() && root->IsFlat()); } return root; } static Handle ConstructLeft( ConsStringGenerationData* data, int depth) { Factory* factory = CcTest::i_isolate()->factory(); Handle answer = factory->NewStringFromStaticChars(""""); data->stats_.leaves_++; for (int i = 0; i < depth; i++) { Handle block = data->block(i); Handle next = factory->NewConsString(answer, block).ToHandleChecked(); if (next->IsConsString()) data->stats_.leaves_++; data->stats_.chars_ += block->length(); answer = next; } data->stats_.left_traversals_ = data->stats_.leaves_ - 2; return answer; } static Handle ConstructRight( ConsStringGenerationData* data, int depth) { Factory* factory = CcTest::i_isolate()->factory(); Handle answer = factory->NewStringFromStaticChars(""""); data->stats_.leaves_++; for (int i = depth - 1; i >= 0; i--) { Handle block = data->block(i); Handle next = factory->NewConsString(block, answer).ToHandleChecked(); if (next->IsConsString()) data->stats_.leaves_++; data->stats_.chars_ += block->length(); answer = next; } data->stats_.right_traversals_ = data->stats_.leaves_ - 2; return answer; } static Handle ConstructBalancedHelper( ConsStringGenerationData* data, int from, int to) { Factory* factory = CcTest::i_isolate()->factory(); CHECK(to > from); if (to - from == 1) { data->stats_.chars_ += data->block(from)->length(); return data->block(from); } if (to - from == 2) { data->stats_.chars_ += data->block(from)->length(); data->stats_.chars_ += data->block(from+1)->length(); return factory->NewConsString(data->block(from), data->block(from+1)) .ToHandleChecked(); } Handle part1 = ConstructBalancedHelper(data, from, from + ((to - from) / 2)); Handle part2 = ConstructBalancedHelper(data, from + ((to - from) / 2), to); if (part1->IsConsString()) data->stats_.left_traversals_++; if (part2->IsConsString()) data->stats_.right_traversals_++; return factory->NewConsString(part1, part2).ToHandleChecked(); } static Handle ConstructBalanced( ConsStringGenerationData* data, int depth = DEEP_DEPTH) { Handle string = ConstructBalancedHelper(data, 0, depth); data->stats_.leaves_ = data->stats_.left_traversals_ + data->stats_.right_traversals_ + 2; return string; } static void Traverse(Handle s1, Handle s2) { int i = 0; StringCharacterStream character_stream_1(*s1); StringCharacterStream character_stream_2(*s2); while (character_stream_1.HasMore()) { CHECK(character_stream_2.HasMore()); uint16_t c = character_stream_1.GetNext(); CHECK_EQ(c, character_stream_2.GetNext()); i++; } CHECK(!character_stream_1.HasMore()); CHECK(!character_stream_2.HasMore()); CHECK_EQ(s1->length(), i); CHECK_EQ(s2->length(), i); } static void TraverseFirst(Handle s1, Handle s2, int chars) { int i = 0; StringCharacterStream character_stream_1(*s1); StringCharacterStream character_stream_2(*s2); while (character_stream_1.HasMore() && i < chars) { CHECK(character_stream_2.HasMore()); uint16_t c = character_stream_1.GetNext(); CHECK_EQ(c, character_stream_2.GetNext()); i++; } s1->Get(s1->length() - 1); s2->Get(s2->length() - 1); } TEST(Traverse) { printf(""TestTraverse\\n""); CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); v8::HandleScope scope(CcTest::isolate()); ConsStringGenerationData data(false); Handle flat = ConstructBalanced(&data); String::Flatten(isolate, flat); Handle left_asymmetric = ConstructLeft(&data, DEEP_DEPTH); Handle right_asymmetric = ConstructRight(&data, DEEP_DEPTH); Handle symmetric = ConstructBalanced(&data); printf(""1\\n""); Traverse(flat, symmetric); printf(""2\\n""); Traverse(flat, left_asymmetric); printf(""3\\n""); Traverse(flat, right_asymmetric); printf(""4\\n""); Handle left_deep_asymmetric = ConstructLeft(&data, SUPER_DEEP_DEPTH); Handle right_deep_asymmetric = ConstructRight(&data, SUPER_DEEP_DEPTH); printf(""5\\n""); TraverseFirst(left_asymmetric, left_deep_asymmetric, 1050); printf(""6\\n""); TraverseFirst(left_asymmetric, right_deep_asymmetric, 65536); printf(""7\\n""); String::Flatten(isolate, left_asymmetric); printf(""10\\n""); Traverse(flat, left_asymmetric); printf(""11\\n""); String::Flatten(isolate, right_asymmetric); printf(""12\\n""); Traverse(flat, right_asymmetric); printf(""14\\n""); String::Flatten(isolate, symmetric); printf(""15\\n""); Traverse(flat, symmetric); printf(""16\\n""); String::Flatten(isolate, left_deep_asymmetric); printf(""18\\n""); } TEST(ConsStringWithEmptyFirstFlatten) { printf(""ConsStringWithEmptyFirstFlatten\\n""); CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); Isolate* isolate = CcTest::i_isolate(); i::Handle initial_fst = isolate->factory()->NewStringFromAsciiChecked(""fst012345""); i::Handle initial_snd = isolate->factory()->NewStringFromAsciiChecked(""snd012345""); i::Handle str = isolate->factory() ->NewConsString(initial_fst, initial_snd) .ToHandleChecked(); CHECK(str->IsConsString()); auto cons = i::Handle::cast(str); const int initial_length = cons->length(); // set_first / set_second does not update the length (which the heap verifier // checks), so we need to ensure the length stays the same. i::Handle new_fst = isolate->factory()->empty_string(); i::Handle new_snd = isolate->factory()->NewStringFromAsciiChecked(""snd012345012345678""); cons->set_first(isolate, *new_fst); cons->set_second(isolate, *new_snd); CHECK(!cons->IsFlat()); CHECK_EQ(initial_length, new_fst->length() + new_snd->length()); CHECK_EQ(initial_length, cons->length()); // Make sure Flatten doesn't alloc a new string. DisallowHeapAllocation no_alloc; i::Handle flat = i::String::Flatten(isolate, cons); CHECK(flat->IsFlat()); CHECK_EQ(initial_length, flat->length()); } static void VerifyCharacterStream( String* flat_string, String* cons_string) { // Do not want to test ConString traversal on flat string. CHECK(flat_string->IsFlat() && !flat_string->IsConsString()); CHECK(cons_string->IsConsString()); // TODO(dcarney) Test stream reset as well. int length = flat_string->length(); // Iterate start search in multiple places in the string. int outer_iterations = length > 20 ? 20 : length; for (int j = 0; j <= outer_iterations; j++) { int offset = length * j / outer_iterations; if (offset < 0) offset = 0; // Want to test the offset == length case. if (offset > length) offset = length; StringCharacterStream flat_stream(flat_string, offset); StringCharacterStream cons_stream(cons_string, offset); for (int i = offset; i < length; i++) { uint16_t c = flat_string->Get(i); CHECK(flat_stream.HasMore()); CHECK(cons_stream.HasMore()); CHECK_EQ(c, flat_stream.GetNext()); CHECK_EQ(c, cons_stream.GetNext()); } CHECK(!flat_stream.HasMore()); CHECK(!cons_stream.HasMore()); } } static inline void PrintStats(const ConsStringGenerationData& data) { #ifdef DEBUG printf(""%s: [%u], %s: [%u], %s: [%u], %s: [%u], %s: [%u], %s: [%u]\\n"", ""leaves"", data.stats_.leaves_, ""empty"", data.stats_.empty_leaves_, ""chars"", data.stats_.chars_, ""lefts"", data.stats_.left_traversals_, ""rights"", data.stats_.right_traversals_, ""early_terminations"", data.early_terminations_); #endif } template void TestStringCharacterStream(BuildString build, int test_cases) { FLAG_gc_global = true; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); ConsStringGenerationData data(true); for (int i = 0; i < test_cases; i++) { printf(""%d\\n"", i); HandleScope inner_scope(isolate); AlwaysAllocateScope always_allocate(isolate); // Build flat version of cons string. Handle flat_string = build(i, &data); ConsStringStats flat_string_stats; AccumulateStats(flat_string, &flat_string_stats); // Flatten string. String::Flatten(isolate, flat_string); // Build unflattened version of cons string to test. Handle cons_string = build(i, &data); ConsStringStats cons_string_stats; AccumulateStats(cons_string, &cons_string_stats); DisallowHeapAllocation no_allocation; PrintStats(data); // Full verify of cons string. cons_string_stats.VerifyEqual(flat_string_stats); cons_string_stats.VerifyEqual(data.stats_); VerifyConsString(cons_string, &data); String* flat_string_ptr = flat_string->IsConsString() ? ConsString::cast(*flat_string)->first() : *flat_string; VerifyCharacterStream(flat_string_ptr, *cons_string); } } static const int kCharacterStreamNonRandomCases = 8; static Handle BuildEdgeCaseConsString(int test_case, ConsStringGenerationData* data) { Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); data->Reset(); switch (test_case) { case 0: return ConstructBalanced(data, 71); case 1: return ConstructLeft(data, 71); case 2: return ConstructRight(data, 71); case 3: return ConstructLeft(data, 10); case 4: return ConstructRight(data, 10); case 5: // 2 element balanced tree. data->stats_.chars_ += data->block(0)->length(); data->stats_.chars_ += data->block(1)->length(); data->stats_.leaves_ += 2; return factory->NewConsString(data->block(0), data->block(1)) .ToHandleChecked(); case 6: // Simple flattened tree. data->stats_.chars_ += data->block(0)->length(); data->stats_.chars_ += data->block(1)->length(); data->stats_.leaves_ += 2; data->stats_.empty_leaves_ += 1; { Handle string = factory->NewConsString(data->block(0), data->block(1)) .ToHandleChecked(); String::Flatten(isolate, string); return string; } case 7: // Left node flattened. data->stats_.chars_ += data->block(0)->length(); data->stats_.chars_ += data->block(1)->length(); data->stats_.chars_ += data->block(2)->length(); data->stats_.leaves_ += 3; data->stats_.empty_leaves_ += 1; data->stats_.left_traversals_ += 1; { Handle left = factory->NewConsString(data->block(0), data->block(1)) .ToHandleChecked(); String::Flatten(isolate, left); return factory->NewConsString(left, data->block(2)).ToHandleChecked(); } case 8: // Left node and right node flattened. data->stats_.chars_ += data->block(0)->length(); data->stats_.chars_ += data->block(1)->length(); data->stats_.chars_ += data->block(2)->length(); data->stats_.chars_ += data->block(3)->length(); data->stats_.leaves_ += 4; data->stats_.empty_leaves_ += 2; data->stats_.left_traversals_ += 1; data->stats_.right_traversals_ += 1; { Handle left = factory->NewConsString(data->block(0), data->block(1)) .ToHandleChecked(); String::Flatten(isolate, left); Handle right = factory->NewConsString(data->block(2), data->block(2)) .ToHandleChecked(); String::Flatten(isolate, right); return factory->NewConsString(left, right).ToHandleChecked(); } } UNREACHABLE(); } TEST(StringCharacterStreamEdgeCases) { printf(""TestStringCharacterStreamEdgeCases\\n""); TestStringCharacterStream( BuildEdgeCaseConsString, kCharacterStreamNonRandomCases); } static const int kBalances = 3; static const int kTreeLengths = 4; static const int kEmptyLeaves = 4; static const int kUniqueRandomParameters = kBalances*kTreeLengths*kEmptyLeaves; static void InitializeGenerationData( int test_case, ConsStringGenerationData* data) { // Clear the settings and reinit the rng. data->Reset(); // Spin up the rng to a known location that is unique per test. static const int kPerTestJump = 501; for (int j = 0; j < test_case*kPerTestJump; j++) { data->rng_.next(); } // Choose balanced, left or right heavy trees. switch (test_case % kBalances) { case 0: // Nothing to do. Already balanced. break; case 1: // Left balanced. data->leftness_ = 0.90; data->rightness_ = 0.15; break; case 2: // Right balanced. data->leftness_ = 0.15; data->rightness_ = 0.90; break; default: UNREACHABLE(); break; } // Must remove the influence of the above decision. test_case /= kBalances; // Choose tree length. switch (test_case % kTreeLengths) { case 0: data->max_leaves_ = 16; data->early_termination_threshold_ = 0.2; break; case 1: data->max_leaves_ = 50; data->early_termination_threshold_ = 0.05; break; case 2: data->max_leaves_ = 500; data->early_termination_threshold_ = 0.03; break; case 3: data->max_leaves_ = 5000; data->early_termination_threshold_ = 0.001; break; default: UNREACHABLE(); break; } // Must remove the influence of the above decision. test_case /= kTreeLengths; // Choose how much we allow empty nodes, including not at all. data->empty_leaf_threshold_ = 0.03 * static_cast(test_case % kEmptyLeaves); } static Handle BuildRandomConsString( int test_case, ConsStringGenerationData* data) { InitializeGenerationData(test_case, data); return ConstructRandomString(data, 200); } TEST(StringCharacterStreamRandom) { printf(""StringCharacterStreamRandom\\n""); TestStringCharacterStream(BuildRandomConsString, kUniqueRandomParameters*7); } static const int kDeepOneByteDepth = 100000; TEST(DeepOneByte) { CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); v8::HandleScope scope(CcTest::isolate()); char* foo = NewArray(kDeepOneByteDepth); for (int i = 0; i < kDeepOneByteDepth; i++) { foo[i] = ""foo ""[i % 4]; } Handle string = factory->NewStringFromOneByte(OneByteVector(foo, kDeepOneByteDepth)) .ToHandleChecked(); Handle foo_string = factory->NewStringFromStaticChars(""foo""); for (int i = 0; i < kDeepOneByteDepth; i += 10) { string = factory->NewConsString(string, foo_string).ToHandleChecked(); } Handle flat_string = factory->NewConsString(string, foo_string).ToHandleChecked(); String::Flatten(isolate, flat_string); for (int i = 0; i < 500; i++) { TraverseFirst(flat_string, string, kDeepOneByteDepth); } DeleteArray(foo); } TEST(Utf8Conversion) { // Smoke test for converting strings to utf-8. CcTest::InitializeVM(); v8::HandleScope handle_scope(CcTest::isolate()); // A simple one-byte string const char* one_byte_string = ""abcdef12345""; int len = v8::String::NewFromUtf8(CcTest::isolate(), one_byte_string, v8::NewStringType::kNormal, StrLength(one_byte_string)) .ToLocalChecked() ->Utf8Length(CcTest::isolate()); CHECK_EQ(StrLength(one_byte_string), len); // A mixed one-byte and two-byte string // U+02E4 -> CB A4 // U+0064 -> 64 // U+12E4 -> E1 8B A4 // U+0030 -> 30 // U+3045 -> E3 81 85 const uint16_t mixed_string[] = {0x02E4, 0x0064, 0x12E4, 0x0030, 0x3045}; // The characters we expect to be output const unsigned char as_utf8[11] = {0xCB, 0xA4, 0x64, 0xE1, 0x8B, 0xA4, 0x30, 0xE3, 0x81, 0x85, 0x00}; // The number of bytes expected to be written for each length const int lengths[12] = {0, 0, 2, 3, 3, 3, 6, 7, 7, 7, 10, 11}; const int char_lengths[12] = {0, 0, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5}; v8::Local mixed = v8::String::NewFromTwoByte(CcTest::isolate(), mixed_string, v8::NewStringType::kNormal, 5) .ToLocalChecked(); CHECK_EQ(10, mixed->Utf8Length(CcTest::isolate())); // Try encoding the string with all capacities char buffer[11]; const char kNoChar = static_cast(-1); for (int i = 0; i <= 11; i++) { // Clear the buffer before reusing it for (int j = 0; j < 11; j++) buffer[j] = kNoChar; int chars_written; int written = mixed->WriteUtf8(buffer, i, &chars_written); CHECK_EQ(lengths[i], written); CHECK_EQ(char_lengths[i], chars_written); // Check that the contents are correct for (int j = 0; j < lengths[i]; j++) CHECK_EQ(as_utf8[j], static_cast(buffer[j])); // Check that the rest of the buffer hasn't been touched for (int j = lengths[i]; j < 11; j++) CHECK_EQ(kNoChar, buffer[j]); } } TEST(ExternalShortStringAdd) { LocalContext context; v8::HandleScope handle_scope(CcTest::isolate()); // Make sure we cover all always-flat lengths and at least one above. static const int kMaxLength = 20; CHECK_GT(kMaxLength, i::ConsString::kMinLength); // Allocate two JavaScript arrays for holding short strings. v8::Local one_byte_external_strings = v8::Array::New(CcTest::isolate(), kMaxLength + 1); v8::Local non_one_byte_external_strings = v8::Array::New(CcTest::isolate(), kMaxLength + 1); // Generate short one-byte and two-byte external strings. for (int i = 0; i <= kMaxLength; i++) { char* one_byte = NewArray(i + 1); for (int j = 0; j < i; j++) { one_byte[j] = 'a'; } // Terminating '\\0' is left out on purpose. It is not required for external // string data. OneByteResource* one_byte_resource = new OneByteResource(one_byte, i); v8::Local one_byte_external_string = v8::String::NewExternalOneByte(CcTest::isolate(), one_byte_resource) .ToLocalChecked(); one_byte_external_strings->Set(context.local(), v8::Integer::New(CcTest::isolate(), i), one_byte_external_string) .FromJust(); uc16* non_one_byte = NewArray(i + 1); for (int j = 0; j < i; j++) { non_one_byte[j] = 0x1234; } // Terminating '\\0' is left out on purpose. It is not required for external // string data. Resource* resource = new Resource(non_one_byte, i); v8::Local non_one_byte_external_string = v8::String::NewExternalTwoByte(CcTest::isolate(), resource) .ToLocalChecked(); non_one_byte_external_strings->Set(context.local(), v8::Integer::New(CcTest::isolate(), i), non_one_byte_external_string) .FromJust(); } // Add the arrays with the short external strings in the global object. v8::Local global = context->Global(); global->Set(context.local(), v8_str(""external_one_byte""), one_byte_external_strings) .FromJust(); global->Set(context.local(), v8_str(""external_non_one_byte""), non_one_byte_external_strings) .FromJust(); global->Set(context.local(), v8_str(""max_length""), v8::Integer::New(CcTest::isolate(), kMaxLength)) .FromJust(); // Add short external one-byte and two-byte strings checking the result. static const char* source = ""function test() {"" "" var one_byte_chars = 'aaaaaaaaaaaaaaaaaaaa';"" "" var non_one_byte_chars = "" ""'\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1"" ""234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\u1234\\\\"" ""u1234';"" // NOLINT "" if (one_byte_chars.length != max_length) return 1;"" "" if (non_one_byte_chars.length != max_length) return 2;"" "" var one_byte = Array(max_length + 1);"" "" var non_one_byte = Array(max_length + 1);"" "" for (var i = 0; i <= max_length; i++) {"" "" one_byte[i] = one_byte_chars.substring(0, i);"" "" non_one_byte[i] = non_one_byte_chars.substring(0, i);"" "" };"" "" for (var i = 0; i <= max_length; i++) {"" "" if (one_byte[i] != external_one_byte[i]) return 3;"" "" if (non_one_byte[i] != external_non_one_byte[i]) return 4;"" "" for (var j = 0; j < i; j++) {"" "" if (external_one_byte[i] !="" "" (external_one_byte[j] + external_one_byte[i - j])) return "" ""5;"" "" if (external_non_one_byte[i] !="" "" (external_non_one_byte[j] + external_non_one_byte[i - "" ""j])) return 6;"" "" if (non_one_byte[i] != (non_one_byte[j] + non_one_byte[i - "" ""j])) return 7;"" "" if (one_byte[i] != (one_byte[j] + one_byte[i - j])) return 8;"" "" if (one_byte[i] != (external_one_byte[j] + one_byte[i - j])) "" ""return 9;"" "" if (one_byte[i] != (one_byte[j] + external_one_byte[i - j])) "" ""return 10;"" "" if (non_one_byte[i] !="" "" (external_non_one_byte[j] + non_one_byte[i - j])) return "" ""11;"" "" if (non_one_byte[i] !="" "" (non_one_byte[j] + external_non_one_byte[i - j])) return "" ""12;"" "" }"" "" }"" "" return 0;"" ""};"" ""test()""; CHECK_EQ(0, CompileRun(source)->Int32Value(context.local()).FromJust()); } TEST(JSONStringifySliceMadeExternal) { if (!FLAG_string_slices) return; CcTest::InitializeVM(); // Create a sliced string from a one-byte string. The latter is turned // into a two-byte external string. Check that JSON.stringify works. v8::HandleScope handle_scope(CcTest::isolate()); v8::Local underlying = CompileRun( ""var underlying = 'abcdefghijklmnopqrstuvwxyz';"" ""underlying"") ->ToString(CcTest::isolate()->GetCurrentContext()) .ToLocalChecked(); v8::Local slice = CompileRun( ""var slice = '';"" ""slice = underlying.slice(1);"" ""slice"") ->ToString(CcTest::isolate()->GetCurrentContext()) .ToLocalChecked(); CHECK(v8::Utils::OpenHandle(*slice)->IsSlicedString()); CHECK(v8::Utils::OpenHandle(*underlying)->IsSeqOneByteString()); int length = underlying->Length(); uc16* two_byte = NewArray(length + 1); underlying->Write(two_byte); Resource* resource = new Resource(two_byte, length); CHECK(underlying->MakeExternal(resource)); CHECK(v8::Utils::OpenHandle(*slice)->IsSlicedString()); CHECK(v8::Utils::OpenHandle(*underlying)->IsExternalTwoByteString()); CHECK_EQ(0, strcmp(""\\""bcdefghijklmnopqrstuvwxyz\\"""", *v8::String::Utf8Value(CcTest::isolate(), CompileRun(""JSON.stringify(slice)"")))); } TEST(CachedHashOverflow) { CcTest::InitializeVM(); // We incorrectly allowed strings to be tagged as array indices even if their // values didn't fit in the hash field. // See http://code.google.com/p/v8/issues/detail?id=728 Isolate* isolate = CcTest::i_isolate(); v8::HandleScope handle_scope(CcTest::isolate()); // Lines must be executed sequentially. Combining them into one script // makes the bug go away. const char* lines[] = {""var x = [];"", ""x[4] = 42;"", ""var s = \\""1073741828\\"";"", ""x[s];"", ""x[s] = 37;"", ""x[4];"", ""x[s];""}; Handle fortytwo(Smi::FromInt(42), isolate); Handle thirtyseven(Smi::FromInt(37), isolate); Handle results[] = { isolate->factory()->undefined_value(), fortytwo, isolate->factory()->undefined_value(), isolate->factory()->undefined_value(), thirtyseven, fortytwo, thirtyseven // Bug yielded 42 here. }; v8::Local context = CcTest::isolate()->GetCurrentContext(); for (size_t i = 0; i < arraysize(lines); i++) { const char* line = lines[i]; printf(""%s\\n"", line); v8::Local result = v8::Script::Compile(context, v8::String::NewFromUtf8(CcTest::isolate(), line, v8::NewStringType::kNormal) .ToLocalChecked()) .ToLocalChecked() ->Run(context) .ToLocalChecked(); CHECK_EQ(results[i]->IsUndefined(CcTest::i_isolate()), result->IsUndefined()); CHECK_EQ(results[i]->IsNumber(), result->IsNumber()); if (result->IsNumber()) { int32_t value = 0; CHECK(results[i]->ToInt32(&value)); CHECK_EQ(value, result->ToInt32(context).ToLocalChecked()->Value()); } } } TEST(SliceFromCons) { if (!FLAG_string_slices) return; CcTest::InitializeVM(); Factory* factory = CcTest::i_isolate()->factory(); v8::HandleScope scope(CcTest::isolate()); Handle string = factory->NewStringFromStaticChars(""parentparentparent""); Handle parent = factory->NewConsString(string, string).ToHandleChecked(); CHECK(parent->IsConsString()); CHECK(!parent->IsFlat()); Handle slice = factory->NewSubString(parent, 1, 25); // After slicing, the original string becomes a flat cons. CHECK(parent->IsFlat()); CHECK(slice->IsSlicedString()); CHECK_EQ(SlicedString::cast(*slice)->parent(), // Parent could have been short-circuited. parent->IsConsString() ? ConsString::cast(*parent)->first() : *parent); CHECK(SlicedString::cast(*slice)->parent()->IsSeqString()); CHECK(slice->IsFlat()); } class OneByteVectorResource : public v8::String::ExternalOneByteStringResource { public: explicit OneByteVectorResource(i::Vector vector) : data_(vector) {} virtual ~OneByteVectorResource() {} virtual size_t length() const { return data_.length(); } virtual const char* data() const { return data_.start(); } private: i::Vector data_; }; TEST(InternalizeExternal) { #ifdef ENABLE_MINOR_MC // TODO(mlippautz): Remove once we add support for forwarding ThinStrings in // minor MC if (FLAG_minor_mc) return; #endif // ENABLE_MINOR_MC FLAG_stress_incremental_marking = false; FLAG_thin_strings = true; CcTest::InitializeVM(); i::Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); // This won't leak; the external string mechanism will call Dispose() on it. OneByteVectorResource* resource = new OneByteVectorResource(i::Vector(""prop-1234"", 9)); { v8::HandleScope scope(CcTest::isolate()); v8::Local ext_string = v8::String::NewExternalOneByte(CcTest::isolate(), resource) .ToLocalChecked(); Handle string = v8::Utils::OpenHandle(*ext_string); CHECK(string->IsExternalString()); CHECK(!string->IsInternalizedString()); CHECK(!i::Heap::InNewSpace(*string)); CHECK_EQ( isolate->factory()->string_table()->LookupStringIfExists_NoAllocate( isolate, *string), Smi::FromInt(ResultSentinel::kNotFound)); factory->InternalizeName(string); CHECK(string->IsExternalString()); CHECK(string->IsInternalizedString()); CHECK(!i::Heap::InNewSpace(*string)); } CcTest::CollectGarbage(i::OLD_SPACE); CcTest::CollectGarbage(i::OLD_SPACE); } TEST(SliceFromExternal) { if (!FLAG_string_slices) return; CcTest::InitializeVM(); Factory* factory = CcTest::i_isolate()->factory(); v8::HandleScope scope(CcTest::isolate()); OneByteVectorResource resource( i::Vector(""abcdefghijklmnopqrstuvwxyz"", 26)); Handle string = factory->NewExternalStringFromOneByte(&resource).ToHandleChecked(); CHECK(string->IsExternalString()); Handle slice = factory->NewSubString(string, 1, 25); CHECK(slice->IsSlicedString()); CHECK(string->IsExternalString()); CHECK_EQ(SlicedString::cast(*slice)->parent(), *string); CHECK(SlicedString::cast(*slice)->parent()->IsExternalString()); CHECK(slice->IsFlat()); // This avoids the GC from trying to free stack allocated resources. i::Handle::cast(string)->set_resource(nullptr); } TEST(TrivialSlice) { // This tests whether a slice that contains the entire parent string // actually creates a new string (it should not). if (!FLAG_string_slices) return; CcTest::InitializeVM(); Factory* factory = CcTest::i_isolate()->factory(); v8::HandleScope scope(CcTest::isolate()); v8::Local result; Handle string; const char* init = ""var str = 'abcdefghijklmnopqrstuvwxyz';""; const char* check = ""str.slice(0,26)""; const char* crosscheck = ""str.slice(1,25)""; CompileRun(init); result = CompileRun(check); CHECK(result->IsString()); string = v8::Utils::OpenHandle(v8::String::Cast(*result)); CHECK(!string->IsSlicedString()); string = factory->NewSubString(string, 0, 26); CHECK(!string->IsSlicedString()); result = CompileRun(crosscheck); CHECK(result->IsString()); string = v8::Utils::OpenHandle(v8::String::Cast(*result)); CHECK(string->IsSlicedString()); CHECK_EQ(0, strcmp(""bcdefghijklmnopqrstuvwxy"", string->ToCString().get())); } TEST(SliceFromSlice) { // This tests whether a slice that contains the entire parent string // actually creates a new string (it should not). if (!FLAG_string_slices) return; CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); v8::Local result; Handle string; const char* init = ""var str = 'abcdefghijklmnopqrstuvwxyz';""; const char* slice = ""var slice = ''; slice = str.slice(1,-1); slice""; const char* slice_from_slice = ""slice.slice(1,-1);""; CompileRun(init); result = CompileRun(slice); CHECK(result->IsString()); string = v8::Utils::OpenHandle(v8::String::Cast(*result)); CHECK(string->IsSlicedString()); CHECK(SlicedString::cast(*string)->parent()->IsSeqString()); CHECK_EQ(0, strcmp(""bcdefghijklmnopqrstuvwxy"", string->ToCString().get())); result = CompileRun(slice_from_slice); CHECK(result->IsString()); string = v8::Utils::OpenHandle(v8::String::Cast(*result)); CHECK(string->IsSlicedString()); CHECK(SlicedString::cast(*string)->parent()->IsSeqString()); CHECK_EQ(0, strcmp(""cdefghijklmnopqrstuvwx"", string->ToCString().get())); } UNINITIALIZED_TEST(OneByteArrayJoin) { v8::Isolate::CreateParams create_params; // Set heap limits. create_params.constraints.set_max_semi_space_size_in_kb(1024); #ifdef DEBUG create_params.constraints.set_max_old_space_size(20); #else create_params.constraints.set_max_old_space_size(7); #endif create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate = v8::Isolate::New(create_params); isolate->Enter(); { // String s is made of 2^17 = 131072 'c' characters and a is an array // starting with 'bad', followed by 2^14 times the string s. That means the // total length of the concatenated strings is 2^31 + 3. So on 32bit systems // summing the lengths of the strings (as Smis) overflows and wraps. LocalContext context(isolate); v8::HandleScope scope(isolate); v8::TryCatch try_catch(isolate); CHECK(CompileRun( ""var two_14 = Math.pow(2, 14);"" ""var two_17 = Math.pow(2, 17);"" ""var s = Array(two_17 + 1).join('c');"" ""var a = ['bad'];"" ""for (var i = 1; i <= two_14; i++) a.push(s);"" ""a.join("" "");"").IsEmpty()); CHECK(try_catch.HasCaught()); } isolate->Exit(); isolate->Dispose(); } namespace { int* global_use_counts = nullptr; void MockUseCounterCallback(v8::Isolate* isolate, v8::Isolate::UseCounterFeature feature) { ++global_use_counts[feature]; } } TEST(CountBreakIterator) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); LocalContext context; int use_counts[v8::Isolate::kUseCounterFeatureCount] = {}; global_use_counts = use_counts; CcTest::isolate()->SetUseCounterCallback(MockUseCounterCallback); CHECK_EQ(0, use_counts[v8::Isolate::kBreakIterator]); v8::Local result = CompileRun( ""(function() {"" "" if (!this.Intl) return 0;"" "" var iterator = Intl.v8BreakIterator(['en']);"" "" iterator.adoptText('Now is the time');"" "" iterator.next();"" "" return iterator.next();"" ""})();""); CHECK(result->IsNumber()); int uses = result->ToInt32(context.local()).ToLocalChecked()->Value() == 0 ? 0 : 1; CHECK_EQ(uses, use_counts[v8::Isolate::kBreakIterator]); // Make sure GC cleans up the break iterator, so we don't get a memory leak // reported by ASAN. CcTest::isolate()->LowMemoryNotification(); } TEST(StringReplaceAtomTwoByteResult) { CcTest::InitializeVM(); v8::HandleScope scope(CcTest::isolate()); LocalContext context; v8::Local result = CompileRun( ""var subject = 'one_byte~only~string~'; "" ""var replace = '\\x80'; "" ""subject.replace(/~/g, replace); ""); CHECK(result->IsString()); Handle string = v8::Utils::OpenHandle(v8::String::Cast(*result)); CHECK(string->IsTwoByteRepresentation()); v8::Local expected = v8_str(""one_byte\\x80only\\x80string\\x80""); CHECK(expected->Equals(context.local(), result).FromJust()); } TEST(IsAscii) { CHECK(String::IsAscii(static_cast(nullptr), 0)); CHECK(String::IsOneByte(static_cast(nullptr), 0)); } template static uint16_t ConvertLatin1(uint16_t c) { uint32_t result[Op::kMaxWidth]; int chars; chars = Op::Convert(c, 0, result, nullptr); if (chars == 0) return 0; CHECK_LE(chars, static_cast(sizeof(result))); if (!return_first && chars > 1) { return 0; } return result[0]; } #ifndef V8_INTL_SUPPORT static void CheckCanonicalEquivalence(uint16_t c, uint16_t test) { uint16_t expect = ConvertLatin1(c); if (expect > unibrow::Latin1::kMaxChar || expect == 0) expect = c; CHECK_EQ(expect, test); } TEST(Latin1IgnoreCase) { for (uint16_t c = unibrow::Latin1::kMaxChar + 1; c != 0; c++) { uint16_t lower = ConvertLatin1(c); uint16_t upper = ConvertLatin1(c); uint16_t test = unibrow::Latin1::TryConvertToLatin1(c); // Filter out all character whose upper is not their lower or vice versa. if (lower == 0 && upper == 0) { CheckCanonicalEquivalence(c, test); continue; } if (lower > unibrow::Latin1::kMaxChar && upper > unibrow::Latin1::kMaxChar) { CheckCanonicalEquivalence(c, test); continue; } if (lower == 0 && upper != 0) { lower = ConvertLatin1(upper); } if (upper == 0 && lower != c) { upper = ConvertLatin1(lower); } if (lower > unibrow::Latin1::kMaxChar && upper > unibrow::Latin1::kMaxChar) { CheckCanonicalEquivalence(c, test); continue; } if (upper != c && lower != c) { CheckCanonicalEquivalence(c, test); continue; } CHECK_EQ(Min(upper, lower), test); } } #endif class DummyResource: public v8::String::ExternalStringResource { public: virtual const uint16_t* data() const { return nullptr; } virtual size_t length() const { return 1 << 30; } }; class DummyOneByteResource: public v8::String::ExternalOneByteStringResource { public: virtual const char* data() const { return nullptr; } virtual size_t length() const { return 1 << 30; } }; TEST(InvalidExternalString) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); { HandleScope scope(isolate); DummyOneByteResource r; CHECK(isolate->factory()->NewExternalStringFromOneByte(&r).is_null()); CHECK(isolate->has_pending_exception()); isolate->clear_pending_exception(); } { HandleScope scope(isolate); DummyResource r; CHECK(isolate->factory()->NewExternalStringFromTwoByte(&r).is_null()); CHECK(isolate->has_pending_exception()); isolate->clear_pending_exception(); } } #define INVALID_STRING_TEST(FUN, TYPE) \\ TEST(StringOOM##FUN) { \\ CcTest::InitializeVM(); \\ LocalContext context; \\ Isolate* isolate = CcTest::i_isolate(); \\ STATIC_ASSERT(String::kMaxLength < kMaxInt); \\ static const int invalid = String::kMaxLength + 1; \\ HandleScope scope(isolate); \\ Vector dummy = Vector::New(invalid); \\ memset(dummy.start(), 0x0, dummy.length() * sizeof(TYPE)); \\ CHECK(isolate->factory()->FUN(Vector::cast(dummy)).is_null()); \\ memset(dummy.start(), 0x20, dummy.length() * sizeof(TYPE)); \\ CHECK(isolate->has_pending_exception()); \\ isolate->clear_pending_exception(); \\ dummy.Dispose(); \\ } INVALID_STRING_TEST(NewStringFromUtf8, char) INVALID_STRING_TEST(NewStringFromOneByte, uint8_t) #undef INVALID_STRING_TEST TEST(FormatMessage) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Handle arg0 = isolate->factory()->NewStringFromAsciiChecked(""arg0""); Handle arg1 = isolate->factory()->NewStringFromAsciiChecked(""arg1""); Handle arg2 = isolate->factory()->NewStringFromAsciiChecked(""arg2""); Handle result = MessageTemplate::FormatMessage(MessageTemplate::kPropertyNotFunction, arg0, arg1, arg2).ToHandleChecked(); Handle expected = isolate->factory()->NewStringFromAsciiChecked( ""'arg0' returned for property 'arg1' of object 'arg2' is not a function""); CHECK(String::Equals(isolate, result, expected)); } TEST(Regress609831) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); { HandleScope scope(isolate); v8::Local result = CompileRun( ""String.fromCharCode(32, 32, 32, 32, 32, "" ""32, 32, 32, 32, 32, 32, 32, 32, 32, 32, "" ""32, 32, 32, 32, 32, 32, 32, 32, 32, 32)""); CHECK(v8::Utils::OpenHandle(*result)->IsSeqOneByteString()); } { HandleScope scope(isolate); v8::Local result = CompileRun( ""String.fromCharCode(432, 432, 432, 432, 432, "" ""432, 432, 432, 432, 432, 432, 432, 432, 432, "" ""432, 432, 432, 432, 432, 432, 432, 432, 432)""); CHECK(v8::Utils::OpenHandle(*result)->IsSeqTwoByteString()); } } TEST(ExternalStringIndexOf) { CcTest::InitializeVM(); LocalContext context; v8::HandleScope scope(CcTest::isolate()); const char* raw_string = ""abcdefghijklmnopqrstuvwxyz""; v8::Local string = v8::String::NewExternalOneByte(CcTest::isolate(), new StaticOneByteResource(raw_string)) .ToLocalChecked(); v8::Local global = context->Global(); global->Set(context.local(), v8_str(""external""), string).FromJust(); char source[] = ""external.indexOf('%')""; for (size_t i = 0; i < strlen(raw_string); i++) { source[18] = raw_string[i]; int result_position = static_cast(i); CHECK_EQ(result_position, CompileRun(source)->Int32Value(context.local()).FromJust()); } CHECK_EQ(-1, CompileRun(""external.indexOf('abcdefghijklmnopqrstuvwxyz%%%%%%')"") ->Int32Value(context.local()) .FromJust()); CHECK_EQ(1, CompileRun(""external.indexOf('', 1)"") ->Int32Value(context.local()) .FromJust()); CHECK_EQ(-1, CompileRun(""external.indexOf('a', 1)"") ->Int32Value(context.local()) .FromJust()); CHECK_EQ(-1, CompileRun(""external.indexOf('$')"") ->Int32Value(context.local()) .FromJust()); } #define GC_INSIDE_NEW_STRING_FROM_UTF8_SUB_STRING(NAME, STRING) \\ TEST(GCInsideNewStringFromUtf8SubStringWith##NAME) { \\ CcTest::InitializeVM(); \\ LocalContext context; \\ v8::HandleScope scope(CcTest::isolate()); \\ Factory* factory = CcTest::i_isolate()->factory(); \\ /* Length must be bigger than the buffer size of the Utf8Decoder. */ \\ const char* buf = STRING; \\ size_t len = strlen(buf); \\ Handle main_string = \\ factory \\ ->NewStringFromOneByte(Vector( \\ reinterpret_cast(buf), len)) \\ .ToHandleChecked(); \\ CHECK(Heap::InNewSpace(*main_string)); \\ /* Next allocation will cause GC. */ \\ heap::SimulateFullSpace(CcTest::i_isolate()->heap()->new_space()); \\ /* Offset by two to check substring-ing. */ \\ Handle s = factory \\ ->NewStringFromUtf8SubString( \\ Handle::cast(main_string), 2, \\ static_cast(len - 2)) \\ .ToHandleChecked(); \\ Handle expected_string = \\ factory->NewStringFromUtf8(Vector(buf + 2, len - 2)) \\ .ToHandleChecked(); \\ CHECK(s->Equals(*expected_string)); \\ } GC_INSIDE_NEW_STRING_FROM_UTF8_SUB_STRING( OneByte, ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"") GC_INSIDE_NEW_STRING_FROM_UTF8_SUB_STRING( TwoByte, ""QQ\\xF0\\x9F\\x98\\x8D\\xF0\\x9F\\x98\\x8D"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ"" ""QQ\\xF0\\x9F\\x98\\x8D\\xF0\\x9F\\x98\\x8D"") #undef GC_INSIDE_NEW_STRING_FROM_UTF8_SUB_STRING TEST(HashArrayIndexStrings) { CcTest::InitializeVM(); LocalContext context; v8::HandleScope scope(CcTest::isolate()); i::Isolate* isolate = CcTest::i_isolate(); CHECK_EQ(StringHasher::MakeArrayIndexHash(0 /* value */, 1 /* length */) >> Name::kHashShift, isolate->factory()->zero_string()->Hash()); CHECK_EQ(StringHasher::MakeArrayIndexHash(1 /* value */, 1 /* length */) >> Name::kHashShift, isolate->factory()->one_string()->Hash()); } } // namespace test_strings } // namespace internal } // namespace v8 ",16381,False,2357.605472449579,median "= EDGE2AI Workshop == Introduction The Cloudera Self Driving Vehicle (CSDV) is a miniature autonomous car which is trained to follow markers along a race track, the team achieved this by rapidly sampling photographs and using them to run inference to adjust the steering angle of the vehicle. ===== Labs summary: * *Lab 1* - On the Gateway host, run a simulator to send IoT sensors data to the MQTT broker. * *Lab 2* - On the Gateway host, configure and start **MiNiFi**, which will read from the MQTT broker, filter and forward to the **NiFi** cluster. * *Lab 3* - Create the MiNiFi flow on the Edge Flow Manager and publish it for the MiNiFi agent to start sending data to the NiFi cluster. * *Lab 4* - On Schema Registry, register the schema describing the data generated by the IoT sensors. * *Lab 5* - On the NiFi cluster, prepare the data and send it to the **Kafka** cluster. * *Lab 6* - On the *Streams Messaging Manager (SMM)* Web UI, monitor the Kafka cluster and confirm data is being ingested correctly. * *Lab 7* - Use the Edge Flow Manager to update existing edge flows and perform additional processing on the edge * *Lab 8* - Use NiFi to process each record, calling the **Model endpoint** and save results to **Kudu**. * *Lab 9* - On the CDH cluster, process each record using **Spark Streaming**, calling the **Model endpoint** and save results to **Kudu**. * *Lab 10* - On the CDH cluster, pull reports on upcoming predicted machine failures using **Impala** and **Hue**. * *Lab 11* - On the **CDSW** cluster, train your model with the **Experiment** feature. * *Lab 12* - On the **CDSW** cluster, deploy the model into production with the **Model** feature. ===== Pre-requisites * Laptop with a supported OS (Windows 7 not supported). * Ability to SSH into remote hosts from Windows or Mac. For Windows machines, install Putty or even better link:https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse[install OpenSSH for PowerShell]. * A modern browser like Google Chrome (IE not supported). ===== Connecting to your cluster You should have 2 addresses for you one-node cluster: the public DNS name and the public IP address. With those addresses you can test the following connectivity to your cluster: . It is convenient to export the DNS, IP, and path to the PEM of your cluster for future use: + [source, shell] ---- export WDNS= export WIP= export WPEM= ---- . Ensure you can SSH into the cluster (using either the DNS name or IP address) + [source,shell] ---- ssh -i $WPEM centos@$WDNS ---- . Ensure you can connect to the following service using your browser: + [%autowidth,options=""header""] |=== |Service|URL|Credentials |Cloudera Manager|http://:7180/|`admin/admin` |Edge Flow Manager|http://:10080/efm/ui/| |NiFi|http://:8080/nifi/| |NiFi Registry|http://:18080/nifi-registry/| |Schema Registry|http://:7788/| |SMM|http://:9991/| |Hue|http://:8888/| |CDSW|http://cdsw..nip.io/|`admin/supersecret1` |=== . Login into *Cloudera Manager* and familiarize yourself with the services installed . Login into *Hue*. As you are the first user to login into Hue, you are granted admin privileges. At this point, you won't need to do anything on Hue, but by logging in, CDH has created your HDFS user and folder. Below a screenshot of Chrome open with 8 tabs, one for each service. image::images/browser.png[width=800] [[lab_1, Lab 1]] == Lab 1 - Configure and run MiNiFi MiNiFi is installed on the host. In this lab you will configure and run MiNiFi to read from the MQTT broker and forward to the NiFi cluster, but it's only in the next lab that you will provide the flow to execute. . Sudo to the root user + [source,shell] ---- sudo su - ---- . Start the MiNiFi agent: + [source,shell] ---- systemctl start minifi ---- . Exit the root session + [source,shell] ---- exit ---- [[lab_2, Lab2]] == Lab 2 - Configuring the NiFi Flow In order to connect MiNiFi to NiFi we need to know where we are going so let's create a path for our data to slowly build a flow. Open NiFi UI on your CDF cluster and create a new input source named `AWS_MiNiFi_CSV` leave it alone for now, we will need the input id to set our connection from MiNiFi processor to NiFi Remote Process Group (RPG) [[lab_3, Lab3]] == Lab 3 - Configuring Edge Flow Management Cloudera Edge Flow Management gives you a visual overview of all MiNiFi agents in your environment, and allows you to update the flow configuration for each one, with versioning control thanks to the **NiFi Registry** integration. In this lab, you will create the MiNiFi flow and publish it for the MiNiFi agent to pick it up. . Open the EFM Web UI at http://:10080/efm/ui/. Ensure you see your minifi agent's heartbeat messages in the **Events Monitor**. + image::images/cem_heartbeats.png[width=800] . You can then select the **Flow Designer** tab (image:images/flow_designer_icon.png[width=30]). To build a dataflow, select the desired class (`iot-1`) from the table and click OPEN. Alternatively, you can double-click on the desired class. . Add a _GetFile_ processor onto canvas to get csv data: + Update processor name to **GetCSVFile**. . Add a _Remote Process Group_ (RPG) to the canvas and configure it as follows: + [source] ---- URL: http://edge2ai-1.dim.local:8080/nifi ---- + image::images/add_rpg.png[width=800] . At this point you need to connect the ConsumerMQTT processor to the RPG. For this, you first need to add an Input Port to the remote NiFi server. Open the NiFi Web UI at `\\http://:8080/nifi/` and drag the _Input Port_ to the canvas. Call it something like ""from Gateway"". + image::images/add_input_port.png[width=800] . To terminate the NiFI _Input Port_ let's, for now, add a _Funnel_ to the canvas... + image::images/add_funnel.png[width=600] . ... and setup a connection from the Input Port to it. To setup a connection, hover the mouse over the Input Port until an arrow symbol is shown in the center. Click on the arrow, drag it and drop it on the Funnel to connect the two elements. + image::images/connecting.png[width=800] . Right-click on the Input Port and start it. Alternatively, click on the Input Port to select it and then press the start (""play"") button on the Operate panel: + image::images/operate_panel.png[width=300] . You will need the ID of the _Input Port_ to complete the connection of the _ConsumeMQTT_ processor to the RPG (NiFi). Double-click on the _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back to the Flow Designer, connect the ConsumeMQTT processor to the RPG. The connection requires an ID and you can paste here the ID you copied from the Input Port. + image::images/connect_to_rpg.png[width=800] . The Flow is now complete, but before publishing it, create the Bucket in the _NiFi Registry_ so that all versions of your flows are stored for review and audit. Open the NiFi Registry at `\\http://:18080/nifi-registry`, click on the wrench/spanner icon (image:images/spanner_icon.png[width=20]) on the top-right corner on and create a bucket called `IoT`. + image::images/create_bucket.png[width=800] . You can now publish the flow for the MiNiFi agent to automatically pick up. Click *Publish*, add a descriptive comment for your changes and click *Apply*. + image::images/publish_flow.png[width=800] + image::images/cem_first_version.png[width=800] . Go back to the *NiFi Registry* Web UI and click on the *NiFi Registry* name, next to the Cloudera logo. If the flow publishing was successful, you should see the flow's version details in the NiFi Registry. + image::images/flow_in_nifi_registry.png[width=800] . At this point, you can test the edge flow up until NiFi. Start the simulator again and confirm you can see the messages queued in NiFi. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- + image::images/running_simulator.png[width=800] + image::images/queued_events.png[width=300] . You can stop the simulator once you confirm that the flow is working correctly. [[lab_4, Lab 4]] == Lab 4 - Registering our schema in Schema Registry The data produced by the temperature sensors is described by the schema in file `link:https://raw.githubusercontent.com/asdaraujo/edge2ai-workshop/master/sensor.avsc[sensor.avsc]`. In this lab we will register this schema in Schema Registry so that our flows in NiFi can refer to schema using an unified service. This will also allow us to evolve the schema in the future, if needed, keeping older versions under version control, so that existing flows and flowfiles will continue to work. . Go the following URL, which contains the schema definition we'll use for this lab. Select all contents of the page and copy it. + `link:https://raw.githubusercontent.com/asdaraujo/edge2ai-workshop/master/sensor.avsc[https://raw.githubusercontent.com/asdaraujo/edge2ai-workshop/master/sensor.avsc, window=""_blank""]` . In the Schema Registry Web UI, click the `+` sign to register a new schema. . Click on a blank area in the *Schema Text* field and paste the contents you copied. . Complete the schema creation by filling the following properties: + [source] ---- Name: SensorReading Description: Schema for the data generated by the IoT sensors Type: Avro schema provider Schema Group: Kafka Compatibility: Backward Evolve: checked ---- image::images/register_schema.png[width=800] . Save the schema [[lab_5, Lab 5]] == Lab 5 - Configuring the NiFi flow and pushing data to Kafka In this lab, you will create a NiFi flow to receive the data from all gateways and push it to **Kafka**. === Creating a Process Group Before we start building our flow, let's create a Process Group to help organizing the flows in the NiFi canvas and also to enable flow version control. . Open the NiFi Web UI, create a new Process Group and name it something like *Process Sensor Data*. + image::images/create_pgroup.png[width=800] . We want to be able to version control the flows we will add to the Process Group. In order to do that, we first need to connect NiFi to the *NiFi Registry*. On the NiFi global menu, click on ""Controller Services"", navigate to the ""Registry Clients"" tab and add a Registry client with the following URL: + ---- Name: NiFi Registry URL: http://edge2ai-1.dim.local:18080 ---- + image::images/global_controller_settings.png[width=800] + image::images/add_registry_client.png[width=800] . On the *NiFi Registry* Web UI, add another bucket for storing the Sensor flow we're about to build'. Call it `SensorFlows`: + image::images/sensor_flows_bucket.png[width=800] . Back on the *NiFi* Web UI, to enable version control for the Process Group, right-click on it and select *Version > Start version control* and enter the details below. Once you complete, a image:images/version_control_tick.png[width=20] will appear on the Process Group, indicating that version control is now enabled for it. + [source] ---- Registry: NiFi Registry Bucket: SensorFlows Flow Name: SensorProcessGroup ---- . Let's also enable processors in this Process Group to use schemas stored in Schema Registry. Right-click on the Process Group, select *Configure* and navigate to the *Controller Services* tab. Click the *`+`* icon and add a *HortonworksSchemaRegistry* service. After the service is added, click on the service's _cog_ icon (image:images/cog_icon.png[width=20]), go to the *Properties* tab and configure it with the following *Schema Registry URL* and click *Apply*. + [source] ---- URL: http://edge2ai-1.dim.local:7788/api/v1 ---- + image::images/added_hwx_sr_service.png[width=800] . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *HortonworksSchemaRegistry* Controller Service. . Still on the *Controller Services* screen, let's add two additional services to handle the reading and writing of JSON records. Click on the image:images/plus_button.png[width=25] button and add the following two services: ** *`JsonTreeReader`*, with the following properties: + [source] ---- Schema Access Strategy: Use 'Schema Name' Property Schema Registry: HortonworksSchemaRegistry Schema Name: ${schema.name} -> already set by default! ---- ** *`JsonRecordSetWriter`*, with the following properties: + [source] ---- Schema Write Strategy: HWX Schema Reference Attributes Schema Access Strategy: Inherit Record Schema Schema Registry: HortonworksSchemaRegistry ---- . Enable the *JsonTreeReader* and the *JsonRecordSetWriter* Controller Services you just created, by clicking on their respective _lightning bolt_ icons (image:images/enable_icon.png[width=20]). + image::images/controller_services.png[width=800] === Creating the flow . Double-click on the newly created process group to expand it. . Inside the process group, add a new _Input Port_ and name it ""Sensor Data"" . We need to tell NiFi which schema should be used to read and write the Sensor data. For this we'll use an _UpdateAttribute_ processor to add an attribute to the FlowFile indicating the schema name. + Add an _UpdateAttribute_ processor by dragging the processor icon to the canvas: + image::images/add_updateattribute.png[width=800] . Double-click the _UpdateAttribute_ processor and configure it as follows: .. In the _SETTINGS_ tab: + [source] ---- Name: Set Schema Name ---- .. In the _PROPERTIES_ tab: ** Click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: schema.name Property Value: SensorReading ---- .. Click *Apply* . Connect the *Sensor Data* input port to the *Set Schema Name* processor. . Add a _PublishKafkaRecord_2.0_ processor and configure it as follows: + *SETTINGS* tab: + [source] ---- Name: Publish to Kafka topic: iot ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name: iot Record Reader: JsonTreeReader Record Writer: JsonRecordSetWriter Use Transactions: false Attributes to Send as Headers (Regex): schema.* ---- + NOTE: Make sure you use the PublishKafkaRecord_2.0 processor and *not* the PublishKafka_2.0 one . While still in the _PROPERTIES_ tab of the _PublishKafkaRecord_2.0_ processor, click on the image:images/plus_button.png[width=25] button and add the following property: + [source] ---- Property Name: client.id Property Value: nifi-sensor-data ---- + Later, this will help us clearly identify who is producing data into the Kafka topic. . Connect the *Set Schema Name* processor to the *Publish to Kafka topic: iot* processor. . Add a new _Funnel_ to the canvas and connect the PublishKafkaRecord processor to it. When the ""Create connection"" dialog appears, select ""*failure*"" and click *Add*. + image::images/add_kafka_failure_connection.png[width=600] . Double-click on the *Publish to Kafka topic: iot* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. + image::images/terminate_publishkafka_relationship.png[width=600] . Start the input port and the two processors. Your canvas should now look like the one below: + image::images/publishKafka_flow.png[width=800] . The only thing that remains to be configured now is to finally connect the ""*from Gateway*"" Input Port to the flow in the ""*Processor Sensor Data*"" group. To do that, first go back to the root canvas by clicking on the *NiFi Flow* link on the status bar. + image::images/breadcrumbs.png[width=400] . Connect the Input Port to the *Process Sensor Data* Process Group by dragging the destination of the current connection from the funnel to the Process Group. When prompted, ensure the ""To input"" fields is set to the *Sensor data* Input Port. + image::images/connect_input.png[width=800] + image::images/to_input.png[width=800] . Refresh the screen (`Ctrl+R` on Linux/Windows; `Cmd+R` on Mac) and you should see that the records that were queued on the ""*from Gateway*"" Input Port disappeared. They flowed into the *Process Sensor Data* flow. If you expand the Process Group you should see that those records were processed by the _PublishKafkaRecord_ processor and there should be no records queued on the ""failure"" output queue. + image::images/kafka_success.png[width=800] + At this point, the messages are already in the Kafka topic. You can add more processors as needed to process, split, duplicate or re-route your FlowFiles to all other destinations and processors. . To complete this Lab, let's commit and version the work we've just done. Go back to the NiFi root canvas, clicking on the ""Nifi Flow"" breadcrumb. Right-click on the *Process Sensor Data* Process Group and select *Version > Commit local changes*. Enter a descriptive comment and save. [[lab_6, Lab 6]] == Lab 6 - Use SMM to confirm that the data is flowing correctly Now that our NiFi flow is pushing data to Kafka, it would be good to have a confirmation that everything is running as expected. In this lab you will use Streams Messaging Manager (SMM) to check and monitor Kafka. . Start the simulator again and confirm you can see the messages queued in NiFi. Leave it running. + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Go to the Stream Messaging Manager (SMM) Web UI and familiarize yourself with the options there. Notice the filters (blue boxes) at the top of the screen. + image::images/smm.png[width=800] . Click on the *Producers* filter and select only the *`nifi-sensor-data`* producer. This will hide all the irrelevant topics and show only the ones that producer is writing to. . If you filter by *Topic* instead and select the `iot` topic, you'll be able to see all the *producers* and *consumers* that are writing to and reading from it, respectively. Since we haven't implemented any consumers yet, the consumer list should be empty. . Click on the topic to explore its details. You can see more details, metrics and the break down per partition. Click on one of the partitions and you'll see additional information and which producers and consumers interact with that partition. + image::images/producers.png[width=800] . Click on the *EXPLORE* link to visualize the data in a particular partition. Confirm that there's data in the Kafka topic and it looks like the JSON produced by the sensor simulator. + image::images/explore_partition.png[width=800] . Check the data from the partition. You'll notice something odd. These are readings from temperature sensors and we don't expect any of the sensors to measure temperatures greater than 150 degrees in the conditions they are used. It seems, though, that `sensor_0` and `sensor_1` are intermittently producing noise and some of the measurements have very high values for these measurements. + image::images/troubled_sensors.png[width=800] . Stop the simulator with CTRL-C. . In the next Lab we'll eliminate with these problematic measurements to avoid problems later in our data flow. [[lab_7, Lab 7]] == Lab 7 - Update the edge flows to perform additional processing on the data In the previous lab we noticed that some of the sensors were sending erroneous measurements intermittently. If we let these measurements to be processed by our data flow we might have problems with the quality of our flow output and we want to avoid that. We could use our *Process Sensor Data* flow in NiFi to filter out those problematic measurements. However, if their volume is large we could be wasting network bandwidth and causing additional overhead in NiFi to process the bogus data. What we'd like to do instead is to push additional logic to the edge to identify and filter those problems in place and avoiding sending them to NiFi in the first place. We've noticed that the problem always happen with the temperatures in measurements `sensor_0` and `sensor_1`, only. If any of these two temperatures are *greater than 500* we *must discard* the entire sensor reading. If both of these temperatures are in the normal range (< 500) we can guarantee that all temperatures reported are correct and can be sent to NiFi. . Go to the CEM Web UI and add a new processor to the canvas. In the Filter box of the dialog that appears, type ""JsonPath"". Select the _EvaluateJSONPath_ processor and click *Add*. . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Extract sensor_0 and sensor1 values Destination: flowfile-attribute ---- + image::images/EvaluateJsonPath.png[width=800] . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`sensor_0`|`$.sensor_0` |`sensor_1`|`$.sensor_1` |=== + image::images/extract_attributes.png[width=800] . Click *Apply* to save the processor configuration. . Drag one more new processor to the canvas. In the Filter box of the dialog that appears, type ""Route"". Select the _RouteOnAttribute_ processor and click *Add*. + image::images/route_on_attribute.png[width=800] . Double-click on the new processor and configure it with the following properties: + [source,python] ---- Processor Name: Filter Errors Route Strategy: Route to Property name ---- . Click on the *Add Property* button and enter the following properties: + [%autowidth,cols=""1a,1a"",options=""header""] |=== |Property Name|Property Value |`error`|`${sensor_0:ge(500):or(${sensor_1:ge(500)})}` |=== + image::images/route_on_attribute_config.png[width=800] . Click *Apply* to save the processor configuration. . Reconnect the _ConsumeMQTT_ processor to the _Extract sensor_0 and sensor1 values_ processor: .. Click on the existing connection between _ConsumeMQTT_ and the _RPG_ to select it. .. Drag the destination end of the connection to the _Extract sensor_0 and sensor1 values_ processor. + image::images/reconnect_consume_mqtt.png[width=800] . Connect the _Extract sensor_0 and sensor1 values_ to the _Filter errors_ processor. When the *Create Connection* dialog appear, select ""*matched*"" and click *Create*. + image::images/connect_extract_to_route.png[width-800] + image::images/create_connection.png[width=800] . Double-click the _Extract sensor_0 and sensor1 values_ and check the following values in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: ** failure ** unmatched ** sensor_0 ** sensor_1 + image::images/terminations.png[width=800] . Before creating the last connection, you will need (again) the ID of the NiFi _Input Port_. Go to the NiFi Web UI , double-click on the ""*from Gateway*"" _Input Port_ and copy its ID. + image::images/input_port_id.png[width=800] . Back on the CEM Web UI, connect the _Filter errors_ processor to the RPG: + image::images/connect_filter_ro_rpg.png[width=800] . In the *Create Connection* dialog, check the ""*unmatched*"" checkbox and enter the copied input port ID, and click on *Create*: + image::images/create_last_connection.png[width=800] . To ignore the errors, double-click on the _Filter errors_ processor, check the *error* checkbox under the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section and click *Apply*: + image::images/terminate_errors.png[width=800] . Finally, click on *ACTIONS > Publish...* on the CEM canvas, enter a descriptive comment like ""Added filtering of erroneous readings"" and click *Publish*. . Start the simulator again. . Go to the NiFi Web UI and confirm that the data is flowing without errors within the *Process Sensor Data* process group. Refresh a few times and check that the numbers are changing. . Use the *EXPLORE* feature on the SMM Web UI to confirm that the bogus readings have been filtered out. . Stop the simulator once you have verified the data. [[lab_8, Lab 8]] == Lab 8 - Use NiFi to call the CDSW model endpoint and save to Kudu In this lab, you will use NiFi to consume the Kafka messages containing the IoT data we ingested in the previous lab, call a CDSW model API endpoint to predict whether the machine where the readings came from is likely to break or not. In preparation for the workshop we trained and deployed a Machine Learning model on the Cloudera Data Science Workbench (CDSW) running on your cluster. The model API can take a feature vector with the reading for the 12 temperature readings provided by the sensor and predict, based on that vector, if the machine is likely to break or not. === Add new Controller Services When the sensor data was sent to Kafka using the _PublishKafkaRecord_ processor, we chose to attach the schema information in the header of Kafka messages. Now, instead of hard-coding which schema we should use to read the message, we can leverage that metadata to dynamically load the correct schema for each message. To do this, though, we need to configure a different _JsonTreeReader_ that will use the schema properties in the header, instead of the `${schema.name}` attribute, as we did before. We'll also add a new _RestLookupService_ controller service to perform the calls to the CDSW model API endpoint. . If you're not in the *Process Sensor Data* process group, double-click on it to expand it. On the *Operate* panel (left-hand side), click on the _cog_ icon (image:images/cog_icon.png[width=25]) to access the *Process Sensor Data* process group's configuration page. + image::images/operate_panel_cog.png[width=300] . Click on the _plus_ button (image:images/plus_button.png[width=25]), add a new *JsonTreeReader*, configure it as shown below and click *Apply* when you're done: + On the *SETTINGS* tab: + [source] ---- Name: JsonTreeReader - With schema identifier ---- + On the *PROPERTIES* tab: + [source] ---- Schema Access Strategy: HWX Schema Reference Attributes Schema Registry: HortonworksSchemaRegistry ---- . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *JsonTreeReader - With schema identifier* controller service. . Click again on the _plus_ button (image:images/plus_button.png[width=25]), add a *RestLookupService* controller service, configure it as shown below and click *Apply* when you're done: + On the *PROPERTIES* tab: + [source] ---- URL: http://cdsw..nip.io/api/altus-ds-1/models/call-model Record Reader: JsonTreeReader Record Path: /response ---- + NOTE: `` above must be replaced with your cluster's public IP, *not* DNS name. The final URL should look something like this: `\\http://cdsw.12.34.56.78.nip.io/api/altus-ds-1/models/call-model` . Click on the _lightning bolt_ icon (image:images/enable_icon.png[width=20]) to *enable* the *RestLookupService* controller service. + image::images/additional_controller_services.png[width=800] . Close the *Process Sensor Data Configuration* page. === Create the flow We'll now create the flow to read the sensor data from Kafka, execute a model prediction for each of them and write the results to Kudu. At the end of this section you flow should look like the one below: image::images/from_kafka_to_kudu_flow.png[width=800] ==== ConsumeKafkaRecord_2_0 processor . We'll add a new flow to the same canvas we were using before (inside the *Process Sensor Data* Process Group). Click on an empty area of the canvas and drag it to the side to give you more space to add new processors. . Add a *ConsumeKafkaRecord_2_0* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Consume Kafka iot messages ---- + *PROPERTIES* tab: + [source] ---- Kafka Brokers: edge2ai-1.dim.local:9092 Topic Name(s): iot Topic Name Format: names Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Honor Transactions: false Group ID: iot-sensor-consumer Offset Reset: latest Headers to Add as Attributes (Regex): schema.* ---- . Add a new _Funnel_ to the canvas and connect the *Consume Kafka iot messages* to it. When prompted, check the *parse.failure* relationship for this connection: + image:images/parse_failure_relationship.png[width=500] ==== LookupRecord processor . Add a *LookupRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Predict machine health ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Lookup Service: RestLookupService Result RecordPath: /response Routing Strategy: Route to 'success' Record Result Contents: Insert Entire Record ---- . Add 3 more user-defined properties by clicking on the _plus_ button (image:images/plus_button.png[width=25]) for each of them: + [source] ---- mime.type: toString('application/json', 'UTF-8') request.body: concat('{""accessKey"":""', '${cdsw.access.key}', '"",""request"":{""feature"":""', /sensor_0, ', ', /sensor_1, ', ', /sensor_2, ', ', /sensor_3, ', ', /sensor_4, ', ', /sensor_5, ', ', /sensor_6, ', ', /sensor_7, ', ', /sensor_8, ', ', /sensor_9, ', ', /sensor_10, ', ', /sensor_11, '""}}') request.method: toString('post', 'UTF-8') ---- . Click *Apply* to save the changes to the *Predict machine health* processor. . Connect the *Consume Kafka iot messages* processor to the *Predict machine health* one. When prompted, check the *success* relationship for this connection. . Connect the *Predict machine health* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== UpdateRecord processor . Add a *UpdateRecord* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Update health flag ---- + *PROPERTIES* tab: + [source] ---- Record Reader: JsonTreeReader - With schema identifier Record Writer: JsonRecordSetWriter Replacement Value Strategy: Record Path Value ---- . Add one more user-defined propertie by clicking on the _plus_ button (image:images/plus_button.png[width=25]): + [source] ---- /is_healthy: /response/result ---- . Connect the *Predict machine health* processor to the *Update health flag* one. When prompted, check the *success* relationship for this connection. . Connect the *Update health flag* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. ==== PutKudu processor . Add a *PutKudu* processor to the canvas and configure it as shown below: + *SETTINGS* tab: + [source] ---- Name: Write to Kudu ---- + *PROPERTIES* tab: + [source] ---- Kudu Masters: edge2ai-1.dim.local:7051 Table Name: impala::default.sensors Record Reader: JsonTreeReader - With schema identifier ---- . Connect the *Update health flag* processor to the *Write to Kudu* one. When prompted, check the *success* relationship for this connection. . Connect the *Write to Kudu* to the same _Funnel_ you had created above. When prompted, check the *failure* relationship for this connection. . Double-click on the *Write to Kudu* processor, go to the *SETTINGS* tab, check the ""*success*"" relationship in the *AUTOMATICALLY TERMINATED RELATIONSHIPS* section. Click *Apply*. ==== CDSW Access Key When we added the *Predict machine health* above, you may have noticed that one of the properties (`request.body`) makes a reference to a variable called `cdsw.access.key`. This is an application key required to authenticate with the CDSW Model API when requesting predictions. So, we need to provide the key to the _LookupRecord_ processor by setting a variable with its value. . To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] . Go back to the NiFi Web UI, right-click on an empty area of the *Process Sensor Data* canvas, and click on *Variables*. . Click on the _plus_ button (image:images/plus_button.png[width=25]) and add the following variable: + [source] ---- Variable Name: cdsw.access.key Variable Value: ---- + image::images/access_key_variable.png[width=800] . Click *Apply* ==== Create the Kudu table . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== Running the flow We're ready not to run and test our flow. Follow the steps below: . Start all the processors in your flow. . If the simulator is not already running, start it again on your SSH window: + [source] ---- python mqtt.iot_simulator.py mqtt.iot.config ---- . Refresh your NiFi page and you should see messages passing through your flow. The failure queues should have no records queued up. + image::images/kudu_success.png[width=800] . On Lab 10, you will learn how to query and verify the records inserted into Kudu. [[lab_9, Lab 9]] == Lab 9 - Use Spark to call the CDSW model endpoint and save to Kudu NOTE: This lab is optional, since it does the same processing we performed in Lab 8 but using Spark instead of NiFi. If you want to run this lab, stop the flow created in Lab 8 first, to avoid duplicated data being sent into Kudu. Otherwise, just skip to *Lab 10* Spark Streaming is a processing framework for (near) real-time data. In this lab, you will use Spark to consume Kafka messages which contains the IoT data from the machine, and call the model API endpoint to predict whether, with those IoT values the machine sent, the machine is likely to break. Then save the results to Kudu for fast analytics. ==== Create the Kudu table NOTE: If you already executed this step in the previous lab, please skip the table creation here. . Go to the Hue Web UI and login. The first user to login to a Hue installation is automatically created and granted admin privileges in Hue. . The Hue UI should open with the Impala Query Editor by default. If it doesn't, you can always find it by clicking on *Query button > Editor -> Impala*: + image::images/impala_editor.png[width=800] . First, create the Kudu table. Login into Hue, and in the Impala Query, run this statement: + [source,sql] ---- CREATE TABLE sensors ( sensor_id INT, sensor_ts TIMESTAMP, sensor_0 DOUBLE, sensor_1 DOUBLE, sensor_2 DOUBLE, sensor_3 DOUBLE, sensor_4 DOUBLE, sensor_5 DOUBLE, sensor_6 DOUBLE, sensor_7 DOUBLE, sensor_8 DOUBLE, sensor_9 DOUBLE, sensor_10 DOUBLE, sensor_11 DOUBLE, is_healthy INT, PRIMARY KEY (sensor_ID, sensor_ts) ) PARTITION BY HASH PARTITIONS 16 STORED AS KUDU TBLPROPERTIES ('kudu.num_tablet_replicas' = '1'); ---- + image::images/create_table.png[width=800] ==== CDSW Access Key . To configure and run the Spark Streaming job, you will need a CDSW Access Key to connect to the model endpoint that has been deployed there. To get the Access Key, go to the CDSW Web UI and click on *Models > Iot Prediction Model > Settings*. Copy the Access Key. + image::images/model_access_key.png[width=800] ==== Running the Spark job . Open a second Terminal and SSH into the VM. The first is running the sensor data simulator, so you can't use it. + [source,shell] ---- ACCESS_KEY= PUBLIC_IP=$(curl https://api.ipify.org/) mv ~/edge2ai-workshop/spark.iot.py ~ sed -i ""s/YourHostname/$(hostname -f)/"" spark.iot.py sed -i ""s/YourCDSWDomain/cdsw.$PUBLIC_IP.nip.io/"" spark.iot.py sed -i ""s/YourAccessKey/$ACCESS_KEY/"" spark.iot.py wget http://central.maven.org/maven2/org/apache/kudu/kudu-spark2_2.11/1.9.0/kudu-spark2_2.11-1.9.0.jar wget https://raw.githubusercontent.com/swordsmanliu/SparkStreamingHbase/master/lib/spark-core_2.11-1.5.2.logging.jar rm -rf ~/.m2 ~/.ivy2/ spark-submit \\ --master local[2] \\ --jars kudu-spark2_2.11-1.9.0.jar,spark-core_2.11-1.5.2.logging.jar \\ --packages org.apache.spark:spark-streaming-kafka_2.11:1.6.3 \\ spark.iot.py ---- + . Spark Streaming will flood your screen with log messages, however, at a 5 seconds interval, you should be able to spot a table: these are the messages that were consumed from Kafka and processed by Spark. You can configure Spark for a smaller time window, however, for this exercise 5 seconds is sufficient. + image::images/spark_job_output.png[width=800] [[lab_10, Lab 10]] == Lab 10 - Fast analytics on fast data with Kudu and Impala In this lab, you will run some SQL queries using the Impala engine. You can run a report to inform you which machines are likely to break in the near future. . Login into Hue and run the following queries in the Impala Query Editor: + [source,sql] ---- SELECT sensor_id, sensor_ts FROM sensors WHERE is_healthy = 0; ---- + [source,sql] ---- SELECT is_healthy, count(*) as occurrences FROM sensors GROUP BY is_healthy; ---- . Run a few times the SQL statements and verify that the number of occurrences are increasing as the data is ingested by either NiFi or the Spark job. This allows you to build real-time reports for fast action. + image::images/table_select.png[width=800] [[lab_11, Lab 11]] == Lab 11 - CDSW: Train the model In this and the following lab, you will wear the hat of a Data Scientist. You will write the model code, train it several times and finally deploy the model to Production. All within 30 minutes! === STEP 1: Configure CDSW . Open CDSW Web UI and log in as `admin`, if you haven't yet done so. . Navigate to the CDSW **Admin** page to fine tune the environment: .. In the **Engines** tab, add in _Engines Profiles_ a new engine (docker image) with 2 vCPUs and 4 GB RAM, while deleting the default engine. .. Check if the following variable already exists under _Environmental Variables_. If not, add it: + [source] ---- HADOOP_CONF_DIR=/etc/hadoop/conf/ ---- + image::images/engines.png[width=800] === STEP 2: Create the project . Return to the main page and click on *New Project*, using this GitHub project as the source: `https://github.com/asdaraujo/edge2ai-workshop` + image::images/create_project.png[width=800] . Now that your project has been created, click on *Open Workbench* and start a Python3 session: + image::images/open_workbench.png[width=800] . Once the Engine is ready, run the following command to install some required libraries: + [source] ---- !pip3 install --upgrade pip scikit-learn ---- . The project comes with a historical dataset. Copy this dataset into HDFS: + [source] ---- !hdfs dfs -put -f data/historical_iot.txt /user/$HADOOP_USER_NAME ---- + image::images/session_prep.png[width=800] . You're now ready to run the Experiment to train the model on your historical data. . You can stop the Engine at this point. === STEP 3: Examine `cdsw.iot_exp.py` Open the file `cdsw.iot_exp.py`. This is a python program that builds a model to predict machine failure (the likelihood that this machine is going to fail). There is a dataset available on hdfs with customer data, including a failure indicator field. The program is going to build a failure prediction model using the Random Forest algorithm. Random forests are ensembles of decision trees. Random forests are one of the most successful machine learning models for classification and regression. They combine many decision trees in order to reduce the risk of overfitting. Like decision trees, random forests handle categorical features, extend to the multiclass classification setting, do not require feature scaling, and are able to capture non-linearities and feature interactions. `spark.mllib` supports random forests for binary and multiclass classification and for regression, using both continuous and categorical features. `spark.mllib` implements random forests using the existing decision tree implementation. Please see the decision tree guide for more information on trees. The Random Forest algorithm expects a couple of parameters: * *numTrees*: Number of trees in the forest. + Increasing the number of trees will decrease the variance in predictions, improving the model’s test-time accuracy. Training time increases roughly linearly in the number of trees. * *maxDepth*: Maximum depth of each tree in the forest. + Increasing the depth makes the model more expressive and powerful. However, deep trees take longer to train and are also more prone to overfitting. In general, it is acceptable to train deeper trees when using random forests than when using a single decision tree. One tree is more likely to overfit than a random forest (because of the variance reduction from averaging multiple trees in the forest). In the `cdsw.iot_exp.py` program, these parameters can be passed to the program at runtime, to these python variables: [source,python] ---- param_numTrees = int(sys.argv[1]) param_maxDepth = int(sys.argv[2]) ---- Also note the quality indicator for the Random Forest model, are written back to the Data Science Workbench repository: [source,python] ---- cdsw.track_metric(""auroc"", auroc) cdsw.track_metric(""ap"", ap) ---- These indicators will show up later in the **Experiments** dashboard. === STEP 4: Run the experiment for the first time . Now, run the experiment using the following parameters: + [source,python] ---- numTrees = 20 numDepth = 20 ---- . From the menu, select `Run -> Run Experiments...`. Now, in the background, the Data Science Workbench environment will spin up a new docker container, where this program will run. + image::images/run_experiment.png[width=800] . Go back to the **Projects** page in CDSW, and hit the **Experiments** button. . If the Status indicates `Running`, you have to wait till the run is completed. In case the status is `Build Failed` or `Failed` , check the log information. This is accessible by clicking on the run number of your experiments. There you can find the session log, as well as the build information. + image::images/experiment_details.png[width=800] . In case your status indicates `Success`, you should be able to see the *auroc* (Area Under the Curve) model quality indicator. It might be that this value is hidden by the CDSW user interface. In that case, click on the ‘3 metrics’ links, and select the auroc field. It might be needed to de-select some other fields, since the interface can only show 3 metrics at the same time. + image::images/exp_metrics.png[width=800] . In this example, `~0.8383`. Not bad, but maybe there are better hyper parameter values available. === STEP 5: Re-run the experiment several times . Go back to the Workbench and run the experiment 2 more times and try different values for NumTrees and NumDepth. Try the following values: + [source,python] ---- NumTrees NumDepth 15 25 25 20 ---- . When all runs have completed successfully, check which parameters had the best quality (best predictive value). This is represented by the highest _area under the curve_: `auroc` metric. + image::images/best_model.png[width=800] === STEP 6: Save the best model to your environment . Select the run number with the best predictive value (in the example above, experiment *4*). . In the *Overview* screen of the experiment, you can see that the model, in Pickle format (`.pkl`), is captured in the file `iot_model.pkl`. Select this file and hit the **Add to Project** button. This will copy the model to your project directory. + image::images/save_model.png[width=800] + image::images/model_saved.png[width=800] [[lab_12, Lab 12]] == Lab 12 - CDSW: Deploy the model === STEP 1: Examine the program `cdsw.iot_model.py` . Open the project you created in the previous lab and examine the file in the Workbench. This PySpark program uses the `pickle.load` mechanism to deploy models. The model is loaded from the `iot_modelf.pkl` file, which was saved in the previous lab from the experiment with the best predictive model. + There program also contains the `predict` definition, which is the function that calls the model, passing the features as parameters, and will return a result variable. . Before deploying the model, try it out in the Workbench: launch a Python3 engine and run the code in file `cdsw.iot_model.py`. Then call the `predict()` method from the prompt: + [source,python] ---- predict({""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""}) ---- + image::images/predict.png[width=800] . The functions returns successfully, so we know we can now deploy the model. You can now stop the engine. === STEP 2: Deploy the model . From the main page of your project, select the *Models* button. Select *New Model* and specify the following configuration: + [source, python] ---- Name: IoT Prediction Model Description: IoT Prediction Model File: cdsw.iot_model.py Function: predict Example Input: {""feature"": ""0, 65, 0, 137, 21.95, 83, 19.42, 111, 9.4, 6, 3.43, 4""} Kernel: Python 3 Engine: 2 vCPU / 4 GB Memory Replicas: 1 ---- + image:images/create_model.png[width=800] . After all parameters are set, click on the *Deploy Model* button. Wait till the model is deployed. This can take several minutes. === STEP 3: Test the deployed model . When your model status change to `Deployed`, click on the model name link to go to the Model's *Overview* page. From the that page, click on the *Test* button to check if the model is working. . The green circle with the `success` status indicates that our REST call to the model is working. The `1` in the response `{""result"": 1}`, means that the machine from where these temperature readings were collected is _unlikely_ to experience a failure. + image::images/test_model.png[width=800] . Now, lets change the input parameters and call the predict function again. Put the following values in the Input field: + [source,python] ---- { ""feature"": ""0, 95, 0, 88, 26.62, 75, 21.05, 115, 8.65, 5, 3.32, 3"" } ---- . With these input parameters, the model returns `0`, which means that the machine is likely to break. == Resources * link:https://medium.freecodecamp.org/building-an-iiot-system-using-apache-nifi-mqtt-and-raspberry-pi-ce1d6ed565bc[Original blog by Abdelkrim Hadjidj] * This workshop was based on the following work by Fabio Ghirardello: ** https://github.com/fabiog1901/IoT-predictive-maintenance ** https://github.com/fabiog1901/OneNodeCDHCluster * link:https://www.cloudera.com/documentation.html[Cloudera Documentation] == Troubleshooting ==== *CEM doesn't pick up new NARs* . Delete the agent manifest manually using the EFM API: . Verify each class has the same agent manifest ID: + [source] ---- http://hostname:10080/efm/api/agent-classes [{""name"":""iot1"",""agentManifests"":[""agent-manifest-id""]},{""name"":""iot4"",""agentManifests"":[""agent-manifest-id""]}] ---- . Confirm the manifest doesn't have the NAR you installed + [source] ---- http://hostname:10080/efm/api/agent-manifests?class=iot4 [{""identifier"":""agent-manifest-id"",""agentType"":""minifi-java"",""version"":""1"",""buildInfo"":{""timestamp"":1556628651811,""compiler"":""JDK 8""},""bundles"":[{""group"":""default"",""artifact"":""system"",""version"":""unversioned"",""componentManifest"":{""controllerServices"":[],""processors"": ---- . Call the API endpoint: + [source] ---- http://hostname:10080/efm/swagger/ ---- . Hit the `DELETE - Delete the agent manifest specified by id` button, and in the id field, enter `agent-manifest-id` ",12192,False,2081.7040955950542,median "//------------------------------------------------------------------------------------------------ // Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). // All rights reserved. //------------------------------------------------------------------------------------------------ /******************************************************************************************************************************************************************************************* * LICENSE NOTICE ******************************************************************************************************************************************************************************************** * By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change * this code. ******************************************************************************************************************************************************************************************** * 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at * g.iannello@unicampus.it for further details. * 2. You agree to appropriately cite this work in your related studies and publications. * 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors ""as is"" and any express or implied war- * ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the * copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil- * ity, 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. * 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without * specific prior written permission. ********************************************************************************************************************************************************************************************/ /****************** * CHANGELOG * ******************* * 2015-12-10. Giluio. @FIXED added several volume creation alternatives in ""instance"" methods to include new formats * 2015-04-15. Alessandro. @ADDED 'instance_format' method with inputs = {path, format}. * 2015-04-15. Alessandro. @ADDED definition for default constructor. * 2015-04-14. Alessandro. @FIXED detection of volume format from .iim.format file * 2015-03-21. Giulio. @FIXED bug in saveImage when tiles have to be saved (the management of offsets over the buffer was wrong) * 2015-03-03. Giulio. @FIXED a 2D plugin has to be used in saveImage_from_UINT8 * 2015-02-15. Giulio. @CHANGED revised all calls to Tiff3DMngr routines passing always width and height in this order * 2015-02-14. Giulio. @CHANGED method saveImage now converts from real to uint8 and calls the new interface of the plugin * 2015-02-13. Giulio. @CHANGED method saveImage_from_UINT8_to_Tiff3D now call a 3D pluging to save a slice (only when do_open is true) * 2015-02-12. Giulio. @FIXED bug concerning the number of channels in the saved image in method 'saveImage_from_UINT8_to_Tiff3D' * 2015-02-06. Giulio. @ADDED added optimizations to reduce opend/close in append operations (only in saveImage_from_UINT8_to_Tiff3D) * 2015-02-06. Alessandro. @ADDED volume format metadata file for fast opening of a ""directory format"" * 2014-11-22. Giulio. @CHANGED code using OpenCV has been commente. It can be found searching comments containing 'Giulio_CV' * 2014-11-10. Giulio. @CHANGED allowed saving 2dseries with a depth of 16 bit (generateTiles) */ #include #include ""VirtualVolume.h"" #include ""SimpleVolume.h"" #include ""SimpleVolumeRaw.h"" #include ""RawVolume.h"" #include ""TiledVolume.h"" #include ""TiledMCVolume.h"" #include ""StackedVolume.h"" #include ""UnstitchedVolume.h"" #include ""BDVVolume.h"" #include ""RawFmtMngr.h"" #include ""Tiff3DMngr.h"" #include ""TimeSeries.h"" #include // Giulio_CV #include // Giulio_CV #include #include ""IOPluginAPI.h"" // 2014-11-26. Giulio. #include using namespace iim; // 2015-04-15. Alessandro. @ADDED definition for default constructor. VirtualVolume::VirtualVolume(void) { /**/iim::debug(iim::LEV3, 0, __iim__current__function__); root_dir = 0; VXL_V = VXL_H = VXL_D = ORG_V = ORG_H = ORG_D = 0.0f; DIM_V = DIM_H = DIM_D = DIM_C = 0; BYTESxCHAN = 0; active = 0; n_active = 0; t0 = t1 = 0; DIM_T = 1; } /************************************************************************************************************* * Save image method. <> parameters are mandatory, while [] are optional. * : absolute path of image to be saved. It DOES NOT include its extension, which is * provided by the [img_format] parameter. * : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. * : dimensions of raw_img. * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. * [img_format] : image format extension to be used (e.g. ""tif"", ""png"", etc.) * [img_depth] : image bitdepth to be used (8 or 16) **************************************************************************************************************/ void VirtualVolume::saveImage(std::string img_path, real32* raw_img, int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, int end_width, const char* img_format, int img_depth) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d"", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); //throw IOException(""in VirtualVolume::saveImage(...): disabled to remove dependence from openCV""); // Giulio_CV // Giulio_CV uint8 *row_data_8bit; // Giulio_CV uint16 *row_data_16bit; // Giulio_CV uint32 img_data_step; // Giulio_CV float scale_factor_16b, scale_factor_8b; int img_height, img_width; // Giulio_CV int i,j; char img_filepath[5000]; //setting some default parameters and image dimensions end_height = (end_height == -1 ? raw_img_height - 1 : end_height); end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); img_height = end_height - start_height + 1; img_width = end_width - start_width + 1; //checking parameters correctness if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width(raw_img[ii*raw_img_width+jj] * 255.0f + 0.5f); } } else // img_depth == 16 { for(int i = 0, ii = start_height; i (raw_img[ii*raw_img_width+jj] * 65535.0f + 0.5f); } } //generating complete path for image to be saved sprintf(img_filepath, ""%s.%s"", img_path.c_str(), img_format); // 2014-11-26. Giulio. @ADDED the output plugin must be explicitly set by the caller try { //iomanager::IOPluginFactory::getPlugin2D(iomanager::IMOUT_PLUGIN)->writeData( // img_filepath, raw_img, img_height, img_width, 1, start_height, end_height, start_width, end_width, img_depth); iomanager::IOPluginFactory::getPlugin2D(iomanager::IMOUT_PLUGIN)->writeData( img_filepath, buffer, img_height, img_width, img_depth/8, 1, 0, img_height, 0, img_width); // ROI limits specify right-open intervals } catch (iom::exception & ex) { if ( strstr(ex.what(),""2D I/O plugin"") ) // this method has be called to save the middle slice for test purposes, even though output plugin is not a 2D plugin iomanager::IOPluginFactory::getPlugin2D(""tiff2D"")->writeData( img_filepath, buffer, img_height, img_width, img_depth/8, 1, 0, img_height, 0, img_width); // ROI limits specify right-open intervals else throw iom::exception(iom::strprintf(ex.what()), __iom__current__function__); } delete []buffer; } /************************************************************************************************************* * Save image method from uint8 raw data. <> parameters are mandatory, while [] are optional. * : absolute path of image to be saved. It DOES NOT include its extension, which is * provided by the [img_format] parameter. * : dimensions of raw_img. * : raw data of the first channel with values in [0,255]. * For grayscale images this is the pointer to the raw image data. * For colour images this is the pointer to the raw image data of the RED channel. * : raw data of the second channel with values in [0,255]. * For grayscale images this should be a null pointer (as it is by default). * For colour images this is the pointer to the raw image data of the GREEN channel. * : raw data of the third channel with values in [0,255]. * For grayscale images this should be a null pointer (as it is by default). * For colour images this is the pointer to the raw image data of the BLUE channel. * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. * [img_format] : image format extension to be used (e.g. ""tif"", ""png"", etc.) * [img_depth] : image bitdepth to be used (8 or 16) **************************************************************************************************************/ void VirtualVolume::saveImage_from_UINT8 (std::string img_path, uint8* raw_ch1, uint8* raw_ch2, uint8* raw_ch3, int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, int end_width, const char* img_format, int img_depth ) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d, img_format=%s, img_depth=%d"", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width, img_format, img_depth).c_str(), __iim__current__function__); // throw IOException(""in VirtualVolume::saveImage_from_UINT8(...): disabled to remove dependence from openCV""); // Giulio_CV if ( strcmp(img_format,""tif"") != 0 ) throw iom::exception(iom::strprintf(""unsupported file format %s"",img_format), __iom__current__function__); //checking for non implemented features //if( img_depth != 8 ) { // char err_msg[STATIC_STRINGS_SIZE]; // sprintf(err_msg,""SimpleVolume::loadSubvolume_to_UINT8: invalid number of bits per channel (%d)"",img_depth); // throw IOException(err_msg); //} //LOCAL VARIABLES char buffer[STATIC_STRINGS_SIZE]; // Giulio_CV IplImage* img = 0; uint8 *img = (uint8 *) 0; int img_height, img_width; int nchannels = 0; //detecting the number of channels (WARNING: the number of channels is an attribute of the volume nchannels = static_cast(raw_ch1!=0) + static_cast(raw_ch2!=0) + static_cast(raw_ch3!=0); //setting some default parameters and image dimensions end_height = (end_height == -1 ? raw_img_height - 1 : end_height); end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); img_height = end_height - start_height + 1; img_width = end_width - start_width + 1; //checking parameters correctness if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width 3) { sprintf(buffer,""in saveImage_from_UINT8(): unsupported number of channels (= %d)\\n"",nchannels); throw IOException(buffer); } if(img_depth != 8 && img_depth != 16 && nchannels == 1) { sprintf(buffer,""in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for greyscale images\\n"",img_depth); throw IOException(buffer); } //if(img_depth != 8 && nchannels == 3) // nchannels may be also 2 if(img_depth != 8 && nchannels > 1) { sprintf(buffer,""in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for multi-channels images\\n"",img_depth); throw IOException(buffer); } if ( nchannels >1 && !(iom::IOPluginFactory::getPlugin2D(iom::IMOUT_PLUGIN)->isChansInterleaved()) ) { throw iom::exception(""the plugin do not store channels in interleaved mode: more than one channel not supported yet.""); } //converting raw data into tif image data if(nchannels == 3) { img = new uint8[img_width * img_height * nchannels]; // Giulio_CV cvCreateImage(cvSize(img_width, img_height), IPL_DEPTH_8U, 3); int img_data_step = img_width * nchannels; for(int i = 0; i depth == 16 { int img_data_step = img_width * nchannels * 2; for(int i = 0; i 1 ? 3 : 1),img_depth/8)) != 0 ) { throw iom::exception(iom::strprintf(""unable to create tiff file (%s)"",err_tiff_fmt), __iom__current__function__); } if ( (err_tiff_fmt = appendSlice2Tiff3DFile(buffer,0,(unsigned char *)img,(int)img_width,(int)img_height)) != 0 ) { throw iom::exception(iom::strprintf(""error in saving 2D image (%lld x %lld) in file %s (appendSlice2Tiff3DFile: %s)"",img_width,img_height,buffer,err_tiff_fmt), __iom__current__function__); } /* Giulio_CV } catch(std::exception ex) { char err_msg[STATIC_STRINGS_SIZE]; sprintf(err_msg,""in saveImage_from_UINT8(...): unable to save image at \\""%s\\"". Unsupported format or wrong path.\\n"",buffer); throw IOException(err_msg); } releasing memory cvReleaseImage(&img); */ if ( img ) delete []img; } /************************************************************************************************************* * Save image method to Vaa3D raw format. <> parameters are mandatory, while [] are optional. * : absolute path of image to be saved. It DOES NOT include its extension, which is * provided by the [img_format] parameter. * : image to be saved. Raw data is in [0,1] and it is stored row-wise in a 1D array. * : dimensions of raw_img. * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. * [img_format] : image format extension to be used (e.g. ""tif"", ""png"", etc.) * [img_depth] : image bitdepth to be used (8 or 16) **************************************************************************************************************/ void VirtualVolume::saveImage_to_Vaa3DRaw(int slice, std::string img_path, real32* raw_img, int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, int end_width, const char* img_format, int img_depth ) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d"", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); //checking for non implemented features if ( strcmp(img_format,""Vaa3DRaw"")!=0 && strcmp(img_format,""Tiff3D"")!=0 ) { // WARNING: there is not a well defined convention yet for specify image format char msg[STATIC_STRINGS_SIZE]; sprintf(msg,""in VirtualVolume::saveImage_to_Vaa3DRaw: format \\""%s\\"" not implemented yet"",img_format); throw IOException(msg); } uint8 *row_data_8bit; uint16 *row_data_16bit; //uint32 img_data_step; float scale_factor_16b, scale_factor_8b; int img_height, img_width; int i, j, k; char img_filepath[5000]; // WARNING: currently supported only 8/16 bits depth by VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw if(img_depth != 8 && img_depth != 16) { char err_msg[STATIC_STRINGS_SIZE]; sprintf(err_msg,""in saveImage_to_Vaa3DRaw(..., img_depth=%d, ...): unsupported bit depth\\n"",img_depth); throw IOException(err_msg); } //setting some default parameters and image dimensions end_height = (end_height == -1 ? raw_img_height - 1 : end_height); end_width = (end_width == -1 ? raw_img_width - 1 : end_width ); img_height = end_height - start_height + 1; img_width = end_width - start_width + 1; //checking parameters correctness if(!(start_height>=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width parameters are mandatory, while [] are optional. * : absolute path of image to be saved. It DOES NOT include its extension, which is * provided by the [img_format] parameter. * : array of pointers to raw data of the channels with values in [0,255]. * For grayscale images raw_ch[0] is the pointer to the raw image data. * For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. * WARNING: raw_ch elements should not be overwritten * : number of channels (length of raw_ch). * : offset to be added to raw_ch[i] to get actual data * : dimensions of raw_img. * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. * [img_format] : image format extension to be used (e.g. ""tif"", ""png"", etc.) * [img_depth] : image bitdepth to be used (8 or 16) **************************************************************************************************************/ void VirtualVolume::saveImage_from_UINT8_to_Vaa3DRaw (int slice, std::string img_path, uint8** raw_ch, int n_chans, sint64 offset, int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, int end_width, const char* img_format, int img_depth ) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d"", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); //LOCAL VARIABLES char buffer[STATIC_STRINGS_SIZE]; sint64 img_height, img_width; sint64 img_width_b; // image width in bytes int img_bytes_per_chan; //add offset to raw_ch //for each channel adds to raw_ch the offset of current slice from the beginning of buffer uint8** raw_ch_temp = new uint8 *[n_chans]; for (int i=0; i=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width 1) // { // sprintf(buffer,""in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth for multi-channel images\\n"",img_depth); // throw iim::IOException(buffer); // } if(img_depth != 8 && img_depth != 16 && n_chans == 1) { sprintf(buffer,""in saveImage_from_UINT8(..., img_depth=%d, ...): unsupported bit depth\\n"",img_depth); throw IOException(buffer); } img_bytes_per_chan = (img_depth == 8) ? 1 : 2; // all width parameters have to be multiplied by the number of bytes per channel img_width_b = img_width * img_bytes_per_chan; raw_img_width *= img_bytes_per_chan; start_width *= img_bytes_per_chan; uint8 *imageData = new uint8[img_height * img_width_b * n_chans]; for ( int c=0; c parameters are mandatory, while [] are optional. * : absolute path of image to be saved. It DOES NOT include its extension, which is * provided by the [img_format] parameter. * : array of pointers to raw data of the channels with values in [0,255]. * For grayscale images raw_ch[0] is the pointer to the raw image data. * For colour images raw_ch[0] is the pointer to the raw image data of the RED channel. * WARNING: raw_ch elements should not be overwritten * : number of channels (length of raw_ch). * : offset to be added to raw_ch[i] to get actual data * : dimensions of raw_img. * [start/end_height/width] : optional ROI (region of interest) to be set on the given image. * [img_format] : image format extension to be used (e.g. ""tif"", ""png"", etc.) * [img_depth] : image bitdepth to be used (8 or 16) **************************************************************************************************************/ void VirtualVolume::saveImage_from_UINT8_to_Tiff3D (int slice, std::string img_path, uint8** raw_ch, int n_chans, sint64 offset, int raw_img_height, int raw_img_width, int start_height, int end_height, int start_width, int end_width, const char* img_format, int img_depth, void *fhandle, int n_pages, bool do_open ) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""img_path=%s, raw_img_height=%d, raw_img_width=%d, start_height=%d, end_height=%d, start_width=%d, end_width=%d"", img_path.c_str(), raw_img_height, raw_img_width, start_height, end_height, start_width, end_width).c_str(), __iim__current__function__); //LOCAL VARIABLES char buffer[STATIC_STRINGS_SIZE]; sint64 img_height, img_width; sint64 img_width_b; // image width in bytes int img_bytes_per_chan; int temp_n_chans = n_chans; // number of channels of the saved image: initialize with the number of channels of the source volume //add offset to raw_ch //for each channel adds to raw_ch the offset of current slice from the beginning of buffer uint8** raw_ch_temp = new uint8 *[n_chans]; for (int i=0; i=0 && end_height>start_height && end_height=0 && end_width>start_width && end_width1 && !(iom::IOPluginFactory::getPlugin3D(iom::IMOUT_PLUGIN)->isChansInterleaved()) ) { throw iom::exception(""the 3D plugin do not store channels in interleaved mode: more than one channel not supported yet.""); } img_bytes_per_chan = (img_depth == 8) ? 1 : 2; img_width_b = img_width * img_bytes_per_chan; if ( n_chans == 2 ) // for Tiff files channels must be 1 or 3 temp_n_chans++; uint8 *imageData = new uint8[img_height * img_width_b * temp_n_chans]; if ( img_bytes_per_chan == 1 ) { for(sint64 i=0; iappendSlice(buffer,(unsigned char *)imageData,(int)img_height,(int)img_width,img_bytes_per_chan,temp_n_chans,-1,-1,-1,-1,slice); else if ( ((err_tiff_fmt = appendSlice2Tiff3DFile(fhandle,slice,(unsigned char *)imageData,(int)img_width,(int)img_height,temp_n_chans,img_depth,n_pages)) != 0) ) { char err_msg[STATIC_STRINGS_SIZE]; sprintf(err_msg,""VirtualVolume::saveImage_from_UINT8_to_Tiff3D: error in saving slice %d (%lld x %lld) in file %s (appendSlice2Tiff3DFile: %s)"", slice,img_width,img_height,buffer,err_tiff_fmt); throw IOException(err_msg); }; delete imageData; } /************************************************************************************************************* * Performs downsampling at a halved frequency on the given 3D image. The given image is overwritten in order * to store its halvesampled version without allocating any additional resources. **************************************************************************************************************/ void VirtualVolume::halveSample ( real32* img, int height, int width, int depth, int method ) { float A,B,C,D,E,F,G,H; // indices are sint64 because offsets can be larger that 2^31 - 1 if ( method == HALVE_BY_MEAN ) { for(sint64 z=0; z A ) A = B; B = img[2*z*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img[2*z*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; B = img[(2*z+1)*width*height + 2*i*width + 2*j]; if ( B > A ) A = B; B = img[(2*z+1)*width*height + 2*i*width + (2*j+1)]; if ( B > A ) A = B; B = img[(2*z+1)*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img[(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; //computing mean img[z*(width/2)*(height/2) + i*(width/2) + j] = A; } } } } else { char buffer[STATIC_STRINGS_SIZE]; sprintf(buffer,""in halveSample(...): invalid halving method\\n""); throw IOException(buffer); } } void VirtualVolume::halveSample_UINT8 ( uint8** img, int height, int width, int depth, int channels, int method, int bytes_chan ) { float A,B,C,D,E,F,G,H; // indices are sint64 because offsets can be larger that 2^31 - 1 if ( bytes_chan == 1 ) { if ( method == HALVE_BY_MEAN ) { for(sint64 c=0; c A ) A = B; B = img[c][2*z*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img[c][2*z*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; B = img[c][(2*z+1)*width*height + 2*i*width + 2*j]; if ( B > A ) A = B; B = img[c][(2*z+1)*width*height + 2*i*width + (2*j+1)]; if ( B > A ) A = B; B = img[c][(2*z+1)*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img[c][(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; //computing mean img[c][z*(width/2)*(height/2) + i*(width/2) + j] = (uint8) iim::round(A); } } } } } else { char buffer[STATIC_STRINGS_SIZE]; sprintf(buffer,""in VirtualVolume::halveSample_UINT8(...): invalid halving method\\n""); throw IOException(buffer); } } else if ( bytes_chan == 2 ) { uint16 **img16 = (uint16 **) img; if ( method == HALVE_BY_MEAN ) { for(sint64 c=0; c A ) A = B; B = img16[c][2*z*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img16[c][2*z*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; B = img16[c][(2*z+1)*width*height + 2*i*width + 2*j]; if ( B > A ) A = B; B = img16[c][(2*z+1)*width*height + 2*i*width + (2*j+1)]; if ( B > A ) A = B; B = img16[c][(2*z+1)*width*height + (2*i+1)*width + 2*j]; if ( B > A ) A = B; B = img16[c][(2*z+1)*width*height + (2*i+1)*width + (2*j+1)]; if ( B > A ) A = B; //computing mean img[c][z*(width/2)*(height/2) + i*(width/2) + j] = (uint8) iim::round(A); } } } } } else { char buffer[STATIC_STRINGS_SIZE]; sprintf(buffer,""in VirtualVolume::halveSample_UINT8(...): invalid halving method\\n""); throw IOException(buffer); } } else { char buffer[STATIC_STRINGS_SIZE]; sprintf(buffer,""VirtualVolume::in halveSample_UINT8(...): invalid number of bytes per channel (%d)\\n"", bytes_chan); throw IOException(buffer); } } // 2014-04-14. Alessandro. @ADDED 'instance_format' method with inputs = {path, format}. VirtualVolume* VirtualVolume::instance_format(const char* path, std::string format) throw (iim::IOException) { /**/iim::debug(iim::LEV3, strprintf(""path = \\""%s\\"", format = \\""%s\\"""", path, format.c_str()).c_str(), __iim__current__function__); VirtualVolume* volume = 0; // directory formats if(isDirectory(path)) { if((format.compare(TILED_MC_FORMAT) == 0) || (format.compare(TILED_MC_TIF3D_FORMAT) == 0)) volume = new TiledMCVolume(path); else if(format.compare(STACKED_FORMAT) == 0) volume = new StackedVolume(path); else if((format.compare(TILED_FORMAT) == 0) || (format.compare(TILED_TIF3D_FORMAT) == 0)) volume = new TiledVolume(path); else if(format.compare(SIMPLE_RAW_FORMAT) == 0) volume = new SimpleVolumeRaw(path); else if(format.compare(SIMPLE_FORMAT) == 0) volume = new SimpleVolume(path); else if(format.compare(TIME_SERIES) == 0) volume = new TimeSeries(path); else throw IOException(strprintf(""in VirtualVolume::instance(): Unsupported format \\""%s\\"" for path \\""%s\\"" which is a directory"", format.c_str(), path), __iim__current__function__); } // file formats else if(isFile(path)) { if(format.compare(RAW_FORMAT) == 0 || (format.compare(TIF3D_FORMAT) == 0)) volume = new RawVolume(path); else if(format.compare(UNST_TIF3D_FORMAT) == 0) volume = new UnstitchedVolume(path); else if(format.compare(BDV_HDF5_FORMAT) == 0) throw IOException(strprintf(""in VirtualVolume::instance(): volumes in format \\""%s\\"" should be created with another \\""instance\\"" method"", format.c_str(), path), __iim__current__function__); else throw IOException(strprintf(""in VirtualVolume::instance(): Unsupported format \\""%s\\"" for path \\""%s\\"" which is a file"", format.c_str(), path), __iim__current__function__); } else throw IOException(strprintf(""in VirtualVolume::instance(): path = \\""%s\\"" does not exist"", path), __iim__current__function__); return volume; } // tries to automatically detect the volume format and returns the imported volume if succeeds (otherwise returns 0) // WARNING: all metadata files (if needed by that format) are assumed to be present. Otherwise, that format will be skipped. VirtualVolume* VirtualVolume::instance(const char* path) throw (IOException) { /**/iim::debug(iim::LEV3, strprintf(""path = \\""%s\\"""", path).c_str(), __iim__current__function__); VirtualVolume* volume = 0; // directory formats if(isDirectory(path)) { // 2015-02-06. Alessandro. @ADDED volume format metadata file for faster opening of a ""directory format"" std::string format = ""unknown""; if(isFile(std::string(path) + ""/"" + iim::FORMAT_MDATA_FILE_NAME)) { try { std::ifstream f((std::string(path) + ""/"" + iim::FORMAT_MDATA_FILE_NAME).c_str()); if(f.is_open()) { std::getline(f,format); f.close(); // 2015-04-14. Alessandro. @FIXED detection of volume format from .iim.format file if(format.compare((TiledMCVolume().getPrintableFormat())) == 0) volume = new TiledMCVolume(path); else if(format.compare((StackedVolume().getPrintableFormat())) == 0) volume = new StackedVolume(path); else if(format.compare((TiledVolume().getPrintableFormat())) == 0) volume = new TiledVolume(path); else if(format.compare((SimpleVolume().getPrintableFormat())) == 0) volume = new SimpleVolume(path); else if(format.compare((SimpleVolumeRaw().getPrintableFormat())) == 0) volume = new SimpleVolumeRaw(path); else if(format.compare((TimeSeries().getPrintableFormat())) == 0) volume = new TimeSeries(path); else iim::warning(iim::strprintf(""Cannot recognize format \\""%s\\"""", format.c_str()).c_str(), __iim__current__function__); } } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import <%s> format at \\""%s\\"": %s"", format.c_str(), path, ex.what()).c_str(),__iim__current__function__); } } if(!volume) { try { volume = new TiledMCVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new StackedVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new TiledVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new SimpleVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new SimpleVolumeRaw(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new TimeSeries(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); } } } } } } catch(...) { debug(LEV3, strprintf(""generic error occurred when importing volume at \\""%s\\"""", path).c_str(),__iim__current__function__); } } // 2015-04-14. Alessandro. @FIXED detection of volume format from .iim.format file // 2015-02-06. Alessandro. @ADDED volume format metadata file for faster opening of a ""directory format"" if(volume && !isFile(std::string(path) + ""/"" + iim::FORMAT_MDATA_FILE_NAME)) { std::ofstream f((std::string(path) + ""/"" + iim::FORMAT_MDATA_FILE_NAME).c_str(), std::ofstream::out); if(f.is_open()) { f << volume->getPrintableFormat(); f.close(); } } } // try all file formats else if(isFile(path)) { try { volume = new RawVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); try { volume = new UnstitchedVolume(path); } catch(IOException &ex) { debug(LEV3, strprintf(""Cannot import at \\""%s\\"": %s"", path, ex.what()).c_str(),__iim__current__function__); // does not try BVDVolume because this volume should be created using the next ""instance"" method } } catch(...) { debug(LEV3, strprintf(""generic error occurred when importing volume at \\""%s\\"""", path).c_str(),__iim__current__function__); } } else throw IOException(strprintf(""Path = \\""%s\\"" does not exist"", path), __iim__current__function__); return volume; } // this version if ""instance"" methods should be used to create a BDVVolume since at least the 'res' parameter is needed VirtualVolume* VirtualVolume::instance(const char* fname, int res, void *descr) throw (iim::IOException) { /**/iim::debug(iim::LEV3, strprintf(""fname = \\""%s\\"", res = %d, descr = %p"", fname, res, descr).c_str(), __iim__current__function__); return new BDVVolume(fname,res,0,descr); // assumes there is only time point 0 } // returns the imported volume if succeeds (otherwise returns 0) // WARNING: no assumption is made on metadata files, which are possibly (re-)generated using the additional informations provided. VirtualVolume* VirtualVolume::instance(const char* path, std::string format, iim::axis AXS_1, iim::axis AXS_2, iim::axis AXS_3, /* = iim::axis_invalid */ float VXL_1 /* = 0 */, float VXL_2 /* = 0 */, float VXL_3 /* = 0 */) throw (iim::IOException) { /**/iim::debug(iim::LEV3, strprintf(""path = \\""%s\\"", format = %s, AXS_1 = %s, AXS_2 = %s, AXS_3 = %s, VXL_1 = %.2f, VXL_2 = %.2f, VXL_3 = %.2f"", path, format.c_str(), axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str(), __iim__current__function__); VirtualVolume* volume = 0; // directory formats if(isDirectory(path)) { if((format.compare(TILED_MC_FORMAT) == 0) || (format.compare(TILED_MC_TIF3D_FORMAT) == 0)) { if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) volume = new TiledMCVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); else throw IOException(strprintf(""Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)"", axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); } else if(format.compare(STACKED_FORMAT) == 0) { if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) volume = new StackedVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); else throw IOException(strprintf(""Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)"", axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); } else if((format.compare(TILED_FORMAT) == 0) || (format.compare(TILED_TIF3D_FORMAT) == 0)) { if(AXS_1 != axis_invalid && AXS_2 != axis_invalid && AXS_3 != axis_invalid && VXL_1 != 0 && VXL_2 != 0 && VXL_3 != 0) volume = new TiledVolume(path, ref_sys(AXS_1,AXS_2,AXS_3), VXL_1, VXL_2, VXL_3, true, true); else throw IOException(strprintf(""Invalid parameters AXS_1(%s), AXS_2(%s), AXS_3(%s), VXL_1(%.2f), VXL_2(%.2f), VXL_3(%.2f)"", axis_to_str(AXS_1), axis_to_str(AXS_2), axis_to_str(AXS_3), VXL_1, VXL_2, VXL_3).c_str()); } else if(format.compare(SIMPLE_RAW_FORMAT) == 0) volume = new SimpleVolumeRaw(path); else if(format.compare(SIMPLE_FORMAT) == 0) volume = new SimpleVolume(path); else throw IOException(strprintf(""in VirtualVolume::instance(): Unsupported format \\""%s\\"" for path \\""%s\\"" which is a directory"", format.c_str(), path), __iim__current__function__); } // file formats else if(isFile(path)) { if(format.compare(RAW_FORMAT) == 0 || (format.compare(TIF3D_FORMAT) == 0)) volume = new RawVolume(path); else if(format.compare(UNST_TIF3D_FORMAT) == 0) volume = new UnstitchedVolume(path); else if(format.compare(BDV_HDF5_FORMAT) == 0) throw IOException(strprintf(""in VirtualVolume::instance(): volumes in format \\""%s\\"" should be created with another \\""instance\\"" method"", format.c_str(), path), __iim__current__function__); else throw IOException(strprintf(""in VirtualVolume::instance(): Unsupported format \\""%s\\"" for path \\""%s\\"" which is a file"", format.c_str(), path), __iim__current__function__); } else throw IOException(strprintf(""in VirtualVolume::instance(): path = \\""%s\\"" does not exist"", path), __iim__current__function__); return volume; } // (@MOVED from TiledMCVolume.cpp by Alessandro on 2014-02-20) void VirtualVolume::setActiveChannels ( uint32 *_active, int _n_active ) { /**/iim::debug(iim::LEV3, 0, __iim__current__function__); if ( active ) delete[] active; active = _active; n_active = _n_active; } // returns true if the given format is hierarchical, i.e. if it consists of nested folders (1 level at least) bool VirtualVolume::isHierarchical(std::string format) throw (iim::IOException) { /**/iim::debug(iim::LEV3, strprintf(""format = %s"", format.c_str()).c_str(), __iim__current__function__); if(format.compare(TILED_FORMAT) == 0) return true; else if(format.compare(TILED_MC_FORMAT) == 0) return true; else if(format.compare(TILED_MC_TIF3D_FORMAT) == 0) return true; else if(format.compare(STACKED_FORMAT) == 0) return true; else if(format.compare(TIME_SERIES) == 0) return true; else if(format.compare(SIMPLE_FORMAT) == 0) return true; else if(format.compare(SIMPLE_RAW_FORMAT) == 0) return true; else if(format.compare(TILED_TIF3D_FORMAT) == 0) return true; else if(format.compare(RAW_FORMAT) == 0) return false; else if(format.compare(TIF3D_FORMAT) == 0) return false; else if(format.compare(UNST_TIF3D_FORMAT) == 0) return false; else if(format.compare(BDV_HDF5_FORMAT) == 0) return false; else throw IOException(strprintf(""Unsupported format %s"", format.c_str()), __iim__current__function__); } ",16297,True,2905.779847696698,median "#include ""surface_emu.h"" #include ""execute_buffer_emu.h"" #include ""structure_log.h"" #include #include ""../helpers/config.h"" namespace emu { namespace { /** * @name Key identifying transparent values for HW composition operation. */ //@{ // For Klingon Academy the black color is entirely sufficient. const unsigned short KA_COMPOSITION_KEY_MEMORY = 0x0000; const float * KA_COMPOSITION_KEY = NULL; // For Starfleet Academy the black is valid color for many areas (radar image) // and must be allowed. They also blends some images with the key color // so using some strange color will cause incorrect blend. For that reason // we use color which is one blue step from the pure black. While it might // be still present in valid parts of the image, it appears to be largely // unnoticeable. const unsigned short SFA_COMPOSITION_KEY_MEMORY = 0x0001; const float SFA_COMPOSITION_KEY[3] = {0.0f, 0.0f, 0.0322580636f}; //@} const float * get_composition_key(void) { return is_inside_sfad3d() ? SFA_COMPOSITION_KEY : KA_COMPOSITION_KEY; } unsigned short get_composition_key_memory(void) { return is_inside_sfad3d() ? SFA_COMPOSITION_KEY_MEMORY : KA_COMPOSITION_KEY_MEMORY; } /** * @brief Currently supported texture formats. */ const DDPIXELFORMAT texture_formats[SIZE_OF_HWFORMAT] = { {0}, { sizeof(DDPIXELFORMAT), // dwSize DDPF_RGB, // dwFlags 0, // dwFourCC 16, // dwRGBBitCount 0x0000F800, // dwRBitMask 0x000007E0, // dwGBitMask 0x0000001F, // dwBBitMask 0x00000000, // dwBBitMask }, { sizeof(DDPIXELFORMAT), // dwSize DDPF_RGB | DDPF_ALPHAPIXELS, // dwFlags 0, // dwFourCC 16, // dwRGBBitCount 0x00000F00, // dwRBitMask 0x000000F0, // dwGBitMask 0x0000000F, // dwBBitMask 0x0000F000, // dwBBitMask } }; /** * @brief Checks if specified memory block contains at least one nonzero byte. * * If the size is not multiple of four or if compare is disabled, function will behave * as if there is a nonzero byte. */ bool is_nonzero(const void * const memory, const size_t memory_size) { if (! is_composition_compare_enabled()) { return true; } if ((memory_size % 4) != 0) { return true; } const size_t step_count = memory_size / 4; size_t nonzero_found; __asm { mov edi, memory mov ecx, step_count xor eax, eax repe scasd mov nonzero_found, ecx } return (nonzero_found != 0); } /** * @brief Id of timer used to schedule presentations if the * application is not calling locking functions fast enough. */ const DWORD PRESENT_UPDATE_TIMER_ID = 1111; /** * @brief Called when timer message is delivered. */ VOID CALLBACK deliver_present_timer(HWND hwnd, UINT UNUSED_PARAMETER(message), UINT_PTR event_id, DWORD UNUSED_PARAMETER(time)) { if (event_id != PRESENT_UPDATE_TIMER_ID) { return; } // Prevent the timer from occuring until explicitly restarted. KillTimer(hwnd, event_id); // Advance the emulation. DirectDrawSurfaceEmu * const surface = reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA)); if (surface) { logKA(MSG_VERBOSE, 0, ""Present timer triggered""); surface->update_presentation_emulation(); } } /** * @brief Creates timer window. */ HWND create_timer_window(const HINSTANCE instance, DirectDrawSurfaceEmu &surface) { return CreateWindowA( ""D3DEMUTimerWindowClass"", ""D3DEMUTimerWindow"", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, instance, &surface ); } } // anonymous namespace. EmulationInfo::EmulationInfo(const HINSTANCE instance, DirectDrawSurfaceEmu &surface) : emulation_state(EMULATION_STATE_WAITING_FOR_TIME) , emulation_timeout_start(0) , timer_window(NULL) { if (! is_option_enabled(""D3DEMU_NO_TIMER"")) { timer_window = create_timer_window(instance, surface); if (timer_window == NULL) { logKA(emu::MSG_ERROR, 0, ""Unable to create helper window, present timer is not available""); } else { logKA(emu::MSG_INFORM, 0, ""Present timer is enabled - use D3DEMU_NO_TIMER to disable it""); } } else { logKA(emu::MSG_INFORM, 0, ""Present timer is disabled""); } } EmulationInfo::~EmulationInfo() { if (timer_window) { DestroyWindow(timer_window); } } /** * @brief Constructor. */ DirectDrawSurfaceEmu::RenderStateSet::RenderStateSet() : hash(0) , sequence_number(0) { memset(states, 0, sizeof(states)); } /** * @brief Sets value of specified state. * * Returns true if there was change. */ bool DirectDrawSurfaceEmu::RenderStateSet::set_rs_dw(const D3DRENDERSTATETYPE type, const DWORD new_value) { assert(type < (sizeof(states) / sizeof(states[0]))); // Set value if there was change. const DWORD old_value = states[type].value.dw_value; if (old_value == new_value) { return false; } states[type].value.dw_value = new_value; // Update the hash. hash -= static_cast(type) * old_value; hash += static_cast(type) * new_value; sequence_number++; return true; } /** * @brief Sets value of specified state to provided float. * * Returns true if there was change. */ bool DirectDrawSurfaceEmu::RenderStateSet::set_rs_float(const D3DRENDERSTATETYPE type, const float value) { RenderStateInfo info; info.value.float_value = value; return set_rs_dw(type, info.value.dw_value); } /** * @brief Returns value for specified dword typed render state. */ size_t DirectDrawSurfaceEmu::RenderStateSet::get_rs_dw(const D3DRENDERSTATETYPE type) const { assert(type < (sizeof(states) / sizeof(states[0]))); return states[type].value.dw_value; } /** * @brief Returns value for specified boolean typed render state. */ bool DirectDrawSurfaceEmu::RenderStateSet::get_rs_bool(const D3DRENDERSTATETYPE type) const { assert(type < (sizeof(states) / sizeof(states[0]))); return states[type].value.dw_value != 0; } /** * @brief Returns value for specified float typed render state. */ float DirectDrawSurfaceEmu::RenderStateSet::get_rs_float(const D3DRENDERSTATETYPE type) const { assert(type < (sizeof(states) / sizeof(states[0]))); return states[type].value.float_value; } /** * @brief Directly compares states without any optimizations. */ bool DirectDrawSurfaceEmu::RenderStateSet::compare_states(const RenderStateSet &other) const { return memcmp(states, other.states, sizeof(states)) == 0; } /** * @brief Determines if both sets represent the same state. */ bool DirectDrawSurfaceEmu::RenderStateSet::equals(const RenderStateSet &other) const { // Hash mismatch means difference. if (hash != other.hash) { assert(! compare_states(other)); return false; } // Compare the content. return compare_states(other); } /** * @brief Compares both sets. * * If they have the same sequence number, they are * considered the same so this method should be only used * to compare state with its older constant copy. */ bool DirectDrawSurfaceEmu::RenderStateSet::equals_with_sequence(const RenderStateSet &other) const { // Same sequence number means that the states are equivalent under // the assumption documented above. if (sequence_number == other.sequence_number) { assert(equals(other)); return true; } // Full scale check. return equals(other); } /** * @brief Applies the render states. */ void DirectDrawSurfaceEmu::RenderStateSet::apply_render_states(HWLayer &hw_layer) const { HWEVENT(hw_layer, L""apply_render_states""); // Set complex states. hw_layer.set_depth_test(get_depth_test_state()); hw_layer.set_alpha_test(get_alpha_test_state()); hw_layer.set_alpha_blend(get_alpha_blend_state()); hw_layer.set_fog(get_fog_state(), get_rs_dw(D3DRENDERSTATE_FOGCOLOR)); hw_layer.set_flat_blend((get_rs_dw(D3DRENDERSTATE_SHADEMODE) & 0x0F) == D3DSHADE_FLAT); hw_layer.set_texture_blend(get_texture_blend()); // Bind the texture. Will force upload to HW if necessary. DirectDrawSurfaceEmu * const texture = reinterpret_cast(get_rs_dw(D3DRENDERSTATE_TEXTUREHANDLE)); if (texture) { hw_layer.set_texture_surface(texture->get_hw_surface(false)); } else { hw_layer.set_texture_surface(INVALID_SURFACE_HANDLE); } // Report mismatch in hardcoded values. if (get_rs_dw(D3DRENDERSTATE_CULLMODE) != D3DCULL_NONE) { logKA(MSG_ERROR, 0, ""CULLMODE %u is not supported"", get_rs_dw(D3DRENDERSTATE_CULLMODE)); } if (get_rs_dw(D3DRENDERSTATE_FILLMODE) != D3DFILL_SOLID) { logKA(MSG_ERROR, 0, ""FILLMODE %u is not supported"", get_rs_dw(D3DRENDERSTATE_FILLMODE)); } if (get_rs_bool(D3DRENDERSTATE_LASTPIXEL)) { logKA(MSG_ERROR, 0, ""LASTPIXEL true is not supported""); } if (get_rs_bool(D3DRENDERSTATE_STIPPLEDALPHA)) { logKA(MSG_ERROR, 0, ""STIPPLEDALPHA true is not supported""); } if (get_rs_dw(D3DRENDERSTATE_TEXTUREMAG) != D3DFILTER_LINEAR) { logKA(MSG_ERROR, 0, ""TETUREMAG %u is not supported"", get_rs_dw(D3DRENDERSTATE_TEXTUREMAG)); } if (get_rs_dw(D3DRENDERSTATE_TEXTUREMIN) != D3DFILTER_LINEAR) { logKA(MSG_ERROR, 0, ""TEXTUREMIN %u is not supported"", get_rs_dw(D3DRENDERSTATE_TEXTUREMIN)); } // States which we do not care for. // // D3DRENDERSTATE_DITHERENABLE // D3DRENDERSTATE_TEXTUREPERSPECTIVE } /** * @name Getters for HW states from DX states. * * Return default value and logKA the problem if the DX state is not supported. */ //@{ DepthTest DirectDrawSurfaceEmu::RenderStateSet::get_depth_test_state(void) const { if (! get_rs_bool(D3DRENDERSTATE_ZENABLE)) { return DEPTH_TEST_NONE; } // The 'always' render state effectively disables test. If the // writes are disabled as well, the result is equivalent to the // full disable state (stencil buffer is not supported). if ((get_rs_dw(D3DRENDERSTATE_ZFUNC) == D3DCMP_ALWAYS) && (! get_rs_bool(D3DRENDERSTATE_ZWRITEENABLE))) { return DEPTH_TEST_NONE; } // For enabled state check that the function is right. if (get_rs_dw(D3DRENDERSTATE_ZFUNC) != D3DCMP_LESSEQUAL) { logKA(MSG_ERROR, 0, ""ZFUNC %u is not supported"", get_rs_dw(D3DRENDERSTATE_ZFUNC)); return DEPTH_TEST_NONE; } // Check for disabled z-buffer writes. if (! get_rs_bool(D3DRENDERSTATE_ZWRITEENABLE)) { return DEPTH_TEST_NOZWRITE; } return DEPTH_TEST_ON; } AlphaTest DirectDrawSurfaceEmu::RenderStateSet::get_alpha_test_state(void) const { if (! get_rs_bool(D3DRENDERSTATE_ALPHATESTENABLE)) { return ALPHA_TEST_NONE; } if (get_rs_dw(D3DRENDERSTATE_ALPHAREF) != 0) { logKA(MSG_ERROR, 0, ""ALPHAREF %u is not supported"", get_rs_dw(D3DRENDERSTATE_ALPHAREF)); return ALPHA_TEST_NONE; } if (get_rs_dw(D3DRENDERSTATE_ALPHAFUNC) == D3DCMP_NOTEQUAL) { return ALPHA_TEST_NOEQUAL; } logKA(MSG_ERROR, 0, ""ALPHAFUNC %u is not supported"", get_rs_dw(D3DRENDERSTATE_ALPHAFUNC)); return ALPHA_TEST_NONE; } Blend DirectDrawSurfaceEmu::RenderStateSet::get_alpha_blend_state(void) const { if (! get_rs_bool(D3DRENDERSTATE_BLENDENABLE)) { return BLEND_NONE; } const size_t src = get_rs_dw(D3DRENDERSTATE_SRCBLEND); const size_t dest = get_rs_dw(D3DRENDERSTATE_DESTBLEND); if ((src == D3DBLEND_ONE) && (dest == D3DBLEND_ZERO)) { return BLEND_NONE; } if ((src == D3DBLEND_SRCALPHA) && (dest == D3DBLEND_INVSRCALPHA)) { return BLEND_OVER; } if ((src == D3DBLEND_BOTHSRCALPHA)) { return BLEND_OVER; } logKA(MSG_ERROR, 0, ""Unsupported blend combination %u + %u"", src, dest); return BLEND_NONE; } Fog DirectDrawSurfaceEmu::RenderStateSet::get_fog_state(void) const { if (! get_rs_bool(D3DRENDERSTATE_FOGENABLE)) { return FOG_NONE; } // Fixed parameters. if (get_rs_float(D3DRENDERSTATE_FOGTABLEDENSITY) != 1.0f) { logKA(MSG_ERROR, 0, ""FOGTABLEDENSITY %f is not supported"", get_rs_float(D3DRENDERSTATE_FOGTABLEDENSITY)); return FOG_NONE; } if (get_rs_float(D3DRENDERSTATE_FOGTABLEEND) != 1.0f) { logKA(MSG_ERROR, 0, ""FOGTABLEEND %f is not supported"", get_rs_float(D3DRENDERSTATE_FOGTABLEEND)); return FOG_NONE; } if (get_rs_float(D3DRENDERSTATE_FOGTABLESTART) != 0.0f) { logKA(MSG_ERROR, 0, ""FOGTABLESTART %f is not supported"", get_rs_float(D3DRENDERSTATE_FOGTABLESTART)); return FOG_NONE; } // Table mode. const size_t table_mode = get_rs_dw(D3DRENDERSTATE_FOGTABLEMODE); if (table_mode == D3DFOG_NONE) { return FOG_VERTEX; } if (table_mode == D3DFOG_LINEAR) { return FOG_TABLE; } logKA(MSG_ERROR, 0, ""FOGTABLESTART %u is not supported"", get_rs_float(D3DRENDERSTATE_FOGTABLESTART)); return FOG_NONE; } TextureBlend DirectDrawSurfaceEmu::RenderStateSet::get_texture_blend(void) const { const size_t mode = get_rs_dw(D3DRENDERSTATE_TEXTUREMAPBLEND); if (mode == D3DTBLEND_MODULATE) { return TEXTURE_BLEND_MODULATE; } if (mode == D3DTBLEND_MODULATEALPHA) { return TEXTURE_BLEND_MODULATEALPHA; } logKA(MSG_ERROR, 0, ""TEXTUREMAPBLEND %u is not supported"", mode); return TEXTURE_BLEND_MODULATE; } //@} /** * @brief Constructor. */ DirectDrawSurfaceEmu::GeometryInfo::GeometryInfo() : geometry_mode(GEOMETRY_MODE_TRIANGLES) , indices() , min_vertex(~static_cast(0)) , max_vertex(0) , state_set() { } /** * @brief Clears old content of the object with the exception of the state set. */ void DirectDrawSurfaceEmu::GeometryInfo::reset(void) { geometry_mode = GEOMETRY_MODE_TRIANGLES; indices.clear(); min_vertex = ~static_cast(0); max_vertex = 0; } /** * @brief Determines if the geometry is empty. */ bool DirectDrawSurfaceEmu::GeometryInfo::is_empty(void) const { return (indices.size() == 0); } /** * @brief Returns geometry mode. */ DirectDrawSurfaceEmu::GeometryMode DirectDrawSurfaceEmu::GeometryInfo::get_mode(void) const { return geometry_mode; } /** * @brief Sets new geometry mode. * * The object must be empty. */ void DirectDrawSurfaceEmu::GeometryInfo::set_mode(const GeometryMode mode) { assert(is_empty()); geometry_mode = mode; } /** * @brief Sets state set to use for rendering of the future geometry. * * The object must be empty. */ void DirectDrawSurfaceEmu::GeometryInfo::set_state_set(const RenderStateSet &set) { assert(is_empty()); state_set = set; } /** * @brief Determines if specified set matches the set stored in the object. * * Function assumes that the set it got as parameter is some future copy * the set which was provided to the set_state_set(). */ bool DirectDrawSurfaceEmu::GeometryInfo::is_state_set_unchanged(const RenderStateSet &set) const { return state_set.equals_with_sequence(set); } /** * @brief Reads value from the D3DRENDERSTATE_SHADEMODE state. */ size_t DirectDrawSurfaceEmu::GeometryInfo::get_shade_mode_render_state(void) const { return state_set.get_rs_dw(D3DRENDERSTATE_SHADEMODE); } /** * @brief Adds triangle with specified indices to the array of vertices. * * The object must be in the triangle mode. */ void DirectDrawSurfaceEmu::GeometryInfo::add_triangle(const unsigned short v0, const unsigned short v1, const unsigned short v2) { assert(geometry_mode == GEOMETRY_MODE_TRIANGLES); // Store the indices. indices.push_back(v0); indices.push_back(v1); indices.push_back(v2); // Update limits. min_vertex = min(min_vertex, v0); min_vertex = min(min_vertex, v1); min_vertex = min(min_vertex, v2); max_vertex = max(max_vertex, v0); max_vertex = max(max_vertex, v1); max_vertex = max(max_vertex, v2); } /** * @brief Adds line with specified indices to the array of vertices. * * The object must be in the line mode. */ void DirectDrawSurfaceEmu::GeometryInfo::add_line(const unsigned short v0, const unsigned short v1) { assert(geometry_mode == GEOMETRY_MODE_LINES); // Store the indices. indices.push_back(v0); indices.push_back(v1); // Update limits. min_vertex = min(min_vertex, v0); min_vertex = min(min_vertex, v1); max_vertex = max(max_vertex, v0); max_vertex = max(max_vertex, v1); } /** * @brief Add points using vertices from specified range. * * The object must be in the point mode. */ void DirectDrawSurfaceEmu::GeometryInfo::add_points(const size_t first, const size_t count) { assert(geometry_mode == GEOMETRY_MODE_POINTS); if (count == 0) { return; } // Store the indices. assert(static_cast(first + count - 1) == (first + count - 1)); for (size_t i = 0; i < count; ++i) { indices.push_back(static_cast(first + i)); } // Update limits. min_vertex = min(min_vertex, first); max_vertex = max(max_vertex, (first + count - 1)); } /** * @brief Applies the stored state to the hw. */ void DirectDrawSurfaceEmu::GeometryInfo::apply_state(HWLayer &hw_layer) { state_set.apply_render_states(hw_layer); } /** * @brief Draws the stored geometry. * * Assumes that correct state is already set. */ void DirectDrawSurfaceEmu::GeometryInfo::draw_geometry(HWLayer &hw_layer, const TLVertex * const vertices) { if (is_empty()) { return; } // Draw corresponding type of the geometry. switch (geometry_mode) { case GEOMETRY_MODE_TRIANGLES: { assert((indices.size() % 3) == 0); hw_layer.draw_triangles( vertices, min_vertex, (max_vertex - min_vertex) + 1, &indices[0], indices.size() / 3 ); break; } case GEOMETRY_MODE_LINES: { assert((indices.size() % 2) == 0); hw_layer.draw_lines( vertices, min_vertex, (max_vertex - min_vertex) + 1, &indices[0], indices.size() / 2 ); break; } case GEOMETRY_MODE_POINTS: { hw_layer.draw_points( vertices, min_vertex, (max_vertex - min_vertex) + 1, &indices[0], indices.size() ); break; } } // Forget the geometry. reset(); } DirectDrawSurfaceEmu::DirectDrawSurfaceEmu(HWLayer &the_hw_layer, const HINSTANCE the_instance) : hw_layer(the_hw_layer) , instance(the_instance) , desc() , master_surface(NULL) , owned(false) , attached_surfaces() , viewports() , memory(NULL) , hw_surface(INVALID_SURFACE_HANDLE) , master(MASTER_NONE) , emulation(NULL) , scene_active(false) , lock_count(0) , active_lock_hack(LOCK_HACK_NONE) , vertices() { LOG_METHOD(); master_surface = this; memset(supported_states, 0, sizeof(supported_states)); set_default_render_states(); queued_geometry.set_state_set(active_render_states); queued_overlay_geometry.set_state_set(active_render_states); } DirectDrawSurfaceEmu::~DirectDrawSurfaceEmu() { LOG_METHOD(); assert(master_surface == this); HWEVENT(hw_layer, L""~DirectDrawSurfaceEmu""); if (hw_surface) { hw_layer.destroy_surface(hw_surface); } if (emulation) { kill_present_timer(); delete emulation; } if (memory) { free(memory); } while (viewports.size() > 0) { DeleteViewport(viewports.front()); } while (attached_surfaces.size() > 0) { detach_sub_surface(attached_surfaces.front()); } } /** * @brief Attempt to initialize surface. */ HRESULT DirectDrawSurfaceEmu::initialize(const DDSURFACEDESC &descriptor) { assert(memory == NULL); desc = descriptor; // Allocate the emulation structure if the type is right. if ((descriptor.ddsCaps.dwCaps & (DDSCAPS_COMPLEX | DDSCAPS_3DDEVICE | DDSCAPS_FRONTBUFFER)) == (DDSCAPS_COMPLEX | DDSCAPS_3DDEVICE | DDSCAPS_FRONTBUFFER)) { emulation = new EmulationInfo(instance, *this); } // Fill calculated values. desc.dwFlags |= DDSD_PITCH; if (get_hw_format() == HWFORMAT_ZBUFFER) { desc.lPitch = desc.dwWidth * 4; } else { desc.lPitch = desc.dwWidth * desc.ddpfPixelFormat.dwRGBBitCount / 8; } // Allocate system memory backing the surface. const size_t memory_size = desc.dwHeight * desc.lPitch; memory = malloc(memory_size); memset(memory, 0, memory_size); return DD_OK; } /** * @brief Attach owned surface to a complex surface. */ void DirectDrawSurfaceEmu::attach_sub_surface(DirectDrawSurfaceEmu * const surface, const bool as_owned) { assert(desc.dwFlags & DDSD_CAPS); assert(desc.ddsCaps.dwCaps & DDSCAPS_COMPLEX); assert(surface); assert(surface->master_surface == surface); assert(! surface->owned); // TODO: Proper update of flags. The KA does not depend on exact emulation so not emulated. // Queue the surface. surface->master_surface = this; surface->owned = as_owned; surface->AddRef(); attached_surfaces.push_back(surface); } /** * @brief Detaches specified subsurface. * * If the subsurface is owned, it will be destroyed. */ void DirectDrawSurfaceEmu::detach_sub_surface(DirectDrawSurfaceEmu * const surface) { assert(surface); assert(surface->master_surface == this); // TODO: Proper update of flags. The KA does not depend on exact emulation so not emulated. // Remove the surface from the list. std::list::iterator it; for (it = attached_surfaces.begin(); it != attached_surfaces.end(); ++it) { if (*it == surface) { attached_surfaces.erase(it); surface->master_surface = surface; // For non-owned surfaces release reference count. if (! surface->owned) { surface->Release(); } else { // Owned surfaces are destroyed with us regardless of // number of references (DirectDraw<7 behavior). surface->owned = false; delete surface; } return; } } } /** * @brief Finds emulation info for this device. */ EmulationInfo *DirectDrawSurfaceEmu::find_emulation_info(void) { if (master_surface == this) { return emulation; } else { return master_surface->find_emulation_info(); } } /** * @brief Returns reference to the emulation info for situations where it is known * that the info must exist. */ EmulationInfo &DirectDrawSurfaceEmu::get_emulation_info(void) { EmulationInfo * const info = find_emulation_info(); assert(info); return *info; } /** * @brief Finds first surface with specified caps set. * * @param allow_up Allows traversal to master surfaces during lookup. */ DirectDrawSurfaceEmu * DirectDrawSurfaceEmu::find_surface(const size_t caps, const bool allow_up) { // Are we the proper surface? if ((desc.ddsCaps.dwCaps & caps) == caps) { return this; } // Traverse to the root of the hierarchy. if (allow_up && (master_surface != this)) { return master_surface->find_surface(caps, true); } // Try the attached surfaces. This time do not allow upwards move. std::list::iterator it; for (it = attached_surfaces.begin(); it != attached_surfaces.end(); ++it) { DirectDrawSurfaceEmu * const found = (*it)->find_surface(caps, false); if (found) { return found; } } return NULL; } /** * @brief Finds surface, if any, serving as front buffer. */ DirectDrawSurfaceEmu * DirectDrawSurfaceEmu::find_front_buffer(void) { return find_surface(DDSCAPS_FRONTBUFFER); } /** * @brief Finds surface, if any, serving as backbuffer. */ DirectDrawSurfaceEmu * DirectDrawSurfaceEmu::find_back_buffer(void) { return find_surface(DDSCAPS_BACKBUFFER); } /** * @brief Finds surface, if any, serving as depth buffer. */ DirectDrawSurfaceEmu * DirectDrawSurfaceEmu::find_depth_buffer(void) { return find_surface(DDSCAPS_ZBUFFER); } /** * @brief Sets presentation timer to trigger after specified timeout. * * Does nothing if timer window is not available. The timer is triggered * only once per call to this function. */ void DirectDrawSurfaceEmu::set_present_timer(const size_t timeout) { if (emulation && emulation->timer_window) { logKA(MSG_VERBOSE, 0, ""Starting present timer for timeout %u"", timeout); SetTimer(emulation->timer_window, PRESENT_UPDATE_TIMER_ID, timeout, deliver_present_timer); } } /** * @brief Kills presentation timer if it is active. */ void DirectDrawSurfaceEmu::kill_present_timer(void) { if (emulation && emulation->timer_window) { logKA(MSG_VERBOSE, 0, ""Killing present timer""); KillTimer(emulation->timer_window, PRESENT_UPDATE_TIMER_ID); } } /** * @brief Monitors timeouts of emulation events. */ void DirectDrawSurfaceEmu::update_presentation_emulation(void) { // Nothing to do for non-primary surfaces. if ((desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) == 0) { return; } // Ignore sufraces which are still locked. We will be called again // at unlock time. if (lock_count > 0) { return; } // If the info is not present, we are used from the kamovies.exe so // show the surface. EmulationInfo * const info = find_emulation_info(); if (info == NULL) { show_primary(); return; } // Some states do not have timeout. if ( (info->emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE) || (info->emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE_POINT_GEOMETRY_DRAWN) || (info->emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE_TRIANGLE_GEOMETRY_DRAWN) || (info->emulation_state == EmulationInfo::EMULATION_STATE_3D_FLIP) ) { return; } // Select proper timeout. const size_t timeout_2d_mode = is_30fps_ui_enabled() ? 30 : 60; const size_t timeout = (info->emulation_state == EmulationInfo::EMULATION_STATE_WAITING_FOR_3D_SCENE) ? 300: timeout_2d_mode ; // Did it expire? const DWORD time = timeGetTime(); const DWORD time_since_start = time - info->emulation_timeout_start; if (time_since_start < timeout) { set_present_timer(timeout - time_since_start); return; } // Update the mode and show the surface. info->emulation_timeout_start = time; info->emulation_state = EmulationInfo::EMULATION_STATE_WAITING_FOR_TIME; show_primary(); // Restart the presentation timeout. set_present_timer(timeout_2d_mode); } /** * @brief Shows the surface if it is primary one. */ void DirectDrawSurfaceEmu::show_primary() { // Nothing to do for non-primary surfaces. if ((desc.ddsCaps.dwCaps & DDSCAPS_PRIMARYSURFACE) == 0) { return; } HWEVENT(hw_layer, L""show_primary""); // For primary, draw it to the screen. synchronize_hw(); assert(hw_surface); hw_layer.display_surface(hw_surface); } /** * @brief Ensures that the memory buffer contains the latest data. */ void DirectDrawSurfaceEmu::synchronize_memory(void) { assert(memory); if ((master == MASTER_NONE) || (master == MASTER_MEMORY) || (master == MASTER_SYNCHRONIZED)) { return; } HWEVENT(hw_layer, L""synchronize_memory""); assert(hw_surface != INVALID_SURFACE_HANDLE); // If there is still a composition pending, we have to do it now. // This should not happen normally. The non-zero composition key // is used for Starfleet Academy which needs black parts of the image. // As the game runs in 640x480 resolution, the check is not implemented // and the worst possible situation is assumed. if (master == MASTER_COMPOSITION) { if ((get_composition_key_memory() != 0) || is_nonzero(memory, desc.dwHeight * desc.lPitch)) { hw_layer.compose_render_target(hw_surface, memory, get_composition_key()); } } else if (master == MASTER_COMPOSITION_NONKEY) { hw_layer.compose_render_target(hw_surface, memory, get_composition_key()); } // Read the result. hw_layer.read_surface(hw_surface, memory); master = MASTER_SYNCHRONIZED; } /** * @brief Ensures that the HW surface contains the latest data. * * Creates the HW surface if it does not exist yet. */ void DirectDrawSurfaceEmu::synchronize_hw(void) { assert(memory); if ((master == MASTER_HW) || (master == MASTER_SYNCHRONIZED)) { return; } HWEVENT(hw_layer, L""synchronize_hw""); // Create the surface if necessary. If the memory copy is // in fresh state, do not upload it yet as it is likely that // it will be filled soon. if (hw_surface == INVALID_SURFACE_HANDLE) { assert((master != MASTER_COMPOSITION) && (master != MASTER_COMPOSITION_NONKEY)); void * const init_memory = (master == MASTER_NONE) ? NULL : memory; const bool render_target = (desc.ddsCaps.dwCaps & DDSCAPS_3DDEVICE) != 0; hw_surface = hw_layer.create_surface(desc.dwWidth, desc.dwHeight, get_hw_format(), init_memory, render_target); assert(hw_surface != INVALID_SURFACE_HANDLE); master = MASTER_SYNCHRONIZED; } else { if (master == MASTER_COMPOSITION) { if ((get_composition_key_memory() != 0) || is_nonzero(memory, desc.dwHeight * desc.lPitch)) { hw_layer.compose_render_target(hw_surface, memory, get_composition_key()); } master = MASTER_HW; } else if (master == MASTER_COMPOSITION_NONKEY) { hw_layer.compose_render_target(hw_surface, memory, get_composition_key()); master = MASTER_HW; } else { hw_layer.update_surface(hw_surface, memory); master = MASTER_SYNCHRONIZED; } } } /** * @brief Returns handle of the hardware surface ensuring that it is properly updated. * * If the for_rendering_into is true, the surface will be changed by the HW in the * future (the handle is used to bind it as framebuffer). Its master is changed * to reflect that the HW copy is now the master. */ HWSurfaceHandle DirectDrawSurfaceEmu::get_hw_surface(const bool for_rendering_into) { synchronize_hw(); if (hw_surface && for_rendering_into) { master = MASTER_HW; } return hw_surface; } /** * @brief Returns HW format corresponding to this surface. */ HWFormat DirectDrawSurfaceEmu::get_hw_format(void) const { if (desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER) { return HWFORMAT_ZBUFFER; } for (size_t i = HWFORMAT_R5G6B5 ; i <= HWFORMAT_R4G4B4A4 ; ++i) { if (memcmp(texture_formats + i, &desc.ddpfPixelFormat, sizeof(DDPIXELFORMAT)) == 0) { return static_cast(i); } } return HWFORMAT_NONE; } /** * @brief Sets default values for all render states. */ void DirectDrawSurfaceEmu::set_default_render_states(void) { active_render_states = RenderStateSet(); // Set values which are not 0 in the default situation. active_render_states.set_rs_dw(D3DRENDERSTATE_TEXTUREADDRESS, D3DTADDRESS_WRAP); active_render_states.set_rs_dw(D3DRENDERSTATE_SHADEMODE, D3DFILL_SOLID); active_render_states.set_rs_dw(D3DRENDERSTATE_FILLMODE, D3DSHADE_GOURAUD); active_render_states.set_rs_dw(D3DRENDERSTATE_PLANEMASK, ~static_cast(0)); active_render_states.set_rs_dw(D3DRENDERSTATE_ZWRITEENABLE, 1); active_render_states.set_rs_dw(D3DRENDERSTATE_LASTPIXEL, 1); active_render_states.set_rs_dw(D3DRENDERSTATE_TEXTUREMAG, D3DFILTER_NEAREST); active_render_states.set_rs_dw(D3DRENDERSTATE_TEXTUREMIN, D3DFILTER_NEAREST); active_render_states.set_rs_dw(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); active_render_states.set_rs_dw(D3DRENDERSTATE_DESTBLEND, D3DBLEND_ZERO); active_render_states.set_rs_dw(D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATE); active_render_states.set_rs_dw(D3DRENDERSTATE_CULLMODE, D3DCULL_CCW); active_render_states.set_rs_dw(D3DRENDERSTATE_ZFUNC, D3DCMP_LESSEQUAL); active_render_states.set_rs_dw(D3DRENDERSTATE_ALPHAFUNC, D3DCMP_ALWAYS); active_render_states.set_rs_dw(D3DRENDERSTATE_SPECULARENABLE, 1); active_render_states.set_rs_dw(D3DRENDERSTATE_FOGTABLEMODE, D3DFOG_NONE); // Not documented. active_render_states.set_rs_float(D3DRENDERSTATE_FOGTABLESTART, 0.0f); active_render_states.set_rs_float(D3DRENDERSTATE_FOGTABLEEND, 1.0f); active_render_states.set_rs_float(D3DRENDERSTATE_FOGTABLEDENSITY, 1.0f); // Mark states we support. memset(supported_states, 0, sizeof(supported_states)); supported_states[D3DRENDERSTATE_ALPHAFUNC] = true; supported_states[D3DRENDERSTATE_ALPHAREF] = true; supported_states[D3DRENDERSTATE_ALPHATESTENABLE] = true; supported_states[D3DRENDERSTATE_BLENDENABLE] = true; supported_states[D3DRENDERSTATE_CULLMODE] = true; supported_states[D3DRENDERSTATE_DESTBLEND] = true; supported_states[D3DRENDERSTATE_DITHERENABLE] = true; supported_states[D3DRENDERSTATE_FILLMODE] = true; supported_states[D3DRENDERSTATE_FOGCOLOR] = true; supported_states[D3DRENDERSTATE_FOGENABLE] = true; supported_states[D3DRENDERSTATE_FOGTABLEDENSITY] = true; supported_states[D3DRENDERSTATE_FOGTABLEEND] = true; supported_states[D3DRENDERSTATE_FOGTABLEMODE] = true; supported_states[D3DRENDERSTATE_FOGTABLESTART] = true; supported_states[D3DRENDERSTATE_LASTPIXEL] = true; supported_states[D3DRENDERSTATE_SHADEMODE] = true; supported_states[D3DRENDERSTATE_SRCBLEND] = true; supported_states[D3DRENDERSTATE_STIPPLEDALPHA] = true; supported_states[D3DRENDERSTATE_TEXTUREHANDLE] = true; supported_states[D3DRENDERSTATE_TEXTUREMAG] = true; supported_states[D3DRENDERSTATE_TEXTUREMAPBLEND] = true; supported_states[D3DRENDERSTATE_TEXTUREMIN] = true; supported_states[D3DRENDERSTATE_TEXTUREPERSPECTIVE] = true; supported_states[D3DRENDERSTATE_ZENABLE] = true; supported_states[D3DRENDERSTATE_ZFUNC] = true; supported_states[D3DRENDERSTATE_ZWRITEENABLE] = true; } /** * @brief Sets specified render state. */ void DirectDrawSurfaceEmu::set_render_state(const D3DSTATE &state) { // Check that the index is within the valid range. const D3DRENDERSTATETYPE type = state.drstRenderStateType; if (type >= RenderStateSet::RENDER_STATE_COUNT) { logKA(MSG_ERROR, 0, ""Setting unknown or unsupported render state %u"", type); return; } // Report changes of unsupported render states. Supported states are checked // for correct values during upload. if (! supported_states[type]) { logKA(MSG_ERROR, 0, ""Setting unsupported render state %u"", type); } // Apply the new value to the live copy. active_render_states.set_rs_dw(type, state.dwArg[0]); } /** * @brief Starts drawing of geometry with specified number of vertices. */ void DirectDrawSurfaceEmu::begin_geometry(const size_t count) { assert(find_back_buffer() == this); queued_geometry.reset(); queued_overlay_geometry.reset(); vertices.resize(count); } /** * @brief Set specified range of vertices using specified source vertices. */ bool DirectDrawSurfaceEmu::set_vertices(const size_t start, const D3DTLVERTEX * const new_vertices, const size_t count) { if (count == 0) { return true; } HWEVENT(hw_layer, L""set_vertices""); // Check that the parameters make sense. if ((start + count) > vertices.size()) { logKA(MSG_ERROR, 0, ""Attempting to set %u vertices from %u when only %u vertices should be present."", count, start, vertices.size()); return false; } assert(sizeof(TLVertex) == sizeof(D3DTLVERTEX)); const TLVertex * const input = reinterpret_cast(new_vertices); // Copy the content. for (size_t i = 0; i < count; ++i) { vertices[start + i] = input[i]; } // HACK: KA sets all vertices in single operation so we can upload // them directly to the HW for triangle drawing. We need to keep in // memory copy for point drawing. assert(count == vertices.size()); hw_layer.set_triangle_vertices(&vertices[0], count); return true; } /** * @brief Adds triangle with specified indices to the array of vertices. */ void DirectDrawSurfaceEmu::add_triangle(const unsigned short v0, const unsigned short v1, const unsigned short v2) { // If the overlay mode is active without correct underlying geometry, deactivate it. if (active_render_states.get_rs_dw(D3DRENDERSTATE_SHADEMODE) == GLOW_HACK_SHADING_MODE_OVERLAY) { if (queued_geometry.is_empty() || (queued_geometry.get_shade_mode_render_state() != GLOW_HACK_SHADING_MODE_BASE)) { logKA(MSG_ULTRA_VERBOSE, 0, ""Switching from overlay mode because no underlying geometry is present""); active_render_states.set_rs_dw(D3DRENDERSTATE_SHADEMODE, D3DSHADE_FLAT); } } // Select geometry object to use. This prevents the overlay triangle // from triggering flush of the base triangle queued before it. GeometryInfo &target_geometry = active_render_states.get_rs_dw(D3DRENDERSTATE_SHADEMODE) == GLOW_HACK_SHADING_MODE_OVERLAY ? queued_overlay_geometry : queued_geometry ; // Flush the geometry buffers if the mode does not match. if (target_geometry.get_mode() != GEOMETRY_MODE_TRIANGLES) { flush_geometry(); } // Or if the state configuration changed since last time. if (! target_geometry.is_empty()) { if (! target_geometry.is_state_set_unchanged(active_render_states)) { flush_geometry(); } } // If we are starting new batch of the geometry, set the mode and state // which will be used for the final drawing. if (target_geometry.is_empty()) { target_geometry.set_mode(GEOMETRY_MODE_TRIANGLES); target_geometry.set_state_set(active_render_states); } // Queue the triangle. target_geometry.add_triangle(v0, v1, v2); } /** * @brief Adds line using vertices from specified range. */ void DirectDrawSurfaceEmu::add_line(const size_t first, const size_t second) { // The points are never part of the base or overlay geometry // so they will force flush of any pending overlay geometry. if (! queued_overlay_geometry.is_empty()) { flush_geometry(); } // Flush the geometry buffers if the mode does not match. if (queued_geometry.get_mode() != GEOMETRY_MODE_LINES) { flush_geometry(); } // Or if the state configuration changed since last time. if (! queued_geometry.is_empty()) { if (! queued_geometry.is_state_set_unchanged(active_render_states)) { flush_geometry(); } } // If we are starting new batch of the geometry, set the mode and state // which will be used for the final drawing. if (queued_geometry.is_empty()) { queued_geometry.set_mode(GEOMETRY_MODE_LINES); queued_geometry.set_state_set(active_render_states); } // Queue the line. assert(static_cast(first) == first); assert(static_cast(second) == second); queued_geometry.add_line(static_cast(first), static_cast(second)); } /** * @brief Add points using vertices from specified range. */ void DirectDrawSurfaceEmu::add_points(const size_t first, const size_t count) { if (count == 0) { return; } // The points are never part of the base or overlay geometry // so they will force flush of any pending overlay geometry. if (! queued_overlay_geometry.is_empty()) { flush_geometry(); } // Flush the geometry buffers if the mode does not match. if (queued_geometry.get_mode() != GEOMETRY_MODE_POINTS) { flush_geometry(); } // Or if the state configuration changed since last time. if (! queued_geometry.is_empty()) { if (! queued_geometry.is_state_set_unchanged(active_render_states)) { flush_geometry(); } } // If we are starting new batch of the geometry, set the mode and state // which will be used for the final drawing. if (queued_geometry.is_empty()) { queued_geometry.set_mode(GEOMETRY_MODE_POINTS); queued_geometry.set_state_set(active_render_states); } // Queue the points. queued_geometry.add_points(first, count); } /** * @brief Draws pending triangles/points. */ void DirectDrawSurfaceEmu::flush_geometry(void) { assert(find_back_buffer() == this); // Nothing to draw if there is no geometry. Note that overlay geometry // is queued only when there is the base geometry. if (queued_geometry.is_empty()) { assert(queued_overlay_geometry.is_empty()); return; } HWEVENT(hw_layer, L""flush_geometry""); // Upload the back buffer to the HW if it was changed since last time. // The GPU copy will now become master. EmulationInfo &info = get_emulation_info(); synchronize_hw(); master = MASTER_HW; // Realize the rendering state for the base geometry. queued_geometry.apply_state(hw_layer); // Emulation specific hacks. Note that the KA enhancements will cause // the first geometry drawn by SFA to be drawn incorrectly so they // need to be disabled for it. if ((queued_geometry.get_mode() == GEOMETRY_MODE_TRIANGLES) && (! is_inside_sfad3d())) { // Apply the skybox override. Draw it in additive mode. if ((info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE) || (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE_POINT_GEOMETRY_DRAWN)) { hw_layer.set_alpha_blend(BLEND_ADD); info.emulation_state = EmulationInfo::EMULATION_STATE_3D_SCENE_TRIANGLE_GEOMETRY_DRAWN; } } else { // Advance the emulation state. if (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE) { info.emulation_state = EmulationInfo::EMULATION_STATE_3D_SCENE_POINT_GEOMETRY_DRAWN; } } // Draw it. queued_geometry.draw_geometry(hw_layer, &vertices[0]); assert(queued_geometry.is_empty()); // Draw the overlay geometry if any. if (queued_overlay_geometry.is_empty()) { return; } queued_overlay_geometry.apply_state(hw_layer); queued_overlay_geometry.draw_geometry(hw_layer, &vertices[0]); assert(queued_overlay_geometry.is_empty()); } /** * @brief Completes the geometry. * * Flushes any pending draws. */ void DirectDrawSurfaceEmu::end_geometry(void) { assert(find_back_buffer() == this); flush_geometry(); vertices.clear(); } /** * @brief Attaches specified surface to end of chain for this surface. */ STDMETHODIMP DirectDrawSurfaceEmu::AddAttachedSurface(LPDIRECTDRAWSURFACE surface) { LOG_METHOD(); CHECK_NOT_NULL(surface); DirectDrawSurfaceEmu * const full_type = static_cast(surface); if (full_type->master_surface != full_type) { return DDERR_SURFACEALREADYATTACHED; } attach_sub_surface(full_type, false); return DD_OK; } /** * @brief BltFast. */ STDMETHODIMP DirectDrawSurfaceEmu::BltFast(DWORD x,DWORD y,LPDIRECTDRAWSURFACE source, LPRECT rect,DWORD trans) { LOG_METHOD(); HWEVENT(hw_layer, L""BltFast""); CHECK_NOT_NULL(source); logKA(MSG_VERBOSE, 1, ""x: %d"", x); logKA(MSG_VERBOSE, 1, ""y: %d"", y); logKA(MSG_VERBOSE, 1, ""source: %p"", source); if (rect) { logKA(MSG_VERBOSE, 1, ""%dx%d->%dx%d"", rect->left, rect->top, rect->right, rect->bottom); } switch (trans & 3) { case DDBLTFAST_DESTCOLORKEY : logKA(MSG_VERBOSE, 1, ""DESTCOLORKEY""); break; case DDBLTFAST_SRCCOLORKEY : logKA(MSG_VERBOSE, 1, ""SRCCOLORKEY""); break; case DDBLTFAST_NOCOLORKEY : logKA(MSG_VERBOSE, 1, ""NOCOLORKEY""); break; } if (trans & DDBLTFAST_WAIT) { logKA(MSG_VERBOSE, 1, ""WAIT""); } // This function is not important for KA however necessary for SFA. Emulate // only required features. if (! is_inside_sfad3d()) { return DD_OK; } // Check for supported parameters. if ((trans & 3) != DDBLTFAST_NOCOLORKEY) { logKA(MSG_ERROR, 0, ""Color key is not supported""); return DDERR_UNSUPPORTED; } if (rect == NULL) { logKA(MSG_ERROR, 0, ""BltFast no rectangle provided""); return DDERR_INVALIDRECT; } if ( (rect->left < 0) || (rect->top < 0) || (rect->left >= rect->right) || (rect->top >= rect->bottom) || (rect->right > static_cast(desc.dwWidth)) || (rect->bottom > static_cast(desc.dwHeight)) ) { logKA(MSG_ERROR, 0, ""Incorrect or unsupported BltFast rectangle""); return DDERR_INVALIDRECT; } DirectDrawSurfaceEmu * const src_surface = static_cast(source); if (src_surface == this) { logKA(MSG_ERROR, 0, ""Blit inside one surface is not supported""); return DDERR_UNSUPPORTED; } // Ensure that the content is in the video memory. This allows us to do full // 24 bit blit. synchronize_hw(); src_surface->synchronize_hw(); // Execute the blit. hw_layer.bitblt( get_hw_surface(true), src_surface->get_hw_surface(false), x, y, rect->left, rect->top, rect->right - rect->left, rect->bottom - rect->top ); return DD_OK; } /** * @brief Flips front and back buffer. */ STDMETHODIMP DirectDrawSurfaceEmu::Flip(LPDIRECTDRAWSURFACE surface_override, DWORD UNUSED_PARAMETER(flags)) { LOG_METHOD(); if (surface_override) { logKA(MSG_ERROR, 0, ""Flip: surface_override is not supported""); return DDERR_UNSUPPORTED; } // Unable to do anything if we do not have both surfaces. DirectDrawSurfaceEmu * const front = find_front_buffer(); DirectDrawSurfaceEmu * const back = find_back_buffer(); if ((front == NULL) || (back == NULL)) { logKA(MSG_ERROR, 0, ""Flip: Called on non-flippable surface.""); return DDERR_NOTFLIPPABLE; } // Flip memory content of both surfaces. void * const tmp_memory = front->memory; front->memory = back->memory; back->memory = tmp_memory; const HWSurfaceHandle tmp_hw_surface = front->hw_surface; front->hw_surface = back->hw_surface; back->hw_surface = tmp_hw_surface; const Master tmp_master = front->master; front->master = back->master; back->master = tmp_master; // Ensure that the primary surface is updated if it is the // front buffer. front->show_primary(); // Start wait for next BeginScene if running in the game. EmulationInfo * const info = find_emulation_info(); if (info) { info->emulation_state = EmulationInfo::EMULATION_STATE_WAITING_FOR_3D_SCENE; info->emulation_timeout_start = timeGetTime(); } return DD_OK; } /** * @brief Returns next attached surface with specified parameters. */ STDMETHODIMP DirectDrawSurfaceEmu::GetAttachedSurface(LPDDSCAPS caps, LPDIRECTDRAWSURFACE FAR * surface) { LOG_METHOD(); CHECK_NOT_NULL(caps); CHECK_NOT_NULL(surface); // logKA the request. log_structure(MSG_VERBOSE, 1, *caps); // Try to find next entry in the chain with specified attributes. DirectDrawSurfaceEmu * const found = find_surface(caps->dwCaps); if (found == NULL) { *surface = NULL; return DDERR_NOTFOUND; } // We found something only if we found anything else than self. if (found == this) { *surface = NULL; return DDERR_NOTFOUND; } found->AddRef(); *surface = found; return DD_OK; } /** * @brief Returns pixel format of the surface. */ STDMETHODIMP DirectDrawSurfaceEmu::GetPixelFormat(LPDDPIXELFORMAT format) { LOG_METHOD(); CHECK_STRUCTURE(format, DDPIXELFORMAT); *format = desc.ddpfPixelFormat; return DD_OK; } /** * @brief Returns descriptor of this surface. */ STDMETHODIMP DirectDrawSurfaceEmu::GetSurfaceDesc(LPDDSURFACEDESC desc) { LOG_METHOD(); CHECK_STRUCTURE(desc, DDSURFACEDESC); *desc = this->desc; return DD_OK; } /** * @brief Lock specified part of the surface. */ STDMETHODIMP DirectDrawSurfaceEmu::Lock(LPRECT rect, LPDDSURFACEDESC desc, DWORD flags, HANDLE handle) { LOG_METHOD(); CHECK_STRUCTURE(desc, DDSURFACEDESC); HWEVENT(hw_layer, L""Lock""); // TODO: Check that we are not locked recursively with different parameters. KA does not do that // so not emulated. // We need to detect if we are called from cloaking field read or for something else. // All KA locking in 3d rendering shares single code path without use of read only flags // so we need to detect that in different way. Find the return address. DWORD caller; __asm { mov eax, [ebp + 4] mov caller, eax } // If that is one known value, look-up next return address in the chain. // The game is compiled with the ""Omit frame pointers"" optimizations so we need // to access fixed offset for this specific caller. if (caller == 0x410113){ DWORD caller2; __asm { mov eax, [ebp + 160] mov caller2, eax } // If it is lock for purpose of cloaking field creation, set the read only // flag. This will prevent the composition hack from activating and also prevent // texture upload on the unlock. if (caller2 == 0x00472d11) { flags |= DDLOCK_READONLY; logKA(MSG_VERBOSE, 1, ""Cloaking field read""); hw_layer.marker(L""Cloaking field read""); } // The same for screenshots. else if (caller2 == 0x004DA47C) { flags |= DDLOCK_READONLY; logKA(MSG_VERBOSE, 1, ""Screenshot read""); hw_layer.marker(L""Screenshot read""); } } // logKA info. if (rect) { logKA(MSG_VERBOSE, 1, ""Lock %dx%d-%dx%d %u %x %08x"", rect->left, rect->top, rect->right, rect->bottom, flags, handle, caller); } else { logKA(MSG_VERBOSE, 1, ""Lock %u %x %08x"", flags, handle, caller); } // Update the lock counter. lock_count++; // Store informations about the surface. desc->dwFlags = DDSD_WIDTH | DDSD_HEIGHT | DDSD_PITCH | DDSD_PIXELFORMAT | DDSD_LPSURFACE; desc->dwWidth = this->desc.dwWidth; desc->dwHeight = this->desc.dwHeight; desc->lPitch = this->desc.lPitch; desc->ddpfPixelFormat = this->desc.ddpfPixelFormat; // Calculate location of the memory. const size_t x_offset = rect ? (rect->left * this->desc.ddpfPixelFormat.dwRGBBitCount / 8) : 0; const size_t y_offset = rect ? (rect->top * this->desc.lPitch) : 0; desc->lpSurface = (rect == NULL) ? memory : (static_cast(memory) + x_offset + y_offset); // For backbuffer ensure that any queued geometry is present on the screen. if (this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER) { flush_geometry(); } if (! is_inside_sfad3d()) { // Hacks for KA. if ((this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER) && (rect == NULL) && (master != MASTER_MEMORY) && (flags == 2049)) { EmulationInfo &info = get_emulation_info(); logKA(MSG_VERBOSE, 1, ""Emulation state %u"", info.emulation_state); // Quality improvement hack. The KA locks the surface so it can draw HUD or text which // results in 24bit->16bit->24bit conversion. To prevent this action from damaging // the 24 bit framebuffer, return black content and use the composition API on unlock. if ( (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_FLIP) || (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE_POINT_GEOMETRY_DRAWN) || (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE_TRIANGLE_GEOMETRY_DRAWN) ) { // If the memory already contains a composition content, we will simply // add to it. Otherwise we create a 'transparent' black color. if ((master != MASTER_COMPOSITION) && (master != MASTER_COMPOSITION_NONKEY)) { assert(KA_COMPOSITION_KEY_MEMORY == 0); memset(memory, 0, desc->lPitch * desc->dwHeight); } active_lock_hack = LOCK_HACK_COMPOSITION; logKA(MSG_VERBOSE, 1, ""Composition hack activated""); hw_layer.marker(L""Composition hack activated""); return DD_OK; } // Starfield hack. The game begins scene, clears the buffer and uses CPU to draw background dots into // the buffer. Emulate this in the same way as with the hud to avoid format conversion on the CPU. // We add the first draw (the skybox) with overridden mode. If the CPU starfield is disabled, we // leave random content in the surface as it will be not uploaded. if (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_SCENE) { if (is_cpu_starfield_enabled() && (master != MASTER_COMPOSITION) && (master != MASTER_COMPOSITION_NONKEY)) { assert(KA_COMPOSITION_KEY_MEMORY == 0); memset(memory, 0, desc->lPitch * desc->dwHeight); } active_lock_hack = LOCK_HACK_STARFIELD; logKA(MSG_VERBOSE, 1, ""Starfield hack activated""); hw_layer.marker(L""Starfield hack activated""); return DD_OK; } } } else { // Hacks for SFA. if ((this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER) && (rect == NULL) && (master != MASTER_MEMORY) && (master != MASTER_NONE) && (flags == 1)) { // Quality improvement hack. The SFA locks the surface so it can draw HUD or text which // results in 24bit->16bit->24bit conversion. To prevent this action from damaging // the 24 bit framebuffer, return content filled with key color and use the composition // API on unlock. if ((master != MASTER_COMPOSITION) && (master != MASTER_COMPOSITION_NONKEY)) { assert((desc->lPitch % 4) == 0); const DWORD clear_dword = ((SFA_COMPOSITION_KEY_MEMORY << 16) | (SFA_COMPOSITION_KEY_MEMORY)); const size_t dword_count = desc->lPitch * desc->dwHeight / 4; const void * const memory_to_set = memory; __asm { mov eax, clear_dword mov edi, memory_to_set mov ecx, dword_count rep stosd } } active_lock_hack = LOCK_HACK_COMPOSITION; logKA(MSG_VERBOSE, 1, ""Composition hack activated""); hw_layer.marker(L""Composition hack activated""); return DD_OK; } } // Ensure that the memory contains the latest content. synchronize_memory(); // Unless the surface is locked for read, consider the HW // copy to be stalled. The Klingon Academy reads the depth // surface for visibility queries without proper flag, assume // read-only behavior for them as well. if (((flags & DDLOCK_READONLY) == 0) && ((this->desc.ddsCaps.dwCaps & DDSCAPS_ZBUFFER) == 0)) { logKA(MSG_VERBOSE, 1, ""Memory copy is now master""); master = MASTER_MEMORY; } return DD_OK; } /** * @brief Unlocks the surface. */ STDMETHODIMP DirectDrawSurfaceEmu::Unlock(LPVOID addr) { LOG_METHOD(); CHECK_NOT_NULL(addr); HWEVENT(hw_layer, L""Unlock""); // It appears that the Klingon Academy sometimes unlocks surface more than once. if (lock_count == 0) { return DDERR_NOTLOCKED; } lock_count--; // See Lock(). if (! is_inside_sfad3d()) { // Hacks for KA. if (active_lock_hack == LOCK_HACK_COMPOSITION) { assert((master == MASTER_HW) || (master == MASTER_SYNCHRONIZED) || (master == MASTER_COMPOSITION) || (master == MASTER_COMPOSITION_NONKEY)); assert(this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER); assert(hw_surface); active_lock_hack = LOCK_HACK_NONE; // The lock after end of the scene and before flip is used to draw // the UI so it is almost certainly non-zero. EmulationInfo &info = get_emulation_info(); if (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_FLIP) { master = MASTER_COMPOSITION_NONKEY; } // Otherwise keep the non-zero state if it was set previously. else if (master != MASTER_COMPOSITION_NONKEY) { master = MASTER_COMPOSITION; } return DD_OK; } if (active_lock_hack == LOCK_HACK_STARFIELD) { assert((master == MASTER_HW) || (master == MASTER_SYNCHRONIZED) || (master == MASTER_COMPOSITION) || (master == MASTER_COMPOSITION_NONKEY)); assert(this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER); assert(hw_surface); active_lock_hack = LOCK_HACK_NONE; // The starfield always contains some content. master = is_cpu_starfield_enabled() ? MASTER_COMPOSITION_NONKEY : MASTER_HW; return DD_OK; } } else { // Hacks for SFA. if (active_lock_hack == LOCK_HACK_COMPOSITION) { assert((master == MASTER_HW) || (master == MASTER_SYNCHRONIZED) || (master == MASTER_COMPOSITION) || (master == MASTER_COMPOSITION_NONKEY)); assert(this->desc.ddsCaps.dwCaps & DDSCAPS_BACKBUFFER); assert(hw_surface); active_lock_hack = LOCK_HACK_NONE; master = MASTER_COMPOSITION_NONKEY; return DD_OK; } } update_presentation_emulation(); return DD_OK; } /** * @brief Creates execute buffer. */ STDMETHODIMP DirectDrawSurfaceEmu::CreateExecuteBuffer(LPD3DEXECUTEBUFFERDESC buffer_desc,LPDIRECT3DEXECUTEBUFFER * buffer, IUnknown * outer) { LOG_METHOD(); CHECK_STRUCTURE(buffer_desc, D3DEXECUTEBUFFERDESC); CHECK_NOT_NULL(buffer); CHECK_NULL(outer); log_structure(MSG_VERBOSE, 1, *buffer_desc); // Check structure we got. if ((buffer_desc->dwFlags & D3DDEB_BUFSIZE) == 0) { logKA(MSG_ERROR, 0, ""CreateExecuteBuffer:Buffer size not specified.""); return DDERR_INVALIDPARAMS; } // Prepare the buffer. *buffer = new Direct3DExecuteBufferEmu(hw_layer, buffer_desc->dwBufferSize); logKA(MSG_VERBOSE, 1, ""Created execute buffer %08x"", *buffer); buffer_desc->dwFlags |= D3DDEB_CAPS; buffer_desc->dwCaps = D3DDEBCAPS_VIDEOMEMORY; return DD_OK; } /** * @brief Executes the execute buffer. */ STDMETHODIMP DirectDrawSurfaceEmu::Execute(LPDIRECT3DEXECUTEBUFFER buffer,LPDIRECT3DVIEWPORT viewport,DWORD flags) { LOG_METHOD(); CHECK_NOT_NULL(buffer); CHECK_NOT_NULL(viewport); HWEVENT(hw_layer, L""Execute""); static_cast(buffer)->execute(*this, viewport, flags); return DD_OK; } /** * @brief Adds viewport to list of registered viewports. */ STDMETHODIMP DirectDrawSurfaceEmu::AddViewport(LPDIRECT3DVIEWPORT viewport) { LOG_METHOD(); CHECK_NOT_NULL(viewport); viewport->AddRef(); viewports.push_back(viewport); return DD_OK; } /** * @brief Removes viewport from list of registered viewports. */ STDMETHODIMP DirectDrawSurfaceEmu::DeleteViewport(LPDIRECT3DVIEWPORT viewport) { LOG_METHOD(); CHECK_NOT_NULL(viewport); std::deque::iterator it; for (it = viewports.begin(); it != viewports.end(); ++it) { if (*it == viewport) { viewports.erase(it); viewport->Release(); return DD_OK; } } return DDERR_INVALIDPARAMS; } /** * @brief Enumerates supported texture formats. */ STDMETHODIMP DirectDrawSurfaceEmu::EnumTextureFormats(LPD3DENUMTEXTUREFORMATSCALLBACK callback, LPVOID user_data) { LOG_METHOD(); CHECK_NOT_NULL(callback); DDSURFACEDESC desc = { 0 }; desc.dwSize = sizeof(desc); desc.dwFlags = DDSD_PIXELFORMAT; desc.ddpfPixelFormat.dwSize = sizeof(desc.ddpfPixelFormat); for (size_t i = HWFORMAT_R5G6B5 ; i <= HWFORMAT_R4G4B4A4 ; ++i) { desc.ddpfPixelFormat = texture_formats[i]; if (callback(&desc, user_data) != DDENUMRET_OK) { return DD_OK; } } return DD_OK; } /** * @brief Returns handle for this texture for specified d3d device. */ STDMETHODIMP DirectDrawSurfaceEmu::GetHandle(LPDIRECT3DDEVICE device, LPD3DTEXTUREHANDLE handle) { LOG_METHOD(); CHECK_NOT_NULL(device); CHECK_NOT_NULL(handle); // HACK: Pointer to us is our handle. This works only for 32 bit process. // The api we are emulating is ancient so it was never used by // any 64 bit process. *handle = reinterpret_cast(this); return DD_OK; } /** * @brief Called before any 3d rendering. */ STDMETHODIMP DirectDrawSurfaceEmu::BeginScene() { LOG_METHOD(); // HACK: The KA loading screen uses begin/endscene without flip. Because // we are waiting uncoditionally for the Flip, doing this prevents // any updates until the load completes so the warp screen is invisible. // If we detect two BeginScene without interleaving Flip, we assume that this // problem is happening and force update of the primary surface. EmulationInfo &info = get_emulation_info(); if (info.emulation_state == EmulationInfo::EMULATION_STATE_3D_FLIP) { DirectDrawSurfaceEmu * const front_buffer = find_front_buffer(); if (front_buffer) { info.emulation_state = EmulationInfo::EMULATION_STATE_WAITING_FOR_TIME; front_buffer->update_presentation_emulation(); } } // Normal operation. hw_layer.start_event(L""scene""); assert(find_back_buffer() == this); hw_layer.begin_scene(); // Bind the correct render target. DirectDrawSurfaceEmu * const back = find_back_buffer(); DirectDrawSurfaceEmu * const depth = find_depth_buffer(); hw_layer.set_render_target( (back ? back->get_hw_surface(true) : NULL), (depth ? depth->get_hw_surface(true) : NULL) ); scene_active = true; // From now on we will be using flip as presentation // event. info.emulation_state = EmulationInfo::EMULATION_STATE_3D_SCENE; return DD_OK; } /** * @brief Called after all 3d rendering. */ STDMETHODIMP DirectDrawSurfaceEmu::EndScene() { LOG_METHOD(); assert(find_back_buffer() == this); hw_layer.end_scene(); hw_layer.set_render_target(NULL, NULL); scene_active = false; // We will wait for the flip which will present the scene. EmulationInfo &info = get_emulation_info(); info.emulation_state = EmulationInfo::EMULATION_STATE_3D_FLIP; hw_layer.end_event(); return DD_OK; } /** * @brief Loads the texture. */ STDMETHODIMP DirectDrawSurfaceEmu::Load(LPDIRECT3DTEXTURE texture) { LOG_METHOD(); CHECK_NOT_NULL(texture); HWEVENT(hw_layer, L""Load""); logKA(MSG_VERBOSE, 1, ""From %08x"", texture); // The memory is already allocated. DirectDrawSurfaceEmu * const impl = static_cast(texture); assert(desc.dwWidth == impl->desc.dwWidth); assert(desc.dwHeight == impl->desc.dwHeight); assert(memcmp(&desc.ddpfPixelFormat, &impl->desc.ddpfPixelFormat, sizeof(desc.ddpfPixelFormat)) == 0); // Copy the data. const size_t memory_size = desc.dwHeight * desc.lPitch; memcpy(memory, impl->memory, memory_size); master = MASTER_MEMORY; update_presentation_emulation(); return DD_OK; } /** * @brief Unloads the texture. */ STDMETHODIMP DirectDrawSurfaceEmu::Unload() { LOG_METHOD(); return DD_OK; } } // namespace emu // EOF // ",16211,True,3148.292957988398,median "/** * @file environment.cpp * @brief Tesseract environment interface implementation. * * @author Levi Armstrong * @date Dec 18, 2017 * @version TODO * @bug No known bugs * * @copyright Copyright (c) 2017, Southwest Research Institute * * @par License * Software License Agreement (Apache License) * @par * 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 * @par * 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 #include #include #include #include #include TESSERACT_COMMON_IGNORE_WARNINGS_PUSH #include #include #include #include #include TESSERACT_COMMON_IGNORE_WARNINGS_POP namespace tesseract_environment { bool Environment::initHelper(const Commands& commands) { if (commands.empty()) return false; if (commands.at(0)->getType() != CommandType::ADD_SCENE_GRAPH) { CONSOLE_BRIDGE_logError(""When initializing environment from command history the first command must be type "" ""ADD_SCENE_GRAPH!""); return false; } clear(); scene_graph_ = std::make_shared( std::static_pointer_cast(commands.at(0))->getSceneGraph()->getName()); scene_graph_const_ = scene_graph_; is_contact_allowed_fn_ = [this](const std::string& l1, const std::string& l2) { return scene_graph_->isCollisionAllowed(l1, l2); }; if (!applyCommandsHelper(commands)) { CONSOLE_BRIDGE_logError(""When initializing environment from command history, it failed to apply a command!""); return false; } initialized_ = true; init_revision_ = revision_; environmentChanged(); return initialized_; } bool Environment::init(const Commands& commands) { bool success{ false }; { std::unique_lock lock(mutex_); success = initHelper(commands); } // Call the event callbacks std::shared_lock lock(mutex_); triggerEnvironmentChangedCallbacks(); triggerCurrentStateChangedCallbacks(); return success; } bool Environment::init(const tesseract_scene_graph::SceneGraph& scene_graph, const tesseract_srdf::SRDFModel::ConstPtr& srdf_model) { Commands commands = getInitCommands(scene_graph, srdf_model); return init(commands); } bool Environment::init(const std::string& urdf_string, const tesseract_common::ResourceLocator::ConstPtr& locator) { resource_locator_ = locator; // Parse urdf string into Scene Graph tesseract_scene_graph::SceneGraph::Ptr scene_graph; try { scene_graph = tesseract_urdf::parseURDFString(urdf_string, *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse URDF.""); tesseract_common::printNestedException(e); return false; } Commands commands = getInitCommands(*scene_graph); return init(commands); } bool Environment::init(const std::string& urdf_string, const std::string& srdf_string, const tesseract_common::ResourceLocator::ConstPtr& locator) { resource_locator_ = locator; // Parse urdf string into Scene Graph tesseract_scene_graph::SceneGraph::Ptr scene_graph; try { scene_graph = tesseract_urdf::parseURDFString(urdf_string, *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse URDF.""); tesseract_common::printNestedException(e); return false; } // Parse srdf string into SRDF Model auto srdf = std::make_shared(); try { srdf->initString(*scene_graph, srdf_string, *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse SRDF.""); tesseract_common::printNestedException(e); return false; } Commands commands = getInitCommands(*scene_graph, srdf); return init(commands); } bool Environment::init(const tesseract_common::fs::path& urdf_path, const tesseract_common::ResourceLocator::ConstPtr& locator) { resource_locator_ = locator; // Parse urdf file into Scene Graph tesseract_scene_graph::SceneGraph::Ptr scene_graph; try { scene_graph = tesseract_urdf::parseURDFFile(urdf_path.string(), *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse URDF.""); tesseract_common::printNestedException(e); return false; } Commands commands = getInitCommands(*scene_graph); return init(commands); } bool Environment::init(const tesseract_common::fs::path& urdf_path, const tesseract_common::fs::path& srdf_path, const tesseract_common::ResourceLocator::ConstPtr& locator) { resource_locator_ = locator; // Parse urdf file into Scene Graph tesseract_scene_graph::SceneGraph::Ptr scene_graph; try { scene_graph = tesseract_urdf::parseURDFFile(urdf_path.string(), *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse URDF.""); tesseract_common::printNestedException(e); return false; } // Parse srdf file into SRDF Model auto srdf = std::make_shared(); try { srdf->initFile(*scene_graph, srdf_path.string(), *resource_locator_); } catch (const std::exception& e) { CONSOLE_BRIDGE_logError(""Failed to parse SRDF.""); tesseract_common::printNestedException(e); return false; } Commands commands = getInitCommands(*scene_graph, srdf); return init(commands); } bool Environment::reset() { bool success{ false }; { std::unique_lock lock(mutex_); Commands init_command; if (commands_.empty() || !initialized_) return false; init_command.reserve(static_cast(init_revision_)); for (std::size_t i = 0; i < static_cast(init_revision_); ++i) init_command.push_back(commands_[i]); success = initHelper(init_command); } // Call the event callbacks std::shared_lock lock(mutex_); triggerCurrentStateChangedCallbacks(); triggerEnvironmentChangedCallbacks(); return success; } void Environment::clear() { initialized_ = false; revision_ = 0; init_revision_ = 0; scene_graph_ = nullptr; scene_graph_const_ = nullptr; state_solver_ = nullptr; commands_.clear(); kinematics_information_.clear(); collision_margin_data_ = tesseract_collision::CollisionMarginData(); } Commands Environment::getInitCommands(const tesseract_scene_graph::SceneGraph& scene_graph, const tesseract_srdf::SRDFModel::ConstPtr& srdf_model) { Commands commands; tesseract_scene_graph::SceneGraph::Ptr local_sg = scene_graph.clone(); if (local_sg == nullptr) { CONSOLE_BRIDGE_logError(""Null pointer to Scene Graph""); return Commands(); } if (!local_sg->getLink(local_sg->getRoot())) { CONSOLE_BRIDGE_logError(""The scene graph has an invalid root.""); return Commands(); } if (srdf_model != nullptr) tesseract_srdf::processSRDFAllowedCollisions(*local_sg, *srdf_model); commands.push_back(std::make_shared(*local_sg)); if (srdf_model) { commands.push_back(std::make_shared(srdf_model->contact_managers_plugin_info)); commands.push_back(std::make_shared(srdf_model->kinematics_information)); // Apply calibration information for (const auto& cal : srdf_model->calibration_info.joints) commands.push_back(std::make_shared(cal.first, cal.second)); // Check srdf for collision margin data if (srdf_model->collision_margin_data) commands.push_back(std::make_shared( *srdf_model->collision_margin_data, tesseract_common::CollisionMarginOverrideType::REPLACE)); } return commands; } bool Environment::isInitialized() const { std::shared_lock lock(mutex_); return initialized_; } int Environment::getRevision() const { std::shared_lock lock(mutex_); return revision_; } Commands Environment::getCommandHistory() const { std::shared_lock lock(mutex_); return commands_; } bool Environment::applyCommands(const Commands& commands) { bool success{ false }; { std::unique_lock lock(mutex_); success = applyCommandsHelper(commands); } std::shared_lock lock(mutex_); triggerEnvironmentChangedCallbacks(); triggerCurrentStateChangedCallbacks(); return success; } bool Environment::applyCommand(Command::ConstPtr command) { return applyCommands({ std::move(command) }); } tesseract_scene_graph::SceneGraph::ConstPtr Environment::getSceneGraph() const { return scene_graph_const_; } std::vector Environment::getGroupJointNames(const std::string& group_name) const { std::shared_lock lock(mutex_); auto it = std::find(kinematics_information_.group_names.begin(), kinematics_information_.group_names.end(), group_name); if (it == kinematics_information_.group_names.end()) throw std::runtime_error(""Environment, Joint group '"" + group_name + ""' does not exist!""); std::unique_lock cache_lock(group_joint_names_cache_mutex_); auto cache_it = group_joint_names_cache_.find(group_name); if (cache_it != group_joint_names_cache_.end()) { CONSOLE_BRIDGE_logDebug(""Environment, getGroupJointNames(%s) cache hit!"", group_name.c_str()); return cache_it->second; } CONSOLE_BRIDGE_logDebug(""Environment, getGroupJointNames(%s) cache miss!"", group_name.c_str()); auto chain_it = kinematics_information_.chain_groups.find(group_name); if (chain_it != kinematics_information_.chain_groups.end()) { if (chain_it->second.size() > 1) throw std::runtime_error(""Environment, Groups with multiple chains is not supported!""); tesseract_scene_graph::ShortestPath path = scene_graph_const_->getShortestPath(chain_it->second.begin()->first, chain_it->second.begin()->second); group_joint_names_cache_[group_name] = path.active_joints; return path.active_joints; } auto joint_it = kinematics_information_.joint_groups.find(group_name); if (joint_it != kinematics_information_.joint_groups.end()) { group_joint_names_cache_[group_name] = joint_it->second; return joint_it->second; } auto link_it = kinematics_information_.link_groups.find(group_name); if (link_it != kinematics_information_.link_groups.end()) throw std::runtime_error(""Environment, Link groups are currently not supported!""); throw std::runtime_error(""Environment, failed to get group '"" + group_name + ""' joint names!""); } tesseract_kinematics::JointGroup::UPtr Environment::getJointGroup(const std::string& group_name) const { std::shared_lock lock(mutex_); std::unique_lock cache_lock(joint_group_cache_mutex_); auto it = joint_group_cache_.find(group_name); if (it != joint_group_cache_.end()) { CONSOLE_BRIDGE_logDebug(""Environment, getJointGroup(%s) cache hit!"", group_name.c_str()); return std::make_unique(*it->second); } CONSOLE_BRIDGE_logDebug(""Environment, getJointGroup(%s) cache miss!"", group_name.c_str()); // Store copy in cache and return std::vector joint_names = getGroupJointNames(group_name); tesseract_kinematics::JointGroup::UPtr jg = getJointGroup(group_name, joint_names); joint_group_cache_[group_name] = std::make_unique(*jg); return jg; } tesseract_kinematics::JointGroup::UPtr Environment::getJointGroup(const std::string& name, const std::vector& joint_names) const { std::shared_lock lock(mutex_); return std::make_unique(name, joint_names, *scene_graph_const_, current_state_); } tesseract_kinematics::KinematicGroup::UPtr Environment::getKinematicGroup(const std::string& group_name, std::string ik_solver_name) const { std::shared_lock lock(mutex_); std::unique_lock cache_lock(kinematic_group_cache_mutex_); std::pair key = std::make_pair(group_name, ik_solver_name); auto it = kinematic_group_cache_.find(key); if (it != kinematic_group_cache_.end()) { CONSOLE_BRIDGE_logDebug( ""Environment, getKinematicGroup(%s, %s) cache hit!"", group_name.c_str(), ik_solver_name.c_str()); return std::make_unique(*it->second); } CONSOLE_BRIDGE_logDebug( ""Environment, getKinematicGroup(%s, %s) cache miss!"", group_name.c_str(), ik_solver_name.c_str()); std::vector joint_names = getGroupJointNames(group_name); if (ik_solver_name.empty()) ik_solver_name = kinematics_factory_.getDefaultInvKinPlugin(group_name); tesseract_kinematics::InverseKinematics::UPtr inv_kin = kinematics_factory_.createInvKin(group_name, ik_solver_name, *scene_graph_const_, current_state_); // TODO add error message if (inv_kin == nullptr) return nullptr; // Store copy in cache and return auto kg = std::make_unique( group_name, joint_names, std::move(inv_kin), *scene_graph_const_, current_state_); kinematic_group_cache_[key] = std::make_unique(*kg); #ifndef NDEBUG if (!tesseract_kinematics::checkKinematics(*kg)) { CONSOLE_BRIDGE_logError(""Check Kinematics failed. This means that inverse kinematics solution for a pose do not "" ""match forward kinematics solution. Did you change the URDF recently?""); } #endif return kg; } // NOLINTNEXTLINE Eigen::Isometry3d Environment::findTCPOffset(const tesseract_common::ManipulatorInfo& manip_info) const { std::shared_lock lock(mutex_); // If it is already an Isometry3d return the offset if (manip_info.tcp_offset.index() != 0) return std::get<1>(manip_info.tcp_offset); // Check if the tcp offset name is a link in the scene, if so throw an exception const std::string& tcp_offset_name = std::get<0>(manip_info.tcp_offset); if (state_solver_->hasLinkName(tcp_offset_name)) throw std::runtime_error(""The tcp offset name '"" + tcp_offset_name + ""' should not be an existing link in the scene. Assign it as the tcp_frame instead!""); // Check Manipulator Manager for TCP if (kinematics_information_.hasGroupTCP(manip_info.manipulator, tcp_offset_name)) return kinematics_information_.group_tcps.at(manip_info.manipulator).at(tcp_offset_name); // Check callbacks for TCP Offset for (const auto& fn : find_tcp_cb_) { try { Eigen::Isometry3d tcp = fn(manip_info); return tcp; } catch (...) { CONSOLE_BRIDGE_logDebug(""User Defined Find TCP Callback Failed!""); } } throw std::runtime_error(""Could not find tcp by name "" + tcp_offset_name + ""'!""); } void Environment::addFindTCPOffsetCallback(const FindTCPOffsetCallbackFn& fn) { std::unique_lock lock(mutex_); find_tcp_cb_.push_back(fn); } std::vector Environment::getFindTCPOffsetCallbacks() const { std::shared_lock lock(mutex_); return find_tcp_cb_; } void Environment::addEventCallback(std::size_t hash, const EventCallbackFn& fn) { std::unique_lock lock(mutex_); event_cb_[hash] = fn; } void Environment::removeEventCallback(std::size_t hash) { std::unique_lock lock(mutex_); event_cb_.erase(hash); } void Environment::clearEventCallbacks() { std::unique_lock lock(mutex_); event_cb_.clear(); } std::map Environment::getEventCallbacks() const { std::shared_lock lock(mutex_); return event_cb_; } void Environment::setResourceLocator(tesseract_common::ResourceLocator::ConstPtr locator) { std::unique_lock lock(mutex_); resource_locator_ = std::move(locator); } tesseract_common::ResourceLocator::ConstPtr Environment::getResourceLocator() const { std::shared_lock lock(mutex_); return resource_locator_; } void Environment::setName(const std::string& name) { std::unique_lock lock(mutex_); scene_graph_->setName(name); } const std::string& Environment::getName() const { std::shared_lock lock(mutex_); return scene_graph_->getName(); } void Environment::setState(const std::unordered_map& joints) { { std::unique_lock lock(mutex_); state_solver_->setState(joints); currentStateChanged(); } std::shared_lock lock; triggerCurrentStateChangedCallbacks(); } void Environment::setState(const std::vector& joint_names, const Eigen::Ref& joint_values) { { std::unique_lock lock(mutex_); state_solver_->setState(joint_names, joint_values); currentStateChanged(); } std::shared_lock lock; triggerCurrentStateChangedCallbacks(); } tesseract_scene_graph::SceneState Environment::getState(const std::unordered_map& joints) const { std::shared_lock lock(mutex_); return state_solver_->getState(joints); } tesseract_scene_graph::SceneState Environment::getState(const std::vector& joint_names, const Eigen::Ref& joint_values) const { std::shared_lock lock(mutex_); return state_solver_->getState(joint_names, joint_values); } tesseract_scene_graph::SceneState Environment::getState() const { std::shared_lock lock(mutex_); return current_state_; } std::chrono::system_clock::time_point Environment::getTimestamp() const { std::shared_lock lock(mutex_); return timestamp_; } std::chrono::system_clock::time_point Environment::getCurrentStateTimestamp() const { std::shared_lock lock(mutex_); return current_state_timestamp_; } tesseract_scene_graph::Link::ConstPtr Environment::getLink(const std::string& name) const { std::shared_lock lock(mutex_); tesseract_scene_graph::Link::ConstPtr link = scene_graph_->getLink(name); return link; } tesseract_scene_graph::JointLimits::ConstPtr Environment::getJointLimits(const std::string& joint_name) const { std::shared_lock lock(mutex_); return scene_graph_->getJointLimits(joint_name); } bool Environment::getLinkCollisionEnabled(const std::string& name) const { std::shared_lock lock(mutex_); return scene_graph_->getLinkCollisionEnabled(name); } bool Environment::getLinkVisibility(const std::string& name) const { std::shared_lock lock(mutex_); return scene_graph_->getLinkVisibility(name); } tesseract_common::AllowedCollisionMatrix::ConstPtr Environment::getAllowedCollisionMatrix() const { std::shared_lock lock(mutex_); return scene_graph_->getAllowedCollisionMatrix(); } std::vector Environment::getJointNames() const { std::shared_lock lock(mutex_); return state_solver_->getJointNames(); } std::vector Environment::getActiveJointNames() const { std::shared_lock lock(mutex_); return state_solver_->getActiveJointNames(); } tesseract_scene_graph::Joint::ConstPtr Environment::getJoint(const std::string& name) const { std::shared_lock lock(mutex_); return scene_graph_->getJoint(name); } Eigen::VectorXd Environment::getCurrentJointValues() const { std::shared_lock lock(mutex_); Eigen::VectorXd jv; std::vector active_joint_names = state_solver_->getActiveJointNames(); jv.resize(static_cast(active_joint_names.size())); for (auto j = 0U; j < active_joint_names.size(); ++j) jv(j) = current_state_.joints.at(active_joint_names[j]); return jv; } Eigen::VectorXd Environment::getCurrentJointValues(const std::vector& joint_names) const { std::shared_lock lock(mutex_); Eigen::VectorXd jv; jv.resize(static_cast(joint_names.size())); for (auto j = 0U; j < joint_names.size(); ++j) jv(j) = current_state_.joints.at(joint_names[j]); return jv; } std::string Environment::getRootLinkName() const { std::shared_lock lock(mutex_); return scene_graph_->getRoot(); } std::vector Environment::getLinkNames() const { std::shared_lock lock(mutex_); return state_solver_->getLinkNames(); } std::vector Environment::getActiveLinkNames() const { std::shared_lock lock(mutex_); return state_solver_->getActiveLinkNames(); } std::vector Environment::getActiveLinkNames(const std::vector& joint_names) const { std::shared_lock lock(mutex_); return scene_graph_const_->getJointChildrenNames(joint_names); } std::vector Environment::getStaticLinkNames() const { std::shared_lock lock(mutex_); return state_solver_->getStaticLinkNames(); } std::vector Environment::getStaticLinkNames(const std::vector& joint_names) const { std::shared_lock lock(mutex_); std::vector active_link_names = getActiveLinkNames(joint_names); std::vector full_link_names = state_solver_->getLinkNames(); std::vector static_link_names; static_link_names.reserve(full_link_names.size()); std::sort(active_link_names.begin(), active_link_names.end()); std::sort(full_link_names.begin(), full_link_names.end()); std::set_difference(full_link_names.begin(), full_link_names.end(), active_link_names.begin(), active_link_names.end(), std::inserter(static_link_names, static_link_names.begin())); return static_link_names; } tesseract_common::VectorIsometry3d Environment::getLinkTransforms() const { std::shared_lock lock(mutex_); return state_solver_->getLinkTransforms(); } Eigen::Isometry3d Environment::getLinkTransform(const std::string& link_name) const { std::shared_lock lock(mutex_); return state_solver_->getLinkTransform(link_name); } Eigen::Isometry3d Environment::getRelativeLinkTransform(const std::string& from_link_name, const std::string& to_link_name) const { std::shared_lock lock(mutex_); return state_solver_->getRelativeLinkTransform(from_link_name, to_link_name); } tesseract_scene_graph::StateSolver::UPtr Environment::getStateSolver() const { std::shared_lock lock(mutex_); return state_solver_->clone(); } tesseract_srdf::KinematicsInformation Environment::getKinematicsInformation() const { std::shared_lock lock(mutex_); return kinematics_information_; } tesseract_srdf::GroupNames Environment::getGroupNames() const { std::shared_lock lock(mutex_); return kinematics_information_.group_names; } tesseract_common::ContactManagersPluginInfo Environment::getContactManagersPluginInfo() const { std::shared_lock lock(mutex_); return contact_managers_plugin_info_; } bool Environment::setActiveDiscreteContactManager(const std::string& name) { std::unique_lock lock(mutex_); std::unique_lock discrete_lock(discrete_manager_mutex_); return setActiveDiscreteContactManagerHelper(name); } tesseract_collision::DiscreteContactManager::UPtr Environment::getDiscreteContactManager(const std::string& name) const { std::shared_lock lock(mutex_); tesseract_collision::DiscreteContactManager::UPtr manager = getDiscreteContactManagerHelper(name); if (manager == nullptr) { CONSOLE_BRIDGE_logError(""Discrete manager with %s does not exist in factory!"", name.c_str()); return nullptr; } return manager; } bool Environment::setActiveContinuousContactManager(const std::string& name) { std::unique_lock lock(mutex_); std::unique_lock continous_lock(continuous_manager_mutex_); return setActiveContinuousContactManagerHelper(name); } tesseract_collision::DiscreteContactManager::UPtr Environment::getDiscreteContactManager() const { std::shared_lock lock(mutex_); { // Clone cached manager if exists std::shared_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_) return discrete_manager_->clone(); } { // Try to create the default plugin std::unique_lock discrete_lock(discrete_manager_mutex_); const std::string& name = contact_managers_plugin_info_.discrete_plugin_infos.default_plugin; discrete_manager_ = getDiscreteContactManagerHelper(name); if (discrete_manager_ == nullptr) { CONSOLE_BRIDGE_logError(""Discrete manager with %s does not exist in factory!"", name.c_str()); return nullptr; } } return discrete_manager_->clone(); } void Environment::clearCachedDiscreteContactManager() const { std::shared_lock lock; std::unique_lock discrete_lock(discrete_manager_mutex_); discrete_manager_ = nullptr; } tesseract_collision::ContinuousContactManager::UPtr Environment::getContinuousContactManager() const { std::shared_lock lock(mutex_); { // Clone cached manager if exists std::shared_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_) return continuous_manager_->clone(); } { // Try to create the default plugin std::unique_lock continuous_lock(continuous_manager_mutex_); const std::string& name = contact_managers_plugin_info_.continuous_plugin_infos.default_plugin; continuous_manager_ = getContinuousContactManagerHelper(name); if (continuous_manager_ == nullptr) { CONSOLE_BRIDGE_logError(""Continuous manager with %s does not exist in factory!"", name.c_str()); return nullptr; } } return continuous_manager_->clone(); } void Environment::clearCachedContinuousContactManager() const { std::shared_lock lock(mutex_); std::unique_lock continuous_lock(continuous_manager_mutex_); continuous_manager_ = nullptr; } tesseract_collision::ContinuousContactManager::UPtr Environment::getContinuousContactManager(const std::string& name) const { std::shared_lock lock(mutex_); tesseract_collision::ContinuousContactManager::UPtr manager = getContinuousContactManagerHelper(name); if (manager == nullptr) { CONSOLE_BRIDGE_logError(""Continuous manager with %s does not exist in factory!"", name.c_str()); return nullptr; } return manager; } tesseract_common::CollisionMarginData Environment::getCollisionMarginData() const { std::shared_lock lock(mutex_); return collision_margin_data_; } std::shared_lock Environment::lockRead() const { return std::shared_lock(mutex_); } bool Environment::operator==(const Environment& rhs) const { std::shared_lock lock(mutex_); // No need to check everything mainly the items serialized bool equal = true; equal &= initialized_ == rhs.initialized_; equal &= revision_ == rhs.revision_; equal &= init_revision_ == rhs.init_revision_; equal &= commands_.size() == rhs.commands_.size(); if (!equal) return equal; for (std::size_t i = 0; i < commands_.size(); ++i) { equal &= *(commands_[i]) == *(rhs.commands_[i]); if (!equal) return equal; } equal &= current_state_ == rhs.current_state_; equal &= timestamp_ == rhs.timestamp_; equal &= current_state_timestamp_ == rhs.current_state_timestamp_; /** @todo uncomment after serialized */ // equal &= is_contact_allowed_fn_ == rhs.is_contact_allowed_fn_; // equal &= find_tcp_cb_ == rhs.find_tcp_cb_; return equal; } bool Environment::operator!=(const Environment& rhs) const { return !operator==(rhs); } bool Environment::setActiveDiscreteContactManagerHelper(const std::string& name) { tesseract_collision::DiscreteContactManager::UPtr manager = getDiscreteContactManagerHelper(name); if (manager == nullptr) { std::string msg = ""\\n Discrete manager with "" + name + "" does not exist in factory!\\n""; msg += "" Available Managers:\\n""; for (const auto& m : contact_managers_factory_.getDiscreteContactManagerPlugins()) msg += "" "" + m.first + ""\\n""; CONSOLE_BRIDGE_logError(msg.c_str()); return false; } contact_managers_plugin_info_.discrete_plugin_infos.default_plugin = name; // The calling function should be locking discrete_manager_mutex_ discrete_manager_ = std::move(manager); return true; } bool Environment::setActiveContinuousContactManagerHelper(const std::string& name) { tesseract_collision::ContinuousContactManager::UPtr manager = getContinuousContactManagerHelper(name); if (manager == nullptr) { std::string msg = ""\\n Continuous manager with "" + name + "" does not exist in factory!\\n""; msg += "" Available Managers:\\n""; for (const auto& m : contact_managers_factory_.getContinuousContactManagerPlugins()) msg += "" "" + m.first + ""\\n""; CONSOLE_BRIDGE_logError(msg.c_str()); return false; } contact_managers_plugin_info_.continuous_plugin_infos.default_plugin = name; // The calling function should be locking continuous_manager_mutex_ continuous_manager_ = std::move(manager); return true; } tesseract_collision::DiscreteContactManager::UPtr Environment::getDiscreteContactManagerHelper(const std::string& name) const { tesseract_collision::DiscreteContactManager::UPtr manager = contact_managers_factory_.createDiscreteContactManager(name); if (manager == nullptr) return nullptr; manager->setIsContactAllowedFn(is_contact_allowed_fn_); if (scene_graph_ != nullptr) { for (const auto& link : scene_graph_->getLinks()) { if (!link->collision.empty()) { tesseract_collision::CollisionShapesConst shapes; tesseract_common::VectorIsometry3d shape_poses; getCollisionObject(shapes, shape_poses, *link); manager->addCollisionObject(link->getName(), 0, shapes, shape_poses, true); } } manager->setActiveCollisionObjects(state_solver_->getActiveLinkNames()); } manager->setCollisionMarginData(collision_margin_data_); manager->setCollisionObjectsTransform(current_state_.link_transforms); return manager; } tesseract_collision::ContinuousContactManager::UPtr Environment::getContinuousContactManagerHelper(const std::string& name) const { tesseract_collision::ContinuousContactManager::UPtr manager = contact_managers_factory_.createContinuousContactManager(name); if (manager == nullptr) return nullptr; manager->setIsContactAllowedFn(is_contact_allowed_fn_); if (scene_graph_ != nullptr) { for (const auto& link : scene_graph_->getLinks()) { if (!link->collision.empty()) { tesseract_collision::CollisionShapesConst shapes; tesseract_common::VectorIsometry3d shape_poses; getCollisionObject(shapes, shape_poses, *link); manager->addCollisionObject(link->getName(), 0, shapes, shape_poses, true); } } manager->setActiveCollisionObjects(state_solver_->getActiveLinkNames()); } manager->setCollisionMarginData(collision_margin_data_); std::vector active_link_names = state_solver_->getActiveLinkNames(); for (const auto& tf : current_state_.link_transforms) { if (std::find(active_link_names.begin(), active_link_names.end(), tf.first) != active_link_names.end()) manager->setCollisionObjectsTransform(tf.first, tf.second, tf.second); else manager->setCollisionObjectsTransform(tf.first, tf.second); } return manager; } void Environment::getCollisionObject(tesseract_collision::CollisionShapesConst& shapes, tesseract_common::VectorIsometry3d& shape_poses, const tesseract_scene_graph::Link& link) { for (const auto& c : link.collision) { shapes.push_back(c->geometry); shape_poses.push_back(c->origin); } } void Environment::currentStateChanged() { timestamp_ = std::chrono::system_clock::now(); current_state_timestamp_ = timestamp_; current_state_ = state_solver_->getState(); std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->setCollisionObjectsTransform(current_state_.link_transforms); std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) { std::vector active_link_names = state_solver_->getActiveLinkNames(); for (const auto& tf : current_state_.link_transforms) { if (std::find(active_link_names.begin(), active_link_names.end(), tf.first) != active_link_names.end()) continuous_manager_->setCollisionObjectsTransform(tf.first, tf.second, tf.second); else continuous_manager_->setCollisionObjectsTransform(tf.first, tf.second); } } { // Clear JointGroup and KinematicGroup std::unique_lock jg_lock(joint_group_cache_mutex_); std::unique_lock kg_lock(kinematic_group_cache_mutex_); joint_group_cache_.clear(); kinematic_group_cache_.clear(); } } void Environment::environmentChanged() { timestamp_ = std::chrono::system_clock::now(); std::vector active_link_names = state_solver_->getActiveLinkNames(); { std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->setActiveCollisionObjects(active_link_names); } { std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) continuous_manager_->setActiveCollisionObjects(active_link_names); } { // Clear JointGroup, KinematicGroup and GroupJointNames cache std::unique_lock jn_lock(group_joint_names_cache_mutex_); group_joint_names_cache_.clear(); } currentStateChanged(); } void Environment::triggerCurrentStateChangedCallbacks() { if (!event_cb_.empty()) { SceneStateChangedEvent event(current_state_); for (const auto& cb : event_cb_) cb.second(event); } } void Environment::triggerEnvironmentChangedCallbacks() { if (!event_cb_.empty()) { CommandAppliedEvent event(commands_, revision_); for (const auto& cb : event_cb_) cb.second(event); } } bool Environment::removeLinkHelper(const std::string& name) { if (scene_graph_->getLink(name) == nullptr) { CONSOLE_BRIDGE_logWarn(""Tried to remove link (%s) that does not exist"", name.c_str()); return false; } std::vector joints = scene_graph_->getInboundJoints(name); assert(joints.size() <= 1); // get child link names to remove std::vector child_link_names = scene_graph_->getLinkChildrenNames(name); scene_graph_->removeLink(name, true); std::unique_lock discrete_lock(discrete_manager_mutex_); std::unique_lock continuous_lock(continuous_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->removeCollisionObject(name); if (continuous_manager_ != nullptr) continuous_manager_->removeCollisionObject(name); for (const auto& link_name : child_link_names) { if (discrete_manager_ != nullptr) discrete_manager_->removeCollisionObject(link_name); if (continuous_manager_ != nullptr) continuous_manager_->removeCollisionObject(link_name); } return true; } Environment::UPtr Environment::clone() const { auto cloned_env = std::make_unique(); std::shared_lock lock(mutex_); std::shared_lock jg_lock(joint_group_cache_mutex_); std::shared_lock kg_lock(kinematic_group_cache_mutex_); std::shared_lock jn_lock(group_joint_names_cache_mutex_); std::shared_lock discrete_lock(discrete_manager_mutex_); std::shared_lock continuous_lock(continuous_manager_mutex_); if (!initialized_) return cloned_env; cloned_env->initialized_ = initialized_; cloned_env->init_revision_ = revision_; cloned_env->revision_ = revision_; cloned_env->commands_ = commands_; cloned_env->scene_graph_ = scene_graph_->clone(); cloned_env->scene_graph_const_ = cloned_env->scene_graph_; cloned_env->timestamp_ = timestamp_; cloned_env->current_state_ = current_state_; cloned_env->current_state_timestamp_ = current_state_timestamp_; // There is not dynamic pointer cast for std::unique_ptr auto cloned_solver = state_solver_->clone(); auto* p = dynamic_cast(cloned_solver.get()); if (p != nullptr) (void)cloned_solver.release(); cloned_env->state_solver_ = std::unique_ptr(p); cloned_env->kinematics_information_ = kinematics_information_; cloned_env->kinematics_factory_ = kinematics_factory_; cloned_env->find_tcp_cb_ = find_tcp_cb_; cloned_env->collision_margin_data_ = collision_margin_data_; // Copy cache cloned_env->joint_group_cache_.reserve(joint_group_cache_.size()); for (const auto& c : joint_group_cache_) cloned_env->joint_group_cache_[c.first] = (std::make_unique(*c.second)); for (const auto& c : kinematic_group_cache_) cloned_env->kinematic_group_cache_[c.first] = (std::make_unique(*c.second)); cloned_env->group_joint_names_cache_ = group_joint_names_cache_; // NOLINTNEXTLINE cloned_env->is_contact_allowed_fn_ = std::bind(&tesseract_scene_graph::SceneGraph::isCollisionAllowed, cloned_env->scene_graph_, std::placeholders::_1, std::placeholders::_2); if (discrete_manager_) { cloned_env->discrete_manager_ = discrete_manager_->clone(); cloned_env->discrete_manager_->setIsContactAllowedFn(cloned_env->is_contact_allowed_fn_); } if (continuous_manager_) { cloned_env->continuous_manager_ = continuous_manager_->clone(); cloned_env->continuous_manager_->setIsContactAllowedFn(cloned_env->is_contact_allowed_fn_); } cloned_env->contact_managers_plugin_info_ = contact_managers_plugin_info_; cloned_env->contact_managers_factory_ = contact_managers_factory_; return cloned_env; } bool Environment::applyCommandsHelper(const Commands& commands) { bool success = true; for (const auto& command : commands) { if (!command) { success = false; break; } switch (command->getType()) { case tesseract_environment::CommandType::ADD_LINK: { auto cmd = std::static_pointer_cast(command); success &= applyAddCommand(cmd); break; } case tesseract_environment::CommandType::MOVE_LINK: { auto cmd = std::static_pointer_cast(command); success &= applyMoveLinkCommand(cmd); break; } case tesseract_environment::CommandType::MOVE_JOINT: { auto cmd = std::static_pointer_cast(command); success &= applyMoveJointCommand(cmd); break; } case tesseract_environment::CommandType::REMOVE_LINK: { auto cmd = std::static_pointer_cast(command); success &= applyRemoveLinkCommand(cmd); break; } case tesseract_environment::CommandType::REMOVE_JOINT: { auto cmd = std::static_pointer_cast(command); success &= applyRemoveJointCommand(cmd); break; } case tesseract_environment::CommandType::REPLACE_JOINT: { auto cmd = std::static_pointer_cast(command); success &= applyReplaceJointCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_LINK_ORIGIN: { auto cmd = std::static_pointer_cast(command); success &= applyChangeLinkOriginCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_JOINT_ORIGIN: { auto cmd = std::static_pointer_cast(command); success &= applyChangeJointOriginCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_LINK_COLLISION_ENABLED: { auto cmd = std::static_pointer_cast(command); success &= applyChangeLinkCollisionEnabledCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_LINK_VISIBILITY: { auto cmd = std::static_pointer_cast(command); success &= applyChangeLinkVisibilityCommand(cmd); break; } case tesseract_environment::CommandType::ADD_ALLOWED_COLLISION: { auto cmd = std::static_pointer_cast(command); success &= applyAddAllowedCollisionCommand(cmd); break; } case tesseract_environment::CommandType::REMOVE_ALLOWED_COLLISION: { auto cmd = std::static_pointer_cast(command); success &= applyRemoveAllowedCollisionCommand(cmd); break; } case tesseract_environment::CommandType::REMOVE_ALLOWED_COLLISION_LINK: { auto cmd = std::static_pointer_cast(command); success &= applyRemoveAllowedCollisionLinkCommand(cmd); break; } case tesseract_environment::CommandType::ADD_SCENE_GRAPH: { auto cmd = std::static_pointer_cast(command); success &= applyAddSceneGraphCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_JOINT_POSITION_LIMITS: { auto cmd = std::static_pointer_cast(command); success &= applyChangeJointPositionLimitsCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_JOINT_VELOCITY_LIMITS: { auto cmd = std::static_pointer_cast(command); success &= applyChangeJointVelocityLimitsCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_JOINT_ACCELERATION_LIMITS: { auto cmd = std::static_pointer_cast(command); success &= applyChangeJointAccelerationLimitsCommand(cmd); break; } case tesseract_environment::CommandType::ADD_KINEMATICS_INFORMATION: { auto cmd = std::static_pointer_cast(command); success &= applyAddKinematicsInformationCommand(cmd); break; } case tesseract_environment::CommandType::CHANGE_COLLISION_MARGINS: { auto cmd = std::static_pointer_cast(command); success &= applyChangeCollisionMarginsCommand(cmd); break; } case tesseract_environment::CommandType::ADD_CONTACT_MANAGERS_PLUGIN_INFO: { auto cmd = std::static_pointer_cast(command); success &= applyAddContactManagersPluginInfoCommand(cmd); break; } case tesseract_environment::CommandType::SET_ACTIVE_CONTINUOUS_CONTACT_MANAGER: { auto cmd = std::static_pointer_cast(command); success &= applySetActiveContinuousContactManagerCommand(cmd); break; } case tesseract_environment::CommandType::SET_ACTIVE_DISCRETE_CONTACT_MANAGER: { auto cmd = std::static_pointer_cast(command); success &= applySetActiveDiscreteContactManagerCommand(cmd); break; } // LCOV_EXCL_START default: { CONSOLE_BRIDGE_logError(""Unhandled environment command""); success &= false; } // LCOV_EXCL_STOP } if (!success) break; } // Update the solver revision to match environment state_solver_->setRevision(revision_); // If this is not true then the initHelper function has called applyCommand so do not call. if (initialized_) environmentChanged(); return success; } ////////////////////////////////////////////////////////////// //////////////// Internal Apply Command ////////////////////// ////////////////////////////////////////////////////////////// bool Environment::applyAddCommand(AddLinkCommand::ConstPtr cmd) { // The command should not allow this to occur but adding an assert to catch if something changes assert(!(!cmd->getLink() && !cmd->getJoint())); assert(!((cmd->getLink() != nullptr) && (cmd->getJoint() != nullptr) && (cmd->getJoint()->child_link_name != cmd->getLink()->getName()))); bool link_exists = false; bool joint_exists = false; std::string link_name, joint_name; if (cmd->getLink() != nullptr) { link_name = cmd->getLink()->getName(); link_exists = (scene_graph_->getLink(link_name) != nullptr); } if (cmd->getJoint() != nullptr) { joint_name = cmd->getJoint()->getName(); joint_exists = (scene_graph_->getJoint(joint_name) != nullptr); } if ((link_exists && !cmd->replaceAllowed())) { CONSOLE_BRIDGE_logWarn(""Tried to add link (%s) which already exists. Set replace_allowed to enable replacing."", link_name.c_str()); return false; } if ((joint_exists && !cmd->replaceAllowed())) { CONSOLE_BRIDGE_logWarn(""Tried to replace link (%s) and joint (%s) where the joint exist but the link does not. "" ""This is not supported."", link_name.c_str(), joint_name.c_str()); return false; } if (!link_exists && joint_exists) { CONSOLE_BRIDGE_logWarn(""Tried to add link (%s) which already exists with a joint provided which does not exist. "" ""This is not supported."", link_name.c_str()); return false; } if ((link_exists && cmd->getJoint() && !joint_exists)) { CONSOLE_BRIDGE_logWarn(""Tried to add link (%s) which already exists with a joint provided which does not exist. "" ""This is not supported."", link_name.c_str()); return false; } if (link_exists && !cmd->getJoint()) { // A link is being replaced if (!scene_graph_->addLink(*cmd->getLink(), true)) return false; // Solver is not affected by replace links } else if (link_exists && joint_exists) { // A link and joint pair is being replaced tesseract_scene_graph::Link::ConstPtr orig_link = scene_graph_->getLink(link_name); tesseract_scene_graph::Joint::ConstPtr orig_joint = scene_graph_->getJoint(joint_name); if (orig_joint->child_link_name != orig_link->getName()) { CONSOLE_BRIDGE_logWarn(""Tried to replace link (%s) and joint (%s) which are currently not linked. This is not "" ""supported."", link_name.c_str(), joint_name.c_str()); return false; } if (!scene_graph_->addLink(*cmd->getLink(), true)) return false; if (!scene_graph_->removeJoint(joint_name)) { // Replace with original link if (!scene_graph_->addLink(*orig_link, true)) throw std::runtime_error(""Environment: Failed to replace link and joint and reset to original state.""); return false; } if (!scene_graph_->addJoint(*cmd->getJoint())) { // Replace with original link if (!scene_graph_->addLink(*orig_link, true)) throw std::runtime_error(""Environment: Failed to replace link and joint reset to original state.""); // Replace with original link if (!scene_graph_->addJoint(*orig_joint)) throw std::runtime_error(""Environment: Failed to replace link and joint and reset to original state.""); return false; } if (!state_solver_->replaceJoint(*cmd->getJoint())) throw std::runtime_error(""Environment, failed to replace link and joint in state solver.""); } else if (!link_exists && !cmd->getJoint()) { // Add a new link is being added attached to the world std::string joint_name = ""joint_"" + link_name; tesseract_scene_graph::Joint joint(joint_name); joint.type = tesseract_scene_graph::JointType::FIXED; joint.child_link_name = link_name; joint.parent_link_name = scene_graph_->getRoot(); tesseract_scene_graph::Link::ConstPtr link = cmd->getLink(); cmd = std::make_shared(*link, joint); if (!scene_graph_->addLink(*cmd->getLink(), *cmd->getJoint())) return false; if (!state_solver_->addLink(*cmd->getLink(), *cmd->getJoint())) throw std::runtime_error(""Environment, failed to add link and joint in state solver.""); } else { // A new link and joint is being added if (!scene_graph_->addLink(*cmd->getLink(), *cmd->getJoint())) return false; if (!state_solver_->addLink(*cmd->getLink(), *cmd->getJoint())) throw std::runtime_error(""Environment, failed to add link and joint in state solver.""); } // If Link existed remove it from collision before adding the replacing links geometry if (link_exists) { std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->removeCollisionObject(link_name); std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) continuous_manager_->removeCollisionObject(link_name); } // We have moved the original objects, get a pointer to them from scene_graph if (!cmd->getLink()->collision.empty()) { tesseract_collision::CollisionShapesConst shapes; tesseract_common::VectorIsometry3d shape_poses; getCollisionObject(shapes, shape_poses, *cmd->getLink()); std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->addCollisionObject(link_name, 0, shapes, shape_poses, true); std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) continuous_manager_->addCollisionObject(link_name, 0, shapes, shape_poses, true); } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyMoveLinkCommand(const MoveLinkCommand::ConstPtr& cmd) { if (!scene_graph_->moveLink(*cmd->getJoint())) return false; if (!state_solver_->moveLink(*cmd->getJoint())) throw std::runtime_error(""Environment, failed to move link in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyMoveJointCommand(const MoveJointCommand::ConstPtr& cmd) { if (!scene_graph_->moveJoint(cmd->getJointName(), cmd->getParentLink())) return false; if (!state_solver_->moveJoint(cmd->getJointName(), cmd->getParentLink())) throw std::runtime_error(""Environment, failed to move joint in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyRemoveLinkCommand(const RemoveLinkCommand::ConstPtr& cmd) { if (!removeLinkHelper(cmd->getLinkName())) return false; if (!state_solver_->removeLink(cmd->getLinkName())) throw std::runtime_error(""Environment, failed to remove link in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyRemoveJointCommand(const RemoveJointCommand::ConstPtr& cmd) { if (scene_graph_->getJoint(cmd->getJointName()) == nullptr) { CONSOLE_BRIDGE_logWarn(""Tried to remove Joint (%s) that does not exist"", cmd->getJointName().c_str()); return false; } std::string target_link_name = scene_graph_->getTargetLink(cmd->getJointName())->getName(); if (!removeLinkHelper(target_link_name)) return false; if (!state_solver_->removeJoint(cmd->getJointName())) throw std::runtime_error(""Environment, failed to remove joint in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyReplaceJointCommand(const ReplaceJointCommand::ConstPtr& cmd) { tesseract_scene_graph::Joint::ConstPtr current_joint = scene_graph_->getJoint(cmd->getJoint()->getName()); if (current_joint == nullptr) { CONSOLE_BRIDGE_logWarn(""Tried to replace Joint (%s) that does not exist"", cmd->getJoint()->getName().c_str()); return false; } if (cmd->getJoint()->child_link_name != current_joint->child_link_name) { CONSOLE_BRIDGE_logWarn(""Tried to replace Joint (%s) where the child links are not the same"", cmd->getJoint()->getName().c_str()); return false; } if (!scene_graph_->removeJoint(cmd->getJoint()->getName())) return false; if (!scene_graph_->addJoint(*cmd->getJoint())) { // Add old joint back if (!scene_graph_->addJoint(*current_joint)) throw std::runtime_error(""Environment: Failed to add old joint back when replace failed!""); return false; } if (!state_solver_->replaceJoint(*cmd->getJoint())) throw std::runtime_error(""Environment, failed to replace joint in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeLinkOriginCommand(const ChangeLinkOriginCommand::ConstPtr& /*cmd*/) // NOLINT { throw std::runtime_error(""Unhandled environment command: CHANGE_LINK_ORIGIN""); } bool Environment::applyChangeJointOriginCommand(const ChangeJointOriginCommand::ConstPtr& cmd) { if (!scene_graph_->changeJointOrigin(cmd->getJointName(), cmd->getOrigin())) return false; if (!state_solver_->changeJointOrigin(cmd->getJointName(), cmd->getOrigin())) throw std::runtime_error(""Environment, failed to change joint origin in state solver.""); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeLinkCollisionEnabledCommand(const ChangeLinkCollisionEnabledCommand::ConstPtr& cmd) { std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) { if (cmd->getEnabled()) discrete_manager_->enableCollisionObject(cmd->getLinkName()); else discrete_manager_->disableCollisionObject(cmd->getLinkName()); } std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) { if (cmd->getEnabled()) continuous_manager_->enableCollisionObject(cmd->getLinkName()); else continuous_manager_->disableCollisionObject(cmd->getLinkName()); } scene_graph_->setLinkCollisionEnabled(cmd->getLinkName(), cmd->getEnabled()); if (scene_graph_->getLinkCollisionEnabled(cmd->getLinkName()) != cmd->getEnabled()) return false; ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeLinkVisibilityCommand(const ChangeLinkVisibilityCommand::ConstPtr& cmd) { scene_graph_->setLinkVisibility(cmd->getLinkName(), cmd->getEnabled()); if (scene_graph_->getLinkVisibility(cmd->getLinkName()) != cmd->getEnabled()) return false; ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyAddAllowedCollisionCommand(const AddAllowedCollisionCommand::ConstPtr& cmd) { scene_graph_->addAllowedCollision(cmd->getLinkName1(), cmd->getLinkName2(), cmd->getReason()); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyRemoveAllowedCollisionCommand(const RemoveAllowedCollisionCommand::ConstPtr& cmd) { scene_graph_->removeAllowedCollision(cmd->getLinkName1(), cmd->getLinkName2()); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyRemoveAllowedCollisionLinkCommand(const RemoveAllowedCollisionLinkCommand::ConstPtr& cmd) { scene_graph_->removeAllowedCollision(cmd->getLinkName()); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyAddSceneGraphCommand(AddSceneGraphCommand::ConstPtr cmd) { if (scene_graph_->isEmpty() && cmd->getJoint()) return false; std::vector pre_links = scene_graph_->getLinks(); if (scene_graph_->isEmpty()) { if (!scene_graph_->insertSceneGraph(*cmd->getSceneGraph(), cmd->getPrefix())) return false; state_solver_ = std::make_unique(*cmd->getSceneGraph(), cmd->getPrefix()); } else if (!cmd->getJoint()) { // Connect root of subgraph to graph tesseract_scene_graph::Joint root_joint(cmd->getPrefix() + cmd->getSceneGraph()->getName() + ""_joint""); root_joint.type = tesseract_scene_graph::JointType::FIXED; root_joint.parent_link_name = scene_graph_->getRoot(); root_joint.child_link_name = cmd->getPrefix() + cmd->getSceneGraph()->getRoot(); root_joint.parent_to_joint_origin_transform = Eigen::Isometry3d::Identity(); tesseract_scene_graph::SceneGraph::ConstPtr sg = cmd->getSceneGraph(); std::string prefix = cmd->getPrefix(); cmd = std::make_shared(*sg, root_joint, prefix); if (!scene_graph_->insertSceneGraph(*cmd->getSceneGraph(), *cmd->getJoint(), cmd->getPrefix())) return false; if (!state_solver_->insertSceneGraph(*cmd->getSceneGraph(), *cmd->getJoint(), cmd->getPrefix())) throw std::runtime_error(""Environment, failed to insert scene graph into state solver.""); } else { if (!scene_graph_->insertSceneGraph(*cmd->getSceneGraph(), *cmd->getJoint(), cmd->getPrefix())) return false; if (!state_solver_->insertSceneGraph(*cmd->getSceneGraph(), *cmd->getJoint(), cmd->getPrefix())) throw std::runtime_error(""Environment, failed to insert scene graph into state solver.""); } // Now need to get list of added links to add to the contact manager std::vector post_links = scene_graph_->getLinks(); assert(post_links.size() > pre_links.size()); std::sort(pre_links.begin(), pre_links.end()); std::sort(post_links.begin(), post_links.end()); std::vector diff_links; std::set_difference(post_links.begin(), post_links.end(), pre_links.begin(), pre_links.end(), std::inserter(diff_links, diff_links.begin())); std::unique_lock discrete_lock(discrete_manager_mutex_); std::unique_lock continuous_lock(continuous_manager_mutex_); for (const auto& link : diff_links) { if (!link->collision.empty()) { tesseract_collision::CollisionShapesConst shapes; tesseract_common::VectorIsometry3d shape_poses; getCollisionObject(shapes, shape_poses, *link); if (discrete_manager_ != nullptr) discrete_manager_->addCollisionObject(link->getName(), 0, shapes, shape_poses, true); if (continuous_manager_ != nullptr) continuous_manager_->addCollisionObject(link->getName(), 0, shapes, shape_poses, true); } } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeJointPositionLimitsCommand(const ChangeJointPositionLimitsCommand::ConstPtr& cmd) { // First check if all of the joint exist for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits::ConstPtr jl = scene_graph_->getJointLimits(jp.first); if (jl == nullptr) return false; } for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits jl_copy = *scene_graph_->getJointLimits(jp.first); jl_copy.lower = jp.second.first; jl_copy.upper = jp.second.second; if (!scene_graph_->changeJointLimits(jp.first, jl_copy)) return false; if (!state_solver_->changeJointPositionLimits(jp.first, jp.second.first, jp.second.second)) throw std::runtime_error(""Environment, failed to change joint position limits in state solver.""); } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeJointVelocityLimitsCommand(const ChangeJointVelocityLimitsCommand::ConstPtr& cmd) { // First check if all of the joint exist for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits::ConstPtr jl = scene_graph_->getJointLimits(jp.first); if (jl == nullptr) return false; } for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits jl_copy = *scene_graph_->getJointLimits(jp.first); jl_copy.velocity = jp.second; if (!scene_graph_->changeJointLimits(jp.first, jl_copy)) return false; if (!state_solver_->changeJointVelocityLimits(jp.first, jp.second)) throw std::runtime_error(""Environment, failed to change joint velocity limits in state solver.""); } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeJointAccelerationLimitsCommand(const ChangeJointAccelerationLimitsCommand::ConstPtr& cmd) { // First check if all of the joint exist for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits::ConstPtr jl = scene_graph_->getJointLimits(jp.first); if (jl == nullptr) return false; } for (const auto& jp : cmd->getLimits()) { tesseract_scene_graph::JointLimits jl_copy = *scene_graph_->getJointLimits(jp.first); jl_copy.acceleration = jp.second; if (!scene_graph_->changeJointLimits(jp.first, jl_copy)) return false; if (!state_solver_->changeJointAccelerationLimits(jp.first, jp.second)) throw std::runtime_error(""Environment, failed to change joint acceleration limits in state solver.""); } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyAddKinematicsInformationCommand(const AddKinematicsInformationCommand::ConstPtr& cmd) { kinematics_information_.insert(cmd->getKinematicsInformation()); if (!cmd->getKinematicsInformation().kinematics_plugin_info.empty()) { const auto& info = cmd->getKinematicsInformation().kinematics_plugin_info; for (const auto& search_path : info.search_paths) kinematics_factory_.addSearchPath(search_path); for (const auto& search_library : info.search_libraries) kinematics_factory_.addSearchLibrary(search_library); for (const auto& group : info.fwd_plugin_infos) { for (const auto& solver : group.second.plugins) kinematics_factory_.addFwdKinPlugin(group.first, solver.first, solver.second); if (!group.second.default_plugin.empty()) kinematics_factory_.setDefaultFwdKinPlugin(group.first, group.second.default_plugin); } for (const auto& group : info.inv_plugin_infos) { for (const auto& solver : group.second.plugins) kinematics_factory_.addInvKinPlugin(group.first, solver.first, solver.second); if (!group.second.default_plugin.empty()) kinematics_factory_.setDefaultInvKinPlugin(group.first, group.second.default_plugin); } } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyAddContactManagersPluginInfoCommand(const AddContactManagersPluginInfoCommand::ConstPtr& cmd) { const auto& info = cmd->getContactManagersPluginInfo(); if (!info.empty()) { contact_managers_plugin_info_.insert(info); for (const auto& search_path : info.search_paths) contact_managers_factory_.addSearchPath(search_path); for (const auto& search_library : info.search_libraries) contact_managers_factory_.addSearchLibrary(search_library); for (const auto& cm : info.discrete_plugin_infos.plugins) contact_managers_factory_.addDiscreteContactManagerPlugin(cm.first, cm.second); if (!info.discrete_plugin_infos.default_plugin.empty()) contact_managers_factory_.setDefaultDiscreteContactManagerPlugin(info.discrete_plugin_infos.default_plugin); for (const auto& cm : info.continuous_plugin_infos.plugins) contact_managers_factory_.addContinuousContactManagerPlugin(cm.first, cm.second); if (!info.continuous_plugin_infos.default_plugin.empty()) contact_managers_factory_.setDefaultContinuousContactManagerPlugin(info.continuous_plugin_infos.default_plugin); } if (contact_managers_factory_.hasDiscreteContactManagerPlugins()) { std::string discrete_default = contact_managers_factory_.getDefaultDiscreteContactManagerPlugin(); std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ == nullptr || discrete_manager_->getName() != discrete_default) setActiveDiscreteContactManagerHelper(discrete_default); } else { CONSOLE_BRIDGE_logDebug(""Environment, No discrete contact manager plugins were provided""); } if (contact_managers_factory_.hasContinuousContactManagerPlugins()) { std::string continuous_default = contact_managers_factory_.getDefaultContinuousContactManagerPlugin(); std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ == nullptr || continuous_manager_->getName() != continuous_default) setActiveContinuousContactManagerHelper(continuous_default); } else { CONSOLE_BRIDGE_logDebug(""Environment, No continuous contact manager plugins were provided""); } ++revision_; commands_.push_back(cmd); return true; } bool Environment::applySetActiveContinuousContactManagerCommand( const SetActiveContinuousContactManagerCommand::ConstPtr& cmd) { setActiveContinuousContactManagerHelper(cmd->getName()); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applySetActiveDiscreteContactManagerCommand( const SetActiveDiscreteContactManagerCommand::ConstPtr& cmd) { setActiveDiscreteContactManagerHelper(cmd->getName()); ++revision_; commands_.push_back(cmd); return true; } bool Environment::applyChangeCollisionMarginsCommand(const ChangeCollisionMarginsCommand::ConstPtr& cmd) { collision_margin_data_.apply(cmd->getCollisionMarginData(), cmd->getCollisionMarginOverrideType()); std::unique_lock continuous_lock(continuous_manager_mutex_); if (continuous_manager_ != nullptr) continuous_manager_->setCollisionMarginData(collision_margin_data_, CollisionMarginOverrideType::REPLACE); std::unique_lock discrete_lock(discrete_manager_mutex_); if (discrete_manager_ != nullptr) discrete_manager_->setCollisionMarginData(collision_margin_data_, CollisionMarginOverrideType::REPLACE); ++revision_; commands_.push_back(cmd); return true; } template void Environment::save(Archive& ar, const unsigned int /*version*/) const { std::shared_lock lock(mutex_); ar& BOOST_SERIALIZATION_NVP(resource_locator_); ar& BOOST_SERIALIZATION_NVP(commands_); ar& BOOST_SERIALIZATION_NVP(init_revision_); ar& BOOST_SERIALIZATION_NVP(current_state_); ar& boost::serialization::make_nvp(""timestamp_"", boost::serialization::make_binary_object(×tamp_, sizeof(timestamp_))); ar& boost::serialization::make_nvp( ""current_state_timestamp_"", boost::serialization::make_binary_object(¤t_state_timestamp_, sizeof(current_state_timestamp_))); } template void Environment::load(Archive& ar, const unsigned int /*version*/) { ar& BOOST_SERIALIZATION_NVP(resource_locator_); tesseract_environment::Commands commands; ar& boost::serialization::make_nvp(""commands_"", commands); init(commands); ar& BOOST_SERIALIZATION_NVP(init_revision_); tesseract_scene_graph::SceneState current_state; ar& boost::serialization::make_nvp(""current_state_"", current_state); setState(current_state.joints); ar& boost::serialization::make_nvp(""timestamp_"", boost::serialization::make_binary_object(×tamp_, sizeof(timestamp_))); ar& boost::serialization::make_nvp( ""current_state_timestamp_"", boost::serialization::make_binary_object(¤t_state_timestamp_, sizeof(current_state_timestamp_))); } template void Environment::serialize(Archive& ar, const unsigned int version) { boost::serialization::split_member(ar, *this, version); } } // namespace tesseract_environment #include TESSERACT_SERIALIZE_ARCHIVES_INSTANTIATE(tesseract_environment::Environment) ",16210,True,3155.6232695647714,median "//===-- SIFoldOperands.cpp - Fold operands --- ----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // /// \\file //===----------------------------------------------------------------------===// // #include ""AMDGPU.h"" #include ""GCNSubtarget.h"" #include ""MCTargetDesc/AMDGPUMCTargetDesc.h"" #include ""SIMachineFunctionInfo.h"" #include ""llvm/ADT/DepthFirstIterator.h"" #include ""llvm/CodeGen/MachineFunctionPass.h"" #define DEBUG_TYPE ""si-fold-operands"" using namespace llvm; namespace { struct FoldCandidate { MachineInstr *UseMI; union { MachineOperand *OpToFold; uint64_t ImmToFold; int FrameIndexToFold; }; int ShrinkOpcode; unsigned UseOpNo; MachineOperand::MachineOperandType Kind; bool Commuted; FoldCandidate(MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp, bool Commuted_ = false, int ShrinkOp = -1) : UseMI(MI), OpToFold(nullptr), ShrinkOpcode(ShrinkOp), UseOpNo(OpNo), Kind(FoldOp->getType()), Commuted(Commuted_) { if (FoldOp->isImm()) { ImmToFold = FoldOp->getImm(); } else if (FoldOp->isFI()) { FrameIndexToFold = FoldOp->getIndex(); } else { assert(FoldOp->isReg() || FoldOp->isGlobal()); OpToFold = FoldOp; } } bool isFI() const { return Kind == MachineOperand::MO_FrameIndex; } bool isImm() const { return Kind == MachineOperand::MO_Immediate; } bool isReg() const { return Kind == MachineOperand::MO_Register; } bool isGlobal() const { return Kind == MachineOperand::MO_GlobalAddress; } bool isCommuted() const { return Commuted; } bool needsShrink() const { return ShrinkOpcode != -1; } int getShrinkOpcode() const { return ShrinkOpcode; } }; class SIFoldOperands : public MachineFunctionPass { public: static char ID; MachineRegisterInfo *MRI; const SIInstrInfo *TII; const SIRegisterInfo *TRI; const GCNSubtarget *ST; const SIMachineFunctionInfo *MFI; void foldOperand(MachineOperand &OpToFold, MachineInstr *UseMI, int UseOpIdx, SmallVectorImpl &FoldList, SmallVectorImpl &CopiesToReplace) const; void foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const; const MachineOperand *isClamp(const MachineInstr &MI) const; bool tryFoldClamp(MachineInstr &MI); std::pair isOMod(const MachineInstr &MI) const; bool tryFoldOMod(MachineInstr &MI); public: SIFoldOperands() : MachineFunctionPass(ID) { initializeSIFoldOperandsPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return ""SI Fold Operands""; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS(SIFoldOperands, DEBUG_TYPE, ""SI Fold Operands"", false, false) char SIFoldOperands::ID = 0; char &llvm::SIFoldOperandsID = SIFoldOperands::ID; // Map multiply-accumulate opcode to corresponding multiply-add opcode if any. static unsigned macToMad(unsigned Opc) { switch (Opc) { case AMDGPU::V_MAC_F32_e64: return AMDGPU::V_MAD_F32_e64; case AMDGPU::V_MAC_F16_e64: return AMDGPU::V_MAD_F16_e64; case AMDGPU::V_FMAC_F32_e64: return AMDGPU::V_FMA_F32_e64; case AMDGPU::V_FMAC_F16_e64: return AMDGPU::V_FMA_F16_gfx9_e64; case AMDGPU::V_FMAC_LEGACY_F32_e64: return AMDGPU::V_FMA_LEGACY_F32_e64; } return AMDGPU::INSTRUCTION_LIST_END; } // Wrapper around isInlineConstant that understands special cases when // instruction types are replaced during operand folding. static bool isInlineConstantIfFolded(const SIInstrInfo *TII, const MachineInstr &UseMI, unsigned OpNo, const MachineOperand &OpToFold) { if (TII->isInlineConstant(UseMI, OpNo, OpToFold)) return true; unsigned Opc = UseMI.getOpcode(); unsigned NewOpc = macToMad(Opc); if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) { // Special case for mac. Since this is replaced with mad when folded into // src2, we need to check the legality for the final instruction. int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2); if (static_cast(OpNo) == Src2Idx) { const MCInstrDesc &MadDesc = TII->get(NewOpc); return TII->isInlineConstant(OpToFold, MadDesc.OpInfo[OpNo].OperandType); } } return false; } // TODO: Add heuristic that the frame index might not fit in the addressing mode // immediate offset to avoid materializing in loops. static bool frameIndexMayFold(const SIInstrInfo *TII, const MachineInstr &UseMI, int OpNo, const MachineOperand &OpToFold) { if (!OpToFold.isFI()) return false; if (TII->isMUBUF(UseMI)) return OpNo == AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::vaddr); if (!TII->isFLATScratch(UseMI)) return false; int SIdx = AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::saddr); if (OpNo == SIdx) return true; int VIdx = AMDGPU::getNamedOperandIdx(UseMI.getOpcode(), AMDGPU::OpName::vaddr); return OpNo == VIdx && SIdx == -1; } FunctionPass *llvm::createSIFoldOperandsPass() { return new SIFoldOperands(); } static bool updateOperand(FoldCandidate &Fold, const SIInstrInfo &TII, const TargetRegisterInfo &TRI, const GCNSubtarget &ST) { MachineInstr *MI = Fold.UseMI; MachineOperand &Old = MI->getOperand(Fold.UseOpNo); assert(Old.isReg()); if (Fold.isImm()) { if (MI->getDesc().TSFlags & SIInstrFlags::IsPacked && !(MI->getDesc().TSFlags & SIInstrFlags::IsMAI) && AMDGPU::isFoldableLiteralV216(Fold.ImmToFold, ST.hasInv2PiInlineImm())) { // Set op_sel/op_sel_hi on this operand or bail out if op_sel is // already set. unsigned Opcode = MI->getOpcode(); int OpNo = MI->getOperandNo(&Old); int ModIdx = -1; if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src0)) ModIdx = AMDGPU::OpName::src0_modifiers; else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src1)) ModIdx = AMDGPU::OpName::src1_modifiers; else if (OpNo == AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::src2)) ModIdx = AMDGPU::OpName::src2_modifiers; assert(ModIdx != -1); ModIdx = AMDGPU::getNamedOperandIdx(Opcode, ModIdx); MachineOperand &Mod = MI->getOperand(ModIdx); unsigned Val = Mod.getImm(); if (!(Val & SISrcMods::OP_SEL_0) && (Val & SISrcMods::OP_SEL_1)) { // Only apply the following transformation if that operand requries // a packed immediate. switch (TII.get(Opcode).OpInfo[OpNo].OperandType) { case AMDGPU::OPERAND_REG_IMM_V2FP16: case AMDGPU::OPERAND_REG_IMM_V2INT16: case AMDGPU::OPERAND_REG_INLINE_C_V2FP16: case AMDGPU::OPERAND_REG_INLINE_C_V2INT16: // If upper part is all zero we do not need op_sel_hi. if (!isUInt<16>(Fold.ImmToFold)) { if (!(Fold.ImmToFold & 0xffff)) { Mod.setImm(Mod.getImm() | SISrcMods::OP_SEL_0); Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1); Old.ChangeToImmediate((Fold.ImmToFold >> 16) & 0xffff); return true; } Mod.setImm(Mod.getImm() & ~SISrcMods::OP_SEL_1); Old.ChangeToImmediate(Fold.ImmToFold & 0xffff); return true; } break; default: break; } } } } if ((Fold.isImm() || Fold.isFI() || Fold.isGlobal()) && Fold.needsShrink()) { MachineBasicBlock *MBB = MI->getParent(); auto Liveness = MBB->computeRegisterLiveness(&TRI, AMDGPU::VCC, MI, 16); if (Liveness != MachineBasicBlock::LQR_Dead) { LLVM_DEBUG(dbgs() << ""Not shrinking "" << MI << "" due to vcc liveness\\n""); return false; } MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo(); int Op32 = Fold.getShrinkOpcode(); MachineOperand &Dst0 = MI->getOperand(0); MachineOperand &Dst1 = MI->getOperand(1); assert(Dst0.isDef() && Dst1.isDef()); bool HaveNonDbgCarryUse = !MRI.use_nodbg_empty(Dst1.getReg()); const TargetRegisterClass *Dst0RC = MRI.getRegClass(Dst0.getReg()); Register NewReg0 = MRI.createVirtualRegister(Dst0RC); MachineInstr *Inst32 = TII.buildShrunkInst(*MI, Op32); if (HaveNonDbgCarryUse) { BuildMI(*MBB, MI, MI->getDebugLoc(), TII.get(AMDGPU::COPY), Dst1.getReg()) .addReg(AMDGPU::VCC, RegState::Kill); } // Keep the old instruction around to avoid breaking iterators, but // replace it with a dummy instruction to remove uses. // // FIXME: We should not invert how this pass looks at operands to avoid // this. Should track set of foldable movs instead of looking for uses // when looking at a use. Dst0.setReg(NewReg0); for (unsigned I = MI->getNumOperands() - 1; I > 0; --I) MI->RemoveOperand(I); MI->setDesc(TII.get(AMDGPU::IMPLICIT_DEF)); if (Fold.isCommuted()) TII.commuteInstruction(*Inst32, false); return true; } assert(!Fold.needsShrink() && ""not handled""); if (Fold.isImm()) { Old.ChangeToImmediate(Fold.ImmToFold); return true; } if (Fold.isGlobal()) { Old.ChangeToGA(Fold.OpToFold->getGlobal(), Fold.OpToFold->getOffset(), Fold.OpToFold->getTargetFlags()); return true; } if (Fold.isFI()) { Old.ChangeToFrameIndex(Fold.FrameIndexToFold); return true; } MachineOperand *New = Fold.OpToFold; Old.substVirtReg(New->getReg(), New->getSubReg(), TRI); Old.setIsUndef(New->isUndef()); return true; } static bool isUseMIInFoldList(ArrayRef FoldList, const MachineInstr *MI) { for (auto Candidate : FoldList) { if (Candidate.UseMI == MI) return true; } return false; } static void appendFoldCandidate(SmallVectorImpl &FoldList, MachineInstr *MI, unsigned OpNo, MachineOperand *FoldOp, bool Commuted = false, int ShrinkOp = -1) { // Skip additional folding on the same operand. for (FoldCandidate &Fold : FoldList) if (Fold.UseMI == MI && Fold.UseOpNo == OpNo) return; LLVM_DEBUG(dbgs() << ""Append "" << (Commuted ? ""commuted"" : ""normal"") << "" operand "" << OpNo << ""\\n "" << *MI << '\\n'); FoldList.push_back(FoldCandidate(MI, OpNo, FoldOp, Commuted, ShrinkOp)); } static bool tryAddToFoldList(SmallVectorImpl &FoldList, MachineInstr *MI, unsigned OpNo, MachineOperand *OpToFold, const SIInstrInfo *TII) { if (!TII->isOperandLegal(*MI, OpNo, OpToFold)) { // Special case for v_mac_{f16, f32}_e64 if we are trying to fold into src2 unsigned Opc = MI->getOpcode(); unsigned NewOpc = macToMad(Opc); if (NewOpc != AMDGPU::INSTRUCTION_LIST_END) { // Check if changing this to a v_mad_{f16, f32} instruction will allow us // to fold the operand. MI->setDesc(TII->get(NewOpc)); bool FoldAsMAD = tryAddToFoldList(FoldList, MI, OpNo, OpToFold, TII); if (FoldAsMAD) { MI->untieRegOperand(OpNo); return true; } MI->setDesc(TII->get(Opc)); } // Special case for s_setreg_b32 if (OpToFold->isImm()) { unsigned ImmOpc = 0; if (Opc == AMDGPU::S_SETREG_B32) ImmOpc = AMDGPU::S_SETREG_IMM32_B32; else if (Opc == AMDGPU::S_SETREG_B32_mode) ImmOpc = AMDGPU::S_SETREG_IMM32_B32_mode; if (ImmOpc) { MI->setDesc(TII->get(ImmOpc)); appendFoldCandidate(FoldList, MI, OpNo, OpToFold); return true; } } // If we are already folding into another operand of MI, then // we can't commute the instruction, otherwise we risk making the // other fold illegal. if (isUseMIInFoldList(FoldList, MI)) return false; unsigned CommuteOpNo = OpNo; // Operand is not legal, so try to commute the instruction to // see if this makes it possible to fold. unsigned CommuteIdx0 = TargetInstrInfo::CommuteAnyOperandIndex; unsigned CommuteIdx1 = TargetInstrInfo::CommuteAnyOperandIndex; bool CanCommute = TII->findCommutedOpIndices(*MI, CommuteIdx0, CommuteIdx1); if (CanCommute) { if (CommuteIdx0 == OpNo) CommuteOpNo = CommuteIdx1; else if (CommuteIdx1 == OpNo) CommuteOpNo = CommuteIdx0; } // One of operands might be an Imm operand, and OpNo may refer to it after // the call of commuteInstruction() below. Such situations are avoided // here explicitly as OpNo must be a register operand to be a candidate // for memory folding. if (CanCommute && (!MI->getOperand(CommuteIdx0).isReg() || !MI->getOperand(CommuteIdx1).isReg())) return false; if (!CanCommute || !TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1)) return false; if (!TII->isOperandLegal(*MI, CommuteOpNo, OpToFold)) { if ((Opc == AMDGPU::V_ADD_CO_U32_e64 || Opc == AMDGPU::V_SUB_CO_U32_e64 || Opc == AMDGPU::V_SUBREV_CO_U32_e64) && // FIXME (OpToFold->isImm() || OpToFold->isFI() || OpToFold->isGlobal())) { MachineRegisterInfo &MRI = MI->getParent()->getParent()->getRegInfo(); // Verify the other operand is a VGPR, otherwise we would violate the // constant bus restriction. unsigned OtherIdx = CommuteOpNo == CommuteIdx0 ? CommuteIdx1 : CommuteIdx0; MachineOperand &OtherOp = MI->getOperand(OtherIdx); if (!OtherOp.isReg() || !TII->getRegisterInfo().isVGPR(MRI, OtherOp.getReg())) return false; assert(MI->getOperand(1).isDef()); // Make sure to get the 32-bit version of the commuted opcode. unsigned MaybeCommutedOpc = MI->getOpcode(); int Op32 = AMDGPU::getVOPe32(MaybeCommutedOpc); appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true, Op32); return true; } TII->commuteInstruction(*MI, false, CommuteIdx0, CommuteIdx1); return false; } appendFoldCandidate(FoldList, MI, CommuteOpNo, OpToFold, true); return true; } // Check the case where we might introduce a second constant operand to a // scalar instruction if (TII->isSALU(MI->getOpcode())) { const MCInstrDesc &InstDesc = MI->getDesc(); const MCOperandInfo &OpInfo = InstDesc.OpInfo[OpNo]; const SIRegisterInfo &SRI = TII->getRegisterInfo(); // Fine if the operand can be encoded as an inline constant if (OpToFold->isImm()) { if (!SRI.opCanUseInlineConstant(OpInfo.OperandType) || !TII->isInlineConstant(*OpToFold, OpInfo)) { // Otherwise check for another constant for (unsigned i = 0, e = InstDesc.getNumOperands(); i != e; ++i) { auto &Op = MI->getOperand(i); if (OpNo != i && TII->isLiteralConstantLike(Op, OpInfo)) { return false; } } } } } appendFoldCandidate(FoldList, MI, OpNo, OpToFold); return true; } // If the use operand doesn't care about the value, this may be an operand only // used for register indexing, in which case it is unsafe to fold. static bool isUseSafeToFold(const SIInstrInfo *TII, const MachineInstr &MI, const MachineOperand &UseMO) { if (UseMO.isUndef() || TII->isSDWA(MI)) return false; switch (MI.getOpcode()) { case AMDGPU::V_MOV_B32_e32: case AMDGPU::V_MOV_B32_e64: case AMDGPU::V_MOV_B64_PSEUDO: // Do not fold into an indirect mov. return !MI.hasRegisterImplicitUseOperand(AMDGPU::M0); } return true; //return !MI.hasRegisterImplicitUseOperand(UseMO.getReg()); } // Find a def of the UseReg, check if it is a reg_seqence and find initializers // for each subreg, tracking it to foldable inline immediate if possible. // Returns true on success. static bool getRegSeqInit( SmallVectorImpl> &Defs, Register UseReg, uint8_t OpTy, const SIInstrInfo *TII, const MachineRegisterInfo &MRI) { MachineInstr *Def = MRI.getUniqueVRegDef(UseReg); if (!Def || !Def->isRegSequence()) return false; for (unsigned I = 1, E = Def->getNumExplicitOperands(); I < E; I += 2) { MachineOperand *Sub = &Def->getOperand(I); assert (Sub->isReg()); for (MachineInstr *SubDef = MRI.getUniqueVRegDef(Sub->getReg()); SubDef && Sub->isReg() && !Sub->getSubReg() && TII->isFoldableCopy(*SubDef); SubDef = MRI.getUniqueVRegDef(Sub->getReg())) { MachineOperand *Op = &SubDef->getOperand(1); if (Op->isImm()) { if (TII->isInlineConstant(*Op, OpTy)) Sub = Op; break; } if (!Op->isReg()) break; Sub = Op; } Defs.push_back(std::make_pair(Sub, Def->getOperand(I + 1).getImm())); } return true; } static bool tryToFoldACImm(const SIInstrInfo *TII, const MachineOperand &OpToFold, MachineInstr *UseMI, unsigned UseOpIdx, SmallVectorImpl &FoldList) { const MCInstrDesc &Desc = UseMI->getDesc(); const MCOperandInfo *OpInfo = Desc.OpInfo; if (!OpInfo || UseOpIdx >= Desc.getNumOperands()) return false; uint8_t OpTy = OpInfo[UseOpIdx].OperandType; if (OpTy < AMDGPU::OPERAND_REG_INLINE_AC_FIRST || OpTy > AMDGPU::OPERAND_REG_INLINE_AC_LAST) return false; if (OpToFold.isImm() && TII->isInlineConstant(OpToFold, OpTy) && TII->isOperandLegal(*UseMI, UseOpIdx, &OpToFold)) { UseMI->getOperand(UseOpIdx).ChangeToImmediate(OpToFold.getImm()); return true; } if (!OpToFold.isReg()) return false; Register UseReg = OpToFold.getReg(); if (!UseReg.isVirtual()) return false; if (llvm::any_of(FoldList, [UseMI](const FoldCandidate &FC) { return FC.UseMI == UseMI; })) return false; MachineRegisterInfo &MRI = UseMI->getParent()->getParent()->getRegInfo(); SmallVector, 32> Defs; if (!getRegSeqInit(Defs, UseReg, OpTy, TII, MRI)) return false; int32_t Imm; for (unsigned I = 0, E = Defs.size(); I != E; ++I) { const MachineOperand *Op = Defs[I].first; if (!Op->isImm()) return false; auto SubImm = Op->getImm(); if (!I) { Imm = SubImm; if (!TII->isInlineConstant(*Op, OpTy) || !TII->isOperandLegal(*UseMI, UseOpIdx, Op)) return false; continue; } if (Imm != SubImm) return false; // Can only fold splat constants } appendFoldCandidate(FoldList, UseMI, UseOpIdx, Defs[0].first); return true; } void SIFoldOperands::foldOperand( MachineOperand &OpToFold, MachineInstr *UseMI, int UseOpIdx, SmallVectorImpl &FoldList, SmallVectorImpl &CopiesToReplace) const { const MachineOperand &UseOp = UseMI->getOperand(UseOpIdx); if (!isUseSafeToFold(TII, *UseMI, UseOp)) return; // FIXME: Fold operands with subregs. if (UseOp.isReg() && OpToFold.isReg()) { if (UseOp.isImplicit() || UseOp.getSubReg() != AMDGPU::NoSubRegister) return; } // Special case for REG_SEQUENCE: We can't fold literals into // REG_SEQUENCE instructions, so we have to fold them into the // uses of REG_SEQUENCE. if (UseMI->isRegSequence()) { Register RegSeqDstReg = UseMI->getOperand(0).getReg(); unsigned RegSeqDstSubReg = UseMI->getOperand(UseOpIdx + 1).getImm(); MachineRegisterInfo::use_nodbg_iterator Next; for (MachineRegisterInfo::use_nodbg_iterator RSUse = MRI->use_nodbg_begin(RegSeqDstReg), RSE = MRI->use_nodbg_end(); RSUse != RSE; RSUse = Next) { Next = std::next(RSUse); MachineInstr *RSUseMI = RSUse->getParent(); if (tryToFoldACImm(TII, UseMI->getOperand(0), RSUseMI, RSUse.getOperandNo(), FoldList)) continue; if (RSUse->getSubReg() != RegSeqDstSubReg) continue; foldOperand(OpToFold, RSUseMI, RSUse.getOperandNo(), FoldList, CopiesToReplace); } return; } if (tryToFoldACImm(TII, OpToFold, UseMI, UseOpIdx, FoldList)) return; if (frameIndexMayFold(TII, *UseMI, UseOpIdx, OpToFold)) { // Sanity check that this is a stack access. // FIXME: Should probably use stack pseudos before frame lowering. if (TII->isMUBUF(*UseMI)) { if (TII->getNamedOperand(*UseMI, AMDGPU::OpName::srsrc)->getReg() != MFI->getScratchRSrcReg()) return; // Ensure this is either relative to the current frame or the current // wave. MachineOperand &SOff = *TII->getNamedOperand(*UseMI, AMDGPU::OpName::soffset); if (!SOff.isImm() || SOff.getImm() != 0) return; } // A frame index will resolve to a positive constant, so it should always be // safe to fold the addressing mode, even pre-GFX9. UseMI->getOperand(UseOpIdx).ChangeToFrameIndex(OpToFold.getIndex()); if (TII->isFLATScratch(*UseMI) && AMDGPU::getNamedOperandIdx(UseMI->getOpcode(), AMDGPU::OpName::vaddr) != -1) { unsigned NewOpc = AMDGPU::getFlatScratchInstSSfromSV(UseMI->getOpcode()); UseMI->setDesc(TII->get(NewOpc)); } return; } bool FoldingImmLike = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); if (FoldingImmLike && UseMI->isCopy()) { Register DestReg = UseMI->getOperand(0).getReg(); Register SrcReg = UseMI->getOperand(1).getReg(); assert(SrcReg.isVirtual()); const TargetRegisterClass *SrcRC = MRI->getRegClass(SrcReg); // Don't fold into a copy to a physical register with the same class. Doing // so would interfere with the register coalescer's logic which would avoid // redundant initalizations. if (DestReg.isPhysical() && SrcRC->contains(DestReg)) return; const TargetRegisterClass *DestRC = TRI->getRegClassForReg(*MRI, DestReg); if (!DestReg.isPhysical()) { if (TRI->isSGPRClass(SrcRC) && TRI->hasVectorRegisters(DestRC)) { MachineRegisterInfo::use_nodbg_iterator NextUse; SmallVector CopyUses; for (MachineRegisterInfo::use_nodbg_iterator Use = MRI->use_nodbg_begin(DestReg), E = MRI->use_nodbg_end(); Use != E; Use = NextUse) { NextUse = std::next(Use); // There's no point trying to fold into an implicit operand. if (Use->isImplicit()) continue; FoldCandidate FC = FoldCandidate(Use->getParent(), Use.getOperandNo(), &UseMI->getOperand(1)); CopyUses.push_back(FC); } for (auto &F : CopyUses) { foldOperand(*F.OpToFold, F.UseMI, F.UseOpNo, FoldList, CopiesToReplace); } } if (DestRC == &AMDGPU::AGPR_32RegClass && TII->isInlineConstant(OpToFold, AMDGPU::OPERAND_REG_INLINE_C_INT32)) { UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64)); UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm()); CopiesToReplace.push_back(UseMI); return; } } // In order to fold immediates into copies, we need to change the // copy to a MOV. unsigned MovOp = TII->getMovOpcode(DestRC); if (MovOp == AMDGPU::COPY) return; UseMI->setDesc(TII->get(MovOp)); MachineInstr::mop_iterator ImpOpI = UseMI->implicit_operands().begin(); MachineInstr::mop_iterator ImpOpE = UseMI->implicit_operands().end(); while (ImpOpI != ImpOpE) { MachineInstr::mop_iterator Tmp = ImpOpI; ImpOpI++; UseMI->RemoveOperand(UseMI->getOperandNo(Tmp)); } CopiesToReplace.push_back(UseMI); } else { if (UseMI->isCopy() && OpToFold.isReg() && UseMI->getOperand(0).getReg().isVirtual() && !UseMI->getOperand(1).getSubReg()) { LLVM_DEBUG(dbgs() << ""Folding "" << OpToFold << ""\\n into "" << *UseMI << '\\n'); unsigned Size = TII->getOpSize(*UseMI, 1); Register UseReg = OpToFold.getReg(); UseMI->getOperand(1).setReg(UseReg); UseMI->getOperand(1).setSubReg(OpToFold.getSubReg()); UseMI->getOperand(1).setIsKill(false); CopiesToReplace.push_back(UseMI); OpToFold.setIsKill(false); // That is very tricky to store a value into an AGPR. v_accvgpr_write_b32 // can only accept VGPR or inline immediate. Recreate a reg_sequence with // its initializers right here, so we will rematerialize immediates and // avoid copies via different reg classes. SmallVector, 32> Defs; if (Size > 4 && TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) && getRegSeqInit(Defs, UseReg, AMDGPU::OPERAND_REG_INLINE_C_INT32, TII, *MRI)) { const DebugLoc &DL = UseMI->getDebugLoc(); MachineBasicBlock &MBB = *UseMI->getParent(); UseMI->setDesc(TII->get(AMDGPU::REG_SEQUENCE)); for (unsigned I = UseMI->getNumOperands() - 1; I > 0; --I) UseMI->RemoveOperand(I); MachineInstrBuilder B(*MBB.getParent(), UseMI); DenseMap VGPRCopies; SmallSetVector SeenAGPRs; for (unsigned I = 0; I < Size / 4; ++I) { MachineOperand *Def = Defs[I].first; TargetInstrInfo::RegSubRegPair CopyToVGPR; if (Def->isImm() && TII->isInlineConstant(*Def, AMDGPU::OPERAND_REG_INLINE_C_INT32)) { int64_t Imm = Def->getImm(); auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass); BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addImm(Imm); B.addReg(Tmp); } else if (Def->isReg() && TRI->isAGPR(*MRI, Def->getReg())) { auto Src = getRegSubRegPair(*Def); Def->setIsKill(false); if (!SeenAGPRs.insert(Src)) { // We cannot build a reg_sequence out of the same registers, they // must be copied. Better do it here before copyPhysReg() created // several reads to do the AGPR->VGPR->AGPR copy. CopyToVGPR = Src; } else { B.addReg(Src.Reg, Def->isUndef() ? RegState::Undef : 0, Src.SubReg); } } else { assert(Def->isReg()); Def->setIsKill(false); auto Src = getRegSubRegPair(*Def); // Direct copy from SGPR to AGPR is not possible. To avoid creation // of exploded copies SGPR->VGPR->AGPR in the copyPhysReg() later, // create a copy here and track if we already have such a copy. if (TRI->isSGPRReg(*MRI, Src.Reg)) { CopyToVGPR = Src; } else { auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass); BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Tmp).add(*Def); B.addReg(Tmp); } } if (CopyToVGPR.Reg) { Register Vgpr; if (VGPRCopies.count(CopyToVGPR)) { Vgpr = VGPRCopies[CopyToVGPR]; } else { Vgpr = MRI->createVirtualRegister(&AMDGPU::VGPR_32RegClass); BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::COPY), Vgpr).add(*Def); VGPRCopies[CopyToVGPR] = Vgpr; } auto Tmp = MRI->createVirtualRegister(&AMDGPU::AGPR_32RegClass); BuildMI(MBB, UseMI, DL, TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64), Tmp).addReg(Vgpr); B.addReg(Tmp); } B.addImm(Defs[I].second); } LLVM_DEBUG(dbgs() << ""Folded "" << *UseMI << '\\n'); return; } if (Size != 4) return; if (TRI->isAGPR(*MRI, UseMI->getOperand(0).getReg()) && TRI->isVGPR(*MRI, UseMI->getOperand(1).getReg())) UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_WRITE_B32_e64)); else if (TRI->isVGPR(*MRI, UseMI->getOperand(0).getReg()) && TRI->isAGPR(*MRI, UseMI->getOperand(1).getReg())) UseMI->setDesc(TII->get(AMDGPU::V_ACCVGPR_READ_B32_e64)); return; } unsigned UseOpc = UseMI->getOpcode(); if (UseOpc == AMDGPU::V_READFIRSTLANE_B32 || (UseOpc == AMDGPU::V_READLANE_B32 && (int)UseOpIdx == AMDGPU::getNamedOperandIdx(UseOpc, AMDGPU::OpName::src0))) { // %vgpr = V_MOV_B32 imm // %sgpr = V_READFIRSTLANE_B32 %vgpr // => // %sgpr = S_MOV_B32 imm if (FoldingImmLike) { if (execMayBeModifiedBeforeUse(*MRI, UseMI->getOperand(UseOpIdx).getReg(), *OpToFold.getParent(), *UseMI)) return; UseMI->setDesc(TII->get(AMDGPU::S_MOV_B32)); if (OpToFold.isImm()) UseMI->getOperand(1).ChangeToImmediate(OpToFold.getImm()); else UseMI->getOperand(1).ChangeToFrameIndex(OpToFold.getIndex()); UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane) return; } if (OpToFold.isReg() && TRI->isSGPRReg(*MRI, OpToFold.getReg())) { if (execMayBeModifiedBeforeUse(*MRI, UseMI->getOperand(UseOpIdx).getReg(), *OpToFold.getParent(), *UseMI)) return; // %vgpr = COPY %sgpr0 // %sgpr1 = V_READFIRSTLANE_B32 %vgpr // => // %sgpr1 = COPY %sgpr0 UseMI->setDesc(TII->get(AMDGPU::COPY)); UseMI->getOperand(1).setReg(OpToFold.getReg()); UseMI->getOperand(1).setSubReg(OpToFold.getSubReg()); UseMI->getOperand(1).setIsKill(false); UseMI->RemoveOperand(2); // Remove exec read (or src1 for readlane) return; } } const MCInstrDesc &UseDesc = UseMI->getDesc(); // Don't fold into target independent nodes. Target independent opcodes // don't have defined register classes. if (UseDesc.isVariadic() || UseOp.isImplicit() || UseDesc.OpInfo[UseOpIdx].RegClass == -1) return; } if (!FoldingImmLike) { tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII); // FIXME: We could try to change the instruction from 64-bit to 32-bit // to enable more folding opportunites. The shrink operands pass // already does this. return; } const MCInstrDesc &FoldDesc = OpToFold.getParent()->getDesc(); const TargetRegisterClass *FoldRC = TRI->getRegClass(FoldDesc.OpInfo[0].RegClass); // Split 64-bit constants into 32-bits for folding. if (UseOp.getSubReg() && AMDGPU::getRegBitWidth(FoldRC->getID()) == 64) { Register UseReg = UseOp.getReg(); const TargetRegisterClass *UseRC = MRI->getRegClass(UseReg); if (AMDGPU::getRegBitWidth(UseRC->getID()) != 64) return; APInt Imm(64, OpToFold.getImm()); if (UseOp.getSubReg() == AMDGPU::sub0) { Imm = Imm.getLoBits(32); } else { assert(UseOp.getSubReg() == AMDGPU::sub1); Imm = Imm.getHiBits(32); } MachineOperand ImmOp = MachineOperand::CreateImm(Imm.getSExtValue()); tryAddToFoldList(FoldList, UseMI, UseOpIdx, &ImmOp, TII); return; } tryAddToFoldList(FoldList, UseMI, UseOpIdx, &OpToFold, TII); } static bool evalBinaryInstruction(unsigned Opcode, int32_t &Result, uint32_t LHS, uint32_t RHS) { switch (Opcode) { case AMDGPU::V_AND_B32_e64: case AMDGPU::V_AND_B32_e32: case AMDGPU::S_AND_B32: Result = LHS & RHS; return true; case AMDGPU::V_OR_B32_e64: case AMDGPU::V_OR_B32_e32: case AMDGPU::S_OR_B32: Result = LHS | RHS; return true; case AMDGPU::V_XOR_B32_e64: case AMDGPU::V_XOR_B32_e32: case AMDGPU::S_XOR_B32: Result = LHS ^ RHS; return true; case AMDGPU::S_XNOR_B32: Result = ~(LHS ^ RHS); return true; case AMDGPU::S_NAND_B32: Result = ~(LHS & RHS); return true; case AMDGPU::S_NOR_B32: Result = ~(LHS | RHS); return true; case AMDGPU::S_ANDN2_B32: Result = LHS & ~RHS; return true; case AMDGPU::S_ORN2_B32: Result = LHS | ~RHS; return true; case AMDGPU::V_LSHL_B32_e64: case AMDGPU::V_LSHL_B32_e32: case AMDGPU::S_LSHL_B32: // The instruction ignores the high bits for out of bounds shifts. Result = LHS << (RHS & 31); return true; case AMDGPU::V_LSHLREV_B32_e64: case AMDGPU::V_LSHLREV_B32_e32: Result = RHS << (LHS & 31); return true; case AMDGPU::V_LSHR_B32_e64: case AMDGPU::V_LSHR_B32_e32: case AMDGPU::S_LSHR_B32: Result = LHS >> (RHS & 31); return true; case AMDGPU::V_LSHRREV_B32_e64: case AMDGPU::V_LSHRREV_B32_e32: Result = RHS >> (LHS & 31); return true; case AMDGPU::V_ASHR_I32_e64: case AMDGPU::V_ASHR_I32_e32: case AMDGPU::S_ASHR_I32: Result = static_cast(LHS) >> (RHS & 31); return true; case AMDGPU::V_ASHRREV_I32_e64: case AMDGPU::V_ASHRREV_I32_e32: Result = static_cast(RHS) >> (LHS & 31); return true; default: return false; } } static unsigned getMovOpc(bool IsScalar) { return IsScalar ? AMDGPU::S_MOV_B32 : AMDGPU::V_MOV_B32_e32; } /// Remove any leftover implicit operands from mutating the instruction. e.g. /// if we replace an s_and_b32 with a copy, we don't need the implicit scc def /// anymore. static void stripExtraCopyOperands(MachineInstr &MI) { const MCInstrDesc &Desc = MI.getDesc(); unsigned NumOps = Desc.getNumOperands() + Desc.getNumImplicitUses() + Desc.getNumImplicitDefs(); for (unsigned I = MI.getNumOperands() - 1; I >= NumOps; --I) MI.RemoveOperand(I); } static void mutateCopyOp(MachineInstr &MI, const MCInstrDesc &NewDesc) { MI.setDesc(NewDesc); stripExtraCopyOperands(MI); } static MachineOperand *getImmOrMaterializedImm(MachineRegisterInfo &MRI, MachineOperand &Op) { if (Op.isReg()) { // If this has a subregister, it obviously is a register source. if (Op.getSubReg() != AMDGPU::NoSubRegister || !Op.getReg().isVirtual()) return &Op; MachineInstr *Def = MRI.getVRegDef(Op.getReg()); if (Def && Def->isMoveImmediate()) { MachineOperand &ImmSrc = Def->getOperand(1); if (ImmSrc.isImm()) return &ImmSrc; } } return &Op; } // Try to simplify operations with a constant that may appear after instruction // selection. // TODO: See if a frame index with a fixed offset can fold. static bool tryConstantFoldOp(MachineRegisterInfo &MRI, const SIInstrInfo *TII, MachineInstr *MI, MachineOperand *ImmOp) { unsigned Opc = MI->getOpcode(); if (Opc == AMDGPU::V_NOT_B32_e64 || Opc == AMDGPU::V_NOT_B32_e32 || Opc == AMDGPU::S_NOT_B32) { MI->getOperand(1).ChangeToImmediate(~ImmOp->getImm()); mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_NOT_B32))); return true; } int Src1Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1); if (Src1Idx == -1) return false; int Src0Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0); MachineOperand *Src0 = getImmOrMaterializedImm(MRI, MI->getOperand(Src0Idx)); MachineOperand *Src1 = getImmOrMaterializedImm(MRI, MI->getOperand(Src1Idx)); if (!Src0->isImm() && !Src1->isImm()) return false; // and k0, k1 -> v_mov_b32 (k0 & k1) // or k0, k1 -> v_mov_b32 (k0 | k1) // xor k0, k1 -> v_mov_b32 (k0 ^ k1) if (Src0->isImm() && Src1->isImm()) { int32_t NewImm; if (!evalBinaryInstruction(Opc, NewImm, Src0->getImm(), Src1->getImm())) return false; const SIRegisterInfo &TRI = TII->getRegisterInfo(); bool IsSGPR = TRI.isSGPRReg(MRI, MI->getOperand(0).getReg()); // Be careful to change the right operand, src0 may belong to a different // instruction. MI->getOperand(Src0Idx).ChangeToImmediate(NewImm); MI->RemoveOperand(Src1Idx); mutateCopyOp(*MI, TII->get(getMovOpc(IsSGPR))); return true; } if (!MI->isCommutable()) return false; if (Src0->isImm() && !Src1->isImm()) { std::swap(Src0, Src1); std::swap(Src0Idx, Src1Idx); } int32_t Src1Val = static_cast(Src1->getImm()); if (Opc == AMDGPU::V_OR_B32_e64 || Opc == AMDGPU::V_OR_B32_e32 || Opc == AMDGPU::S_OR_B32) { if (Src1Val == 0) { // y = or x, 0 => y = copy x MI->RemoveOperand(Src1Idx); mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); } else if (Src1Val == -1) { // y = or x, -1 => y = v_mov_b32 -1 MI->RemoveOperand(Src1Idx); mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_OR_B32))); } else return false; return true; } if (MI->getOpcode() == AMDGPU::V_AND_B32_e64 || MI->getOpcode() == AMDGPU::V_AND_B32_e32 || MI->getOpcode() == AMDGPU::S_AND_B32) { if (Src1Val == 0) { // y = and x, 0 => y = v_mov_b32 0 MI->RemoveOperand(Src0Idx); mutateCopyOp(*MI, TII->get(getMovOpc(Opc == AMDGPU::S_AND_B32))); } else if (Src1Val == -1) { // y = and x, -1 => y = copy x MI->RemoveOperand(Src1Idx); mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); stripExtraCopyOperands(*MI); } else return false; return true; } if (MI->getOpcode() == AMDGPU::V_XOR_B32_e64 || MI->getOpcode() == AMDGPU::V_XOR_B32_e32 || MI->getOpcode() == AMDGPU::S_XOR_B32) { if (Src1Val == 0) { // y = xor x, 0 => y = copy x MI->RemoveOperand(Src1Idx); mutateCopyOp(*MI, TII->get(AMDGPU::COPY)); return true; } } return false; } // Try to fold an instruction into a simpler one static bool tryFoldInst(const SIInstrInfo *TII, MachineInstr *MI) { unsigned Opc = MI->getOpcode(); if (Opc == AMDGPU::V_CNDMASK_B32_e32 || Opc == AMDGPU::V_CNDMASK_B32_e64 || Opc == AMDGPU::V_CNDMASK_B64_PSEUDO) { const MachineOperand *Src0 = TII->getNamedOperand(*MI, AMDGPU::OpName::src0); const MachineOperand *Src1 = TII->getNamedOperand(*MI, AMDGPU::OpName::src1); int Src1ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1_modifiers); int Src0ModIdx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0_modifiers); if (Src1->isIdenticalTo(*Src0) && (Src1ModIdx == -1 || !MI->getOperand(Src1ModIdx).getImm()) && (Src0ModIdx == -1 || !MI->getOperand(Src0ModIdx).getImm())) { LLVM_DEBUG(dbgs() << ""Folded "" << *MI << "" into ""); auto &NewDesc = TII->get(Src0->isReg() ? (unsigned)AMDGPU::COPY : getMovOpc(false)); int Src2Idx = AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src2); if (Src2Idx != -1) MI->RemoveOperand(Src2Idx); MI->RemoveOperand(AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1)); if (Src1ModIdx != -1) MI->RemoveOperand(Src1ModIdx); if (Src0ModIdx != -1) MI->RemoveOperand(Src0ModIdx); mutateCopyOp(*MI, NewDesc); LLVM_DEBUG(dbgs() << *MI << '\\n'); return true; } } return false; } void SIFoldOperands::foldInstOperand(MachineInstr &MI, MachineOperand &OpToFold) const { // We need mutate the operands of new mov instructions to add implicit // uses of EXEC, but adding them invalidates the use_iterator, so defer // this. SmallVector CopiesToReplace; SmallVector FoldList; MachineOperand &Dst = MI.getOperand(0); bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); if (FoldingImm) { unsigned NumLiteralUses = 0; MachineOperand *NonInlineUse = nullptr; int NonInlineUseOpNo = -1; MachineRegisterInfo::use_nodbg_iterator NextUse; for (MachineRegisterInfo::use_nodbg_iterator Use = MRI->use_nodbg_begin(Dst.getReg()), E = MRI->use_nodbg_end(); Use != E; Use = NextUse) { NextUse = std::next(Use); MachineInstr *UseMI = Use->getParent(); unsigned OpNo = Use.getOperandNo(); // Folding the immediate may reveal operations that can be constant // folded or replaced with a copy. This can happen for example after // frame indices are lowered to constants or from splitting 64-bit // constants. // // We may also encounter cases where one or both operands are // immediates materialized into a register, which would ordinarily not // be folded due to multiple uses or operand constraints. if (OpToFold.isImm() && tryConstantFoldOp(*MRI, TII, UseMI, &OpToFold)) { LLVM_DEBUG(dbgs() << ""Constant folded "" << *UseMI << '\\n'); // Some constant folding cases change the same immediate's use to a new // instruction, e.g. and x, 0 -> 0. Make sure we re-visit the user // again. The same constant folded instruction could also have a second // use operand. NextUse = MRI->use_nodbg_begin(Dst.getReg()); FoldList.clear(); continue; } // Try to fold any inline immediate uses, and then only fold other // constants if they have one use. // // The legality of the inline immediate must be checked based on the use // operand, not the defining instruction, because 32-bit instructions // with 32-bit inline immediate sources may be used to materialize // constants used in 16-bit operands. // // e.g. it is unsafe to fold: // s_mov_b32 s0, 1.0 // materializes 0x3f800000 // v_add_f16 v0, v1, s0 // 1.0 f16 inline immediate sees 0x00003c00 // Folding immediates with more than one use will increase program size. // FIXME: This will also reduce register usage, which may be better // in some cases. A better heuristic is needed. if (isInlineConstantIfFolded(TII, *UseMI, OpNo, OpToFold)) { foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace); } else if (frameIndexMayFold(TII, *UseMI, OpNo, OpToFold)) { foldOperand(OpToFold, UseMI, OpNo, FoldList, CopiesToReplace); } else { if (++NumLiteralUses == 1) { NonInlineUse = &*Use; NonInlineUseOpNo = OpNo; } } } if (NumLiteralUses == 1) { MachineInstr *UseMI = NonInlineUse->getParent(); foldOperand(OpToFold, UseMI, NonInlineUseOpNo, FoldList, CopiesToReplace); } } else { // Folding register. SmallVector UsesToProcess; for (MachineRegisterInfo::use_nodbg_iterator Use = MRI->use_nodbg_begin(Dst.getReg()), E = MRI->use_nodbg_end(); Use != E; ++Use) { UsesToProcess.push_back(Use); } for (auto U : UsesToProcess) { MachineInstr *UseMI = U->getParent(); foldOperand(OpToFold, UseMI, U.getOperandNo(), FoldList, CopiesToReplace); } } MachineFunction *MF = MI.getParent()->getParent(); // Make sure we add EXEC uses to any new v_mov instructions created. for (MachineInstr *Copy : CopiesToReplace) Copy->addImplicitDefUseOperands(*MF); SmallPtrSet Folded; for (FoldCandidate &Fold : FoldList) { assert(!Fold.isReg() || Fold.OpToFold); if (Folded.count(Fold.UseMI)) continue; if (Fold.isReg() && Fold.OpToFold->getReg().isVirtual()) { Register Reg = Fold.OpToFold->getReg(); MachineInstr *DefMI = Fold.OpToFold->getParent(); if (DefMI->readsRegister(AMDGPU::EXEC, TRI) && execMayBeModifiedBeforeUse(*MRI, Reg, *DefMI, *Fold.UseMI)) continue; } if (updateOperand(Fold, *TII, *TRI, *ST)) { // Clear kill flags. if (Fold.isReg()) { assert(Fold.OpToFold && Fold.OpToFold->isReg()); // FIXME: Probably shouldn't bother trying to fold if not an // SGPR. PeepholeOptimizer can eliminate redundant VGPR->VGPR // copies. MRI->clearKillFlags(Fold.OpToFold->getReg()); } LLVM_DEBUG(dbgs() << ""Folded source from "" << MI << "" into OpNo "" << static_cast(Fold.UseOpNo) << "" of "" << *Fold.UseMI << '\\n'); if (tryFoldInst(TII, Fold.UseMI)) Folded.insert(Fold.UseMI); } else if (Fold.isCommuted()) { // Restoring instruction's original operand order if fold has failed. TII->commuteInstruction(*Fold.UseMI, false); } } } // Clamp patterns are canonically selected to v_max_* instructions, so only // handle them. const MachineOperand *SIFoldOperands::isClamp(const MachineInstr &MI) const { unsigned Op = MI.getOpcode(); switch (Op) { case AMDGPU::V_MAX_F32_e64: case AMDGPU::V_MAX_F16_e64: case AMDGPU::V_MAX_F64_e64: case AMDGPU::V_PK_MAX_F16: { if (!TII->getNamedOperand(MI, AMDGPU::OpName::clamp)->getImm()) return nullptr; // Make sure sources are identical. const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (!Src0->isReg() || !Src1->isReg() || Src0->getReg() != Src1->getReg() || Src0->getSubReg() != Src1->getSubReg() || Src0->getSubReg() != AMDGPU::NoSubRegister) return nullptr; // Can't fold up if we have modifiers. if (TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) return nullptr; unsigned Src0Mods = TII->getNamedOperand(MI, AMDGPU::OpName::src0_modifiers)->getImm(); unsigned Src1Mods = TII->getNamedOperand(MI, AMDGPU::OpName::src1_modifiers)->getImm(); // Having a 0 op_sel_hi would require swizzling the output in the source // instruction, which we can't do. unsigned UnsetMods = (Op == AMDGPU::V_PK_MAX_F16) ? SISrcMods::OP_SEL_1 : 0u; if (Src0Mods != UnsetMods && Src1Mods != UnsetMods) return nullptr; return Src0; } default: return nullptr; } } // We obviously have multiple uses in a clamp since the register is used twice // in the same instruction. static bool hasOneNonDBGUseInst(const MachineRegisterInfo &MRI, unsigned Reg) { int Count = 0; for (auto I = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end(); I != E; ++I) { if (++Count > 1) return false; } return true; } // FIXME: Clamp for v_mad_mixhi_f16 handled during isel. bool SIFoldOperands::tryFoldClamp(MachineInstr &MI) { const MachineOperand *ClampSrc = isClamp(MI); if (!ClampSrc || !hasOneNonDBGUseInst(*MRI, ClampSrc->getReg())) return false; MachineInstr *Def = MRI->getVRegDef(ClampSrc->getReg()); // The type of clamp must be compatible. if (TII->getClampMask(*Def) != TII->getClampMask(MI)) return false; MachineOperand *DefClamp = TII->getNamedOperand(*Def, AMDGPU::OpName::clamp); if (!DefClamp) return false; LLVM_DEBUG(dbgs() << ""Folding clamp "" << *DefClamp << "" into "" << *Def << '\\n'); // Clamp is applied after omod, so it is OK if omod is set. DefClamp->setImm(1); MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg()); MI.eraseFromParent(); return true; } static int getOModValue(unsigned Opc, int64_t Val) { switch (Opc) { case AMDGPU::V_MUL_F32_e64: { switch (static_cast(Val)) { case 0x3f000000: // 0.5 return SIOutMods::DIV2; case 0x40000000: // 2.0 return SIOutMods::MUL2; case 0x40800000: // 4.0 return SIOutMods::MUL4; default: return SIOutMods::NONE; } } case AMDGPU::V_MUL_F16_e64: { switch (static_cast(Val)) { case 0x3800: // 0.5 return SIOutMods::DIV2; case 0x4000: // 2.0 return SIOutMods::MUL2; case 0x4400: // 4.0 return SIOutMods::MUL4; default: return SIOutMods::NONE; } } default: llvm_unreachable(""invalid mul opcode""); } } // FIXME: Does this really not support denormals with f16? // FIXME: Does this need to check IEEE mode bit? SNaNs are generally not // handled, so will anything other than that break? std::pair SIFoldOperands::isOMod(const MachineInstr &MI) const { unsigned Op = MI.getOpcode(); switch (Op) { case AMDGPU::V_MUL_F32_e64: case AMDGPU::V_MUL_F16_e64: { // If output denormals are enabled, omod is ignored. if ((Op == AMDGPU::V_MUL_F32_e64 && MFI->getMode().FP32OutputDenormals) || (Op == AMDGPU::V_MUL_F16_e64 && MFI->getMode().FP64FP16OutputDenormals)) return std::make_pair(nullptr, SIOutMods::NONE); const MachineOperand *RegOp = nullptr; const MachineOperand *ImmOp = nullptr; const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (Src0->isImm()) { ImmOp = Src0; RegOp = Src1; } else if (Src1->isImm()) { ImmOp = Src1; RegOp = Src0; } else return std::make_pair(nullptr, SIOutMods::NONE); int OMod = getOModValue(Op, ImmOp->getImm()); if (OMod == SIOutMods::NONE || TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) || TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) || TII->hasModifiersSet(MI, AMDGPU::OpName::omod) || TII->hasModifiersSet(MI, AMDGPU::OpName::clamp)) return std::make_pair(nullptr, SIOutMods::NONE); return std::make_pair(RegOp, OMod); } case AMDGPU::V_ADD_F32_e64: case AMDGPU::V_ADD_F16_e64: { // If output denormals are enabled, omod is ignored. if ((Op == AMDGPU::V_ADD_F32_e64 && MFI->getMode().FP32OutputDenormals) || (Op == AMDGPU::V_ADD_F16_e64 && MFI->getMode().FP64FP16OutputDenormals)) return std::make_pair(nullptr, SIOutMods::NONE); // Look through the DAGCombiner canonicalization fmul x, 2 -> fadd x, x const MachineOperand *Src0 = TII->getNamedOperand(MI, AMDGPU::OpName::src0); const MachineOperand *Src1 = TII->getNamedOperand(MI, AMDGPU::OpName::src1); if (Src0->isReg() && Src1->isReg() && Src0->getReg() == Src1->getReg() && Src0->getSubReg() == Src1->getSubReg() && !TII->hasModifiersSet(MI, AMDGPU::OpName::src0_modifiers) && !TII->hasModifiersSet(MI, AMDGPU::OpName::src1_modifiers) && !TII->hasModifiersSet(MI, AMDGPU::OpName::clamp) && !TII->hasModifiersSet(MI, AMDGPU::OpName::omod)) return std::make_pair(Src0, SIOutMods::MUL2); return std::make_pair(nullptr, SIOutMods::NONE); } default: return std::make_pair(nullptr, SIOutMods::NONE); } } // FIXME: Does this need to check IEEE bit on function? bool SIFoldOperands::tryFoldOMod(MachineInstr &MI) { const MachineOperand *RegOp; int OMod; std::tie(RegOp, OMod) = isOMod(MI); if (OMod == SIOutMods::NONE || !RegOp->isReg() || RegOp->getSubReg() != AMDGPU::NoSubRegister || !hasOneNonDBGUseInst(*MRI, RegOp->getReg())) return false; MachineInstr *Def = MRI->getVRegDef(RegOp->getReg()); MachineOperand *DefOMod = TII->getNamedOperand(*Def, AMDGPU::OpName::omod); if (!DefOMod || DefOMod->getImm() != SIOutMods::NONE) return false; // Clamp is applied after omod. If the source already has clamp set, don't // fold it. if (TII->hasModifiersSet(*Def, AMDGPU::OpName::clamp)) return false; LLVM_DEBUG(dbgs() << ""Folding omod "" << MI << "" into "" << *Def << '\\n'); DefOMod->setImm(OMod); MRI->replaceRegWith(MI.getOperand(0).getReg(), Def->getOperand(0).getReg()); MI.eraseFromParent(); return true; } bool SIFoldOperands::runOnMachineFunction(MachineFunction &MF) { if (skipFunction(MF.getFunction())) return false; MRI = &MF.getRegInfo(); ST = &MF.getSubtarget(); TII = ST->getInstrInfo(); TRI = &TII->getRegisterInfo(); MFI = MF.getInfo(); // omod is ignored by hardware if IEEE bit is enabled. omod also does not // correctly handle signed zeros. // // FIXME: Also need to check strictfp bool IsIEEEMode = MFI->getMode().IEEE; bool HasNSZ = MFI->hasNoSignedZerosFPMath(); for (MachineBasicBlock *MBB : depth_first(&MF)) { MachineBasicBlock::iterator I, Next; MachineOperand *CurrentKnownM0Val = nullptr; for (I = MBB->begin(); I != MBB->end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; tryFoldInst(TII, &MI); if (!TII->isFoldableCopy(MI)) { // Saw an unknown clobber of m0, so we no longer know what it is. if (CurrentKnownM0Val && MI.modifiesRegister(AMDGPU::M0, TRI)) CurrentKnownM0Val = nullptr; // TODO: Omod might be OK if there is NSZ only on the source // instruction, and not the omod multiply. if (IsIEEEMode || (!HasNSZ && !MI.getFlag(MachineInstr::FmNsz)) || !tryFoldOMod(MI)) tryFoldClamp(MI); continue; } // Specially track simple redefs of m0 to the same value in a block, so we // can erase the later ones. if (MI.getOperand(0).getReg() == AMDGPU::M0) { MachineOperand &NewM0Val = MI.getOperand(1); if (CurrentKnownM0Val && CurrentKnownM0Val->isIdenticalTo(NewM0Val)) { MI.eraseFromParent(); continue; } // We aren't tracking other physical registers CurrentKnownM0Val = (NewM0Val.isReg() && NewM0Val.getReg().isPhysical()) ? nullptr : &NewM0Val; continue; } MachineOperand &OpToFold = MI.getOperand(1); bool FoldingImm = OpToFold.isImm() || OpToFold.isFI() || OpToFold.isGlobal(); // FIXME: We could also be folding things like TargetIndexes. if (!FoldingImm && !OpToFold.isReg()) continue; if (OpToFold.isReg() && !OpToFold.getReg().isVirtual()) continue; // Prevent folding operands backwards in the function. For example, // the COPY opcode must not be replaced by 1 in this example: // // %3 = COPY %vgpr0; VGPR_32:%3 // ... // %vgpr0 = V_MOV_B32_e32 1, implicit %exec MachineOperand &Dst = MI.getOperand(0); if (Dst.isReg() && !Dst.getReg().isVirtual()) continue; foldInstOperand(MI, OpToFold); } } return true; } ",16316,True,3352.644354688488,median "// Copyright (c) 2015-2019, Satoshi Tanda. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. /// @file /// Implements VMM functions. #include ""vmm.h"" #include #include ""asm.h"" #include ""common.h"" #include ""ept.h"" #include ""log.h"" #include ""util.h"" #include ""performance.h"" extern ""C"" { //////////////////////////////////////////////////////////////////////////////// // // macro utilities // //////////////////////////////////////////////////////////////////////////////// // // constants and macros // // Whether VM-exit recording is enabled static const bool kVmmpEnableRecordVmExit = false; // How many events should be recorded per a processor static const long kVmmpNumberOfRecords = 100; // How many processors are supported for recording static const long kVmmpNumberOfProcessors = 2; //////////////////////////////////////////////////////////////////////////////// // // types // // Represents raw structure of stack of VMM when VmmVmExitHandler() is called struct VmmInitialStack { GpRegisters gp_regs; KtrapFrame trap_frame; ProcessorData *processor_data; }; // Things need to be read and written by each VM-exit handler struct GuestContext { union { VmmInitialStack *stack; GpRegisters *gp_regs; }; FlagRegister flag_reg; ULONG_PTR ip; ULONG_PTR cr8; KIRQL irql; bool vm_continue; }; #if defined(_AMD64_) static_assert(sizeof(GuestContext) == 40, ""Size check""); #else static_assert(sizeof(GuestContext) == 20, ""Size check""); #endif // Context at the moment of vmexit struct VmExitHistory { GpRegisters gp_regs; ULONG_PTR ip; VmExitInformation exit_reason; ULONG_PTR exit_qualification; ULONG_PTR instruction_info; }; typedef struct _CONTEXT_SWITCH_MON{ ULONG_PTR GuestRip; GpRegisters GuestGpReg[100]; int GuestGpRegIndex; ULONG GuestExecTimes; }CSMON, *PCSMON; CSMON g_CsMonitor[4][100] = { 0 }; int g_MonitorPointer[4] = { 0 }; //////////////////////////////////////////////////////////////////////////////// // // prototypes // bool __stdcall VmmVmExitHandler(_Inout_ VmmInitialStack *stack); DECLSPEC_NORETURN void __stdcall VmmVmxFailureHandler( _Inout_ AllRegisters *all_regs); static void VmmpHandleVmExit(_Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleTripleFault( _Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleUnexpectedExit( _Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleMonitorTrap( _Inout_ GuestContext *guest_context); static void VmmpHandleException(_Inout_ GuestContext *guest_context); static void VmmpHandleCpuid(_Inout_ GuestContext *guest_context); static void VmmpHandleRdtsc(_Inout_ GuestContext *guest_context); static void VmmpHandleRdtscp(_Inout_ GuestContext *guest_context); static void VmmpHandleXsetbv(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrReadAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrWriteAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleMsrAccess(_Inout_ GuestContext *guest_context, _In_ bool read_access); static void VmmpHandleGdtrOrIdtrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleLdtrOrTrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleDrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleIoPort(_Inout_ GuestContext *guest_context); static void VmmpHandleCrAccess(_Inout_ GuestContext *guest_context); static void VmmpHandleVmx(_Inout_ GuestContext *guest_context); static void VmmpHandleVmCall(_Inout_ GuestContext *guest_context); static void VmmpHandleInvalidateInternalCaches( _Inout_ GuestContext *guest_context); static void VmmpHandleInvalidateTlbEntry(_Inout_ GuestContext *guest_context); static void VmmpHandleEptViolation(_Inout_ GuestContext *guest_context); DECLSPEC_NORETURN static void VmmpHandleEptMisconfig( _Inout_ GuestContext *guest_context); static ULONG_PTR *VmmpSelectRegister(_In_ ULONG index, _In_ GuestContext *guest_context); static void VmmpDumpGuestState(); static void VmmpAdjustGuestInstructionPointer(_In_ GuestContext *guest_context); static void VmmpIoWrapper(_In_ bool to_memory, _In_ bool is_string, _In_ SIZE_T size_of_access, _In_ unsigned short port, _Inout_ void *address, _In_ unsigned long count); static void VmmpIndicateSuccessfulVmcall(_In_ GuestContext *guest_context); static void VmmpIndicateUnsuccessfulVmcall(_In_ GuestContext *guest_context); static void VmmpHandleVmCallTermination(_In_ GuestContext *guest_context, _Inout_ void *context); static UCHAR VmmpGetGuestCpl(); static void VmmpInjectInterruption(_In_ InterruptionType interruption_type, _In_ InterruptionVector vector, _In_ bool deliver_error_code, _In_ ULONG32 error_code); static ULONG_PTR VmmpGetKernelCr3(); //////////////////////////////////////////////////////////////////////////////// // // variables // // Those variables are all for diagnostic purpose static ULONG g_vmmp_next_history_index[kVmmpNumberOfProcessors]; static VmExitHistory g_vmmp_vm_exit_history[kVmmpNumberOfProcessors] [kVmmpNumberOfRecords]; //////////////////////////////////////////////////////////////////////////////// // // implementations // _Use_decl_annotations_ void __stdcall CSMonitorCallback(int ProcessorId, ULONG_PTR GuestRip, GpRegisters* GpReg, ULONG_PTR Cr3) { bool IsFound = false; int index = g_MonitorPointer[ProcessorId]; CSMON* CsMonitor = g_CsMonitor[ProcessorId]; for (int i = 0; i < 100 ; i++) { CSMON* CsMon = &CsMonitor[i]; if (CsMon->GuestRip == GuestRip) { int bufferIndex = CsMon->GuestGpRegIndex; memcpy(&CsMon->GuestGpReg[bufferIndex] , GpReg, sizeof(GpRegisters)); GpRegisters gp = CsMon->GuestGpReg[bufferIndex]; HYPERPLATFORM_LOG_DEBUG(""ContextSwitch at= %p ExecTimes= %x cr3= %p Esi= %p Esp= %p"",CsMon->GuestRip, CsMon->GuestExecTimes, Cr3, gp.si, gp.sp); CsMon->GuestGpRegIndex = ((bufferIndex + 1) % 100); CsMon->GuestExecTimes++; IsFound = true; break; } } if (!IsFound) { CSMON* CsMon = &CsMonitor[index]; CsMon->GuestRip = GuestRip; memcpy(&CsMon->GuestGpReg[0], GpReg, sizeof(GpRegisters)); GpRegisters gp = CsMon->GuestGpReg[0]; HYPERPLATFORM_LOG_DEBUG(""[First Cap] ContextSwitch at= %p ExecTimes= %x cr3= %p Esi= %p Esp= %p"", CsMon->GuestRip, CsMon->GuestExecTimes, Cr3, gp.si, gp.sp); CsMon->GuestGpRegIndex = 1; CsMon->GuestExecTimes = 1; } g_MonitorPointer[ProcessorId] = (index + 1) % 100; } // A high level VMX handler called from AsmVmExitHandler(). // Return true for vmresume, or return false for vmxoff. #pragma warning(push) #pragma warning(disable : 28167) _Use_decl_annotations_ bool __stdcall VmmVmExitHandler(VmmInitialStack *stack) { // Save guest's context and raise IRQL as quick as possible const auto guest_irql = KeGetCurrentIrql(); const auto guest_cr8 = IsX64() ? __readcr8() : 0; if (guest_irql < DISPATCH_LEVEL) { KeRaiseIrqlToDpcLevel(); } // Capture the current guest state GuestContext guest_context = {stack, UtilVmRead(VmcsField::kGuestRflags), UtilVmRead(VmcsField::kGuestRip), guest_cr8, guest_irql, true}; guest_context.gp_regs->sp = UtilVmRead(VmcsField::kGuestRsp); // Update the trap frame so that Windbg can construct the stack trace of the // guest. The rest of trap frame fields are entirely unused. Note that until // this code is executed, Windbg will display incorrect stack trace based off // the stale, old values. stack->trap_frame.sp = guest_context.gp_regs->sp; stack->trap_frame.ip = guest_context.ip + UtilVmRead(VmcsField::kVmExitInstructionLen); // Dispatch the current VM-exit event VmmpHandleVmExit(&guest_context); // See: Guidelines for Use of the INVVPID Instruction, and Guidelines for Use // of the INVEPT Instruction if (!guest_context.vm_continue) { UtilInveptGlobal(); UtilInvvpidAllContext(); } // Restore guest's context if (guest_context.irql < DISPATCH_LEVEL) { KeLowerIrql(guest_context.irql); } // Apply possibly updated CR8 by the handler if (IsX64()) { __writecr8(guest_context.cr8); } return guest_context.vm_continue; } #pragma warning(pop) // Dispatches VM-exit to a corresponding handler _Use_decl_annotations_ static void VmmpHandleVmExit( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const VmExitInformation exit_reason = { static_cast(UtilVmRead(VmcsField::kVmExitReason))}; if (kVmmpEnableRecordVmExit) { // Save them for ease of trouble shooting const auto processor = KeGetCurrentProcessorNumberEx(nullptr); auto &index = g_vmmp_next_history_index[processor]; auto &history = g_vmmp_vm_exit_history[processor][index]; history.gp_regs = *guest_context->gp_regs; history.ip = guest_context->ip; history.exit_reason = exit_reason; history.exit_qualification = UtilVmRead(VmcsField::kExitQualification); history.instruction_info = UtilVmRead(VmcsField::kVmxInstructionInfo); if (++index == kVmmpNumberOfRecords) { index = 0; } } switch (exit_reason.fields.reason) { case VmxExitReason::kExceptionOrNmi: VmmpHandleException(guest_context); break; case VmxExitReason::kTripleFault: VmmpHandleTripleFault(guest_context); /* UNREACHABLE */ case VmxExitReason::kCpuid: VmmpHandleCpuid(guest_context); break; case VmxExitReason::kInvd: VmmpHandleInvalidateInternalCaches(guest_context); break; case VmxExitReason::kInvlpg: VmmpHandleInvalidateTlbEntry(guest_context); break; case VmxExitReason::kRdtsc: VmmpHandleRdtsc(guest_context); break; case VmxExitReason::kCrAccess: VmmpHandleCrAccess(guest_context); break; case VmxExitReason::kDrAccess: VmmpHandleDrAccess(guest_context); break; case VmxExitReason::kIoInstruction: VmmpHandleIoPort(guest_context); break; case VmxExitReason::kMsrRead: VmmpHandleMsrReadAccess(guest_context); break; case VmxExitReason::kMsrWrite: VmmpHandleMsrWriteAccess(guest_context); break; case VmxExitReason::kMonitorTrapFlag: VmmpHandleMonitorTrap(guest_context); /* UNREACHABLE */ case VmxExitReason::kGdtrOrIdtrAccess: VmmpHandleGdtrOrIdtrAccess(guest_context); break; case VmxExitReason::kLdtrOrTrAccess: VmmpHandleLdtrOrTrAccess(guest_context); break; case VmxExitReason::kEptViolation: VmmpHandleEptViolation(guest_context); break; case VmxExitReason::kEptMisconfig: VmmpHandleEptMisconfig(guest_context); /* UNREACHABLE */ case VmxExitReason::kVmcall: VmmpHandleVmCall(guest_context); break; case VmxExitReason::kVmclear: case VmxExitReason::kVmlaunch: case VmxExitReason::kVmptrld: case VmxExitReason::kVmptrst: case VmxExitReason::kVmread: case VmxExitReason::kVmresume: case VmxExitReason::kVmwrite: case VmxExitReason::kVmoff: case VmxExitReason::kVmon: case VmxExitReason::kInvept: case VmxExitReason::kInvvpid: VmmpHandleVmx(guest_context); break; case VmxExitReason::kRdtscp: VmmpHandleRdtscp(guest_context); break; case VmxExitReason::kXsetbv: VmmpHandleXsetbv(guest_context); break; default: VmmpHandleUnexpectedExit(guest_context); /* UNREACHABLE */ } } // Triple fault VM-exit. Fatal error. _Use_decl_annotations_ static void VmmpHandleTripleFault( GuestContext *guest_context) { VmmpDumpGuestState(); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kTripleFaultVmExit, reinterpret_cast(guest_context), guest_context->ip, 0); } // Unexpected VM-exit. Fatal error. _Use_decl_annotations_ static void VmmpHandleUnexpectedExit( GuestContext *guest_context) { VmmpDumpGuestState(); const auto qualification = UtilVmRead(VmcsField::kExitQualification); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnexpectedVmExit, reinterpret_cast(guest_context), guest_context->ip, qualification); } // MTF VM-exit _Use_decl_annotations_ static void VmmpHandleMonitorTrap( GuestContext *guest_context) { VmmpDumpGuestState(); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnexpectedVmExit, reinterpret_cast(guest_context), guest_context->ip, 0); } // Interrupt _Use_decl_annotations_ static void VmmpHandleException( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const VmExitInterruptionInformationField exception = { static_cast(UtilVmRead(VmcsField::kVmExitIntrInfo))}; const auto interruption_type = static_cast(exception.fields.interruption_type); const auto vector = static_cast(exception.fields.vector); if (interruption_type == InterruptionType::kHardwareException) { // Hardware exception if (vector == InterruptionVector::kPageFaultException) { // #PF const PageFaultErrorCode fault_code = { static_cast(UtilVmRead(VmcsField::kVmExitIntrErrorCode))}; const auto fault_address = UtilVmRead(VmcsField::kExitQualification); VmmpInjectInterruption(interruption_type, vector, true, fault_code.all); HYPERPLATFORM_LOG_INFO_SAFE( ""GuestIp= %016Ix, #PF Fault= %016Ix Code= 0x%2x"", guest_context->ip, fault_address, fault_code.all); AsmWriteCR2(fault_address); } else if (vector == InterruptionVector::kGeneralProtectionException) { // # GP const auto error_code = static_cast(UtilVmRead(VmcsField::kVmExitIntrErrorCode)); VmmpInjectInterruption(interruption_type, vector, true, error_code); HYPERPLATFORM_LOG_INFO_SAFE(""GuestIp= %016Ix, #GP Code= 0x%2x"", guest_context->ip, error_code); } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } else if (interruption_type == InterruptionType::kSoftwareException) { // Software exception if (vector == InterruptionVector::kBreakpointException) { // #BP VmmpInjectInterruption(interruption_type, vector, false, 0); HYPERPLATFORM_LOG_INFO_SAFE(""GuestIp= %016Ix, #BP "", guest_context->ip); const auto exit_inst_length = UtilVmRead(VmcsField::kVmExitInstructionLen); UtilVmWrite(VmcsField::kVmEntryInstructionLen, exit_inst_length); } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } else { HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); } } // CPUID _Use_decl_annotations_ static void VmmpHandleCpuid( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); unsigned int cpu_info[4] = {}; const auto function_id = static_cast(guest_context->gp_regs->ax); const auto sub_function_id = static_cast(guest_context->gp_regs->cx); __cpuidex(reinterpret_cast(cpu_info), function_id, sub_function_id); if (function_id == 1) { // Present existence of a hypervisor using the HypervisorPresent bit CpuFeaturesEcx cpu_features = {static_cast(cpu_info[2])}; cpu_features.fields.not_used = true; cpu_info[2] = static_cast(cpu_features.all); } else if (function_id == kHyperVCpuidInterface) { // Leave signature of HyperPlatform onto EAX cpu_info[0] = 'PpyH'; } guest_context->gp_regs->ax = cpu_info[0]; guest_context->gp_regs->bx = cpu_info[1]; guest_context->gp_regs->cx = cpu_info[2]; guest_context->gp_regs->dx = cpu_info[3]; VmmpAdjustGuestInstructionPointer(guest_context); } // RDTSC _Use_decl_annotations_ static void VmmpHandleRdtsc( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); ULARGE_INTEGER tsc = {}; tsc.QuadPart = __rdtsc(); guest_context->gp_regs->dx = tsc.HighPart; guest_context->gp_regs->ax = tsc.LowPart; VmmpAdjustGuestInstructionPointer(guest_context); } // RDTSCP _Use_decl_annotations_ static void VmmpHandleRdtscp( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); unsigned int tsc_aux = 0; ULARGE_INTEGER tsc = {}; tsc.QuadPart = __rdtscp(&tsc_aux); guest_context->gp_regs->dx = tsc.HighPart; guest_context->gp_regs->ax = tsc.LowPart; guest_context->gp_regs->cx = tsc_aux; VmmpAdjustGuestInstructionPointer(guest_context); } // XSETBV. It is executed at the time of system resuming _Use_decl_annotations_ static void VmmpHandleXsetbv( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); ULARGE_INTEGER value = {}; value.LowPart = static_cast(guest_context->gp_regs->ax); value.HighPart = static_cast(guest_context->gp_regs->dx); _xsetbv(static_cast(guest_context->gp_regs->cx), value.QuadPart); VmmpAdjustGuestInstructionPointer(guest_context); } // RDMSR _Use_decl_annotations_ static void VmmpHandleMsrReadAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); VmmpHandleMsrAccess(guest_context, true); } // WRMSR _Use_decl_annotations_ static void VmmpHandleMsrWriteAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); VmmpHandleMsrAccess(guest_context, false); } // RDMSR and WRMSR _Use_decl_annotations_ static void VmmpHandleMsrAccess( GuestContext *guest_context, bool read_access) { // Apply it for VMCS instead of a real MSR if a specified MSR is either of // them. const auto msr = static_cast(guest_context->gp_regs->cx); bool transfer_to_vmcs = false; VmcsField vmcs_field = {}; switch (msr) { case Msr::kIa32SysenterCs: vmcs_field = VmcsField::kGuestSysenterCs; transfer_to_vmcs = true; break; case Msr::kIa32SysenterEsp: vmcs_field = VmcsField::kGuestSysenterEsp; transfer_to_vmcs = true; break; case Msr::kIa32SysenterEip: vmcs_field = VmcsField::kGuestSysenterEip; transfer_to_vmcs = true; break; case Msr::kIa32Debugctl: vmcs_field = VmcsField::kGuestIa32Debugctl; transfer_to_vmcs = true; break; case Msr::kIa32GsBase: vmcs_field = VmcsField::kGuestGsBase; transfer_to_vmcs = true; break; case Msr::kIa32FsBase: vmcs_field = VmcsField::kGuestFsBase; transfer_to_vmcs = true; break; default: break; } const auto is_64bit_vmcs = UtilIsInBounds(vmcs_field, VmcsField::kIoBitmapA, VmcsField::kHostIa32PerfGlobalCtrlHigh); LARGE_INTEGER msr_value = {}; if (read_access) { if (transfer_to_vmcs) { if (is_64bit_vmcs) { msr_value.QuadPart = UtilVmRead64(vmcs_field); } else { msr_value.QuadPart = UtilVmRead(vmcs_field); } } else { msr_value.QuadPart = UtilReadMsr64(msr); } guest_context->gp_regs->ax = msr_value.LowPart; guest_context->gp_regs->dx = msr_value.HighPart; } else { msr_value.LowPart = static_cast(guest_context->gp_regs->ax); msr_value.HighPart = static_cast(guest_context->gp_regs->dx); if (transfer_to_vmcs) { if (is_64bit_vmcs) { UtilVmWrite64(vmcs_field, static_cast(msr_value.QuadPart)); } else { UtilVmWrite(vmcs_field, static_cast(msr_value.QuadPart)); } } else { UtilWriteMsr64(msr, msr_value.QuadPart); } } VmmpAdjustGuestInstructionPointer(guest_context); } // LIDT, SIDT, LGDT and SGDT _Use_decl_annotations_ static void VmmpHandleGdtrOrIdtrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const GdtrOrIdtrInstInformation instruction_info = { static_cast(UtilVmRead(VmcsField::kVmxInstructionInfo))}; // Calculate an address to be used for the instruction const auto displacement = UtilVmRead(VmcsField::kExitQualification); // Base ULONG_PTR base_value = 0; if (!instruction_info.fields.base_register_invalid) { const auto register_used = VmmpSelectRegister( instruction_info.fields.base_register, guest_context); base_value = *register_used; } // Index ULONG_PTR index_value = 0; if (!instruction_info.fields.index_register_invalid) { const auto register_used = VmmpSelectRegister( instruction_info.fields.index_register, guest_context); index_value = *register_used; switch (static_cast(instruction_info.fields.scalling)) { case Scaling::kScaleBy2: index_value = index_value * 2; break; case Scaling::kScaleBy4: index_value = index_value * 4; break; case Scaling::kScaleBy8: index_value = index_value * 8; break; default: break; } } // clang-format off ULONG_PTR segment_base = 0; switch (instruction_info.fields.segment_register) { case 0: segment_base = UtilVmRead(VmcsField::kGuestEsBase); break; case 1: segment_base = UtilVmRead(VmcsField::kGuestCsBase); break; case 2: segment_base = UtilVmRead(VmcsField::kGuestSsBase); break; case 3: segment_base = UtilVmRead(VmcsField::kGuestDsBase); break; case 4: segment_base = UtilVmRead(VmcsField::kGuestFsBase); break; case 5: segment_base = UtilVmRead(VmcsField::kGuestGsBase); break; default: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // clang-format on auto operation_address = segment_base + base_value + index_value + displacement; if (static_cast(instruction_info.fields.address_size) == AddressSize::k32bit) { operation_address &= MAXULONG; } // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = VmmpGetKernelCr3(); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // Emulate the instruction auto descriptor_table_reg = reinterpret_cast(operation_address); switch (static_cast( instruction_info.fields.instruction_identity)) { case GdtrOrIdtrInstructionIdentity::kSgdt: { // On 64bit system, SIDT and SGDT can be executed from a 32bit process // where runs with the 32bit operand size. The following checks the // current guest's operand size and writes either full 10 bytes (for the // 64bit more) or 6 bytes or IDTR or GDTR as the processor does. See: // Operand Size and Address Size in 64-Bit Mode See: SGDT-Store Global // Descriptor Table Register See: SIDT-Store Interrupt Descriptor Table // Register const auto gdt_base = UtilVmRead(VmcsField::kGuestGdtrBase); const auto gdt_limit = static_cast(UtilVmRead(VmcsField::kGuestGdtrLimit)); const SegmentSelector ss = { static_cast(UtilVmRead(VmcsField::kGuestCsSelector))}; const auto segment_descriptor = reinterpret_cast( gdt_base + ss.fields.index * sizeof(SegmentDescriptor)); if (segment_descriptor->fields.l) { // 64bit descriptor_table_reg->base = gdt_base; descriptor_table_reg->limit = gdt_limit; } else { // 32bit const auto descriptor_table_reg32 = reinterpret_cast(descriptor_table_reg); descriptor_table_reg32->base = static_cast(gdt_base); descriptor_table_reg32->limit = gdt_limit; } break; } case GdtrOrIdtrInstructionIdentity::kSidt: { const auto idt_base = UtilVmRead(VmcsField::kGuestIdtrBase); const auto idt_limit = static_cast(UtilVmRead(VmcsField::kGuestIdtrLimit)); const auto gdt_base = UtilVmRead(VmcsField::kGuestGdtrBase); const SegmentSelector ss = { static_cast(UtilVmRead(VmcsField::kGuestCsSelector))}; const auto segment_descriptor = reinterpret_cast( gdt_base + ss.fields.index * sizeof(SegmentDescriptor)); if (segment_descriptor->fields.l) { // 64bit descriptor_table_reg->base = idt_base; descriptor_table_reg->limit = idt_limit; } else { // 32bit const auto descriptor_table_reg32 = reinterpret_cast(descriptor_table_reg); descriptor_table_reg32->base = static_cast(idt_base); descriptor_table_reg32->limit = idt_limit; } break; } case GdtrOrIdtrInstructionIdentity::kLgdt: UtilVmWrite(VmcsField::kGuestGdtrBase, descriptor_table_reg->base); UtilVmWrite(VmcsField::kGuestGdtrLimit, descriptor_table_reg->limit); break; case GdtrOrIdtrInstructionIdentity::kLidt: UtilVmWrite(VmcsField::kGuestIdtrBase, descriptor_table_reg->base); UtilVmWrite(VmcsField::kGuestIdtrLimit, descriptor_table_reg->limit); break; } __writecr3(vmm_cr3); VmmpAdjustGuestInstructionPointer(guest_context); } // LLDT, LTR, SLDT, and STR _Use_decl_annotations_ static void VmmpHandleLdtrOrTrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const LdtrOrTrInstInformation instruction_info = { static_cast(UtilVmRead(VmcsField::kVmxInstructionInfo))}; // Calculate an address or a register to be used for the instruction const auto displacement = UtilVmRead(VmcsField::kExitQualification); ULONG_PTR operation_address = 0; if (instruction_info.fields.register_access) { // Register const auto register_used = VmmpSelectRegister(instruction_info.fields.register1, guest_context); operation_address = reinterpret_cast(register_used); } else { // Base ULONG_PTR base_value = 0; if (!instruction_info.fields.base_register_invalid) { const auto register_used = VmmpSelectRegister( instruction_info.fields.base_register, guest_context); base_value = *register_used; } // Index ULONG_PTR index_value = 0; if (!instruction_info.fields.index_register_invalid) { const auto register_used = VmmpSelectRegister( instruction_info.fields.index_register, guest_context); index_value = *register_used; switch (static_cast(instruction_info.fields.scalling)) { case Scaling::kScaleBy2: index_value = index_value * 2; break; case Scaling::kScaleBy4: index_value = index_value * 4; break; case Scaling::kScaleBy8: index_value = index_value * 8; break; default: break; } } // clang-format off ULONG_PTR segment_base = 0; switch (instruction_info.fields.segment_register) { case 0: segment_base = UtilVmRead(VmcsField::kGuestEsBase); break; case 1: segment_base = UtilVmRead(VmcsField::kGuestCsBase); break; case 2: segment_base = UtilVmRead(VmcsField::kGuestSsBase); break; case 3: segment_base = UtilVmRead(VmcsField::kGuestDsBase); break; case 4: segment_base = UtilVmRead(VmcsField::kGuestFsBase); break; case 5: segment_base = UtilVmRead(VmcsField::kGuestGsBase); break; default: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // clang-format on operation_address = segment_base + base_value + index_value + displacement; if (static_cast(instruction_info.fields.address_size) == AddressSize::k32bit) { operation_address &= MAXULONG; } } // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = VmmpGetKernelCr3(); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // Emulate the instruction auto selector = reinterpret_cast(operation_address); switch (static_cast( instruction_info.fields.instruction_identity)) { case LdtrOrTrInstructionIdentity::kSldt: *selector = static_cast(UtilVmRead(VmcsField::kGuestLdtrSelector)); break; case LdtrOrTrInstructionIdentity::kStr: *selector = static_cast(UtilVmRead(VmcsField::kGuestTrSelector)); break; case LdtrOrTrInstructionIdentity::kLldt: UtilVmWrite(VmcsField::kGuestLdtrSelector, *selector); break; case LdtrOrTrInstructionIdentity::kLtr: { UtilVmWrite(VmcsField::kGuestTrSelector, *selector); // Set the Busy bit in TSS. // See: LTR - Load Task Register const SegmentSelector ss = {*selector}; const auto sd = reinterpret_cast( UtilVmRead(VmcsField::kGuestGdtrBase) + ss.fields.index * sizeof(SegmentDescriptor)); sd->fields.type |= 2; // Set the Busy bit break; } } __writecr3(vmm_cr3); VmmpAdjustGuestInstructionPointer(guest_context); } // MOV to / from DRx _Use_decl_annotations_ static void VmmpHandleDrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); // Normally, when the privileged instruction is executed at CPL3, #GP(0) // occurs instead of VM-exit. However, access to the debug registers is // exception. Inject #GP(0) in such case to emulate what the processor // normally does. See: Instructions That Cause VM Exits Conditionally if (VmmpGetGuestCpl() != 0) { VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kGeneralProtectionException, true, 0); return; } const MovDrQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; auto debugl_register = exit_qualification.fields.debugl_register; // Access to DR4 and 5 causes #UD when CR4.DE (Debugging Extensions) is set. // Otherwise, these registers are aliased to DR6 and 7 respectively. // See: Debug Registers DR4 and DR5 if (debugl_register == 4 || debugl_register == 5) { const Cr4 guest_cr4 = {UtilVmRead(VmcsField::kGuestCr4)}; if (guest_cr4.fields.de) { VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kInvalidOpcodeException, false, 0); return; } else if (debugl_register == 4) { debugl_register = 6; } else { debugl_register = 7; } } // Access to any of DRs causes #DB when DR7.GD (General Detect Enable) is set. // See: Debug Control Register (DR7) Dr7 guest_dr7 = {UtilVmRead(VmcsField::kGuestDr7)}; if (guest_dr7.fields.gd) { Dr6 guest_dr6 = {__readdr(6)}; // Clear DR6.B0-3 since the #DB being injected is not due to match of a // condition specified in DR6. The processor is allowed to clear those bits // as ""Certain debug exceptions may clear bits 0-3."" guest_dr6.fields.b0 = false; guest_dr6.fields.b1 = false; guest_dr6.fields.b2 = false; guest_dr6.fields.b3 = false; // ""When such a condition is detected, the BD flag in debug status register // DR6 is set prior to generating the exception."" guest_dr6.fields.bd = true; __writedr(6, guest_dr6.all); VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kDebugException, false, 0); // While the processor clears the DR7.GD bit on #DB (""The processor clears // the GD flag upon entering to the debug exception handler""), it does not // change that in the VMCS. Emulate that behavior here. Note that this bit // should actually be cleared by intercepting #DB and in the handler instead // of here, since the processor clears it on any #DB. We do not do that as // we do not intercept #DB as-is. guest_dr7.fields.gd = false; UtilVmWrite(VmcsField::kGuestDr7, guest_dr7.all); return; } const auto register_used = VmmpSelectRegister(exit_qualification.fields.gp_register, guest_context); const auto direction = static_cast(exit_qualification.fields.direction); // In 64-bit mode, the upper 32 bits of DR6 and DR7 are reserved and must be // written with zeros. Writing 1 to any of the upper 32 bits results in a // #GP(0) exception. See: Debug Registers and Intel® 64 Processors if (IsX64() && direction == MovDrDirection::kMoveToDr) { const auto value64 = static_cast(*register_used); if ((debugl_register == 6 || debugl_register == 7) && (value64 >> 32)) { VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kGeneralProtectionException, true, 0); return; } } switch (direction) { case MovDrDirection::kMoveToDr: switch (debugl_register) { // clang-format off case 0: __writedr(0, *register_used); break; case 1: __writedr(1, *register_used); break; case 2: __writedr(2, *register_used); break; case 3: __writedr(3, *register_used); break; // clang-format on case 6: { // Make sure that we write 0 and 1 into the bits that are stated to be // so. The Intel SDM does not appear to state what happens when the // processor attempts to write 1 to the always 0 bits, and vice versa, // however, observation is that writes to those bits are ignored // *as long as it is done on the non-root mode*, and other hypervisors // emulate in that way as well. Dr6 write_value = {*register_used}; write_value.fields.reserved1 |= ~write_value.fields.reserved1; write_value.fields.reserved2 = 0; write_value.fields.reserved3 |= ~write_value.fields.reserved3; __writedr(6, write_value.all); break; } case 7: { // Similar to the case of CR6, enforce always 1 and 0 behavior. Dr7 write_value = {*register_used}; write_value.fields.reserved1 |= ~write_value.fields.reserved1; write_value.fields.reserved2 = 0; write_value.fields.reserved3 = 0; UtilVmWrite(VmcsField::kGuestDr7, write_value.all); break; } default: break; } break; case MovDrDirection::kMoveFromDr: // clang-format off switch (debugl_register) { case 0: *register_used = __readdr(0); break; case 1: *register_used = __readdr(1); break; case 2: *register_used = __readdr(2); break; case 3: *register_used = __readdr(3); break; case 6: *register_used = __readdr(6); break; case 7: *register_used = UtilVmRead(VmcsField::kGuestDr7); break; default: break; } // clang-format on break; } VmmpAdjustGuestInstructionPointer(guest_context); } // IN, INS, OUT, OUTS _Use_decl_annotations_ static void VmmpHandleIoPort( GuestContext *guest_context) { const IoInstQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; const auto is_in = exit_qualification.fields.direction == 1; // to memory? const auto is_string = exit_qualification.fields.string_instruction == 1; const auto is_rep = exit_qualification.fields.rep_prefixed == 1; const auto port = static_cast(exit_qualification.fields.port_number); const auto string_address = reinterpret_cast( (is_in) ? guest_context->gp_regs->di : guest_context->gp_regs->si); const auto count = static_cast((is_rep) ? guest_context->gp_regs->cx : 1); const auto address = (is_string) ? string_address : &guest_context->gp_regs->ax; SIZE_T size_of_access = 0; const char *suffix = """"; switch (static_cast( exit_qualification.fields.size_of_access)) { case IoInstSizeOfAccess::k1Byte: size_of_access = 1; suffix = ""B""; break; case IoInstSizeOfAccess::k2Byte: size_of_access = 2; suffix = ""W""; break; case IoInstSizeOfAccess::k4Byte: size_of_access = 4; suffix = ""D""; break; } HYPERPLATFORM_LOG_DEBUG_SAFE(""GuestIp= %016Ix, Port= %04x, %s%s%s"", guest_context->ip, port, (is_in ? ""IN"" : ""OUT""), (is_string ? ""S"" : """"), (is_string ? suffix : """")); VmmpIoWrapper(is_in, is_string, size_of_access, port, address, count); // Update RCX, RDI and RSI accordingly. Note that this code can handle only // the REP prefix. if (is_string) { const auto update_count = (is_rep) ? guest_context->gp_regs->cx : 1; const auto update_size = update_count * size_of_access; const auto update_register = (is_in) ? &guest_context->gp_regs->di : &guest_context->gp_regs->si; if (guest_context->flag_reg.fields.df) { *update_register = *update_register - update_size; } else { *update_register = *update_register + update_size; } if (is_rep) { guest_context->gp_regs->cx = 0; } } VmmpAdjustGuestInstructionPointer(guest_context); } // Perform IO instruction according with parameters _Use_decl_annotations_ static void VmmpIoWrapper(bool to_memory, bool is_string, SIZE_T size_of_access, unsigned short port, void *address, unsigned long count) { NT_ASSERT(size_of_access == 1 || size_of_access == 2 || size_of_access == 4); // Update CR3 with that of the guest since below code is going to access // memory. const auto guest_cr3 = VmmpGetKernelCr3(); const auto vmm_cr3 = __readcr3(); __writecr3(guest_cr3); // clang-format off if (to_memory) { if (is_string) { // INS switch (size_of_access) { case 1: __inbytestring(port, static_cast(address), count); break; case 2: __inwordstring(port, static_cast(address), count); break; case 4: __indwordstring(port, static_cast(address), count); break; } } else { // IN switch (size_of_access) { case 1: *static_cast(address) = __inbyte(port); break; case 2: *static_cast(address) = __inword(port); break; case 4: *static_cast(address) = __indword(port); break; } } } else { if (is_string) { // OUTS switch (size_of_access) { case 1: __outbytestring(port, static_cast(address), count); break; case 2: __outwordstring(port, static_cast(address), count); break; case 4: __outdwordstring(port, static_cast(address), count); break; } } else { // OUT switch (size_of_access) { case 1: __outbyte(port, *static_cast(address)); break; case 2: __outword(port, *static_cast(address)); break; case 4: __outdword(port, *static_cast(address)); break; } } } // clang-format on __writecr3(vmm_cr3); } // MOV to / from CRx _Use_decl_annotations_ static void VmmpHandleCrAccess( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const MovCrQualification exit_qualification = { UtilVmRead(VmcsField::kExitQualification)}; const auto register_used = VmmpSelectRegister(exit_qualification.fields.gp_register, guest_context); switch (static_cast(exit_qualification.fields.access_type)) { case MovCrAccessType::kMoveToCr: switch (exit_qualification.fields.control_register) { // CR0 <- Reg case 0: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); if (UtilIsX86Pae()) { UtilLoadPdptes(UtilVmRead(VmcsField::kGuestCr3)); } const Cr0 cr0_fixed0 = {UtilReadMsr(Msr::kIa32VmxCr0Fixed0)}; const Cr0 cr0_fixed1 = {UtilReadMsr(Msr::kIa32VmxCr0Fixed1)}; Cr0 cr0 = {*register_used}; cr0.all &= cr0_fixed1.all; cr0.all |= cr0_fixed0.all; UtilVmWrite(VmcsField::kGuestCr0, cr0.all); UtilVmWrite(VmcsField::kCr0ReadShadow, cr0.all); break; } // CR3 <- Reg case 3: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); CSMonitorCallback( KeGetCurrentProcessorNumber(), UtilVmRead64(VmcsField::kGuestRip), guest_context->gp_regs, (*register_used & ~(1ULL << 63)) ); if (UtilIsX86Pae()) { UtilLoadPdptes(VmmpGetKernelCr3()); } // Under some circumstances MOV to CR3 is not *required* to flush TLB // entries, but also NOT prohibited to do so. Therefore, we flush it // all time. // See: Operations that Invalidate TLBs and Paging-Structure Caches UtilInvvpidSingleContextExceptGlobal( static_cast(KeGetCurrentProcessorNumberEx(nullptr) + 1)); // The MOV to CR3 does not modify the bit63 of CR3. Emulate this // behavior. // See: MOV - Move to/from Control Registers UtilVmWrite(VmcsField::kGuestCr3, (*register_used & ~(1ULL << 63))); break; } // CR4 <- Reg case 4: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); if (UtilIsX86Pae()) { UtilLoadPdptes(UtilVmRead(VmcsField::kGuestCr3)); } UtilInvvpidAllContext(); const Cr4 cr4_fixed0 = {UtilReadMsr(Msr::kIa32VmxCr4Fixed0)}; const Cr4 cr4_fixed1 = {UtilReadMsr(Msr::kIa32VmxCr4Fixed1)}; Cr4 cr4 = {*register_used}; cr4.all &= cr4_fixed1.all; cr4.all |= cr4_fixed0.all; UtilVmWrite(VmcsField::kGuestCr4, cr4.all); UtilVmWrite(VmcsField::kCr4ReadShadow, cr4.all); break; } // CR8 <- Reg case 8: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); guest_context->cr8 = *register_used; break; } default: HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); /* UNREACHABLE */ } break; case MovCrAccessType::kMoveFromCr: switch (exit_qualification.fields.control_register) { // Reg <- CR3 case 3: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); *register_used = UtilVmRead(VmcsField::kGuestCr3); break; } // Reg <- CR8 case 8: { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); *register_used = guest_context->cr8; break; } default: HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kUnspecified, 0, 0, 0); /* UNREACHABLE */ } break; // Unimplemented case MovCrAccessType::kClts: case MovCrAccessType::kLmsw: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } VmmpAdjustGuestInstructionPointer(guest_context); } // VMX instructions except for VMCALL _Use_decl_annotations_ static void VmmpHandleVmx(GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); // See: CONVENTIONS guest_context->flag_reg.fields.cf = true; // Error without status guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; // Error without status guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; UtilVmWrite(VmcsField::kGuestRflags, guest_context->flag_reg.all); VmmpAdjustGuestInstructionPointer(guest_context); } // VMCALL _Use_decl_annotations_ static void VmmpHandleVmCall( GuestContext *guest_context) { // VMCALL convention for HyperPlatform: // ecx: hyper-call number (always 32bit) // edx: arbitrary context parameter (pointer size) // Any unsuccessful VMCALL will inject #UD into a guest const auto hypercall_number = static_cast(guest_context->gp_regs->cx); const auto context = reinterpret_cast(guest_context->gp_regs->dx); if (!UtilIsInBounds(hypercall_number, HypercallNumber::kMinimumHypercallNumber, HypercallNumber::kMaximumHypercallNumber)) { // Unsupported hypercall VmmpIndicateUnsuccessfulVmcall(guest_context); } switch (hypercall_number) { case HypercallNumber::kTerminateVmm: // Unloading requested. This VMCALL is allowed to execute only from CPL=0 if (VmmpGetGuestCpl() == 0) { VmmpHandleVmCallTermination(guest_context, context); } else { VmmpIndicateUnsuccessfulVmcall(guest_context); } break; case HypercallNumber::kPingVmm: // Sample VMCALL handler HYPERPLATFORM_LOG_INFO_SAFE(""Pong by VMM! (context = %p)"", context); VmmpIndicateSuccessfulVmcall(guest_context); break; case HypercallNumber::kGetSharedProcessorData: *static_cast(context) = guest_context->stack->processor_data->shared_data; VmmpIndicateSuccessfulVmcall(guest_context); break; } } // INVD _Use_decl_annotations_ static void VmmpHandleInvalidateInternalCaches( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); AsmInvalidateInternalCaches(); VmmpAdjustGuestInstructionPointer(guest_context); } // INVLPG _Use_decl_annotations_ static void VmmpHandleInvalidateTlbEntry( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); const auto invalidate_address = reinterpret_cast(UtilVmRead(VmcsField::kExitQualification)); UtilInvvpidIndividualAddress( static_cast(KeGetCurrentProcessorNumberEx(nullptr) + 1), invalidate_address); VmmpAdjustGuestInstructionPointer(guest_context); } // EXIT_REASON_EPT_VIOLATION _Use_decl_annotations_ static void VmmpHandleEptViolation( GuestContext *guest_context) { HYPERPLATFORM_PERFORMANCE_MEASURE_THIS_SCOPE(); auto processor_data = guest_context->stack->processor_data; EptHandleEptViolation(processor_data->ept_data); } // EXIT_REASON_EPT_MISCONFIG _Use_decl_annotations_ static void VmmpHandleEptMisconfig( GuestContext *guest_context) { UNREFERENCED_PARAMETER(guest_context); const auto fault_address = UtilVmRead(VmcsField::kGuestPhysicalAddress); const auto ept_pt_entry = EptGetEptPtEntry( guest_context->stack->processor_data->ept_data, fault_address); HYPERPLATFORM_COMMON_BUG_CHECK(HyperPlatformBugCheck::kEptMisconfigVmExit, fault_address, reinterpret_cast(ept_pt_entry), 0); } // Selects a register to be used based on the index _Use_decl_annotations_ static ULONG_PTR *VmmpSelectRegister( ULONG index, GuestContext *guest_context) { ULONG_PTR *register_used = nullptr; // clang-format off switch (index) { case 0: register_used = &guest_context->gp_regs->ax; break; case 1: register_used = &guest_context->gp_regs->cx; break; case 2: register_used = &guest_context->gp_regs->dx; break; case 3: register_used = &guest_context->gp_regs->bx; break; case 4: register_used = &guest_context->gp_regs->sp; break; case 5: register_used = &guest_context->gp_regs->bp; break; case 6: register_used = &guest_context->gp_regs->si; break; case 7: register_used = &guest_context->gp_regs->di; break; #if defined(_AMD64_) case 8: register_used = &guest_context->gp_regs->r8; break; case 9: register_used = &guest_context->gp_regs->r9; break; case 10: register_used = &guest_context->gp_regs->r10; break; case 11: register_used = &guest_context->gp_regs->r11; break; case 12: register_used = &guest_context->gp_regs->r12; break; case 13: register_used = &guest_context->gp_regs->r13; break; case 14: register_used = &guest_context->gp_regs->r14; break; case 15: register_used = &guest_context->gp_regs->r15; break; #endif default: HYPERPLATFORM_COMMON_DBG_BREAK(); break; } // clang-format on return register_used; } // Dumps guest state VMCS fields /*_Use_decl_annotations_*/ static void VmmpDumpGuestState() { // clang-format off HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest EsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestEsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest CsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestCsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestSsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest DsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestDsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest FsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestFsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GsSelector = %016Ix"", UtilVmRead(VmcsField::kGuestGsSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest LdtrSelector = %016Ix"", UtilVmRead(VmcsField::kGuestLdtrSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest TrSelector = %016Ix"", UtilVmRead(VmcsField::kGuestTrSelector)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Ia32Debugctl = %016llx"", UtilVmRead64(VmcsField::kGuestIa32Debugctl)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest EsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestEsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest CsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestCsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestSsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest DsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestDsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest FsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestFsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GsLimit = %016Ix"", UtilVmRead(VmcsField::kGuestGsLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest LdtrLimit = %016Ix"", UtilVmRead(VmcsField::kGuestLdtrLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest TrLimit = %016Ix"", UtilVmRead(VmcsField::kGuestTrLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GdtrLimit = %016Ix"", UtilVmRead(VmcsField::kGuestGdtrLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest IdtrLimit = %016Ix"", UtilVmRead(VmcsField::kGuestIdtrLimit)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest EsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestEsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest CsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestCsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestSsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest DsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestDsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest FsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestFsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GsArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestGsArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest LdtrArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestLdtrArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest TrArBytes = %016Ix"", UtilVmRead(VmcsField::kGuestTrArBytes)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SysenterCs = %016Ix"", UtilVmRead(VmcsField::kGuestSysenterCs)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Cr0 = %016Ix"", UtilVmRead(VmcsField::kGuestCr0)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Cr3 = %016Ix"", UtilVmRead(VmcsField::kGuestCr3)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Cr4 = %016Ix"", UtilVmRead(VmcsField::kGuestCr4)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest EsBase = %016Ix"", UtilVmRead(VmcsField::kGuestEsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest CsBase = %016Ix"", UtilVmRead(VmcsField::kGuestCsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SsBase = %016Ix"", UtilVmRead(VmcsField::kGuestSsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest DsBase = %016Ix"", UtilVmRead(VmcsField::kGuestDsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest FsBase = %016Ix"", UtilVmRead(VmcsField::kGuestFsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GsBase = %016Ix"", UtilVmRead(VmcsField::kGuestGsBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest LdtrBase = %016Ix"", UtilVmRead(VmcsField::kGuestLdtrBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest TrBase = %016Ix"", UtilVmRead(VmcsField::kGuestTrBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest GdtrBase = %016Ix"", UtilVmRead(VmcsField::kGuestGdtrBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest IdtrBase = %016Ix"", UtilVmRead(VmcsField::kGuestIdtrBase)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Dr7 = %016Ix"", UtilVmRead(VmcsField::kGuestDr7)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Rsp = %016Ix"", UtilVmRead(VmcsField::kGuestRsp)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Rip = %016Ix"", UtilVmRead(VmcsField::kGuestRip)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest Rflags = %016Ix"", UtilVmRead(VmcsField::kGuestRflags)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SysenterEsp = %016Ix"", UtilVmRead(VmcsField::kGuestSysenterEsp)); HYPERPLATFORM_LOG_DEBUG_SAFE(""Guest SysenterEip = %016Ix"", UtilVmRead(VmcsField::kGuestSysenterEip)); // clang-format on } // Advances guest's IP to the next instruction _Use_decl_annotations_ static void VmmpAdjustGuestInstructionPointer( GuestContext *guest_context) { const auto exit_inst_length = UtilVmRead(VmcsField::kVmExitInstructionLen); UtilVmWrite(VmcsField::kGuestRip, guest_context->ip + exit_inst_length); // Inject #DB if TF is set if (guest_context->flag_reg.fields.tf) { VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kDebugException, false, 0); UtilVmWrite(VmcsField::kVmEntryInstructionLen, exit_inst_length); } } // Handle VMRESUME or VMXOFF failure. Fatal error. _Use_decl_annotations_ void __stdcall VmmVmxFailureHandler( AllRegisters *all_regs) { const auto guest_ip = UtilVmRead(VmcsField::kGuestRip); // See: VM-Instruction Error Numbers const auto vmx_error = (all_regs->flags.fields.zf) ? UtilVmRead(VmcsField::kVmInstructionError) : 0; HYPERPLATFORM_COMMON_BUG_CHECK( HyperPlatformBugCheck::kCriticalVmxInstructionFailure, vmx_error, guest_ip, 0); } // Indicates successful VMCALL _Use_decl_annotations_ static void VmmpIndicateSuccessfulVmcall( GuestContext *guest_context) { // See: CONVENTIONS guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.zf = false; UtilVmWrite(VmcsField::kGuestRflags, guest_context->flag_reg.all); VmmpAdjustGuestInstructionPointer(guest_context); } // Indicates unsuccessful VMCALL _Use_decl_annotations_ static void VmmpIndicateUnsuccessfulVmcall( GuestContext *guest_context) { UNREFERENCED_PARAMETER(guest_context); VmmpInjectInterruption(InterruptionType::kHardwareException, InterruptionVector::kInvalidOpcodeException, false, 0); const auto exit_inst_length = UtilVmRead(VmcsField::kVmExitInstructionLen); UtilVmWrite(VmcsField::kVmEntryInstructionLen, exit_inst_length); } // Handles an unloading request _Use_decl_annotations_ static void VmmpHandleVmCallTermination( GuestContext *guest_context, void *context) { // The processor sets ffff to limits of IDT and GDT when VM-exit occurred. // It is not correct value but fine to ignore since vmresume loads correct // values from VMCS. But here, we are going to skip vmresume and simply // return to where VMCALL is executed. It results in keeping those broken // values and ends up with bug check 109, so we should fix them manually. const auto gdt_limit = UtilVmRead(VmcsField::kGuestGdtrLimit); const auto gdt_base = UtilVmRead(VmcsField::kGuestGdtrBase); const auto idt_limit = UtilVmRead(VmcsField::kGuestIdtrLimit); const auto idt_base = UtilVmRead(VmcsField::kGuestIdtrBase); Gdtr gdtr = {static_cast(gdt_limit), gdt_base}; Idtr idtr = {static_cast(idt_limit), idt_base}; __lgdt(&gdtr); __lidt(&idtr); // Store an address of the management structure to the context parameter const auto result_ptr = static_cast(context); *result_ptr = guest_context->stack->processor_data; HYPERPLATFORM_LOG_DEBUG_SAFE(""Context at %p %p"", context, guest_context->stack->processor_data); // Set rip to the next instruction of VMCALL const auto exit_instruction_length = UtilVmRead(VmcsField::kVmExitInstructionLen); const auto return_address = guest_context->ip + exit_instruction_length; // Since the flag register is overwritten after VMXOFF, we should manually // indicates that VMCALL was successful by clearing those flags. // See: CONVENTIONS guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.pf = false; guest_context->flag_reg.fields.af = false; guest_context->flag_reg.fields.zf = false; guest_context->flag_reg.fields.sf = false; guest_context->flag_reg.fields.of = false; guest_context->flag_reg.fields.cf = false; guest_context->flag_reg.fields.zf = false; // Set registers used after VMXOFF to recover the context. Volatile // registers must be used because those changes are reflected to the // guest's context after VMXOFF. guest_context->gp_regs->cx = return_address; guest_context->gp_regs->dx = guest_context->gp_regs->sp; guest_context->gp_regs->ax = guest_context->flag_reg.all; guest_context->vm_continue = false; } // Returns guest's CPL /*_Use_decl_annotations_*/ static UCHAR VmmpGetGuestCpl() { VmxRegmentDescriptorAccessRight ar = { static_cast(UtilVmRead(VmcsField::kGuestSsArBytes))}; return ar.fields.dpl; } // Injects interruption to a guest _Use_decl_annotations_ static void VmmpInjectInterruption( InterruptionType interruption_type, InterruptionVector vector, bool deliver_error_code, ULONG32 error_code) { VmEntryInterruptionInformationField inject = {}; inject.fields.valid = true; inject.fields.interruption_type = static_cast(interruption_type); inject.fields.vector = static_cast(vector); inject.fields.deliver_error_code = deliver_error_code; UtilVmWrite(VmcsField::kVmEntryIntrInfoField, inject.all); if (deliver_error_code) { UtilVmWrite(VmcsField::kVmEntryExceptionErrorCode, error_code); } } // Returns a kernel CR3 value of the current process; /*_Use_decl_annotations_*/ static ULONG_PTR VmmpGetKernelCr3() { ULONG_PTR guest_cr3 = 0; static const long kDirectoryTableBaseOffset = IsX64() ? 0x28 : 0x18; if (IsX64()) { // On x64, assume it is an user-mode CR3 when the lowest bit is set. If so, // get CR3 from _KPROCESS::DirectoryTableBase. guest_cr3 = UtilVmRead(VmcsField::kGuestCr3); if (guest_cr3 & 1) { const auto process = reinterpret_cast(PsGetCurrentProcess()); guest_cr3 = *reinterpret_cast(process + kDirectoryTableBaseOffset); } } else { // On x86, there is no easy way to tell whether the CR3 taken from VMCS is // a user-mode CR3 or kernel-mode CR3 by only looking at the value. // Therefore, we simply use _KPROCESS::DirectoryTableBase always. const auto process = reinterpret_cast(PsGetCurrentProcess()); guest_cr3 = *reinterpret_cast(process + kDirectoryTableBaseOffset); } return guest_cr3; } } // extern ""C"" ",16372,True,3396.5107873475567,median "/* * The MIT License * * Copyright (c) 1997-2019 The University of Utah * * 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 __APPLE__ // This is a hack. gcc 3.3 #undefs isnan in the cmath header, which // make the isnan function not work. This define makes the cmath header // not get included since we do not need it anyway. # define _CPP_CMATH #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; using namespace Uintah; static DebugStream cout_EP(""SSEP"",false); static DebugStream cout_EP1(""SSEP1"",false); static DebugStream CSTi(""SSEPi"",false); static DebugStream CSTir(""SSEPir"",false); SmallStrainPlastic::SmallStrainPlastic(ProblemSpecP& ps,MPMFlags* Mflag) : ConstitutiveModel(Mflag), ImplicitCM() { ps->require(""bulk_modulus"",d_initialData.Bulk); ps->require(""shear_modulus"",d_initialData.Shear); d_initialData.CTE = 1.0e-5; // default is per K ps->get(""coeff_thermal_expansion"", d_initialData.CTE); d_initialData.Chi = 0.9; ps->get(""taylor_quinney_coeff"",d_initialData.Chi); d_initialData.sigma_crit = 2.0e9; // default is Pa ps->get(""critical_stress"", d_initialData.sigma_crit); d_doIsothermal = false; d_isothermal = 1.0; ps->get(""isothermal"", d_doIsothermal); if (d_doIsothermal) d_isothermal = 0.0; d_tol = 1.0e-10; ps->get(""tolerance"",d_tol); d_useModifiedEOS = false; ps->get(""useModifiedEOS"",d_useModifiedEOS); d_initialMaterialTemperature = 294.0; ps->get(""initial_material_temperature"",d_initialMaterialTemperature); d_checkTeplaFailureCriterion = true; ps->get(""check_TEPLA_failure_criterion"",d_checkTeplaFailureCriterion); d_doMelting = true; ps->get(""do_melting"",d_doMelting); d_checkStressTriax = true; ps->get(""check_max_stress_failure"",d_checkStressTriax); d_eos = UintahBB::PressureModelFactory::create(ps); d_eos->setBulkModulus(d_initialData.Bulk); if(!d_eos){ ostringstream desc; desc << ""An error occured in the PressureModelFactory that has \\n"" << "" slipped through the existing bullet proofing. Please tell \\n"" << "" Biswajit. ""<< endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_shear = UintahBB::ShearModulusModelFactory::create(ps); if (!d_shear) { ostringstream desc; desc << ""SmallStrainPlastic::Error in shear modulus model factory"" << endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_melt = MeltingTempModelFactory::create(ps); if (!d_melt) { ostringstream desc; desc << ""SmallStrainPlastic::Error in melting temp model factory"" << endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_computeSpecificHeat = false; ps->get(""compute_specific_heat"",d_computeSpecificHeat); d_Cp = SpecificHeatModelFactory::create(ps); d_yield = UintahBB::YieldConditionFactory::create(ps); if(!d_yield){ ostringstream desc; desc << ""An error occured in the YieldConditionFactory that has \\n"" << "" slipped through the existing bullet proofing. Please tell \\n"" << "" Biswajit. ""<< endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_plastic = FlowStressModelFactory::create(ps); if(!d_plastic){ ostringstream desc; desc << ""An error occured in the FlowStressModelFactory that has \\n"" << "" slipped through the existing bullet proofing. Please tell \\n"" << "" Biswajit. ""<< endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_kinematic = UintahBB::KinematicHardeningModelFactory::create(ps); if(!d_kinematic){ ostringstream desc; desc << ""An error occured in the KinematicHardeningModelFactory that has \\n"" << "" slipped through the existing bullet proofing. Please tell \\n"" << "" Biswajit. ""<< endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_damage = DamageModelFactory::create(ps); if(!d_damage){ ostringstream desc; desc << ""An error occured in the DamageModelFactory that has \\n"" << "" slipped through the existing bullet proofing. Please tell \\n"" << "" Biswajit. ""<< endl; throw ParameterNotFound(desc.str(), __FILE__, __LINE__); } d_stable = StabilityCheckFactory::create(ps); if(!d_stable) cerr << ""Stability check disabled\\n""; setErosionAlgorithm(); getInitialPorosityData(ps); getInitialDamageData(ps); initializeLocalMPMLabels(); } SmallStrainPlastic::SmallStrainPlastic(const SmallStrainPlastic* cm) : ConstitutiveModel(cm), ImplicitCM(cm) { d_initialData.Bulk = cm->d_initialData.Bulk; d_initialData.Shear = cm->d_initialData.Shear; d_initialData.CTE = cm->d_initialData.CTE; d_initialData.Chi = cm->d_initialData.Chi; d_initialData.sigma_crit = cm->d_initialData.sigma_crit; d_tol = cm->d_tol ; d_useModifiedEOS = cm->d_useModifiedEOS; d_isothermal = cm->d_isothermal; d_initialMaterialTemperature = cm->d_initialMaterialTemperature ; d_checkTeplaFailureCriterion = cm->d_checkTeplaFailureCriterion; d_doMelting = cm->d_doMelting; d_checkStressTriax = cm->d_checkStressTriax; d_setStressToZero = cm->d_setStressToZero; d_allowNoTension = cm->d_allowNoTension; d_evolvePorosity = cm->d_evolvePorosity; d_porosity.f0 = cm->d_porosity.f0 ; d_porosity.f0_std = cm->d_porosity.f0_std ; d_porosity.fc = cm->d_porosity.fc ; d_porosity.fn = cm->d_porosity.fn ; d_porosity.en = cm->d_porosity.en ; d_porosity.sn = cm->d_porosity.sn ; d_porosity.porosityDist = cm->d_porosity.porosityDist ; d_evolveDamage = cm->d_evolveDamage; d_scalarDam.D0 = cm->d_scalarDam.D0 ; d_scalarDam.D0_std = cm->d_scalarDam.D0_std ; d_scalarDam.Dc = cm->d_scalarDam.Dc ; d_scalarDam.scalarDamageDist = cm->d_scalarDam.scalarDamageDist ; d_eos = UintahBB::PressureModelFactory::createCopy(cm->d_eos); d_eos->setBulkModulus(d_initialData.Bulk); d_shear = UintahBB::ShearModulusModelFactory::createCopy(cm->d_shear); d_melt = MeltingTempModelFactory::createCopy(cm->d_melt); d_computeSpecificHeat = cm->d_computeSpecificHeat; d_Cp = SpecificHeatModelFactory::createCopy(cm->d_Cp); d_yield = UintahBB::YieldConditionFactory::createCopy(cm->d_yield); d_plastic = FlowStressModelFactory::createCopy(cm->d_plastic); d_kinematic = UintahBB::KinematicHardeningModelFactory::createCopy(cm->d_kinematic); d_damage = DamageModelFactory::createCopy(cm->d_damage); d_stable = StabilityCheckFactory::createCopy(cm->d_stable); initializeLocalMPMLabels(); } SmallStrainPlastic::~SmallStrainPlastic() { // Destructor VarLabel::destroy(pStrainRateLabel); VarLabel::destroy(pPlasticStrainLabel); VarLabel::destroy(pPlasticStrainRateLabel); VarLabel::destroy(pDamageLabel); VarLabel::destroy(pPorosityLabel); VarLabel::destroy(pLocalizedLabel); VarLabel::destroy(pStrainRateLabel_preReloc); VarLabel::destroy(pPlasticStrainLabel_preReloc); VarLabel::destroy(pPlasticStrainRateLabel_preReloc); VarLabel::destroy(pDamageLabel_preReloc); VarLabel::destroy(pPorosityLabel_preReloc); VarLabel::destroy(pLocalizedLabel_preReloc); delete d_eos; delete d_shear; delete d_melt; delete d_Cp; delete d_yield; delete d_plastic; delete d_kinematic; delete d_damage; delete d_stable; } void SmallStrainPlastic::outputProblemSpec(ProblemSpecP& ps,bool output_cm_tag) { ProblemSpecP cm_ps = ps; if (output_cm_tag) { cm_ps = ps->appendChild(""constitutive_model""); cm_ps->setAttribute(""type"",""small_strain_plastic""); } cm_ps->appendElement(""bulk_modulus"",d_initialData.Bulk); cm_ps->appendElement(""shear_modulus"",d_initialData.Shear); cm_ps->appendElement(""coeff_thermal_expansion"", d_initialData.CTE); cm_ps->appendElement(""taylor_quinney_coeff"",d_initialData.Chi); cm_ps->appendElement(""critical_stress"", d_initialData.sigma_crit); cm_ps->appendElement(""isothermal"", d_doIsothermal); cm_ps->appendElement(""tolerance"",d_tol); cm_ps->appendElement(""useModifiedEOS"",d_useModifiedEOS); cm_ps->appendElement(""initial_material_temperature"", d_initialMaterialTemperature); cm_ps->appendElement(""check_TEPLA_failure_criterion"", d_checkTeplaFailureCriterion); cm_ps->appendElement(""do_melting"",d_doMelting); cm_ps->appendElement(""check_max_stress_failure"",d_checkStressTriax); cm_ps->appendElement(""compute_specific_heat"",d_computeSpecificHeat); d_eos->outputProblemSpec(cm_ps); d_shear->outputProblemSpec(cm_ps); d_melt->outputProblemSpec(cm_ps); d_Cp->outputProblemSpec(cm_ps); d_yield->outputProblemSpec(cm_ps); d_plastic->outputProblemSpec(cm_ps); d_kinematic->outputProblemSpec(cm_ps); d_damage->outputProblemSpec(cm_ps); d_stable->outputProblemSpec(cm_ps); cm_ps->appendElement(""evolve_porosity"",d_evolvePorosity); cm_ps->appendElement(""initial_mean_porosity"",d_porosity.f0); cm_ps->appendElement(""initial_std_porosity"",d_porosity.f0_std); cm_ps->appendElement(""critical_porosity"",d_porosity.fc); cm_ps->appendElement(""frac_nucleation"",d_porosity.fn); cm_ps->appendElement(""meanstrain_nucleation"",d_porosity.en); cm_ps->appendElement(""stddevstrain_nucleation"",d_porosity.sn); cm_ps->appendElement(""initial_porosity_distrib"",d_porosity.porosityDist); cm_ps->appendElement(""evolve_damage"",d_evolveDamage); cm_ps->appendElement(""initial_mean_scalar_damage"",d_scalarDam.D0); cm_ps->appendElement(""initial_std_scalar_damage"",d_scalarDam.D0_std); cm_ps->appendElement(""critical_scalar_damage"",d_scalarDam.Dc); cm_ps->appendElement(""initial_scalar_damage_distrib"", d_scalarDam.scalarDamageDist); } SmallStrainPlastic* SmallStrainPlastic::clone() { return scinew SmallStrainPlastic(*this); } void SmallStrainPlastic::initializeLocalMPMLabels() { pStrainRateLabel = VarLabel::create(""p.strainRate"", ParticleVariable::getTypeDescription()); pPlasticStrainLabel = VarLabel::create(""p.plasticStrain"", ParticleVariable::getTypeDescription()); pPlasticStrainRateLabel = VarLabel::create(""p.plasticStrainRate"", ParticleVariable::getTypeDescription()); pDamageLabel = VarLabel::create(""p.damage"", ParticleVariable::getTypeDescription()); pPorosityLabel = VarLabel::create(""p.porosity"", ParticleVariable::getTypeDescription()); pLocalizedLabel = VarLabel::create(""p.localized"", ParticleVariable::getTypeDescription()); pStrainRateLabel_preReloc = VarLabel::create(""p.strainRate+"", ParticleVariable::getTypeDescription()); pPlasticStrainLabel_preReloc = VarLabel::create(""p.plasticStrain+"", ParticleVariable::getTypeDescription()); pPlasticStrainRateLabel_preReloc = VarLabel::create(""p.plasticStrainRate+"", ParticleVariable::getTypeDescription()); pDamageLabel_preReloc = VarLabel::create(""p.damage+"", ParticleVariable::getTypeDescription()); pPorosityLabel_preReloc = VarLabel::create(""p.porosity+"", ParticleVariable::getTypeDescription()); pLocalizedLabel_preReloc = VarLabel::create(""p.localized+"", ParticleVariable::getTypeDescription()); } void SmallStrainPlastic::getInitialPorosityData(ProblemSpecP& ps) { d_evolvePorosity = true; ps->get(""evolve_porosity"",d_evolvePorosity); d_porosity.f0 = 0.002; // Initial porosity d_porosity.f0_std = 0.002; // Initial STD porosity d_porosity.fc = 0.5; // Critical porosity d_porosity.fn = 0.1; // Volume fraction of void nucleating particles d_porosity.en = 0.3; // Mean strain for nucleation d_porosity.sn = 0.1; // Standard deviation strain for nucleation d_porosity.porosityDist = ""constant""; ps->get(""initial_mean_porosity"", d_porosity.f0); ps->get(""initial_std_porosity"", d_porosity.f0_std); ps->get(""critical_porosity"", d_porosity.fc); ps->get(""frac_nucleation"", d_porosity.fn); ps->get(""meanstrain_nucleation"", d_porosity.en); ps->get(""stddevstrain_nucleation"", d_porosity.sn); ps->get(""initial_porosity_distrib"", d_porosity.porosityDist); } void SmallStrainPlastic::getInitialDamageData(ProblemSpecP& ps) { d_evolveDamage = true; ps->get(""evolve_damage"",d_evolveDamage); d_scalarDam.D0 = 0.0; // Initial scalar damage d_scalarDam.D0_std = 0.0; // Initial STD scalar damage d_scalarDam.Dc = 1.0; // Critical scalar damage d_scalarDam.scalarDamageDist = ""constant""; ps->get(""initial_mean_scalar_damage"", d_scalarDam.D0); ps->get(""initial_std_scalar_damage"", d_scalarDam.D0_std); ps->get(""critical_scalar_damage"", d_scalarDam.Dc); ps->get(""initial_scalar_damage_distrib"", d_scalarDam.scalarDamageDist); } void SmallStrainPlastic::setErosionAlgorithm() { d_setStressToZero = false; d_allowNoTension = false; if (flag->d_doErosion) { if (flag->d_erosionAlgorithm == ""AllowNoTension"") d_allowNoTension = true; else if (flag->d_erosionAlgorithm == ""ZeroStress"") d_setStressToZero = true; } } void SmallStrainPlastic::addParticleState(std::vector& from, std::vector& to) { // Add the local particle state data for this constitutive model. from.push_back(pStrainRateLabel); from.push_back(pPlasticStrainLabel); from.push_back(pPlasticStrainRateLabel); from.push_back(pDamageLabel); from.push_back(pPorosityLabel); from.push_back(pLocalizedLabel); to.push_back(pStrainRateLabel_preReloc); to.push_back(pPlasticStrainLabel_preReloc); to.push_back(pPlasticStrainRateLabel_preReloc); to.push_back(pDamageLabel_preReloc); to.push_back(pPorosityLabel_preReloc); to.push_back(pLocalizedLabel_preReloc); // Add the particle state for the plasticity models d_plastic->addParticleState(from, to); d_kinematic->addParticleState(from, to); } void SmallStrainPlastic::addInitialComputesAndRequires(Task* task, const MPMMaterial* matl, const PatchSet* patch) const { const MaterialSubset* matlset = matl->thisMaterial(); task->computes(pStrainRateLabel, matlset); task->computes(pPlasticStrainLabel, matlset); task->computes(pPlasticStrainRateLabel, matlset); task->computes(pDamageLabel, matlset); task->computes(pPorosityLabel, matlset); task->computes(pLocalizedLabel, matlset); // Add internal evolution variables computed by plasticity model d_plastic->addInitialComputesAndRequires(task, matl, patch); d_kinematic->addInitialComputesAndRequires(task, matl, patch); } void SmallStrainPlastic::initializeCMData(const Patch* patch, const MPMMaterial* matl, DataWarehouse* new_dw) { // Initialize the variables shared by all constitutive models // This method is defined in the ConstitutiveModel base class. if (flag->d_integrator == MPMFlags::Implicit) initSharedDataForImplicit(patch, matl, new_dw); else { initSharedDataForExplicit(patch, matl, new_dw); computeStableTimeStep(patch, matl, new_dw); } // Put stuff in here to initialize each particle's // constitutive model parameters and deformationMeasure //cout << ""Initialize CM Data in SmallStrainPlastic"" << endl; Matrix3 one, zero(0.); one.Identity(); ParticleSubset* pset = new_dw->getParticleSubset(matl->getDWIndex(), patch); ParticleVariable pPlasticStrain, pDamage, pPorosity, pPlasticStrainRate, pStrainRate; ParticleVariable pLocalized; new_dw->allocateAndPut(pStrainRate, pStrainRateLabel, pset); new_dw->allocateAndPut(pPlasticStrain, pPlasticStrainLabel, pset); new_dw->allocateAndPut(pPlasticStrainRate, pPlasticStrainRateLabel, pset); new_dw->allocateAndPut(pDamage, pDamageLabel, pset); new_dw->allocateAndPut(pLocalized, pLocalizedLabel, pset); new_dw->allocateAndPut(pPorosity, pPorosityLabel, pset); for(ParticleSubset::iterator iter = pset->begin();iter != pset->end();iter++){ pStrainRate[*iter] = 0.0; pPlasticStrain[*iter] = 0.0; pPlasticStrainRate[*iter] = 0.0; pDamage[*iter] = d_damage->initialize(); pPorosity[*iter] = d_porosity.f0; pLocalized[*iter] = 0; } // Do some extra things if the porosity or the damage distribution // is not uniform. // ** WARNING ** Weibull distribution needs to be implemented. // At present only Gaussian available. if (d_porosity.porosityDist != ""constant"") { Gaussian gaussGen(d_porosity.f0, d_porosity.f0_std, 0, 1, DBL_MAX); ParticleSubset::iterator iter = pset->begin(); for(;iter != pset->end();iter++){ // Generate a Gaussian distributed random number given the mean // porosity and the std. pPorosity[*iter] = fabs(gaussGen.rand(1.0)); } } if (d_scalarDam.scalarDamageDist != ""constant"") { Gaussian gaussGen(d_scalarDam.D0, d_scalarDam.D0_std, 0, 1,DBL_MAX); ParticleSubset::iterator iter = pset->begin(); for(;iter != pset->end();iter++){ // Generate a Gaussian distributed random number given the mean // damage and the std. pDamage[*iter] = fabs(gaussGen.rand(1.0)); } } // Initialize the data for the plasticity model d_plastic->initializeInternalVars(pset, new_dw); d_kinematic->initializeBackStress(pset, new_dw); } void SmallStrainPlastic::computeStableTimeStep(const Patch* patch, const MPMMaterial* matl, DataWarehouse* new_dw) { // This is only called for the initial timestep - all other timesteps // are computed as a side-effect of computeStressTensor Vector dx = patch->dCell(); int matlindex = matl->getDWIndex(); // Retrieve the array of constitutive parameters ParticleSubset* pset = new_dw->getParticleSubset(matlindex, patch); constParticleVariable pMass, pVol_new; constParticleVariable pVelocity; new_dw->get(pMass, lb->pMassLabel, pset); new_dw->get(pVol_new, lb->pVolumeLabel, pset); new_dw->get(pVelocity, lb->pVelocityLabel, pset); double c_dil = 0.0; Vector waveSpeed(1.e-12,1.e-12,1.e-12); double shear = d_initialData.Shear; double bulk = d_initialData.Bulk; ParticleSubset::iterator iter = pset->begin(); for(; iter != pset->end(); iter++){ particleIndex idx = *iter; // Compute wave speed at each particle, store the maximum Vector pvelocity_idx = pVelocity[idx]; if(pMass[idx] > 0){ c_dil = sqrt((bulk + 4.0*shear/3.0)*pVol_new[idx]/pMass[idx]); } else { c_dil = 0.0; pvelocity_idx = Vector(0.0,0.0,0.0); } waveSpeed=Vector(Max(c_dil+fabs(pvelocity_idx.x()),waveSpeed.x()), Max(c_dil+fabs(pvelocity_idx.y()),waveSpeed.y()), Max(c_dil+fabs(pvelocity_idx.z()),waveSpeed.z())); } waveSpeed = dx/waveSpeed; double delT_new = waveSpeed.minComponent(); new_dw->put(delt_vartype(delT_new), lb->delTLabel, patch->getLevel()); } void SmallStrainPlastic::addComputesAndRequires(Task* task, const MPMMaterial* matl, const PatchSet* patches) const { // Add the computes and requires that are common to all explicit // constitutive models. The method is defined in the ConstitutiveModel // base class. Ghost::GhostType gnone = Ghost::None; const MaterialSubset* matlset = matl->thisMaterial(); if (flag->d_integrator == MPMFlags::Implicit) { addSharedCRForImplicit(task, matlset, patches); } else { addSharedCRForHypoExplicit(task, matlset, patches); } // Other constitutive model and input dependent computes and requires task->requires(Task::OldDW, lb->pTempPreviousLabel, matlset, gnone); task->requires(Task::OldDW, pStrainRateLabel, matlset, gnone); task->requires(Task::OldDW, pPlasticStrainLabel, matlset, gnone); task->requires(Task::OldDW, pPlasticStrainRateLabel,matlset, gnone); task->requires(Task::OldDW, pDamageLabel, matlset, gnone); task->requires(Task::OldDW, pPorosityLabel, matlset, gnone); task->requires(Task::OldDW, pLocalizedLabel, matlset, gnone); task->computes(pStrainRateLabel_preReloc, matlset); task->computes(pPlasticStrainLabel_preReloc, matlset); task->computes(pPlasticStrainRateLabel_preReloc, matlset); task->computes(pDamageLabel_preReloc, matlset); task->computes(pPorosityLabel_preReloc, matlset); task->computes(pLocalizedLabel_preReloc, matlset); // Add internal evolution variables computed by plasticity model d_plastic->addComputesAndRequires(task, matl, patches); d_kinematic->addComputesAndRequires(task, matl, patches); } void SmallStrainPlastic::computeStressTensor(const PatchSubset* patches, const MPMMaterial* matl, DataWarehouse* old_dw, DataWarehouse* new_dw) { if (flag->d_integrator == MPMFlags::Implicit) { computeStressTensorImplicit(patches, matl, old_dw, new_dw); } else { computeStressTensorExplicit(patches, matl, old_dw, new_dw); } } void SmallStrainPlastic::computeStressTensorExplicit(const PatchSubset* patches, const MPMMaterial* matl, DataWarehouse* old_dw, DataWarehouse* new_dw) { // General stuff Matrix3 one; one.Identity(); Matrix3 zero(0.0); Matrix3 rightStretch; rightStretch.Identity(); Matrix3 rotation; rotation.Identity(); Matrix3 rateOfDef_new(0.0); Matrix3 rateOfDef_dev_new(0.0); Matrix3 sigma_old(0.0); Matrix3 sigma_dev_old(0.0); Matrix3 sigma_dev_new(0.0); Matrix3 backStress_old(0.0); Matrix3 backStress_dev_old(0.0); Matrix3 backStress_new(0.0); Vector waveSpeed(1.e-12,1.e-12,1.e-12); double bulk = d_initialData.Bulk; double shear = d_initialData.Shear; double CTE = d_initialData.CTE; double rho_0 = matl->getInitialDensity(); double Tm = matl->getMeltTemperature(); double sqrtThreeTwo = sqrt(1.5); double sqrtTwoThird = 1.0/sqrtThreeTwo; double totalStrainEnergy = 0.0; // Do thermal expansion? if (!flag->d_doThermalExpansion) { CTE = 0.0; } // Loop thru patches for(int patchIndex=0; patchIndexsize(); patchIndex++){ const Patch* patch = patches->get(patchIndex); // Get grid size Vector dx = patch->dCell(); // Get the set of particles int dwi = matl->getDWIndex(); ParticleSubset* pset = old_dw->getParticleSubset(dwi, patch); // GET GLOBAL DATA // Get the deformation gradient (F) constParticleVariable pVol_new; constParticleVariable pVelGrad_new, pDefGrad_new; new_dw->get(pVol_new, lb->pVolumeLabel_preReloc, pset); new_dw->get(pVelGrad_new, lb->pVelGradLabel_preReloc, pset); new_dw->get(pDefGrad_new, lb->pDeformationMeasureLabel_preReloc, pset); // Get the particle location, particle size, particle mass, particle volume constParticleVariable px; constParticleVariable pMass; old_dw->get(px, lb->pXLabel, pset); old_dw->get(pMass, lb->pMassLabel, pset); // Get the velocity from the grid and particle velocity constParticleVariable pVelocity; old_dw->get(pVelocity, lb->pVelocityLabel, pset); // Get the particle stress and temperature constParticleVariable pStress_old; constParticleVariable pTempPrev, pTemp_old; old_dw->get(pStress_old, lb->pStressLabel, pset); old_dw->get(pTempPrev, lb->pTempPreviousLabel, pset); old_dw->get(pTemp_old, lb->pTemperatureLabel, pset); // Get the time increment (delT) delt_vartype delT; old_dw->get(delT, lb->delTLabel, getLevel(patches)); // GET LOCAL DATA constParticleVariable pPlasticStrain_old, pDamage_old, pPorosity_old, pStrainRate_old, pPlasticStrainRate_old; old_dw->get(pPlasticStrain_old, pPlasticStrainLabel, pset); old_dw->get(pDamage_old, pDamageLabel, pset); old_dw->get(pStrainRate_old, pStrainRateLabel, pset); old_dw->get(pPlasticStrainRate_old, pPlasticStrainRateLabel, pset); old_dw->get(pPorosity_old, pPorosityLabel, pset); constParticleVariable pLocalized_old; old_dw->get(pLocalized_old, pLocalizedLabel, pset); // Create and allocate arrays for storing the updated information // GLOBAL ParticleVariable pStress_new; ParticleVariable pdTdt, p_q; new_dw->allocateAndPut(pStress_new, lb->pStressLabel_preReloc, pset); new_dw->allocateAndPut(pdTdt, lb->pdTdtLabel_preReloc, pset); new_dw->allocateAndPut(p_q, lb->p_qLabel_preReloc, pset); // LOCAL ParticleVariable pPlasticStrain_new, pDamage_new, pPorosity_new, pStrainRate_new, pPlasticStrainRate_new; ParticleVariable pLocalized_new; new_dw->allocateAndPut(pStrainRate_new, pStrainRateLabel_preReloc, pset); new_dw->allocateAndPut(pPlasticStrain_new, pPlasticStrainLabel_preReloc, pset); new_dw->allocateAndPut(pPlasticStrainRate_new, pPlasticStrainRateLabel_preReloc, pset); new_dw->allocateAndPut(pDamage_new, pDamageLabel_preReloc, pset); new_dw->allocateAndPut(pPorosity_new, pPorosityLabel_preReloc, pset); new_dw->allocateAndPut(pLocalized_new, pLocalizedLabel_preReloc, pset); // Get the plastic strain and back stress and allocate // space for the updated internal variables and back stress d_plastic->getInternalVars(pset, old_dw); d_plastic->allocateAndPutInternalVars(pset, new_dw); d_kinematic->getBackStress(pset, old_dw); d_kinematic->allocateAndPutBackStress(pset, new_dw); // Loop thru particles ParticleSubset::iterator iter = pset->begin(); for( ; iter != pset->end(); iter++){ particleIndex idx = *iter; // Assign zero internal heating by default - modify if necessary. pdTdt[idx] = 0.0; double J_new = pDefGrad_new[idx].Determinant(); // If the erosion algorithm sets the stress to zero then don't allow // any deformation. if(d_setStressToZero && pLocalized_old[idx]){ // **WARNING** TODO: Need to carry foward other data too pStress_new[idx] = zero; continue; } // Check 1: Check for negative Jacobian (determinant of deformation gradient) if (!(J_new > 0.0)) { cerr << getpid() << ""**ERROR** Negative Jacobian of deformation gradient"" << "" in particle "" << idx << endl; cerr << ""l = "" << pVelGrad_new[idx] << endl; cerr << ""F_new = "" << pDefGrad_new[idx] << endl; cerr << ""J_new = "" << J_new << endl; throw ParameterNotFound(""**ERROR**:InvalidValue: J < 0.0"", __FILE__, __LINE__); } // Calculate the current density and deformed volume double rho_cur = rho_0/J_new; // Compute polar decomposition of F (F = RU) pDefGrad_new[idx].polarDecompositionRMB(rightStretch, rotation); // Calculate rate of deformation tensor (D) rateOfDef_new = (pVelGrad_new[idx] + pVelGrad_new[idx].Transpose())*0.5; // Rotate the total rate of deformation tensor back to the // material configuration rateOfDef_new = (rotation.Transpose())*(rateOfDef_new*rotation); pStrainRate_new[idx] = sqrtTwoThird*rateOfDef_new.Norm(); // Calculate the deviatoric part of the non-thermal part // of the rate of deformation tensor rateOfDef_dev_new = rateOfDef_new - one*(rateOfDef_new.Trace()/3.0); // Rotate the Cauchy stress back to the // material configuration and calculate the deviatoric part sigma_old = pStress_old[idx]; sigma_old = (rotation.Transpose())*(sigma_old*rotation); double pressure_old = sigma_old.Trace()/3.0; sigma_dev_old = sigma_old - one*pressure_old; // Get the back stress from the kinematic hardening model and rotate d_kinematic->getBackStress(idx, backStress_old); backStress_old = (rotation.Transpose())*(backStress_old*rotation); backStress_dev_old = backStress_old - one*(backStress_old.Trace()/3.0); backStress_new = backStress_old; // Set up the ModelState (for t_n) UintahBB::ModelState* state = scinew UintahBB::ModelState(); state->strainRate = pStrainRate_new[idx]; state->plasticStrainRate = pPlasticStrainRate_old[idx]; state->plasticStrain = pPlasticStrain_old[idx]; state->pressure = pressure_old; state->temperature = pTemp_old[idx]; state->initialTemperature = d_initialMaterialTemperature; state->density = rho_cur; state->initialDensity = rho_0; state->volume = pVol_new[idx]; state->initialVolume = pMass[idx]/rho_0; state->bulkModulus = bulk; state->initialBulkModulus = bulk; state->shearModulus = shear; state->initialShearModulus = shear; state->meltingTemp = Tm; state->initialMeltTemp = Tm; state->specificHeat = matl->getSpecificHeat(); state->porosity = pPorosity_old[idx]; state->backStress = backStress_old; // Compute the pressure double pressure_new = d_eos->computePressure(matl, state, pDefGrad_new[idx], rateOfDef_new, delT); state->pressure = pressure_new; // Get or compute the specific heat if (d_computeSpecificHeat) { double C_p = d_Cp->computeSpecificHeat(state); state->specificHeat = C_p; } // Calculate the shear modulus and the melting temperature at the // start of the time step and update the plasticity state double Tm_cur = d_melt->computeMeltingTemp(state); state->meltingTemp = Tm_cur ; double mu_cur = d_shear->computeShearModulus(state); state->shearModulus = mu_cur ; // compute the local sound wave speed double c_dil = sqrt((bulk + 4.0*mu_cur/3.0)/rho_cur); //----------------------------------------------------------------------- // Stage 2: Elastic-plastic stress update //----------------------------------------------------------------------- // Keep the temperature constant over the time step double T_new = state->temperature; // Calculate flow stress double flowStress = d_plastic->computeFlowStress(state, delT, d_tol, matl, idx); state->yieldStress = flowStress; // Material has melted if flowStress <= 0.0 bool melted = false; bool plastic = false; if (T_new > Tm_cur || flowStress <= 0.0) { melted = true; // Set the deviatoric stress to zero if (d_doMelting) sigma_dev_old = 0.0; d_plastic->updateElastic(idx); d_kinematic->updateBackStress(idx, Matrix3(0.0)); } else { plastic = true; // Integrate the stress rate equation to get a trial deviatoric stress Matrix3 sigma_dev_trial = sigma_dev_old + rateOfDef_dev_new*(2.0*mu_cur*delT); // Compute xi_trial = s_trial - beta_n Matrix3 xi_trial = sigma_dev_trial - backStress_dev_old; // Check whether the step is elastic or plastic double f_0 = d_yield->evalYieldCondition(xi_trial, state); if (std::isnan(f_0)) { cout << ""idx = "" << idx << "" epdot = "" << state->plasticStrainRate << "" ep = "" << state->plasticStrain << "" T = "" << state->temperature << "" p = "" << state->pressure << "" sigy = "" << state->yieldStress << endl; throw InvalidValue(""**ERROR**:SmallStrainPlastic: f_0 = nan."", __FILE__, __LINE__); } if (f_0 < 0.0) { // Set the elastic stress to the trial stress sigma_dev_new = sigma_dev_trial; // Update the internal variables d_plastic->updateElastic(idx); d_kinematic->updateBackStress(idx, backStress_old); } else { Matrix3 xi_n = sigma_dev_old - backStress_dev_old; if (!(xi_n.NormSquared() > 0.0)) { cout << ""Particle idx = "" << idx << "" has zero deviatoric stress. Reduce initial time step size"" << "" and restart. "" << endl; throw InvalidValue(""**ERROR**:SmallStrainPlastic: Lower time step"", __FILE__, __LINE__); } // Get ep_n, phi_n double ep_n = state->plasticStrain; double phi_n = state->porosity; // Compute r_k, h_k Matrix3 xi_k = xi_trial; Matrix3 r_k(0.0); d_yield->eval_df_dsigma(xi_k, state, r_k); double h_alpha_k = d_yield->eval_h_alpha(xi_k, state); double A_k = voidNucleationFactor(state->plasticStrain); double h_phi_k = d_yield->eval_h_phi(xi_k, A_k, state); Matrix3 h_beta_k(0.0); d_kinematic->eval_h_beta(r_k, state, h_beta_k); Matrix3 r_k_dev = r_k - one*(r_k.Trace()/3.0); Matrix3 h_beta_k_dev = h_beta_k - one*(h_beta_k.Trace()/3.0); Matrix3 term1_k = r_k_dev*(2.0*mu_cur) + h_beta_k_dev; // Iterate to find DeltaGamma int count = 0; double Delta_gamma = 0.0; double f_k = f_0; while (f_k > d_tol) { // Get the derivatives of the yield function Matrix3 df_dxi_k(0.0); d_yield->eval_df_dxi(xi_k, state, df_dxi_k); double dsigy_dep_k = d_plastic->evalDerivativeWRTPlasticStrain(state, idx); double df_dep_k = d_yield->eval_df_dep(xi_k, dsigy_dep_k, state); double df_dphi_k = d_yield->eval_df_dphi(xi_k, state); // compute delta gamma (k) double denom = df_dxi_k.Contract(term1_k) - h_alpha_k*df_dep_k - h_phi_k*df_dphi_k; double delta_gamma_k = f_k/denom; if (std::isnan(f_k) || std::isnan(delta_gamma_k)) { cout << ""idx = "" << idx << "" iter = "" << count << "" f_k = "" << f_k << "" delta_gamma_k = "" << delta_gamma_k << "" sigy = "" << state->yieldStress << "" dsigy_dep_k = "" << dsigy_dep_k << "" df_dep_k = "" << df_dep_k << "" epdot = "" << state->plasticStrainRate << "" ep = "" << state->plasticStrain << endl; cout << ""df_dxi = \\n"" << df_dxi_k << ""\\n term1 = "" << term1_k << ""\\n h_alpha = "" << h_alpha_k << "" df_dep = "" << df_dep_k << ""\\n h_phi = "" << h_phi_k << "" df_dphi = "" << df_dphi_k << "" denom = "" << denom << endl; throw InvalidValue(""**ERROR**:SmallStrainPlastic: Found nan."", __FILE__, __LINE__); } // Update Delta_gamma double Delta_gamma_old = Delta_gamma; Delta_gamma += delta_gamma_k; if (Delta_gamma < 0.0) { cout << ""Delta_gamma = "" << Delta_gamma << endl; cout << ""h_alpha = "" << h_alpha_k << "" delta_gamma = "" << delta_gamma_k << "" ep = "" << state->plasticStrain << endl; cout << ""idx = "" << idx << "" iter = "" << count << "" f_k = "" << f_k << "" delta_gamma_k = "" << delta_gamma_k << "" sigy = "" << state->yieldStress << "" dsigy_dep_k = "" << dsigy_dep_k << "" df_dep_k = "" << df_dep_k << "" epdot = "" << state->plasticStrainRate << "" ep = "" << state->plasticStrain << endl; cout << ""xi = \\n"" << xi_k << ""\\n df_dxi:term1 = ""<< df_dxi_k.Contract(term1_k) << ""\\n df_dxi = \\n"" << df_dxi_k << ""\\n term1 = "" << term1_k << ""\\n h_alpha = "" << h_alpha_k << "" df_dep = "" << df_dep_k << ""\\n h_phi = "" << h_phi_k << "" df_dphi = "" << df_dphi_k << "" denom = "" << denom << endl; cout << ""r_n_dev = \\n"" << r_k_dev << ""\\n mu_cur = "" << mu_cur << ""\\n h_bet_n_dev = \\n"" << h_beta_k_dev << endl; } /* Updated algorithm - use value of xi_k */ // Compute r_k, h_k d_yield->eval_df_dsigma(xi_k, state, r_k); h_alpha_k = d_yield->eval_h_alpha(xi_k, state); A_k = voidNucleationFactor(state->plasticStrain); h_phi_k = d_yield->eval_h_phi(xi_k, A_k, state); d_kinematic->eval_h_beta(r_k, state, h_beta_k); r_k_dev = r_k - one*(r_k.Trace()/3.0); h_beta_k_dev = h_beta_k - one*(h_beta_k.Trace()/3.0); term1_k = r_k_dev*(2.0*mu_cur) + h_beta_k_dev; // Update ep, phi, xi state->plasticStrain = ep_n + Delta_gamma*h_alpha_k; state->porosity = phi_n + Delta_gamma*h_phi_k; xi_k = xi_trial - term1_k*Delta_gamma; /* Original Algorithm */ /* // compute increments of xi, ep, phi Matrix3 Delta_xi_k = term1*(-delta_gamma_k); double Delta_ep_k = h_alpha_n*delta_gamma_k; double Delta_phi_k = h_phi_n*delta_gamma_k; // Update ep, phi, xi, Delta_gamma state->plasticStrain += Delta_ep_k; state->porosity += Delta_phi_k; xi_k += Delta_xi_k; */ if (fabs(Delta_gamma-Delta_gamma_old) < d_tol || count > 100) break; // Update the flow stress state->yieldStress = d_plastic->computeFlowStress(state, delT, d_tol, matl, idx); // Check yield condition. The state variable contains // ep_k, phi_k, beta_k f_k = d_yield->evalYieldCondition(xi_k, state); ++count; } // Update the back stress and deviatoric stress Matrix3 r_new(0.0); d_yield->eval_df_dsigma(xi_k, state, r_new); Matrix3 h_beta_new(0.0); d_kinematic->eval_h_beta(r_new, state, h_beta_new); backStress_new = backStress_old + h_beta_new*Delta_gamma; state->backStress = backStress_new; Matrix3 backStress_dev_new = backStress_new - one*(backStress_new.Trace()/3.0); sigma_dev_new = xi_k + backStress_dev_new; // Update the plastic strain rate double h_alpha_new = d_yield->eval_h_alpha(xi_k, state); state->plasticStrainRate = Delta_gamma/delT*h_alpha_new; // Update internal variables d_plastic->updatePlastic(idx, Delta_gamma); // Calculate rate of temperature increase due to plastic strain double taylorQuinney = d_initialData.Chi; double fac = taylorQuinney/(rho_cur*state->specificHeat); // Calculate Tdot (internal plastic heating rate). This // is used during the solution of the heat equation. double Tdot = state->yieldStress*state->plasticStrainRate*fac; pdTdt[idx] = Tdot*d_isothermal; // Calculate a local change in temperature due to adiabatic // heating for the purpose of thermal expansion corrections. // If isothermal conditions exist then d_isothermal = 0. T_new += (Tdot*delT*d_isothermal); } // end of Phi if } // end of temperature if // Calculate the total stress double T_0 = state->initialTemperature; double kappa_new = d_eos->eval_dp_dJ(matl, J_new, state); kappa_new *= J_new; Matrix3 sigma_new = sigma_dev_new + one*(pressure_new - 3.0*kappa_new*CTE*(T_new - T_0)); // If the particle has already failed, apply various erosion algorithms if (flag->d_doErosion) { if (pLocalized_old[idx]) { if (d_allowNoTension) { if (pressure_new > 0.0) sigma_new = zero; else sigma_new = one*pressure_new; } else if (d_setStressToZero) sigma_new = zero; } } //----------------------------------------------------------------------- // Stage 3: Compute damage //----------------------------------------------------------------------- if (!plastic) { // Save the updated data pPlasticStrain_new[idx] = pPlasticStrain_old[idx]; pPlasticStrainRate_new[idx] = 0.0; pPorosity_new[idx] = pPorosity_old[idx]; pDamage_new[idx] = pDamage_old[idx]; } else { // Update the plastic strain, plastic strain rate, porosity pPlasticStrain_new[idx] = state->plasticStrain; pPlasticStrainRate_new[idx] = state->plasticStrainRate; if (d_evolvePorosity) { pPorosity_new[idx] = state->porosity; } else { pPorosity_new[idx] = pPorosity_old[idx]; } // Calculate the updated scalar damage parameter if (d_evolveDamage) { pDamage_new[idx] = d_damage->computeScalarDamage(state->plasticStrainRate, sigma_new, T_new, delT, matl, d_tol, pDamage_old[idx]); } else { pDamage_new[idx] = pDamage_old[idx]; } } //----------------------------------------------------------------------- // Stage 4: //----------------------------------------------------------------------- // Find if the particle has failed/localized pLocalized_new[idx] = pLocalized_old[idx]; bool isLocalized = false; double tepla = 0.0; if (flag->d_doErosion) { // Check 1: Look at the temperature if (melted) isLocalized = true; // Check 2 and 3: Look at TEPLA and stability else if (plastic) { // Check 2: Modified Tepla rule if (d_checkTeplaFailureCriterion) { tepla = pow(pPorosity_new[idx]/d_porosity.fc,2.0) + pow(pDamage_new[idx],2.0); if (tepla > 1.0) isLocalized = true; } // Check 3: Stability criterion (only if material is plastic) if (d_stable->doIt() && !isLocalized) { // Calculate values needed for tangent modulus calculation state->temperature = T_new; Tm_cur = d_melt->computeMeltingTemp(state); state->meltingTemp = Tm_cur ; mu_cur = d_shear->computeShearModulus(state); state->shearModulus = mu_cur ; state->yieldStress = d_plastic->computeFlowStress(state, delT, d_tol, matl, idx); if (!(state->yieldStress > 0.0)) isLocalized = true; else { // Get the derivatives of the yield function Matrix3 xi_hat = sigma_new - backStress_new; Matrix3 xi = xi_hat - one*(xi_hat.Trace()/3.0); Matrix3 rr(0.0); d_yield->eval_df_dsigma(xi, state, rr); Matrix3 df_ds(0.0), df_dbeta(0.0); d_yield->eval_df_ds_df_dbeta(xi, state, df_ds, df_dbeta); Matrix3 h_beta(0.0); d_kinematic->eval_h_beta(rr, state, h_beta); Matrix3 r_dev = rr - one*(rr.Trace()/3.0); Matrix3 h_beta_dev = h_beta - one*(h_beta.Trace()/3.0); double dsigy_dep = d_plastic->evalDerivativeWRTPlasticStrain(state, idx); double df_dep = d_yield->eval_df_dep(xi, dsigy_dep, state); double h_alpha = d_yield->eval_h_alpha(xi, state); double df_dphi = d_yield->eval_df_dphi(xi, state); double A = voidNucleationFactor(state->plasticStrain); double h_phi = d_yield->eval_h_phi(xi, A, state); double dp_dJ = d_eos->eval_dp_dJ(matl, J_new, state); // Calculate the elastic-plastic tangent modulus TangentModulusTensor Cep; d_yield->computeElasPlasTangentModulus(rr, df_ds, h_beta, df_dbeta, h_alpha, df_dep, h_phi, df_dphi, J_new, dp_dJ, state, Cep); // Initialize localization direction Vector direction(0.0,0.0,0.0); isLocalized = d_stable->checkStability(sigma_new, rateOfDef_new, Cep, direction); } } } // Check 4: Look at maximum stress if (d_checkStressTriax) { // Compute eigenvalues of the stress tensor SymmMatrix3 stress(sigma_new); Vector eigVal(0.0, 0.0, 0.0); Matrix3 eigVec; stress.eigen(eigVal, eigVec); double max_stress = Max(Max(eigVal[0],eigVal[1]), eigVal[2]); if (max_stress > d_initialData.sigma_crit) { isLocalized = true; } } // Use erosion algorithms to treat localized particles if (isLocalized) { // If the localized particles fail again then set their stress to zero if (pLocalized_old[idx]) { pDamage_new[idx] = 0.0; pPorosity_new[idx] = 0.0; sigma_new = zero; } else { // set the particle localization flag to true pLocalized_new[idx] = 1; pDamage_new[idx] = 0.0; pPorosity_new[idx] = 0.0; // Apply various erosion algorithms if (d_allowNoTension) { if (pressure_new > 0.0) sigma_new = zero; else sigma_new = one*pressure_new; } else if (d_setStressToZero) sigma_new = zero; } } } //----------------------------------------------------------------------- // Stage 5: //----------------------------------------------------------------------- // Rotate the stress/backStress back to the laboratory coordinates // Update the stress/back stress // Use new rotation pDefGrad_new[idx].polarDecompositionRMB(rightStretch, rotation); backStress_new = (rotation*backStress_new)*(rotation.Transpose()); sigma_new = (rotation*sigma_new)*(rotation.Transpose()); d_kinematic->updateBackStress(idx, backStress_new); pStress_new[idx] = sigma_new; // Rotate the deformation rate back to the laboratory coordinates rateOfDef_new = (rotation*rateOfDef_new)*(rotation.Transpose()); // Compute the strain energy for non-localized particles if(pLocalized_new[idx] == 0){ Matrix3 avgStress = (pStress_new[idx] + pStress_old[idx])*0.5; double pStrainEnergy = (rateOfDef_new(0,0)*avgStress(0,0) + rateOfDef_new(1,1)*avgStress(1,1) + rateOfDef_new(2,2)*avgStress(2,2) + 2.0*(rateOfDef_new(0,1)*avgStress(0,1) + rateOfDef_new(0,2)*avgStress(0,2) + rateOfDef_new(1,2)*avgStress(1,2)))* pVol_new[idx]*delT; totalStrainEnergy += pStrainEnergy; } // Compute wave speed at each particle, store the maximum Vector pVel = pVelocity[idx]; waveSpeed=Vector(Max(c_dil+fabs(pVel.x()),waveSpeed.x()), Max(c_dil+fabs(pVel.y()),waveSpeed.y()), Max(c_dil+fabs(pVel.z()),waveSpeed.z())); // Compute artificial viscosity term double de_s=0.; if (flag->d_artificial_viscosity) { double dx_ave = (dx.x() + dx.y() + dx.z())/3.0; double c_bulk = sqrt(bulk/rho_cur); Matrix3 D=(pVelGrad_new[idx] + pVelGrad_new[idx].Transpose())*0.5; double Dkk=D.Trace(); p_q[idx] = artificialBulkViscosity(Dkk, c_bulk, rho_cur, dx_ave); de_s = -p_q[idx]*Dkk/rho_cur; } else { p_q[idx] = 0.; de_s = 0.; } pdTdt[idx] += de_s/state->specificHeat; delete state; } // end loop over particles waveSpeed = dx/waveSpeed; double delT_new = waveSpeed.minComponent(); new_dw->put(delt_vartype(delT_new), lb->delTLabel, patch->getLevel()); if (flag->d_reductionVars->accStrainEnergy || flag->d_reductionVars->strainEnergy) { new_dw->put(sum_vartype(totalStrainEnergy), lb->StrainEnergyLabel); } } if (cout_EP.active()) cout_EP << getpid() << ""... End."" << endl; } void SmallStrainPlastic::computeStressTensorImplicit(const PatchSubset* patches, const MPMMaterial* matl, DataWarehouse* old_dw, DataWarehouse* new_dw) { throw InvalidValue(""**ERROR**:SmallStrainPlastic: No implicit stress update available"", __FILE__, __LINE__); } void SmallStrainPlastic::addComputesAndRequires(Task* task, const MPMMaterial* matl, const PatchSet* patches, const bool recurse, const bool SchedParent) const { const MaterialSubset* matlset = matl->thisMaterial(); addSharedCRForImplicit(task, matlset, patches, recurse, SchedParent); // Local stuff Ghost::GhostType gnone = Ghost::None; if(SchedParent){ task->requires(Task::ParentOldDW, lb->pTempPreviousLabel, matlset, gnone); task->requires(Task::ParentOldDW, lb->pTemperatureLabel, matlset, gnone); task->requires(Task::ParentOldDW, pPlasticStrainLabel, matlset, gnone); task->requires(Task::ParentOldDW, pPlasticStrainRateLabel, matlset, gnone); task->requires(Task::ParentOldDW, pPorosityLabel, matlset, gnone); }else{ task->requires(Task::OldDW, lb->pTempPreviousLabel, matlset, gnone); task->requires(Task::OldDW, lb->pTemperatureLabel, matlset, gnone); task->requires(Task::OldDW, pPlasticStrainLabel, matlset, gnone); task->requires(Task::OldDW, pPlasticStrainRateLabel, matlset, gnone); task->requires(Task::OldDW, pPorosityLabel, matlset, gnone); } // Add internal evolution variables computed by plasticity model d_plastic->addComputesAndRequires(task, matl, patches, recurse,SchedParent); d_kinematic->addComputesAndRequires(task, matl, patches, recurse); } void SmallStrainPlastic::computeStressTensor(const PatchSubset* patches, const MPMMaterial* matl, DataWarehouse* old_dw, DataWarehouse* new_dw, Solver* solver, const bool ) { throw InvalidValue(""**ERROR**:SmallStrainPlastic: No implicit stress update available"", __FILE__, __LINE__); } /*! Compute the elastic-plastic tangent modulus tensor for isotropic materials for use in the implicit stress update Assume: [stress] = [s11 s22 s33 s12 s23 s31] [strain] = [e11 e22 e33 2e12 2e23 2e31] Uses alogorithm for small strain plasticity (Simo 1998, p.124) */ void SmallStrainPlastic::computeEPlasticTangentModulus(const double& K, const double& mu, const double& delGamma, const double& normTrialS, const particleIndex idx, const Matrix3& n, UintahBB::ModelState* state, double Cep[6][6], bool consistent) { throw InvalidValue(""**ERROR**:SmallStrainPlastic: No elastic-plastic tangent modulus available"", __FILE__, __LINE__); } /*! Compute K matrix */ void SmallStrainPlastic::computeStiffnessMatrix(const double B[6][24], const double Bnl[3][24], const double D[6][6], const Matrix3& sig, const double& vol_old, const double& vol_new, double Kmatrix[24][24]) { throw InvalidValue(""**ERROR**:SmallStrainPlastic: No stiffness matrix available"", __FILE__, __LINE__); } void SmallStrainPlastic::BnlTSigBnl(const Matrix3& sig, const double Bnl[3][24], double Kgeo[24][24]) const { throw InvalidValue(""**ERROR**:SmallStrainPlastic: No geometric stiffness matrix available"", __FILE__, __LINE__); } void SmallStrainPlastic::carryForward(const PatchSubset* patches, const MPMMaterial* matl, DataWarehouse* old_dw, DataWarehouse* new_dw) { for(int p=0;psize();p++){ const Patch* patch = patches->get(p); int dwi = matl->getDWIndex(); ParticleSubset* pset = old_dw->getParticleSubset(dwi, patch); // Carry forward the data common to all constitutive models // when using RigidMPM. // This method is defined in the ConstitutiveModel base class. carryForwardSharedData(pset, old_dw, new_dw, matl); // Carry forward the data local to this constitutive model constParticleVariable pPlasticStrain, pDamage, pPorosity, pStrainRate, pPlasticStrainRate; constParticleVariable pLocalized; old_dw->get(pStrainRate, pStrainRateLabel, pset); old_dw->get(pPlasticStrain, pPlasticStrainLabel, pset); old_dw->get(pPlasticStrainRate, pPlasticStrainRateLabel, pset); old_dw->get(pDamage, pDamageLabel, pset); old_dw->get(pPorosity, pPorosityLabel, pset); old_dw->get(pLocalized, pLocalizedLabel, pset); ParticleVariable pPlasticStrain_new, pDamage_new, pPorosity_new, pStrainRate_new, pPlasticStrainRate_new; ParticleVariable pLocalized_new; new_dw->allocateAndPut(pStrainRate_new, pStrainRateLabel_preReloc, pset); new_dw->allocateAndPut(pPlasticStrain_new, pPlasticStrainLabel_preReloc, pset); new_dw->allocateAndPut(pPlasticStrainRate_new, pPlasticStrainRateLabel_preReloc, pset); new_dw->allocateAndPut(pDamage_new, pDamageLabel_preReloc, pset); new_dw->allocateAndPut(pPorosity_new, pPorosityLabel_preReloc, pset); new_dw->allocateAndPut(pLocalized_new, pLocalizedLabel_preReloc, pset); // Get the plastic strain d_plastic->getInternalVars(pset, old_dw); d_plastic->allocateAndPutRigid(pset, new_dw); d_kinematic->getBackStress(pset, old_dw); d_kinematic->allocateAndPutRigid(pset, new_dw); for(ParticleSubset::iterator iter = pset->begin(); iter != pset->end(); iter++){ particleIndex idx = *iter; pStrainRate_new[idx] = pStrainRate[idx]; pPlasticStrain_new[idx] = pPlasticStrain[idx]; pPlasticStrainRate_new[idx] = pPlasticStrainRate[idx]; pDamage_new[idx] = pDamage[idx]; pPorosity_new[idx] = pPorosity[idx]; pLocalized_new[idx] = pLocalized[idx]; } new_dw->put(delt_vartype(1.e10), lb->delTLabel, patch->getLevel()); if (flag->d_reductionVars->accStrainEnergy || flag->d_reductionVars->strainEnergy) { new_dw->put(sum_vartype(0.), lb->StrainEnergyLabel); } } } void SmallStrainPlastic::addRequiresDamageParameter(Task* task, const MPMMaterial* matl, const PatchSet* ) const { const MaterialSubset* matlset = matl->thisMaterial(); task->requires(Task::NewDW, pLocalizedLabel_preReloc,matlset,Ghost::None); } void SmallStrainPlastic::getDamageParameter(const Patch* patch, ParticleVariable& damage, int dwi, DataWarehouse* old_dw, DataWarehouse* new_dw) { ParticleSubset* pset = old_dw->getParticleSubset(dwi,patch); constParticleVariable pLocalized; new_dw->get(pLocalized, pLocalizedLabel_preReloc, pset); ParticleSubset::iterator iter; for (iter = pset->begin(); iter != pset->end(); iter++) { damage[*iter] = pLocalized[*iter]; } } // Calculate the void nucleation factor inline double SmallStrainPlastic::voidNucleationFactor(double ep) { double temp = (ep - d_porosity.en)/d_porosity.sn; double A = d_porosity.fn/(d_porosity.sn*sqrt(2.0*M_PI))* exp(-0.5*temp*temp); return A; } double SmallStrainPlastic::computeRhoMicroCM(double pressure, const double p_ref, const MPMMaterial* matl, double temperature, double rho_guess) { double rho_orig = matl->getInitialDensity(); double bulk = d_initialData.Bulk; double p_gauge = pressure - p_ref; double rho_cur; if(d_useModifiedEOS && p_gauge < 0.0) { double A = p_ref; // modified EOS double n = p_ref/bulk; rho_cur = rho_orig*pow(pressure/A,n); } else { // Standard EOS double p_g_over_bulk = p_gauge/bulk; rho_cur=rho_orig*(p_g_over_bulk + sqrt(p_g_over_bulk*p_g_over_bulk +1.)); } return rho_cur; } void SmallStrainPlastic::computePressEOSCM(double rho_cur,double& pressure, double p_ref, double& dp_drho, double& tmp, const MPMMaterial* matl, double temperature) { double bulk = d_initialData.Bulk; double rho_orig = matl->getInitialDensity(); double inv_rho_orig = 1./rho_orig; if(d_useModifiedEOS && rho_cur < rho_orig){ double A = p_ref; // MODIFIED EOS double n = bulk/p_ref; double rho_rat_to_the_n = pow(rho_cur/rho_orig,n); pressure = A*rho_rat_to_the_n; dp_drho = (bulk/rho_cur)*rho_rat_to_the_n; tmp = dp_drho; // speed of sound squared } else { // STANDARD EOS double p_g = .5*bulk*(rho_cur*inv_rho_orig - rho_orig/rho_cur); pressure = p_ref + p_g; dp_drho = .5*bulk*(rho_orig/(rho_cur*rho_cur) + inv_rho_orig); tmp = bulk/rho_cur; // speed of sound squared } } double SmallStrainPlastic::getCompressibility() { return 1.0/d_initialData.Bulk; } ",16327,True,2660.506615845802,median "[[jms]] == JMS Support Spring Integration provides channel adapters for receiving and sending JMS messages. You need to include this dependency into your project: ==== [source, xml, subs=""normal"", role=""primary""] .Maven ---- org.springframework.integration spring-integration-jms {project-version} ---- [source, groovy, subs=""normal"", role=""secondary""] .Gradle ---- compile ""org.springframework.integration:spring-integration-jms:{project-version}"" ---- ==== The `javax.jms:javax.jms-api` must be added explicitly via some JMS vendor-specific implementation, e.g. Apache ActiveMQ. There are actually two JMS-based inbound Channel Adapters. The first uses Spring's `JmsTemplate` to receive based on a polling period. The second is ""`message-driven`"" and relies on a Spring `MessageListener` container. The outbound channel adapter uses the `JmsTemplate` to convert and send a JMS message on demand. By using `JmsTemplate` and the `MessageListener` container, Spring Integration relies on Spring's JMS support. This is important to understand, since most of the attributes exposed on these adapters configure the underlying `JmsTemplate` and `MessageListener` container. For more details about `JmsTemplate` and the `MessageListener` container, see the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jms.html[Spring JMS documentation]. Whereas the JMS channel adapters are intended for unidirectional messaging (send-only or receive-only), Spring Integration also provides inbound and outbound JMS Gateways for request and reply operations. The inbound gateway relies on one of Spring's `MessageListener` container implementations for message-driven reception. It is also capable of sending a return value to the `reply-to` destination, as provided by the received message. The outbound gateway sends a JMS message to a `request-destination` (or `request-destination-name` or `request-destination-expression`) and then receives a reply message. You can explicitly configure the `reply-destination` reference (or `reply-destination-name` or `reply-destination-expression`). Otherwise, the outbound gateway uses a JMS https://docs.oracle.com/javaee/6/api/javax/jms/TemporaryQueue.html[TemporaryQueue]. Prior to Spring Integration 2.2, if necessary, a `TemporaryQueue` was created (and removed) for each request or reply. Beginning with Spring Integration 2.2, you can configure the outbound gateway to use a `MessageListener` container to receive replies instead of directly using a new (or cached) `Consumer` to receive the reply for each request. When so configured, and no explicit reply destination is provided, a single `TemporaryQueue` is used for each gateway instead of one for each request. [[jms-inbound-channel-adapter]] === Inbound Channel Adapter The inbound channel adapter requires a reference to either a single `JmsTemplate` instance or both a `ConnectionFactory` and a `Destination` (you can provide a 'destinationName' in place of the 'destination' reference). The following example defines an inbound channel adapter with a `Destination` reference: ==== [source, java, role=""primary""] .Java DSL ---- @Bean public IntegrationFlow jmsInbound(ConnectionFactory connectionFactory) { return IntegrationFlows.from( Jms.inboundAdapter(connectionFactory) .destination(""inQueue""), e -> e.poller(poller -> poller.fixedRate(30000))) .handle(m -> System.out.println(m.getPayload())) .get(); } ---- [source, kotlin, role=""secondary""] .Kotlin DSL ---- @Bean fun jmsInbound(connectionFactory: ConnectionFactory) = integrationFlow( Jms.inboundAdapter(connectionFactory).destination(""inQueue""), { poller { Pollers.fixedRate(30000) } }) { handle { m -> println(m.payload) } } ---- [source, java, role=""secondary""] .Java ---- @Bean @InboundChannelAdapter(value = ""exampleChannel"", poller = @Poller(fixedRate = ""30000"")) public MessageSource jmsIn(ConnectionFactory connectionFactory) { JmsDestinationPollingSource source = new JmsDestinationPollingSource(new JmsTemplate(connectionFactory)); source.setDestinationName(""inQueue""); return source; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== TIP: Notice from the preceding configuration that the `inbound-channel-adapter` is a polling consumer. That means that it invokes `receive()` when triggered. You should use this should only in situations where polling is done relatively infrequently and timeliness is not important. For all other situations (a vast majority of JMS-based use-cases), the `message-driven-channel-adapter` (<>) is a better option. NOTE: By default, all of the JMS adapters that require a reference to the `ConnectionFactory` automatically look for a bean named `jmsConnectionFactory`. That is why you do not see a `connection-factory` attribute in many of the examples. However, if your JMS `ConnectionFactory` has a different bean name, you need to provide that attribute. If `extract-payload` is set to `true` (the default), the received JMS Message is passed through the `MessageConverter`. When relying on the default `SimpleMessageConverter`, this means that the resulting Spring Integration Message has the JMS message's body as its payload. A JMS `TextMessage` produces a string-based payload, a JMS `BytesMessage` produces a byte array payload, and the serializable instance of a JMS `ObjectMessage` becomes the Spring Integration message's payload. If you prefer to have the raw JMS message as the Spring Integration message's payload, set the `extractPayload` option to `false`. Starting with version 5.0.8, a default value of the `receive-timeout` is `-1` (no wait) for the `org.springframework.jms.connection.CachingConnectionFactory` and `cacheConsumers`, otherwise it is 1 second. The JMS Inbound Channel Adapter crates a `DynamicJmsTemplate` based on the provided `ConnectionFactory` and options. If an external `JmsTemplate` is required (e.g. in Spring Boot environment), or `ConnectionFactory` is not caching, or no `cacheConsumers`, it is recommended to set `jmsTemplate.receiveTimeout(-1)` if a non-blocking consumption is expected: ==== [source,java] ---- Jms.inboundAdapter(connectionFactory) .destination(queueName) .configureJmsTemplate(template -> template.receiveTimeout(-1)) ---- ==== [[jms-ib-transactions]] ==== Transactions Starting with version 4.0, the inbound channel adapter supports the `session-transacted` attribute. In earlier versions, you had to inject a `JmsTemplate` with `sessionTransacted` set to `true`. (The adapter did let you set the `acknowledge` attribute to `transacted`, but this was incorrect and did not work). Note, however, that setting `session-transacted` to `true` has little value, because the transaction is committed immediately after the `receive()` operation and before the message is sent to the `channel`. If you want the entire flow to be transactional (for example, if there is a downstream outbound channel adapter), you must use a `transactional` poller with a `JmsTransactionManager`. Alternatively, consider using a `jms-message-driven-channel-adapter` with `acknowledge` set to `transacted` (the default). [[jms-message-driven-channel-adapter]] === Message-driven Channel Adapter The `message-driven-channel-adapter` requires a reference to either an instance of a Spring `MessageListener` container (any subclass of `AbstractMessageListenerContainer`) or both `ConnectionFactory` and `Destination` (a 'destinationName' can be provided in place of the 'destination' reference). The following example defines a message-driven channel adapter with a `Destination` reference: ==== [source, java, role=""primary""] .Java DSL ---- @Bean public IntegrationFlow jmsMessageDrivenRedeliveryFlow() { return IntegrationFlows .from(Jms.messageDrivenChannelAdapter(jmsConnectionFactory()) .destination(""inQueue"")) .channel(""exampleChannel"") .get(); } ---- [source, kotlin, role=""secondary""] .Kotlin DSL ---- @Bean fun jmsMessageDrivenFlowWithContainer() = integrationFlow( Jms.messageDrivenChannelAdapter(jmsConnectionFactory()) .destination(""inQueue"")) { channel(""exampleChannel"") } ---- [source, java, role=""secondary""] .Java ---- @Bean public JmsMessageDrivenEndpoint jmsIn() { JmsMessageDrivenEndpoint endpoint = new JmsMessageDrivenEndpoint(container(), listener()); return endpoint; } @Bean public AbstractMessageListenerContainer container() { DefaultMessageListenerContainer container = new DefaultMessageListenerContainer(); container.setConnectionFactory(cf()); container.setDestinationName(""inQueue""); return container; } @Bean public ChannelPublishingJmsMessageListener listener() { ChannelPublishingJmsMessageListener listener = new ChannelPublishingJmsMessageListener(); listener.setRequestChannelName(""exampleChannel""); return listener; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== [NOTE] ===== The message-driven adapter also accepts several properties that pertain to the `MessageListener` container. These values are considered only if you do not provide a `container` reference. In that case, an instance of `DefaultMessageListenerContainer` is created and configured based on these properties. For example, you can specify the `transaction-manager` reference, the `concurrent-consumers` value, and several other property references and values. See the https://docs.spring.io/spring-integration/api/index.html[Javadoc] and Spring Integration's JMS schema (`spring-integration-jms.xsd`) for more details. If you have a custom listener container implementation (usually a subclass of `DefaultMessageListenerContainer`), you can either provide a reference to an instance of it by using the `container` attribute or provide its fully qualified class name by using the `container-class` attribute. In that case, the attributes on the adapter are transferred to an instance of your custom container. ===== [NOTE] ===== You can't use the Spring JMS namespace element `` to configure a container reference for the `` since that element doesn't actually reference a container. Each `` sub-element gets its own `DefaultMessageListenerContainer` (with shared attributes defined on the parent `` element). You can give each listener sub-element an `id`, and use that to inject into the channel adapter, however, the `` namespace requires a real listener. Since, for Spring Integration, the adapter itself needs to configure the listener, the configured listener will be overwritten. If you go this route, you will see a warning for each adapter. It is recommended to configure a regular `` for the `DefaultMessageListenerContainer` and use it as a reference in the channel adapter. ===== IMPORTANT: Starting with version 4.2, the default `acknowledge` mode is `transacted`, unless you provide an external container. In that case, you should configure the container as needed. We recommend using `transacted` with the `DefaultMessageListenerContainer` to avoid message loss. The 'extract-payload' property has the same effect, and its default value is 'true'. The `poller` element is not applicable for a message-driven channel adapter, as it is actively invoked. For most scenarios, the message-driven approach is better, since the messages are passed along to the `MessageChannel` as soon as they are received from the underlying JMS consumer. Finally, the `` element also accepts the 'error-channel' attribute. This provides the same basic functionality, as described in <<./gateway.adoc#gateway-proxy,Enter the `GatewayProxyFactoryBean`>>. The following example shows how to set an error channel on a message-driven channel adapter: ==== [source,xml] ---- ---- ==== When comparing the preceding example to the generic gateway configuration or the JMS 'inbound-gateway' that we discuss later, the key difference is that we are in a one-way flow, since this is a 'channel-adapter', not a gateway. Therefore, the flow downstream from the 'error-channel' should also be one-way. For example, it could send to a logging handler or it could connect to a different JMS `` element. When consuming from topics, set the `pub-sub-domain` attribute to true. Set `subscription-durable` to `true` for a durable subscription or `subscription-shared` for a shared subscription (which requires a JMS 2.0 broker and has been available since version 4.2). Use `subscription-name` to name the subscription. Starting with version 5.1, when the endpoint is stopped while the application remains running, the underlying listener container is shut down, closing its shared connection and consumers. Previously, the connection and consumers remained open. To revert to the previous behavior, set the `shutdownContainerOnStop` on the `JmsMessageDrivenEndpoint` to `false`. [[jms-md-conversion-errors]] ==== Inbound Conversion Errors Starting with version 4.2, the 'error-channel' is used for the conversion errors, too. Previously, if a JMS `` or `` could not deliver a message due to a conversion error, an exception would be thrown back to the container. If the container is configured to use transactions, the message is rolled back and redelivered repeatedly. The conversion process occurs before and during message construction so that such errors are not sent to the 'error-channel'. Now such conversion exceptions result in an `ErrorMessage` being sent to the 'error-channel', with the exception as the `payload`. If you wish the transaction to roll back and you have an 'error-channel' defined, the integration flow on the 'error-channel' must re-throw the exception (or another exception). If the error flow does not throw an exception, the transaction is committed and the message is removed. If no 'error-channel' is defined, the exception is thrown back to the container, as before. [[jms-outbound-channel-adapter]] === Outbound Channel Adapter The `JmsSendingMessageHandler` implements the `MessageHandler` interface and is capable of converting Spring Integration `Messages` to JMS messages and then sending to a JMS destination. It requires either a `jmsTemplate` reference or both `jmsConnectionFactory` and `destination` references (`destinationName` may be provided in place of `destination`). As with the inbound channel adapter, the easiest way to configure this adapter is with the namespace support. The following configuration produces an adapter that receives Spring Integration messages from the `exampleChannel`, converts those into JMS messages, and sends them to the JMS destination reference whose bean name is `outQueue`: ==== [source, java, role=""primary""] .Java DSL ---- @Bean public IntegrationFlow jmsOutboundFlow() { return f -> f .handle(Jms.outboundAdapter(cachingConnectionFactory()) .destinationExpression(""headers."" + SimpMessageHeaderAccessor.DESTINATION_HEADER) .configureJmsTemplate(t -> t.id(""jmsOutboundFlowTemplate""))); } ---- [source, kotlin, role=""secondary""] .Kotlin DSL ---- @Bean fun jmsOutboundFlow() = integrationFlow { handle(Jms.outboundAdapter(jmsConnectionFactory()) .apply { destinationExpression(""headers."" + SimpMessageHeaderAccessor.DESTINATION_HEADER) deliveryModeFunction { DeliveryMode.NON_PERSISTENT } timeToLiveExpression(""10000"") configureJmsTemplate { it.explicitQosEnabled(true) } } ) } ---- [source, java, role=""secondary""] .Java ---- @Bean @ServiceActivator(inputChannel = ""exampleChannel"") public MessageHandler jmsOut() { JmsSendingMessageHandler handler = new JmsSendingMessageHandler(new JmsTemplate(connectionFactory)); handler.setDestinationName(""outQueue""); return handler; } ---- [source, xml, role=""secondary""] .XML ---- ---- ==== As with the inbound channel adapters, there is an 'extract-payload' property. However, the meaning is reversed for the outbound adapter. Rather than applying to the JMS message, the boolean property applies to the Spring Integration message payload. In other words, the decision is whether to pass the Spring Integration message itself as the JMS message body or to pass the Spring Integration message payload as the JMS message body. The default value is 'true'. Therefore, if you pass a Spring Integration message whose payload is a `String`, a JMS `TextMessage` is created. If, on the other hand, you want to send the actual Spring Integration message to another system over JMS, set it to 'false'. NOTE: Regardless of the boolean value for payload extraction, the Spring Integration `MessageHeaders` map to JMS properties, as long as you rely on the default converter or provide a reference to another instance of `MessageConverter`. (The same holds true for 'inbound' adapters, except that, in those cases, the JMS properties map to Spring Integration `MessageHeaders`). Starting with version 5.1, the `` (`JmsSendingMessageHandler`) can be configured with the `deliveryModeExpression` and `timeToLiveExpression` properties to evaluate an appropriate QoS values for JMS message to send at runtime against request Spring `Message`. The new `setMapInboundDeliveryMode(true)` and `setMapInboundExpiration(true)` options of the `DefaultJmsHeaderMapper` may facilitate as a source of the information for the dynamic `deliveryMode` and `timeToLive` from message headers: ==== [source,xml] ---- ---- ==== [[jms-ob-transactions]] ==== Transactions Starting with version 4.0, the outbound channel adapter supports the `session-transacted` attribute. In earlier versions, you had to inject a `JmsTemplate` with `sessionTransacted` set to `true`. The attribute now sets the property on the built-in default `JmsTemplate`. If a transaction exists (perhaps from an upstream `message-driven-channel-adapter`), the send operation is performed within the same transaction. Otherwise, a new transaction is started. [[jms-inbound-gateway]] === Inbound Gateway Spring Integration's message-driven JMS inbound-gateway delegates to a `MessageListener` container, supports dynamically adjusting concurrent consumers, and can also handle replies. The inbound gateway requires references to a `ConnectionFactory` and a request `Destination` (or 'requestDestinationName'). The following example defines a JMS `inbound-gateway` that receives from the JMS queue referenced by the bean id, `inQueue`, and sends to the Spring Integration channel named `exampleChannel`: ==== [source,xml] ---- ---- ==== Since the gateways provide request-reply behavior instead of unidirectional send or receive behavior, they also have two distinct properties for ""`payload extraction`"" (as <> for the channel adapters' 'extract-payload' setting). For an inbound gateway, the 'extract-request-payload' property determines whether the received JMS Message body is extracted. If 'false', the JMS message itself becomes the Spring Integration message payload. The default is 'true'. Similarly, for an inbound-gateway, the 'extract-reply-payload' property applies to the Spring Integration message that is to be converted into a reply JMS Message. If you want to pass the whole Spring Integration message (as the body of a JMS ObjectMessage), set value this to 'false'. By default, it is also 'true' that the Spring Integration message payload is converted into a JMS Message (for example, a `String` payload becomes a JMS TextMessage). As with anything else, gateway invocation might result in error. By default, a producer is not notified of the errors that might have occurred on the consumer side and times out waiting for the reply. However, there might be times when you want to communicate an error condition back to the consumer (in other words, you might want to treat the exception as a valid reply by mapping it to a message). To accomplish this, JMS inbound gateway provides support for a message channel to which errors can be sent for processing, potentially resulting in a reply message payload that conforms to some contract that defines what a caller may expect as an ""`error`"" reply. You can use the error-channel attribute to configure such a channel, as the following example shows: ==== [source,xml] ---- ---- ==== You might notice that this example looks very similar to that included within <<./gateway.adoc#gateway-proxy,Enter the `GatewayProxyFactoryBean`>>. The same idea applies here: The `exceptionTransformer` could be a POJO that creates error-response objects, you could reference the `nullChannel` to suppress the errors, or you could leave 'error-channel' out to let the exception propagate. See <>. When consuming from topics, set the `pub-sub-domain` attribute to true. Set `subscription-durable` to `true` for a durable subscription or `subscription-shared` for a shared subscription (requires a JMS 2.0 broker and has been available since version 4.2). Use `subscription-name` to name the subscription. IMPORTANT: Starting with version 4.2, the default `acknowledge` mode is `transacted`, unless an external container is provided. In that case, you should configure the container as needed. We recommend that you use `transacted` with the `DefaultMessageListenerContainer` to avoid message loss. Starting with version 5.1, when the endpoint is stopped while the application remains running, the underlying listener container is shut down, closing its shared connection and consumers. Previously, the connection and consumers remained open. To revert to the previous behavior, set the `shutdownContainerOnStop` on the `JmsInboundGateway` to `false`. [[jms-outbound-gateway]] === Outbound Gateway The outbound gateway creates JMS messages from Spring Integration messages and sends them to a 'request-destination'. It then handles the JMS reply message either by using a selector to receive from the 'reply-destination' that you configure or, if no 'reply-destination' is provided, by creating JMS `TemporaryQueue` instances. [[jms-outbound-gateway-memory-caution]] [CAUTION] ===== Using a `reply-destination` (or `reply-destination-name`) together with a `CachingConnectionFactory` that has cacheConsumers set to `true` can cause out-of-memory conditions. This is because each request gets a new consumer with a new selector (selecting on the `correlation-key` value or, when there is no `correlation-key`, on the sent JMSMessageID). Given that these selectors are unique, they remain in the cache (unused) after the current request completes. If you specify a reply destination, you are advised to not use cached consumers. Alternatively, consider using a `` as <>. ===== The following example shows how to configure an outbound gateway: ==== [source,xml] ---- ---- ==== The 'outbound-gateway' payload extraction properties are inversely related to those of the 'inbound-gateway' (see the <>). That means that the 'extract-request-payload' property value applies to the Spring Integration message being converted into a JMS message to be sent as a request. The 'extract-reply-payload' property value applies to the JMS message received as a reply and is then converted into a Spring Integration message to be subsequently sent to the 'reply-channel', as shown in the preceding configuration example. [[jms-outbound-gateway-reply-listener]] ==== Using a `` Spring Integration 2.2 introduced an alternative technique for handling replies. If you add a `` child element to the gateway instead of creating a consumer for each reply, a `MessageListener` container is used to receive the replies and hand them over to the requesting thread. This provides a number of performance benefits as well as alleviating the cached consumer memory utilization problem described in the <>. When using a `` with an outbound gateway that has no `reply-destination`, instead of creating a `TemporaryQueue` for each request, a single `TemporaryQueue` is used. (The gateway creates an additional `TemporaryQueue`, as necessary, if the connection to the broker is lost and recovered). When using a `correlation-key`, multiple gateways can share the same reply destination, because the listener container uses a selector that is unique to each gateway. [CAUTION] ==== If you specify a reply listener and specify a reply destination (or reply destination name) but provide no correlation key, the gateway logs a warning and falls back to pre-version 2.2 behavior. This is because there is no way to configure a selector in this case. Thus, there is no way to avoid a reply going to a different gateway that might be configured with the same reply destination. Note that, in this situation, a new consumer is used for each request, and consumers can build up in memory as described in the caution above; therefore cached consumers should not be used in this case. ==== The following example shows a reply listener with default attributes: ==== [source,xml] ---- ---- ==== The listener is very lightweight, and we anticipate that, in most cases, you need only a single consumer. However, you can add attributes such as `concurrent-consumers`, `max-concurrent-consumers`, and others. See the schema for a complete list of supported attributes, together with the https://docs.spring.io/spring/docs/current/spring-framework-reference/html/jms.html[Spring JMS documentation] for their meanings. ==== Idle Reply Listeners Starting with version 4.2, you can start the reply listener as needed (and stop it after an idle time) instead of running for the duration of the gateway's lifecycle. This can be useful if you have many gateways in the application context where they are mostly idle. One such situation is a context with many (inactive) partitioned https://spring.io/projects/spring-batch[Spring Batch] jobs using Spring Integration and JMS for partition distribution. If all the reply listeners are active, the JMS broker has an active consumer for each gateway. By enabling the idle timeout, each consumer exists only while the corresponding batch job is running (and for a short time after it finishes). See `idle-reply-listener-timeout` in <>. ==== Gateway Reply Correlation This section describes the mechanisms used for reply correlation (ensuring the originating gateway receives replies to only its requests), depending on how the gateway is configured. See <> for complete description of the attributes discussed here. The following list describes the various scenarios (the numbers are for identification -- order does not matter): . No `reply-destination*` properties and no `` + A `TemporaryQueue` is created for each request and deleted when the request is complete (successfully or otherwise). `correlation-key` is irrelevant. . A `reply-destination*` property is provided and neither a `` nor a `correlation-key` is provided + The `JMSCorrelationID` equal to the outgoing message IS is used as a message selector for the consumer: + `messageSelector = ""JMSCorrelationID = '"" + messageId + ""'""` + The responding system is expected to return the inbound `JMSMessageID` in the reply `JMSCorrelationID`. This is a common pattern and is implemented by the Spring Integration inbound gateway as well as Spring's `MessageListenerAdapter` for message-driven POJOs. + NOTE: When you use this configuration, you should not use a topic for replies. The reply may be lost. . A `reply-destination*` property is provided, no `` is provided, and `correlation-key=""JMSCorrelationID""` + The gateway generates a unique correlation IS and inserts it in the `JMSCorrelationID` header. The message selector is: + `messageSelector = ""JMSCorrelationID = '"" + uniqueId + ""'""` + The responding system is expected to return the inbound `JMSCorrelationID` in the reply `JMSCorrelationID`. This is a common pattern and is implemented by the Spring Integration inbound gateway as well as Spring's `MessageListenerAdapter` for message-driven POJOs. . A `reply-destination*` property is provided, no `` is provided, and `correlation-key=""myCorrelationHeader""` + The gateway generates a unique correlation ID and inserts it in the `myCorrelationHeader` message property. The `correlation-key` can be any user-defined value. The message selector is: + `messageSelector = ""myCorrelationHeader = '"" + uniqueId + ""'""` + The responding system is expected to return the inbound `myCorrelationHeader` in the reply `myCorrelationHeader`. . A `reply-destination*` property is provided, no `` is provided, and `correlation-key=""JMSCorrelationID*""` (Note the `*` in the correlation key.) + The gateway uses the value in the `jms_correlationId` header (if present) from the request message and inserts it in the `JMSCorrelationID` header. The message selector is: + `messageSelector = ""JMSCorrelationID = '"" + headers['jms_correlationId'] + ""'""` + The user must ensure this value is unique. + If the header does not exist, the gateway behaves as in `3`. + The responding system is expected to return the inbound `JMSCorrelationID` in the reply `JMSCorrelationID`. This is a common pattern and is implemented by the Spring Integration inbound gateway as well as Spring's `MessageListenerAdapter` for message-driven POJOs. . No `reply-destination*` properties is provided, and a `` is provided + A temporary queue is created and used for all replies from this gateway instance. No correlation data is needed in the message, but the outgoing `JMSMessageID` is used internally in the gateway to direct the reply to the correct requesting thread. . A `reply-destination*` property is provided, a `` is provided, and no `correlation-key` is provided + Not allowed. + The `` configuration is ignored, and the gateway behaves as in `2`. A warning log message is written to indicate this situation. . A `reply-destination*` property is provided, a `` is provided, and `correlation-key=""JMSCorrelationID""` + The gateway has a unique correlation ID and inserts it, together with an incrementing value in the `JMSCorrelationID` header (`gatewayId + ""_"" + ++seq`). The message selector is: + `messageSelector = ""JMSCorrelationID LIKE '"" + gatewayId%'""` + The responding system is expected to return the inbound `JMSCorrelationID` in the reply `JMSCorrelationID`. This is a common pattern and is implemented by the Spring Integration inbound gateway as well as Spring's `MessageListenerAdapter` for message-driven POJOs. Since each gateway has a unique ID, each instance gets only its own replies. The complete correlation data is used to route the reply to the correct requesting thread. . A `reply-destination*` property is provided a `` is provided, and `correlation-key=""myCorrelationHeader""` + The gateway has a unique correlation ID and inserts it, together with an incrementing value in the `myCorrelationHeader` property (`gatewayId + ""_"" + ++seq`). The `correlation-key` can be any user-defined value. The message selector is: + `messageSelector = ""myCorrelationHeader LIKE '"" + gatewayId%'""` + The responding system is expected to return the inbound `myCorrelationHeader` in the reply `myCorrelationHeader`. Since each gateway has a unique ID, each instance only gets its own replies. The complete correlation data is used to route the reply to the correct requesting thread. . A `reply-destination*` property is provided, a `` is provided, and `correlation-key=""JMSCorrelationID*""` + (Note the `*` in the correlation key) + Not allowed. + User-supplied correlation IDs are not permitted with a reply listener. The gateway does not initialize with this configuration. [[jms-async-gateway]] ==== Async Gateway Starting with version 4.3, you can now specify `async=""true""` (or `setAsync(true)` in Java) when configuring the outbound gateway. By default, when a request is sent to the gateway, the requesting thread is suspended until the reply is received. The flow then continues on that thread. If `async` is `true`, the requesting thread is released immediately after the send completes, and the reply is returned (and the flow continues) on the listener container thread. This can be useful when the gateway is invoked on a poller thread. The thread is released and is available for other tasks within the framework. `async` requires a `` (or `setUseReplyContainer(true)` when using Java configuration). It also requires a `correlationKey` (usually `JMSCorrelationID`) to be specified. If either of these conditions are not met, `async` is ignored. [[jms-og-attributes]] ==== Attribute Reference The following listing shows all the available attributes for an `outbound-gateway`: ==== [source,xml] ---- correlation-key="""" <2> delivery-persistent="""" <3> destination-resolver="""" <4> explicit-qos-enabled="""" <5> extract-reply-payload=""true"" <6> extract-request-payload=""true"" <7> header-mapper="""" <8> message-converter="""" <9> priority="""" <10> receive-timeout="""" <11> reply-channel="""" <12> reply-destination="""" <13> reply-destination-expression="""" <14> reply-destination-name="""" <15> reply-pub-sub-domain="""" <16> reply-timeout="""" <17> request-channel="""" <18> request-destination="""" <19> request-destination-expression="""" <20> request-destination-name="""" <21> request-pub-sub-domain="""" <22> time-to-live="""" <23> requires-reply="""" <24> idle-reply-listener-timeout="""" <25> async=""""> <26> <27> ---- <1> Reference to a `javax.jms.ConnectionFactory`. The default `jmsConnectionFactory`. <2> The name of a property that contains correlation data to correlate responses with replies. If omitted, the gateway expects the responding system to return the value of the outbound `JMSMessageID` header in the `JMSCorrelationID` header. If specified, the gateway generates a correlation ID and populates the specified property with it. The responding system must echo back that value in the same property. It can be set to `JMSCorrelationID`, in which case the standard header is used instead of a `String` property to hold the correlation data. When you use a ``, you must specify the `correlation-key` if you provide an explicit `reply-destination`. Starting with version 4.0.1, this attribute also supports the value `JMSCorrelationID*`, which means that if the outbound message already has a `JMSCorrelationID` (mapped from the `jms_correlationId`) header, it is used instead of generating a new one. Note, the `JMSCorrelationID*` key is not allowed when you use a ``, because the container needs to set up a message selector during initialization. + IMPORTANT: You should understand that the gateway has no way to ensure uniqueness, and unexpected side effects can occur if the provided correlation ID is not unique. <3> A boolean value indicating whether the delivery mode should be `DeliveryMode.PERSISTENT` (`true`) or `DeliveryMode.NON_PERSISTENT` (`false`). This setting takes effect only if `explicit-qos-enabled` is `true`. <4> A `DestinationResolver`. The default is a `DynamicDestinationResolver`, which maps the destination name to a queue or topic of that name. <5> When set to `true`, it enables the use of quality of service attributes: `priority`, `delivery-mode`, and `time-to-live`. <6> When set to `true` (the default), the payload of the Spring Integration reply message is created from the JMS Reply message's body (by using the `MessageConverter`). When set to `false`, the entire JMS message becomes the payload of the Spring Integration message. <7> When set to `true` (the default), the payload of the Spring Integration message is converted to a `JMSMessage` (by using the `MessageConverter`). When set to `false`, the entire Spring Integration Message is converted to the `JMSMessage`. In both cases, the Spring Integration message headers are mapped to JMS headers and properties by using the `HeaderMapper`. <8> A `HeaderMapper` used to map Spring Integration message headers to and from JMS message headers and properties. <9> A reference to a `MessageConverter` for converting between JMS messages and the Spring Integration message payloads (or messages if `extract-request-payload` is `false`). The default is a `SimpleMessageConverter`. <10> The default priority of request messages. Overridden by the message priority header, if present. Its range is `0` to `9`. This setting takes effect only if `explicit-qos-enabled` is `true`. <11> The time (in milliseconds) to wait for a reply. The default is `5000` (five seconds). <12> The channel to which the reply message is sent. <13> A reference to a `Destination`, which is set as the `JMSReplyTo` header. At most, only one of `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is allowed. If none is provided, a `TemporaryQueue` is used for replies to this gateway. <14> A SpEL expression evaluating to a `Destination`, which will be set as the `JMSReplyTo` header. The expression can result in a `Destination` object or a `String`. It is used by the `DestinationResolver` to resolve the actual `Destination`. At most, only one of `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is allowed. If none is provided, a `TemporaryQueue` is used for replies to this gateway. <15> The name of the destination that is set as the JMSReplyTo header. It is used by the `DestinationResolver` to resolve the actual `Destination`. At most, only one of `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is allowed. If none is provided, a `TemporaryQueue` is used for replies to this gateway. <16> When set to `true`, it indicates that any reply `Destination` resolved by the `DestinationResolver` should be a `Topic` rather then a `Queue`. <17> The time the gateway waits when sending the reply message to the `reply-channel`. This only has an effect if the `reply-channel` can block -- such as a `QueueChannel` with a capacity limit that is currently full. The default is infinity. <18> The channel on which this gateway receives request messages. <19> A reference to a `Destination` to which request messages are sent. One of `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is required. You can use only one of those three attributes. <20> A SpEL expression evaluating to a `Destination` to which request messages are sent. The expression can result in a `Destination` object or a `String`. It is used by the `DestinationResolver` to resolve the actual `Destination`. Oneof `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is required. You can use only one of those three attributes. <21> The name of the destination to which request messages are sent. It is used by the `DestinationResolver` to resolve the actual `Destination`. One of `reply-destination`, `reply-destination-expression`, or `reply-destination-name` is required. You can use only one of those three attributes. <22> When set to `true`, it indicates that any request `Destination` resolved by the `DestinationResolver` should be a `Topic` rather then a `Queue`. <23> Specifies the message time to live. This setting takes effect only if `explicit-qos-enabled` is `true`. <24> Specifies whether this outbound gateway must return a non-null value. By default, this value is `true`, and a `MessageTimeoutException` is thrown when the underlying service does not return a value after the `receive-timeout`. Note that, if the service is never expected to return a reply, it would be better to use a `` instead of a `` with `requires-reply=""false""`. With the latter, the sending thread is blocked, waiting for a reply for the `receive-timeout` period. <25> When you use a ``, its lifecycle (start and stop) matches that of the gateway by default. When this value is greater than `0`, the container is started on demand (when a request is sent). The container continues to run until at least this time elapses with no requests being received (and until no replies are outstanding). The container is started again on the next request. The stop time is a minimum and may actually be up to 1.5x this value. <26> See <>. <27> When this element is included, replies are received by an asynchronous `MessageListenerContainer` rather than creating a consumer for each reply. This can be more efficient in many cases. ==== [[jms-header-mapping]] === Mapping Message Headers to and from JMS Message JMS messages can contain meta-information such as JMS API headers and simple properties. You can map those to and from Spring Integration message headers by using `JmsHeaderMapper`. The JMS API headers are passed to the appropriate setter methods (such as `setJMSReplyTo`), whereas other headers are copied to the general properties of the JMS Message. JMS outbound gateway is bootstrapped with the default implementation of `JmsHeaderMapper`, which will map standard JMS API Headers as well as primitive or `String` message headers. You could also provide a custom header mapper by using the `header-mapper` attribute of inbound and outbound gateways. IMPORTANT: Many JMS vendor-specific clients don't allow setting the `deliveryMode`, `priority` and `timeToLive` properties directly on an already created JMS message. They are considered to be QoS properties and therefore have to be propagated to the target `MessageProducer.send(message, deliveryMode, priority, timeToLive)` API. For this reason the `DefaultJmsHeaderMapper` doesn't map appropriate Spring Integration headers (or expression results) into the mentioned JMS message properties. Instead, a `DynamicJmsTemplate` is used by the `JmsSendingMessageHandler` to propagate header values from the request message into the `MessageProducer.send()` API. To enable this feature, you must configure the outbound endpoint with a `DynamicJmsTemplate` with its `explicitQosEnabled` property set to true. The Spring Integration Java DSL configures a `DynamicJmsTemplate` by default but you must still set the `explicitQosEnabled` property. IMPORTANT: Since version 4.0, the `JMSPriority` header is mapped to the standard `priority` header for inbound messages. Previously, the `priority` header was only used for outbound messages. To revert to the previous behavior (that is, to not map the inbound priority), set the `mapInboundPriority` property of `DefaultJmsHeaderMapper` to `false`. IMPORTANT: Since version 4.3, the `DefaultJmsHeaderMapper` maps the standard `correlationId` header as a message property by invoking its `toString()` method (`correlationId` is often a `UUID`, which is not supported by JMS). On the inbound side, it is mapped as a `String`. This is independent of the `jms_correlationId` header, which is mapped to and from the `JMSCorrelationID` header. The `JMSCorrelationID` is generally used to correlate requests and replies, whereas the `correlationId` is often used to combine related messages into a group (such as with an aggregator or a resequencer). Starting with version 5.1, the `DefaultJmsHeaderMapper` can be configured for mapping inbound `JMSDeliveryMode` and `JMSExpiration` properties: ==== [source,java] ---- @Bean public DefaultJmsHeaderMapper jmsHeaderMapper() { DefaultJmsHeaderMapper mapper = new DefaultJmsHeaderMapper(); mapper.setMapInboundDeliveryMode(true) mapper.setMapInboundExpiration(true) return mapper; } ---- ==== These JMS properties are mapped to the `JmsHeaders.DELIVERY_MODE` and `JmsHeaders.EXPIRATION` Spring Message headers respectively. [[jms-conversion-and-marshalling]] === Message Conversion, Marshalling, and Unmarshalling If you need to convert the message, all JMS adapters and gateways let you provide a `MessageConverter` by setting the `message-converter` attribute. To do so, provide the bean name of an instance of `MessageConverter` that is available within the same ApplicationContext. Also, to provide some consistency with marshaller and unmarshaller interfaces, Spring provides `MarshallingMessageConverter`, which you can configure with your own custom marshallers and unmarshallers. The following example shows how to do so ==== [source,xml] ---- ---- ==== NOTE: When you provide your own `MessageConverter` instance, it is still wrapped within the `HeaderMappingMessageConverter`. This means that the 'extract-request-payload' and 'extract-reply-payload' properties can affect the actual objects passed to your converter. The `HeaderMappingMessageConverter` itself delegates to a target `MessageConverter` while also mapping the Spring Integration `MessageHeaders` to JMS message properties and back again. [[jms-channel]] === JMS-backed Message Channels The channel adapters and gateways featured earlier are all intended for applications that integrate with other external systems. The inbound options assume that some other system is sending JMS messages to the JMS destination, and the outbound options assume that some other system is receiving from the destination. The other system may or may not be a Spring Integration application. Of course, when sending a Spring Integration message instance as the body of the JMS message itself (with 'extract-payload' value set to `false`), it is assumed that the other system is based on Spring Integration. However, that is by no means a requirement. That flexibility is one of the benefits of using a message-based integration option with the abstraction of ""`channels`""( or destinations in the case of JMS). Sometimes, both the producer and consumer for a given JMS Destination are intended to be part of the same application, running within the same process. You can accomplish this by using a pair of inbound and outbound channel adapters. The problem with that approach is that you need two adapters, even though, conceptually, the goal is to have a single message channel. A better option is supported as of Spring Integration version 2.0. Now it is possible to define a single ""`channel`"" when using the JMS namespace, as the following example shows: ==== [source,xml] ---- ---- ==== The channel in the preceding example behaves much like a normal `` element from the main Spring Integration namespace. It can be referenced by both the `input-channel` and `output-channel` attributes of any endpoint. The difference is that this channel is backed by a JMS Queue instance named `exampleQueue`. This means that asynchronous messaging is possible between the producing and consuming endpoints. However, unlike the simpler asynchronous message channels created by adding a `` element within a non-JMS `` element, the messages are not stored in an in-memory queue. Instead, those messages are passed within a JMS message body, and the full power of the underlying JMS provider is then available for that channel. Probably the most common rationale for using this alternative is to take advantage of the persistence made available by the store-and-forward approach of JMS messaging. If configured properly, the JMS-backed message channel also supports transactions. In other words, a producer would not actually write to a transactional JMS-backed channel if its send operation is part of a transaction that rolls back. Likewise, a consumer would not physically remove a JMS message from the channel if the reception of that message is part of a transaction that rolls back. Note that the producer and consumer transactions are separate in such a scenario. This is significantly different than the propagation of a transactional context across a simple, synchronous `` element that has no `` child element. Since the preceding example above references a JMS Queue instance, it acts as a point-to-point channel. If, on the other hand, you need publish-subscribe behavior, you can use a separate element and reference a JMS Topic instead. The following example shows how to do so: ==== [source,xml] ---- ---- ==== For either type of JMS-backed channel, the name of the destination may be provided instead of a reference, as the following example shows: ==== [source,xml] ---- ---- ==== In the preceding examples, the destination names are resolved by Spring's default `DynamicDestinationResolver` implementation, but you could provide any implementation of the `DestinationResolver` interface. Also, the JMS `ConnectionFactory` is a required property of the channel, but, by default, the expected bean name would be `jmsConnectionFactory`. The following example provides both a custom instance for resolution of the JMS destination names and a different name for the `ConnectionFactory`: ==== [source,xml] ---- ---- ==== For the ``, set the `durable` attribute to `true` for a durable subscription or `subscription-shared` for a shared subscription (requires a JMS 2.0 broker and has been available since version 4.2). Use `subscription` to name the subscription. [[jms-selectors]] === Using JMS Message Selectors With JMS message selectors, you can filter https://docs.oracle.com/javaee/6/api/javax/jms/Message.html[JMS Messages] based on JMS headers as well as JMS properties. For example, if you want to listen to messages whose custom JMS header property, `myHeaderProperty`, equals `something`, you can specify the following expression: ==== [source,xml] ---- myHeaderProperty = 'something' ---- ==== Message selector expressions are a subset of the https://en.wikipedia.org/wiki/SQL-92[SQL-92] conditional expression syntax and are defined as part of the https://download.oracle.com/otn-pub/jcp/7195-jms-1.1-fr-spec-oth-JSpec/jms-1_1-fr-spec.pdf[Java Message Service] specification (Version 1.1, April 12, 2002). Specifically, see chapter ""3.8, Message Selection"". It contains a detailed explanation of the expressions syntax. You can specify the JMS message `selector` attribute by using XML namespace configuration for the following Spring Integration JMS components: * JMS Channel * JMS Publish Subscribe Channel * JMS Inbound Channel Adapter * JMS Inbound Gateway * JMS Message-driven Channel Adapter IMPORTANT: You cannot reference message body values by using JMS Message selectors. [[jms-samples]] === JMS Samples To experiment with these JMS adapters, check out the JMS samples available in the Spring Integration Samples Git repository at https://github.com/SpringSource/spring-integration-samples/tree/master/basic/jms[https://github.com/SpringSource/spring-integration-samples/tree/master/basic/jms]. That repository includes two samples. One provides inbound and outbound channel adapters, and the other provides inbound and outbound gateways. They are configured to run with an embedded https://activemq.apache.org/[ActiveMQ] process, but you can modify the https://github.com/SpringSource/spring-integration-samples/blob/master/basic/jms/src/main/resources/META-INF/spring/integration/common.xml[common.xml] Spring application context file of each sample to support either a different JMS provider or a standalone ActiveMQ process. In other words, you can split the configuration so that the inbound and outbound adapters run in separate JVMs. If you have ActiveMQ installed, modify the `brokerURL` property within the common.xml file to use `tcp://localhost:61616` (instead of `vm://localhost`). Both of the samples accept input from stdin and echo back to stdout. Look at the configuration to see how these messages are routed over JMS. ",12072,False,2339.244155648816,median "/******************************************************************************* * Filename : dma0fieldvalues.hpp * * Details : Enumerations related with DMA0 peripheral. This header file is * auto-generated for GD32VF103 device. * * *******************************************************************************/ #if !defined(DMA0ENUMS_HPP) #define DMA0ENUMS_HPP #include ""fieldvalue.hpp"" //for FieldValues template struct DMA0_INTF_GIF0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_GIF6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_FTFIF6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_HTFIF6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTF_ERRIF6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC0_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC1_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC2_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC3_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC4_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC5_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_GIFC6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_FTFIFC6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_HTFIFC6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_INTC_ERRIFC6_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH0CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH0CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH0CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH0CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH0PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH0MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH1CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH1CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH1CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH1CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH1CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH1PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH1MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH2CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH2CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH2CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH2CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH2CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH2PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH2MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH3CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH3CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH3CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH3CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH3CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH3PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH3MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH4CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH4CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH4CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH4CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH4CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH4PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH4MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH5CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH5CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH5CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH5CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH5CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH5PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH5MADDR_MADDR_Values: public RegisterField { } ; template struct DMA0_CH6CTL_CHEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_FTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_HTFIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_ERRIE_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_DIR_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_CMEN_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_PNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_MNAGA_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CTL_PWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH6CTL_MWIDTH_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH6CTL_PRIO_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; using Value2 = FieldValue ; using Value3 = FieldValue ; } ; template struct DMA0_CH6CTL_M2M_Values: public RegisterField { using Value0 = FieldValue ; using Value1 = FieldValue ; } ; template struct DMA0_CH6CNT_CNT_Values: public RegisterField { } ; template struct DMA0_CH6PADDR_PADDR_Values: public RegisterField { } ; template struct DMA0_CH6MADDR_MADDR_Values: public RegisterField { } ; #endif //#if !defined(DMA0ENUMS_HPP) ",16329,True,6183.628000191986,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // = Utilizando o Hibernate em uma Aplicação Web :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Utilizando o Hibernate em uma Aplicação Web - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Utilizando o Hibernate em uma Aplicação Web Neste tutorial, você utiliza o NetBeans IDE para criar e implantar uma aplicação Web que exibe dados do banco de dados. A aplicação Web utiliza o framework do Hibernate como a camada de persistência para recuperar e armazenar objetos Java simples antigos (POJOs) em um banco de dados relacional. O Hibernate é o framework que fornece ferramentas para o mapeamento relacional de objeto (ORM). O tutorial demonstra como adicionar suporte para o framework do Hibernate ao IDE e criar os arquivos necessários do Hibernate. Depois de criar os objetos Java e configurar a aplicação para utilizar o Hibernate, você cria um bean gerenciado pelo JSF e páginas do JSF 2.0 para exibir dados. Antes de começar este tutorial, você pode se familiarizar com os seguintes documentos. * Documentação do Hibernate em link:http://www.hibernate.org/[+hibernate.org+] * link:quickstart-webapps.html[+Introdução ao Desenvolvimento de Aplicações Web+] * link:jsf20-intro.html[+Introdução ao JavaServer Faces 2.x+] image::images/netbeans-stamp-74-73-72.png[title=""O conteúdo desta página se aplica ao NetBeans IDE 7.2, 7.3 e 7.4""] *Para seguir este tutorial, são necessários os recursos e o software a seguir.* |=== |Software ou Recurso |Versão Necessária |link:https://netbeans.org/downloads/index.html[+NetBeans IDE+] |Versões 7.1, 7.2, 7.3 e 7.4 do Java EE |link:http://www.oracle.com/technetwork/java/javase/downloads/index.html[+JDK (Java Development Kit)+] |Versão 6 ou 7 |GlassFish Server Open Source Edition |3.x ou 4.x |link:http://www.mysql.com/[+Servidor de banco de dados MySQL+] |Versão 5.x |Banco de Dados Sakila |Plug-in disponível na Central de Atualização |=== Você pode fazer download link:https://netbeans.org/projects/samples/downloads/download/Samples/JavaEE/DVDStoreEE6.zip[+de um arquivo compactado zip do projeto finalizado+]. == Criando o Banco de Dados Este tutorial utiliza um banco de dados MySQL chamado ``sakila`` , uma amostra gratuita do banco de dados MySQL que está disponível no site do MySQL. O banco de dados sakila não está incluído quando você instala o IDE, portanto, você precisa primeiro criar o banco de dados para seguir este tutorial. Para criar o banco de dados sakila, você pode fazer o download e instalar o plug-in Banco de Dados de Amostra do Sakila usando o Gerenciador de plug-ins. Depois que você instala o plug-in, o banco de dados sakila é adicionado à lista de bancos de dados na caixa de diálogo Criar banco de dados MySQL. Para obter mais informações sobre a configuração do IDE para trabalhar com o MySQL, consulte o tutorial link:../ide/mysql.html[+Estabelecendo Conexão com um Banco de Dados MySQL+]. 1. Abra o Gerenciador de plug-ins e instale o plug-in Banco de Dados de Amostra do Sakila. 2. Depois da instalação do plug-in, inicie o banco de dados MySQL expandindo o nó Bancos de Dados na janela Serviços, clicando com o botão direito do mouse no nó Servidor MySQL e selecionando Iniciar. 3. Clique com o botão direito do mouse no nó Servidor MySQL e escolha Criar Banco de Dados. 4. Selecione o banco de dados Sakila na lista drop-down Novo Nome de Banco de Dados, na caixa de diálogo Criar Banco de Dados MySQL. Clique em OK. image::images/create-sakila-mysql.png[title=""Tela da caixa de diálogo Criar Banco de Dados MySQL""] Quando você clicar em OK, um nó do Salkila será exibido sob o nó Servidor MySQL. 5. Clique com o botão direito do mouse no nó do Sakila e escolha Conectar. Quando você clicar em Conectar, um nó de conexão do banco de dados do banco de dados Sakila ( ``jdbc:mysql://localhost:3306/sakila [_nome de usuário_ em Default]`` ) será apresentado no nó Bancos de Dados. Quando uma conexão for aberta, você poderá exibir os dados no banco de dados ampliando o nó de conexão. == Criando o Projeto de Aplicação Web Neste exercício, você criará um projeto de aplicação Web e adicionará as bibliotecas do Hibernate ao projeto. Após criar o projeto, você selecionará Hibernate no painel Frameworks do assistente de Novo Projeto e especificará o banco de dados. 1. Escolha Arquivo > Novo Projeto (Ctrl-Shift-N; &#8984-Shift-N no Mac) no menu principal. Selecione Aplicação Web na categoria Java Web e clique em Próximo. 2. Digite *DVDStore* para o nome do projeto e defina a localização do projeto. 3. Desmarque a opção Usar Pasta Dedicada, se ela estiver selecionada. Clique em Próximo. Neste tutorial, não é necessário copiar as bibliotecas do projeto para uma pasta dedicada, pois você não precisará compartilhar bibliotecas com outros usuários. 4. Defina o servidor como GlassFish Server e defina a versão do Java EE para Java EE 6 Web ou Java EE 7 Web. Clique em Próximo. 5. Marque a caixa de seleção JavaServer Faces e utilize as bibliotecas default do JSF 2.x. 6. Marque a caixa de seleção Hibernar na lista de frameworks. 7. Selecione o banco de dados sakila na lista drop-down Conexão de Banco de Dados. Clique em Finalizar. *Observação:* se o banco de dados sakila não estiver disponível como uma opção no painel Framework do assistente, verifique se a conexão está listada no nó Bancos de Dados da janela Serviços. Se a conexão não existir, será necessário criar a conexão do banco de dados. image::images/hib-newwebapp.png[title=""Painel Frameworks do assistente de Novo Projeto mostrando como adicionar o suporte do Hibernar ao projeto""] Quando você clicar em Finalizar, o IDE criará o projeto de aplicação Web e abrirá o arquivo ``hibernate.cfg.xml`` e ``index.xhtml`` no editor. Se expandir o nó Bibliotecas na janela Projetos, você poderá ver que o IDE adicionou as bibliotecas do Hibernate ao projeto. image::images/hib-libraries.png[title=""Tela da janela Projetos mostrando bibliotecas do Hibernate""] == Modificando o Arquivo de Configuração do Hibernate Quando você cria um novo projeto que utiliza o framework do Hibernate, o IDE cria automaticamente o arquivo de configuração ``hibernate.cfg.xml`` na raiz do classpath de contexto da aplicação (na janela Arquivos, ``src/java`` ). O arquivo está localizado em ```` no nó Pacotes de Código-Fonte na janela Projetos. O arquivo de configuração contém informações sobre a conexão do banco de dados, os mapeamentos de recursos e outras propriedades da conexão. É possível editar o arquivo utilizando o editor de várias views ou editar o XML diretamente no editor XML. Neste exercício, você editará as propriedades default especificadas em ``hibernate.cfg.xml`` para ativar o log de depuração das instruções SQL e para ativar o gerenciamento de contexto de sessão do Hibernate. 1. Abra ``hibernate.cfg.xml`` na guia Desenho. Você pode abrir o arquivo expandindo o nó ```` em Pacotes de Códigos-Fonte na janela Projetos e clicando duas vezes em ``hibernate.cfg.xml`` . 2. No editor XML com várias views, expanda o nó Propriedades da Configuração em Propriedades Opcionais. 3. Clique em Adicionar para abrir a caixa de diálogo Adicionar Propriedade do Hibernate. 4. Na caixa de diálogo, selecione a propriedade ``hibernate.show_sql`` e defina o valor para ``true`` . Isso ativa o log de depuração das instruções SQL. image::images/add-property-showsql.png[title=""Caixa de diálogo Adicionar Propriedade Hibernate que mostra o valor de definição de hibernate.show_sql""] 5. Expanda o nó Propriedades Diversas e clique em Adicionar. 6. Na caixa de diálogo, selecione ``properties hibernate.current_session_context_class`` e defina o valor para ``thread`` para ativar o gerenciamento de contexto automático da sessão do Hibernate. image::images/add-property-sessioncontext.png[title=""Adicione a caixa e diálogo Propriedade do Hibernate mostrando como definir o valor da propriedade hibernate.current_session_context_class""] 7. Clique novamente em Adicionar no nó Propriedades Diversas e selecione ``hibernate.query.factory_class`` na lista drop-down Nome da Propriedade. 8. Selecione *org.hibernate.hql.classic.ClassicQueryTranslatorFactory* como o Valor da Propriedade. Clique em OK. image::images/add-property-factoryclass.png[title=""Caixa de diálogo Adicionar Propriedade Hibernate que mostra o valor de definição de hibernate.query.factory_class""] Se clicar na guia XML no editor, você pode ver o arquivo na view XML. O arquivo deve ter uma aparência semelhante à seguinte (as três novas propriedades estão em negrito): [source,xml] ---- org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### *true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory* ---- 9. Salve as alterações feitas no arquivo. Você pode fechar o arquivo, pois não será necessário editá-lo novamente. == Criando o Arquivo de Ajuda ``HibernateUtil.java`` Para usar o Hibernate, é necessário criar uma classe de ajuda que lide com a inicialização e que acesse o ``SessionFactory`` do Hibernate para obter um objeto de Sessão. A classe chama ``configure()`` , carrega o arquivo de configuração ``hibernate.cfg.xml`` e cria ``SessionFactory`` para obter o objeto Sessão. Nesta seção, você usa o assistente para Novo Arquivo a fim de criar a classe helper ``HibernateUtil.java`` . 1. Clique com o botão direito do mouse no nó dos Pacote de Códigos-fonte e selecione Novo > Outro para abrir o assistente para Novo Arquivo. 2. Selecione Hibernate na lista Categorias e HibernateUtil.java na lista Tipos de Arquivo. Clique em Próximo. 3. Digite *HibernateUtil* para o nome da classe e *dvdrental* para o pacote. Clique em Finalizar. image::images/hibernate-util-wizard.png[title=""Tela do assistente do HibernateUtil""] Quando você clicar em Finalizar, o ``HibernateUtil.java`` será aberto no editor. Você pode fechar o arquivo porque não precisa editá-lo. == Gerando Arquivos de Mapeamento Hibernate e Classes Java Neste tutorial, você utilizará um POJO (objetos Java simples antigos) para representar os dados em cada uma das tabelas do banco de dados a ser utilizado. A classe Java especifica os campos das colunas nas tabelas e utiliza setters e getters simples para recuperar e gravar os dados. Para mapear os POJOs para as tabelas, utilize um arquivo de mapeamento do Hibernate ou utilize anotações na classe. Você pode utilizar os Arquivos de Mapeamento do Hibernate e POJOs obtidos de um assistente de Banco de Dados para criar vários POJOs e arquivos de mapeamento com base nas tabelas de banco de dados. Ao utilizar o assistente, selecione todas as tabelas para as quais deseja POJOs e arquivos de mapeamento, e o IDE irá gerar os arquivos com base nas tabelas do banco de dados e adicionar as entradas de mapeamento no ``hibernate.cfg.xml`` . Quando usa o assistente, você pode escolher os arquivos que deseja que o IDE gere (somente os POJOs, por exemplo) e selecionar as opções de geração de código (gerar código que use anotações EJB 3, por exemplo). *Observação.* O IDE também possui assistentes para ajudá-lo a criar POJOs e arquivos de mapeamento individuais do zero. === Criando o Arquivo de Engenharia Reversa do Hibernate Se quiser utilizar os arquivos de Mapeamento do Hibernate e POJOs de um assistente de Banco de Dados, primeiro é necessário criar um arquivo de engenharia reversa ``hibernate.reveng.xml`` . Os Arquivos de Mapeamento do Hibernate e POJOs de um assistente de Banco de Dados requerem os arquivos ``hibernate.reveng.xml`` e ``hibernate.cfg.xml`` . O arquivo de engenharia reversa permite ter maior controle sobre a estratégia de mapeamento do banco de dados. O Assistente para Engenharia Reversa do Hibernate cria um arquivo de engenharia reversa com uma configuração default que pode ser editada no editor XML. Para criar o arquivo de engenharia reversa do Hibernate, execute as etapas seguintes. 1. Clique com o botão direito do mouse no nó Pacotes de Código-fonte na janela Projetos e escolha Novo > Outro para abrir o assistente para Novo Arquivo. 2. Selecione o Assistente para Engenharia Reversa do Hibernate na categoria Hibernate. Clique em Próximo. 3. Especifique ``hibernate.reveng`` como o Nome do arquivo e ``src/java`` para a Pasta. Clique em Próximo. 4. Selecione ``hibernate.cfg.xml`` na lista drop-down Arquivo de Configuração, caso não esteja selecionado. 5. Selecione as tabelas a seguir em Tabelas Disponíveis e clique em Adicionar para adicionar as tabelas a Tabelas Selecionadas. * ator * categoria * filme * film_actor * film_category * idioma Clique em Finalizar. image::images/hibernate-reveng-wizard.png[title=""Novo assistente de Engenharia Reversa do Hibernate""] O assistente gera um arquivo de engenharia reversa ``hibernate.reveng.xml`` e abre o arquivo no editor. Você pode fechar o arquivo de engenharia reversa porque não precisará editar o arquivo. Para obter mais detalhes sobre como trabalhar com o arquivo ``hibernate.reveng.xml`` , consulte o link:http://docs.jboss.org/tools/2.1.0.Beta1/hibernatetools/html/reverseengineering.html[+Capítulo 5. Controlando a engenharia reversa+] no link:http://docs.jboss.org/tools/2.1.0.Beta1/hibernatetools/html/[+Guia de Referência das Ferramentas do Hibernate+]. === Criando arquivos de mapeamento do Hibernate e POJOs Você pode utilizar os Arquivos de Mapeamento do Hibernate e POJOs obtidos de um assistente de Banco de Dados para gerar arquivos. O assistente pode gerar um POJO e um arquivo de mapeamento correspondente para cada tabela que você selecionar no assistente. Os arquivos de mapeamento são arquivos XML que contêm dados sobre como as colunas das tabelas são mapeadas para os campos nos POJOs. É necessário ter os arquivos ``hibernate.reveng.xml`` e ``hibernate.cfg.xml`` para utilizar o assistente. Para criar os POJOS e arquivos de mapeamento utilizando um assistente, execute as etapas a seguir: 1. Clique com o botão direito do mouse no nó Pacotes de Código-fonte na janela Projetos e escolha Novo > Outro para abrir o assistente para Novo Arquivo. 2. Selecione Arquivos de Mapeamento do Hibernate e POJOs provenientes de um Banco de Dados na categoria Hibernate. Clique em Próximo. 3. Certifique-se de que os arquivos ``hibernate.cfg.xml`` e ``hibernate.reveng.xml`` estejam selecionados nas listas drop-down. 4. Selecione *Funcionalidades da Linguagem JDK 5* nas opções Definições Gerais. 5. Certifique-se de que as opções *Código do Domínio* e *Mapeamentos XML do Hibernate* estejam selecionadas. 6. Selecione *dvdrental* para o Nome do pacote. Clique em Finalizar. image::images/hibernate-pojo-wizard2.png[title=""Gerar assistente Arquivos de Mapeamento Hibernar e POJOs""] Quando você clicar em Finalizar, o IDE irá gera POJOs e arquivos de mapeamento do Hibernate com os campos mapeados para as colunas especificadas em ``hibernate.reveng.xml`` . O IDE também adicionará entradas de mapeamento em ``hibernate.cfg.xml`` . [source,xml] ---- org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory ---- *Observação.* Confirme se os elementos ``mapping`` serão listados após os elementos ``property`` no arquivo ``hibernate.cfg.xml`` . É possível expandir o pacote ``dvdrental`` para ver os arquivos gerados pelo assistente. image::images/hib-projectswindow.png[title=""Janela Projetos mostrando os POJOs gerados""] Você pode utilizar o assistente para mapeamento do Hibernate se quiser criar um arquivo de mapeamento do Hibernate que mapeie uma tabela específica para uma classe específica. Para obter mais detalhes sobre como trabalhar com o arquivo ``hibernate.reveng.xml`` , consulte o link:http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html[+Capítulo 5. Mapeamento O/R Básico+] da link:http://docs.jboss.org/hibernate/stable/core/reference/en/html/[+Documentação de Referência do Hibernate+]. == Criando a Classe do Helper ``FilmHelper.java`` Agora você criará uma classe do helper no pacote ``dvdrental`` que será utilizada para efetuar consultas do Hibernate no banco de dados. Você utilizará o editor HQL (Hibernate Query Language) para criar e testar as consultas para recuperar dados. Depois de testar as consultas, você criará criados métodos na classe do helper que criarão e executarão as consultas. Em seguida, você chamará os métodos na classe do helper de um bean gerenciado pelo JSF. === Criando a Classe Nesta seção, utilize o assistente de Novo Arquivo para criar a classe do helper ``FilmHelper.java`` no pacote ``dvdrental`` . Você criará uma sessão do Hibernate, chamando ``getSessionFactory`` em ``HibernateUtil.java`` e criará alguns métodos do helper para fazer consultas e recuperar dados do banco de dados. Você chamará os métodos do helper de páginas JSP. 1. Clique com o botão direito do mouse no nó do pacote de códigos-fonte ``dvdrental`` e selecione Novo > Classe Java para abrir o assistente de Novo arquivo. 2. Digite *FilmHelper* como nome da classe. 3. Confirme se *dvdrental* está selecionado como o Pacote. Clique em Finalizar. 4. Adicionando o código a seguir (em negrito) para criar uma sessão do Hibernate. [source,java] ---- public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* } ---- 5. Clique com o botão direito do mouse no editor, selecione Corrigir importações (Alt-Shift-I; &#8984-Shift-I no Mac) para adicionar as instruções necessárias de importação ( ``org.hibernate.Session`` ) e salve suas alterações. Agora você modificará ``FilmHelper.java`` para adicionar métodos de consulta do BD. === Enumerando Títulos de Filmes e Recuperando Atores Utilizando uma Consulta HQL Neste exercício, você criará uma consulta HQL (Hibernate Query Language) que consulta o banco de dados para recuperar uma lista de títulos de filmes da tabela Film. Em seguida, você adicionará um método que consulte as tabelas Actor e Film_actor para extrair os atores que atuam em um filme específico. A tabela Film possui 1000 registros, de modo que o método para recuperar a lista de filmes deveria ser capaz de recuperar os registros com base na chave primária ``filmId`` . Utilize o editor HQL para criar e testar a consulta HQL. Após criar a consulta correta, você adicionará um método à classe que possa gerar a consulta apropriada. 1. Clique com o botão direito do mouse no nó do projeto na janela Projetos e selecione Limpar e Construir. 2. Clique com o botão direito do mouse em ``hibernate.cfg.xml`` na janela Projetos e selecione Executar Consulta HQL para abrir o editor de consultas HQL. 3. Selecione hibernate.cfg na lista drop-down da barra de ferramentas. 4. Teste a conexão digitando no editor e clicando no botão Executar a Consulta HQL ( image::images/run_hql_query_16.png[title=""Botão Executar Consulta HQL""] ) da barra de ferramentas. [source,java] ---- from Film ---- Ao clicar em Executar a Consulta HQL, você verá os resultados da consulta na janela inferior do editor de consultas HQL. image::images/hibernate-hqleditor1.png[title=""Gerar assistente Arquivos de Mapeamento Hibernar e POJOs""] Se você clicar no botão SQL, você verá a consulta SQL equivalente. [source,java] ---- select film0_.film_id as col_0_0_ from sakila.film film0_ ---- 5. Digite a consulta a seguir para recuperar os registros da tabela Film, onde o id do filme está entre 100 e 200. [source,java] ---- from Film as film where film.filmId between 100 and 200 ---- A janela de resultados exibirá uma lista de registros. Agora que você verificou que a consulta testada retorna os resultados desejados, utilize a consulta na classe do helper. 6. Adicione o método a seguir, ``getFilmTitles`` a ``FilmHelper.java`` , para recuperar os filmes, onde o id do filme está entre uma determinada faixa especificada pelas variáveis ``startID`` e ``endID`` . [source,java] ---- public List getFilmTitles(int startID, int endID) { List filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery (""from Film as film where film.filmId between '""+startID+""' and '""+endID+""'""); filmList = (List) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; } ---- 7. Adicione o método a seguir, ``getActorsByID`` , para recuperar os atores de um filme específico. O método construirá a consulta utilizando ``filmId`` como a variável de entrada. [source,java] ---- public List getActorsByID(int filmId){ List actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery (""from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='"" + filmId + ""')""); actorList = (List) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; } ---- 8. Corrija as importações e salve as alterações. Ao corrigir suas importações, selecione ``java.util.List`` e ``org.hibernate.Query`` . === Adicionando Métodos Adicionais do Helper Agora você adicionará métodos adicionais do assistente que criem consultas com base em uma variável de entrada. É possível verificar as consultas no editor de consultas HQL. 1. Adicione o método a seguir para recuperar uma lista de categorias de acordo com ``filmId`` . [source,java] ---- public Category getCategoryByID(int filmId){ List categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery(""from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='"" + filmId + ""')""); categoryList = (List) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); } ---- 2. Adicione o método seguinte para recuperar um único filme de acordo com o ``filmId`` . [source,java] ---- public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery(""from Film as film where film.filmId="" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; } ---- 3. Adicione o método a seguir para recuperar o idioma do filme de acordo com o ``filmId`` . [source,java] ---- public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery(""from Language as lang where lang.languageId="" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); } ---- 4. Salve as alterações. == Criando o Bean Gerenciado pelo JSF Neste exercício, você criará um bean gerenciado pelo JSF. Os métodos do bean gerenciado são utilizados para exibir dados nas páginas JSF e para acessar métodos da classe do helper para recuperar registros. A especificação do JSF 2.0 permite utilizar anotações em uma classe bean para identificar a classe como um bean gerenciado pelo JSF, especificar o escopo e um nome para o bean. Para criar o bean gerenciado, execute as seguintes etapas: 1. Clique com o botão direito do mouse no nó do pacote de código-fonte ``dvdrental`` e selecione Novo > Outro. 2. Selecione Bean Gerenciado pelo JSF na categoria JavaServer Faces. Clique em Próximo. 3. Digite *FilmController* para Nome da Classe. Você usará o nome ``filmController`` do Bean Gerenciado como o valor para ``inputText`` e ``commandButton`` na página JSF ``index.xhtml`` ao chamar métodos no Bean. 4. Selecione *dvdrental* para o Pacote. 5. Digite *filmController* como o Nome que será utilizado para o bean gerenciado. 6. Defina o Escopo Como Sessão. Clique em Finalizar. image::images/hib-newmanagedbean.png[title=""Novo assistente de Bean Gerenciado pelo JSF""] Quando você clicar em Finalizar, o IDE gerará a classe bean e abrirá a classe no editor. O IDE adicionou as anotações ``@ManagedBean`` e ``@SessionScoped`` . [source,java] ---- @ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } } ---- *Observação.* Observe que o nome do bean gerenciado não está especificado explicitamente. Por default, o nome do bean é o mesmo que o nome da classe e inicia com letra minúscula. Se você quiser que o nome do bean seja diferente do nome da classe, você poderá especificá-lo explicitamente como um parâmetro das anotações ``@ManagedBean`` (por exemplo, ``@ManagedBean(name=""myBeanName"")`` . 1. Adicione os campos a seguir (em negrito) à classe. [source,java] ---- @ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* } ---- 2. Adicione o código a seguir (em negrito) para criar a instância do FilmController e recuperar os filmes. [source,java] ---- /** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }* ---- 3. Adicione os métodos a seguir usados para exibir a tabela e navegar entre as páginas.* public boolean isHasNextPage() { if (endId + pageSize <= recordCount) { return true; } return false; } public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; } public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return ""index""; } public String previous() { startId = startId - pageSize; endId = endId - pageSize; recreateModel(); return ""index""; } public int getPageSize() { return pageSize; } public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return ""browse""; } public String prepareList(){ recreateModel(); return ""index""; } * Os métodos que retornam ""index"" ou ""browse"" solicitarão o handler de navegação JSF para tentar abrir uma página denominada ``index.xhtml`` ou ``browse.xhtml`` . A especificação JSF 2.0 permite a utilização de regras de navegação implícitas em aplicações que utilizam a tecnologia Facelets. Nesta aplicação, não há regras de navegação configuradas em ``faces-config.xml`` . Em vez disso, o handler de navegação tentará localizar a página adequada na aplicação. 4. Adicione os métodos a seguir que acessam a classe do helper para recuperar detalhes adicionais do filme.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; } public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append("" ""); totalCast.append(actor.getLastName()); totalCast.append("" ""); } return totalCast.toString(); } public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }* [source,java] ---- ---- 5. Corrija as importações (Ctrl-Shift-I) e salve as alterações. Você pode utilizar a funcionalidade para autocompletar código no editor para ajudar a digitar seu código. == Criando as Páginas Web Neste exercício, você criará duas páginas Web para exibir os dados. Você modificará o ``index.xhtml`` gerado pelo IDE para adicionar uma tabela que exiba os filmes do banco de dados. Em seguida, você criará ``browse.xhtml`` para exibir os detalhes de um filme ao clicar no link ""Exibir"" da tabela. Você criará também uma página modelo do JSF que será utilizada por ``index.xhtml`` e ``browse.xhtml`` . Para saber mais sobre a utilização do JSF 2.0 e modelos do Facelets, consulte link:jsf20-intro.html[+Introdução ao JavaServer Faces 2.0+] === Criando ``template.xhtml`` Primeiro, você criará o modelo de Facelets ``template.xhtml`` do JSF utilizado na composição das páginas ``index.xhtml`` e ``browse.xhtml`` . 1. Clique com o botão direito do mouse no nó do projeto DVDStore na janela Projetos e selecione Novo > Outro. 2. Selecione Modelo de Facelets na categoria JavaServer Faces. Clique em Próximo. 3. Digite *template* para o Nome do Arquivo e selecione o primeiro estilo de layout CSS. 4. Clique em Finalizar. Quando você clica em Finalizar, o arquivo ``template.xhtml`` é aberto no editor. O modelo contém o código default a seguir. [source,html] ----
Top
Content
---- 5. Modifique o elemento ```` para alterar o nome gerado default para ""corpo"". [source,html] ----
Content
---- 6. Salve as alterações. O conteúdo do elemento ```` nos arquivos ``index.xhtml`` e ``browse.xhtml`` será inserido no local identificado com `` Content`` no modelo. === Modificando ``index.xhtml`` Quando você criou a aplicação Web, o IDE gerou automaticamente a página ``index.xhtml`` . Neste exercício, você modifica a página para exibir uma lista de títulos de filmes. A página JSF chama os métodos no FilmController do Bean Gerenciado pelo JSF para recuperar a lista de filmes e exibir uma tabela com títulos e descrições dos filmes. 1. Expanda a pasta Páginas Web na janela Projetos e abra ``index.xhtml`` no editor. O assistente para Novo Projeto gerou a seguinte página ``index.xhtml`` default. [source,xml] ---- Facelet Title Hello from Facelets ---- 2. Modifique a página para utilizar os elementos JSF ```` e ```` e adicione um elemento ```` . [source,xml] ---- * ---- Quando você começa a digitar as tags, o IDE adiciona a declaração da biblioteca de tags ``xmlns:ui=""http://java.sun.com/jsf/facelets""`` . Os elementos ```` e ```` são utilizados em combinação com o modelo de página que você criará. O elemento ```` faz referência à localização do modelo que será utilizado por essa página. O elemento ```` faz referência à posição no modelo que o código incluído ocupará. 3. Adicione os seguintes links de navegação que chamam os métodos ``previous`` e ``next`` no Bean gerenciado pelo JSF. [source,xml] ---- *   * ---- 4. Adicione o seguinte elemento ``dataTable`` (em negrito) para gerar a tabela para exibir os itens recuperados. [source,xml] ----     *
*
---- 5. Salve as alterações. A página de índice agora exibirá uma lista de títulos de filmes no banco de dados. Cada linha da tabela inclui um link ""Exibir"" que chama o método ``prepareView`` no bean gerenciado. O método ``prepareView`` retornará ""browse"" e abrirá o ``browse.xhtml`` . *Observação.* Quando você digitar a tag ```` , o IDE adicionará a declaração da biblioteca de tags ``xmlns:f=""http://java.sun.com/jsf/core`` . *Confirme se a biblioteca de tags está declarada no arquivo.* === Criando ``browse.xhtml`` Agora você criará a página ``browse.xhtml`` para exibir os detalhes do filme selecionado. É possível utilizar o assistente Cliente de Modelo de Facelets para criar a página com base no modelo de Facelets do JSF ``template.xhtml`` que você criou. 1. Clique com o botão direito do mouse no nó do projeto DVDStore na janela Projetos e selecione Novo > Outro. 2. Selecione Cliente de Modelo de Facelets na categoria JavaServer Faces. Clique em Próximo. image::images/hib-faceletsclient.png[title=""Tipo de arquivo Cliente de Modelo de Facelets no assistente Novo Arquivo""] 3. Digite *browse* para o Nome do Arquivo. 4. Localize o Modelo da página clicando em Procurar para abrir a caixa de diálogo Procurar Arquivos. 5. Expanda a pasta Páginas Web e selecione ``template.xhtml`` . Clique em Selecionar Arquivo. image::images/hib-browsetemplate.png[title=""Selecione o modelo na caixa de diálogo Procurar Arquivos""] 6. Selecione ** para a Tag Raiz Gerada. Clique em Finalizar. Quando você clica em Finalizar, o arquivo ``browse.xhtml`` abrirá no editor com o código a seguir. [source,xml] ---- top body ---- É possível ver que o novo arquivo especifica o arquivo ``template.xhtml`` e que a tag ```` possui a propriedade ``name=""body""`` 7. Adicione o código a seguir (em negrito) entre as tags ```` para criar o form e chamar os métodos no FilmController do Bean gerenciado para recuperar os dados e preencher o form. [source,xml] ---- top *


*
---- É possível ver que os arquivos ``browse.xhtml`` e ``index.xhtml`` utilizarão o mesmo modelo de página. 8. Salve as alterações. == Executando o Projeto O conceito básico da aplicação agora está concluído. Agora você pode executar a aplicação para verificar se tudo está funcionando corretamente. 1. Clique em Executar Projeto Principal na barra de ferramentas principal ou clique com o botão direito do mouse no nó da aplicação DVDStore na janela Projetos e selecione Executar. O IDE salva todos os arquivos alterados, constrói e implanta a aplicação no servidor. O IDE abre a janela do browser no URL ``http://localhost:8080/DVDStore/`` que exibe a lista de filmes. image::images/hib-browser1.png[title=""Tela do browser exibindo a lista de filme na página de índice""] 2. No browser, clique em ""Exibir"" para carregar o ``browse.xhtml`` e exibir os detalhes do filme. === Fazendo Download do Projeto da Solução Você pode fazer o download da solução para este projeto como um projeto das seguintes formas. * Faça download link:https://netbeans.org/projects/samples/downloads/download/Samples/JavaEE/DVDStoreEE6.zip[+de um arquivo compactado zip do projeto finalizado+]. * Faça o check-out do código-fonte do projeto das Amostras do NetBeans ao executar as etapas a seguir: 1. Escolha Equipe > Subversion > Efetuar check-out no menu principal. 2. Na caixa de diálogo Efetuar Check-out, insira o Repositório URL a seguir: ``https://svn.netbeans.org/svn/samples~samples-source-code`` Clique em Próximo. 3. Clique em Procurar para abrir a caixa de diálogo Procurar nas Pastas do Repositório: 4. Expanda o nó raiz e selecione *samples/javaee/DVDStoreEE6*. Clique em OK. 5. Especifique a Pasta Local dos códigos-fonte. 6. Clique em Finalizar. Quando você clica em Finalizar, o IDE inicializa a pasta local como um repositório Subversion e verifica os códigos-fonte do projeto. 7. Clique em Abrir Projeto na caixa de diálogo exibida quando o check-out for concluído. *Observações.* Para saber mais sobre a instalação do Subversion, consulte a seção link:../ide/subversion.html#settingUp[+Configurando o Subversion+] no link:../ide/subversion.html[+Guia do Subversion no NetBeans IDE+]. === Solução de Problemas A maioria dos problemas que ocorrem com a aplicação do tutorial são devidos a dificuldades de comunicação entre o GlassFish Server Open Source Edition e o servidor de banco de dados MySQL. Se sua aplicação não for exibida corretamente, ou se estiver recebendo um erro do servidor, você pode verificar a seção link:mysql-webapp.html#troubleshoot[+Solução de Problemas+] do tutorial link:mysql-webapp.html[+Criando uma Aplicação Web Simples Usando um Banco de Dados MySQL+] ou o tutorial link:../ide/mysql.html[+Estabelecendo Conexão a um Banco de Dados MySQL+]. Se fizer download e executar o projeto da solução, você verá o seguinte erro na janela de Saída se for a primeira vez que você implantou uma aplicação que usa o banco de dados My SQL. [source,java] ---- SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org ---- Em sua janela do browser você pode ver um ``java.lang.ExceptionInInitializerError`` e o seguinte rastreamento de pilha. [source,java] ---- java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ... ---- A mensagem de saída declara que o driver JDBC do banco de dados MySQL não foi encontrado. O motivo mais provável é que você precisa adicionar o arquivo do driver JDBC de MySQL em sua instalação do servidor GlassFish. Para confirmar se o driver não foi encontrado, navegue até o diretório ``_GLASSFISH-INSTALL_/glassfish/domains/domain1/lib`` em seu sistema local (no qual _GLASSFISH-INSTALL_ é seu diretório de instalação GlassFish). Se o diretório ``domain1/lib`` não contiver o arquivo do driver JDBC (por exemplo, `mysql-connector-java-5.1.13-bin.jar`) você precisa copiar o driver JDBC para o diretório. O driver JDBC de MySQL não é adicionado à sua instalação do GlassFish quando você instala o servidor. Você pode adicionar uma cópia do driver JDBC do MySQL para sua instalação do GlassFish executando as seguintes etapas. 1. Faça download do link:http://dev.mysql.com/downloads/connector/j/[+Conector MySQL/driver J JDBC+]. 2. Extrai o driver e copie o arquivo do driver (por exemplo, `mysql-connector-java-5.1.13-bin.jar`) para o diretório ``domain1/lib`` de sua instalação do GlassFish. Se preferir, quando usar o IDE para criar uma aplicação que usa o banco de dados MySQL, o IDE pode automaticamente copiar o driver JDBC de MySQL para o servidor GlassFish quando você implantar o projeto, se necessário. Para confirmar se o IDE copiará os drivers JDBC necessários, escolha Ferramentas > Servidores do menu principal para abrir o gerenciador de Servidores e confirmar que a opção Ativar Implantação do Driver JDBC é selecionada para seu servidor GlassFish. Depois de criar e implantar uma aplicação web que usa o banco de dados MySQL, se você navegar para o diretório `domain1/lib` de sua instalação GlassFish local você verá que o diretório contém o arquivo do driver JDBC. link:/about/contact_form.html?to=3&subject=Feedback:%20Using%20Hibernate%20in%20a%20Web%20Application[+Enviar Feedback neste Tutorial+] == Consulte Também * link:jsf20-support.html[+Suporte a JSF 2.x no NetBeans IDE+] * link:jsf20-intro.html[+Introdução ao JavaServer Faces 2.x+] * link:../../trails/java-ee.html[+Trilha de Aprendizado do Java EE e Java Web+] ",12522,False,1981.359593213196,median "/* Copyright (c) 2016, 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. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include ""../test/test_util.h"" // kTag128 is an ASN.1 structure with a universal tag with number 128. static const uint8_t kTag128[] = { 0x1f, 0x81, 0x00, 0x01, 0x00, }; // kTag258 is an ASN.1 structure with a universal tag with number 258. static const uint8_t kTag258[] = { 0x1f, 0x82, 0x02, 0x01, 0x00, }; static_assert(V_ASN1_NEG_INTEGER == 258, ""V_ASN1_NEG_INTEGER changed. Update kTag258 to collide with it.""); // kTagOverflow is an ASN.1 structure with a universal tag with number 2^35-1, // which will not fit in an int. static const uint8_t kTagOverflow[] = { 0x1f, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01, 0x00, }; TEST(ASN1Test, LargeTags) { const uint8_t *p = kTag258; bssl::UniquePtr obj(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag258))); EXPECT_FALSE(obj) << ""Parsed value with illegal tag"" << obj->type; ERR_clear_error(); p = kTagOverflow; obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTagOverflow))); EXPECT_FALSE(obj) << ""Parsed value with tag overflow"" << obj->type; ERR_clear_error(); p = kTag128; obj.reset(d2i_ASN1_TYPE(NULL, &p, sizeof(kTag128))); ASSERT_TRUE(obj); EXPECT_EQ(128, obj->type); const uint8_t kZero = 0; EXPECT_EQ(Bytes(&kZero, 1), Bytes(obj->value.asn1_string->data, obj->value.asn1_string->length)); } TEST(ASN1Test, IntegerSetting) { bssl::UniquePtr by_bn(ASN1_INTEGER_new()); bssl::UniquePtr by_long(ASN1_INTEGER_new()); bssl::UniquePtr by_uint64(ASN1_INTEGER_new()); bssl::UniquePtr bn(BN_new()); const std::vector kValues = { LONG_MIN, -2, -1, 0, 1, 2, 0xff, 0x100, 0xffff, 0x10000, LONG_MAX, }; for (const auto &i : kValues) { SCOPED_TRACE(i); ASSERT_EQ(1, ASN1_INTEGER_set(by_long.get(), i)); const uint64_t abs = i < 0 ? (0 - (uint64_t) i) : i; ASSERT_TRUE(BN_set_u64(bn.get(), abs)); BN_set_negative(bn.get(), i < 0); ASSERT_TRUE(BN_to_ASN1_INTEGER(bn.get(), by_bn.get())); EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_long.get())); if (i >= 0) { ASSERT_EQ(1, ASN1_INTEGER_set_uint64(by_uint64.get(), i)); EXPECT_EQ(0, ASN1_INTEGER_cmp(by_bn.get(), by_uint64.get())); } } } template void TestSerialize(T obj, int (*i2d_func)(T a, uint8_t **pp), bssl::Span expected) { // Test the allocating version first. It is easiest to debug. uint8_t *ptr = nullptr; int len = i2d_func(obj, &ptr); ASSERT_GT(len, 0); EXPECT_EQ(Bytes(expected), Bytes(ptr, len)); OPENSSL_free(ptr); len = i2d_func(obj, nullptr); ASSERT_GT(len, 0); EXPECT_EQ(len, static_cast(expected.size())); std::vector buf(len); ptr = buf.data(); len = i2d_func(obj, &ptr); ASSERT_EQ(len, static_cast(expected.size())); EXPECT_EQ(ptr, buf.data() + buf.size()); EXPECT_EQ(Bytes(expected), Bytes(buf)); } TEST(ASN1Test, SerializeObject) { static const uint8_t kDER[] = {0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01}; const ASN1_OBJECT *obj = OBJ_nid2obj(NID_rsaEncryption); TestSerialize(obj, i2d_ASN1_OBJECT, kDER); } TEST(ASN1Test, SerializeBoolean) { static const uint8_t kTrue[] = {0x01, 0x01, 0xff}; TestSerialize(0xff, i2d_ASN1_BOOLEAN, kTrue); // Other constants are also correctly encoded as TRUE. TestSerialize(1, i2d_ASN1_BOOLEAN, kTrue); TestSerialize(0x100, i2d_ASN1_BOOLEAN, kTrue); static const uint8_t kFalse[] = {0x01, 0x01, 0x00}; TestSerialize(0x00, i2d_ASN1_BOOLEAN, kFalse); } // The templates go through a different codepath, so test them separately. TEST(ASN1Test, SerializeEmbeddedBoolean) { bssl::UniquePtr val(BASIC_CONSTRAINTS_new()); ASSERT_TRUE(val); // BasicConstraints defaults to FALSE, so the encoding should be empty. static const uint8_t kLeaf[] = {0x30, 0x00}; val->ca = 0; TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kLeaf); // TRUE should always be encoded as 0xff, independent of what value the caller // placed in the |ASN1_BOOLEAN|. static const uint8_t kCA[] = {0x30, 0x03, 0x01, 0x01, 0xff}; val->ca = 0xff; TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA); val->ca = 1; TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA); val->ca = 0x100; TestSerialize(val.get(), i2d_BASIC_CONSTRAINTS, kCA); } TEST(ASN1Test, ASN1Type) { const struct { int type; std::vector der; } kTests[] = { // BOOLEAN { TRUE } {V_ASN1_BOOLEAN, {0x01, 0x01, 0xff}}, // BOOLEAN { FALSE } {V_ASN1_BOOLEAN, {0x01, 0x01, 0x00}}, // OCTET_STRING { ""a"" } {V_ASN1_OCTET_STRING, {0x04, 0x01, 0x61}}, // OCTET_STRING { } {V_ASN1_OCTET_STRING, {0x04, 0x00}}, // BIT_STRING { `01` `00` } {V_ASN1_BIT_STRING, {0x03, 0x02, 0x01, 0x00}}, // INTEGER { -1 } {V_ASN1_INTEGER, {0x02, 0x01, 0xff}}, // OBJECT_IDENTIFIER { 1.2.840.113554.4.1.72585.2 } {V_ASN1_OBJECT, {0x06, 0x0c, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02}}, // NULL {} {V_ASN1_NULL, {0x05, 0x00}}, // SEQUENCE {} {V_ASN1_SEQUENCE, {0x30, 0x00}}, // SET {} {V_ASN1_SET, {0x31, 0x00}}, // [0] { UTF8String { ""a"" } } {V_ASN1_OTHER, {0xa0, 0x03, 0x0c, 0x01, 0x61}}, }; for (const auto &t : kTests) { SCOPED_TRACE(Bytes(t.der)); // The input should successfully parse. const uint8_t *ptr = t.der.data(); bssl::UniquePtr val(d2i_ASN1_TYPE(nullptr, &ptr, t.der.size())); ASSERT_TRUE(val); EXPECT_EQ(ASN1_TYPE_get(val.get()), t.type); EXPECT_EQ(val->type, t.type); TestSerialize(val.get(), i2d_ASN1_TYPE, t.der); } } // Test that reading |value.ptr| from a FALSE |ASN1_TYPE| behaves correctly. The // type historically supported this, so maintain the invariant in case external // code relies on it. TEST(ASN1Test, UnusedBooleanBits) { // OCTET_STRING { ""a"" } static const uint8_t kDER[] = {0x04, 0x01, 0x61}; const uint8_t *ptr = kDER; bssl::UniquePtr val(d2i_ASN1_TYPE(nullptr, &ptr, sizeof(kDER))); ASSERT_TRUE(val); EXPECT_EQ(V_ASN1_OCTET_STRING, val->type); EXPECT_TRUE(val->value.ptr); // Set |val| to a BOOLEAN containing FALSE. ASN1_TYPE_set(val.get(), V_ASN1_BOOLEAN, NULL); EXPECT_EQ(V_ASN1_BOOLEAN, val->type); EXPECT_FALSE(val->value.ptr); } TEST(ASN1Test, ASN1ObjectReuse) { // 1.2.840.113554.4.1.72585.2, an arbitrary unknown OID. static const uint8_t kOID[] = {0x2a, 0x86, 0x48, 0x86, 0xf7, 0x12, 0x04, 0x01, 0x84, 0xb7, 0x09, 0x02}; ASN1_OBJECT *obj = ASN1_OBJECT_create(NID_undef, kOID, sizeof(kOID), ""short name"", ""long name""); ASSERT_TRUE(obj); // OBJECT_IDENTIFIER { 1.3.101.112 } static const uint8_t kDER[] = {0x06, 0x03, 0x2b, 0x65, 0x70}; const uint8_t *ptr = kDER; EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER))); EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj)); ASN1_OBJECT_free(obj); // Repeat the test, this time overriding a static |ASN1_OBJECT|. obj = OBJ_nid2obj(NID_rsaEncryption); ptr = kDER; EXPECT_TRUE(d2i_ASN1_OBJECT(&obj, &ptr, sizeof(kDER))); EXPECT_EQ(NID_ED25519, OBJ_obj2nid(obj)); ASN1_OBJECT_free(obj); } TEST(ASN1Test, BitString) { const size_t kNotWholeBytes = static_cast(-1); const struct { std::vector in; size_t num_bytes; } kValidInputs[] = { // Empty bit string {{0x03, 0x01, 0x00}, 0}, // 0b1 {{0x03, 0x02, 0x07, 0x80}, kNotWholeBytes}, // 0b1010 {{0x03, 0x02, 0x04, 0xa0}, kNotWholeBytes}, // 0b1010101 {{0x03, 0x02, 0x01, 0xaa}, kNotWholeBytes}, // 0b10101010 {{0x03, 0x02, 0x00, 0xaa}, 1}, // Bits 0 and 63 are set {{0x03, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, 8}, // 64 zero bits {{0x03, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, 8}, }; for (const auto &test : kValidInputs) { SCOPED_TRACE(Bytes(test.in)); // The input should parse and round-trip correctly. const uint8_t *ptr = test.in.data(); bssl::UniquePtr val( d2i_ASN1_BIT_STRING(nullptr, &ptr, test.in.size())); ASSERT_TRUE(val); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, test.in); // Check the byte count. size_t num_bytes; if (test.num_bytes == kNotWholeBytes) { EXPECT_FALSE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes)); } else { ASSERT_TRUE(ASN1_BIT_STRING_num_bytes(val.get(), &num_bytes)); EXPECT_EQ(num_bytes, test.num_bytes); } } const std::vector kInvalidInputs[] = { // Wrong tag {0x04, 0x01, 0x00}, // Missing leading byte {0x03, 0x00}, // Leading byte too high {0x03, 0x02, 0x08, 0x00}, {0x03, 0x02, 0xff, 0x00}, // TODO(https://crbug.com/boringssl/354): Reject these inputs. // Empty bit strings must have a zero leading byte. // {0x03, 0x01, 0x01}, // Unused bits must all be zero. // {0x03, 0x02, 0x06, 0xc1 /* 0b11000001 */}, }; for (const auto &test : kInvalidInputs) { SCOPED_TRACE(Bytes(test)); const uint8_t *ptr = test.data(); bssl::UniquePtr val( d2i_ASN1_BIT_STRING(nullptr, &ptr, test.size())); EXPECT_FALSE(val); } } TEST(ASN1Test, SetBit) { bssl::UniquePtr val(ASN1_BIT_STRING_new()); ASSERT_TRUE(val); static const uint8_t kBitStringEmpty[] = {0x03, 0x01, 0x00}; TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 100)); // Set a few bits via |ASN1_BIT_STRING_set_bit|. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1)); ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 1)); ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 2, 0)); ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 1)); static const uint8_t kBitString1101[] = {0x03, 0x02, 0x04, 0xd0}; TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1101); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 1)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2)); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4)); // Bits that were set may be cleared. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 1, 0)); static const uint8_t kBitString1001[] = {0x03, 0x02, 0x04, 0x90}; TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2)); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 3)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4)); // Clearing trailing bits truncates the string. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 3, 0)); static const uint8_t kBitString1[] = {0x03, 0x02, 0x07, 0x80}; TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 1)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 2)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 3)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 4)); // Bits may be set beyond the end of the string. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 1)); static const uint8_t kBitStringLong[] = {0x03, 0x09, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62)); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 63)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64)); // The string can be truncated back down again. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0)); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64)); // |ASN1_BIT_STRING_set_bit| also truncates when starting from a parsed // string. const uint8_t *ptr = kBitStringLong; val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitStringLong))); ASSERT_TRUE(val); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringLong); ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 63, 0)); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64)); // A parsed bit string preserves trailing zero bits. static const uint8_t kBitString10010[] = {0x03, 0x02, 0x03, 0x90}; ptr = kBitString10010; val.reset(d2i_ASN1_BIT_STRING(nullptr, &ptr, sizeof(kBitString10010))); ASSERT_TRUE(val); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString10010); // But |ASN1_BIT_STRING_set_bit| will truncate it even if otherwise a no-op. ASSERT_TRUE(ASN1_BIT_STRING_set_bit(val.get(), 0, 1)); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitString1001); EXPECT_EQ(1, ASN1_BIT_STRING_get_bit(val.get(), 0)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 62)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 63)); EXPECT_EQ(0, ASN1_BIT_STRING_get_bit(val.get(), 64)); // By default, a BIT STRING implicitly truncates trailing zeros. val.reset(ASN1_BIT_STRING_new()); ASSERT_TRUE(val); static const uint8_t kZeros[64] = {0}; ASSERT_TRUE(ASN1_STRING_set(val.get(), kZeros, sizeof(kZeros))); TestSerialize(val.get(), i2d_ASN1_BIT_STRING, kBitStringEmpty); } TEST(ASN1Test, StringToUTF8) { static const struct { std::vector in; int type; const char *expected; } kTests[] = { // Non-minimal, two-byte UTF-8. {{0xc0, 0x81}, V_ASN1_UTF8STRING, nullptr}, // Non-minimal, three-byte UTF-8. {{0xe0, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr}, // Non-minimal, four-byte UTF-8. {{0xf0, 0x80, 0x80, 0x81}, V_ASN1_UTF8STRING, nullptr}, // Truncated, four-byte UTF-8. {{0xf0, 0x80, 0x80}, V_ASN1_UTF8STRING, nullptr}, // Low-surrogate value. {{0xed, 0xa0, 0x80}, V_ASN1_UTF8STRING, nullptr}, // High-surrogate value. {{0xed, 0xb0, 0x81}, V_ASN1_UTF8STRING, nullptr}, // Initial BOMs should be rejected from UCS-2 and UCS-4. {{0xfe, 0xff, 0, 88}, V_ASN1_BMPSTRING, nullptr}, {{0, 0, 0xfe, 0xff, 0, 0, 0, 88}, V_ASN1_UNIVERSALSTRING, nullptr}, // Otherwise, BOMs should pass through. {{0, 88, 0xfe, 0xff}, V_ASN1_BMPSTRING, ""X\\xef\\xbb\\xbf""}, {{0, 0, 0, 88, 0, 0, 0xfe, 0xff}, V_ASN1_UNIVERSALSTRING, ""X\\xef\\xbb\\xbf""}, // The maximum code-point should pass though. {{0, 16, 0xff, 0xfd}, V_ASN1_UNIVERSALSTRING, ""\\xf4\\x8f\\xbf\\xbd""}, // Values outside the Unicode space should not. {{0, 17, 0, 0}, V_ASN1_UNIVERSALSTRING, nullptr}, // Non-characters should be rejected. {{0, 1, 0xff, 0xff}, V_ASN1_UNIVERSALSTRING, nullptr}, {{0, 1, 0xff, 0xfe}, V_ASN1_UNIVERSALSTRING, nullptr}, {{0, 0, 0xfd, 0xd5}, V_ASN1_UNIVERSALSTRING, nullptr}, // BMPString is UCS-2, not UTF-16, so surrogate pairs are invalid. {{0xd8, 0, 0xdc, 1}, V_ASN1_BMPSTRING, nullptr}, }; for (const auto &test : kTests) { SCOPED_TRACE(Bytes(test.in)); SCOPED_TRACE(test.type); bssl::UniquePtr s(ASN1_STRING_type_new(test.type)); ASSERT_TRUE(s); ASSERT_TRUE(ASN1_STRING_set(s.get(), test.in.data(), test.in.size())); uint8_t *utf8; const int utf8_len = ASN1_STRING_to_UTF8(&utf8, s.get()); EXPECT_EQ(utf8_len < 0, test.expected == nullptr); if (utf8_len >= 0) { if (test.expected != nullptr) { EXPECT_EQ(Bytes(test.expected), Bytes(utf8, utf8_len)); } OPENSSL_free(utf8); } else { ERR_clear_error(); } } } static std::string ASN1StringToStdString(const ASN1_STRING *str) { return std::string(ASN1_STRING_get0_data(str), ASN1_STRING_get0_data(str) + ASN1_STRING_length(str)); } TEST(ASN1Test, SetTime) { static const struct { time_t time; const char *generalized; const char *utc; } kTests[] = { {-631152001, ""19491231235959Z"", nullptr}, {-631152000, ""19500101000000Z"", ""500101000000Z""}, {0, ""19700101000000Z"", ""700101000000Z""}, {981173106, ""20010203040506Z"", ""010203040506Z""}, #if defined(OPENSSL_64_BIT) // TODO(https://crbug.com/boringssl/416): These cases overflow 32-bit // |time_t| and do not consistently work on 32-bit platforms. For now, // disable the tests on 32-bit. Re-enable them once the bug is fixed. {2524607999, ""20491231235959Z"", ""491231235959Z""}, {2524608000, ""20500101000000Z"", nullptr}, // Test boundary conditions. {-62167219200, ""00000101000000Z"", nullptr}, {-62167219201, nullptr, nullptr}, {253402300799, ""99991231235959Z"", nullptr}, {253402300800, nullptr, nullptr}, #endif }; for (const auto &t : kTests) { SCOPED_TRACE(t.time); #if defined(OPENSSL_WINDOWS) // Windows |time_t| functions can only handle 1970 through 3000. See // https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/gmtime-s-gmtime32-s-gmtime64-s?view=msvc-160 if (t.time < 0 || int64_t{t.time} > 32535215999) { continue; } #endif bssl::UniquePtr utc(ASN1_UTCTIME_set(nullptr, t.time)); if (t.utc) { ASSERT_TRUE(utc); EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(utc.get())); EXPECT_EQ(t.utc, ASN1StringToStdString(utc.get())); } else { EXPECT_FALSE(utc); } bssl::UniquePtr generalized( ASN1_GENERALIZEDTIME_set(nullptr, t.time)); if (t.generalized) { ASSERT_TRUE(generalized); EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(generalized.get())); EXPECT_EQ(t.generalized, ASN1StringToStdString(generalized.get())); } else { EXPECT_FALSE(generalized); } bssl::UniquePtr choice(ASN1_TIME_set(nullptr, t.time)); if (t.generalized) { ASSERT_TRUE(choice); if (t.utc) { EXPECT_EQ(V_ASN1_UTCTIME, ASN1_STRING_type(choice.get())); EXPECT_EQ(t.utc, ASN1StringToStdString(choice.get())); } else { EXPECT_EQ(V_ASN1_GENERALIZEDTIME, ASN1_STRING_type(choice.get())); EXPECT_EQ(t.generalized, ASN1StringToStdString(choice.get())); } } else { EXPECT_FALSE(choice); } } } static std::vector StringToVector(const std::string &str) { return std::vector(str.begin(), str.end()); } TEST(ASN1Test, StringPrintEx) { const struct { int type; std::vector data; int str_flags; unsigned long flags; std::string expected; } kTests[] = { // A string like ""hello"" is never escaped or quoted. // |ASN1_STRFLGS_ESC_QUOTE| only introduces quotes when needed. Note // OpenSSL interprets T61String as Latin-1. {V_ASN1_T61STRING, StringToVector(""hello""), 0, 0, ""hello""}, {V_ASN1_T61STRING, StringToVector(""hello""), 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB, ""hello""}, {V_ASN1_T61STRING, StringToVector(""hello""), 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_ESC_QUOTE, ""hello""}, // By default, 8-bit characters are printed without escaping. {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, 0, std::string(1, '\\0') + ""\\n\\x80\\xff,+\\""\\\\<>;""}, // Flags control different escapes. Note that any escape flag will cause // blackslashes to be escaped. {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, ASN1_STRFLGS_ESC_2253, std::string(1, '\\0') + ""\\n\\x80\\xff\\\\,\\\\+\\\\\\""\\\\\\\\\\\\<\\\\>\\\\;""}, {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, ASN1_STRFLGS_ESC_CTRL, ""\\\\00\\\\0A\\x80\\xff,+\\""\\\\\\\\<>;""}, {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, ASN1_STRFLGS_ESC_MSB, std::string(1, '\\0') + ""\\n\\\\80\\\\FF,+\\""\\\\\\\\<>;""}, {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB, ""\\\\00\\\\0A\\\\80\\\\FF\\\\,\\\\+\\\\\\""\\\\\\\\\\\\<\\\\>\\\\;""}, // When quoted, fewer characters need to be escaped in RFC 2253. {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, ',', '+', '""', '\\\\', '<', '>', ';'}, 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_ESC_QUOTE, ""\\""\\\\00\\\\0A\\\\80\\\\FF,+\\\\\\""\\\\\\\\<>;\\""""}, // If no characters benefit from quotes, no quotes are added. {V_ASN1_T61STRING, {0, '\\n', 0x80, 0xff, '""', '\\\\'}, 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_CTRL | ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_ESC_QUOTE, ""\\\\00\\\\0A\\\\80\\\\FF\\\\\\""\\\\\\\\""}, // RFC 2253 only escapes spaces at the start and end of a string. {V_ASN1_T61STRING, StringToVector("" ""), 0, ASN1_STRFLGS_ESC_2253, ""\\\\ \\\\ ""}, {V_ASN1_T61STRING, StringToVector("" ""), 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, ""\\"" \\""""}, // RFC 2253 only escapes # at the start of a string. {V_ASN1_T61STRING, StringToVector(""###""), 0, ASN1_STRFLGS_ESC_2253, ""\\\\###""}, {V_ASN1_T61STRING, StringToVector(""###""), 0, ASN1_STRFLGS_ESC_2253 | ASN1_STRFLGS_ESC_QUOTE, ""\\""###\\""""}, // By default, strings are decoded and Unicode code points are // individually escaped. {V_ASN1_UTF8STRING, StringToVector(""a\\xc2\\x80\\xc4\\x80\\xf0\\x90\\x80\\x80""), 0, ASN1_STRFLGS_ESC_MSB, ""a\\\\80\\\\U0100\\\\W00010000""}, {V_ASN1_BMPSTRING, {0x00, 'a', 0x00, 0x80, 0x01, 0x00}, 0, ASN1_STRFLGS_ESC_MSB, ""a\\\\80\\\\U0100""}, {V_ASN1_UNIVERSALSTRING, {0x00, 0x00, 0x00, 'a', // 0x00, 0x00, 0x00, 0x80, // 0x00, 0x00, 0x01, 0x00, // 0x00, 0x01, 0x00, 0x00}, 0, ASN1_STRFLGS_ESC_MSB, ""a\\\\80\\\\U0100\\\\W00010000""}, // |ASN1_STRFLGS_UTF8_CONVERT| normalizes everything to UTF-8 and then // escapes individual bytes. {V_ASN1_IA5STRING, StringToVector(""a\\x80""), 0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, ""a\\\\C2\\\\80""}, {V_ASN1_T61STRING, StringToVector(""a\\x80""), 0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, ""a\\\\C2\\\\80""}, {V_ASN1_UTF8STRING, StringToVector(""a\\xc2\\x80\\xc4\\x80\\xf0\\x90\\x80\\x80""), 0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, ""a\\\\C2\\\\80\\\\C4\\\\80\\\\F0\\\\90\\\\80\\\\80""}, {V_ASN1_BMPSTRING, {0x00, 'a', 0x00, 0x80, 0x01, 0x00}, 0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, ""a\\\\C2\\\\80\\\\C4\\\\80""}, {V_ASN1_UNIVERSALSTRING, {0x00, 0x00, 0x00, 'a', // 0x00, 0x00, 0x00, 0x80, // 0x00, 0x00, 0x01, 0x00, // 0x00, 0x01, 0x00, 0x00}, 0, ASN1_STRFLGS_ESC_MSB | ASN1_STRFLGS_UTF8_CONVERT, ""a\\\\C2\\\\80\\\\C4\\\\80\\\\F0\\\\90\\\\80\\\\80""}, // The same as above, but without escaping the UTF-8 encoding. {V_ASN1_IA5STRING, StringToVector(""a\\x80""), 0, ASN1_STRFLGS_UTF8_CONVERT, ""a\\xc2\\x80""}, {V_ASN1_T61STRING, StringToVector(""a\\x80""), 0, ASN1_STRFLGS_UTF8_CONVERT, ""a\\xc2\\x80""}, {V_ASN1_UTF8STRING, StringToVector(""a\\xc2\\x80\\xc4\\x80\\xf0\\x90\\x80\\x80""), 0, ASN1_STRFLGS_UTF8_CONVERT, ""a\\xc2\\x80\\xc4\\x80\\xf0\\x90\\x80\\x80""}, {V_ASN1_BMPSTRING, {0x00, 'a', 0x00, 0x80, 0x01, 0x00}, 0, ASN1_STRFLGS_UTF8_CONVERT, ""a\\xc2\\x80\\xc4\\x80""}, {V_ASN1_UNIVERSALSTRING, {0x00, 0x00, 0x00, 'a', // 0x00, 0x00, 0x00, 0x80, // 0x00, 0x00, 0x01, 0x00, // 0x00, 0x01, 0x00, 0x00}, 0, ASN1_STRFLGS_UTF8_CONVERT, ""a\\xc2\\x80\\xc4\\x80\\xf0\\x90\\x80\\x80""}, // Types that cannot be decoded are, by default, treated as a byte string. {V_ASN1_OCTET_STRING, {0xff}, 0, 0, ""\\xff""}, {-1, {0xff}, 0, 0, ""\\xff""}, {100, {0xff}, 0, 0, ""\\xff""}, // |ASN1_STRFLGS_UTF8_CONVERT| still converts these bytes to UTF-8. // // TODO(davidben): This seems like a bug. Although it's unclear because // the non-RFC-2253 options aren't especially sound. Can we just remove // them? {V_ASN1_OCTET_STRING, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, ""\\xc3\\xbf""}, {-1, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, ""\\xc3\\xbf""}, {100, {0xff}, 0, ASN1_STRFLGS_UTF8_CONVERT, ""\\xc3\\xbf""}, // |ASN1_STRFLGS_IGNORE_TYPE| causes the string type to be ignored, so it // is always treated as a byte string, even if it is not a valid encoding. {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, ""\\xff""}, {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, ""\\xff""}, {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_IGNORE_TYPE, ""\\xff""}, // |ASN1_STRFLGS_SHOW_TYPE| prepends the type name. {V_ASN1_UTF8STRING, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, ""UTF8STRING:a""}, {-1, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, ""(unknown):a""}, {100, {'a'}, 0, ASN1_STRFLGS_SHOW_TYPE, ""(unknown):a""}, // |ASN1_STRFLGS_DUMP_ALL| and |ASN1_STRFLGS_DUMP_UNKNOWN| cause // non-string types to be printed in hex, though without the DER wrapper // by default. {V_ASN1_UTF8STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_UNKNOWN, ""\\\\U2603""}, {V_ASN1_UTF8STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_ALL, ""#E29883""}, {V_ASN1_OCTET_STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_UNKNOWN, ""#E29883""}, {V_ASN1_OCTET_STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_ALL, ""#E29883""}, // |ASN1_STRFLGS_DUMP_DER| includes the entire element. {V_ASN1_UTF8STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#0C03E29883""}, {V_ASN1_OCTET_STRING, StringToVector(""\\xe2\\x98\\x83""), 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#0403E29883""}, {V_ASN1_BIT_STRING, {0x80}, ASN1_STRING_FLAG_BITS_LEFT | 4, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#03020480""}, // INTEGER { 1 } {V_ASN1_INTEGER, {0x01}, 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#020101""}, // INTEGER { -1 } {V_ASN1_NEG_INTEGER, {0x01}, 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#0201FF""}, // ENUMERATED { 1 } {V_ASN1_ENUMERATED, {0x01}, 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#0A0101""}, // ENUMERATED { -1 } {V_ASN1_NEG_ENUMERATED, {0x01}, 0, ASN1_STRFLGS_DUMP_ALL | ASN1_STRFLGS_DUMP_DER, ""#0A01FF""}, }; for (const auto &t : kTests) { SCOPED_TRACE(t.type); SCOPED_TRACE(Bytes(t.data)); SCOPED_TRACE(t.str_flags); SCOPED_TRACE(t.flags); bssl::UniquePtr str(ASN1_STRING_type_new(t.type)); ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size())); str->flags = t.str_flags; // If the |BIO| is null, it should measure the size. int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags); EXPECT_EQ(len, static_cast(t.expected.size())); // Measuring the size should also work for the |FILE| version len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags); EXPECT_EQ(len, static_cast(t.expected.size())); // Actually print the string. bssl::UniquePtr bio(BIO_new(BIO_s_mem())); ASSERT_TRUE(bio); len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags); EXPECT_EQ(len, static_cast(t.expected.size())); const uint8_t *bio_contents; size_t bio_len; ASSERT_TRUE(BIO_mem_contents(bio.get(), &bio_contents, &bio_len)); EXPECT_EQ(t.expected, std::string(bio_contents, bio_contents + bio_len)); } const struct { int type; std::vector data; int str_flags; unsigned long flags; } kUnprintableTests[] = { // When decoding strings, invalid codepoints are errors. {V_ASN1_UTF8STRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB}, {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB}, {V_ASN1_BMPSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB}, {V_ASN1_UNIVERSALSTRING, {0xff}, 0, ASN1_STRFLGS_ESC_MSB}, }; for (const auto &t : kUnprintableTests) { SCOPED_TRACE(t.type); SCOPED_TRACE(Bytes(t.data)); SCOPED_TRACE(t.str_flags); SCOPED_TRACE(t.flags); bssl::UniquePtr str(ASN1_STRING_type_new(t.type)); ASSERT_TRUE(ASN1_STRING_set(str.get(), t.data.data(), t.data.size())); str->flags = t.str_flags; // If the |BIO| is null, it should measure the size. int len = ASN1_STRING_print_ex(nullptr, str.get(), t.flags); EXPECT_EQ(len, -1); ERR_clear_error(); // Measuring the size should also work for the |FILE| version len = ASN1_STRING_print_ex_fp(nullptr, str.get(), t.flags); EXPECT_EQ(len, -1); ERR_clear_error(); // Actually print the string. bssl::UniquePtr bio(BIO_new(BIO_s_mem())); ASSERT_TRUE(bio); len = ASN1_STRING_print_ex(bio.get(), str.get(), t.flags); EXPECT_EQ(len, -1); ERR_clear_error(); } } TEST(ASN1Test, MBString) { const unsigned long kAll = B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING | B_ASN1_BMPSTRING | B_ASN1_UNIVERSALSTRING | B_ASN1_UTF8STRING; const struct { int format; std::vector in; unsigned long mask; int expected_type; std::vector expected_data; int num_codepoints; } kTests[] = { // Given a choice of formats, we pick the smallest that fits. {MBSTRING_UTF8, {}, kAll, V_ASN1_PRINTABLESTRING, {}, 0}, {MBSTRING_UTF8, {'a'}, kAll, V_ASN1_PRINTABLESTRING, {'a'}, 1}, {MBSTRING_UTF8, {'a', 'A', '0', '\\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'}, kAll, V_ASN1_PRINTABLESTRING, {'a', 'A', '0', '\\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'}, 14}, {MBSTRING_UTF8, {'*'}, kAll, V_ASN1_IA5STRING, {'*'}, 1}, {MBSTRING_UTF8, {'\\n'}, kAll, V_ASN1_IA5STRING, {'\\n'}, 1}, {MBSTRING_UTF8, {0xc2, 0x80 /* U+0080 */}, kAll, V_ASN1_T61STRING, {0x80}, 1}, {MBSTRING_UTF8, {0xc4, 0x80 /* U+0100 */}, kAll, V_ASN1_BMPSTRING, {0x01, 0x00}, 1}, {MBSTRING_UTF8, {0xf0, 0x90, 0x80, 0x80 /* U+10000 */}, kAll, V_ASN1_UNIVERSALSTRING, {0x00, 0x01, 0x00, 0x00}, 1}, {MBSTRING_UTF8, {0xf0, 0x90, 0x80, 0x80 /* U+10000 */}, kAll & ~B_ASN1_UNIVERSALSTRING, V_ASN1_UTF8STRING, {0xf0, 0x90, 0x80, 0x80}, 1}, // NUL is not printable. It should also not terminate iteration. {MBSTRING_UTF8, {0}, kAll, V_ASN1_IA5STRING, {0}, 1}, {MBSTRING_UTF8, {0, 'a'}, kAll, V_ASN1_IA5STRING, {0, 'a'}, 2}, // When a particular format is specified, we use it. {MBSTRING_UTF8, {'a'}, B_ASN1_PRINTABLESTRING, V_ASN1_PRINTABLESTRING, {'a'}, 1}, {MBSTRING_UTF8, {'a'}, B_ASN1_IA5STRING, V_ASN1_IA5STRING, {'a'}, 1}, {MBSTRING_UTF8, {'a'}, B_ASN1_T61STRING, V_ASN1_T61STRING, {'a'}, 1}, {MBSTRING_UTF8, {'a'}, B_ASN1_UTF8STRING, V_ASN1_UTF8STRING, {'a'}, 1}, {MBSTRING_UTF8, {'a'}, B_ASN1_BMPSTRING, V_ASN1_BMPSTRING, {0x00, 'a'}, 1}, {MBSTRING_UTF8, {'a'}, B_ASN1_UNIVERSALSTRING, V_ASN1_UNIVERSALSTRING, {0x00, 0x00, 0x00, 'a'}, 1}, // A long string with characters of many widths, to test sizes are // measured in code points. {MBSTRING_UTF8, { 'a', // 0xc2, 0x80, // U+0080 0xc4, 0x80, // U+0100 0xf0, 0x90, 0x80, 0x80, // U+10000 }, B_ASN1_UNIVERSALSTRING, V_ASN1_UNIVERSALSTRING, { 0x00, 0x00, 0x00, 'a', // 0x00, 0x00, 0x00, 0x80, // 0x00, 0x00, 0x01, 0x00, // 0x00, 0x01, 0x00, 0x00, // }, 4}, }; for (const auto &t : kTests) { SCOPED_TRACE(t.format); SCOPED_TRACE(Bytes(t.in)); SCOPED_TRACE(t.mask); // Passing in nullptr should do a dry run. EXPECT_EQ(t.expected_type, ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(), t.format, t.mask)); // Test allocating a new object. ASN1_STRING *str = nullptr; EXPECT_EQ( t.expected_type, ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask)); ASSERT_TRUE(str); EXPECT_EQ(t.expected_type, ASN1_STRING_type(str)); EXPECT_EQ(Bytes(t.expected_data), Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str))); // Test writing into an existing object. ASN1_STRING_free(str); str = ASN1_STRING_new(); ASSERT_TRUE(str); ASN1_STRING *old_str = str; EXPECT_EQ( t.expected_type, ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask)); ASSERT_EQ(old_str, str); EXPECT_EQ(t.expected_type, ASN1_STRING_type(str)); EXPECT_EQ(Bytes(t.expected_data), Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str))); ASN1_STRING_free(str); str = nullptr; // minsize and maxsize should be enforced, even in a dry run. EXPECT_EQ(t.expected_type, ASN1_mbstring_ncopy(nullptr, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/t.num_codepoints, /*maxsize=*/t.num_codepoints)); EXPECT_EQ(t.expected_type, ASN1_mbstring_ncopy(&str, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/t.num_codepoints, /*maxsize=*/t.num_codepoints)); ASSERT_TRUE(str); EXPECT_EQ(t.expected_type, ASN1_STRING_type(str)); EXPECT_EQ(Bytes(t.expected_data), Bytes(ASN1_STRING_get0_data(str), ASN1_STRING_length(str))); ASN1_STRING_free(str); str = nullptr; EXPECT_EQ(-1, ASN1_mbstring_ncopy( nullptr, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0)); ERR_clear_error(); EXPECT_EQ(-1, ASN1_mbstring_ncopy( &str, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/t.num_codepoints + 1, /*maxsize=*/0)); EXPECT_FALSE(str); ERR_clear_error(); if (t.num_codepoints > 1) { EXPECT_EQ(-1, ASN1_mbstring_ncopy( nullptr, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1)); ERR_clear_error(); EXPECT_EQ(-1, ASN1_mbstring_ncopy( &str, t.in.data(), t.in.size(), t.format, t.mask, /*minsize=*/0, /*maxsize=*/t.num_codepoints - 1)); EXPECT_FALSE(str); ERR_clear_error(); } } const struct { int format; std::vector in; unsigned long mask; } kInvalidTests[] = { // Invalid encodings are rejected. {MBSTRING_UTF8, {0xff}, B_ASN1_UTF8STRING}, {MBSTRING_BMP, {0xff}, B_ASN1_UTF8STRING}, {MBSTRING_UNIV, {0xff}, B_ASN1_UTF8STRING}, // Lone surrogates are not code points. {MBSTRING_UTF8, {0xed, 0xa0, 0x80}, B_ASN1_UTF8STRING}, {MBSTRING_BMP, {0xd8, 0x00}, B_ASN1_UTF8STRING}, {MBSTRING_UNIV, {0x00, 0x00, 0xd8, 0x00}, B_ASN1_UTF8STRING}, // The input does not fit in the allowed output types. {MBSTRING_UTF8, {'\\n'}, B_ASN1_PRINTABLESTRING}, {MBSTRING_UTF8, {0xc2, 0x80 /* U+0080 */}, B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING}, {MBSTRING_UTF8, {0xc4, 0x80 /* U+0100 */}, B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING}, {MBSTRING_UTF8, {0xf0, 0x90, 0x80, 0x80 /* U+10000 */}, B_ASN1_PRINTABLESTRING | B_ASN1_IA5STRING | B_ASN1_T61STRING | B_ASN1_BMPSTRING}, // Unrecognized bits are ignored. {MBSTRING_UTF8, {'\\n'}, B_ASN1_PRINTABLESTRING | B_ASN1_SEQUENCE}, }; for (const auto &t : kInvalidTests) { SCOPED_TRACE(t.format); SCOPED_TRACE(Bytes(t.in)); SCOPED_TRACE(t.mask); EXPECT_EQ(-1, ASN1_mbstring_copy(nullptr, t.in.data(), t.in.size(), t.format, t.mask)); ERR_clear_error(); ASN1_STRING *str = nullptr; EXPECT_EQ(-1, ASN1_mbstring_copy(&str, t.in.data(), t.in.size(), t.format, t.mask)); ERR_clear_error(); EXPECT_EQ(nullptr, str); } } // Test that multi-string types correctly encode negative ENUMERATED. // Multi-string types cannot contain INTEGER, so we only test ENUMERATED. TEST(ASN1Test, NegativeEnumeratedMultistring) { static const uint8_t kMinusOne[] = {0x0a, 0x01, 0xff}; // ENUMERATED { -1 } // |ASN1_PRINTABLE| is a multi-string type that allows ENUMERATED. const uint8_t *p = kMinusOne; bssl::UniquePtr str( d2i_ASN1_PRINTABLE(nullptr, &p, sizeof(kMinusOne))); ASSERT_TRUE(str); TestSerialize(str.get(), i2d_ASN1_PRINTABLE, kMinusOne); } TEST(ASN1Test, PrintableType) { const struct { std::vector in; int result; } kTests[] = { {{}, V_ASN1_PRINTABLESTRING}, {{'a', 'A', '0', '\\'', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'}, V_ASN1_PRINTABLESTRING}, {{'*'}, V_ASN1_IA5STRING}, {{'\\0'}, V_ASN1_IA5STRING}, {{'\\0', 'a'}, V_ASN1_IA5STRING}, {{0, 1, 2, 3, 125, 126, 127}, V_ASN1_IA5STRING}, {{0, 1, 2, 3, 125, 126, 127, 128}, V_ASN1_T61STRING}, {{128, 0, 1, 2, 3, 125, 126, 127}, V_ASN1_T61STRING}, }; for (const auto &t : kTests) { SCOPED_TRACE(Bytes(t.in)); EXPECT_EQ(t.result, ASN1_PRINTABLE_type(t.in.data(), t.in.size())); } } // Encoding a CHOICE type with an invalid selector should fail. TEST(ASN1Test, InvalidChoice) { bssl::UniquePtr name(GENERAL_NAME_new()); ASSERT_TRUE(name); // CHOICE types are initialized with an invalid selector. EXPECT_EQ(-1, name->type); // |name| should fail to encode. EXPECT_EQ(-1, i2d_GENERAL_NAME(name.get(), nullptr)); // The error should be propagated through types containing |name|. bssl::UniquePtr names(GENERAL_NAMES_new()); ASSERT_TRUE(names); EXPECT_TRUE(bssl::PushToStack(names.get(), std::move(name))); EXPECT_EQ(-1, i2d_GENERAL_NAMES(names.get(), nullptr)); } // Encoding NID-only |ASN1_OBJECT|s should fail. TEST(ASN1Test, InvalidObject) { EXPECT_EQ(-1, i2d_ASN1_OBJECT(OBJ_nid2obj(NID_kx_ecdhe), nullptr)); bssl::UniquePtr alg(X509_ALGOR_new()); ASSERT_TRUE(alg); ASSERT_TRUE(X509_ALGOR_set0(alg.get(), OBJ_nid2obj(NID_kx_ecdhe), V_ASN1_UNDEF, nullptr)); EXPECT_EQ(-1, i2d_X509_ALGOR(alg.get(), nullptr)); } // Encoding invalid |ASN1_TYPE|s should fail. |ASN1_TYPE|s are // default-initialized to an invalid type. TEST(ASN1Test, InvalidASN1Type) { bssl::UniquePtr obj(ASN1_TYPE_new()); ASSERT_TRUE(obj); EXPECT_EQ(-1, obj->type); EXPECT_EQ(-1, i2d_ASN1_TYPE(obj.get(), nullptr)); } // Encoding invalid MSTRING types should fail. An MSTRING is a CHOICE of // string-like types. They are initialized to an invalid type. TEST(ASN1Test, InvalidMSTRING) { bssl::UniquePtr obj(ASN1_TIME_new()); ASSERT_TRUE(obj); EXPECT_EQ(-1, obj->type); EXPECT_EQ(-1, i2d_ASN1_TIME(obj.get(), nullptr)); obj.reset(DIRECTORYSTRING_new()); ASSERT_TRUE(obj); EXPECT_EQ(-1, obj->type); EXPECT_EQ(-1, i2d_DIRECTORYSTRING(obj.get(), nullptr)); } // The ASN.1 macros do not work on Windows shared library builds, where usage of // |OPENSSL_EXPORT| is a bit stricter. #if !defined(OPENSSL_WINDOWS) || !defined(BORINGSSL_SHARED_LIBRARY) typedef struct asn1_linked_list_st { struct asn1_linked_list_st *next; } ASN1_LINKED_LIST; DECLARE_ASN1_ITEM(ASN1_LINKED_LIST) DECLARE_ASN1_FUNCTIONS(ASN1_LINKED_LIST) ASN1_SEQUENCE(ASN1_LINKED_LIST) = { ASN1_OPT(ASN1_LINKED_LIST, next, ASN1_LINKED_LIST), } ASN1_SEQUENCE_END(ASN1_LINKED_LIST) IMPLEMENT_ASN1_FUNCTIONS(ASN1_LINKED_LIST) static bool MakeLinkedList(bssl::UniquePtr *out, size_t *out_len, size_t count) { bssl::ScopedCBB cbb; std::vector cbbs(count); if (!CBB_init(cbb.get(), 2 * count) || !CBB_add_asn1(cbb.get(), &cbbs[0], CBS_ASN1_SEQUENCE)) { return false; } for (size_t i = 1; i < count; i++) { if (!CBB_add_asn1(&cbbs[i - 1], &cbbs[i], CBS_ASN1_SEQUENCE)) { return false; } } uint8_t *ptr; if (!CBB_finish(cbb.get(), &ptr, out_len)) { return false; } out->reset(ptr); return true; } TEST(ASN1Test, Recursive) { bssl::UniquePtr data; size_t len; // Sanity-check that MakeLinkedList can be parsed. ASSERT_TRUE(MakeLinkedList(&data, &len, 5)); const uint8_t *ptr = data.get(); ASN1_LINKED_LIST *list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len); EXPECT_TRUE(list); ASN1_LINKED_LIST_free(list); // Excessively deep structures are rejected. ASSERT_TRUE(MakeLinkedList(&data, &len, 100)); ptr = data.get(); list = d2i_ASN1_LINKED_LIST(nullptr, &ptr, len); EXPECT_FALSE(list); // Note checking the error queue here does not work. The error ""stack trace"" // is too deep, so the |ASN1_R_NESTED_TOO_DEEP| entry drops off the queue. ASN1_LINKED_LIST_free(list); } struct IMPLICIT_CHOICE { ASN1_STRING *string; }; DECLARE_ASN1_FUNCTIONS(IMPLICIT_CHOICE) ASN1_SEQUENCE(IMPLICIT_CHOICE) = { ASN1_IMP(IMPLICIT_CHOICE, string, DIRECTORYSTRING, 0), } ASN1_SEQUENCE_END(IMPLICIT_CHOICE) IMPLEMENT_ASN1_FUNCTIONS(IMPLICIT_CHOICE) // Test that the ASN.1 templates reject types with implicitly-tagged CHOICE // types. TEST(ASN1Test, ImplicitChoice) { // Serializing a type with an implicitly tagged CHOICE should fail. std::unique_ptr obj( IMPLICIT_CHOICE_new(), IMPLICIT_CHOICE_free); EXPECT_EQ(-1, i2d_IMPLICIT_CHOICE(obj.get(), nullptr)); // An implicitly-tagged CHOICE is an error. Depending on the implementation, // it may be misinterpreted as without the tag, or as clobbering the CHOICE // tag. Test both inputs and ensure they fail. // SEQUENCE { UTF8String {} } static const uint8_t kInput1[] = {0x30, 0x02, 0x0c, 0x00}; const uint8_t *ptr = kInput1; EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput1))); // SEQUENCE { [0 PRIMITIVE] {} } static const uint8_t kInput2[] = {0x30, 0x02, 0x80, 0x00}; ptr = kInput2; EXPECT_EQ(nullptr, d2i_IMPLICIT_CHOICE(nullptr, &ptr, sizeof(kInput2))); } struct REQUIRED_FIELD { ASN1_INTEGER *value; ASN1_INTEGER *value_imp; ASN1_INTEGER *value_exp; STACK_OF(ASN1_INTEGER) *seq; STACK_OF(ASN1_INTEGER) *seq_imp; STACK_OF(ASN1_INTEGER) *seq_exp; }; DECLARE_ASN1_FUNCTIONS(REQUIRED_FIELD) ASN1_SEQUENCE(REQUIRED_FIELD) = { ASN1_SIMPLE(REQUIRED_FIELD, value, ASN1_INTEGER), ASN1_IMP(REQUIRED_FIELD, value_imp, ASN1_INTEGER, 0), ASN1_EXP(REQUIRED_FIELD, value_exp, ASN1_INTEGER, 1), ASN1_SEQUENCE_OF(REQUIRED_FIELD, seq, ASN1_INTEGER), ASN1_IMP_SEQUENCE_OF(REQUIRED_FIELD, seq_imp, ASN1_INTEGER, 2), ASN1_EXP_SEQUENCE_OF(REQUIRED_FIELD, seq_exp, ASN1_INTEGER, 3), } ASN1_SEQUENCE_END(REQUIRED_FIELD) IMPLEMENT_ASN1_FUNCTIONS(REQUIRED_FIELD) // Test that structures with missing required fields cannot be serialized. Test // the full combination of tagging and SEQUENCE OF. TEST(ASN1Test, MissingRequiredField) { EXPECT_EQ(-1, i2d_REQUIRED_FIELD(nullptr, nullptr)); std::unique_ptr obj( nullptr, REQUIRED_FIELD_free); for (auto field : {&REQUIRED_FIELD::value, &REQUIRED_FIELD::value_imp, &REQUIRED_FIELD::value_exp}) { obj.reset(REQUIRED_FIELD_new()); ASSERT_TRUE(obj); ASN1_INTEGER_free((*obj).*field); (*obj).*field = nullptr; EXPECT_EQ(-1, i2d_REQUIRED_FIELD(obj.get(), nullptr)); } for (auto field : {&REQUIRED_FIELD::seq, &REQUIRED_FIELD::seq_imp, &REQUIRED_FIELD::seq_exp}) { obj.reset(REQUIRED_FIELD_new()); ASSERT_TRUE(obj); sk_ASN1_INTEGER_pop_free((*obj).*field, ASN1_INTEGER_free); (*obj).*field = nullptr; EXPECT_EQ(-1, i2d_REQUIRED_FIELD(obj.get(), nullptr)); } } #endif // !WINDOWS || !SHARED_LIBRARY ",16201,True,2877.6962783696918,median "[[email-ext-plugin-changelog]] = email-ext-plugin Changelog :toc: == 2.72 and later * Changelog moved to https://github.com/jenkinsci/email-ext-plugin/releases[GitHub Releases]. == 2.71 (July 24, 2020) * Added BuilderUserRecipientProvider (thanks srasmussen) * https://issues.jenkins-ci.org/browse/JENKINS-61379[Fix issue with pre-send script timing] (thanks srasmussen) * Added filtering for testSuiteName (thanks https://github.com/DivyeshChandra[DivyeshChandra]) * Users with Jenkins.MANAGE permission have access to manage settings (thanks https://github.com/escoem[escoem]) * Added yaml output for test failure information (thanks https://github.com/DivyeshChandra[DivyeshChandra]) == 2.69 (February 26, 2020) * Added `escapeHtml` flag to FAILED_TESTS macro (thanks Lukasz Kostrzewa) * https://issues.jenkins-ci.org/browse/JENKINS-60911[Fix issue with config-file-provider not loading folder level files] (thanks https://github.com/gcernier-amadeus[gcernier-amadeus]) == 2.67 (October 2, 2019) * https://issues.jenkins-ci.org/browse/JENKINS-55128[Fix issue with CC parsing] * Support `saveOutput` parameter in pipeline (thanks https://github.com/v1v[v1v]) * https://issues.jenkins-ci.org/browse/JENKINS-54997[Fix deprecated calls to getLogFile] * Upgrade dependency on jsoup for XXS in older versions (thanks https://github.com/madchap[madchap] * Several code clean up improvements (thanks https://github.com/darxriggs[darxriggs] * https://issues.jenkins-ci.org/browse/JENKINS-54363[Fix issue with invalid mail account handling] == 2.66 (March 21, 2019) * Fix some usages of ""email"" to ""e-mail"" to be consistent (thanks https://github.com/VirtualTim[VirtualTim]) * Update plugin to build and test with JDK11 (thanks https://github.com/batmat[batmat]) == 2.65 (March 6, 2019) * https://jenkins.io/security/advisory/2019-03-06/#SECURITY-1340[Fix] https://jenkins.io/security/advisory/2019-03-06/#SECURITY-1340[security issue] == 2.63 (August 5, 2018) * allow filtering email domains we send emails to (https://github.com/jenkinsci/email-ext-plugin/pull/167[pull 167]) * Help markup (https://github.com/jenkinsci/email-ext-plugin/pull/169[pull 169]) * Same recipient in CC or BCC removes it from TO https://issues.jenkins-ci.org/browse/JENKINS-52748[JENKINS-52748] - Getting issue details... STATUS == 2.62 (March 23, 2018) * Styling changes + change in test results table + code alignment (https://github.com/jenkinsci/email-ext-plugin/pull/162[pull 162]) * Fix link for RFC-2919 in help (https://github.com/jenkinsci/email-ext-plugin/pull/164[pull 164]) * Update some libraries for some feature additions. (https://github.com/jenkinsci/email-ext-plugin/pull/165[pull 165]) * The email-ext-plugin Pipeline integration is not very ergonomic https://issues.jenkins-ci.org/browse/JENKINS-49733[JENKINS-49733] - Getting issue details... STATUS * Check for attachment size does not consider compression https://issues.jenkins-ci.org/browse/JENKINS-49913[JENKINS-49913] - Getting issue details... STATUS * Add additional accounts (https://github.com/jenkinsci/email-ext-plugin/pull/166[pull 166]) == 2.61 (October 27, 2017) * Add global checkbox to allow sending emails to unregistered users (https://github.com/jenkinsci/email-ext-plugin/pull/161[pull 161]) * Switch to using RunWithSCM for getCulprits logic https://issues.jenkins-ci.org/browse/JENKINS-24141[JENKINS-24141] - Getting issue details... STATUS == 2.60 (September 19, 2017) * groovy-text.template: use of member changeSet instead of changeSets (https://issues.jenkins-ci.org/browse/JENKINS-38968[JENKINS-38968]) == 2.59 (September 12, 2017) * NullPointerException when calling addRecipients (https://issues.jenkins-ci.org/browse/JENKINS-45529[JENKINS-45529]) * groovy-html.template: use of member changeSet instead of changeSets (https://issues.jenkins-ci.org/browse/JENKINS-38968[JENKINS-38968]) == 2.58 (Jun 29, 2017) * Make message clearer added in SECURITY-372 * Add presend and postsend script support in pipeline (https://github.com/jenkinsci/email-ext-plugin/pull/157[#157]) * allRecipients could be null if presend script remove all of them (https://github.com/jenkinsci/email-ext-plugin/pull/156[#156]) == 2.57.2 (April 10, 2017) * SECURITY-257(https://jenkins.io/security/advisory/2017-04-10/[advisory]) Run Groovy and Jelly scripts only if approved or in secure sandbox Jenkins administrators may need to approve scripts used by this plugin. Administrators can either proactively review all job configurations for Groovy scripts or they can wait for the jobs to run and fail. Approval is performed via the https://plugins.jenkins.io/script-security/[Script Security Plugin]. == 2.57.1 (March 20, 2017) * SECURITY-372 (https://jenkins.io/security/advisory/2017-03-20/[advisory]) Emails were sent to addresses not associated with actual users of Jenkins. If the security fix is undesirable in a particular instance, it can be disabled with either or both of the following two system properties: * `-Dhudson.tasks.MailSender.SEND_TO_UNKNOWN_USERS=true`: send mail to build culprits even if they do not seem to be associated with a valid Jenkins login. * `-Dhudson.tasks.MailSender.SEND_TO_USERS_WITHOUT_READ=true`: send mail to build culprits associated with a valid Jenkins login even if they would not otherwise have read access to the job. == 2.57 (February 18, 2017) * Allow using 'emailext' step in pipeline without 'node'/workspace context (https://issues.jenkins-ci.org/browse/JENKINS-42140[JENKINS-42140]) == 2.56 (February 14, 2017) * Take 2 on previous == 2.55 (February 11, 2017) * Bring back functions removed in JENKINS-40964 that are required for upgrade of existing config == 2.54 (January 22, 2017) * update to latest config-file-provider (https://issues.jenkins-ci.org/browse/JENKINS-40964[JENKINS-40964]) == 2.53 (December 23, 2016) * CulpritsRecipientProvider does not work with pipeline (https://issues.jenkins-ci.org/browse/JENKINS-40653[JENKINS-40653]) == 2.52 (October 23, 2016) * enable setter for smtpHost in descriptor (PR-142) * Fix getter value in UI (https://issues.jenkins-ci.org/browse/JENKINS-37995[JENKINS-37995]) * Add API to programmatically configure global settings (https://issues.jenkins-ci.org/browse/JENKINS-39147[JENKINS-39147]) == 2.51 (September 28, 2016) * Pipeline Support - Failed Tests (https://issues.jenkins-ci.org/browse/JENKINS-38519[JENKINS-38519]) == 2.50 (September 24, 2016) * Template support in pipelines (https://issues.jenkins-ci.org/browse/JENKINS-35367[JENKINS-35367]) * X failure trigger (https://issues.jenkins-ci.org/browse/JENKINS-37995[JENKINS-37995]) * Don't use random for filename in Save to Workspace option (https://issues.jenkins-ci.org/browse/JENKINS-37350[JENKINS-37350]) == 2.48 & 2.49 Failed releases == 2.47 (August 7, 2016) * 2nd failure emails being sent even when build is successful with job-dsl-plugin (https://issues.jenkins-ci.org/browse/JENKINS-37188[JENKINS-37188]) == 2.46 (August 4, 2016) * emailext Pipeline step sends mails to irrelevant people (https://issues.jenkins-ci.org/browse/JENKINS-37163[JENKINS-37163]) == 2.45 (July 31, 2016) * Non breaking spaces being double escaped - Thanks https://issues.jenkins-ci.org/secure/ViewProfile.jspa?name=pgmillon[Pierre-Gildas MILLON] (https://issues.jenkins-ci.org/browse/JENKINS-35669[JENKINS-35669]) * NPE in email-ext FailingTestSuspectsRecipientProvider (https://issues.jenkins-ci.org/browse/JENKINS-36402[JENKINS-36402]) * Fix of findbugs reported issues * Upgrade to plugin pom 2.7 == 2.44 (June 13, 2016) * Extended Pipeline support (https://issues.jenkins-ci.org/browse/JENKINS-35365[JENKINS-35365]) == 2.43 (June 4, 2016) * Fixed Content Token Reference throwing error if Config File Provider plugin is not installed (https://issues.jenkins-ci.org/browse/JENKINS-35289[issue 35289]) * Fixed NPE when watching a job (https://issues.jenkins-ci.org/browse/JENKINS-33717[Issue 33717]) * Merged pull request https://github.com/jenkinsci/email-ext-plugin/pull/130[130] * Merged pull request https://github.com/jenkinsci/email-ext-plugin/pull/133[133] Fix for https://issues.jenkins-ci.org/browse/JENKINS-34785[issue 34785] * Added ability to use a template from the workspace. == 2.42 (April 17, 2016) * Fixed issue with post-send script not saving (https://issues.jenkins-ci.org/browse/JENKINS-33205[issue 33205] thanks to https://github.com/weisslj[weisslj]) * Fixed issue with non-English characters in file names for attachments (https://issues.jenkins-ci.org/browse/JENKINS-33574[issue 33574]) * Fixed NPE issue when using groovy script (https://issues.jenkins-ci.org/browse/JENKINS-33690[issue 33690]) * Added a license file * Moved to new parent pom version * Fixed up some tests == 2.41.3 (Feb 23, 2016) * Fixed issue when workflow is not installed (https://issues.jenkins-ci.org/browse/JENKINS-33035[issue 33035]) == 2.41.2 (Feb 18, 2016) * Fixed issue with wrong class loader for templates (https://issues.jenkins-ci.org/browse/JENKINS-32910[issue 32910]) * Allow semicolon for address separator (https://issues.jenkins-ci.org/browse/JENKINS-32889[issue 32889]) == 2.41 (Feb 07, 2016) * Cleaned up dependencies * Removed several tokens that were moved to token-macro * Fixed several items flagged by PMD (thanks Mohammed Ezzat**)** * Added post-send script feature similar to pre-send script. (Thanks https://github.com/weisslj[weisslj]) * Fixed issue with non-AbstractProject/Build items (https://issues.jenkins-ci.org/browse/JENKINS-29970[issue 29970]https://issues.jenkins-ci.org/browse/JENKINS-29970) * Fixed watching so it doesn't show recipient fields (issue 29449) == 2.40.5 (Jun 08, 2015) * Whitespace and import cleanup * DefaultTriggers refactoring == 2.40.4 (May 24, 2015) * Fix issue where the wrong config provider would be cached if using multiple types of managed templates. == 2.40.3 (May 20, 2015) * Fix issue with incorrect handling of cc and bcc recipients (https://issues.jenkins-ci.org/browse/JENKINS-28444[issue #28444]) * Fix issue with readResolve including Mailer components (https://issues.jenkins-ci.org/browse/JENKINS-28402[issue #28402]) * Fix issue where default extension was not added to template name if there was something that looked like an extension in the name (https://issues.jenkins-ci.org/browse/JENKINS-28357[issue #28357]) == 2.40.2 (May 13, 2015) * Set the debug mode for JavaMail correctly when debug mode is enabled in global configuration * Fixed issue where the deserialization was not working correctly for descriptors (https://issues.jenkins-ci.org/browse/JENKINS-28212[issue #28212]) == 2.40.1 (May 4, 2015) * Fixed issue with classpath entries that have environment variables (https://issues.jenkins-ci.org/browse/JENKINS-28145[issue #28145]) * Fixed issue with check of the extension for templates on the file system (https://issues.jenkins-ci.org/browse/JENKINS-28202[issue #28202]) == 2.40 (April 28, 2015) * Thanks to https://github.com/krwalker[K.R. Walker], https://github.com/CedricLevasseur[Cédric Levasseur] * Fixed issue with pre-send scripts not using 'cancel' correctly (https://issues.jenkins-ci.org/browse/JENKINS-27448[issue #27448]) * Added ability to send email in HTML and plaintext with plaintext being a stripped version of the HTML (https://issues.jenkins-ci.org/browse/JENKINS-23126[issue #23126]) * Added ability to configure the set of triggers that is setup by default when adding email-ext to a project (https://issues.jenkins-ci.org/browse/JENKINS-27856[issue #27856]) * Moved away from using the Mailer plugin to create a session. * Added new TEMPLATE token that can be used to pull normal content from a file (https://issues.jenkins-ci.org/browse/JENKINS-26478[issue #26478]) * Allow use of content tokens in the pre-send script (https://issues.jenkins-ci.org/browse/JENKINS-26286[issue #26286]) * Allow sending console logs for all nodes in matrix build (https://issues.jenkins-ci.org/browse/JENKINS-21861[issue #21861]) * Added ability for users to watch jobs (https://issues.jenkins-ci.org/browse/JENKINS-18567[issue #18567]) * Removed admin email address since it should be set in the Jenkins Location area (https://issues.jenkins-ci.org/browse/JENKINS-25926[issue #25926]) * Fixed output from CSSInliner that was escaping entities (https://issues.jenkins-ci.org/browse/JENKINS-25719[issue #25719]) * Added FirstFailingBuildSuspectsRecipientProvider == 2.39.2 (January 30, 2015) * Thanks to https://github.com/Everspace[Everspace] * Add workaround for https://issues.jenkins-ci.org/browse/JENKINS-25940[JENKINS-25940] * Added new SCRIPT_CONTENT macro that can be used with pre-send scripts. * Added uberClassLoader to JellyContext == 2.39 (November 16, 2014) * Thanks to https://github.com/christiangalsterer[Christian Galsterer], https://github.com/alexouzounis[Alex Ouzounis], https://github.com/gssiyankai[Gregory SSI-YAN-KAI], https://github.com/jglick[Jesse Glick], https://github.com/jeffmaury[Jeff Maury], https://github.com/robin-knight[robin-knight], https://github.com/krwalker[K.R. Walker] * Updated to 1.554.1 as parent pom version * Added a recipient provider for upstream committers (https://issues.jenkins-ci.org/browse/JENKINS-17742[issue #17742]) * Fixed issue with template testing not supporting managed files (https://issues.jenkins-ci.org/browse/JENKINS-23619[issue #23619]) * Fixed typo in help file for CHANGES_SINCE_LAST_BUILD * Added support of regex to replace/change the messages in CHANGES token (https://issues.jenkins-ci.org/browse/JENKINS-23691[issue #23691]) * Fixed issue that attached build log is not complete (https://issues.jenkins-ci.org/browse/JENKINS-23660[issue #23660]) * Added disable at the project level (https://issues.jenkins-ci.org/browse/JENKINS-22154[issue #22154]) * Added caching of the templates to improve performance * Added parameter to CHANGES tokens to allow user to show a specific message when there are no changes (https://issues.jenkins-ci.org/browse/JENKINS-20324[issue #20324]) * Added classpath support for the pre-send script (https://issues.jenkins-ci.org/browse/JENKINS-21672[issue #21672]) * Added SMTP timeout so that jobs won't hang indefinitely * Added retry for ConnectionExceptions (https://issues.jenkins-ci.org/browse/JENKINS-16181[issue #16181]) * Added console output for template testing (https://issues.jenkins-ci.org/browse/JENKINS-24063[issue #24063]) * Added check for test failure age in regression trigger (https://issues.jenkins-ci.org/browse/JENKINS-22041[issue #22041]) * Added FailingTestSuspectsRecipientProvider == 2.38.2 (August 26, 2014) * Switch to using getAction instead of getTestResultAction to work with newer versions of core. == 2.38.1 (June 2, 2014) * Fix for NPE when no recipient providers are selected in a trigger. == 2.38 (May 24, 2014) * Implemented new extension point for recipient providers (RecipientProvider) this changes the way that recipient types are added ** There are no longer checkboxes for ""Requestor"" ""Recipients"" etc, each is provided by an implementation of a RecipientProvider * Fixed log zipping to remove annotations (https://issues.jenkins-ci.org/browse/JENKINS-21180[issue #21180]) * Added help information for TRIGGER_NAME token (https://issues.jenkins-ci.org/browse/JENKINS-21912[issue #21912]) * Added support for managed files using the Config File Provider plugin, prefix managed file name with ""managed:"" * Removed dependency on the Maven plugin * Added more help and updated help messages to be more clear (https://issues.jenkins-ci.org/browse/JENKINS-20384[issue #20384]) * Added bcc support (https://issues.jenkins-ci.org/browse/JENKINS-21730[issue #21730]) * Added showMessage parameter to FAILED_TESTS to allow turning off error messages * Cleaned up template to remove duplicate sections (https://issues.jenkins-ci.org/browse/JENKINS-22592[issue #22592]) * Added %a and %d for pathFormat parameter of the CHANGES_SINCE* tokens (https://issues.jenkins-ci.org/browse/JENKINS-20692[issue #20692]) == 2.37.2.2 (March 8, 2014) * Added caching to the private macros to reduce time (https://issues.jenkins-ci.org/browse/JENKINS-20078[issue #20078]) == 2.37.2 (January 26, 2014) * Marked the Config subclass Extensions as optional, so the plugin doesn't cause issues if the Config File Provider plugin is not installed. (https://issues.jenkins-ci.org/browse/JENKINS-21326[issue #21326]) == 2.37.1 (January 11, 2014) * Fix issue with missing dependency on maven-plugin in pom.xml == 2.37 (January 8, 2014) * Updated parent pom version to 1.532.1 LTS * Allow use of managed scripts for Jelly or Groovy content. Use prefix ""managed:"" before name of managed script (https://issues.jenkins-ci.org/browse/JENKINS-18203[issue #18203]) * Added new ""Status Changed"" trigger (thanks francois_ritaly) * Added fileNotFoundMessage to FILE token (https://issues.jenkins-ci.org/browse/JENKINS-20325[issue #20325]) * Added inline help for triggers that was missing (https://issues.jenkins-ci.org/browse/JENKINS-20170[issue #20170]) * Changed BuildStepMonitor.NONE to allow concurrent builds (thanks jglick) (https://issues.jenkins-ci.org/browse/JENKINS-16376[issue #16376])** You must take care when using content or triggers that look at previous builds if you enable concurrent builds for your project * Added TRIGGER_NAME token so users can determine what trigger caused the email (https://issues.jenkins-ci.org/browse/JENKINS-20265[issue #20265]) * Changed to Mutlimap so that you can add multiple triggers of the same type and have them work correctly (https://issues.jenkins-ci.org/browse/JENKINS-20524[issue #20524]) * Fixed issue where pre-send script would get expanded and remain expanded (https://issues.jenkins-ci.org/browse/JENKINS-20770[issue #20770]) * Added First Unstable trigger * Added helper script for emailing Jive community (thanks Dan Barker) == 2.36 (October 26, 2013) * Fixed issue with mismatch between form field name and what was parsed in the backend (https://issues.jenkins-ci.org/browse/JENKINS-20133[issue #20133]) * Fixed issue with NPE on 1.535 (thanks to https://github.com/agudian[agudian] for the PR) * Added ability to customize the date format for the CHANGES_SINCE tokens (https://issues.jenkins-ci.org/browse/JENKINS-20151[issue #20151]) * Added help files for all the built-in triggers (https://issues.jenkins-ci.org/browse/JENKINS-20170[issue #20170]) * By default when you add the email-ext publisher, an Always trigger will be added (https://issues.jenkins-ci.org/browse/JENKINS-20013[issue #20013]) * Fixed issue with template project plugin based jobs and Jelly script content. (https://issues.jenkins-ci.org/browse/JENKINS-20117[issue #20117]) * If user doesn't have a Mailer.UserProperty, just add the user id and see if the system can resolve it (https://issues.jenkins-ci.org/browse/JENKINS-20215[issue #20215]) * Fixed issue with newInstance method for EmailTrigger causing an exception on 1.536 (https://issues.jenkins-ci.org/browse/JENKINS-20198[issue #20198]) == 2.35.1 (October 14, 2013) * Fixed issue introduced by new parameter parsing in global config (https://issues.jenkins-ci.org/browse/JENKINS-20030[issue #20030]) * Update descriptor usage in triggers * Fixed command line to not max out PermGen during testing == 2.35 (October 12, 2013) * Refactored descriptor to follow recommended method * Added tests for global config default values * Updated to latest LTS for parent version * Updated exclusion list to be for full email list, not just committers * Fixed issue with email-ext not restoring values for some fields if no triggers were configured (https://issues.jenkins-ci.org/browse/JENKINS-15442[issue #15442]) * Fixed issue where the project could be null (https://issues.jenkins-ci.org/browse/JENKINS-14338[issue #14338]) == 2.34 (September 15, 2013) * Started adding HtmlUnit tests for UI interaction and round trip testing * Added more debug for excluded committers feature * Reverted field name to includeCulprits * Fixed issue where PROJECT_DEFAULT_RECIPIENTS was being added to triggers (https://issues.jenkins-ci.org/browse/JENKINS-19583[issue #19583]) * Fixed issue that stopped users from being able to add triggers (https://issues.jenkins-ci.org/browse/JENKINS-19585[issue #19585]) == 2.33 (September 12, 2013) * Fixed issue with triggers for matrix projects not saving the value correctly (https://issues.jenkins-ci.org/browse/JENKINS-19291[issue #19291]) * Added ability to set content type at the trigger level * Added back send to culprits * Fixed missing dependency for Mailer plugin in pom.xml * Added setting debug mode for JavaMail when debug mode for email-ext is set == 2.32 (August 13, 2013) * Fix issue with matrix project (https://issues.jenkins-ci.org/browse/JENKINS-19190[issue #19190]) * Added ""Fixed Unhealthy"" trigger == 2.31 (August 12, 2013) * Changed way that triggers work so that you can add multiple triggers of the same type * Changed triggers into extension points so that other plugins can provide email triggers * Migrated all tokens to use the Token Macro plugin * Fixed issue with using template testing with Jelly scripts (https://issues.jenkins-ci.org/browse/JENKINS-18157[issue #18157]) * General clean-up of sources to remove unused imports and so forth * Added JUnit report into groovy html template (thanks https://github.com/praagii[praagii]) * Fixed issue with wrong StringUtils being imported thanks to NetBeans (https://issues.jenkins-ci.org/browse/JENKINS-19089[issue #19089]) == 2.30.2 (May 23, 2013) * Fix issue with escaping tokens by using a more groovy like method (double dollar $$) (https://issues.jenkins-ci.org/browse/JENKINS-18014[issue #18014]) * Fix issue with metaClass for Script (thanks to Geoff Cummings for patch) (https://issues.jenkins-ci.org/browse/JENKINS-17910[issue #17910]) * Added ability to test Groovy and Jelly templates via a link on the project page. (https://issues.jenkins-ci.org/browse/JENKINS-9594[issue #9594]) == 2.29 (May 6, 2013) * Refixed typo in email template. * Updated to latest LTS release for base (1.509.1) * Added global user exclusion list (https://issues.jenkins-ci.org/browse/JENKINS-17503[issue #17503]) * Added expansion of environment variable in the FILE token's path argument (https://issues.jenkins-ci.org/browse/JENKINS-16716[issue #16716]) * Added trigger and triggered variables to pre-send script object model (https://issues.jenkins-ci.org/browse/JENKINS-17577[issue #17577]) * Added DEFAULT_PRESEND_SCRIPT token (https://issues.jenkins-ci.org/browse/JENKINS-14508[issue #14508]) * Added option to save the output of the generated email into the workspace (https://issues.jenkins-ci.org/browse/JENKINS-13302[issue #13302]) * Added new trigger for broken \\-> compiling state (https://issues.jenkins-ci.org/browse/JENKINS-17546[17546]) * Fixed default value for ReplyTo (https://issues.jenkins-ci.org/browse/JENKINS-17733[issue #17733]) * Turned off pretty-printing for the CssInliner (https://issues.jenkins-ci.org/browse/JENKINS-17759[issue #17759]) == 2.28 (April 4, 2013) * Fixed token macro help in projects * Added additional Chinese translations * Improved help text for `BUILD_LOG_EXCERPT` token * Added support for inlining CSS and images into emails * Fixed regression in attaching build log (https://issues.jenkins-ci.org/browse/JENKINS-17296[issue #17296]) * Fixed regression in 1st Failure Trigger (https://issues.jenkins-ci.org/browse/JENKINS-17307[issue #17307]) * Updated docs for Improvement trigger (https://issues.jenkins-ci.org/browse/JENKINS-17074[issue #17074]) * Fixed class loading inside Groovy templates (https://issues.jenkins-ci.org/browse/JENKINS-16990[issue #16990])) * Removed script that created and used template usage * Cleaned up unused files == 2.27.1 (March 5, 2013) * Fix issue with matrix configurations (https://issues.jenkins-ci.org/browse/JENKINS-17064[issue #17064]) * Add 1st Failure and 2nd Failure Triggers == 2.27 (March 2, 2013) * Re-added ability to use tokens in attachment areas * Allow a default string if regex match is not found for BUILD_LOG_REGEX (https://issues.jenkins-ci.org/browse/JENKINS-16269[issue #16269]) * Fixed message layout if attachments are present (https://issues.jenkins-ci.org/browse/JENKINS-16281[issue #16281]) * Added info to the help on using the CC: mechanism * Fixed an issue with regression triggers (https://issues.jenkins-ci.org/browse/JENKINS-16404[issue #16404]) * Added a single retry if a SocketException occurs, in case the network issue was temporary (https://issues.jenkins-ci.org/browse/JENKINS-16181[issue #16181]) * Fixed attaching build log from a trigger. * Made default send to lists less verbose for certain triggers (https://issues.jenkins-ci.org/browse/JENKINS-8642[issue #8642]) * Added support for personal portions of email addresses (""Some Name"" ) including support for unicode * Added check of return values from SendFailedException (https://issues.jenkins-ci.org/browse/JENKINS-16919[issue #16919]) * Made it much easier to use content tokens from groovy templates (https://issues.jenkins-ci.org/browse/JENKINS-16916[issue #16916]) * Fixed a typo in the html template (https://issues.jenkins-ci.org/browse/JENKINS-16975[issue #16975]) * Fixed groovy html template when Maven artifacts cause an exception (https://issues.jenkins-ci.org/browse/JENKINS-16983[issue #16983]) * Include Jacoco output in the default Jelly HTML template. == 2.25 (December 12, 2012) * Fixed test failures on Mac OS * Fixed issue with NullReferenceException if the file doesn't exist for the FILE token (https://issues.jenkins-ci.org/browse/JENKINS-15008[issue #15008]) * Improved address resolution if the user is setup in the Jenkins system * Added a debug mode that will add extra log messages to the build log when enabled in the global config. * Updated to core 1.480 * Added ability to add attachments at the trigger level (https://issues.jenkins-ci.org/browse/JENKINS-13672[issue #13672]) * Added option to attach the build log at either the project level, or at the trigger level (https://issues.jenkins-ci.org/browse/JENKINS-13848[issue #13848]) * Improved capture of failed email addresses (https://issues.jenkins-ci.org/browse/JENKINS-16076[issue #16076]) * Added ability to set Reply-To header value at global, project and trigger level. (https://issues.jenkins-ci.org/browse/JENKINS-3324[issue #3324])* Added ability to set Reply-To header value at global, project and trigger level. (https://issues.jenkins-ci.org/browse/JENKINS-3324[issue #3324]) * Added parameter (maxLength) to FAILED_TESTS content token to allow truncating the test information. The maxLength is the number of KB allowed (https://issues.jenkins-ci.org/browse/JENKINS-5949[issue #5949])* Added parameter (maxLength) to FAILED_TESTS content token to allow truncating the test information. The maxLength is the number of KB allowed (https://issues.jenkins-ci.org/browse/JENKINS-5949[issue #5949]) * Added ability to secure the pre-send script by adding a sandbox when enabled in the global config. (https://issues.jenkins-ci.org/browse/JENKINS-15213[issue #15213]) == 2.24.1 (July 20, 2012) * Fixed a few tests which were erroring on Windows. * Fixed issue with very long token strings causing SOE (https://issues.jenkins-ci.org/browse/JENKINS-14132[issue #14132]) * Updated TEST_COUNTS token to include passing tests. * Fixed charset issue when using Jelly templates (https://issues.jenkins-ci.org/browse/JENKINS-7997[issue #7997]) * Allow nested content in JELLEY_SCRIPT tag (https://issues.jenkins-ci.org/browse/JENKINS-14210[issue #14210]) * Added onlyRegressions parameter to FAILED_TESTS token * Allow disable of newlines after each regex match (https://issues.jenkins-ci.org/browse/JENKINS-14320[issue #14320]) * Removed token macro error messages from logs (https://issues.jenkins-ci.org/browse/JENKINS-9364[issue #9364]) * Fixed issue when token-macro was older than expected (https://issues.jenkins-ci.org/browse/JENKINS-14224[issue #14224]) * Fixed changeset author issue with text template * Added new trigger for when a job first fails (https://issues.jenkins-ci.org/browse/JENKINS-7859[issue #7859]) * Allow specifying CC addresses (https://issues.jenkins-ci.org/browse/JENKINS-6703[issue #6703]) * Updated improvement trigger to only fire if there are failures, but less than previous build (https://issues.jenkins-ci.org/browse/JENKINS-14500[issue #14500]) == 2.22 (June 15, 2012) * Added pre-send groovy script for modifying the MimeMessage and even cancelling the email altogether. (https://issues.jenkins-ci.org/browse/JENKINS-12421[issue #12421]) * Added support for the token-macro plugin (https://issues.jenkins-ci.org/browse/JENKINS-9364[issue #9364]) * Added try/catch around user email resolution (https://issues.jenkins-ci.org/browse/JENKINS-13102[issue #13102]) * Attachment file path now supports content tokens (https://issues.jenkins-ci.org/browse/JENKINS-13563[issue #13563]) * Fixed issues with tests causing OutOfMemory exception * Added `BUILD_LOG_MULTILINE_REGEX` that allows regexes to match even newlines == 2.21 (May 16, 2012) * Fix issue with new drop down list for post-build (https://issues.jenkins-ci.org/browse/JENKINS-13737[issue #13737]) * Added a https://github.com/jenkinsci/email-ext-plugin/blob/master/src/main/resources/hudson/plugins/emailext/templates/static-analysis.jelly[new jelly template] that shows the https://plugins.jenkins.io/analysis-core/[static analysis results] == 2.20 (April 12, 2012) * Fix issue with hierarchical projects (see [https://wiki.jenkins.io/display/JENKINS/Hierarchical+projects+support[Hierarchical+projects+support]|]) * Updated html_gmail.jelly file to updated fields * Updated maven pom to use repo.jenkins-ci.org repository * Added scripts for regenerating html.jelly for inline CSS styles * Fix issue with Jenkins URL overriding (https://issues.jenkins-ci.org/browse/JENKINS-13242[issue #13242]) * Fix groovy template for git usage (https://issues.jenkins-ci.org/browse/JENKINS-13192[issue #13192]) * Fix NPE that causes build to hang (https://issues.jenkins-ci.org/browse/JENKINS-12577[issue #12577]) == 2.19 ( Mar 24, 2012 ) * Reimplement default (global) recipient list * Fixed default suffix lookup (https://issues.jenkins-ci.org/browse/JENKINS-11731[issue #11731]) * Added JOB_DESCRIPTION token (https://issues.jenkins-ci.org/browse/JENKINS-4100[issue #4100]) * Added BUILD_ID token (https://issues.jenkins-ci.org/browse/JENKINS-11895[issue #11895]) * Groovy template now correctly determines SUCCESS and FAILURE (https://issues.jenkins-ci.org/browse/JENKINS-13191[issue #13191]) * CHANGES now allows nested content (https://issues.jenkins-ci.org/browse/JENKINS-5376[issue #5376]) * Fixed NRE when recipientList is not in the saved config (https://issues.jenkins-ci.org/browse/JENKINS-12047[issue #12047]) * Emails now send when one or more of the recipients is an invalid recipient (https://issues.jenkins-ci.org/browse/JENKINS-9006[issue #9006]) * Fixed issues with default recipients (https://issues.jenkins-ci.org/browse/JENKINS-11665[issue #11665]) == 2.18 ( Jan 31, 2012 ) * Add maximum size limit to $\\{FAILED_TESTS} (https://issues.jenkins-ci.org/browse/JENKINS-11413[JENKINS-11413]) * Added improvement and regression triggers * Added $\\{BUILD_LOG_EXCERPT} token (https://issues.jenkins-ci.org/browse/JENKINS-10924[issue #10924]) * Added emergency reroute option * Made compatible with LTS 1.424 * Email to requester is now correct (https://issues.jenkins-ci.org/browse/JENKINS-9160[issue #9160]) * Fixed configuration with promoted builds (https://issues.jenkins-ci.org/browse/JENKINS-10812[issue #10812]) * Only include the stack trace if showStacks is true (https://issues.jenkins-ci.org/browse/JENKINS-3430[issue #3430]) == 2.16 (Nov 07, 2011) * More flexible firing control for matrix projects (https://issues.jenkins-ci.org/browse/JENKINS-8590[JENKINS-8590]) * E-mail trigger for aborted and ""not built"" results (https://issues.jenkins-ci.org/browse/JENKINS-10990[JENKINS-10990]) == 2.15 (Sep 05, 2011) * Allow email-ext to attach files to emails (https://issues.jenkins-ci.org/browse/JENKINS-9018[JENKINS-9018]). * Default Recipients list does not appear in Jenkins global settings(https://issues.jenkins-ci.org/browse/JENKINS-10783[JENKINS-10783]). * Email to requester uses wrong email address (https://issues.jenkins-ci.org/browse/JENKINS-9160[JENKINS-9160]). * Allow using Groovy (or other JSR223 languages) to generate the email content. == 2.14.1 (Jul 01, 2011) * Added option for adding 'Precedence: bulk' header according to http://tools.ietf.org/search/rfc3834 to prevent out-of-office replies. == 2.14 (Apr 21, 2011) * Improved the portability of the default Jelly templates across different SCM implementations (whereas previously some of the information was only displayed for Subversion) * Send the ""still unstable"" email rather than the ""unstable"" email, when the previous status was fail, and the status before that was unstable. (https://issues.jenkins-ci.org/browse/JENKINS-5411[JENKINS-5411]) == 2.13 (Mar 23 2011) * Fixed a bug where the html/text Jelly template fail to report the change log correctly for all SCMs but Subversion. * If an e-mail is supposed to be sent to the requester, follow the build triggering chain to find the root requester (https://issues.jenkins-ci.org/browse/JENKINS-7740[JENKINS-7740]) * Added an option to configure a List-ID header on emails. == 2.12 (Feb 26, 2011) * Rerelease 2.11 to properly set required Jenkins version. == 2.11 (Feb 19, 2011) *This version requires Jenkins 1.396 or newer.* * Added Charset option. (https://issues.jenkins-ci.org/browse/JENKINS-8011[JENKINS-8011]) ** Added ""hudson.plugins.emailext.ExtendedEmailPublisher.Content-Transfer-Encoding"" system property to specify ""Content-Transfer-Encoding"". * Added ""Requester"" as possible mail destination (https://issues.jenkins-ci.org/browse/JENKINS-7740[JENKINS-7740]) * Need tokens to get failed tests count and total tests count, to put them in mail subject easy. (https://issues.jenkins-ci.org/browse/JENKINS-5936[JENKINS-5936]) * Introduce $JENKINS_URL and deprecated $HUDSON_URL. * i18n & l10n(ja) == 2.10 (Jan 20, 2011) * Added a new content token ""FILE"" that includes a file from the workspace. * BUILD_LOG_REGEX Token: ** Add escapeHtml - If true, escape HTML. Defaults to false. ** Add matchedLineHtmlStyle - If non-null, output HTML. Matched lines will become `html escaped matched line`. Defaults to null. * Prevent duplicate email notifications. (https://issues.jenkins-ci.org/browse/JENKINS-8071[JENKINS-8071]) == 2.9 (Oct 14, 2010) * The _showPaths_ argument was not working for CHANGES_SINCE_LAST_UNSTABLE and CHANGES_SINCE_LAST_SUCCESS. (issue #http://issues.jenkins-ci.org/browse/JENKINS-5486[5486]) * Add support for custom Jelly script content (JELLY_SCRIPT) (issue #http://issues.jenkins-ci.org/browse/JENKINS-7514[7514]) == 2.8 (Sept 15, 2010) _This version requires Hudson 1.356 or newer._ * Update BUILD_LOG_REGEX to properly handle http://kohsuke.org/2010/04/14/hudson-console-markups/[console notes]. (issue #http://issues.jenkins-ci.org/browse/JENKINS-7402[7402]) * Fixed password being saved in plaintext. (issue #http://issues.jenkins-ci.org/browse/JENKINS-5816[5816]) * Override ""Hudson URL"" only when ""override global settings"" is checked. (issue #http://issues.jenkins-ci.org/browse/JENKINS-6193[6193]) * Add escapeHtml parameter to BUILD_LOG content for escaping HTML. Defaults to false for backwards compatibility. (issue #http://issues.jenkins-ci.org/browse/JENKINS-7397[7397]) == 2.7 (Aug 30, 2010) * New optional arg: ${BUILD_LOG_REGEX, regex, linesBefore, linesAfter, maxMatches, showTruncatedLines, substText} which allows substituting text for the matched regex. This is particularly useful when the text contains references to capture groups (i.e. $1, $2, etc.)   * Fix invalid illegal email address exception (https://issues.jenkins-ci.org/browse/JENKINS-7057[JENKINS-7057]). == 2.6 (Jul 20, 2010) * Add ${BUILD_LOG_REGEX, regex, linesBefore, linesAfter, maxMatches, showTruncatedLines} token. * Add token for build cause. (https://issues.jenkins-ci.org/browse/JENKINS-3166[JENKINS-3166]) * Add ""changes since last unstable build"" token. (https://issues.jenkins-ci.org/browse/JENKINS-6671[JENKINS-6671]) * Fix issue with node properties not being available for the $ENV token. (https://issues.jenkins-ci.org/browse/JENKINS-5465[JENKINS-5465]) * Recipient list can now use parameters. (https://issues.jenkins-ci.org/browse/JENKINS-6396[JENKINS-6396]) * Improve docs regarding use of quotes for string parameters. (https://issues.jenkins-ci.org/browse/JENKINS-5322[JENKINS-5322]) == 2.5 (Jan 20, 2010) * Fix issue with adding a pre-build trigger using $BUILD_STATUS would make the build appear as if it was successful or fixed when the build hadn't actually ran yet. (http://issues.jenkins-ci.org/browse/JENKINS-953[issue #953]) * Fix NullPointerException when no root URL is configured. (http://issues.jenkins-ci.org/browse/JENKINS-1771[issue #1771]) * $CHANGES_SINCE_LAST_SUCCESS was not showing unstable or aborted builds in the list of changes since the last successful build. (http://issues.jenkins-ci.org/browse/JENKINS-3519[issue #3519]) == 2.4 (Jan 7, 2010) * Fix bug in 2.3 release that broke saving project config changes if Promoted Builds plugin is not also installed. (https://issues.jenkins-ci.org/browse/JENKINS-5208[JENKINS-5208]) * Fix in overriding global email settings. * Fix to allow authentication without SSL. * Send emails as replies to previous ones for same project, as done in Hudson's built-in emailer. (https://issues.jenkins-ci.org/browse/JENKINS-3089[JENKINS-3089]) * New ""Before Build"" trigger type. (https://issues.jenkins-ci.org/browse/JENKINS-4190[JENKINS-4190]) == 2.3 (Jan 6, 2010) * Change the token handling to allow for passing of arguments, and allow arguments for the `BUILD_LOG`, `CHANGES`, and `CHANGES_SINCE_LAST_SUCCESS` tokens. (https://issues.jenkins-ci.org/browse/JENKINS-3085[JENKINS-3085]) * Revamp the help. Now have help on each form element in the config. Rearranged help files hierarchially and deleted unused help. * Allow HTML content in emails. There is a global preference plus a per-project preference, which default to plain text. * When the emailer can not process an email address, it now prints to the builder output. (https://issues.jenkins-ci.org/browse/JENKINS-1529[JENKINS-1529]) * Allow use of any environment variable. (https://issues.jenkins-ci.org/browse/JENKINS-3605[JENKINS-3605]) * Add ability to re-use ""global"" settings (i.e. settings from the core Mailer configuration) * Add support for SVN_REVISION * Fix for email triggers with space in name. (https://issues.jenkins-ci.org/browse/JENKINS-3614[JENKINS-3614]) * Update code for more recent Hudson. * Fixed help links. (https://issues.jenkins-ci.org/browse/JENKINS-4566[JENKINS-4566]) * Compatibility with https://plugins.jenkins.io/promoted-builds/[Promoted Builds Plugin]. == 2.2.1 (Dec 23, 2008) ",12466,True,3091.7060989819493,median "//===- InlineSpiller.cpp - Insert spills and restores inline --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // The inline spiller modifies the machine function directly instead of // inserting spills and restores in VirtRegMap. // //===----------------------------------------------------------------------===// #include ""SplitKit.h"" #include ""llvm/ADT/ArrayRef.h"" #include ""llvm/ADT/DenseMap.h"" #include ""llvm/ADT/MapVector.h"" #include ""llvm/ADT/None.h"" #include ""llvm/ADT/STLExtras.h"" #include ""llvm/ADT/SetVector.h"" #include ""llvm/ADT/SmallPtrSet.h"" #include ""llvm/ADT/SmallVector.h"" #include ""llvm/ADT/Statistic.h"" #include ""llvm/Analysis/AliasAnalysis.h"" #include ""llvm/CodeGen/LiveInterval.h"" #include ""llvm/CodeGen/LiveIntervalCalc.h"" #include ""llvm/CodeGen/LiveIntervals.h"" #include ""llvm/CodeGen/LiveRangeEdit.h"" #include ""llvm/CodeGen/LiveStacks.h"" #include ""llvm/CodeGen/MachineBasicBlock.h"" #include ""llvm/CodeGen/MachineBlockFrequencyInfo.h"" #include ""llvm/CodeGen/MachineDominators.h"" #include ""llvm/CodeGen/MachineFunction.h"" #include ""llvm/CodeGen/MachineFunctionPass.h"" #include ""llvm/CodeGen/MachineInstr.h"" #include ""llvm/CodeGen/MachineInstrBuilder.h"" #include ""llvm/CodeGen/MachineInstrBundle.h"" #include ""llvm/CodeGen/MachineLoopInfo.h"" #include ""llvm/CodeGen/MachineOperand.h"" #include ""llvm/CodeGen/MachineRegisterInfo.h"" #include ""llvm/CodeGen/SlotIndexes.h"" #include ""llvm/CodeGen/Spiller.h"" #include ""llvm/CodeGen/StackMaps.h"" #include ""llvm/CodeGen/TargetInstrInfo.h"" #include ""llvm/CodeGen/TargetOpcodes.h"" #include ""llvm/CodeGen/TargetRegisterInfo.h"" #include ""llvm/CodeGen/TargetSubtargetInfo.h"" #include ""llvm/CodeGen/VirtRegMap.h"" #include ""llvm/Config/llvm-config.h"" #include ""llvm/Support/BlockFrequency.h"" #include ""llvm/Support/BranchProbability.h"" #include ""llvm/Support/CommandLine.h"" #include ""llvm/Support/Compiler.h"" #include ""llvm/Support/Debug.h"" #include ""llvm/Support/ErrorHandling.h"" #include ""llvm/Support/raw_ostream.h"" #include #include #include #include #include using namespace llvm; #define DEBUG_TYPE ""regalloc"" STATISTIC(NumSpilledRanges, ""Number of spilled live ranges""); STATISTIC(NumSnippets, ""Number of spilled snippets""); STATISTIC(NumSpills, ""Number of spills inserted""); STATISTIC(NumSpillsRemoved, ""Number of spills removed""); STATISTIC(NumReloads, ""Number of reloads inserted""); STATISTIC(NumReloadsRemoved, ""Number of reloads removed""); STATISTIC(NumFolded, ""Number of folded stack accesses""); STATISTIC(NumFoldedLoads, ""Number of folded loads""); STATISTIC(NumRemats, ""Number of rematerialized defs for spilling""); static cl::opt DisableHoisting(""disable-spill-hoist"", cl::Hidden, cl::desc(""Disable inline spill hoisting"")); static cl::opt RestrictStatepointRemat(""restrict-statepoint-remat"", cl::init(false), cl::Hidden, cl::desc(""Restrict remat for statepoint operands"")); namespace { class HoistSpillHelper : private LiveRangeEdit::Delegate { MachineFunction &MF; LiveIntervals &LIS; LiveStacks &LSS; AliasAnalysis *AA; MachineDominatorTree &MDT; MachineLoopInfo &Loops; VirtRegMap &VRM; MachineRegisterInfo &MRI; const TargetInstrInfo &TII; const TargetRegisterInfo &TRI; const MachineBlockFrequencyInfo &MBFI; InsertPointAnalysis IPA; // Map from StackSlot to the LiveInterval of the original register. // Note the LiveInterval of the original register may have been deleted // after it is spilled. We keep a copy here to track the range where // spills can be moved. DenseMap> StackSlotToOrigLI; // Map from pair of (StackSlot and Original VNI) to a set of spills which // have the same stackslot and have equal values defined by Original VNI. // These spills are mergeable and are hoist candiates. using MergeableSpillsMap = MapVector, SmallPtrSet>; MergeableSpillsMap MergeableSpills; /// This is the map from original register to a set containing all its /// siblings. To hoist a spill to another BB, we need to find out a live /// sibling there and use it as the source of the new spill. DenseMap> Virt2SiblingsMap; bool isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI, MachineBasicBlock &BB, Register &LiveReg); void rmRedundantSpills( SmallPtrSet &Spills, SmallVectorImpl &SpillsToRm, DenseMap &SpillBBToSpill); void getVisitOrders( MachineBasicBlock *Root, SmallPtrSet &Spills, SmallVectorImpl &Orders, SmallVectorImpl &SpillsToRm, DenseMap &SpillsToKeep, DenseMap &SpillBBToSpill); void runHoistSpills(LiveInterval &OrigLI, VNInfo &OrigVNI, SmallPtrSet &Spills, SmallVectorImpl &SpillsToRm, DenseMap &SpillsToIns); public: HoistSpillHelper(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm) : MF(mf), LIS(pass.getAnalysis()), LSS(pass.getAnalysis()), AA(&pass.getAnalysis().getAAResults()), MDT(pass.getAnalysis()), Loops(pass.getAnalysis()), VRM(vrm), MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()), TRI(*mf.getSubtarget().getRegisterInfo()), MBFI(pass.getAnalysis()), IPA(LIS, mf.getNumBlockIDs()) {} void addToMergeableSpills(MachineInstr &Spill, int StackSlot, unsigned Original); bool rmFromMergeableSpills(MachineInstr &Spill, int StackSlot); void hoistAllSpills(); void LRE_DidCloneVirtReg(unsigned, unsigned) override; }; class InlineSpiller : public Spiller { MachineFunction &MF; LiveIntervals &LIS; LiveStacks &LSS; AliasAnalysis *AA; MachineDominatorTree &MDT; MachineLoopInfo &Loops; VirtRegMap &VRM; MachineRegisterInfo &MRI; const TargetInstrInfo &TII; const TargetRegisterInfo &TRI; const MachineBlockFrequencyInfo &MBFI; // Variables that are valid during spill(), but used by multiple methods. LiveRangeEdit *Edit; LiveInterval *StackInt; int StackSlot; unsigned Original; // All registers to spill to StackSlot, including the main register. SmallVector RegsToSpill; // All COPY instructions to/from snippets. // They are ignored since both operands refer to the same stack slot. SmallPtrSet SnippetCopies; // Values that failed to remat at some point. SmallPtrSet UsedValues; // Dead defs generated during spilling. SmallVector DeadDefs; // Object records spills information and does the hoisting. HoistSpillHelper HSpiller; ~InlineSpiller() override = default; public: InlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm) : MF(mf), LIS(pass.getAnalysis()), LSS(pass.getAnalysis()), AA(&pass.getAnalysis().getAAResults()), MDT(pass.getAnalysis()), Loops(pass.getAnalysis()), VRM(vrm), MRI(mf.getRegInfo()), TII(*mf.getSubtarget().getInstrInfo()), TRI(*mf.getSubtarget().getRegisterInfo()), MBFI(pass.getAnalysis()), HSpiller(pass, mf, vrm) {} void spill(LiveRangeEdit &) override; void postOptimization() override; private: bool isSnippet(const LiveInterval &SnipLI); void collectRegsToSpill(); bool isRegToSpill(Register Reg) { return is_contained(RegsToSpill, Reg); } bool isSibling(Register Reg); bool hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI); void eliminateRedundantSpills(LiveInterval &LI, VNInfo *VNI); void markValueUsed(LiveInterval*, VNInfo*); bool canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI); bool reMaterializeFor(LiveInterval &, MachineInstr &MI); void reMaterializeAll(); bool coalesceStackAccess(MachineInstr *MI, Register Reg); bool foldMemoryOperand(ArrayRef>, MachineInstr *LoadMI = nullptr); void insertReload(Register VReg, SlotIndex, MachineBasicBlock::iterator MI); void insertSpill(Register VReg, bool isKill, MachineBasicBlock::iterator MI); void spillAroundUses(Register Reg); void spillAll(); }; } // end anonymous namespace Spiller::~Spiller() = default; void Spiller::anchor() {} Spiller *llvm::createInlineSpiller(MachineFunctionPass &pass, MachineFunction &mf, VirtRegMap &vrm) { return new InlineSpiller(pass, mf, vrm); } //===----------------------------------------------------------------------===// // Snippets //===----------------------------------------------------------------------===// // When spilling a virtual register, we also spill any snippets it is connected // to. The snippets are small live ranges that only have a single real use, // leftovers from live range splitting. Spilling them enables memory operand // folding or tightens the live range around the single use. // // This minimizes register pressure and maximizes the store-to-load distance for // spill slots which can be important in tight loops. /// isFullCopyOf - If MI is a COPY to or from Reg, return the other register, /// otherwise return 0. static Register isFullCopyOf(const MachineInstr &MI, Register Reg) { if (!MI.isFullCopy()) return Register(); if (MI.getOperand(0).getReg() == Reg) return MI.getOperand(1).getReg(); if (MI.getOperand(1).getReg() == Reg) return MI.getOperand(0).getReg(); return Register(); } /// isSnippet - Identify if a live interval is a snippet that should be spilled. /// It is assumed that SnipLI is a virtual register with the same original as /// Edit->getReg(). bool InlineSpiller::isSnippet(const LiveInterval &SnipLI) { Register Reg = Edit->getReg(); // A snippet is a tiny live range with only a single instruction using it // besides copies to/from Reg or spills/fills. We accept: // // %snip = COPY %Reg / FILL fi# // %snip = USE %snip // %Reg = COPY %snip / SPILL %snip, fi# // if (SnipLI.getNumValNums() > 2 || !LIS.intervalIsInOneMBB(SnipLI)) return false; MachineInstr *UseMI = nullptr; // Check that all uses satisfy our criteria. for (MachineRegisterInfo::reg_instr_nodbg_iterator RI = MRI.reg_instr_nodbg_begin(SnipLI.reg()), E = MRI.reg_instr_nodbg_end(); RI != E;) { MachineInstr &MI = *RI++; // Allow copies to/from Reg. if (isFullCopyOf(MI, Reg)) continue; // Allow stack slot loads. int FI; if (SnipLI.reg() == TII.isLoadFromStackSlot(MI, FI) && FI == StackSlot) continue; // Allow stack slot stores. if (SnipLI.reg() == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) continue; // Allow a single additional instruction. if (UseMI && &MI != UseMI) return false; UseMI = &MI; } return true; } /// collectRegsToSpill - Collect live range snippets that only have a single /// real use. void InlineSpiller::collectRegsToSpill() { Register Reg = Edit->getReg(); // Main register always spills. RegsToSpill.assign(1, Reg); SnippetCopies.clear(); // Snippets all have the same original, so there can't be any for an original // register. if (Original == Reg) return; for (MachineRegisterInfo::reg_instr_iterator RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) { MachineInstr &MI = *RI++; Register SnipReg = isFullCopyOf(MI, Reg); if (!isSibling(SnipReg)) continue; LiveInterval &SnipLI = LIS.getInterval(SnipReg); if (!isSnippet(SnipLI)) continue; SnippetCopies.insert(&MI); if (isRegToSpill(SnipReg)) continue; RegsToSpill.push_back(SnipReg); LLVM_DEBUG(dbgs() << ""\\talso spill snippet "" << SnipLI << '\\n'); ++NumSnippets; } } bool InlineSpiller::isSibling(Register Reg) { return Reg.isVirtual() && VRM.getOriginal(Reg) == Original; } /// It is beneficial to spill to earlier place in the same BB in case /// as follows: /// There is an alternative def earlier in the same MBB. /// Hoist the spill as far as possible in SpillMBB. This can ease /// register pressure: /// /// x = def /// y = use x /// s = copy x /// /// Hoisting the spill of s to immediately after the def removes the /// interference between x and y: /// /// x = def /// spill x /// y = use killed x /// /// This hoist only helps when the copy kills its source. /// bool InlineSpiller::hoistSpillInsideBB(LiveInterval &SpillLI, MachineInstr &CopyMI) { SlotIndex Idx = LIS.getInstructionIndex(CopyMI); #ifndef NDEBUG VNInfo *VNI = SpillLI.getVNInfoAt(Idx.getRegSlot()); assert(VNI && VNI->def == Idx.getRegSlot() && ""Not defined by copy""); #endif Register SrcReg = CopyMI.getOperand(1).getReg(); LiveInterval &SrcLI = LIS.getInterval(SrcReg); VNInfo *SrcVNI = SrcLI.getVNInfoAt(Idx); LiveQueryResult SrcQ = SrcLI.Query(Idx); MachineBasicBlock *DefMBB = LIS.getMBBFromIndex(SrcVNI->def); if (DefMBB != CopyMI.getParent() || !SrcQ.isKill()) return false; // Conservatively extend the stack slot range to the range of the original // value. We may be able to do better with stack slot coloring by being more // careful here. assert(StackInt && ""No stack slot assigned yet.""); LiveInterval &OrigLI = LIS.getInterval(Original); VNInfo *OrigVNI = OrigLI.getVNInfoAt(Idx); StackInt->MergeValueInAsValue(OrigLI, OrigVNI, StackInt->getValNumInfo(0)); LLVM_DEBUG(dbgs() << ""\\tmerged orig valno "" << OrigVNI->id << "": "" << *StackInt << '\\n'); // We are going to spill SrcVNI immediately after its def, so clear out // any later spills of the same value. eliminateRedundantSpills(SrcLI, SrcVNI); MachineBasicBlock *MBB = LIS.getMBBFromIndex(SrcVNI->def); MachineBasicBlock::iterator MII; if (SrcVNI->isPHIDef()) MII = MBB->SkipPHIsLabelsAndDebug(MBB->begin()); else { MachineInstr *DefMI = LIS.getInstructionFromIndex(SrcVNI->def); assert(DefMI && ""Defining instruction disappeared""); MII = DefMI; ++MII; } // Insert spill without kill flag immediately after def. TII.storeRegToStackSlot(*MBB, MII, SrcReg, false, StackSlot, MRI.getRegClass(SrcReg), &TRI); --MII; // Point to store instruction. LIS.InsertMachineInstrInMaps(*MII); LLVM_DEBUG(dbgs() << ""\\thoisted: "" << SrcVNI->def << '\\t' << *MII); HSpiller.addToMergeableSpills(*MII, StackSlot, Original); ++NumSpills; return true; } /// eliminateRedundantSpills - SLI:VNI is known to be on the stack. Remove any /// redundant spills of this value in SLI.reg and sibling copies. void InlineSpiller::eliminateRedundantSpills(LiveInterval &SLI, VNInfo *VNI) { assert(VNI && ""Missing value""); SmallVector, 8> WorkList; WorkList.push_back(std::make_pair(&SLI, VNI)); assert(StackInt && ""No stack slot assigned yet.""); do { LiveInterval *LI; std::tie(LI, VNI) = WorkList.pop_back_val(); Register Reg = LI->reg(); LLVM_DEBUG(dbgs() << ""Checking redundant spills for "" << VNI->id << '@' << VNI->def << "" in "" << *LI << '\\n'); // Regs to spill are taken care of. if (isRegToSpill(Reg)) continue; // Add all of VNI's live range to StackInt. StackInt->MergeValueInAsValue(*LI, VNI, StackInt->getValNumInfo(0)); LLVM_DEBUG(dbgs() << ""Merged to stack int: "" << *StackInt << '\\n'); // Find all spills and copies of VNI. for (MachineRegisterInfo::use_instr_nodbg_iterator UI = MRI.use_instr_nodbg_begin(Reg), E = MRI.use_instr_nodbg_end(); UI != E; ) { MachineInstr &MI = *UI++; if (!MI.isCopy() && !MI.mayStore()) continue; SlotIndex Idx = LIS.getInstructionIndex(MI); if (LI->getVNInfoAt(Idx) != VNI) continue; // Follow sibling copies down the dominator tree. if (Register DstReg = isFullCopyOf(MI, Reg)) { if (isSibling(DstReg)) { LiveInterval &DstLI = LIS.getInterval(DstReg); VNInfo *DstVNI = DstLI.getVNInfoAt(Idx.getRegSlot()); assert(DstVNI && ""Missing defined value""); assert(DstVNI->def == Idx.getRegSlot() && ""Wrong copy def slot""); WorkList.push_back(std::make_pair(&DstLI, DstVNI)); } continue; } // Erase spills. int FI; if (Reg == TII.isStoreToStackSlot(MI, FI) && FI == StackSlot) { LLVM_DEBUG(dbgs() << ""Redundant spill "" << Idx << '\\t' << MI); // eliminateDeadDefs won't normally remove stores, so switch opcode. MI.setDesc(TII.get(TargetOpcode::KILL)); DeadDefs.push_back(&MI); ++NumSpillsRemoved; if (HSpiller.rmFromMergeableSpills(MI, StackSlot)) --NumSpills; } } } while (!WorkList.empty()); } //===----------------------------------------------------------------------===// // Rematerialization //===----------------------------------------------------------------------===// /// markValueUsed - Remember that VNI failed to rematerialize, so its defining /// instruction cannot be eliminated. See through snippet copies void InlineSpiller::markValueUsed(LiveInterval *LI, VNInfo *VNI) { SmallVector, 8> WorkList; WorkList.push_back(std::make_pair(LI, VNI)); do { std::tie(LI, VNI) = WorkList.pop_back_val(); if (!UsedValues.insert(VNI).second) continue; if (VNI->isPHIDef()) { MachineBasicBlock *MBB = LIS.getMBBFromIndex(VNI->def); for (MachineBasicBlock *P : MBB->predecessors()) { VNInfo *PVNI = LI->getVNInfoBefore(LIS.getMBBEndIdx(P)); if (PVNI) WorkList.push_back(std::make_pair(LI, PVNI)); } continue; } // Follow snippet copies. MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); if (!SnippetCopies.count(MI)) continue; LiveInterval &SnipLI = LIS.getInterval(MI->getOperand(1).getReg()); assert(isRegToSpill(SnipLI.reg()) && ""Unexpected register in copy""); VNInfo *SnipVNI = SnipLI.getVNInfoAt(VNI->def.getRegSlot(true)); assert(SnipVNI && ""Snippet undefined before copy""); WorkList.push_back(std::make_pair(&SnipLI, SnipVNI)); } while (!WorkList.empty()); } bool InlineSpiller::canGuaranteeAssignmentAfterRemat(Register VReg, MachineInstr &MI) { if (!RestrictStatepointRemat) return true; // Here's a quick explanation of the problem we're trying to handle here: // * There are some pseudo instructions with more vreg uses than there are // physical registers on the machine. // * This is normally handled by spilling the vreg, and folding the reload // into the user instruction. (Thus decreasing the number of used vregs // until the remainder can be assigned to physregs.) // * However, since we may try to spill vregs in any order, we can end up // trying to spill each operand to the instruction, and then rematting it // instead. When that happens, the new live intervals (for the remats) are // expected to be trivially assignable (i.e. RS_Done). However, since we // may have more remats than physregs, we're guaranteed to fail to assign // one. // At the moment, we only handle this for STATEPOINTs since they're the only // pseudo op where we've seen this. If we start seeing other instructions // with the same problem, we need to revisit this. if (MI.getOpcode() != TargetOpcode::STATEPOINT) return true; // For STATEPOINTs we allow re-materialization for fixed arguments only hoping // that number of physical registers is enough to cover all fixed arguments. // If it is not true we need to revisit it. for (unsigned Idx = StatepointOpers(&MI).getVarIdx(), EndIdx = MI.getNumOperands(); Idx < EndIdx; ++Idx) { MachineOperand &MO = MI.getOperand(Idx); if (MO.isReg() && MO.getReg() == VReg) return false; } return true; } /// reMaterializeFor - Attempt to rematerialize before MI instead of reloading. bool InlineSpiller::reMaterializeFor(LiveInterval &VirtReg, MachineInstr &MI) { // Analyze instruction SmallVector, 8> Ops; VirtRegInfo RI = AnalyzeVirtRegInBundle(MI, VirtReg.reg(), &Ops); if (!RI.Reads) return false; SlotIndex UseIdx = LIS.getInstructionIndex(MI).getRegSlot(true); VNInfo *ParentVNI = VirtReg.getVNInfoAt(UseIdx.getBaseIndex()); if (!ParentVNI) { LLVM_DEBUG(dbgs() << ""\\tadding flags: ""); for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { MachineOperand &MO = MI.getOperand(i); if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) MO.setIsUndef(); } LLVM_DEBUG(dbgs() << UseIdx << '\\t' << MI); return true; } if (SnippetCopies.count(&MI)) return false; LiveInterval &OrigLI = LIS.getInterval(Original); VNInfo *OrigVNI = OrigLI.getVNInfoAt(UseIdx); LiveRangeEdit::Remat RM(ParentVNI); RM.OrigMI = LIS.getInstructionFromIndex(OrigVNI->def); if (!Edit->canRematerializeAt(RM, OrigVNI, UseIdx, false)) { markValueUsed(&VirtReg, ParentVNI); LLVM_DEBUG(dbgs() << ""\\tcannot remat for "" << UseIdx << '\\t' << MI); return false; } // If the instruction also writes VirtReg.reg, it had better not require the // same register for uses and defs. if (RI.Tied) { markValueUsed(&VirtReg, ParentVNI); LLVM_DEBUG(dbgs() << ""\\tcannot remat tied reg: "" << UseIdx << '\\t' << MI); return false; } // Before rematerializing into a register for a single instruction, try to // fold a load into the instruction. That avoids allocating a new register. if (RM.OrigMI->canFoldAsLoad() && foldMemoryOperand(Ops, RM.OrigMI)) { Edit->markRematerialized(RM.ParentVNI); ++NumFoldedLoads; return true; } // If we can't guarantee that we'll be able to actually assign the new vreg, // we can't remat. if (!canGuaranteeAssignmentAfterRemat(VirtReg.reg(), MI)) { markValueUsed(&VirtReg, ParentVNI); LLVM_DEBUG(dbgs() << ""\\tcannot remat for "" << UseIdx << '\\t' << MI); return false; } // Allocate a new register for the remat. Register NewVReg = Edit->createFrom(Original); // Finally we can rematerialize OrigMI before MI. SlotIndex DefIdx = Edit->rematerializeAt(*MI.getParent(), MI, NewVReg, RM, TRI); // We take the DebugLoc from MI, since OrigMI may be attributed to a // different source location. auto *NewMI = LIS.getInstructionFromIndex(DefIdx); NewMI->setDebugLoc(MI.getDebugLoc()); (void)DefIdx; LLVM_DEBUG(dbgs() << ""\\tremat: "" << DefIdx << '\\t' << *LIS.getInstructionFromIndex(DefIdx)); // Replace operands for (const auto &OpPair : Ops) { MachineOperand &MO = OpPair.first->getOperand(OpPair.second); if (MO.isReg() && MO.isUse() && MO.getReg() == VirtReg.reg()) { MO.setReg(NewVReg); MO.setIsKill(); } } LLVM_DEBUG(dbgs() << ""\\t "" << UseIdx << '\\t' << MI << '\\n'); ++NumRemats; return true; } /// reMaterializeAll - Try to rematerialize as many uses as possible, /// and trim the live ranges after. void InlineSpiller::reMaterializeAll() { if (!Edit->anyRematerializable(AA)) return; UsedValues.clear(); // Try to remat before all uses of snippets. bool anyRemat = false; for (Register Reg : RegsToSpill) { LiveInterval &LI = LIS.getInterval(Reg); for (MachineRegisterInfo::reg_bundle_iterator RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end(); RegI != E; ) { MachineInstr &MI = *RegI++; // Debug values are not allowed to affect codegen. if (MI.isDebugValue()) continue; assert(!MI.isDebugInstr() && ""Did not expect to find a use in debug "" ""instruction that isn't a DBG_VALUE""); anyRemat |= reMaterializeFor(LI, MI); } } if (!anyRemat) return; // Remove any values that were completely rematted. for (Register Reg : RegsToSpill) { LiveInterval &LI = LIS.getInterval(Reg); for (LiveInterval::vni_iterator I = LI.vni_begin(), E = LI.vni_end(); I != E; ++I) { VNInfo *VNI = *I; if (VNI->isUnused() || VNI->isPHIDef() || UsedValues.count(VNI)) continue; MachineInstr *MI = LIS.getInstructionFromIndex(VNI->def); MI->addRegisterDead(Reg, &TRI); if (!MI->allDefsAreDead()) continue; LLVM_DEBUG(dbgs() << ""All defs dead: "" << *MI); DeadDefs.push_back(MI); } } // Eliminate dead code after remat. Note that some snippet copies may be // deleted here. if (DeadDefs.empty()) return; LLVM_DEBUG(dbgs() << ""Remat created "" << DeadDefs.size() << "" dead defs.\\n""); Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA); // LiveRangeEdit::eliminateDeadDef is used to remove dead define instructions // after rematerialization. To remove a VNI for a vreg from its LiveInterval, // LiveIntervals::removeVRegDefAt is used. However, after non-PHI VNIs are all // removed, PHI VNI are still left in the LiveInterval. // So to get rid of unused reg, we need to check whether it has non-dbg // reference instead of whether it has non-empty interval. unsigned ResultPos = 0; for (Register Reg : RegsToSpill) { if (MRI.reg_nodbg_empty(Reg)) { Edit->eraseVirtReg(Reg); continue; } assert(LIS.hasInterval(Reg) && (!LIS.getInterval(Reg).empty() || !MRI.reg_nodbg_empty(Reg)) && ""Empty and not used live-range?!""); RegsToSpill[ResultPos++] = Reg; } RegsToSpill.erase(RegsToSpill.begin() + ResultPos, RegsToSpill.end()); LLVM_DEBUG(dbgs() << RegsToSpill.size() << "" registers to spill after remat.\\n""); } //===----------------------------------------------------------------------===// // Spilling //===----------------------------------------------------------------------===// /// If MI is a load or store of StackSlot, it can be removed. bool InlineSpiller::coalesceStackAccess(MachineInstr *MI, Register Reg) { int FI = 0; Register InstrReg = TII.isLoadFromStackSlot(*MI, FI); bool IsLoad = InstrReg; if (!IsLoad) InstrReg = TII.isStoreToStackSlot(*MI, FI); // We have a stack access. Is it the right register and slot? if (InstrReg != Reg || FI != StackSlot) return false; if (!IsLoad) HSpiller.rmFromMergeableSpills(*MI, StackSlot); LLVM_DEBUG(dbgs() << ""Coalescing stack access: "" << *MI); LIS.RemoveMachineInstrFromMaps(*MI); MI->eraseFromParent(); if (IsLoad) { ++NumReloadsRemoved; --NumReloads; } else { ++NumSpillsRemoved; --NumSpills; } return true; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD // Dump the range of instructions from B to E with their slot indexes. static void dumpMachineInstrRangeWithSlotIndex(MachineBasicBlock::iterator B, MachineBasicBlock::iterator E, LiveIntervals const &LIS, const char *const header, Register VReg = Register()) { char NextLine = '\\n'; char SlotIndent = '\\t'; if (std::next(B) == E) { NextLine = ' '; SlotIndent = ' '; } dbgs() << '\\t' << header << "": "" << NextLine; for (MachineBasicBlock::iterator I = B; I != E; ++I) { SlotIndex Idx = LIS.getInstructionIndex(*I).getRegSlot(); // If a register was passed in and this instruction has it as a // destination that is marked as an early clobber, print the // early-clobber slot index. if (VReg) { MachineOperand *MO = I->findRegisterDefOperand(VReg); if (MO && MO->isEarlyClobber()) Idx = Idx.getRegSlot(true); } dbgs() << SlotIndent << Idx << '\\t' << *I; } } #endif /// foldMemoryOperand - Try folding stack slot references in Ops into their /// instructions. /// /// @param Ops Operand indices from AnalyzeVirtRegInBundle(). /// @param LoadMI Load instruction to use instead of stack slot when non-null. /// @return True on success. bool InlineSpiller:: foldMemoryOperand(ArrayRef> Ops, MachineInstr *LoadMI) { if (Ops.empty()) return false; // Don't attempt folding in bundles. MachineInstr *MI = Ops.front().first; if (Ops.back().first != MI || MI->isBundled()) return false; bool WasCopy = MI->isCopy(); Register ImpReg; // TII::foldMemoryOperand will do what we need here for statepoint // (fold load into use and remove corresponding def). We will replace // uses of removed def with loads (spillAroundUses). // For that to work we need to untie def and use to pass it through // foldMemoryOperand and signal foldPatchpoint that it is allowed to // fold them. bool UntieRegs = MI->getOpcode() == TargetOpcode::STATEPOINT; // Spill subregs if the target allows it. // We always want to spill subregs for stackmap/patchpoint pseudos. bool SpillSubRegs = TII.isSubregFoldable() || MI->getOpcode() == TargetOpcode::STATEPOINT || MI->getOpcode() == TargetOpcode::PATCHPOINT || MI->getOpcode() == TargetOpcode::STACKMAP; // TargetInstrInfo::foldMemoryOperand only expects explicit, non-tied // operands. SmallVector FoldOps; for (const auto &OpPair : Ops) { unsigned Idx = OpPair.second; assert(MI == OpPair.first && ""Instruction conflict during operand folding""); MachineOperand &MO = MI->getOperand(Idx); if (MO.isImplicit()) { ImpReg = MO.getReg(); continue; } if (UntieRegs && MO.isTied()) MI->untieRegOperand(Idx); if (!SpillSubRegs && MO.getSubReg()) return false; // We cannot fold a load instruction into a def. if (LoadMI && MO.isDef()) return false; // Tied use operands should not be passed to foldMemoryOperand. if (!MI->isRegTiedToDefOperand(Idx)) FoldOps.push_back(Idx); } // If we only have implicit uses, we won't be able to fold that. // Moreover, TargetInstrInfo::foldMemoryOperand will assert if we try! if (FoldOps.empty()) return false; MachineInstrSpan MIS(MI, MI->getParent()); MachineInstr *FoldMI = LoadMI ? TII.foldMemoryOperand(*MI, FoldOps, *LoadMI, &LIS) : TII.foldMemoryOperand(*MI, FoldOps, StackSlot, &LIS, &VRM); if (!FoldMI) return false; // Remove LIS for any dead defs in the original MI not in FoldMI. for (MIBundleOperands MO(*MI); MO.isValid(); ++MO) { if (!MO->isReg()) continue; Register Reg = MO->getReg(); if (!Reg || Register::isVirtualRegister(Reg) || MRI.isReserved(Reg)) { continue; } // Skip non-Defs, including undef uses and internal reads. if (MO->isUse()) continue; PhysRegInfo RI = AnalyzePhysRegInBundle(*FoldMI, Reg, &TRI); if (RI.FullyDefined) continue; // FoldMI does not define this physreg. Remove the LI segment. assert(MO->isDead() && ""Cannot fold physreg def""); SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot(); LIS.removePhysRegDefAt(Reg, Idx); } int FI; if (TII.isStoreToStackSlot(*MI, FI) && HSpiller.rmFromMergeableSpills(*MI, FI)) --NumSpills; LIS.ReplaceMachineInstrInMaps(*MI, *FoldMI); // Update the call site info. if (MI->isCandidateForCallSiteEntry()) MI->getMF()->moveCallSiteInfo(MI, FoldMI); MI->eraseFromParent(); // Insert any new instructions other than FoldMI into the LIS maps. assert(!MIS.empty() && ""Unexpected empty span of instructions!""); for (MachineInstr &MI : MIS) if (&MI != FoldMI) LIS.InsertMachineInstrInMaps(MI); // TII.foldMemoryOperand may have left some implicit operands on the // instruction. Strip them. if (ImpReg) for (unsigned i = FoldMI->getNumOperands(); i; --i) { MachineOperand &MO = FoldMI->getOperand(i - 1); if (!MO.isReg() || !MO.isImplicit()) break; if (MO.getReg() == ImpReg) FoldMI->RemoveOperand(i - 1); } LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MIS.end(), LIS, ""folded"")); if (!WasCopy) ++NumFolded; else if (Ops.front().second == 0) { ++NumSpills; HSpiller.addToMergeableSpills(*FoldMI, StackSlot, Original); } else ++NumReloads; return true; } void InlineSpiller::insertReload(Register NewVReg, SlotIndex Idx, MachineBasicBlock::iterator MI) { MachineBasicBlock &MBB = *MI->getParent(); MachineInstrSpan MIS(MI, &MBB); TII.loadRegFromStackSlot(MBB, MI, NewVReg, StackSlot, MRI.getRegClass(NewVReg), &TRI); LIS.InsertMachineInstrRangeInMaps(MIS.begin(), MI); LLVM_DEBUG(dumpMachineInstrRangeWithSlotIndex(MIS.begin(), MI, LIS, ""reload"", NewVReg)); ++NumReloads; } /// Check if \\p Def fully defines a VReg with an undefined value. /// If that's the case, that means the value of VReg is actually /// not relevant. static bool isRealSpill(const MachineInstr &Def) { if (!Def.isImplicitDef()) return true; assert(Def.getNumOperands() == 1 && ""Implicit def with more than one definition""); // We can say that the VReg defined by Def is undef, only if it is // fully defined by Def. Otherwise, some of the lanes may not be // undef and the value of the VReg matters. return Def.getOperand(0).getSubReg(); } /// insertSpill - Insert a spill of NewVReg after MI. void InlineSpiller::insertSpill(Register NewVReg, bool isKill, MachineBasicBlock::iterator MI) { // Spill are not terminators, so inserting spills after terminators will // violate invariants in MachineVerifier. assert(!MI->isTerminator() && ""Inserting a spill after a terminator""); MachineBasicBlock &MBB = *MI->getParent(); MachineInstrSpan MIS(MI, &MBB); MachineBasicBlock::iterator SpillBefore = std::next(MI); bool IsRealSpill = isRealSpill(*MI); if (IsRealSpill) TII.storeRegToStackSlot(MBB, SpillBefore, NewVReg, isKill, StackSlot, MRI.getRegClass(NewVReg), &TRI); else // Don't spill undef value. // Anything works for undef, in particular keeping the memory // uninitialized is a viable option and it saves code size and // run time. BuildMI(MBB, SpillBefore, MI->getDebugLoc(), TII.get(TargetOpcode::KILL)) .addReg(NewVReg, getKillRegState(isKill)); MachineBasicBlock::iterator Spill = std::next(MI); LIS.InsertMachineInstrRangeInMaps(Spill, MIS.end()); LLVM_DEBUG( dumpMachineInstrRangeWithSlotIndex(Spill, MIS.end(), LIS, ""spill"")); ++NumSpills; if (IsRealSpill) HSpiller.addToMergeableSpills(*Spill, StackSlot, Original); } /// spillAroundUses - insert spill code around each use of Reg. void InlineSpiller::spillAroundUses(Register Reg) { LLVM_DEBUG(dbgs() << ""spillAroundUses "" << printReg(Reg) << '\\n'); LiveInterval &OldLI = LIS.getInterval(Reg); // Iterate over instructions using Reg. for (MachineRegisterInfo::reg_bundle_iterator RegI = MRI.reg_bundle_begin(Reg), E = MRI.reg_bundle_end(); RegI != E; ) { MachineInstr *MI = &*(RegI++); // Debug values are not allowed to affect codegen. if (MI->isDebugValue()) { // Modify DBG_VALUE now that the value is in a spill slot. MachineBasicBlock *MBB = MI->getParent(); LLVM_DEBUG(dbgs() << ""Modifying debug info due to spill:\\t"" << *MI); buildDbgValueForSpill(*MBB, MI, *MI, StackSlot); MBB->erase(MI); continue; } assert(!MI->isDebugInstr() && ""Did not expect to find a use in debug "" ""instruction that isn't a DBG_VALUE""); // Ignore copies to/from snippets. We'll delete them. if (SnippetCopies.count(MI)) continue; // Stack slot accesses may coalesce away. if (coalesceStackAccess(MI, Reg)) continue; // Analyze instruction. SmallVector, 8> Ops; VirtRegInfo RI = AnalyzeVirtRegInBundle(*MI, Reg, &Ops); // Find the slot index where this instruction reads and writes OldLI. // This is usually the def slot, except for tied early clobbers. SlotIndex Idx = LIS.getInstructionIndex(*MI).getRegSlot(); if (VNInfo *VNI = OldLI.getVNInfoAt(Idx.getRegSlot(true))) if (SlotIndex::isSameInstr(Idx, VNI->def)) Idx = VNI->def; // Check for a sibling copy. Register SibReg = isFullCopyOf(*MI, Reg); if (SibReg && isSibling(SibReg)) { // This may actually be a copy between snippets. if (isRegToSpill(SibReg)) { LLVM_DEBUG(dbgs() << ""Found new snippet copy: "" << *MI); SnippetCopies.insert(MI); continue; } if (RI.Writes) { if (hoistSpillInsideBB(OldLI, *MI)) { // This COPY is now dead, the value is already in the stack slot. MI->getOperand(0).setIsDead(); DeadDefs.push_back(MI); continue; } } else { // This is a reload for a sib-reg copy. Drop spills downstream. LiveInterval &SibLI = LIS.getInterval(SibReg); eliminateRedundantSpills(SibLI, SibLI.getVNInfoAt(Idx)); // The COPY will fold to a reload below. } } // Attempt to fold memory ops. if (foldMemoryOperand(Ops)) continue; // Create a new virtual register for spill/fill. // FIXME: Infer regclass from instruction alone. Register NewVReg = Edit->createFrom(Reg); if (RI.Reads) insertReload(NewVReg, Idx, MI); // Rewrite instruction operands. bool hasLiveDef = false; for (const auto &OpPair : Ops) { MachineOperand &MO = OpPair.first->getOperand(OpPair.second); MO.setReg(NewVReg); if (MO.isUse()) { if (!OpPair.first->isRegTiedToDefOperand(OpPair.second)) MO.setIsKill(); } else { if (!MO.isDead()) hasLiveDef = true; } } LLVM_DEBUG(dbgs() << ""\\trewrite: "" << Idx << '\\t' << *MI << '\\n'); // FIXME: Use a second vreg if instruction has no tied ops. if (RI.Writes) if (hasLiveDef) insertSpill(NewVReg, true, MI); } } /// spillAll - Spill all registers remaining after rematerialization. void InlineSpiller::spillAll() { // Update LiveStacks now that we are committed to spilling. if (StackSlot == VirtRegMap::NO_STACK_SLOT) { StackSlot = VRM.assignVirt2StackSlot(Original); StackInt = &LSS.getOrCreateInterval(StackSlot, MRI.getRegClass(Original)); StackInt->getNextValue(SlotIndex(), LSS.getVNInfoAllocator()); } else StackInt = &LSS.getInterval(StackSlot); if (Original != Edit->getReg()) VRM.assignVirt2StackSlot(Edit->getReg(), StackSlot); assert(StackInt->getNumValNums() == 1 && ""Bad stack interval values""); for (Register Reg : RegsToSpill) StackInt->MergeSegmentsInAsValue(LIS.getInterval(Reg), StackInt->getValNumInfo(0)); LLVM_DEBUG(dbgs() << ""Merged spilled regs: "" << *StackInt << '\\n'); // Spill around uses of all RegsToSpill. for (Register Reg : RegsToSpill) spillAroundUses(Reg); // Hoisted spills may cause dead code. if (!DeadDefs.empty()) { LLVM_DEBUG(dbgs() << ""Eliminating "" << DeadDefs.size() << "" dead defs\\n""); Edit->eliminateDeadDefs(DeadDefs, RegsToSpill, AA); } // Finally delete the SnippetCopies. for (Register Reg : RegsToSpill) { for (MachineRegisterInfo::reg_instr_iterator RI = MRI.reg_instr_begin(Reg), E = MRI.reg_instr_end(); RI != E; ) { MachineInstr &MI = *(RI++); assert(SnippetCopies.count(&MI) && ""Remaining use wasn't a snippet copy""); // FIXME: Do this with a LiveRangeEdit callback. LIS.RemoveMachineInstrFromMaps(MI); MI.eraseFromParent(); } } // Delete all spilled registers. for (Register Reg : RegsToSpill) Edit->eraseVirtReg(Reg); } void InlineSpiller::spill(LiveRangeEdit &edit) { ++NumSpilledRanges; Edit = &edit; assert(!Register::isStackSlot(edit.getReg()) && ""Trying to spill a stack slot.""); // Share a stack slot among all descendants of Original. Original = VRM.getOriginal(edit.getReg()); StackSlot = VRM.getStackSlot(Original); StackInt = nullptr; LLVM_DEBUG(dbgs() << ""Inline spilling "" << TRI.getRegClassName(MRI.getRegClass(edit.getReg())) << ':' << edit.getParent() << ""\\nFrom original "" << printReg(Original) << '\\n'); assert(edit.getParent().isSpillable() && ""Attempting to spill already spilled value.""); assert(DeadDefs.empty() && ""Previous spill didn't remove dead defs""); collectRegsToSpill(); reMaterializeAll(); // Remat may handle everything. if (!RegsToSpill.empty()) spillAll(); Edit->calculateRegClassAndHint(MF, Loops, MBFI); } /// Optimizations after all the reg selections and spills are done. void InlineSpiller::postOptimization() { HSpiller.hoistAllSpills(); } /// When a spill is inserted, add the spill to MergeableSpills map. void HoistSpillHelper::addToMergeableSpills(MachineInstr &Spill, int StackSlot, unsigned Original) { BumpPtrAllocator &Allocator = LIS.getVNInfoAllocator(); LiveInterval &OrigLI = LIS.getInterval(Original); // save a copy of LiveInterval in StackSlotToOrigLI because the original // LiveInterval may be cleared after all its references are spilled. if (StackSlotToOrigLI.find(StackSlot) == StackSlotToOrigLI.end()) { auto LI = std::make_unique(OrigLI.reg(), OrigLI.weight()); LI->assign(OrigLI, Allocator); StackSlotToOrigLI[StackSlot] = std::move(LI); } SlotIndex Idx = LIS.getInstructionIndex(Spill); VNInfo *OrigVNI = StackSlotToOrigLI[StackSlot]->getVNInfoAt(Idx.getRegSlot()); std::pair MIdx = std::make_pair(StackSlot, OrigVNI); MergeableSpills[MIdx].insert(&Spill); } /// When a spill is removed, remove the spill from MergeableSpills map. /// Return true if the spill is removed successfully. bool HoistSpillHelper::rmFromMergeableSpills(MachineInstr &Spill, int StackSlot) { auto It = StackSlotToOrigLI.find(StackSlot); if (It == StackSlotToOrigLI.end()) return false; SlotIndex Idx = LIS.getInstructionIndex(Spill); VNInfo *OrigVNI = It->second->getVNInfoAt(Idx.getRegSlot()); std::pair MIdx = std::make_pair(StackSlot, OrigVNI); return MergeableSpills[MIdx].erase(&Spill); } /// Check BB to see if it is a possible target BB to place a hoisted spill, /// i.e., there should be a living sibling of OrigReg at the insert point. bool HoistSpillHelper::isSpillCandBB(LiveInterval &OrigLI, VNInfo &OrigVNI, MachineBasicBlock &BB, Register &LiveReg) { SlotIndex Idx; Register OrigReg = OrigLI.reg(); MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, BB); if (MI != BB.end()) Idx = LIS.getInstructionIndex(*MI); else Idx = LIS.getMBBEndIdx(&BB).getPrevSlot(); SmallSetVector &Siblings = Virt2SiblingsMap[OrigReg]; assert(OrigLI.getVNInfoAt(Idx) == &OrigVNI && ""Unexpected VNI""); for (const Register &SibReg : Siblings) { LiveInterval &LI = LIS.getInterval(SibReg); VNInfo *VNI = LI.getVNInfoAt(Idx); if (VNI) { LiveReg = SibReg; return true; } } return false; } /// Remove redundant spills in the same BB. Save those redundant spills in /// SpillsToRm, and save the spill to keep and its BB in SpillBBToSpill map. void HoistSpillHelper::rmRedundantSpills( SmallPtrSet &Spills, SmallVectorImpl &SpillsToRm, DenseMap &SpillBBToSpill) { // For each spill saw, check SpillBBToSpill[] and see if its BB already has // another spill inside. If a BB contains more than one spill, only keep the // earlier spill with smaller SlotIndex. for (const auto CurrentSpill : Spills) { MachineBasicBlock *Block = CurrentSpill->getParent(); MachineDomTreeNode *Node = MDT.getBase().getNode(Block); MachineInstr *PrevSpill = SpillBBToSpill[Node]; if (PrevSpill) { SlotIndex PIdx = LIS.getInstructionIndex(*PrevSpill); SlotIndex CIdx = LIS.getInstructionIndex(*CurrentSpill); MachineInstr *SpillToRm = (CIdx > PIdx) ? CurrentSpill : PrevSpill; MachineInstr *SpillToKeep = (CIdx > PIdx) ? PrevSpill : CurrentSpill; SpillsToRm.push_back(SpillToRm); SpillBBToSpill[MDT.getBase().getNode(Block)] = SpillToKeep; } else { SpillBBToSpill[MDT.getBase().getNode(Block)] = CurrentSpill; } } for (const auto SpillToRm : SpillsToRm) Spills.erase(SpillToRm); } /// Starting from \\p Root find a top-down traversal order of the dominator /// tree to visit all basic blocks containing the elements of \\p Spills. /// Redundant spills will be found and put into \\p SpillsToRm at the same /// time. \\p SpillBBToSpill will be populated as part of the process and /// maps a basic block to the first store occurring in the basic block. /// \\post SpillsToRm.union(Spills\\@post) == Spills\\@pre void HoistSpillHelper::getVisitOrders( MachineBasicBlock *Root, SmallPtrSet &Spills, SmallVectorImpl &Orders, SmallVectorImpl &SpillsToRm, DenseMap &SpillsToKeep, DenseMap &SpillBBToSpill) { // The set contains all the possible BB nodes to which we may hoist // original spills. SmallPtrSet WorkSet; // Save the BB nodes on the path from the first BB node containing // non-redundant spill to the Root node. SmallPtrSet NodesOnPath; // All the spills to be hoisted must originate from a single def instruction // to the OrigReg. It means the def instruction should dominate all the spills // to be hoisted. We choose the BB where the def instruction is located as // the Root. MachineDomTreeNode *RootIDomNode = MDT[Root]->getIDom(); // For every node on the dominator tree with spill, walk up on the dominator // tree towards the Root node until it is reached. If there is other node // containing spill in the middle of the path, the previous spill saw will // be redundant and the node containing it will be removed. All the nodes on // the path starting from the first node with non-redundant spill to the Root // node will be added to the WorkSet, which will contain all the possible // locations where spills may be hoisted to after the loop below is done. for (const auto Spill : Spills) { MachineBasicBlock *Block = Spill->getParent(); MachineDomTreeNode *Node = MDT[Block]; MachineInstr *SpillToRm = nullptr; while (Node != RootIDomNode) { // If Node dominates Block, and it already contains a spill, the spill in // Block will be redundant. if (Node != MDT[Block] && SpillBBToSpill[Node]) { SpillToRm = SpillBBToSpill[MDT[Block]]; break; /// If we see the Node already in WorkSet, the path from the Node to /// the Root node must already be traversed by another spill. /// Then no need to repeat. } else if (WorkSet.count(Node)) { break; } else { NodesOnPath.insert(Node); } Node = Node->getIDom(); } if (SpillToRm) { SpillsToRm.push_back(SpillToRm); } else { // Add a BB containing the original spills to SpillsToKeep -- i.e., // set the initial status before hoisting start. The value of BBs // containing original spills is set to 0, in order to descriminate // with BBs containing hoisted spills which will be inserted to // SpillsToKeep later during hoisting. SpillsToKeep[MDT[Block]] = 0; WorkSet.insert(NodesOnPath.begin(), NodesOnPath.end()); } NodesOnPath.clear(); } // Sort the nodes in WorkSet in top-down order and save the nodes // in Orders. Orders will be used for hoisting in runHoistSpills. unsigned idx = 0; Orders.push_back(MDT.getBase().getNode(Root)); do { MachineDomTreeNode *Node = Orders[idx++]; for (MachineDomTreeNode *Child : Node->children()) { if (WorkSet.count(Child)) Orders.push_back(Child); } } while (idx != Orders.size()); assert(Orders.size() == WorkSet.size() && ""Orders have different size with WorkSet""); #ifndef NDEBUG LLVM_DEBUG(dbgs() << ""Orders size is "" << Orders.size() << ""\\n""); SmallVector::reverse_iterator RIt = Orders.rbegin(); for (; RIt != Orders.rend(); RIt++) LLVM_DEBUG(dbgs() << ""BB"" << (*RIt)->getBlock()->getNumber() << "",""); LLVM_DEBUG(dbgs() << ""\\n""); #endif } /// Try to hoist spills according to BB hotness. The spills to removed will /// be saved in \\p SpillsToRm. The spills to be inserted will be saved in /// \\p SpillsToIns. void HoistSpillHelper::runHoistSpills( LiveInterval &OrigLI, VNInfo &OrigVNI, SmallPtrSet &Spills, SmallVectorImpl &SpillsToRm, DenseMap &SpillsToIns) { // Visit order of dominator tree nodes. SmallVector Orders; // SpillsToKeep contains all the nodes where spills are to be inserted // during hoisting. If the spill to be inserted is an original spill // (not a hoisted one), the value of the map entry is 0. If the spill // is a hoisted spill, the value of the map entry is the VReg to be used // as the source of the spill. DenseMap SpillsToKeep; // Map from BB to the first spill inside of it. DenseMap SpillBBToSpill; rmRedundantSpills(Spills, SpillsToRm, SpillBBToSpill); MachineBasicBlock *Root = LIS.getMBBFromIndex(OrigVNI.def); getVisitOrders(Root, Spills, Orders, SpillsToRm, SpillsToKeep, SpillBBToSpill); // SpillsInSubTreeMap keeps the map from a dom tree node to a pair of // nodes set and the cost of all the spills inside those nodes. // The nodes set are the locations where spills are to be inserted // in the subtree of current node. using NodesCostPair = std::pair, BlockFrequency>; DenseMap SpillsInSubTreeMap; // Iterate Orders set in reverse order, which will be a bottom-up order // in the dominator tree. Once we visit a dom tree node, we know its // children have already been visited and the spill locations in the // subtrees of all the children have been determined. SmallVector::reverse_iterator RIt = Orders.rbegin(); for (; RIt != Orders.rend(); RIt++) { MachineBasicBlock *Block = (*RIt)->getBlock(); // If Block contains an original spill, simply continue. if (SpillsToKeep.find(*RIt) != SpillsToKeep.end() && !SpillsToKeep[*RIt]) { SpillsInSubTreeMap[*RIt].first.insert(*RIt); // SpillsInSubTreeMap[*RIt].second contains the cost of spill. SpillsInSubTreeMap[*RIt].second = MBFI.getBlockFreq(Block); continue; } // Collect spills in subtree of current node (*RIt) to // SpillsInSubTreeMap[*RIt].first. for (MachineDomTreeNode *Child : (*RIt)->children()) { if (SpillsInSubTreeMap.find(Child) == SpillsInSubTreeMap.end()) continue; // The stmt ""SpillsInSubTree = SpillsInSubTreeMap[*RIt].first"" below // should be placed before getting the begin and end iterators of // SpillsInSubTreeMap[Child].first, or else the iterators may be // invalidated when SpillsInSubTreeMap[*RIt] is seen the first time // and the map grows and then the original buckets in the map are moved. SmallPtrSet &SpillsInSubTree = SpillsInSubTreeMap[*RIt].first; BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second; SubTreeCost += SpillsInSubTreeMap[Child].second; auto BI = SpillsInSubTreeMap[Child].first.begin(); auto EI = SpillsInSubTreeMap[Child].first.end(); SpillsInSubTree.insert(BI, EI); SpillsInSubTreeMap.erase(Child); } SmallPtrSet &SpillsInSubTree = SpillsInSubTreeMap[*RIt].first; BlockFrequency &SubTreeCost = SpillsInSubTreeMap[*RIt].second; // No spills in subtree, simply continue. if (SpillsInSubTree.empty()) continue; // Check whether Block is a possible candidate to insert spill. Register LiveReg; if (!isSpillCandBB(OrigLI, OrigVNI, *Block, LiveReg)) continue; // If there are multiple spills that could be merged, bias a little // to hoist the spill. BranchProbability MarginProb = (SpillsInSubTree.size() > 1) ? BranchProbability(9, 10) : BranchProbability(1, 1); if (SubTreeCost > MBFI.getBlockFreq(Block) * MarginProb) { // Hoist: Move spills to current Block. for (const auto SpillBB : SpillsInSubTree) { // When SpillBB is a BB contains original spill, insert the spill // to SpillsToRm. if (SpillsToKeep.find(SpillBB) != SpillsToKeep.end() && !SpillsToKeep[SpillBB]) { MachineInstr *SpillToRm = SpillBBToSpill[SpillBB]; SpillsToRm.push_back(SpillToRm); } // SpillBB will not contain spill anymore, remove it from SpillsToKeep. SpillsToKeep.erase(SpillBB); } // Current Block is the BB containing the new hoisted spill. Add it to // SpillsToKeep. LiveReg is the source of the new spill. SpillsToKeep[*RIt] = LiveReg; LLVM_DEBUG({ dbgs() << ""spills in BB: ""; for (const auto Rspill : SpillsInSubTree) dbgs() << Rspill->getBlock()->getNumber() << "" ""; dbgs() << ""were promoted to BB"" << (*RIt)->getBlock()->getNumber() << ""\\n""; }); SpillsInSubTree.clear(); SpillsInSubTree.insert(*RIt); SubTreeCost = MBFI.getBlockFreq(Block); } } // For spills in SpillsToKeep with LiveReg set (i.e., not original spill), // save them to SpillsToIns. for (const auto &Ent : SpillsToKeep) { if (Ent.second) SpillsToIns[Ent.first->getBlock()] = Ent.second; } } /// For spills with equal values, remove redundant spills and hoist those left /// to less hot spots. /// /// Spills with equal values will be collected into the same set in /// MergeableSpills when spill is inserted. These equal spills are originated /// from the same defining instruction and are dominated by the instruction. /// Before hoisting all the equal spills, redundant spills inside in the same /// BB are first marked to be deleted. Then starting from the spills left, walk /// up on the dominator tree towards the Root node where the define instruction /// is located, mark the dominated spills to be deleted along the way and /// collect the BB nodes on the path from non-dominated spills to the define /// instruction into a WorkSet. The nodes in WorkSet are the candidate places /// where we are considering to hoist the spills. We iterate the WorkSet in /// bottom-up order, and for each node, we will decide whether to hoist spills /// inside its subtree to that node. In this way, we can get benefit locally /// even if hoisting all the equal spills to one cold place is impossible. void HoistSpillHelper::hoistAllSpills() { SmallVector NewVRegs; LiveRangeEdit Edit(nullptr, NewVRegs, MF, LIS, &VRM, this); for (unsigned i = 0, e = MRI.getNumVirtRegs(); i != e; ++i) { Register Reg = Register::index2VirtReg(i); Register Original = VRM.getPreSplitReg(Reg); if (!MRI.def_empty(Reg)) Virt2SiblingsMap[Original].insert(Reg); } // Each entry in MergeableSpills contains a spill set with equal values. for (auto &Ent : MergeableSpills) { int Slot = Ent.first.first; LiveInterval &OrigLI = *StackSlotToOrigLI[Slot]; VNInfo *OrigVNI = Ent.first.second; SmallPtrSet &EqValSpills = Ent.second; if (Ent.second.empty()) continue; LLVM_DEBUG({ dbgs() << ""\\nFor Slot"" << Slot << "" and VN"" << OrigVNI->id << "":\\n"" << ""Equal spills in BB: ""; for (const auto spill : EqValSpills) dbgs() << spill->getParent()->getNumber() << "" ""; dbgs() << ""\\n""; }); // SpillsToRm is the spill set to be removed from EqValSpills. SmallVector SpillsToRm; // SpillsToIns is the spill set to be newly inserted after hoisting. DenseMap SpillsToIns; runHoistSpills(OrigLI, *OrigVNI, EqValSpills, SpillsToRm, SpillsToIns); LLVM_DEBUG({ dbgs() << ""Finally inserted spills in BB: ""; for (const auto &Ispill : SpillsToIns) dbgs() << Ispill.first->getNumber() << "" ""; dbgs() << ""\\nFinally removed spills in BB: ""; for (const auto Rspill : SpillsToRm) dbgs() << Rspill->getParent()->getNumber() << "" ""; dbgs() << ""\\n""; }); // Stack live range update. LiveInterval &StackIntvl = LSS.getInterval(Slot); if (!SpillsToIns.empty() || !SpillsToRm.empty()) StackIntvl.MergeValueInAsValue(OrigLI, OrigVNI, StackIntvl.getValNumInfo(0)); // Insert hoisted spills. for (auto const &Insert : SpillsToIns) { MachineBasicBlock *BB = Insert.first; Register LiveReg = Insert.second; MachineBasicBlock::iterator MI = IPA.getLastInsertPointIter(OrigLI, *BB); TII.storeRegToStackSlot(*BB, MI, LiveReg, false, Slot, MRI.getRegClass(LiveReg), &TRI); LIS.InsertMachineInstrRangeInMaps(std::prev(MI), MI); ++NumSpills; } // Remove redundant spills or change them to dead instructions. NumSpills -= SpillsToRm.size(); for (auto const RMEnt : SpillsToRm) { RMEnt->setDesc(TII.get(TargetOpcode::KILL)); for (unsigned i = RMEnt->getNumOperands(); i; --i) { MachineOperand &MO = RMEnt->getOperand(i - 1); if (MO.isReg() && MO.isImplicit() && MO.isDef() && !MO.isDead()) RMEnt->RemoveOperand(i - 1); } } Edit.eliminateDeadDefs(SpillsToRm, None, AA); } } /// For VirtReg clone, the \\p New register should have the same physreg or /// stackslot as the \\p old register. void HoistSpillHelper::LRE_DidCloneVirtReg(unsigned New, unsigned Old) { if (VRM.hasPhys(Old)) VRM.assignVirt2Phys(New, VRM.getPhys(Old)); else if (VRM.getStackSlot(Old) != VirtRegMap::NO_STACK_SLOT) VRM.assignVirt2StackSlot(New, VRM.getStackSlot(Old)); else llvm_unreachable(""VReg should be assigned either physreg or stackslot""); } ",16138,True,2997.3211319660845,median "//===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for constructing a dwarf compile unit. // //===----------------------------------------------------------------------===// #include ""DwarfUnit.h"" #include ""AddressPool.h"" #include ""DwarfCompileUnit.h"" #include ""DwarfDebug.h"" #include ""DwarfExpression.h"" #include ""llvm/ADT/APFloat.h"" #include ""llvm/ADT/APInt.h"" #include ""llvm/ADT/None.h"" #include ""llvm/ADT/iterator_range.h"" #include ""llvm/CodeGen/MachineFunction.h"" #include ""llvm/CodeGen/MachineOperand.h"" #include ""llvm/CodeGen/TargetLoweringObjectFile.h"" #include ""llvm/CodeGen/TargetRegisterInfo.h"" #include ""llvm/CodeGen/TargetSubtargetInfo.h"" #include ""llvm/IR/Constants.h"" #include ""llvm/IR/DataLayout.h"" #include ""llvm/IR/GlobalValue.h"" #include ""llvm/IR/Metadata.h"" #include ""llvm/MC/MCAsmInfo.h"" #include ""llvm/MC/MCDwarf.h"" #include ""llvm/MC/MCSection.h"" #include ""llvm/MC/MCStreamer.h"" #include ""llvm/MC/MachineLocation.h"" #include ""llvm/Support/Casting.h"" #include ""llvm/Support/CommandLine.h"" #include #include #include #include using namespace llvm; #define DEBUG_TYPE ""dwarfdebug"" static cl::opt GenerateDwarfTypeUnits(""generate-type-units"", cl::Hidden, cl::desc(""Generate DWARF4 type units.""), cl::init(false)); DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU, DIELoc &DIE) : DwarfExpression(AP.getDwarfVersion()), AP(AP), DU(DU), DIE(DIE) {} void DIEDwarfExpression::emitOp(uint8_t Op, const char* Comment) { DU.addUInt(DIE, dwarf::DW_FORM_data1, Op); } void DIEDwarfExpression::emitSigned(int64_t Value) { DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value); } void DIEDwarfExpression::emitUnsigned(uint64_t Value) { DU.addUInt(DIE, dwarf::DW_FORM_udata, Value); } bool DIEDwarfExpression::isFrameRegister(const TargetRegisterInfo &TRI, unsigned MachineReg) { return MachineReg == TRI.getFrameRegister(*AP.MF); } DwarfUnit::DwarfUnit(dwarf::Tag UnitTag, const DICompileUnit *Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU) : DIEUnit(A->getDwarfVersion(), A->MAI->getCodePointerSize(), UnitTag), CUNode(Node), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr) { } DwarfTypeUnit::DwarfTypeUnit(DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, MCDwarfDwoLineTable *SplitLineTable) : DwarfUnit(dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU), SplitLineTable(SplitLineTable) { if (SplitLineTable) addSectionOffset(getUnitDie(), dwarf::DW_AT_stmt_list, 0); } DwarfUnit::~DwarfUnit() { for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j) DIEBlocks[j]->~DIEBlock(); for (unsigned j = 0, M = DIELocs.size(); j < M; ++j) DIELocs[j]->~DIELoc(); } int64_t DwarfUnit::getDefaultLowerBound() const { switch (getLanguage()) { default: break; // The languages below have valid values in all DWARF versions. case dwarf::DW_LANG_C: case dwarf::DW_LANG_C89: case dwarf::DW_LANG_C_plus_plus: return 0; case dwarf::DW_LANG_Fortran77: case dwarf::DW_LANG_Fortran90: return 1; // The languages below have valid values only if the DWARF version >= 3. case dwarf::DW_LANG_C99: case dwarf::DW_LANG_ObjC: case dwarf::DW_LANG_ObjC_plus_plus: if (DD->getDwarfVersion() >= 3) return 0; break; case dwarf::DW_LANG_Fortran95: if (DD->getDwarfVersion() >= 3) return 1; break; // Starting with DWARF v4, all defined languages have valid values. case dwarf::DW_LANG_D: case dwarf::DW_LANG_Java: case dwarf::DW_LANG_Python: case dwarf::DW_LANG_UPC: if (DD->getDwarfVersion() >= 4) return 0; break; case dwarf::DW_LANG_Ada83: case dwarf::DW_LANG_Ada95: case dwarf::DW_LANG_Cobol74: case dwarf::DW_LANG_Cobol85: case dwarf::DW_LANG_Modula2: case dwarf::DW_LANG_Pascal83: case dwarf::DW_LANG_PLI: if (DD->getDwarfVersion() >= 4) return 1; break; // The languages below are new in DWARF v5. case dwarf::DW_LANG_BLISS: case dwarf::DW_LANG_C11: case dwarf::DW_LANG_C_plus_plus_03: case dwarf::DW_LANG_C_plus_plus_11: case dwarf::DW_LANG_C_plus_plus_14: case dwarf::DW_LANG_Dylan: case dwarf::DW_LANG_Go: case dwarf::DW_LANG_Haskell: case dwarf::DW_LANG_OCaml: case dwarf::DW_LANG_OpenCL: case dwarf::DW_LANG_RenderScript: case dwarf::DW_LANG_Rust: case dwarf::DW_LANG_Swift: if (DD->getDwarfVersion() >= 5) return 0; break; case dwarf::DW_LANG_Fortran03: case dwarf::DW_LANG_Fortran08: case dwarf::DW_LANG_Julia: case dwarf::DW_LANG_Modula3: if (DD->getDwarfVersion() >= 5) return 1; break; } return -1; } /// Check whether the DIE for this MDNode can be shared across CUs. bool DwarfUnit::isShareableAcrossCUs(const DINode *D) const { // When the MDNode can be part of the type system, the DIE can be shared // across CUs. // Combining type units and cross-CU DIE sharing is lower value (since // cross-CU DIE sharing is used in LTO and removes type redundancy at that // level already) but may be implementable for some value in projects // building multiple independent libraries with LTO and then linking those // together. if (isDwoUnit() && !DD->shareAcrossDWOCUs()) return false; return (isa(D) || (isa(D) && !cast(D)->isDefinition())) && !GenerateDwarfTypeUnits; } DIE *DwarfUnit::getDIE(const DINode *D) const { if (isShareableAcrossCUs(D)) return DU->getDIE(D); return MDNodeToDieMap.lookup(D); } void DwarfUnit::insertDIE(const DINode *Desc, DIE *D) { if (isShareableAcrossCUs(Desc)) { DU->insertDIE(Desc, D); return; } MDNodeToDieMap.insert(std::make_pair(Desc, D)); } void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) { if (DD->getDwarfVersion() >= 4) Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag_present, DIEInteger(1)); else Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_flag, DIEInteger(1)); } void DwarfUnit::addUInt(DIEValueList &Die, dwarf::Attribute Attribute, Optional Form, uint64_t Integer) { if (!Form) Form = DIEInteger::BestForm(false, Integer); assert(Form != dwarf::DW_FORM_implicit_const && ""DW_FORM_implicit_const is used only for signed integers""); Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer)); } void DwarfUnit::addUInt(DIEValueList &Block, dwarf::Form Form, uint64_t Integer) { addUInt(Block, (dwarf::Attribute)0, Form, Integer); } void DwarfUnit::addSInt(DIEValueList &Die, dwarf::Attribute Attribute, Optional Form, int64_t Integer) { if (!Form) Form = DIEInteger::BestForm(true, Integer); Die.addValue(DIEValueAllocator, Attribute, *Form, DIEInteger(Integer)); } void DwarfUnit::addSInt(DIELoc &Die, Optional Form, int64_t Integer) { addSInt(Die, (dwarf::Attribute)0, Form, Integer); } void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute, StringRef String) { Die.addValue(DIEValueAllocator, Attribute, isDwoUnit() ? dwarf::DW_FORM_GNU_str_index : dwarf::DW_FORM_strp, DIEString(DU->getStringPool().getEntry(*Asm, String))); } DIEValueList::value_iterator DwarfUnit::addLabel(DIEValueList &Die, dwarf::Attribute Attribute, dwarf::Form Form, const MCSymbol *Label) { return Die.addValue(DIEValueAllocator, Attribute, Form, DIELabel(Label)); } void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) { addLabel(Die, (dwarf::Attribute)0, Form, Label); } void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer) { if (DD->getDwarfVersion() >= 4) addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer); else addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer); } unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) { return SplitLineTable ? SplitLineTable->getFile(DirName, FileName) : getCU().getOrCreateSourceID(FileName, DirName); } void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) { if (!DD->useSplitDwarf()) { addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); addLabel(Die, dwarf::DW_FORM_udata, Sym); } else { addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DD->getAddressPool().getIndex(Sym)); } } void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi, const MCSymbol *Lo) { Die.addValue(DIEValueAllocator, Attribute, dwarf::DW_FORM_data4, new (DIEValueAllocator) DIEDelta(Hi, Lo)); } void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) { addDIEEntry(Die, Attribute, DIEEntry(Entry)); } void DwarfUnit::addDIETypeSignature(DIE &Die, uint64_t Signature) { // Flag the type unit reference as a declaration so that if it contains // members (implicit special members, static data member definitions, member // declarations for definitions in this CU, etc) consumers don't get confused // and think this is a full definition. addFlag(Die, dwarf::DW_AT_declaration); Die.addValue(DIEValueAllocator, dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8, DIEInteger(Signature)); } void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry Entry) { const DIEUnit *CU = Die.getUnit(); const DIEUnit *EntryCU = Entry.getEntry().getUnit(); if (!CU) // We assume that Die belongs to this CU, if it is not linked to any CU yet. CU = getUnitDie().getUnit(); if (!EntryCU) EntryCU = getUnitDie().getUnit(); Die.addValue(DIEValueAllocator, Attribute, EntryCU == CU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr, Entry); } DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, const DINode *N) { DIE &Die = Parent.addChild(DIE::get(DIEValueAllocator, (dwarf::Tag)Tag)); if (N) insertDIE(N, &Die); return Die; } void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) { Loc->ComputeSize(Asm); DIELocs.push_back(Loc); // Memoize so we can call the destructor later on. Die.addValue(DIEValueAllocator, Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc); } void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIEBlock *Block) { Block->ComputeSize(Asm); DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. Die.addValue(DIEValueAllocator, Attribute, Block->BestForm(), Block); } void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File, StringRef Directory) { if (Line == 0) return; unsigned FileID = getOrCreateSourceID(File, Directory); assert(FileID && ""Invalid file id""); addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); addUInt(Die, dwarf::DW_AT_decl_line, None, Line); } void DwarfUnit::addSourceLine(DIE &Die, const DILocalVariable *V) { assert(V); addSourceLine(Die, V->getLine(), V->getScope()->getFilename(), V->getScope()->getDirectory()); } void DwarfUnit::addSourceLine(DIE &Die, const DIGlobalVariable *G) { assert(G); addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory()); } void DwarfUnit::addSourceLine(DIE &Die, const DISubprogram *SP) { assert(SP); addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory()); } void DwarfUnit::addSourceLine(DIE &Die, const DIType *Ty) { assert(Ty); addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); } void DwarfUnit::addSourceLine(DIE &Die, const DIObjCProperty *Ty) { assert(Ty); addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); } /* Byref variables, in Blocks, are declared by the programmer as ""SomeType VarName;"", but the compiler creates a __Block_byref_x_VarName struct, and gives the variable VarName either the struct, or a pointer to the struct, as its type. This is necessary for various behind-the-scenes things the compiler needs to do with by-reference variables in Blocks. However, as far as the original *programmer* is concerned, the variable should still have type 'SomeType', as originally declared. The function getBlockByrefType dives into the __Block_byref_x_VarName struct to find the original type of the variable, which is then assigned to the variable's Debug Information Entry as its real type. So far, so good. However now the debugger will expect the variable VarName to have the type SomeType. So we need the location attribute for the variable to be an expression that explains to the debugger how to navigate through the pointers and struct to find the actual variable of type SomeType. The following function does just that. We start by getting the ""normal"" location for the variable. This will be the location of either the struct __Block_byref_x_VarName or the pointer to the struct __Block_byref_x_VarName. The struct will look something like: struct __Block_byref_x_VarName { ... struct __Block_byref_x_VarName *forwarding; ... SomeType VarName; ... }; If we are given the struct directly (as our starting point) we need to tell the debugger to: 1). Add the offset of the forwarding field. 2). Follow that pointer to get the real __Block_byref_x_VarName struct to use (the real one may have been copied onto the heap). 3). Add the offset for the field VarName, to find the actual variable. If we started with a pointer to the struct, then we need to dereference that pointer first, before the other steps. Translating this into DWARF ops, we will need to append the following to the current location description for the variable: DW_OP_deref -- optional, if we start with a pointer DW_OP_plus_uconst DW_OP_deref DW_OP_plus_uconst That is what this function does. */ void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die, dwarf::Attribute Attribute, const MachineLocation &Location) { const DIType *Ty = DV.getType(); const DIType *TmpTy = Ty; uint16_t Tag = Ty->getTag(); bool isPointer = false; StringRef varName = DV.getName(); if (Tag == dwarf::DW_TAG_pointer_type) { auto *DTy = cast(Ty); TmpTy = resolve(DTy->getBaseType()); isPointer = true; } // Find the __forwarding field and the variable field in the __Block_byref // struct. DINodeArray Fields = cast(TmpTy)->getElements(); const DIDerivedType *varField = nullptr; const DIDerivedType *forwardingField = nullptr; for (unsigned i = 0, N = Fields.size(); i < N; ++i) { auto *DT = cast(Fields[i]); StringRef fieldName = DT->getName(); if (fieldName == ""__forwarding"") forwardingField = DT; else if (fieldName == varName) varField = DT; } // Get the offsets for the forwarding field and the variable field. unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3; unsigned varFieldOffset = varField->getOffsetInBits() >> 2; // Decode the original location, and use that as the start of the byref // variable's location. DIELoc *Loc = new (DIEValueAllocator) DIELoc; DIEDwarfExpression DwarfExpr(*Asm, *this, *Loc); if (Location.isIndirect()) DwarfExpr.setMemoryLocationKind(); SmallVector Ops; // If we started with a pointer to the __Block_byref... struct, then // the first thing we need to do is dereference the pointer (DW_OP_deref). if (isPointer) Ops.push_back(dwarf::DW_OP_deref); // Next add the offset for the '__forwarding' field: // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in // adding the offset if it's 0. if (forwardingFieldOffset > 0) { Ops.push_back(dwarf::DW_OP_plus_uconst); Ops.push_back(forwardingFieldOffset); } // Now dereference the __forwarding field to get to the real __Block_byref // struct: DW_OP_deref. Ops.push_back(dwarf::DW_OP_deref); // Now that we've got the real __Block_byref... struct, add the offset // for the variable's field to get to the location of the actual variable: // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. if (varFieldOffset > 0) { Ops.push_back(dwarf::DW_OP_plus_uconst); Ops.push_back(varFieldOffset); } DIExpressionCursor Cursor(Ops); const TargetRegisterInfo &TRI = *Asm->MF->getSubtarget().getRegisterInfo(); if (!DwarfExpr.addMachineRegExpression(TRI, Cursor, Location.getReg())) return; DwarfExpr.addExpression(std::move(Cursor)); // Now attach the location information to the DIE. addBlock(Die, Attribute, DwarfExpr.finalize()); } /// Return true if type encoding is unsigned. static bool isUnsignedDIType(DwarfDebug *DD, const DIType *Ty) { if (auto *CTy = dyn_cast(Ty)) { // FIXME: Enums without a fixed underlying type have unknown signedness // here, leading to incorrectly emitted constants. if (CTy->getTag() == dwarf::DW_TAG_enumeration_type) return false; // (Pieces of) aggregate types that get hacked apart by SROA may be // represented by a constant. Encode them as unsigned bytes. return true; } if (auto *DTy = dyn_cast(Ty)) { dwarf::Tag T = (dwarf::Tag)Ty->getTag(); // Encode pointer constants as unsigned bytes. This is used at least for // null pointer constant emission. // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed // here, but accept them for now due to a bug in SROA producing bogus // dbg.values. if (T == dwarf::DW_TAG_pointer_type || T == dwarf::DW_TAG_ptr_to_member_type || T == dwarf::DW_TAG_reference_type || T == dwarf::DW_TAG_rvalue_reference_type) return true; assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type || T == dwarf::DW_TAG_volatile_type || T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_atomic_type); DITypeRef Deriv = DTy->getBaseType(); assert(Deriv && ""Expected valid base type""); return isUnsignedDIType(DD, DD->resolve(Deriv)); } auto *BTy = cast(Ty); unsigned Encoding = BTy->getEncoding(); assert((Encoding == dwarf::DW_ATE_unsigned || Encoding == dwarf::DW_ATE_unsigned_char || Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char || Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || (Ty->getTag() == dwarf::DW_TAG_unspecified_type && Ty->getName() == ""decltype(nullptr)"")) && ""Unsupported encoding""); return Encoding == dwarf::DW_ATE_unsigned || Encoding == dwarf::DW_ATE_unsigned_char || Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || Ty->getTag() == dwarf::DW_TAG_unspecified_type; } void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) { assert(MO.isFPImm() && ""Invalid machine operand!""); DIEBlock *Block = new (DIEValueAllocator) DIEBlock; APFloat FPImm = MO.getFPImm()->getValueAPF(); // Get the raw data form of the floating point. const APInt FltVal = FPImm.bitcastToAPInt(); const char *FltPtr = (const char *)FltVal.getRawData(); int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. bool LittleEndian = Asm->getDataLayout().isLittleEndian(); int Incr = (LittleEndian ? 1 : -1); int Start = (LittleEndian ? 0 : NumBytes - 1); int Stop = (LittleEndian ? NumBytes : -1); // Output the constant to DWARF one byte at a time. for (; Start != Stop; Start += Incr) addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]); addBlock(Die, dwarf::DW_AT_const_value, Block); } void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) { // Pass this down to addConstantValue as an unsigned bag of bits. addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); } void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, const DIType *Ty) { addConstantValue(Die, CI->getValue(), Ty); } void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO, const DIType *Ty) { assert(MO.isImm() && ""Invalid machine operand!""); addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm()); } void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) { // FIXME: This is a bit conservative/simple - it emits negative values always // sign extended to 64 bits rather than minimizing the number of bytes. addUInt(Die, dwarf::DW_AT_const_value, Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val); } void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, const DIType *Ty) { addConstantValue(Die, Val, isUnsignedDIType(DD, Ty)); } void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) { unsigned CIBitWidth = Val.getBitWidth(); if (CIBitWidth <= 64) { addConstantValue(Die, Unsigned, Unsigned ? Val.getZExtValue() : Val.getSExtValue()); return; } DIEBlock *Block = new (DIEValueAllocator) DIEBlock; // Get the raw data form of the large APInt. const uint64_t *Ptr64 = Val.getRawData(); int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. bool LittleEndian = Asm->getDataLayout().isLittleEndian(); // Output the constant to DWARF one byte at a time. for (int i = 0; i < NumBytes; i++) { uint8_t c; if (LittleEndian) c = Ptr64[i / 8] >> (8 * (i & 7)); else c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); addUInt(*Block, dwarf::DW_FORM_data1, c); } addBlock(Die, dwarf::DW_AT_const_value, Block); } void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) { if (!LinkageName.empty()) addString(Die, DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name : dwarf::DW_AT_MIPS_linkage_name, GlobalValue::dropLLVMManglingEscape(LinkageName)); } void DwarfUnit::addTemplateParams(DIE &Buffer, DINodeArray TParams) { // Add template parameters. for (const auto *Element : TParams) { if (auto *TTP = dyn_cast(Element)) constructTemplateTypeParameterDIE(Buffer, TTP); else if (auto *TVP = dyn_cast(Element)) constructTemplateValueParameterDIE(Buffer, TVP); } } /// Add thrown types. void DwarfUnit::addThrownTypes(DIE &Die, DINodeArray ThrownTypes) { for (const auto *Ty : ThrownTypes) { DIE &TT = createAndAddDIE(dwarf::DW_TAG_thrown_type, Die); addType(TT, cast(Ty)); } } DIE *DwarfUnit::getOrCreateContextDIE(const DIScope *Context) { if (!Context || isa(Context)) return &getUnitDie(); if (auto *T = dyn_cast(Context)) return getOrCreateTypeDIE(T); if (auto *NS = dyn_cast(Context)) return getOrCreateNameSpace(NS); if (auto *SP = dyn_cast(Context)) return getOrCreateSubprogramDIE(SP); if (auto *M = dyn_cast(Context)) return getOrCreateModule(M); return getDIE(Context); } DIE *DwarfTypeUnit::createTypeDIE(const DICompositeType *Ty) { auto *Context = resolve(Ty->getScope()); DIE *ContextDIE = getOrCreateContextDIE(Context); if (DIE *TyDIE = getDIE(Ty)) return TyDIE; // Create new type. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); constructTypeDIE(TyDIE, cast(Ty)); updateAcceleratorTables(Context, Ty, TyDIE); return &TyDIE; } DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { if (!TyNode) return nullptr; auto *Ty = cast(TyNode); // DW_TAG_restrict_type is not supported in DWARF2 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2) return getOrCreateTypeDIE(resolve(cast(Ty)->getBaseType())); // DW_TAG_atomic_type is not supported in DWARF < 5 if (Ty->getTag() == dwarf::DW_TAG_atomic_type && DD->getDwarfVersion() < 5) return getOrCreateTypeDIE(resolve(cast(Ty)->getBaseType())); // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. auto *Context = resolve(Ty->getScope()); DIE *ContextDIE = getOrCreateContextDIE(Context); assert(ContextDIE); if (DIE *TyDIE = getDIE(Ty)) return TyDIE; // Create new type. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); updateAcceleratorTables(Context, Ty, TyDIE); if (auto *BT = dyn_cast(Ty)) constructTypeDIE(TyDIE, BT); else if (auto *STy = dyn_cast(Ty)) constructTypeDIE(TyDIE, STy); else if (auto *CTy = dyn_cast(Ty)) { if (GenerateDwarfTypeUnits && !Ty->isForwardDecl()) if (MDString *TypeId = CTy->getRawIdentifier()) { DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy); // Skip updating the accelerator tables since this is not the full type. return &TyDIE; } constructTypeDIE(TyDIE, CTy); } else { constructTypeDIE(TyDIE, cast(Ty)); } return &TyDIE; } void DwarfUnit::updateAcceleratorTables(const DIScope *Context, const DIType *Ty, const DIE &TyDIE) { if (!Ty->getName().empty() && !Ty->isForwardDecl()) { bool IsImplementation = false; if (auto *CT = dyn_cast(Ty)) { // A runtime language of 0 actually means C/C++ and that any // non-negative value is some version of Objective-C/C++. IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete(); } unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0; DD->addAccelType(Ty->getName(), TyDIE, Flags); if (!Context || isa(Context) || isa(Context) || isa(Context)) addGlobalType(Ty, TyDIE, Context); } } void DwarfUnit::addType(DIE &Entity, const DIType *Ty, dwarf::Attribute Attribute) { assert(Ty && ""Trying to add a type that doesn't exist?""); addDIEEntry(Entity, Attribute, DIEEntry(*getOrCreateTypeDIE(Ty))); } std::string DwarfUnit::getParentContextString(const DIScope *Context) const { if (!Context) return """"; // FIXME: Decide whether to implement this for non-C++ languages. if (getLanguage() != dwarf::DW_LANG_C_plus_plus) return """"; std::string CS; SmallVector Parents; while (!isa(Context)) { Parents.push_back(Context); if (Context->getScope()) Context = resolve(Context->getScope()); else // Structure, etc types will have a NULL context if they're at the top // level. break; } // Reverse iterate over our list to go from the outermost construct to the // innermost. for (const DIScope *Ctx : make_range(Parents.rbegin(), Parents.rend())) { StringRef Name = Ctx->getName(); if (Name.empty() && isa(Ctx)) Name = ""(anonymous namespace)""; if (!Name.empty()) { CS += Name; CS += ""::""; } } return CS; } void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIBasicType *BTy) { // Get core information. StringRef Name = BTy->getName(); // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); // An unspecified type only has a name attribute. if (BTy->getTag() == dwarf::DW_TAG_unspecified_type) return; addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, BTy->getEncoding()); uint64_t Size = BTy->getSizeInBits() >> 3; addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); } void DwarfUnit::constructTypeDIE(DIE &Buffer, const DIDerivedType *DTy) { // Get core information. StringRef Name = DTy->getName(); uint64_t Size = DTy->getSizeInBits() >> 3; uint16_t Tag = Buffer.getTag(); // Map to main type, void will not have a type. const DIType *FromTy = resolve(DTy->getBaseType()); if (FromTy) addType(Buffer, FromTy); // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); // Add size if non-zero (derived types might be zero-sized.) if (Size && Tag != dwarf::DW_TAG_pointer_type && Tag != dwarf::DW_TAG_ptr_to_member_type && Tag != dwarf::DW_TAG_reference_type && Tag != dwarf::DW_TAG_rvalue_reference_type) addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); if (Tag == dwarf::DW_TAG_ptr_to_member_type) addDIEEntry( Buffer, dwarf::DW_AT_containing_type, *getOrCreateTypeDIE(resolve(cast(DTy)->getClassType()))); // Add source line info if available and TyDesc is not a forward declaration. if (!DTy->isForwardDecl()) addSourceLine(Buffer, DTy); // If DWARF address space value is other than None, add it for pointer and // reference types as DW_AT_address_class. if (DTy->getDWARFAddressSpace() && (Tag == dwarf::DW_TAG_pointer_type || Tag == dwarf::DW_TAG_reference_type)) addUInt(Buffer, dwarf::DW_AT_address_class, dwarf::DW_FORM_data4, DTy->getDWARFAddressSpace().getValue()); } void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeRefArray Args) { for (unsigned i = 1, N = Args.size(); i < N; ++i) { const DIType *Ty = resolve(Args[i]); if (!Ty) { assert(i == N-1 && ""Unspecified parameter must be the last argument""); createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); } else { DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); addType(Arg, Ty); if (Ty->isArtificial()) addFlag(Arg, dwarf::DW_AT_artificial); } } } void DwarfUnit::constructTypeDIE(DIE &Buffer, const DISubroutineType *CTy) { // Add return type. A void return won't have a type. auto Elements = cast(CTy)->getTypeArray(); if (Elements.size()) if (auto RTy = resolve(Elements[0])) addType(Buffer, RTy); bool isPrototyped = true; if (Elements.size() == 2 && !Elements[1]) isPrototyped = false; constructSubprogramArguments(Buffer, Elements); // Add prototype flag if we're dealing with a C language and the function has // been prototyped. uint16_t Language = getLanguage(); if (isPrototyped && (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || Language == dwarf::DW_LANG_ObjC)) addFlag(Buffer, dwarf::DW_AT_prototyped); // Add a DW_AT_calling_convention if this has an explicit convention. if (CTy->getCC() && CTy->getCC() != dwarf::DW_CC_normal) addUInt(Buffer, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CTy->getCC()); if (CTy->isLValueReference()) addFlag(Buffer, dwarf::DW_AT_reference); if (CTy->isRValueReference()) addFlag(Buffer, dwarf::DW_AT_rvalue_reference); } void DwarfUnit::constructTypeDIE(DIE &Buffer, const DICompositeType *CTy) { // Add name if not anonymous or intermediate type. StringRef Name = CTy->getName(); uint64_t Size = CTy->getSizeInBits() >> 3; uint16_t Tag = Buffer.getTag(); switch (Tag) { case dwarf::DW_TAG_array_type: constructArrayTypeDIE(Buffer, CTy); break; case dwarf::DW_TAG_enumeration_type: constructEnumTypeDIE(Buffer, CTy); break; case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_class_type: { // Add elements to structure type. DINodeArray Elements = CTy->getElements(); for (const auto *Element : Elements) { if (!Element) continue; if (auto *SP = dyn_cast(Element)) getOrCreateSubprogramDIE(SP); else if (auto *DDTy = dyn_cast(Element)) { if (DDTy->getTag() == dwarf::DW_TAG_friend) { DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend); } else if (DDTy->isStaticMember()) { getOrCreateStaticMemberDIE(DDTy); } else { constructMemberDIE(Buffer, DDTy); } } else if (auto *Property = dyn_cast(Element)) { DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer); StringRef PropertyName = Property->getName(); addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); if (Property->getType()) addType(ElemDie, resolve(Property->getType())); addSourceLine(ElemDie, Property); StringRef GetterName = Property->getGetterName(); if (!GetterName.empty()) addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); StringRef SetterName = Property->getSetterName(); if (!SetterName.empty()) addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); if (unsigned PropertyAttributes = Property->getAttributes()) addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None, PropertyAttributes); } } if (CTy->isAppleBlockExtension()) addFlag(Buffer, dwarf::DW_AT_APPLE_block); // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type // inside C++ composite types to point to the base class with the vtable. // Rust uses DW_AT_containing_type to link a vtable to the type // for which it was created. if (auto *ContainingType = resolve(CTy->getVTableHolder())) addDIEEntry(Buffer, dwarf::DW_AT_containing_type, *getOrCreateTypeDIE(ContainingType)); if (CTy->isObjcClassComplete()) addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type); // Add template parameters to a class, structure or union types. // FIXME: The support isn't in the metadata for this yet. if (Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) addTemplateParams(Buffer, CTy->getTemplateParams()); break; } default: break; } // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) { // Add size if non-zero (derived types might be zero-sized.) // TODO: Do we care about size for enum forward declarations? if (Size) addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); else if (!CTy->isForwardDecl()) // Add zero size if it is not a forward declaration. addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0); // If we're a forward decl, say so. if (CTy->isForwardDecl()) addFlag(Buffer, dwarf::DW_AT_declaration); // Add source line info if available. if (!CTy->isForwardDecl()) addSourceLine(Buffer, CTy); // No harm in adding the runtime language to the declaration. unsigned RLang = CTy->getRuntimeLang(); if (RLang) addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, RLang); // Add align info if available. if (uint32_t AlignInBytes = CTy->getAlignInBytes()) addUInt(Buffer, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, AlignInBytes); } } void DwarfUnit::constructTemplateTypeParameterDIE( DIE &Buffer, const DITemplateTypeParameter *TP) { DIE &ParamDIE = createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); // Add the type if it exists, it could be void and therefore no type. if (TP->getType()) addType(ParamDIE, resolve(TP->getType())); if (!TP->getName().empty()) addString(ParamDIE, dwarf::DW_AT_name, TP->getName()); } void DwarfUnit::constructTemplateValueParameterDIE( DIE &Buffer, const DITemplateValueParameter *VP) { DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer); // Add the type if there is one, template template and template parameter // packs will not have a type. if (VP->getTag() == dwarf::DW_TAG_template_value_parameter) addType(ParamDIE, resolve(VP->getType())); if (!VP->getName().empty()) addString(ParamDIE, dwarf::DW_AT_name, VP->getName()); if (Metadata *Val = VP->getValue()) { if (ConstantInt *CI = mdconst::dyn_extract(Val)) addConstantValue(ParamDIE, CI, resolve(VP->getType())); else if (GlobalValue *GV = mdconst::dyn_extract(Val)) { // We cannot describe the location of dllimport'd entities: the // computation of their address requires loads from the IAT. if (!GV->hasDLLImportStorageClass()) { // For declaration non-type template parameters (such as global values // and functions) DIELoc *Loc = new (DIEValueAllocator) DIELoc; addOpAddress(*Loc, Asm->getSymbol(GV)); // Emit DW_OP_stack_value to use the address as the immediate value of // the parameter, rather than a pointer to it. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); addBlock(ParamDIE, dwarf::DW_AT_location, Loc); } } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) { assert(isa(Val)); addString(ParamDIE, dwarf::DW_AT_GNU_template_name, cast(Val)->getString()); } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { addTemplateParams(ParamDIE, cast(Val)); } } } DIE *DwarfUnit::getOrCreateNameSpace(const DINamespace *NS) { // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIE *ContextDIE = getOrCreateContextDIE(NS->getScope()); if (DIE *NDie = getDIE(NS)) return NDie; DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); StringRef Name = NS->getName(); if (!Name.empty()) addString(NDie, dwarf::DW_AT_name, NS->getName()); else Name = ""(anonymous namespace)""; DD->addAccelNamespace(Name, NDie); addGlobalName(Name, NDie, NS->getScope()); if (NS->getExportSymbols()) addFlag(NDie, dwarf::DW_AT_export_symbols); return &NDie; } DIE *DwarfUnit::getOrCreateModule(const DIModule *M) { // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIE *ContextDIE = getOrCreateContextDIE(M->getScope()); if (DIE *MDie = getDIE(M)) return MDie; DIE &MDie = createAndAddDIE(dwarf::DW_TAG_module, *ContextDIE, M); if (!M->getName().empty()) { addString(MDie, dwarf::DW_AT_name, M->getName()); addGlobalName(M->getName(), MDie, M->getScope()); } if (!M->getConfigurationMacros().empty()) addString(MDie, dwarf::DW_AT_LLVM_config_macros, M->getConfigurationMacros()); if (!M->getIncludePath().empty()) addString(MDie, dwarf::DW_AT_LLVM_include_path, M->getIncludePath()); if (!M->getISysRoot().empty()) addString(MDie, dwarf::DW_AT_LLVM_isysroot, M->getISysRoot()); return &MDie; } DIE *DwarfUnit::getOrCreateSubprogramDIE(const DISubprogram *SP, bool Minimal) { // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE (as is the case for member function // declarations). DIE *ContextDIE = Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope())); if (DIE *SPDie = getDIE(SP)) return SPDie; if (auto *SPDecl = SP->getDeclaration()) { if (!Minimal) { // Add subprogram definitions to the CU die directly. ContextDIE = &getUnitDie(); // Build the decl now to ensure it precedes the definition. getOrCreateSubprogramDIE(SPDecl); } } // DW_TAG_inlined_subroutine may refer to this DIE. DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); // Stop here and fill this in later, depending on whether or not this // subprogram turns out to have inlined instances or not. if (SP->isDefinition()) return &SPDie; applySubprogramAttributes(SP, SPDie); return &SPDie; } bool DwarfUnit::applySubprogramDefinitionAttributes(const DISubprogram *SP, DIE &SPDie) { DIE *DeclDie = nullptr; StringRef DeclLinkageName; if (auto *SPDecl = SP->getDeclaration()) { DeclDie = getDIE(SPDecl); assert(DeclDie && ""This DIE should've already been constructed when the "" ""definition DIE was created in "" ""getOrCreateSubprogramDIE""); // Look at the Decl's linkage name only if we emitted it. if (DD->useAllLinkageNames()) DeclLinkageName = SPDecl->getLinkageName(); unsigned DeclID = getOrCreateSourceID(SPDecl->getFilename(), SPDecl->getDirectory()); unsigned DefID = getOrCreateSourceID(SP->getFilename(), SP->getDirectory()); if (DeclID != DefID) addUInt(SPDie, dwarf::DW_AT_decl_file, None, DefID); if (SP->getLine() != SPDecl->getLine()) addUInt(SPDie, dwarf::DW_AT_decl_line, None, SP->getLine()); } // Add function template parameters. addTemplateParams(SPDie, SP->getTemplateParams()); // Add the linkage name if we have one and it isn't in the Decl. StringRef LinkageName = SP->getLinkageName(); assert(((LinkageName.empty() || DeclLinkageName.empty()) || LinkageName == DeclLinkageName) && ""decl has a linkage name and it is different""); if (DeclLinkageName.empty() && // Always emit it for abstract subprograms. (DD->useAllLinkageNames() || DU->getAbstractSPDies().lookup(SP))) addLinkageName(SPDie, LinkageName); if (!DeclDie) return false; // Refer to the function declaration where all the other attributes will be // found. addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie); return true; } void DwarfUnit::applySubprogramAttributes(const DISubprogram *SP, DIE &SPDie, bool SkipSPAttributes) { // If -fdebug-info-for-profiling is enabled, need to emit the subprogram // and its source location. bool SkipSPSourceLocation = SkipSPAttributes && !CUNode->getDebugInfoForProfiling(); if (!SkipSPSourceLocation) if (applySubprogramDefinitionAttributes(SP, SPDie)) return; // Constructors and operators for anonymous aggregates do not have names. if (!SP->getName().empty()) addString(SPDie, dwarf::DW_AT_name, SP->getName()); if (!SkipSPSourceLocation) addSourceLine(SPDie, SP); // Skip the rest of the attributes under -gmlt to save space. if (SkipSPAttributes) return; // Add the prototype if we have a prototype and we have a C like // language. uint16_t Language = getLanguage(); if (SP->isPrototyped() && (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || Language == dwarf::DW_LANG_ObjC)) addFlag(SPDie, dwarf::DW_AT_prototyped); unsigned CC = 0; DITypeRefArray Args; if (const DISubroutineType *SPTy = SP->getType()) { Args = SPTy->getTypeArray(); CC = SPTy->getCC(); } // Add a DW_AT_calling_convention if this has an explicit convention. if (CC && CC != dwarf::DW_CC_normal) addUInt(SPDie, dwarf::DW_AT_calling_convention, dwarf::DW_FORM_data1, CC); // Add a return type. If this is a type like a C/C++ void type we don't add a // return type. if (Args.size()) if (auto Ty = resolve(Args[0])) addType(SPDie, Ty); unsigned VK = SP->getVirtuality(); if (VK) { addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); if (SP->getVirtualIndex() != -1u) { DIELoc *Block = getDIELoc(); addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex()); addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); } ContainingTypeMap.insert( std::make_pair(&SPDie, resolve(SP->getContainingType()))); } if (!SP->isDefinition()) { addFlag(SPDie, dwarf::DW_AT_declaration); // Add arguments. Do not add arguments for subprogram definition. They will // be handled while processing variables. constructSubprogramArguments(SPDie, Args); } addThrownTypes(SPDie, SP->getThrownTypes()); if (SP->isArtificial()) addFlag(SPDie, dwarf::DW_AT_artificial); if (!SP->isLocalToUnit()) addFlag(SPDie, dwarf::DW_AT_external); if (DD->useAppleExtensionAttributes()) { if (SP->isOptimized()) addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); if (unsigned isa = Asm->getISAEncoding()) addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); } if (SP->isLValueReference()) addFlag(SPDie, dwarf::DW_AT_reference); if (SP->isRValueReference()) addFlag(SPDie, dwarf::DW_AT_rvalue_reference); if (SP->isNoReturn()) addFlag(SPDie, dwarf::DW_AT_noreturn); if (SP->isProtected()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (SP->isPrivate()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); else if (SP->isPublic()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (SP->isExplicit()) addFlag(SPDie, dwarf::DW_AT_explicit); if (SP->isMainSubprogram()) addFlag(SPDie, dwarf::DW_AT_main_subprogram); } void DwarfUnit::constructSubrangeDIE(DIE &Buffer, const DISubrange *SR, DIE *IndexTy) { DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy); // The LowerBound value defines the lower bounds which is typically zero for // C/C++. The Count value is the number of elements. Values are 64 bit. If // Count == -1 then the array is unbounded and we do not emit // DW_AT_lower_bound and DW_AT_count attributes. int64_t LowerBound = SR->getLowerBound(); int64_t DefaultLowerBound = getDefaultLowerBound(); int64_t Count = SR->getCount(); if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound) addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound); if (Count != -1) // FIXME: An unbounded array should reference the expression that defines // the array. addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count); } DIE *DwarfUnit::getIndexTyDie() { if (IndexTyDie) return IndexTyDie; // Construct an integer type to use for indexes. IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, getUnitDie()); addString(*IndexTyDie, dwarf::DW_AT_name, ""sizetype""); addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t)); addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, dwarf::DW_ATE_unsigned); return IndexTyDie; } void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, const DICompositeType *CTy) { if (CTy->isVector()) addFlag(Buffer, dwarf::DW_AT_GNU_vector); // Emit the element type. addType(Buffer, resolve(CTy->getBaseType())); // Get an anonymous type for index type. // FIXME: This type should be passed down from the front end // as different languages may have different sizes for indexes. DIE *IdxTy = getIndexTyDie(); // Add subranges to array type. DINodeArray Elements = CTy->getElements(); for (unsigned i = 0, N = Elements.size(); i < N; ++i) { // FIXME: Should this really be such a loose cast? if (auto *Element = dyn_cast_or_null(Elements[i])) if (Element->getTag() == dwarf::DW_TAG_subrange_type) constructSubrangeDIE(Buffer, cast(Element), IdxTy); } } void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, const DICompositeType *CTy) { DINodeArray Elements = CTy->getElements(); // Add enumerators to enumeration type. for (unsigned i = 0, N = Elements.size(); i < N; ++i) { auto *Enum = dyn_cast_or_null(Elements[i]); if (Enum) { DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); StringRef Name = Enum->getName(); addString(Enumerator, dwarf::DW_AT_name, Name); int64_t Value = Enum->getValue(); addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value); } } const DIType *DTy = resolve(CTy->getBaseType()); if (DTy) { addType(Buffer, DTy); addFlag(Buffer, dwarf::DW_AT_enum_class); } } void DwarfUnit::constructContainingTypeDIEs() { for (auto CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end(); CI != CE; ++CI) { DIE &SPDie = *CI->first; const DINode *D = CI->second; if (!D) continue; DIE *NDie = getDIE(D); if (!NDie) continue; addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie); } } void DwarfUnit::constructMemberDIE(DIE &Buffer, const DIDerivedType *DT) { DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer); StringRef Name = DT->getName(); if (!Name.empty()) addString(MemberDie, dwarf::DW_AT_name, Name); addType(MemberDie, resolve(DT->getBaseType())); addSourceLine(MemberDie, DT); if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) { // For C++, virtual base classes are not at fixed offset. Use following // expression to extract appropriate offset from vtable. // BaseAddr = ObAddr + *((*ObAddr) - Offset) DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc; addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits()); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); } else { uint64_t Size = DT->getSizeInBits(); uint64_t FieldSize = DD->getBaseTypeSize(DT); uint32_t AlignInBytes = DT->getAlignInBytes(); uint64_t OffsetInBytes; bool IsBitfield = FieldSize && Size != FieldSize; if (IsBitfield) { // Handle bitfield, assume bytes are 8 bits. if (DD->useDWARF2Bitfields()) addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8); addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size); uint64_t Offset = DT->getOffsetInBits(); // We can't use DT->getAlignInBits() here: AlignInBits for member type // is non-zero if and only if alignment was forced (e.g. _Alignas()), // which can't be done with bitfields. Thus we use FieldSize here. uint32_t AlignInBits = FieldSize; uint32_t AlignMask = ~(AlignInBits - 1); // The bits from the start of the storage unit to the start of the field. uint64_t StartBitOffset = Offset - (Offset & AlignMask); // The byte offset of the field's aligned storage unit inside the struct. OffsetInBytes = (Offset - StartBitOffset) / 8; if (DD->useDWARF2Bitfields()) { uint64_t HiMark = (Offset + FieldSize) & AlignMask; uint64_t FieldOffset = (HiMark - FieldSize); Offset -= FieldOffset; // Maybe we need to work from the other end. if (Asm->getDataLayout().isLittleEndian()) Offset = FieldSize - (Offset + Size); addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset); OffsetInBytes = FieldOffset >> 3; } else { addUInt(MemberDie, dwarf::DW_AT_data_bit_offset, None, Offset); } } else { // This is not a bitfield. OffsetInBytes = DT->getOffsetInBits() / 8; if (AlignInBytes) addUInt(MemberDie, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, AlignInBytes); } if (DD->getDwarfVersion() <= 2) { DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc; addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes); addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie); } else if (!IsBitfield || DD->useDWARF2Bitfields()) addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes); } if (DT->isProtected()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (DT->isPrivate()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); // Otherwise C++ member and base classes are considered public. else if (DT->isPublic()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (DT->isVirtual()) addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, dwarf::DW_VIRTUALITY_virtual); // Objective-C properties. if (DINode *PNode = DT->getObjCProperty()) if (DIE *PDie = getDIE(PNode)) MemberDie.addValue(DIEValueAllocator, dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4, DIEEntry(*PDie)); if (DT->isArtificial()) addFlag(MemberDie, dwarf::DW_AT_artificial); } DIE *DwarfUnit::getOrCreateStaticMemberDIE(const DIDerivedType *DT) { if (!DT) return nullptr; // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope())); assert(dwarf::isType(ContextDIE->getTag()) && ""Static member should belong to a type.""); if (DIE *StaticMemberDIE = getDIE(DT)) return StaticMemberDIE; DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT); const DIType *Ty = resolve(DT->getBaseType()); addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName()); addType(StaticMemberDIE, Ty); addSourceLine(StaticMemberDIE, DT); addFlag(StaticMemberDIE, dwarf::DW_AT_external); addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); // FIXME: We could omit private if the parent is a class_type, and // public if the parent is something else. if (DT->isProtected()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (DT->isPrivate()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); else if (DT->isPublic()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (const ConstantInt *CI = dyn_cast_or_null(DT->getConstant())) addConstantValue(StaticMemberDIE, CI, Ty); if (const ConstantFP *CFP = dyn_cast_or_null(DT->getConstant())) addConstantFPValue(StaticMemberDIE, CFP); if (uint32_t AlignInBytes = DT->getAlignInBytes()) addUInt(StaticMemberDIE, dwarf::DW_AT_alignment, dwarf::DW_FORM_udata, AlignInBytes); return &StaticMemberDIE; } void DwarfUnit::emitCommonHeader(bool UseOffsets, dwarf::UnitType UT) { // Emit size of content not including length itself Asm->OutStreamer->AddComment(""Length of Unit""); Asm->EmitInt32(getHeaderSize() + getUnitDie().getSize()); Asm->OutStreamer->AddComment(""DWARF version number""); unsigned Version = DD->getDwarfVersion(); Asm->EmitInt16(Version); // DWARF v5 reorders the address size and adds a unit type. if (Version >= 5) { Asm->OutStreamer->AddComment(""DWARF Unit Type""); Asm->EmitInt8(UT); Asm->OutStreamer->AddComment(""Address Size (in bytes)""); Asm->EmitInt8(Asm->MAI->getCodePointerSize()); } // We share one abbreviations table across all units so it's always at the // start of the section. Use a relocatable offset where needed to ensure // linking doesn't invalidate that offset. Asm->OutStreamer->AddComment(""Offset Into Abbrev. Section""); const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); if (UseOffsets) Asm->EmitInt32(0); else Asm->emitDwarfSymbolReference( TLOF.getDwarfAbbrevSection()->getBeginSymbol(), false); if (Version <= 4) { Asm->OutStreamer->AddComment(""Address Size (in bytes)""); Asm->EmitInt8(Asm->MAI->getCodePointerSize()); } } void DwarfTypeUnit::emitHeader(bool UseOffsets) { DwarfUnit::emitCommonHeader(UseOffsets, DD->useSplitDwarf() ? dwarf::DW_UT_split_type : dwarf::DW_UT_type); Asm->OutStreamer->AddComment(""Type Signature""); Asm->OutStreamer->EmitIntValue(TypeSignature, sizeof(TypeSignature)); Asm->OutStreamer->AddComment(""Type DIE Offset""); // In a skeleton type unit there is no type DIE so emit a zero offset. Asm->OutStreamer->EmitIntValue(Ty ? Ty->getOffset() : 0, sizeof(Ty->getOffset())); } DIE::value_iterator DwarfUnit::addSectionDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi, const MCSymbol *Lo) { return Die.addValue(DIEValueAllocator, Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset : dwarf::DW_FORM_data4, new (DIEValueAllocator) DIEDelta(Hi, Lo)); } DIE::value_iterator DwarfUnit::addSectionLabel(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Label, const MCSymbol *Sec) { if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) return addLabel(Die, Attribute, DD->getDwarfVersion() >= 4 ? dwarf::DW_FORM_sec_offset : dwarf::DW_FORM_data4, Label); return addSectionDelta(Die, Attribute, Label, Sec); } bool DwarfTypeUnit::isDwoUnit() const { // Since there are no skeleton type units, all type units are dwo type units // when split DWARF is being used. return DD->useSplitDwarf(); } void DwarfTypeUnit::addGlobalName(StringRef Name, const DIE &Die, const DIScope *Context) { getCU().addGlobalNameForTypeUnit(Name, Context); } void DwarfTypeUnit::addGlobalType(const DIType *Ty, const DIE &Die, const DIScope *Context) { getCU().addGlobalTypeUnitType(Ty, Context); } const MCSymbol *DwarfUnit::getCrossSectionRelativeBaseAddress() const { if (!Asm->MAI->doesDwarfUseRelocationsAcrossSections()) return nullptr; if (isDwoUnit()) return nullptr; return getSection()->getBeginSymbol(); } ",16311,True,3260.1375406698216,median "// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include ""core/fxcodec/jbig2/JBig2_Context.h"" #include #include #include #include #include ""core/fpdfapi/fpdf_parser/include/cpdf_stream.h"" #include ""core/fpdfapi/fpdf_parser/include/cpdf_stream_acc.h"" #include ""core/fxcodec/jbig2/JBig2_ArithDecoder.h"" #include ""core/fxcodec/jbig2/JBig2_BitStream.h"" #include ""core/fxcodec/jbig2/JBig2_GrdProc.h"" #include ""core/fxcodec/jbig2/JBig2_GrrdProc.h"" #include ""core/fxcodec/jbig2/JBig2_HtrdProc.h"" #include ""core/fxcodec/jbig2/JBig2_HuffmanTable_Standard.h"" #include ""core/fxcodec/jbig2/JBig2_PddProc.h"" #include ""core/fxcodec/jbig2/JBig2_SddProc.h"" #include ""core/fxcodec/jbig2/JBig2_TrdProc.h"" #include ""third_party/base/stl_util.h"" namespace { size_t GetHuffContextSize(uint8_t val) { return val == 0 ? 65536 : val == 1 ? 8192 : 1024; } size_t GetRefAggContextSize(FX_BOOL val) { return val ? 1024 : 8192; } } // namespace // Implement a very small least recently used (LRU) cache. It is very // common for a JBIG2 dictionary to span multiple pages in a PDF file, // and we do not want to decode the same dictionary over and over // again. We key off of the memory location of the dictionary. The // list keeps track of the freshness of entries, with freshest ones // at the front. Even a tiny cache size like 2 makes a dramatic // difference for typical JBIG2 documents. static const int kSymbolDictCacheMaxSize = 2; CJBig2_Context::CJBig2_Context(CPDF_StreamAcc* pGlobalStream, CPDF_StreamAcc* pSrcStream, std::list* pSymbolDictCache, IFX_Pause* pPause, bool bIsGlobal) : m_nSegmentDecoded(0), m_bInPage(false), m_bBufSpecified(false), m_PauseStep(10), m_pPause(pPause), m_ProcessingStatus(FXCODEC_STATUS_FRAME_READY), m_dwOffset(0), m_pSymbolDictCache(pSymbolDictCache), m_bIsGlobal(bIsGlobal) { if (pGlobalStream && (pGlobalStream->GetSize() > 0)) { m_pGlobalContext.reset(new CJBig2_Context(nullptr, pGlobalStream, pSymbolDictCache, pPause, true)); } m_pStream.reset(new CJBig2_BitStream(pSrcStream)); } CJBig2_Context::~CJBig2_Context() {} int32_t CJBig2_Context::decode_SquentialOrgnazation(IFX_Pause* pPause) { int32_t nRet; if (m_pStream->getByteLeft() <= 0) return JBIG2_END_OF_FILE; while (m_pStream->getByteLeft() >= JBIG2_MIN_SEGMENT_SIZE) { if (!m_pSegment) { m_pSegment.reset(new CJBig2_Segment); nRet = parseSegmentHeader(m_pSegment.get()); if (nRet != JBIG2_SUCCESS) { m_pSegment.reset(); return nRet; } m_dwOffset = m_pStream->getOffset(); } nRet = parseSegmentData(m_pSegment.get(), pPause); if (m_ProcessingStatus == FXCODEC_STATUS_DECODE_TOBECONTINUE) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_TOBECONTINUE; m_PauseStep = 2; return JBIG2_SUCCESS; } if (nRet == JBIG2_END_OF_PAGE || nRet == JBIG2_END_OF_FILE) { m_pSegment.reset(); return JBIG2_SUCCESS; } if (nRet != JBIG2_SUCCESS) { m_pSegment.reset(); return nRet; } if (m_pSegment->m_dwData_length != 0xffffffff) { m_dwOffset += m_pSegment->m_dwData_length; m_pStream->setOffset(m_dwOffset); } else { m_pStream->offset(4); } m_SegmentList.push_back(m_pSegment.release()); if (m_pStream->getByteLeft() > 0 && m_pPage && pPause && pPause->NeedToPauseNow()) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_TOBECONTINUE; m_PauseStep = 2; return JBIG2_SUCCESS; } } return JBIG2_SUCCESS; } int32_t CJBig2_Context::decode_EmbedOrgnazation(IFX_Pause* pPause) { return decode_SquentialOrgnazation(pPause); } int32_t CJBig2_Context::decode_RandomOrgnazation_FirstPage(IFX_Pause* pPause) { int32_t nRet; while (m_pStream->getByteLeft() > JBIG2_MIN_SEGMENT_SIZE) { std::unique_ptr pSegment(new CJBig2_Segment); nRet = parseSegmentHeader(pSegment.get()); if (nRet != JBIG2_SUCCESS) { return nRet; } else if (pSegment->m_cFlags.s.type == 51) { break; } m_SegmentList.push_back(pSegment.release()); if (pPause && m_pPause && pPause->NeedToPauseNow()) { m_PauseStep = 3; m_ProcessingStatus = FXCODEC_STATUS_DECODE_TOBECONTINUE; return JBIG2_SUCCESS; } } m_nSegmentDecoded = 0; return decode_RandomOrgnazation(pPause); } int32_t CJBig2_Context::decode_RandomOrgnazation(IFX_Pause* pPause) { for (; m_nSegmentDecoded < m_SegmentList.size(); ++m_nSegmentDecoded) { int32_t nRet = parseSegmentData(m_SegmentList.get(m_nSegmentDecoded), pPause); if (nRet == JBIG2_END_OF_PAGE || nRet == JBIG2_END_OF_FILE) return JBIG2_SUCCESS; if (nRet != JBIG2_SUCCESS) return nRet; if (m_pPage && pPause && pPause->NeedToPauseNow()) { m_PauseStep = 4; m_ProcessingStatus = FXCODEC_STATUS_DECODE_TOBECONTINUE; return JBIG2_SUCCESS; } } return JBIG2_SUCCESS; } int32_t CJBig2_Context::getFirstPage(uint8_t* pBuf, int32_t width, int32_t height, int32_t stride, IFX_Pause* pPause) { int32_t nRet = 0; if (m_pGlobalContext) { nRet = m_pGlobalContext->decode_EmbedOrgnazation(pPause); if (nRet != JBIG2_SUCCESS) { m_ProcessingStatus = FXCODEC_STATUS_ERROR; return nRet; } } m_PauseStep = 0; m_pPage.reset(new CJBig2_Image(width, height, stride, pBuf)); m_bBufSpecified = true; if (pPause && pPause->NeedToPauseNow()) { m_PauseStep = 1; m_ProcessingStatus = FXCODEC_STATUS_DECODE_TOBECONTINUE; return nRet; } return Continue(pPause); } int32_t CJBig2_Context::Continue(IFX_Pause* pPause) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_READY; int32_t nRet = 0; if (m_PauseStep <= 1) { nRet = decode_EmbedOrgnazation(pPause); } else if (m_PauseStep == 2) { nRet = decode_SquentialOrgnazation(pPause); } else if (m_PauseStep == 3) { nRet = decode_RandomOrgnazation_FirstPage(pPause); } else if (m_PauseStep == 4) { nRet = decode_RandomOrgnazation(pPause); } else if (m_PauseStep == 5) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_FINISH; return JBIG2_SUCCESS; } if (m_ProcessingStatus == FXCODEC_STATUS_DECODE_TOBECONTINUE) { return nRet; } m_PauseStep = 5; if (!m_bBufSpecified && nRet == JBIG2_SUCCESS) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_FINISH; return JBIG2_SUCCESS; } if (nRet == JBIG2_SUCCESS) { m_ProcessingStatus = FXCODEC_STATUS_DECODE_FINISH; } else { m_ProcessingStatus = FXCODEC_STATUS_ERROR; } return nRet; } CJBig2_Segment* CJBig2_Context::findSegmentByNumber(uint32_t dwNumber) { if (m_pGlobalContext) { CJBig2_Segment* pSeg = m_pGlobalContext->findSegmentByNumber(dwNumber); if (pSeg) { return pSeg; } } for (size_t i = 0; i < m_SegmentList.size(); ++i) { CJBig2_Segment* pSeg = m_SegmentList.get(i); if (pSeg->m_dwNumber == dwNumber) { return pSeg; } } return nullptr; } CJBig2_Segment* CJBig2_Context::findReferredSegmentByTypeAndIndex( CJBig2_Segment* pSegment, uint8_t cType, int32_t nIndex) { int32_t count = 0; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i]); if (pSeg && pSeg->m_cFlags.s.type == cType) { if (count == nIndex) return pSeg; ++count; } } return nullptr; } int32_t CJBig2_Context::parseSegmentHeader(CJBig2_Segment* pSegment) { if (m_pStream->readInteger(&pSegment->m_dwNumber) != 0 || m_pStream->read1Byte(&pSegment->m_cFlags.c) != 0) { return JBIG2_ERROR_TOO_SHORT; } uint32_t dwTemp; uint8_t cTemp = m_pStream->getCurByte(); if ((cTemp >> 5) == 7) { if (m_pStream->readInteger( (uint32_t*)&pSegment->m_nReferred_to_segment_count) != 0) { return JBIG2_ERROR_TOO_SHORT; } pSegment->m_nReferred_to_segment_count &= 0x1fffffff; if (pSegment->m_nReferred_to_segment_count > JBIG2_MAX_REFERRED_SEGMENT_COUNT) { return JBIG2_ERROR_LIMIT; } dwTemp = 5 + 4 + (pSegment->m_nReferred_to_segment_count + 1) / 8; } else { if (m_pStream->read1Byte(&cTemp) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_nReferred_to_segment_count = cTemp >> 5; dwTemp = 5 + 1; } uint8_t cSSize = pSegment->m_dwNumber > 65536 ? 4 : pSegment->m_dwNumber > 256 ? 2 : 1; uint8_t cPSize = pSegment->m_cFlags.s.page_association_size ? 4 : 1; if (pSegment->m_nReferred_to_segment_count) { pSegment->m_pReferred_to_segment_numbers = FX_Alloc(uint32_t, pSegment->m_nReferred_to_segment_count); for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { switch (cSSize) { case 1: if (m_pStream->read1Byte(&cTemp) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_pReferred_to_segment_numbers[i] = cTemp; break; case 2: uint16_t wTemp; if (m_pStream->readShortInteger(&wTemp) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_pReferred_to_segment_numbers[i] = wTemp; break; case 4: if (m_pStream->readInteger(&dwTemp) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_pReferred_to_segment_numbers[i] = dwTemp; break; } if (pSegment->m_pReferred_to_segment_numbers[i] >= pSegment->m_dwNumber) return JBIG2_ERROR_TOO_SHORT; } } if (cPSize == 1) { if (m_pStream->read1Byte(&cTemp) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_dwPage_association = cTemp; } else { if (m_pStream->readInteger(&pSegment->m_dwPage_association) != 0) { return JBIG2_ERROR_TOO_SHORT; } } if (m_pStream->readInteger(&pSegment->m_dwData_length) != 0) return JBIG2_ERROR_TOO_SHORT; pSegment->m_dwObjNum = m_pStream->getObjNum(); pSegment->m_dwDataOffset = m_pStream->getOffset(); pSegment->m_State = JBIG2_SEGMENT_DATA_UNPARSED; return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseSegmentData(CJBig2_Segment* pSegment, IFX_Pause* pPause) { int32_t ret = ProcessingParseSegmentData(pSegment, pPause); while (m_ProcessingStatus == FXCODEC_STATUS_DECODE_TOBECONTINUE && m_pStream->getByteLeft() > 0) { ret = ProcessingParseSegmentData(pSegment, pPause); } return ret; } int32_t CJBig2_Context::ProcessingParseSegmentData(CJBig2_Segment* pSegment, IFX_Pause* pPause) { switch (pSegment->m_cFlags.s.type) { case 0: return parseSymbolDict(pSegment, pPause); case 4: case 6: case 7: if (!m_bInPage) return JBIG2_ERROR_FATAL; return parseTextRegion(pSegment); case 16: return parsePatternDict(pSegment, pPause); case 20: case 22: case 23: if (!m_bInPage) return JBIG2_ERROR_FATAL; return parseHalftoneRegion(pSegment, pPause); case 36: case 38: case 39: if (!m_bInPage) return JBIG2_ERROR_FATAL; return parseGenericRegion(pSegment, pPause); case 40: case 42: case 43: if (!m_bInPage) return JBIG2_ERROR_FATAL; return parseGenericRefinementRegion(pSegment); case 48: { uint16_t wTemp; std::unique_ptr pPageInfo(new JBig2PageInfo); if (m_pStream->readInteger(&pPageInfo->m_dwWidth) != 0 || m_pStream->readInteger(&pPageInfo->m_dwHeight) != 0 || m_pStream->readInteger(&pPageInfo->m_dwResolutionX) != 0 || m_pStream->readInteger(&pPageInfo->m_dwResolutionY) != 0 || m_pStream->read1Byte(&pPageInfo->m_cFlags) != 0 || m_pStream->readShortInteger(&wTemp) != 0) { return JBIG2_ERROR_TOO_SHORT; } pPageInfo->m_bIsStriped = !!(wTemp & 0x8000); pPageInfo->m_wMaxStripeSize = wTemp & 0x7fff; bool bMaxHeight = (pPageInfo->m_dwHeight == 0xffffffff); if (bMaxHeight && pPageInfo->m_bIsStriped != TRUE) pPageInfo->m_bIsStriped = TRUE; if (!m_bBufSpecified) { uint32_t height = bMaxHeight ? pPageInfo->m_wMaxStripeSize : pPageInfo->m_dwHeight; m_pPage.reset(new CJBig2_Image(pPageInfo->m_dwWidth, height)); } if (!m_pPage->m_pData) { m_ProcessingStatus = FXCODEC_STATUS_ERROR; return JBIG2_ERROR_TOO_SHORT; } m_pPage->fill((pPageInfo->m_cFlags & 4) ? 1 : 0); m_PageInfoList.push_back(pPageInfo.release()); m_bInPage = true; } break; case 49: m_bInPage = false; return JBIG2_END_OF_PAGE; break; case 50: m_pStream->offset(pSegment->m_dwData_length); break; case 51: return JBIG2_END_OF_FILE; case 52: m_pStream->offset(pSegment->m_dwData_length); break; case 53: return parseTable(pSegment); case 62: m_pStream->offset(pSegment->m_dwData_length); break; default: break; } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseSymbolDict(CJBig2_Segment* pSegment, IFX_Pause* pPause) { uint16_t wFlags; if (m_pStream->readShortInteger(&wFlags) != 0) return JBIG2_ERROR_TOO_SHORT; std::unique_ptr pSymbolDictDecoder(new CJBig2_SDDProc); pSymbolDictDecoder->SDHUFF = wFlags & 0x0001; pSymbolDictDecoder->SDREFAGG = (wFlags >> 1) & 0x0001; pSymbolDictDecoder->SDTEMPLATE = (wFlags >> 10) & 0x0003; pSymbolDictDecoder->SDRTEMPLATE = (wFlags >> 12) & 0x0003; uint8_t cSDHUFFDH = (wFlags >> 2) & 0x0003; uint8_t cSDHUFFDW = (wFlags >> 4) & 0x0003; uint8_t cSDHUFFBMSIZE = (wFlags >> 6) & 0x0001; uint8_t cSDHUFFAGGINST = (wFlags >> 7) & 0x0001; if (pSymbolDictDecoder->SDHUFF == 0) { const uint32_t dwTemp = (pSymbolDictDecoder->SDTEMPLATE == 0) ? 8 : 2; for (uint32_t i = 0; i < dwTemp; ++i) { if (m_pStream->read1Byte((uint8_t*)&pSymbolDictDecoder->SDAT[i]) != 0) return JBIG2_ERROR_TOO_SHORT; } } if (pSymbolDictDecoder->SDREFAGG == 1 && pSymbolDictDecoder->SDRTEMPLATE == 0) { for (int32_t i = 0; i < 4; ++i) { if (m_pStream->read1Byte((uint8_t*)&pSymbolDictDecoder->SDRAT[i]) != 0) return JBIG2_ERROR_TOO_SHORT; } } if (m_pStream->readInteger(&pSymbolDictDecoder->SDNUMEXSYMS) != 0 || m_pStream->readInteger(&pSymbolDictDecoder->SDNUMNEWSYMS) != 0) { return JBIG2_ERROR_TOO_SHORT; } if (pSymbolDictDecoder->SDNUMEXSYMS > JBIG2_MAX_EXPORT_SYSMBOLS || pSymbolDictDecoder->SDNUMNEWSYMS > JBIG2_MAX_NEW_SYSMBOLS) { return JBIG2_ERROR_LIMIT; } for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { if (!findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i])) return JBIG2_ERROR_FATAL; } CJBig2_Segment* pLRSeg = nullptr; pSymbolDictDecoder->SDNUMINSYMS = 0; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i]); if (pSeg->m_cFlags.s.type == 0) { pSymbolDictDecoder->SDNUMINSYMS += pSeg->m_Result.sd->NumImages(); pLRSeg = pSeg; } } std::unique_ptr SDINSYMS; if (pSymbolDictDecoder->SDNUMINSYMS != 0) { SDINSYMS.reset(FX_Alloc(CJBig2_Image*, pSymbolDictDecoder->SDNUMINSYMS)); uint32_t dwTemp = 0; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i]); if (pSeg->m_cFlags.s.type == 0) { const CJBig2_SymbolDict& dict = *pSeg->m_Result.sd; for (size_t j = 0; j < dict.NumImages(); ++j) SDINSYMS.get()[dwTemp + j] = dict.GetImage(j); dwTemp += dict.NumImages(); } } } pSymbolDictDecoder->SDINSYMS = SDINSYMS.get(); std::unique_ptr Table_B1; std::unique_ptr Table_B2; std::unique_ptr Table_B3; std::unique_ptr Table_B4; std::unique_ptr Table_B5; if (pSymbolDictDecoder->SDHUFF == 1) { if (cSDHUFFDH == 2 || cSDHUFFDW == 2) return JBIG2_ERROR_FATAL; int32_t nIndex = 0; if (cSDHUFFDH == 0) { Table_B4.reset(new CJBig2_HuffmanTable( HuffmanTable_B4, HuffmanTable_B4_Size, HuffmanTable_HTOOB_B4)); pSymbolDictDecoder->SDHUFFDH = Table_B4.get(); } else if (cSDHUFFDH == 1) { Table_B5.reset(new CJBig2_HuffmanTable( HuffmanTable_B5, HuffmanTable_B5_Size, HuffmanTable_HTOOB_B5)); pSymbolDictDecoder->SDHUFFDH = Table_B5.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pSymbolDictDecoder->SDHUFFDH = pSeg->m_Result.ht; } if (cSDHUFFDW == 0) { Table_B2.reset(new CJBig2_HuffmanTable( HuffmanTable_B2, HuffmanTable_B2_Size, HuffmanTable_HTOOB_B2)); pSymbolDictDecoder->SDHUFFDW = Table_B2.get(); } else if (cSDHUFFDW == 1) { Table_B3.reset(new CJBig2_HuffmanTable( HuffmanTable_B3, HuffmanTable_B3_Size, HuffmanTable_HTOOB_B3)); pSymbolDictDecoder->SDHUFFDW = Table_B3.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pSymbolDictDecoder->SDHUFFDW = pSeg->m_Result.ht; } if (cSDHUFFBMSIZE == 0) { Table_B1.reset(new CJBig2_HuffmanTable( HuffmanTable_B1, HuffmanTable_B1_Size, HuffmanTable_HTOOB_B1)); pSymbolDictDecoder->SDHUFFBMSIZE = Table_B1.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pSymbolDictDecoder->SDHUFFBMSIZE = pSeg->m_Result.ht; } if (pSymbolDictDecoder->SDREFAGG == 1) { if (cSDHUFFAGGINST == 0) { if (!Table_B1) { Table_B1.reset(new CJBig2_HuffmanTable( HuffmanTable_B1, HuffmanTable_B1_Size, HuffmanTable_HTOOB_B1)); } pSymbolDictDecoder->SDHUFFAGGINST = Table_B1.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pSymbolDictDecoder->SDHUFFAGGINST = pSeg->m_Result.ht; } } } const bool bUseGbContext = (pSymbolDictDecoder->SDHUFF == 0); const bool bUseGrContext = (pSymbolDictDecoder->SDREFAGG == 1); const size_t gbContextSize = GetHuffContextSize(pSymbolDictDecoder->SDTEMPLATE); const size_t grContextSize = GetRefAggContextSize(pSymbolDictDecoder->SDRTEMPLATE); std::vector gbContext; std::vector grContext; if ((wFlags & 0x0100) && pLRSeg) { if (bUseGbContext) { gbContext = pLRSeg->m_Result.sd->GbContext(); if (gbContext.size() != gbContextSize) return JBIG2_ERROR_FATAL; } if (bUseGrContext) { grContext = pLRSeg->m_Result.sd->GrContext(); if (grContext.size() != grContextSize) return JBIG2_ERROR_FATAL; } } else { if (bUseGbContext) gbContext.resize(gbContextSize); if (bUseGrContext) grContext.resize(grContextSize); } CJBig2_CacheKey key = CJBig2_CacheKey(pSegment->m_dwObjNum, pSegment->m_dwDataOffset); FX_BOOL cache_hit = false; pSegment->m_nResultType = JBIG2_SYMBOL_DICT_POINTER; if (m_bIsGlobal && key.first != 0) { for (auto it = m_pSymbolDictCache->begin(); it != m_pSymbolDictCache->end(); ++it) { if (it->first == key) { std::unique_ptr copy(it->second->DeepCopy()); pSegment->m_Result.sd = copy.release(); m_pSymbolDictCache->push_front( CJBig2_CachePair(key, std::move(it->second))); m_pSymbolDictCache->erase(it); cache_hit = true; break; } } } if (!cache_hit) { if (bUseGbContext) { std::unique_ptr pArithDecoder( new CJBig2_ArithDecoder(m_pStream.get())); pSegment->m_Result.sd = pSymbolDictDecoder->decode_Arith( pArithDecoder.get(), &gbContext, &grContext); if (!pSegment->m_Result.sd) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); m_pStream->offset(2); } else { pSegment->m_Result.sd = pSymbolDictDecoder->decode_Huffman( m_pStream.get(), &gbContext, &grContext, pPause); if (!pSegment->m_Result.sd) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); } if (m_bIsGlobal) { std::unique_ptr value = pSegment->m_Result.sd->DeepCopy(); int size = pdfium::CollectionSize(*m_pSymbolDictCache); while (size >= kSymbolDictCacheMaxSize) { m_pSymbolDictCache->pop_back(); --size; } m_pSymbolDictCache->push_front(CJBig2_CachePair(key, std::move(value))); } } if (wFlags & 0x0200) { if (bUseGbContext) pSegment->m_Result.sd->SetGbContext(gbContext); if (bUseGrContext) pSegment->m_Result.sd->SetGrContext(grContext); } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseTextRegion(CJBig2_Segment* pSegment) { uint16_t wFlags; JBig2RegionInfo ri; if (parseRegionInfo(&ri) != JBIG2_SUCCESS || m_pStream->readShortInteger(&wFlags) != 0) { return JBIG2_ERROR_TOO_SHORT; } std::unique_ptr pTRD(new CJBig2_TRDProc); pTRD->SBW = ri.width; pTRD->SBH = ri.height; pTRD->SBHUFF = wFlags & 0x0001; pTRD->SBREFINE = (wFlags >> 1) & 0x0001; uint32_t dwTemp = (wFlags >> 2) & 0x0003; pTRD->SBSTRIPS = 1 << dwTemp; pTRD->REFCORNER = (JBig2Corner)((wFlags >> 4) & 0x0003); pTRD->TRANSPOSED = (wFlags >> 6) & 0x0001; pTRD->SBCOMBOP = (JBig2ComposeOp)((wFlags >> 7) & 0x0003); pTRD->SBDEFPIXEL = (wFlags >> 9) & 0x0001; pTRD->SBDSOFFSET = (wFlags >> 10) & 0x001f; if (pTRD->SBDSOFFSET >= 0x0010) { pTRD->SBDSOFFSET = pTRD->SBDSOFFSET - 0x0020; } pTRD->SBRTEMPLATE = (wFlags >> 15) & 0x0001; uint8_t cSBHUFFFS = 0; uint8_t cSBHUFFDS = 0; uint8_t cSBHUFFDT = 0; uint8_t cSBHUFFRDW = 0; uint8_t cSBHUFFRDH = 0; uint8_t cSBHUFFRDX = 0; uint8_t cSBHUFFRDY = 0; uint8_t cSBHUFFRSIZE = 0; if (pTRD->SBHUFF == 1) { if (m_pStream->readShortInteger(&wFlags) != 0) return JBIG2_ERROR_TOO_SHORT; cSBHUFFFS = wFlags & 0x0003; cSBHUFFDS = (wFlags >> 2) & 0x0003; cSBHUFFDT = (wFlags >> 4) & 0x0003; cSBHUFFRDW = (wFlags >> 6) & 0x0003; cSBHUFFRDH = (wFlags >> 8) & 0x0003; cSBHUFFRDX = (wFlags >> 10) & 0x0003; cSBHUFFRDY = (wFlags >> 12) & 0x0003; cSBHUFFRSIZE = (wFlags >> 14) & 0x0001; } if (pTRD->SBREFINE == 1 && pTRD->SBRTEMPLATE == 0) { for (int32_t i = 0; i < 4; ++i) { if (m_pStream->read1Byte((uint8_t*)&pTRD->SBRAT[i]) != 0) return JBIG2_ERROR_TOO_SHORT; } } if (m_pStream->readInteger(&pTRD->SBNUMINSTANCES) != 0) return JBIG2_ERROR_TOO_SHORT; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { if (!findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i])) return JBIG2_ERROR_FATAL; } pTRD->SBNUMSYMS = 0; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i]); if (pSeg->m_cFlags.s.type == 0) { pTRD->SBNUMSYMS += pSeg->m_Result.sd->NumImages(); } } std::unique_ptr SBSYMS; if (pTRD->SBNUMSYMS > 0) { SBSYMS.reset(FX_Alloc(CJBig2_Image*, pTRD->SBNUMSYMS)); dwTemp = 0; for (int32_t i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[i]); if (pSeg->m_cFlags.s.type == 0) { const CJBig2_SymbolDict& dict = *pSeg->m_Result.sd; for (size_t j = 0; j < dict.NumImages(); ++j) SBSYMS.get()[dwTemp + j] = dict.GetImage(j); dwTemp += dict.NumImages(); } } pTRD->SBSYMS = SBSYMS.get(); } else { pTRD->SBSYMS = nullptr; } std::unique_ptr SBSYMCODES; if (pTRD->SBHUFF == 1) { SBSYMCODES.reset( decodeSymbolIDHuffmanTable(m_pStream.get(), pTRD->SBNUMSYMS)); if (!SBSYMCODES) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); pTRD->SBSYMCODES = SBSYMCODES.get(); } else { dwTemp = 0; while ((uint32_t)(1 << dwTemp) < pTRD->SBNUMSYMS) { ++dwTemp; } pTRD->SBSYMCODELEN = (uint8_t)dwTemp; } std::unique_ptr Table_B1; std::unique_ptr Table_B6; std::unique_ptr Table_B7; std::unique_ptr Table_B8; std::unique_ptr Table_B9; std::unique_ptr Table_B10; std::unique_ptr Table_B11; std::unique_ptr Table_B12; std::unique_ptr Table_B13; std::unique_ptr Table_B14; std::unique_ptr Table_B15; if (pTRD->SBHUFF == 1) { if (cSBHUFFFS == 2 || cSBHUFFRDW == 2 || cSBHUFFRDH == 2 || cSBHUFFRDX == 2 || cSBHUFFRDY == 2) { return JBIG2_ERROR_FATAL; } int32_t nIndex = 0; if (cSBHUFFFS == 0) { Table_B6.reset(new CJBig2_HuffmanTable( HuffmanTable_B6, HuffmanTable_B6_Size, HuffmanTable_HTOOB_B6)); pTRD->SBHUFFFS = Table_B6.get(); } else if (cSBHUFFFS == 1) { Table_B7.reset(new CJBig2_HuffmanTable( HuffmanTable_B7, HuffmanTable_B7_Size, HuffmanTable_HTOOB_B7)); pTRD->SBHUFFFS = Table_B7.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFFS = pSeg->m_Result.ht; } if (cSBHUFFDS == 0) { Table_B8.reset(new CJBig2_HuffmanTable( HuffmanTable_B8, HuffmanTable_B8_Size, HuffmanTable_HTOOB_B8)); pTRD->SBHUFFDS = Table_B8.get(); } else if (cSBHUFFDS == 1) { Table_B9.reset(new CJBig2_HuffmanTable( HuffmanTable_B9, HuffmanTable_B9_Size, HuffmanTable_HTOOB_B9)); pTRD->SBHUFFDS = Table_B9.get(); } else if (cSBHUFFDS == 2) { Table_B10.reset(new CJBig2_HuffmanTable( HuffmanTable_B10, HuffmanTable_B10_Size, HuffmanTable_HTOOB_B10)); pTRD->SBHUFFDS = Table_B10.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFDS = pSeg->m_Result.ht; } if (cSBHUFFDT == 0) { Table_B11.reset(new CJBig2_HuffmanTable( HuffmanTable_B11, HuffmanTable_B11_Size, HuffmanTable_HTOOB_B11)); pTRD->SBHUFFDT = Table_B11.get(); } else if (cSBHUFFDT == 1) { Table_B12.reset(new CJBig2_HuffmanTable( HuffmanTable_B12, HuffmanTable_B12_Size, HuffmanTable_HTOOB_B12)); pTRD->SBHUFFDT = Table_B12.get(); } else if (cSBHUFFDT == 2) { Table_B13.reset(new CJBig2_HuffmanTable( HuffmanTable_B13, HuffmanTable_B13_Size, HuffmanTable_HTOOB_B13)); pTRD->SBHUFFDT = Table_B13.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFDT = pSeg->m_Result.ht; } if (cSBHUFFRDW == 0) { Table_B14.reset(new CJBig2_HuffmanTable( HuffmanTable_B14, HuffmanTable_B14_Size, HuffmanTable_HTOOB_B14)); pTRD->SBHUFFRDW = Table_B14.get(); } else if (cSBHUFFRDW == 1) { Table_B15.reset(new CJBig2_HuffmanTable( HuffmanTable_B15, HuffmanTable_B15_Size, HuffmanTable_HTOOB_B15)); pTRD->SBHUFFRDW = Table_B15.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFRDW = pSeg->m_Result.ht; } if (cSBHUFFRDH == 0) { if (!Table_B14) { Table_B14.reset(new CJBig2_HuffmanTable( HuffmanTable_B14, HuffmanTable_B14_Size, HuffmanTable_HTOOB_B14)); } pTRD->SBHUFFRDH = Table_B14.get(); } else if (cSBHUFFRDH == 1) { if (!Table_B15) { Table_B15.reset(new CJBig2_HuffmanTable( HuffmanTable_B15, HuffmanTable_B15_Size, HuffmanTable_HTOOB_B15)); } pTRD->SBHUFFRDH = Table_B15.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFRDH = pSeg->m_Result.ht; } if (cSBHUFFRDX == 0) { if (!Table_B14) { Table_B14.reset(new CJBig2_HuffmanTable( HuffmanTable_B14, HuffmanTable_B14_Size, HuffmanTable_HTOOB_B14)); } pTRD->SBHUFFRDX = Table_B14.get(); } else if (cSBHUFFRDX == 1) { if (!Table_B15) { Table_B15.reset(new CJBig2_HuffmanTable( HuffmanTable_B15, HuffmanTable_B15_Size, HuffmanTable_HTOOB_B15)); } pTRD->SBHUFFRDX = Table_B15.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFRDX = pSeg->m_Result.ht; } if (cSBHUFFRDY == 0) { if (!Table_B14) { Table_B14.reset(new CJBig2_HuffmanTable( HuffmanTable_B14, HuffmanTable_B14_Size, HuffmanTable_HTOOB_B14)); } pTRD->SBHUFFRDY = Table_B14.get(); } else if (cSBHUFFRDY == 1) { if (!Table_B15) { Table_B15.reset(new CJBig2_HuffmanTable( HuffmanTable_B15, HuffmanTable_B15_Size, HuffmanTable_HTOOB_B15)); } pTRD->SBHUFFRDY = Table_B15.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFRDY = pSeg->m_Result.ht; } if (cSBHUFFRSIZE == 0) { Table_B1.reset(new CJBig2_HuffmanTable( HuffmanTable_B1, HuffmanTable_B1_Size, HuffmanTable_HTOOB_B1)); pTRD->SBHUFFRSIZE = Table_B1.get(); } else { CJBig2_Segment* pSeg = findReferredSegmentByTypeAndIndex(pSegment, 53, nIndex++); if (!pSeg) return JBIG2_ERROR_FATAL; pTRD->SBHUFFRSIZE = pSeg->m_Result.ht; } } std::unique_ptr grContext; if (pTRD->SBREFINE == 1) { const size_t size = GetRefAggContextSize(pTRD->SBRTEMPLATE); grContext.reset(FX_Alloc(JBig2ArithCtx, size)); JBIG2_memset(grContext.get(), 0, sizeof(JBig2ArithCtx) * size); } if (pTRD->SBHUFF == 0) { std::unique_ptr pArithDecoder( new CJBig2_ArithDecoder(m_pStream.get())); pSegment->m_nResultType = JBIG2_IMAGE_POINTER; pSegment->m_Result.im = pTRD->decode_Arith(pArithDecoder.get(), grContext.get(), nullptr); if (!pSegment->m_Result.im) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); m_pStream->offset(2); } else { pSegment->m_nResultType = JBIG2_IMAGE_POINTER; pSegment->m_Result.im = pTRD->decode_Huffman(m_pStream.get(), grContext.get()); if (!pSegment->m_Result.im) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); } if (pSegment->m_cFlags.s.type != 4) { if (!m_bBufSpecified) { JBig2PageInfo* pPageInfo = m_PageInfoList.back(); if ((pPageInfo->m_bIsStriped == 1) && (ri.y + ri.height > m_pPage->height())) { m_pPage->expand(ri.y + ri.height, (pPageInfo->m_cFlags & 4) ? 1 : 0); } } m_pPage->composeFrom(ri.x, ri.y, pSegment->m_Result.im, (JBig2ComposeOp)(ri.flags & 0x03)); delete pSegment->m_Result.im; pSegment->m_Result.im = nullptr; } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parsePatternDict(CJBig2_Segment* pSegment, IFX_Pause* pPause) { uint8_t cFlags; std::unique_ptr pPDD(new CJBig2_PDDProc); if (m_pStream->read1Byte(&cFlags) != 0 || m_pStream->read1Byte(&pPDD->HDPW) != 0 || m_pStream->read1Byte(&pPDD->HDPH) != 0 || m_pStream->readInteger(&pPDD->GRAYMAX) != 0) { return JBIG2_ERROR_TOO_SHORT; } if (pPDD->GRAYMAX > JBIG2_MAX_PATTERN_INDEX) return JBIG2_ERROR_LIMIT; pPDD->HDMMR = cFlags & 0x01; pPDD->HDTEMPLATE = (cFlags >> 1) & 0x03; pSegment->m_nResultType = JBIG2_PATTERN_DICT_POINTER; if (pPDD->HDMMR == 0) { const size_t size = GetHuffContextSize(pPDD->HDTEMPLATE); std::unique_ptr gbContext( FX_Alloc(JBig2ArithCtx, size)); JBIG2_memset(gbContext.get(), 0, sizeof(JBig2ArithCtx) * size); std::unique_ptr pArithDecoder( new CJBig2_ArithDecoder(m_pStream.get())); pSegment->m_Result.pd = pPDD->decode_Arith(pArithDecoder.get(), gbContext.get(), pPause); if (!pSegment->m_Result.pd) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); m_pStream->offset(2); } else { pSegment->m_Result.pd = pPDD->decode_MMR(m_pStream.get(), pPause); if (!pSegment->m_Result.pd) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseHalftoneRegion(CJBig2_Segment* pSegment, IFX_Pause* pPause) { uint8_t cFlags; JBig2RegionInfo ri; std::unique_ptr pHRD(new CJBig2_HTRDProc); if (parseRegionInfo(&ri) != JBIG2_SUCCESS || m_pStream->read1Byte(&cFlags) != 0 || m_pStream->readInteger(&pHRD->HGW) != 0 || m_pStream->readInteger(&pHRD->HGH) != 0 || m_pStream->readInteger((uint32_t*)&pHRD->HGX) != 0 || m_pStream->readInteger((uint32_t*)&pHRD->HGY) != 0 || m_pStream->readShortInteger(&pHRD->HRX) != 0 || m_pStream->readShortInteger(&pHRD->HRY) != 0) { return JBIG2_ERROR_TOO_SHORT; } if (pHRD->HGW == 0 || pHRD->HGH == 0) return JBIG2_ERROR_FATAL; pHRD->HBW = ri.width; pHRD->HBH = ri.height; pHRD->HMMR = cFlags & 0x01; pHRD->HTEMPLATE = (cFlags >> 1) & 0x03; pHRD->HENABLESKIP = (cFlags >> 3) & 0x01; pHRD->HCOMBOP = (JBig2ComposeOp)((cFlags >> 4) & 0x07); pHRD->HDEFPIXEL = (cFlags >> 7) & 0x01; if (pSegment->m_nReferred_to_segment_count != 1) return JBIG2_ERROR_FATAL; CJBig2_Segment* pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[0]); if (!pSeg || (pSeg->m_cFlags.s.type != 16)) return JBIG2_ERROR_FATAL; CJBig2_PatternDict* pPatternDict = pSeg->m_Result.pd; if (!pPatternDict || (pPatternDict->NUMPATS == 0)) return JBIG2_ERROR_FATAL; pHRD->HNUMPATS = pPatternDict->NUMPATS; pHRD->HPATS = pPatternDict->HDPATS; pHRD->HPW = pPatternDict->HDPATS[0]->width(); pHRD->HPH = pPatternDict->HDPATS[0]->height(); pSegment->m_nResultType = JBIG2_IMAGE_POINTER; if (pHRD->HMMR == 0) { const size_t size = GetHuffContextSize(pHRD->HTEMPLATE); std::unique_ptr gbContext( FX_Alloc(JBig2ArithCtx, size)); JBIG2_memset(gbContext.get(), 0, sizeof(JBig2ArithCtx) * size); std::unique_ptr pArithDecoder( new CJBig2_ArithDecoder(m_pStream.get())); pSegment->m_Result.im = pHRD->decode_Arith(pArithDecoder.get(), gbContext.get(), pPause); if (!pSegment->m_Result.im) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); m_pStream->offset(2); } else { pSegment->m_Result.im = pHRD->decode_MMR(m_pStream.get(), pPause); if (!pSegment->m_Result.im) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); } if (pSegment->m_cFlags.s.type != 20) { if (!m_bBufSpecified) { JBig2PageInfo* pPageInfo = m_PageInfoList.back(); if (pPageInfo->m_bIsStriped == 1 && ri.y + ri.height > m_pPage->height()) { m_pPage->expand(ri.y + ri.height, (pPageInfo->m_cFlags & 4) ? 1 : 0); } } m_pPage->composeFrom(ri.x, ri.y, pSegment->m_Result.im, (JBig2ComposeOp)(ri.flags & 0x03)); delete pSegment->m_Result.im; pSegment->m_Result.im = nullptr; } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseGenericRegion(CJBig2_Segment* pSegment, IFX_Pause* pPause) { if (!m_pGRD) { std::unique_ptr pGRD(new CJBig2_GRDProc); uint8_t cFlags; if (parseRegionInfo(&m_ri) != JBIG2_SUCCESS || m_pStream->read1Byte(&cFlags) != 0) { return JBIG2_ERROR_TOO_SHORT; } if (m_ri.height < 0 || m_ri.width < 0) return JBIG2_FAILED; pGRD->GBW = m_ri.width; pGRD->GBH = m_ri.height; pGRD->MMR = cFlags & 0x01; pGRD->GBTEMPLATE = (cFlags >> 1) & 0x03; pGRD->TPGDON = (cFlags >> 3) & 0x01; if (pGRD->MMR == 0) { if (pGRD->GBTEMPLATE == 0) { for (int32_t i = 0; i < 8; ++i) { if (m_pStream->read1Byte((uint8_t*)&pGRD->GBAT[i]) != 0) { return JBIG2_ERROR_TOO_SHORT; } } } else { for (int32_t i = 0; i < 2; ++i) { if (m_pStream->read1Byte((uint8_t*)&pGRD->GBAT[i]) != 0) { return JBIG2_ERROR_TOO_SHORT; } } } } pGRD->USESKIP = 0; m_pGRD = std::move(pGRD); } pSegment->m_nResultType = JBIG2_IMAGE_POINTER; if (m_pGRD->MMR == 0) { if (m_gbContext.empty()) { const size_t size = GetHuffContextSize(m_pGRD->GBTEMPLATE); m_gbContext.resize(size); } if (!m_pArithDecoder) { m_pArithDecoder.reset(new CJBig2_ArithDecoder(m_pStream.get())); m_ProcessingStatus = m_pGRD->Start_decode_Arith(&pSegment->m_Result.im, m_pArithDecoder.get(), &m_gbContext[0], pPause); } else { m_ProcessingStatus = m_pGRD->Continue_decode(pPause); } if (m_ProcessingStatus == FXCODEC_STATUS_DECODE_TOBECONTINUE) { if (pSegment->m_cFlags.s.type != 36) { if (!m_bBufSpecified) { JBig2PageInfo* pPageInfo = m_PageInfoList.back(); if ((pPageInfo->m_bIsStriped == 1) && (m_ri.y + m_ri.height > m_pPage->height())) { m_pPage->expand(m_ri.y + m_ri.height, (pPageInfo->m_cFlags & 4) ? 1 : 0); } } FX_RECT Rect = m_pGRD->GetReplaceRect(); m_pPage->composeFrom(m_ri.x + Rect.left, m_ri.y + Rect.top, pSegment->m_Result.im, (JBig2ComposeOp)(m_ri.flags & 0x03), &Rect); } return JBIG2_SUCCESS; } else { m_pArithDecoder.reset(); m_gbContext.clear(); if (!pSegment->m_Result.im) { m_ProcessingStatus = FXCODEC_STATUS_ERROR; m_pGRD.reset(); return JBIG2_ERROR_FATAL; } m_pStream->alignByte(); m_pStream->offset(2); } } else { m_pGRD->Start_decode_MMR(&pSegment->m_Result.im, m_pStream.get(), pPause); if (!pSegment->m_Result.im) { m_pGRD.reset(); return JBIG2_ERROR_FATAL; } m_pStream->alignByte(); } if (pSegment->m_cFlags.s.type != 36) { if (!m_bBufSpecified) { JBig2PageInfo* pPageInfo = m_PageInfoList.back(); if ((pPageInfo->m_bIsStriped == 1) && (m_ri.y + m_ri.height > m_pPage->height())) { m_pPage->expand(m_ri.y + m_ri.height, (pPageInfo->m_cFlags & 4) ? 1 : 0); } } FX_RECT Rect = m_pGRD->GetReplaceRect(); m_pPage->composeFrom(m_ri.x + Rect.left, m_ri.y + Rect.top, pSegment->m_Result.im, (JBig2ComposeOp)(m_ri.flags & 0x03), &Rect); delete pSegment->m_Result.im; pSegment->m_Result.im = nullptr; } m_pGRD.reset(); return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseGenericRefinementRegion(CJBig2_Segment* pSegment) { JBig2RegionInfo ri; uint8_t cFlags; if (parseRegionInfo(&ri) != JBIG2_SUCCESS || m_pStream->read1Byte(&cFlags) != 0) { return JBIG2_ERROR_TOO_SHORT; } std::unique_ptr pGRRD(new CJBig2_GRRDProc); pGRRD->GRW = ri.width; pGRRD->GRH = ri.height; pGRRD->GRTEMPLATE = cFlags & 0x01; pGRRD->TPGRON = (cFlags >> 1) & 0x01; if (pGRRD->GRTEMPLATE == 0) { for (int32_t i = 0; i < 4; ++i) { if (m_pStream->read1Byte((uint8_t*)&pGRRD->GRAT[i]) != 0) return JBIG2_ERROR_TOO_SHORT; } } CJBig2_Segment* pSeg = nullptr; if (pSegment->m_nReferred_to_segment_count > 0) { int32_t i; for (i = 0; i < pSegment->m_nReferred_to_segment_count; ++i) { pSeg = findSegmentByNumber(pSegment->m_pReferred_to_segment_numbers[0]); if (!pSeg) return JBIG2_ERROR_FATAL; if (pSeg->m_cFlags.s.type == 4 || pSeg->m_cFlags.s.type == 20 || pSeg->m_cFlags.s.type == 36 || pSeg->m_cFlags.s.type == 40) { break; } } if (i >= pSegment->m_nReferred_to_segment_count) return JBIG2_ERROR_FATAL; pGRRD->GRREFERENCE = pSeg->m_Result.im; } else { pGRRD->GRREFERENCE = m_pPage.get(); } pGRRD->GRREFERENCEDX = 0; pGRRD->GRREFERENCEDY = 0; const size_t size = GetRefAggContextSize(pGRRD->GRTEMPLATE); std::unique_ptr grContext( FX_Alloc(JBig2ArithCtx, size)); JBIG2_memset(grContext.get(), 0, sizeof(JBig2ArithCtx) * size); std::unique_ptr pArithDecoder( new CJBig2_ArithDecoder(m_pStream.get())); pSegment->m_nResultType = JBIG2_IMAGE_POINTER; pSegment->m_Result.im = pGRRD->decode(pArithDecoder.get(), grContext.get()); if (!pSegment->m_Result.im) return JBIG2_ERROR_FATAL; m_pStream->alignByte(); m_pStream->offset(2); if (pSegment->m_cFlags.s.type != 40) { if (!m_bBufSpecified) { JBig2PageInfo* pPageInfo = m_PageInfoList.back(); if ((pPageInfo->m_bIsStriped == 1) && (ri.y + ri.height > m_pPage->height())) { m_pPage->expand(ri.y + ri.height, (pPageInfo->m_cFlags & 4) ? 1 : 0); } } m_pPage->composeFrom(ri.x, ri.y, pSegment->m_Result.im, (JBig2ComposeOp)(ri.flags & 0x03)); delete pSegment->m_Result.im; pSegment->m_Result.im = nullptr; } return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseTable(CJBig2_Segment* pSegment) { pSegment->m_nResultType = JBIG2_HUFFMAN_TABLE_POINTER; pSegment->m_Result.ht = nullptr; std::unique_ptr pHuff( new CJBig2_HuffmanTable(m_pStream.get())); if (!pHuff->IsOK()) return JBIG2_ERROR_FATAL; pSegment->m_Result.ht = pHuff.release(); m_pStream->alignByte(); return JBIG2_SUCCESS; } int32_t CJBig2_Context::parseRegionInfo(JBig2RegionInfo* pRI) { if (m_pStream->readInteger((uint32_t*)&pRI->width) != 0 || m_pStream->readInteger((uint32_t*)&pRI->height) != 0 || m_pStream->readInteger((uint32_t*)&pRI->x) != 0 || m_pStream->readInteger((uint32_t*)&pRI->y) != 0 || m_pStream->read1Byte(&pRI->flags) != 0) { return JBIG2_ERROR_TOO_SHORT; } return JBIG2_SUCCESS; } JBig2HuffmanCode* CJBig2_Context::decodeSymbolIDHuffmanTable( CJBig2_BitStream* pStream, uint32_t SBNUMSYMS) { const size_t kRunCodesSize = 35; int32_t runcodes[kRunCodesSize]; int32_t runcodes_len[kRunCodesSize]; for (size_t i = 0; i < kRunCodesSize; ++i) { if (pStream->readNBits(4, &runcodes_len[i]) != 0) return nullptr; } huffman_assign_code(runcodes, runcodes_len, kRunCodesSize); std::unique_ptr SBSYMCODES( FX_Alloc(JBig2HuffmanCode, SBNUMSYMS)); int32_t run = 0; int32_t i = 0; while (i < (int)SBNUMSYMS) { size_t j; int32_t nVal = 0; int32_t nBits = 0; uint32_t nTemp; while (true) { if (pStream->read1Bit(&nTemp) != 0) return nullptr; nVal = (nVal << 1) | nTemp; ++nBits; for (j = 0; j < kRunCodesSize; ++j) { if (nBits == runcodes_len[j] && nVal == runcodes[j]) break; } if (j < kRunCodesSize) break; } int32_t runcode = static_cast(j); if (runcode < 32) { SBSYMCODES.get()[i].codelen = runcode; run = 0; } else if (runcode == 32) { if (pStream->readNBits(2, &nTemp) != 0) return nullptr; run = nTemp + 3; } else if (runcode == 33) { if (pStream->readNBits(3, &nTemp) != 0) return nullptr; run = nTemp + 3; } else if (runcode == 34) { if (pStream->readNBits(7, &nTemp) != 0) return nullptr; run = nTemp + 11; } if (run > 0) { if (i + run > (int)SBNUMSYMS) return nullptr; for (int32_t k = 0; k < run; ++k) { if (runcode == 32 && i > 0) { SBSYMCODES.get()[i + k].codelen = SBSYMCODES.get()[i - 1].codelen; } else { SBSYMCODES.get()[i + k].codelen = 0; } } i += run; } else { ++i; } } huffman_assign_code(SBSYMCODES.get(), SBNUMSYMS); return SBSYMCODES.release(); } void CJBig2_Context::huffman_assign_code(int* CODES, int* PREFLEN, int NTEMP) { // TODO(thestig) CJBig2_HuffmanTable::parseFromCodedBuffer() has similar code. int CURLEN, LENMAX, CURCODE, CURTEMP, i; int* LENCOUNT; int* FIRSTCODE; LENMAX = 0; for (i = 0; i < NTEMP; ++i) { if (PREFLEN[i] > LENMAX) { LENMAX = PREFLEN[i]; } } LENCOUNT = FX_Alloc(int, LENMAX + 1); JBIG2_memset(LENCOUNT, 0, sizeof(int) * (LENMAX + 1)); FIRSTCODE = FX_Alloc(int, LENMAX + 1); for (i = 0; i < NTEMP; ++i) { ++LENCOUNT[PREFLEN[i]]; } CURLEN = 1; FIRSTCODE[0] = 0; LENCOUNT[0] = 0; while (CURLEN <= LENMAX) { FIRSTCODE[CURLEN] = (FIRSTCODE[CURLEN - 1] + LENCOUNT[CURLEN - 1]) << 1; CURCODE = FIRSTCODE[CURLEN]; CURTEMP = 0; while (CURTEMP < NTEMP) { if (PREFLEN[CURTEMP] == CURLEN) { CODES[CURTEMP] = CURCODE; CURCODE = CURCODE + 1; } CURTEMP = CURTEMP + 1; } CURLEN = CURLEN + 1; } FX_Free(LENCOUNT); FX_Free(FIRSTCODE); } void CJBig2_Context::huffman_assign_code(JBig2HuffmanCode* SBSYMCODES, int NTEMP) { int CURLEN, LENMAX, CURCODE, CURTEMP, i; int* LENCOUNT; int* FIRSTCODE; LENMAX = 0; for (i = 0; i < NTEMP; ++i) { if (SBSYMCODES[i].codelen > LENMAX) { LENMAX = SBSYMCODES[i].codelen; } } LENCOUNT = FX_Alloc(int, (LENMAX + 1)); JBIG2_memset(LENCOUNT, 0, sizeof(int) * (LENMAX + 1)); FIRSTCODE = FX_Alloc(int, (LENMAX + 1)); for (i = 0; i < NTEMP; ++i) { ++LENCOUNT[SBSYMCODES[i].codelen]; } CURLEN = 1; FIRSTCODE[0] = 0; LENCOUNT[0] = 0; while (CURLEN <= LENMAX) { FIRSTCODE[CURLEN] = (FIRSTCODE[CURLEN - 1] + LENCOUNT[CURLEN - 1]) << 1; CURCODE = FIRSTCODE[CURLEN]; CURTEMP = 0; while (CURTEMP < NTEMP) { if (SBSYMCODES[CURTEMP].codelen == CURLEN) { SBSYMCODES[CURTEMP].code = CURCODE; CURCODE = CURCODE + 1; } CURTEMP = CURTEMP + 1; } CURLEN = CURLEN + 1; } FX_Free(LENCOUNT); FX_Free(FIRSTCODE); } ",16190,True,3313.788339528285,median "#pragma ident ""$Id$"" //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk 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 // any later version. // // The GPSTk 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= /** * @file EngNav.cpp * Engineering units navigation message abstraction. */ #include #include #include #include ""EngNav.hpp"" #include ""GNSSconstants.hpp"" #ifdef _MSC_VER #define LDEXP(x,y) ldexp(x,y) #else #define LDEXP(x,y) std::ldexp(x,y) #endif namespace gpstk { /// DecodeBits . struct DecodeBits { short startBit; short numBits; }; /** DecodeQuant contains the information necessary to decode * a given quantity for a particular navigation message * subframe. */ struct DecodeQuant { short outIndex; ///< Output array index (0-19) short pow2; ///< Power of 2 to scale factor short powPI; ///< Power of PI scale factor double scale; ///< Scalar scale factor short signq; ///< 0 = unsigned, 1 = signed DecodeBits fmt[2]; ///< start bit, #bits for up to 2 sections DecodeQuant *nxtq; ///< Pointer to next structure in list }; /** Pointers to list of subframe conversions. There are ten * formats numbered 1-10. Index 0 is unused. */ static DecodeQuant *subframeList[11]; /// Table of powers of PI, initialized in EngNav(). static double PItab[7] = {0,0,0,0,0,0,0}; static DecodeQuant formats[] = { { 0, 0, 0, 1.0L, 0,{ { 1, 8}, { 0, 0} }, 0 }, /* Preamble */ { 1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0} }, 0 }, /* Message */ { 2, 0, 0, 6.0L, 0,{ { 31,17}, { 0, 0} }, 0 }, /* HOW */ { 3, 0, 0, 1.0L, 0,{ { 48, 2}, { 0, 0} }, 0 }, /* ""alert"" */ { 4, 0, 0, 1.0L, 0,{ { 50, 3}, { 0, 0} }, 0 }, /* SF ID */ { 5, 0, 0, 1.0L, 0,{ { 61, 10},{ 0, 0} }, 0 }, /* week # */ { 6, 0, 0, 1.0L, 0,{ { 71, 2},{ 0, 0} }, 0}, /* L2 code */ { 7, 0, 0, 1.0L, 0,{ { 73, 4},{ 0, 0} }, 0}, /* accuracy */ { 8, 0, 0, 1.0L, 0,{ { 77, 6},{ 0, 0} }, 0}, /* health */ { 9, 11, 0, 1.0L, 0,{ { 83, 2},{ 211,8}}, 0}, /* AODC */ { 10, 0, 0, 1.0L, 0,{ { 91, 1},{ 0, 0}}, 0}, /* L2 P */ { 11, -31, 0, 1.0L, 1,{ {197, 8},{ 0, 0}}, 0}, /* Tgd */ { 12, 4, 0, 1.0L, 0,{ {219, 16},{ 0, 0}}, 0}, /* Toc */ { 13, -55, 0, 1.0L, 1,{ {241, 8},{ 0, 0}}, 0}, /* Af2 */ { 14, -43, 0, 1.0L, 1,{ {249, 16},{ 0, 0}}, 0}, /* Af1 */ { 15, -31, 0, 1.0L, 1,{ {271, 22}, {0, 0}}, 0}, /* Af0 */ /* Pattern 2 */ {0, 0, 0, 1.0L, 0,{ { 1, 8}, {0, 0 }}, 0 }, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0 }}, 0 }, /* Message */ {2, 0, 0, 6.0L, 0,{ { 31,17}, { 0, 0 }}, 0 }, /* HOW */ {3, 0, 0, 1.0L, 0,{ { 48, 2}, { 0, 0 }}, 0 }, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ { 50, 3}, { 0, 0 }}, 0 }, /* SF ID */ {5, 11, 0, 1.0L, 0,{ { 61, 8 }, { 0, 0 }}, 0 }, /* AODE */ {6, -5, 0, 1.0L, 1,{ { 69, 16 }, { 0, 0 }}, 0 }, /* Crs */ {7, -43, 1, 1.0L, 1,{ { 91,16 }, { 0, 0 }}, 0 }, /* delta n */ {8, -31, 1, 1.0L, 1,{ { 107, 8 }, {121,24 }}, 0 }, /* M0 */ {9, -29, 0, 1.0L, 1,{ { 151, 16}, { 0, 0 }}, 0}, /* Cuc */ {10, -33, 0, 1.0L, 0,{ { 167, 8}, {181,24 }}, 0}, /* ecc */ {11, -29, 0, 1.0L, 1,{ { 211,16}, { 0, 0 }}, 0}, /* Cus */ {12, -19, 0, 1.0L, 0,{ { 227, 8}, {241, 24 }}, 0}, /* sqrt(A) */ {13, 4, 0, 1.0L, 0,{ { 271,16}, { 0, 0 }}, 0}, /* Toe */ {14, 0, 0, 1.0L, 0,{ { 287, 1}, { 0, 0 }}, 0}, /* fit init */ {15, 0, 0, 900.0L, 0,{ { 288, 5}, { 0, 0 }}, 0}, /* AODO */ /* Pattern 3 */ {0, 0, 0, 1.0L, 0,{ { 1, 8}, { 0, 0 }}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0 }}, 0}, /* Message */ {2, 0, 0, 6.0L, 0,{ { 31,17}, { 0, 0 }}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0,{ { 48, 2}, { 0, 0 }}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ { 50, 3}, { 0, 0 }}, 0}, /* SF ID */ {5, -29, 0, 1.0L, 1,{ { 61,16}, { 0, 0 }}, 0}, /* Cic */ {6, -31, 1, 1.0L, 1,{ { 77,8}, { 91, 24}}, 0}, /* OMEGA0 */ {7, -29, 0, 1.0L, 1,{ { 121,16}, { 0, 0 }}, 0}, /* Cis */ {8, -31, 1, 1.0L, 1,{ { 137, 8}, {151, 24}}, 0}, /* i0 */ {9, -5, 0, 1.0L, 1,{ { 181,16}, { 0, 0 }}, 0}, /* Crc */ {10, -31, 1, 1.0L, 1,{ { 197, 8}, {211, 24}}, 0}, /* w */ {11, -43, 1, 1.0L, 1,{ { 241,24}, { 0, 0 }}, 0}, /* OMEGAdot */ {12, 11, 0, 1.0L, 0,{ { 271, 8}, { 0, 0 }}, 0}, /* AODE */ {13, -43, 1, 1.0L, 1,{ { 279,14}, { 0, 0 }}, 0}, /* idot */ /* Pattern 4 */ {0, 0, 0, 1.0L, 0,{ { 1, 8}, { 0, 0}}, 0 }, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0,{ { 31,17}, { 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0,{ { 48, 2}, { 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ { 50, 3}, { 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0,{ { 61, 2}, { 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0,{ { 63, 6}, { 0, 0}}, 0}, /* Page ID */ {7, -21, 0, 1.0L, 0,{ { 69,16}, { 0, 0}}, 0}, /* e */ {8, 12, 0, 1.0L, 0,{ { 91, 8}, { 0, 0}}, 0}, /* time ep */ {9, -19, 1, 1.0L, 1,{ { 99,16}, { 0, 0}}, 0}, /* i offset */ {10, -38, 1, 1.0L, 1,{ {121,16}, { 0, 0}}, 0}, /* OMEGADOT */ {11, 0, 0, 1.0L, 0,{ {137, 8}, { 0, 0}}, 0}, /* Health */ {12, -11, 0, 1.0L, 0,{ {151,24}, { 0, 0}}, 0}, /* SQRT(a) */ {13, -23, 1, 1.0L, 1,{ {181,24}, { 0, 0}}, 0}, /* OMEGA */ {14, -23, 1, 1.0L, 1,{ {211,24}, { 0, 0}}, 0}, /* w */ {15, -23, 1, 1.0L, 1,{ {241,24}, { 0, 0}}, 0}, /* Mean Ano */ {16, -20, 0, 1.0L, 1,{ {271, 8}, {290, 3}}, 0}, /* AF0 */ {17, -38, 0, 1.0L, 1,{ {279,11}, { 0, 0}}, 0}, /* AF1 */ {18, 0, 0, 1.0L, 0,{ { 0, 0}, { 0, 0}}, 0}, /* REF WEEK */ {19, 0, 0, 1.0L, 0,{ { 63, 6}, { 0, 0}}, 0}, /* PRN # */ /* Pattern 5 */ {0, 0, 0, 1.0L, 0,{ { 1, 8}, { 0, 0}}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0,{ {31, 17}, { 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0,{ {48, 2}, { 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ {50, 3}, { 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0,{ { 61, 2}, { 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0,{ { 63, 6}, { 0, 0}}, 0}, /* Page ID */ {7, 0, 0, 1.0L, 0,{ { 77, 8}, { 0, 0}}, 0}, /* Refweek */ {8, 0, 0, 1.0L, 0,{ { 91, 6}, { 0, 0}}, 0}, /* SV1 Hlth */ {9, 0, 0, 1.0L, 0,{ { 97, 6}, { 0, 0}}, 0}, /* SV2 Hlth */ {10, 0, 0, 1.0L, 0,{ { 103,6}, { 0, 0}}, 0}, /* SV3 Hlth */ {11, 0, 0, 1.0L, 0,{ { 109,6}, { 0, 0}}, 0}, /* SV4 Hlth */ {12, 0, 0, 1.0L, 0,{ { 121,6}, { 0, 0}}, 0}, /* SV5 Hlth */ {13, 0, 0, 1.0L, 0,{ { 127,6}, { 0, 0}}, 0}, /* SV6 Hlth */ {14, 0, 0, 1.0L, 0,{ { 133,6}, { 0, 0}}, 0}, /* SV7 Hlth */ {15, 0, 0, 1.0L, 0,{ { 139,6}, { 0, 0}}, 0}, /* SV8 Hlth */ {16, 0, 0, 1.0L, 0,{ { 151,6}, { 0, 0}}, 0}, /* SV9 Hlth */ {17, 0, 0, 1.0L, 0,{ { 157,6}, { 0, 0}}, 0}, /* SV10 Hlth*/ {18, 0, 0, 1.0L, 0,{ { 163,6}, { 0, 0}}, 0}, /* SV11 Hlth*/ {19, 0, 0, 1.0L, 0,{ { 169,6}, { 0, 0}}, 0}, /* SV12 Hlth*/ {20, 0, 0, 1.0L, 0,{ { 181,6}, { 0, 0}}, 0}, /* SV13 Hlth*/ {21, 0, 0, 1.0L, 0,{ { 187,6}, { 0, 0}}, 0}, /* SV14 Hlth*/ {22, 0, 0, 1.0L, 0,{ { 193,6}, { 0, 0}}, 0}, /* SV15 Hlth*/ {23, 0, 0, 1.0L, 0,{ { 199,6}, { 0, 0}}, 0}, /* SV16 Hlth*/ {24, 0, 0, 1.0L, 0,{ { 211,6}, { 0, 0}}, 0}, /* SV17 Hlth*/ {25, 0, 0, 1.0L, 0,{ { 217,6}, { 0, 0}}, 0}, /* SV18 Hlth*/ {26, 0, 0, 1.0L, 0,{ { 223,6}, { 0, 0}}, 0}, /* SV19 Hlth*/ {27, 0, 0, 1.0L, 0,{ { 229,6}, { 0, 0}}, 0}, /* SV20 Hlth*/ {28, 0, 0, 1.0L, 0,{ { 241,6}, { 0, 0}}, 0}, /* SV21 Hlth*/ {29, 0, 0, 1.0L, 0,{ { 247,6}, { 0, 0}}, 0}, /* SV22 Hlth*/ {30, 0, 0, 1.0L, 0,{ { 253,6}, { 0, 0}}, 0}, /* SV23 Hlth*/ {31, 0, 0, 1.0L, 0,{ { 259,6}, { 0, 0}}, 0}, /* SV24 Hlth*/ /* Pattern 6 */ {0, 0, 0, 1.0L, 0, { { 1, 8},{ 0, 0}}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0, { { 9, 14},{ 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0, { { 31, 17},{ 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0, { { 48, 2},{ 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0, { { 50, 3},{ 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0, { { 61, 2},{ 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0, { { 63, 6},{ 0, 0}}, 0}, /* Page ID */ {7, 0, 0, 1.0L, 0, { { 69, 16},{ 0, 0}}, 0}, /* Reserved */ {8, 0, 0, 1.0L, 0, { { 91, 24},{ 0, 0}}, 0}, /* Reserved */ {9, 0, 0, 1.0L, 0, { { 121, 24},{ 0, 0}}, 0}, /* Reserved */ {10, 0, 0, 1.0L, 0, { { 151, 24},{ 0, 0}}, 0}, /* Reserved */ {11, 0, 0, 1.0L, 0, { { 181, 24},{ 0, 0}}, 0}, /* Reserved */ {12, 0, 0, 1.0L, 0, { { 211, 24},{ 0, 0}}, 0}, /* Reserved */ {13, 0, 0, 1.0L, 0, { { 241, 8},{ 0, 0}}, 0}, /* Reserved */ {14, 0, 0, 1.0L, 0, { { 249,16},{ 0, 0}}, 0}, /* Reserved */ /* Pattern 7 */ {0, 0, 0, 1.0L, 0, { { 1, 8}, { 0, 0} }, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0, { { 9, 14}, { 0, 0} }, 0}, /* Message */ {2, 0, 0, 6.0L, 0, { { 31, 17}, { 0, 0} }, 0}, /* HOW */ {3, 0, 0, 1.0L, 0, { { 48, 2}, { 0, 0} }, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0, { { 50, 3}, { 0, 0} }, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0, { { 61, 2}, { 0, 0} }, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0, { { 63, 6}, { 0, 0} }, 0}, /* Page ID */ {7, 0, 0, 1.0L, 0, { { 69, 16}, { 0, 0} }, 0}, /* Reserved */ {8, 0, 0, 1.0L, 0, { { 91, 24}, { 0, 0} }, 0}, /* Reserved */ {9, 0, 0, 1.0L, 0, { {121, 24}, { 0, 0} }, 0}, /* Reserved */ {10, 0, 0, 1.0L, 0, { {151, 24}, { 0, 0} }, 0}, /* Reserved */ {11, 0, 0, 1.0L, 0, { {181, 24}, { 0, 0} }, 0}, /* Reserved */ {12, 0, 0, 1.0L, 0, { {211, 24}, { 0, 0} }, 0}, /* Reserved */ {13, 0, 0, 1.0L, 0, { {241, 8}, { 0, 0} }, 0}, /* Reserved */ {14, 0, 0, 1.0L, 0, { {249, 16}, { 0, 0} }, 0}, /* Reserved */ /* Pattern 8 */ {0, 0, 0, 1.0L, 0,{ { 1, 8},{ 0, 0}}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14},{ 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0,{ { 31, 17},{ 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0,{ { 48, 2},{ 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ { 50, 3},{ 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0,{ { 61, 2},{ 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0,{ { 63, 6},{ 0, 0}}, 0}, /* Page ID */ {7, -30, 0, 1.0L, 1,{ { 69, 8},{ 0, 0}}, 0}, /* ALPHA0 */ {8, -27, -1, 1.0L, 1,{ { 77, 8},{ 0, 0}}, 0}, /* ALPHA1 */ {9, -24, -2, 1.0L, 1,{ { 91, 8},{ 0, 0}}, 0}, /* ALPHA2 */ {10, -24, -3, 1.0L, 1,{ { 99, 8},{ 0, 0}}, 0}, /* ALPHA3 */ {11, 11, 0, 1.0L, 1,{ { 107, 8},{ 0, 0}}, 0}, /* BETA0 */ {12, 14, -1, 1.0L, 1,{ { 121, 8},{ 0, 0}}, 0}, /* BETA1 */ {13, 16, -2, 1.0L, 1,{ { 129, 8},{ 0, 0}}, 0}, /* BETA2 */ {14, 16, -3, 1.0L, 1,{ { 137, 8},{ 0, 0}}, 0}, /* BETA3 */ {15, -30, 0, 1.0L, 1,{ { 181,24},{211, 8}}, 0}, /* A0 */ {16, -50, 0, 1.0L, 1,{ { 151,24},{ 0, 0}}, 0}, /* A1 */ {17, 12, 0, 1.0L, 0,{ { 219, 8},{ 0, 0}}, 0}, /* Tot */ {18, 0, 0, 1.0L, 0,{ { 227, 8},{ 0, 0}}, 0}, /* wnt */ {19, 0, 0, 1.0L, 1,{ { 241, 8},{ 0, 0}}, 0}, /* DELTATLS */ {20, 0, 0, 1.0L, 0,{ { 249, 8},{ 0, 0}}, 0}, /* WN LSF */ {21, 0, 0, 1.0L, 0,{ { 257, 8},{ 0, 0}}, 0}, /* DN */ {22, 0, 0, 1.0L, 1,{ { 271, 8},{ 0, 0}}, 0}, /* DELTALSF */ /* Pattern 9 */ {0, 0, 0, 1.0L, 0, { { 1, 8}, { 0, 0}}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0, { { 9, 14}, { 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0, { { 31, 17}, { 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0, { { 48, 2}, { 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0, { { 50, 3}, { 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0, { { 61, 2}, { 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0, { { 63, 6}, { 0, 0}}, 0}, /* Page ID */ {7, 0, 0, 1.0L, 0, { { 69, 4}, { 0, 0}}, 0}, /* SV1 cnfig*/ {8, 0, 0, 1.0L, 0, { { 73, 4}, { 0, 0}}, 0}, /* SV2 cnfig*/ {9, 0, 0, 1.0L, 0, { { 77, 4}, { 0, 0}}, 0}, /* SV3 cnfig*/ {10, 0, 0, 1.0L, 0, { { 81, 4}, { 0, 0}}, 0}, /* SV4 cnfig*/ {11, 0, 0, 1.0L, 0, { { 91, 4}, { 0, 0}}, 0}, /* SV5 cnfig*/ {12, 0, 0, 1.0L, 0, { { 95, 4}, { 0, 0}}, 0}, /* SV6 cnfig*/ {13, 0, 0, 1.0L, 0, { { 99, 4}, { 0, 0}}, 0}, /* SV7 cnfig*/ {14, 0, 0, 1.0L, 0, { { 103, 4}, { 0, 0}}, 0}, /* SV8 cnfig*/ {15, 0, 0, 1.0L, 0, { { 107, 4}, { 0, 0}}, 0}, /* SV9 cnfig*/ {16, 0, 0, 1.0L, 0, { { 111, 4}, { 0, 0}}, 0}, /* SV10 cnfig*/ {17, 0, 0, 1.0L, 0, { { 121, 4}, { 0, 0}}, 0}, /* SV11 cnfig*/ {18, 0, 0, 1.0L, 0, { { 125, 4}, { 0, 0}}, 0}, /* SV12 cnfig*/ {19, 0, 0, 1.0L, 0, { { 129, 4}, { 0, 0}}, 0}, /* SV13 cnfig*/ {20, 0, 0, 1.0L, 0, { { 133, 4}, { 0, 0}}, 0}, /* SV14 cnfig*/ {21, 0, 0, 1.0L, 0, { { 137, 4}, { 0, 0}}, 0}, /* SV15 cnfig*/ {22, 0, 0, 1.0L, 0, { { 141, 4}, { 0, 0}}, 0}, /* SV16 cnfig*/ {23, 0, 0, 1.0L, 0, { { 151, 4}, { 0, 0}}, 0}, /* SV17 cnfig*/ {24, 0, 0, 1.0L, 0, { { 155, 4}, { 0, 0}}, 0}, /* SV18 cnfig*/ {25, 0, 0, 1.0L, 0, { { 159, 4}, { 0, 0}}, 0}, /* SV19 cnfig*/ {26, 0, 0, 1.0L, 0, { { 163, 4}, { 0, 0}}, 0}, /* SV20 cnfig*/ {27, 0, 0, 1.0L, 0, { { 167, 4}, { 0, 0}}, 0}, /* SV21 cnfig*/ {28, 0, 0, 1.0L, 0, { { 171, 4}, { 0, 0}}, 0}, /* SV22 cnfig*/ {29, 0, 0, 1.0L, 0, { { 181, 4}, { 0, 0}}, 0}, /* SV23 cnfig*/ {30, 0, 0, 1.0L, 0, { { 185, 4}, { 0, 0}}, 0}, /* SV24 cnfig*/ {31, 0, 0, 1.0L, 0, { { 189, 4}, { 0, 0}}, 0}, /* SV25 cnfig*/ {32, 0, 0, 1.0L, 0, { { 193, 4}, { 0, 0}}, 0}, /* SV26 cnfig*/ {33, 0, 0, 1.0L, 0, { { 197, 4}, { 0, 0}}, 0}, /* SV27 cnfig*/ {34, 0, 0, 1.0L, 0, { { 201, 4}, { 0, 0}}, 0}, /* SV28 cnfig*/ {35, 0, 0, 1.0L, 0, { { 211, 4}, { 0, 0}}, 0}, /* SV29 cnfig*/ {36, 0, 0, 1.0L, 0, { { 215, 4}, { 0, 0}}, 0}, /* SV30 cnfig*/ {37, 0, 0, 1.0L, 0, { { 219, 4}, { 0, 0}}, 0}, /* SV31 cnfig*/ {38, 0, 0, 1.0L, 0, { { 223, 4}, { 0, 0}}, 0}, /* SV32 cnfig*/ {39, 0, 0, 1.0L, 0, { { 229, 6}, { 0, 0}}, 0}, /* SV25 Hlth */ {40, 0, 0, 1.0L, 0, { { 241, 6}, { 0, 0}}, 0}, /* SV26 Hlth */ {41, 0, 0, 1.0L, 0, { { 247, 6}, { 0, 0}}, 0}, /* SV27 Hlth */ {42, 0, 0, 1.0L, 0, { { 253, 6}, { 0, 0}}, 0}, /* SV28 Hlth */ {43, 0, 0, 1.0L, 0, { { 259, 6}, { 0, 0}}, 0}, /* SV29 Hlth */ {44, 0, 0, 1.0L, 0, { { 271, 6}, { 0, 0}}, 0}, /* SV30 Hlth */ {45, 0, 0, 1.0L, 0, { { 277, 6}, { 0, 0}}, 0}, /* SV31 Hlth */ {46, 0, 0, 1.0L, 0, { { 283, 6}, { 0, 0}}, 0}, /* SV32 Hlth */ /* Pattern 10 */ {0, 0, 0, 1.0L, 0,{ { 1, 8}, { 0, 0}}, 0}, /* Preamble */ {1, 0, 0, 1.0L, 0,{ { 9, 14}, { 0, 0}}, 0}, /* Message */ {2, 0, 0, 6.0L, 0,{ { 31, 17}, { 0, 0}}, 0}, /* HOW */ {3, 0, 0, 1.0L, 0,{ { 48, 2}, { 0, 0}}, 0}, /* ""alert"" */ {4, 0, 0, 1.0L, 0,{ { 50, 3}, { 0, 0}}, 0}, /* SF ID */ {5, 0, 0, 1.0L, 0,{ { 61, 2}, { 0, 0}}, 0}, /* Dataflag */ {6, 0, 0, 1.0L, 0,{ { 63, 6}, { 0, 0}}, 0}, /* Page ID */ {7, 0, 0, 1.0L, 0,{ { 69, 8}, { 0, 0}}, 0}, /* ASCII */ {8, 0, 0, 1.0L, 0,{ { 77, 8}, { 0, 0}}, 0}, /* ASCII */ {9, 0, 0, 1.0L, 0,{ { 91, 8}, { 0, 0}}, 0}, /* ASCII */ {10, 0, 0, 1.0L, 0,{ { 99, 8}, { 0, 0}}, 0}, /* ASCII */ {11, 0, 0, 1.0L, 0,{ { 107, 8}, { 0, 0}}, 0}, /* ASCII */ {12, 0, 0, 1.0L, 0,{ { 121, 8}, { 0, 0}}, 0}, /* ASCII */ {13, 0, 0, 1.0L, 0,{ { 129, 8}, { 0, 0}}, 0}, /* ASCII */ {14, 0, 0, 1.0L, 0,{ { 137, 8}, { 0, 0}}, 0}, /* ASCII */ {15, 0, 0, 1.0L, 0,{ { 151, 8}, { 0, 0}}, 0}, /* ASCII */ {16, 0, 0, 1.0L, 0,{ { 159, 8}, { 0, 0}}, 0}, /* ASCII */ {17, 0, 0, 1.0L, 0,{ { 167, 8}, { 0, 0}}, 0}, /* ASCII */ {18, 0, 0, 1.0L, 0,{ { 181, 8}, { 0, 0}}, 0}, /* ASCII */ {19, 0, 0, 1.0L, 0,{ { 189, 8}, { 0, 0}}, 0}, /* ASCII */ {20, 0, 0, 1.0L, 0,{ { 197, 8}, { 0, 0}}, 0}, /* ASCII */ {21, 0, 0, 1.0L, 0,{ { 211, 8}, { 0, 0}}, 0}, /* ASCII */ {22, 0, 0, 1.0L, 0,{ { 219, 8}, { 0, 0}}, 0}, /* ASCII */ {23, 0, 0, 1.0L, 0,{ { 227, 8}, { 0, 0}}, 0}, /* ASCII */ {24, 0, 0, 1.0L, 0,{ { 241, 8}, { 0, 0}}, 0}, /* ASCII */ {25, 0, 0, 1.0L, 0,{ { 249, 8}, { 0, 0}}, 0}, /* ASCII */ {26, 0, 0, 1.0L, 0,{ { 257, 8}, { 0, 0}}, 0}, /* ASCII */ {27, 0, 0, 1.0L, 0,{ { 271, 8}, { 0, 0}}, 0}, /* ASCII */ {28, 0, 0, 1.0L, 0,{ { 279, 8}, { 0, 0}}, 0}, /* ASCII */ /* Dummy pattern for constructor */ {0, 0, 0, 1.0L, 0,{{ 0, 0}, { 0, 0}}, 0} }; EngNav::EngNav() throw() { short i=0, n=0; static short initialized = 0; if (initialized) return; // Set up pointers within subframe format structure. for (i=1; i<=10; i++) { subframeList[i] = &formats[n]; while (formats[n+1].outIndex != 0) { formats[n].nxtq = &formats[n+1]; n++; } formats[n].nxtq = NULL; n++; } // Calculate powers of PI table. PItab[3] = 1.0L; for (i=0; i<=2; i++) { PItab[4+i] = PItab[3+i] * PI; PItab[2-i] = PItab[3-i] / PI; } initialized = 1; } // Retained for backward compatibility bool EngNav :: subframeConvert(const long input[10], int gpsWeek, double output[60]) throw() { uint32_t tinput[10]; for (int n=0; n<10; ++n) tinput[n] = static_cast( input[n] ); short tgpsWeek = gpsWeek; return( subframeConvert( tinput, tgpsWeek, output )); } bool EngNav :: subframeConvert(const uint32_t input[10], short gpsWeek, double output[60]) throw() { short patId = -2, i = 2; struct DecodeQuant *p=NULL; for (i=0; i< 20; i++) output[i] = 0.0L; // Get subframe and page id and derive pattern number. if ((patId = getSubframePattern(input)) == 0) return false; // convert each quantity in the list p = subframeList[patId]; while (p != NULL) { convertQuant(input, output, p); if(p->nxtq) p = p->nxtq; else p = NULL; } // Almanac does not contain a reference week // However we need to put one in the FIC version of the Almanac if (patId==4) { output[18]= static_cast( gpsWeek ); } // Modify the 8-bit week numbers to be the full week numbers if (patId == 8) { if (!convert8bit(gpsWeek, &output[18])) return false; if (!convert8bit(gpsWeek, &output[20])) return false; } // Change the 10 bit week number in subframe 1 to full weeks if (patId == 1) { short week10Bit = static_cast( output[5] ); output[5] = static_cast( convertXBit(gpsWeek, week10Bit, BITS10) ); } return true; } // Retained for backward compatibility bool EngNav :: convert8bit(int gpsWeek, double *output) throw() { short tgpsWeek = static_cast( gpsWeek ); short toutput = static_cast ( *output ); short retArg = convertXBit( tgpsWeek, toutput, BITS8 ); *output = static_cast(retArg); return true; } // Retained for backward compatibility bool EngNav :: convert10bit(int gpsWeek, double *output) throw() { short tgpsWeek = static_cast( gpsWeek ); short toutput = static_cast ( *output ); short retArg = convertXBit( tgpsWeek, toutput, BITS10 ); *output = static_cast(retArg); return true; } static short LIMIT[] = { 127, 511 }; static short RANGE[] = { 256, 1024 }; short EngNav :: convertXBit(short fullGPSWeek, short incompleteGPSWeek, BitConvertType type) { short extension = fullGPSWeek - (fullGPSWeek % RANGE[type]); short target = extension + incompleteGPSWeek; short diff = target - fullGPSWeek; if (diff>LIMIT[type]) target -= RANGE[type]; else if (diff< -LIMIT[type]) target += RANGE[type]; return( target ); } // Retained for backward compatibility short EngNav :: getSubframePattern(const long input[10]) throw() { uint32_t tinput[10]; for (int n=0; n<10; ++n) tinput[n] = static_cast( input[n] ); return( getSubframePattern( tinput )); } short EngNav :: getSubframePattern(const uint32_t input[10]) throw() { short iret, svid; long itemp; short patId[] = { 5, 6, 6, 6, 10, 8, 6, 7, 7, 7, 7, 7, 9 }; /*SVid 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63 */ // Get subframe id. If 1-3 return as patId. itemp = input[1]; /* move HOW to temp storage */ itemp >>= 8; /* shift so subframe id is in 3 lsb */ itemp &= 0x00000007L; /* and mask off msbs */ iret = static_cast( itemp ); /* Not a valid sf id */ if ( iret < 1 || iret > 5 ) return(0); if ( iret < 4 ) return(iret); /* If subframe 1-5, get page id and look up patId */ itemp = input[2]; /* move word 3 into temp storage */ itemp >>= 22; /* shift so SV ID is in 6 lsbs */ itemp &= 0x0000003FL; /* and mask off msbs */ svid = static_cast( itemp ); if ( svid <= 32 ) iret = 4; /* PRN orbit data */ else iret = patId[svid-51]; /* look up pat id for almanac overhead information */ return iret; } uint32_t EngNav :: computeParity(uint32_t sfword, uint32_t psfword, bool knownUpright) { /* This function is somewhat table-driven. There is one element in bmask for each of the six parity bits. Each element is a bit mask with bits set corresponding to the bits which are to be exclusive-OR'd together to form the parity check bit. The following bit maps define the bmask array. They were drawn from table 20-XIV of ICD-GPS-200C (10 OCT 1993). Bit in navigation message bit1 bit 30 bit 12 3456 789. 1234 5678 9.12 3456 789. --- ------------------------------------- D25 11 1011 0001 1111 0011 0100 1000 0000 D26 01 1101 1000 1111 1001 1010 0100 0000 D27 10 1110 1100 0111 1100 1101 0000 0000 D28 01 0111 0110 0011 1110 0110 1000 0000 D29 10 1011 1011 0001 1111 0011 0100 0000 D30 00 1011 0111 1010 1000 1001 1100 0000 */ uint32_t bmask[6] = { 0x3B1F3480L, 0x1D8F9A40L, 0x2EC7CD00L, 0x1763E680L, 0x2BB1F340L, 0x0B7A89C0L }; uint32_t D = 0; uint32_t d = sfword; uint32_t D29 = getd29(psfword); uint32_t D30 = getd30(psfword); // If D30 of the previous subframe was set, complement the word // to get the source data bits. This will also complement the // parity, but we don't need the original parity to compute the // new. if (D30 && !knownUpright) d = ~d; D |= ((D29 + BinUtils::countBits(bmask[0] & d)) % 2) << 5; D |= ((D30 + BinUtils::countBits(bmask[1] & d)) % 2) << 4; D |= ((D29 + BinUtils::countBits(bmask[2] & d)) % 2) << 3; D |= ((D30 + BinUtils::countBits(bmask[3] & d)) % 2) << 2; D |= ((D30 + BinUtils::countBits(bmask[4] & d)) % 2) << 1; D |= ((D29 + BinUtils::countBits(bmask[5] & d)) % 2); return D; } uint32_t EngNav :: fixParity(uint32_t sfword, uint32_t psfword, bool nib) { uint32_t bmask[6] = { 0x3B1F3480L, 0x1D8F9A40L, 0x2EC7CD00L, 0x1763E680L, 0x2BB1F340L, 0x0B7A89C0L }; uint32_t D = 0; uint32_t d = sfword; uint32_t D29 = getd29(psfword); uint32_t D30 = getd30(psfword); if (nib) { // make sure the non-information bits are zero to start with. d &= 0xffffff00; if ((D30 + BinUtils::countBits(bmask[4] & d)) % 2) d |= 0x00000040; if ((D29 + BinUtils::countBits(bmask[5] & d)) % 2) d |= 0x00000080; } D = computeParity(d, psfword); return D | d; } /// This is the OLD GPSTk method, left here for compatibility bool EngNav :: subframeParity(const long input[10]) { uint32_t temp[10]; for (int n=0; n<10; ++n) temp[n] = input[n]; return(checkParity( temp )); } bool EngNav :: checkParity(const std::vector& sf, bool knownUpright) { return (((sf[0] & 0x0000003f) == computeParity(sf[0], 0, knownUpright)) && ((sf[1] & 0x0000003f) == computeParity(sf[1], sf[0], knownUpright)) && ((sf[2] & 0x0000003f) == computeParity(sf[2], sf[1], knownUpright)) && ((sf[3] & 0x0000003f) == computeParity(sf[3], sf[2], knownUpright)) && ((sf[4] & 0x0000003f) == computeParity(sf[4], sf[3], knownUpright)) && ((sf[5] & 0x0000003f) == computeParity(sf[5], sf[4], knownUpright)) && ((sf[6] & 0x0000003f) == computeParity(sf[6], sf[5], knownUpright)) && ((sf[7] & 0x0000003f) == computeParity(sf[7], sf[6], knownUpright)) && ((sf[8] & 0x0000003f) == computeParity(sf[8], sf[7], knownUpright)) && ((sf[9] & 0x0000003f) == computeParity(sf[9], sf[8], knownUpright))); } bool EngNav :: checkParity(const uint32_t sf[10], bool knownUpright) { std::vector temp(10); for (size_t n=0; n<10; ++n) temp[n] = sf[n]; return checkParity(temp, knownUpright); } void EngNav :: convertQuant(const uint32_t input[10], double output[60], DecodeQuant *p) throw() { double dval; short i, n, bit1, nword, nbit; union equ { uint32_t u; int32_t s; } temp; uint32_t *b; uint32_t mask; // Convert starting bit number to word/bit pair temp.u = 0x0L; for (n=0; n<=1; n++) { if (p->fmt[n].startBit == 0) break; bit1 = p->fmt[n].startBit; nword = (bit1-1) / 30; nbit = (bit1 % 30) + 1; b = const_cast( input ) + nword; for (i=0; ifmt[n].numBits; i++) { temp.u <<= 1; mask = 0x80000000L >> nbit++; if (*b & mask) temp.u++; if (nbit>=32) { b++; nbit = 0; } } } // Convert to double and scale if (p->signq) { nbit = 32 - (p->fmt[0].numBits + p->fmt[1].numBits); temp.u <<= nbit; // Move sign bit to msb temp.s >>= nbit; // Move lsb back to right spot with sign extend dval = temp.s; } else { dval = temp.u; // msb = 0 } dval = dval * p->scale; // Scale by scalar dval = dval * PItab[ p->powPI+3 ]; // Scale by power of PI dval = LDEXP(dval,p->pow2); // Scale by power of 2 output[p->outIndex] = dval; // Store result in output array } void EngNav :: dump(std::ostream& s) { struct DecodeQuant *p = NULL; for(short pattern = 1; pattern <= 10; pattern++) { s.setf(std::ios::fixed, std::ios::floatfield); s.setf(std::ios::right, std::ios::adjustfield); s.precision(0); s.fill(' '); int n = 0; p = subframeList[pattern]; s << ""****************************************"" << ""*****************************************"" << std::endl << ""Pattern : "" << pattern << std::endl << std::endl << "" First Second"" << std::endl << "" n OutIndex pow2 powPI Scale Signq Start #bits Start #bits"" << std::endl; bool done = false; while(!done) { /* s.setf(std::ios::fixed, std::ios::floatfield); s.setf(std::ios::right, std::ios::adjustfield); s.precision(0); s.fill(' '); */ s << std::dec << std::setw(2) << n << "" "" << std::setw(3) << p->outIndex << "" "" << std::setw(3) << p->pow2 << "" "" << std::setw(3) << p->powPI << "" "" << std::setw(3) << p->scale << "" "" << std::setw(3) << p->signq << "" "" << std::setw(3) << p->fmt[0].startBit << "" "" << std::setw(3) << p->fmt[0].numBits << "" "" << std::setw(3) << p->fmt[1].startBit << "" "" << std::setw(3) << p->fmt[1].numBits << std::endl; n++; p = p->nxtq; if(p==NULL) done = true; } s << std::endl; } s << std::endl; s << ""Index Power Value\\n""; int x = -3; for(int i = 0; i < 7; i++) { s << "" "" << i << "" "" << std::setw(2) << x << "" "" << std::setw(8) << std::setprecision(5) << PItab[i] << std::endl; x++; } } } // namespace ",16258,True,4087.526359524569,median "/** @file A brief file description @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the ""License""); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /*************************************************************************** Log.cc This file defines the implementation of the static Log class, which is primarily used as a namespace. That is, there are no Log objects, but the class scope and static members provide a protected namespace for all of the logging routines and enumerated types. When C++ namespaces are more widely-implemented, Log could be implemented as a namespace rather than a class. ***************************************************************************/ #include ""ts/ink_platform.h"" #include ""Main.h"" #include ""P_EventSystem.h"" #include ""P_Net.h"" #include ""I_Machine.h"" #include ""HTTP.h"" #include ""LogAccess.h"" #include ""LogField.h"" #include ""LogFilter.h"" #include ""LogFormat.h"" #include ""LogFile.h"" #include ""LogHost.h"" #include ""LogObject.h"" #include ""LogConfig.h"" #include ""LogBuffer.h"" #include ""LogUtils.h"" #include ""Log.h"" #include ""LogSock.h"" #include ""ts/SimpleTokenizer.h"" #include ""ts/ink_apidefs.h"" #define PERIODIC_TASKS_INTERVAL_FALLBACK 5 // Log global objects inkcoreapi LogObject *Log::error_log = nullptr; LogFieldList Log::global_field_list; LogFormat *Log::global_scrap_format = nullptr; LogObject *Log::global_scrap_object = nullptr; Log::LoggingMode Log::logging_mode = LOG_MODE_NONE; // Flush thread stuff EventNotify *Log::preproc_notify; EventNotify *Log::flush_notify; InkAtomicList *Log::flush_data_list; // Collate thread stuff EventNotify Log::collate_notify; ink_thread Log::collate_thread; int Log::collation_accept_file_descriptor; int Log::collation_preproc_threads; int Log::collation_port; // Log private objects int Log::init_status = 0; int Log::config_flags = 0; bool Log::logging_mode_changed = false; uint32_t Log::periodic_tasks_interval = PERIODIC_TASKS_INTERVAL_FALLBACK; // Hash table for LogField symbols InkHashTable *Log::field_symbol_hash = nullptr; RecRawStatBlock *log_rsb; /*------------------------------------------------------------------------- Log::change_configuration This routine is invoked when the current LogConfig object says it needs to be changed (as the result of a manager callback). -------------------------------------------------------------------------*/ LogConfig *Log::config = nullptr; static unsigned log_configid = 0; // Downcast from a Ptr to a Ptr. static Ptr make_alias_map(Ptr &table) { return make_ptr(static_cast(table.get())); } void Log::change_configuration() { LogConfig *prev = Log::config; LogConfig *new_config = nullptr; Debug(""log-config"", ""Changing configuration ...""); new_config = new LogConfig; ink_assert(new_config != nullptr); new_config->read_configuration_variables(); // grab the _APImutex so we can transfer the api objects to // the new config // ink_mutex_acquire(prev->log_object_manager._APImutex); Debug(""log-api-mutex"", ""Log::change_configuration acquired api mutex""); new_config->init(Log::config); // Make the new LogConfig active. ink_atomic_swap(&Log::config, new_config); // XXX There is a race condition with API objects. If TSTextLogObjectCreate() // is called before the Log::config swap, then it will be blocked on the lock // on the *old* LogConfig and register it's LogObject with that manager. If // this happens, then the new TextLogObject will be immediately lost. Traffic // Server would crash the next time the plugin referenced the freed object. ink_mutex_release(prev->log_object_manager._APImutex); Debug(""log-api-mutex"", ""Log::change_configuration released api mutex""); // Register the new config in the config processor; the old one will now be scheduled for a // future deletion. We don't need to do anything magical with refcounts, since the // configProcessor will keep a reference count, and drop it when the deletion is scheduled. configProcessor.set(log_configid, new_config); // If we replaced the logging configuration, flush any log // objects that weren't transferred to the new config ... prev->log_object_manager.flush_all_objects(); Debug(""log-config"", ""... new configuration in place""); } /*------------------------------------------------------------------------- PERIODIC EVENTS There are a number of things that need to get done on a periodic basis, such as checking the amount of space used, seeing if it's time to roll files, and flushing idle log buffers. Most of these tasks require having exclusive access to the back-end structures, which is controlled by the flush_thread. Therefore, we will simply instruct the flush thread to execute a periodic_tasks() function once per period. To ensure that the tasks are executed AT LEAST once each period, we'll register a call-back with the system and trigger the flush thread's condition variable. To ensure that the tasks are executed AT MOST once per period, the flush thread will keep track of executions per period. -------------------------------------------------------------------------*/ /*------------------------------------------------------------------------- PeriodicWakeup This continuation is invoked each second to wake-up the flush thread, just in case it's sleeping on the job. -------------------------------------------------------------------------*/ struct PeriodicWakeup; using PeriodicWakeupHandler = int (PeriodicWakeup::*)(int, void *); struct PeriodicWakeup : Continuation { int m_preproc_threads; int m_flush_threads; int wakeup(int /* event ATS_UNUSED */, Event * /* e ATS_UNUSED */) { for (int i = 0; i < m_preproc_threads; i++) { Log::preproc_notify[i].signal(); } for (int i = 0; i < m_flush_threads; i++) { Log::flush_notify[i].signal(); } return EVENT_CONT; } PeriodicWakeup(int preproc_threads, int flush_threads) : Continuation(new_ProxyMutex()), m_preproc_threads(preproc_threads), m_flush_threads(flush_threads) { SET_HANDLER((PeriodicWakeupHandler)&PeriodicWakeup::wakeup); } }; /*------------------------------------------------------------------------- Log::periodic_tasks This function contains all of the tasks that need to be done each PERIODIC_TASKS_INTERVAL seconds. -------------------------------------------------------------------------*/ void Log::periodic_tasks(long time_now) { Debug(""log-api-mutex"", ""entering Log::periodic_tasks""); if (logging_mode_changed || Log::config->reconfiguration_needed) { Debug(""log-config"", ""Performing reconfiguration, init status = %d"", init_status); if (logging_mode_changed) { int val = (int)REC_ConfigReadInteger(""proxy.config.log.logging_enabled""); if (val < LOG_MODE_NONE || val > LOG_MODE_FULL) { logging_mode = LOG_MODE_FULL; Warning(""proxy.config.log.logging_enabled has an invalid "" ""value setting it to %d"", logging_mode); } else { logging_mode = (LoggingMode)val; } logging_mode_changed = false; } // even if we are disabling logging, we call change configuration // so that log objects are flushed // change_configuration(); } else if (logging_mode > LOG_MODE_NONE || config->collation_mode == Log::COLLATION_HOST || config->has_api_objects()) { Debug(""log-periodic"", ""Performing periodic tasks""); Debug(""log-periodic"", ""Periodic task interval = %d"", periodic_tasks_interval); // Check if space is ok and update the space used // if (config->space_is_short() || time_now % config->space_used_frequency == 0) { Log::config->update_space_used(); } // See if there are any buffers that have expired // Log::config->log_object_manager.check_buffer_expiration(time_now); // Check if we received a request to roll, and roll if so, otherwise // give objects a chance to roll if they need to // if (Log::config->roll_log_files_now) { if (error_log) { error_log->roll_files(time_now); } if (global_scrap_object) { global_scrap_object->roll_files(time_now); } Log::config->log_object_manager.roll_files(time_now); Log::config->roll_log_files_now = false; } else { if (error_log) { error_log->roll_files(time_now); } if (global_scrap_object) { global_scrap_object->roll_files(time_now); } Log::config->log_object_manager.roll_files(time_now); } } } /*------------------------------------------------------------------------- MAIN INTERFACE -------------------------------------------------------------------------*/ struct LoggingPreprocContinuation : public Continuation { int m_idx; int mainEvent(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */) { Log::preproc_thread_main((void *)&m_idx); return 0; } LoggingPreprocContinuation(int idx) : Continuation(nullptr), m_idx(idx) { SET_HANDLER(&LoggingPreprocContinuation::mainEvent); } }; struct LoggingFlushContinuation : public Continuation { int m_idx; int mainEvent(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */) { Log::flush_thread_main((void *)&m_idx); return 0; } LoggingFlushContinuation(int idx) : Continuation(nullptr), m_idx(idx) { SET_HANDLER(&LoggingFlushContinuation::mainEvent); } }; struct LoggingCollateContinuation : public Continuation { int mainEvent(int /* event ATS_UNUSED */, void * /* data ATS_UNUSED */) { Log::collate_thread_main(nullptr); return 0; } LoggingCollateContinuation() : Continuation(nullptr) { SET_HANDLER(&LoggingCollateContinuation::mainEvent); } }; /*------------------------------------------------------------------------- Log::init_fields Define the available logging fields. This used to be part of the init() function, but now is separate so that standalone programs that do not require more services (e.g., that do not need to read records.config) can just call init_fields. Note that the LogFields are added to the list with the copy flag false so that the LogFieldList destructor will reclaim this memory. -------------------------------------------------------------------------*/ void Log::init_fields() { if (init_status & FIELDS_INITIALIZED) { return; } LogField *field; // // Initializes material to find a milestone name from their // name in a rapid manner. LogField::init_milestone_container(); // // Create a hash table that will be used to find the global field // objects from their symbol names in a rapid manner. // field_symbol_hash = ink_hash_table_create(InkHashTableKeyType_String); // client -> proxy fields field = new LogField(""client_host_ip"", ""chi"", LogField::IP, &LogAccess::marshal_client_host_ip, &LogAccess::unmarshal_ip_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""chi"", field); field = new LogField(""client_host_port"", ""chp"", LogField::sINT, &LogAccess::marshal_client_host_port, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""chp"", field); field = new LogField(""client_host_ip_hex"", ""chih"", LogField::IP, &LogAccess::marshal_client_host_ip, &LogAccess::unmarshal_ip_to_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""chih"", field); // interface ip field = new LogField(""host_interface_ip"", ""hii"", LogField::IP, &LogAccess::marshal_host_interface_ip, &LogAccess::unmarshal_ip_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""hii"", field); field = new LogField(""host_interface_ip_hex"", ""hiih"", LogField::IP, &LogAccess::marshal_host_interface_ip, &LogAccess::unmarshal_ip_to_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""hiih"", field); // interface ip end field = new LogField(""client_auth_user_name"", ""caun"", LogField::STRING, &LogAccess::marshal_client_auth_user_name, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""caun"", field); field = new LogField(""plugin_identity_id"", ""piid"", LogField::sINT, &LogAccess::marshal_plugin_identity_id, reinterpret_cast(&LogAccess::unmarshal_int_to_str)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""piid"", field); field = new LogField(""plugin_identity_tag"", ""pitag"", LogField::STRING, &LogAccess::marshal_plugin_identity_tag, reinterpret_cast(&LogAccess::unmarshal_str)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pitag"", field); field = new LogField(""client_req_timestamp_sec"", ""cqts"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_sec, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqts"", field); field = new LogField(""client_req_timestamp_hex_sec"", ""cqth"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_sec, &LogAccess::unmarshal_int_to_str_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqth"", field); field = new LogField(""client_req_timestamp_squid"", ""cqtq"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_ms, &LogAccess::unmarshal_ttmsf); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtq"", field); field = new LogField(""client_req_timestamp_netscape"", ""cqtn"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_sec, &LogAccess::unmarshal_int_to_netscape_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtn"", field); field = new LogField(""client_req_timestamp_date"", ""cqtd"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_sec, &LogAccess::unmarshal_int_to_date_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtd"", field); field = new LogField(""client_req_timestamp_time"", ""cqtt"", LogField::sINT, &LogAccess::marshal_client_req_timestamp_sec, &LogAccess::unmarshal_int_to_time_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtt"", field); field = new LogField(""client_req_text"", ""cqtx"", LogField::STRING, &LogAccess::marshal_client_req_text, (LogField::UnmarshalFunc)&LogAccess::unmarshal_http_text); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtx"", field); field = new LogField(""client_req_http_method"", ""cqhm"", LogField::STRING, &LogAccess::marshal_client_req_http_method, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqhm"", field); field = new LogField(""client_req_url"", ""cqu"", LogField::STRING, &LogAccess::marshal_client_req_url, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_url); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqu"", field); field = new LogField(""client_req_url_canonical"", ""cquc"", LogField::STRING, &LogAccess::marshal_client_req_url_canon, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_url_canon); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cquc"", field); field = new LogField(""client_req_unmapped_url_canonical"", ""cquuc"", LogField::STRING, &LogAccess::marshal_client_req_unmapped_url_canon, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_unmapped_url_canon); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cquuc"", field); field = new LogField(""client_req_unmapped_url_path"", ""cquup"", LogField::STRING, &LogAccess::marshal_client_req_unmapped_url_path, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_unmapped_url_path); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cquup"", field); field = new LogField(""client_req_unmapped_url_host"", ""cquuh"", LogField::STRING, &LogAccess::marshal_client_req_unmapped_url_host, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_unmapped_url_host); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cquuh"", field); field = new LogField(""client_req_url_scheme"", ""cqus"", LogField::STRING, &LogAccess::marshal_client_req_url_scheme, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqus"", field); field = new LogField(""client_req_url_path"", ""cqup"", LogField::STRING, &LogAccess::marshal_client_req_url_path, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str, &LogAccess::set_client_req_url_path); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqup"", field); field = new LogField(""client_req_http_version"", ""cqhv"", LogField::dINT, &LogAccess::marshal_client_req_http_version, &LogAccess::unmarshal_http_version); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqhv"", field); field = new LogField(""client_req_protocol_version"", ""cqpv"", LogField::dINT, &LogAccess::marshal_client_req_protocol_version, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqpv"", field); field = new LogField(""client_req_header_len"", ""cqhl"", LogField::sINT, &LogAccess::marshal_client_req_header_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqhl"", field); field = new LogField(""client_req_squid_len"", ""cqql"", LogField::sINT, &LogAccess::marshal_client_req_squid_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqql"", field); field = new LogField(""cache_lookup_url_canonical"", ""cluc"", LogField::STRING, &LogAccess::marshal_cache_lookup_url_canon, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cluc"", field); field = new LogField(""process_uuid"", ""puuid"", LogField::STRING, &LogAccess::marshal_process_uuid, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""puuid"", field); // TS-4765: This alias is deprecated to be removed in 8.0. field = new LogField(""client_req_body_len"", ""cqbl"", LogField::sINT, &LogAccess::marshal_client_req_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqbl"", field); field = new LogField(""client_req_content_len"", ""cqcl"", LogField::sINT, &LogAccess::marshal_client_req_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqcl"", field); field = new LogField(""client_req_tcp_reused"", ""cqtr"", LogField::dINT, &LogAccess::marshal_client_req_tcp_reused, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqtr"", field); field = new LogField(""client_req_is_ssl"", ""cqssl"", LogField::dINT, &LogAccess::marshal_client_req_is_ssl, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqssl"", field); field = new LogField(""client_req_ssl_reused"", ""cqssr"", LogField::dINT, &LogAccess::marshal_client_req_ssl_reused, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqssr"", field); field = new LogField(""client_sec_protocol"", ""cqssv"", LogField::STRING, &LogAccess::marshal_client_security_protocol, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqssv"", field); field = new LogField(""client_cipher_suite"", ""cqssc"", LogField::STRING, &LogAccess::marshal_client_security_cipher_suite, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cqssc"", field); Ptr finish_status_map = make_ptr(new LogFieldAliasTable); finish_status_map->init(N_LOG_FINISH_CODE_TYPES, LOG_FINISH_FIN, ""FIN"", LOG_FINISH_INTR, ""INTR"", LOG_FINISH_TIMEOUT, ""TIMEOUT""); field = new LogField(""client_finish_status_code"", ""cfsc"", LogField::sINT, &LogAccess::marshal_client_finish_status_code, &LogAccess::unmarshal_finish_status, make_alias_map(finish_status_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cfsc"", field); field = new LogField(""client_req_id"", ""crid"", LogField::sINT, &LogAccess::marshal_client_req_id, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""crid"", field); field = new LogField(""client_req_uuid"", ""cruuid"", LogField::STRING, &LogAccess::marshal_client_req_uuid, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cruuid"", field); field = new LogField(""client_rx_error_code"", ""crec"", LogField::STRING, &LogAccess::marshal_client_rx_error_code, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""crec"", field); field = new LogField(""client_tx_error_code"", ""ctec"", LogField::STRING, &LogAccess::marshal_client_tx_error_code, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ctec"", field); // proxy -> client fields field = new LogField(""proxy_resp_content_type"", ""psct"", LogField::STRING, &LogAccess::marshal_proxy_resp_content_type, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""psct"", field); field = new LogField(""proxy_resp_reason_phrase"", ""prrp"", LogField::STRING, &LogAccess::marshal_proxy_resp_reason_phrase, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""prrp"", field); field = new LogField(""proxy_resp_squid_len"", ""psql"", LogField::sINT, &LogAccess::marshal_proxy_resp_squid_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""psql"", field); field = new LogField(""proxy_resp_content_len"", ""pscl"", LogField::sINT, &LogAccess::marshal_proxy_resp_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pscl"", field); field = new LogField(""proxy_resp_content_len_hex"", ""psch"", LogField::sINT, &LogAccess::marshal_proxy_resp_content_len, &LogAccess::unmarshal_int_to_str_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""psch"", field); field = new LogField(""proxy_resp_status_code"", ""pssc"", LogField::sINT, &LogAccess::marshal_proxy_resp_status_code, &LogAccess::unmarshal_http_status); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pssc"", field); field = new LogField(""proxy_resp_header_len"", ""pshl"", LogField::sINT, &LogAccess::marshal_proxy_resp_header_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pshl"", field); field = new LogField(""proxy_finish_status_code"", ""pfsc"", LogField::sINT, &LogAccess::marshal_proxy_finish_status_code, &LogAccess::unmarshal_finish_status, make_alias_map(finish_status_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pfsc"", field); Ptr cache_code_map = make_ptr(new LogFieldAliasTable); cache_code_map->init( 51, SQUID_LOG_EMPTY, ""UNDEFINED"", SQUID_LOG_TCP_HIT, ""TCP_HIT"", SQUID_LOG_TCP_DISK_HIT, ""TCP_DISK_HIT"", SQUID_LOG_TCP_MEM_HIT, ""TCP_MEM_HIT"", SQUID_LOG_TCP_MISS, ""TCP_MISS"", SQUID_LOG_TCP_EXPIRED_MISS, ""TCP_EXPIRED_MISS"", SQUID_LOG_TCP_REFRESH_HIT, ""TCP_REFRESH_HIT"", SQUID_LOG_TCP_REF_FAIL_HIT, ""TCP_REFRESH_FAIL_HIT"", SQUID_LOG_TCP_REFRESH_MISS, ""TCP_REFRESH_MISS"", SQUID_LOG_TCP_CLIENT_REFRESH, ""TCP_CLIENT_REFRESH_MISS"", SQUID_LOG_TCP_IMS_HIT, ""TCP_IMS_HIT"", SQUID_LOG_TCP_IMS_MISS, ""TCP_IMS_MISS"", SQUID_LOG_TCP_SWAPFAIL, ""TCP_SWAPFAIL_MISS"", SQUID_LOG_TCP_DENIED, ""TCP_DENIED"", SQUID_LOG_TCP_WEBFETCH_MISS, ""TCP_WEBFETCH_MISS"", SQUID_LOG_TCP_FUTURE_2, ""TCP_FUTURE_2"", SQUID_LOG_TCP_HIT_REDIRECT, ""TCP_HIT_REDIRECT"", SQUID_LOG_TCP_MISS_REDIRECT, ""TCP_MISS_REDIRECT"", SQUID_LOG_TCP_HIT_X_REDIRECT, ""TCP_HIT_X_REDIRECT"", SQUID_LOG_TCP_MISS_X_REDIRECT, ""TCP_MISS_X_REDIRECT"", SQUID_LOG_UDP_HIT, ""UDP_HIT"", SQUID_LOG_UDP_WEAK_HIT, ""UDP_WEAK_HIT"", SQUID_LOG_UDP_HIT_OBJ, ""UDP_HIT_OBJ"", SQUID_LOG_UDP_MISS, ""UDP_MISS"", SQUID_LOG_UDP_DENIED, ""UDP_DENIED"", SQUID_LOG_UDP_INVALID, ""UDP_INVALID"", SQUID_LOG_UDP_RELOADING, ""UDP_RELOADING"", SQUID_LOG_UDP_FUTURE_1, ""UDP_FUTURE_1"", SQUID_LOG_UDP_FUTURE_2, ""UDP_FUTURE_2"", SQUID_LOG_ERR_READ_TIMEOUT, ""ERR_READ_TIMEOUT"", SQUID_LOG_ERR_LIFETIME_EXP, ""ERR_LIFETIME_EXP"", SQUID_LOG_ERR_POST_ENTITY_TOO_LARGE, ""ERR_POST_ENTITY_TOO_LARGE"", SQUID_LOG_ERR_NO_CLIENTS_BIG_OBJ, ""ERR_NO_CLIENTS_BIG_OBJ"", SQUID_LOG_ERR_READ_ERROR, ""ERR_READ_ERROR"", SQUID_LOG_ERR_CLIENT_ABORT, ""ERR_CLIENT_ABORT"", SQUID_LOG_ERR_CLIENT_READ_ERROR, ""ERR_CLIENT_READ_ERROR"", SQUID_LOG_ERR_CONNECT_FAIL, ""ERR_CONNECT_FAIL"", SQUID_LOG_ERR_INVALID_REQ, ""ERR_INVALID_REQ"", SQUID_LOG_ERR_UNSUP_REQ, ""ERR_UNSUP_REQ"", SQUID_LOG_ERR_INVALID_URL, ""ERR_INVALID_URL"", SQUID_LOG_ERR_NO_FDS, ""ERR_NO_FDS"", SQUID_LOG_ERR_DNS_FAIL, ""ERR_DNS_FAIL"", SQUID_LOG_ERR_NOT_IMPLEMENTED, ""ERR_NOT_IMPLEMENTED"", SQUID_LOG_ERR_CANNOT_FETCH, ""ERR_CANNOT_FETCH"", SQUID_LOG_ERR_NO_RELAY, ""ERR_NO_RELAY"", SQUID_LOG_ERR_DISK_IO, ""ERR_DISK_IO"", SQUID_LOG_ERR_ZERO_SIZE_OBJECT, ""ERR_ZERO_SIZE_OBJECT"", SQUID_LOG_ERR_PROXY_DENIED, ""ERR_PROXY_DENIED"", SQUID_LOG_ERR_WEBFETCH_DETECTED, ""ERR_WEBFETCH_DETECTED"", SQUID_LOG_ERR_FUTURE_1, ""ERR_FUTURE_1"", SQUID_LOG_ERR_UNKNOWN, ""ERR_UNKNOWN""); Ptr cache_subcode_map = make_ptr(new LogFieldAliasTable); cache_subcode_map->init(2, SQUID_SUBCODE_EMPTY, ""NONE"", SQUID_SUBCODE_NUM_REDIRECTIONS_EXCEEDED, ""NUM_REDIRECTIONS_EXCEEDED""); Ptr cache_hit_miss_map = make_ptr(new LogFieldAliasTable); cache_hit_miss_map->init(21, SQUID_HIT_RESERVED, ""HIT"", SQUID_HIT_LEVEL_1, ""HIT_RAM"", // Also SQUID_HIT_RAM SQUID_HIT_LEVEL_2, ""HIT_SSD"", // Also SQUID_HIT_SSD SQUID_HIT_LEVEL_3, ""HIT_DISK"", // Also SQUID_HIT_DISK SQUID_HIT_LEVEL_4, ""HIT_CLUSTER"", // Also SQUID_HIT_CLUSTER SQUID_HIT_LEVEL_5, ""HIT_NET"", // Also SQUID_HIT_NET SQUID_HIT_LEVEL_6, ""HIT_LEVEL_6"", SQUID_HIT_LEVEL_7, ""HIT_LEVEL_7"", SQUID_HIT_LEVEL_8, ""HIT_LEVEL_8"", SQUID_HIT_LEVEl_9, ""HIT_LEVEL_9"", SQUID_MISS_NONE, ""MISS"", SQUID_MISS_HTTP_NON_CACHE, ""MISS_HTTP_NON_CACHE"", SQUID_MISS_HTTP_NO_DLE, ""MISS_HTTP_NO_DLE"", SQUID_MISS_HTTP_NO_LE, ""MISS_HTTP_NO_LE"", SQUID_MISS_HTTP_CONTENT, ""MISS_HTTP_CONTENT"", SQUID_MISS_PRAGMA_NOCACHE, ""MISS_PRAGMA_NOCACHE"", SQUID_MISS_PASS, ""MISS_PASS"", SQUID_MISS_PRE_EXPIRED, ""MISS_PRE_EXPIRED"", SQUID_MISS_ERROR, ""MISS_ERROR"", SQUID_MISS_CACHE_BYPASS, ""MISS_CACHE_BYPASS"", SQUID_HIT_MISS_INVALID_ASSIGNED_CODE, ""INVALID_CODE""); field = new LogField(""cache_result_code"", ""crc"", LogField::sINT, &LogAccess::marshal_cache_result_code, &LogAccess::unmarshal_cache_code, make_alias_map(cache_code_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""crc"", field); // Reuse the unmarshalling code from crc field = new LogField(""cache_result_subcode"", ""crsc"", LogField::sINT, &LogAccess::marshal_cache_result_subcode, &LogAccess::unmarshal_cache_code, make_alias_map(cache_subcode_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""crsc"", field); field = new LogField(""cache_hit_miss"", ""chm"", LogField::sINT, &LogAccess::marshal_cache_hit_miss, &LogAccess::unmarshal_cache_hit_miss, make_alias_map(cache_hit_miss_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""chm"", field); // proxy -> server fields field = new LogField(""proxy_req_header_len"", ""pqhl"", LogField::sINT, &LogAccess::marshal_proxy_req_header_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqhl"", field); field = new LogField(""proxy_req_squid_len"", ""pqql"", LogField::sINT, &LogAccess::marshal_proxy_req_squid_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqql"", field); // TS-4765: This alias is deprecated to be removed in 8.0. field = new LogField(""proxy_req_body_len"", ""pqbl"", LogField::sINT, &LogAccess::marshal_proxy_req_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqbl"", field); field = new LogField(""proxy_req_content_len"", ""pqcl"", LogField::sINT, &LogAccess::marshal_proxy_req_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqcl"", field); field = new LogField(""proxy_req_server_name"", ""pqsn"", LogField::STRING, &LogAccess::marshal_proxy_req_server_name, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqsn"", field); field = new LogField(""proxy_req_server_ip"", ""pqsi"", LogField::IP, &LogAccess::marshal_proxy_req_server_ip, &LogAccess::unmarshal_ip_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqsi"", field); field = new LogField(""proxy_req_server_port"", ""pqsp"", LogField::sINT, &LogAccess::marshal_proxy_req_server_port, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqsp"", field); Ptr hierarchy_map = make_ptr(new LogFieldAliasTable); hierarchy_map->init( 36, SQUID_HIER_EMPTY, ""EMPTY"", SQUID_HIER_NONE, ""NONE"", SQUID_HIER_DIRECT, ""DIRECT"", SQUID_HIER_SIBLING_HIT, ""SIBLING_HIT"", SQUID_HIER_PARENT_HIT, ""PARENT_HIT"", SQUID_HIER_DEFAULT_PARENT, ""DEFAULT_PARENT"", SQUID_HIER_SINGLE_PARENT, ""SINGLE_PARENT"", SQUID_HIER_FIRST_UP_PARENT, ""FIRST_UP_PARENT"", SQUID_HIER_NO_PARENT_DIRECT, ""NO_PARENT_DIRECT"", SQUID_HIER_FIRST_PARENT_MISS, ""FIRST_PARENT_MISS"", SQUID_HIER_LOCAL_IP_DIRECT, ""LOCAL_IP_DIRECT"", SQUID_HIER_FIREWALL_IP_DIRECT, ""FIREWALL_IP_DIRECT"", SQUID_HIER_NO_DIRECT_FAIL, ""NO_DIRECT_FAIL"", SQUID_HIER_SOURCE_FASTEST, ""SOURCE_FASTEST"", SQUID_HIER_SIBLING_UDP_HIT_OBJ, ""SIBLING_UDP_HIT_OBJ"", SQUID_HIER_PARENT_UDP_HIT_OBJ, ""PARENT_UDP_HIT_OBJ"", SQUID_HIER_PASSTHROUGH_PARENT, ""PASSTHROUGH_PARENT"", SQUID_HIER_SSL_PARENT_MISS, ""SSL_PARENT_MISS"", SQUID_HIER_INVALID_CODE, ""INVALID_CODE"", SQUID_HIER_TIMEOUT_DIRECT, ""TIMEOUT_DIRECT"", SQUID_HIER_TIMEOUT_SIBLING_HIT, ""TIMEOUT_SIBLING_HIT"", SQUID_HIER_TIMEOUT_PARENT_HIT, ""TIMEOUT_PARENT_HIT"", SQUID_HIER_TIMEOUT_DEFAULT_PARENT, ""TIMEOUT_DEFAULT_PARENT"", SQUID_HIER_TIMEOUT_SINGLE_PARENT, ""TIMEOUT_SINGLE_PARENT"", SQUID_HIER_TIMEOUT_FIRST_UP_PARENT, ""TIMEOUT_FIRST_UP_PARENT"", SQUID_HIER_TIMEOUT_NO_PARENT_DIRECT, ""TIMEOUT_NO_PARENT_DIRECT"", SQUID_HIER_TIMEOUT_FIRST_PARENT_MISS, ""TIMEOUT_FIRST_PARENT_MISS"", SQUID_HIER_TIMEOUT_LOCAL_IP_DIRECT, ""TIMEOUT_LOCAL_IP_DIRECT"", SQUID_HIER_TIMEOUT_FIREWALL_IP_DIRECT, ""TIMEOUT_FIREWALL_IP_DIRECT"", SQUID_HIER_TIMEOUT_NO_DIRECT_FAIL, ""TIMEOUT_NO_DIRECT_FAIL"", SQUID_HIER_TIMEOUT_SOURCE_FASTEST, ""TIMEOUT_SOURCE_FASTEST"", SQUID_HIER_TIMEOUT_SIBLING_UDP_HIT_OBJ, ""TIMEOUT_SIBLING_UDP_HIT_OBJ"", SQUID_HIER_TIMEOUT_PARENT_UDP_HIT_OBJ, ""TIMEOUT_PARENT_UDP_HIT_OBJ"", SQUID_HIER_TIMEOUT_PASSTHROUGH_PARENT, ""TIMEOUT_PASSTHROUGH_PARENT"", SQUID_HIER_TIMEOUT_TIMEOUT_SSL_PARENT_MISS, ""TIMEOUT_TIMEOUT_SSL_PARENT_MISS"", SQUID_HIER_INVALID_ASSIGNED_CODE, ""INVALID_ASSIGNED_CODE""); field = new LogField(""proxy_hierarchy_route"", ""phr"", LogField::sINT, &LogAccess::marshal_proxy_hierarchy_route, &LogAccess::unmarshal_hierarchy, make_alias_map(hierarchy_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""phr"", field); field = new LogField(""proxy_host_name"", ""phn"", LogField::STRING, &LogAccess::marshal_proxy_host_name, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""phn"", field); field = new LogField(""proxy_host_ip"", ""phi"", LogField::IP, &LogAccess::marshal_proxy_host_ip, &LogAccess::unmarshal_ip_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""phi"", field); field = new LogField(""proxy_host_port"", ""php"", LogField::sINT, &LogAccess::marshal_proxy_host_port, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""php"", field); field = new LogField(""proxy_req_is_ssl"", ""pqssl"", LogField::sINT, &LogAccess::marshal_proxy_req_is_ssl, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""pqssl"", field); // server -> proxy fields field = new LogField(""server_host_ip"", ""shi"", LogField::IP, &LogAccess::marshal_server_host_ip, &LogAccess::unmarshal_ip_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""shi"", field); field = new LogField(""server_host_name"", ""shn"", LogField::STRING, &LogAccess::marshal_server_host_name, (LogField::UnmarshalFunc)&LogAccess::unmarshal_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""shn"", field); field = new LogField(""server_resp_status_code"", ""sssc"", LogField::sINT, &LogAccess::marshal_server_resp_status_code, &LogAccess::unmarshal_http_status); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sssc"", field); field = new LogField(""server_resp_content_len"", ""sscl"", LogField::sINT, &LogAccess::marshal_server_resp_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sscl"", field); field = new LogField(""server_resp_header_len"", ""sshl"", LogField::sINT, &LogAccess::marshal_server_resp_header_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sshl"", field); field = new LogField(""server_resp_squid_len"", ""ssql"", LogField::sINT, &LogAccess::marshal_server_resp_squid_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ssql"", field); field = new LogField(""server_resp_http_version"", ""sshv"", LogField::dINT, &LogAccess::marshal_server_resp_http_version, &LogAccess::unmarshal_http_version); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sshv"", field); field = new LogField(""server_resp_time"", ""stms"", LogField::sINT, &LogAccess::marshal_server_resp_time_ms, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""stms"", field); field = new LogField(""server_resp_time_hex"", ""stmsh"", LogField::sINT, &LogAccess::marshal_server_resp_time_ms, &LogAccess::unmarshal_int_to_str_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""stmsh"", field); field = new LogField(""server_resp_time_fractional"", ""stmsf"", LogField::sINT, &LogAccess::marshal_server_resp_time_ms, &LogAccess::unmarshal_ttmsf); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""stmsf"", field); field = new LogField(""server_resp_time_sec"", ""sts"", LogField::sINT, &LogAccess::marshal_server_resp_time_s, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sts"", field); field = new LogField(""server_transact_count"", ""sstc"", LogField::sINT, &LogAccess::marshal_server_transact_count, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sstc"", field); field = new LogField(""server_connect_attempts"", ""sca"", LogField::sINT, &LogAccess::marshal_server_connect_attempts, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""sca"", field); field = new LogField(""cached_resp_status_code"", ""csssc"", LogField::sINT, &LogAccess::marshal_cache_resp_status_code, &LogAccess::unmarshal_http_status); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""csssc"", field); field = new LogField(""cached_resp_content_len"", ""csscl"", LogField::sINT, &LogAccess::marshal_cache_resp_content_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""csscl"", field); field = new LogField(""cached_resp_header_len"", ""csshl"", LogField::sINT, &LogAccess::marshal_cache_resp_header_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""csshl"", field); field = new LogField(""cached_resp_squid_len"", ""cssql"", LogField::sINT, &LogAccess::marshal_cache_resp_squid_len, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cssql"", field); field = new LogField(""cached_resp_http_version"", ""csshv"", LogField::dINT, &LogAccess::marshal_cache_resp_http_version, &LogAccess::unmarshal_http_version); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""csshv"", field); field = new LogField(""client_retry_after_time"", ""crat"", LogField::sINT, &LogAccess::marshal_client_retry_after_time, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""crat"", field); // cache write fields Ptr cache_write_code_map = make_ptr(new LogFieldAliasTable); cache_write_code_map->init(N_LOG_CACHE_WRITE_TYPES, LOG_CACHE_WRITE_NONE, ""-"", LOG_CACHE_WRITE_LOCK_MISSED, ""WL_MISS"", LOG_CACHE_WRITE_LOCK_ABORTED, ""INTR"", LOG_CACHE_WRITE_ERROR, ""ERR"", LOG_CACHE_WRITE_COMPLETE, ""FIN""); field = new LogField(""cache_write_result"", ""cwr"", LogField::sINT, &LogAccess::marshal_cache_write_code, &LogAccess::unmarshal_cache_write_code, make_alias_map(cache_write_code_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cwr"", field); field = new LogField(""cache_write_transform_result"", ""cwtr"", LogField::sINT, &LogAccess::marshal_cache_write_transform_code, &LogAccess::unmarshal_cache_write_code, make_alias_map(cache_write_code_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""cwtr"", field); // other fields field = new LogField(""transfer_time_ms"", ""ttms"", LogField::sINT, &LogAccess::marshal_transfer_time_ms, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ttms"", field); field = new LogField(""transfer_time_ms_hex"", ""ttmh"", LogField::sINT, &LogAccess::marshal_transfer_time_ms, &LogAccess::unmarshal_int_to_str_hex); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ttmh"", field); field = new LogField(""transfer_time_ms_fractional"", ""ttmsf"", LogField::sINT, &LogAccess::marshal_transfer_time_ms, &LogAccess::unmarshal_ttmsf); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ttmsf"", field); field = new LogField(""transfer_time_sec"", ""tts"", LogField::sINT, &LogAccess::marshal_transfer_time_s, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""tts"", field); field = new LogField(""file_size"", ""fsiz"", LogField::sINT, &LogAccess::marshal_file_size, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""fsiz"", field); field = new LogField(""client_connection_id"", ""ccid"", LogField::sINT, &LogAccess::marshal_client_http_connection_id, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ccid"", field); field = new LogField(""client_transaction_id"", ""ctid"", LogField::sINT, &LogAccess::marshal_client_http_transaction_id, &LogAccess::unmarshal_int_to_str); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""ctid"", field); Ptr entry_type_map = make_ptr(new LogFieldAliasTable); entry_type_map->init(N_LOG_ENTRY_TYPES, LOG_ENTRY_HTTP, ""LOG_ENTRY_HTTP""); field = new LogField(""log_entry_type"", ""etype"", LogField::sINT, &LogAccess::marshal_entry_type, &LogAccess::unmarshal_entry_type, make_alias_map(entry_type_map)); global_field_list.add(field, false); ink_hash_table_insert(field_symbol_hash, ""etype"", field); init_status |= FIELDS_INITIALIZED; } /*------------------------------------------------------------------------- Initialization functions -------------------------------------------------------------------------*/ int Log::handle_logging_mode_change(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData /* data ATS_UNUSED */, void * /* cookie ATS_UNUSED */) { Debug(""log-config"", ""Enabled status changed""); logging_mode_changed = true; return 0; } int Log::handle_periodic_tasks_int_change(const char * /* name ATS_UNUSED */, RecDataT /* data_type ATS_UNUSED */, RecData data, void * /* cookie ATS_UNSED */) { Debug(""log-periodic"", ""periodic task interval changed""); if (data.rec_int <= 0) { periodic_tasks_interval = PERIODIC_TASKS_INTERVAL_FALLBACK; Error(""new periodic tasks interval = %d is invalid, falling back to default = %d"", (int)data.rec_int, PERIODIC_TASKS_INTERVAL_FALLBACK); } else { periodic_tasks_interval = (uint32_t)data.rec_int; Debug(""log-periodic"", ""periodic task interval changed to %u"", periodic_tasks_interval); } return REC_ERR_OKAY; } void Log::init(int flags) { collation_preproc_threads = 1; collation_accept_file_descriptor = NO_FD; // store the configuration flags // config_flags = flags; // create the configuration object config = new LogConfig(); ink_assert(config != nullptr); log_configid = configProcessor.set(log_configid, config); // set the logging_mode and read config variables if needed // if (config_flags & LOGCAT) { logging_mode = LOG_MODE_NONE; } else { log_rsb = RecAllocateRawStatBlock((int)log_stat_count); LogConfig::register_stat_callbacks(); config->read_configuration_variables(); collation_port = config->collation_port; collation_preproc_threads = config->collation_preproc_threads; if (config_flags & STANDALONE_COLLATOR) { logging_mode = LOG_MODE_TRANSACTIONS; } else { int val = (int)REC_ConfigReadInteger(""proxy.config.log.logging_enabled""); if (val < LOG_MODE_NONE || val > LOG_MODE_FULL) { logging_mode = LOG_MODE_FULL; Warning(""proxy.config.log.logging_enabled has an invalid "" ""value, setting it to %d"", logging_mode); } else { logging_mode = (LoggingMode)val; } // periodic task interval are set on a per instance basis MgmtInt pti = REC_ConfigReadInteger(""proxy.config.log.periodic_tasks_interval""); if (pti <= 0) { Error(""proxy.config.log.periodic_tasks_interval = %"" PRId64 "" is invalid"", pti); Note(""falling back to default periodic tasks interval = %d"", PERIODIC_TASKS_INTERVAL_FALLBACK); periodic_tasks_interval = PERIODIC_TASKS_INTERVAL_FALLBACK; } else { periodic_tasks_interval = static_cast(pti); } REC_RegisterConfigUpdateFunc(""proxy.config.log.periodic_tasks_interval"", &Log::handle_periodic_tasks_int_change, nullptr); } } // if remote management is enabled, do all necessary initialization to // be able to handle a logging mode change // if (!(config_flags & NO_REMOTE_MANAGEMENT)) { REC_RegisterConfigUpdateFunc(""proxy.config.log.logging_enabled"", &Log::handle_logging_mode_change, nullptr); REC_RegisterConfigUpdateFunc(""proxy.local.log.collation_mode"", &Log::handle_logging_mode_change, nullptr); // Clear any stat values that need to be reset on startup // RecSetRawStatSum(log_rsb, log_stat_log_files_open_stat, 0); RecSetRawStatCount(log_rsb, log_stat_log_files_open_stat, 0); } init_fields(); if (!(config_flags & LOGCAT)) { Debug(""log-config"", ""Log::init(): logging_mode = %d init status = %d"", logging_mode, init_status); if (config_flags & STANDALONE_COLLATOR) { config->collation_mode = Log::COLLATION_HOST; } config->init(); init_when_enabled(); } } void Log::init_when_enabled() { // make sure the log config has been initialized ink_release_assert(config->initialized == true); if (!(init_status & FULLY_INITIALIZED)) { if (!(config_flags & STANDALONE_COLLATOR)) { // register callbacks // if (!(config_flags & NO_REMOTE_MANAGEMENT)) { LogConfig::register_config_callbacks(); } LogConfig::register_mgmt_callbacks(); } // setup global scrap object // global_scrap_format = MakeTextLogFormat(); global_scrap_object = new LogObject(global_scrap_format, Log::config->logfile_dir, ""scrapfile.log"", LOG_FILE_BINARY, nullptr, Log::config->rolling_enabled, Log::config->collation_preproc_threads, Log::config->rolling_interval_sec, Log::config->rolling_offset_hr, Log::config->rolling_size_mb); // create the flush thread and the collation thread create_threads(); eventProcessor.schedule_every(new PeriodicWakeup(collation_preproc_threads, 1), HRTIME_SECOND, ET_CALL); init_status |= FULLY_INITIALIZED; } Note(""logging initialized[%d], logging_mode = %d"", init_status, logging_mode); if (is_debug_tag_set(""log-config"")) { config->display(); } } void Log::create_threads() { char desc[64]; preproc_notify = new EventNotify[collation_preproc_threads]; size_t stacksize; REC_ReadConfigInteger(stacksize, ""proxy.config.thread.default.stacksize""); // start the preproc threads // // no need for the conditional var since it will be relying on // on the event system. for (int i = 0; i < collation_preproc_threads; i++) { Continuation *preproc_cont = new LoggingPreprocContinuation(i); sprintf(desc, ""[LOG_PREPROC %d]"", i); eventProcessor.spawn_thread(preproc_cont, desc, stacksize); } // Now, only one flush thread is supported. // TODO: Enable multiple flush threads, such as // one flush thread per file. // flush_notify = new EventNotify; flush_data_list = new InkAtomicList; sprintf(desc, ""Logging flush buffer list""); ink_atomiclist_init(flush_data_list, desc, 0); Continuation *flush_cont = new LoggingFlushContinuation(0); sprintf(desc, ""[LOG_FLUSH]""); eventProcessor.spawn_thread(flush_cont, desc, stacksize); } /*------------------------------------------------------------------------- Log::access Make an entry in the access log for the data supplied by the given LogAccess object. -------------------------------------------------------------------------*/ int Log::access(LogAccess *lad) { // See if transaction logging is disabled // if (!transaction_logging_enabled()) { return Log::SKIP; } ink_assert(init_status & FULLY_INITIALIZED); ink_assert(lad != nullptr); int ret; static long sample = 1; long this_sample; ProxyMutex *mutex = this_ethread()->mutex.get(); // See if we're sampling and it is not time for another sample // if (Log::config->sampling_frequency > 1) { this_sample = sample++; if (this_sample && this_sample % Log::config->sampling_frequency) { Debug(""log"", ""sampling, skipping this entry ...""); RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_access_skip_stat, 1); ret = Log::SKIP; goto done; } else { Debug(""log"", ""sampling, LOGGING this entry ...""); sample = 1; } } if (Log::config->log_object_manager.get_num_objects() == 0) { Debug(""log"", ""no log objects, skipping this entry ...""); RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_access_skip_stat, 1); ret = Log::SKIP; goto done; } // initialize this LogAccess object and proccess // lad->init(); ret = config->log_object_manager.log(lad); done: return ret; } /*------------------------------------------------------------------------- Log::error Make an entry into the current error log. For convenience, it is given in both variable argument (format, ...) and stdarg (format, va_list) forms. -------------------------------------------------------------------------*/ int Log::error(const char *format, ...) { va_list ap; int ret; va_start(ap, format); ret = Log::va_error(format, ap); va_end(ap); return ret; } int Log::va_error(const char *format, va_list ap) { int ret_val = Log::SKIP; ProxyMutex *mutex = this_ethread()->mutex.get(); if (error_log) { ink_assert(format != nullptr); ret_val = error_log->va_log(nullptr, format, ap); switch (ret_val) { case Log::LOG_OK: RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_ok_stat, 1); break; case Log::SKIP: RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_skip_stat, 1); break; case Log::AGGR: RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_aggr_stat, 1); break; case Log::FULL: RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_full_stat, 1); break; case Log::FAIL: RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_fail_stat, 1); break; default: ink_release_assert(!""Unexpected result""); } return ret_val; } RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_event_log_error_skip_stat, 1); return ret_val; } /*------------------------------------------------------------------------- Log::trace These functions are used for wiretracing of incoming SSL connections. They are an extension of the existing Log::error functionality but with special formatting and handling of the non null terminated buffer. -------------------------------------------------------------------------*/ void Log::trace_in(const sockaddr *peer_addr, uint16_t peer_port, const char *format_string, ...) { va_list ap; va_start(ap, format_string); trace_va(true, peer_addr, peer_port, format_string, ap); va_end(ap); } void Log::trace_out(const sockaddr *peer_addr, uint16_t peer_port, const char *format_string, ...) { va_list ap; va_start(ap, format_string); trace_va(false, peer_addr, peer_port, format_string, ap); va_end(ap); } void Log::trace_va(bool in, const sockaddr *peer_addr, uint16_t peer_port, const char *format_string, va_list ap) { if (!peer_addr || !format_string) { return; } char ip[INET6_ADDRSTRLEN]; ats_ip_ntop(peer_addr, ip, sizeof(ip)); struct timeval tp = ink_gettimeofday(); Log::error(""[%9d.%03d] Trace {0x%"" PRIx64 ""} %s %s:%d: "", (int)tp.tv_sec, (int)(tp.tv_usec / 1000), (uint64_t)ink_thread_self(), in ? ""RECV"" : ""SEND"", ip, peer_port); Log::va_error(format_string, ap); Log::error(""[End Trace]\\n""); } /*------------------------------------------------------------------------- Log::preproc_thread_main This function defines the functionality of the logging flush preprocess thread, whose purpose is to consume full LogBuffer objects, do some prepare work (such as convert to ascii), and then forward to flush thread. -------------------------------------------------------------------------*/ void * Log::preproc_thread_main(void *args) { int idx = *(int *)args; Debug(""log-preproc"", ""log preproc thread is alive ...""); Log::preproc_notify[idx].lock(); while (true) { if (unlikely(shutdown_event_system == true)) { return nullptr; } size_t buffers_preproced = 0; LogConfig *current = (LogConfig *)configProcessor.get(log_configid); if (likely(current)) { buffers_preproced = current->log_object_manager.preproc_buffers(idx); // config->increment_space_used(bytes_to_disk); // TODO: the bytes_to_disk should be set to Log Debug(""log-preproc"", ""%zu buffers preprocessed from LogConfig %p (refcount=%d) this round"", buffers_preproced, current, current->refcount()); configProcessor.release(log_configid, current); } // wait for more work; a spurious wake-up is ok since we'll just // check the queue and find there is nothing to do, then wait // again. // Log::preproc_notify[idx].wait(); } /* NOTREACHED */ Log::preproc_notify[idx].unlock(); return nullptr; } void * Log::flush_thread_main(void * /* args ATS_UNUSED */) { LogBuffer *logbuffer; LogFlushData *fdata; ink_hrtime now, last_time = 0; int len, total_bytes; SLL link, invert_link; ProxyMutex *mutex = this_thread()->mutex.get(); Log::flush_notify->lock(); while (true) { if (unlikely(shutdown_event_system == true)) { return nullptr; } fdata = (LogFlushData *)ink_atomiclist_popall(flush_data_list); // invert the list // link.head = fdata; while ((fdata = link.pop())) { invert_link.push(fdata); } // process each flush data // while ((fdata = invert_link.pop())) { char *buf = nullptr; int bytes_written = 0; LogFile *logfile = fdata->m_logfile.get(); if (logfile->m_file_format == LOG_FILE_BINARY) { logbuffer = (LogBuffer *)fdata->m_data; LogBufferHeader *buffer_header = logbuffer->header(); buf = (char *)buffer_header; total_bytes = buffer_header->byte_count; } else if (logfile->m_file_format == LOG_FILE_ASCII || logfile->m_file_format == LOG_FILE_PIPE) { buf = (char *)fdata->m_data; total_bytes = fdata->m_len; } else { ink_release_assert(!""Unknown file format type!""); } // make sure we're open & ready to write logfile->check_fd(); if (!logfile->is_open()) { Warning(""File:%s was closed, have dropped (%d) bytes."", logfile->get_name(), total_bytes); RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_bytes_lost_before_written_to_disk_stat, total_bytes); delete fdata; continue; } int logfilefd = logfile->get_fd(); // This should always be true because we just checked it. ink_assert(logfilefd >= 0); // write *all* data to target file as much as possible // while (total_bytes - bytes_written) { if (Log::config->logging_space_exhausted) { Debug(""log"", ""logging space exhausted, failed to write file:%s, have dropped (%d) bytes."", logfile->get_name(), (total_bytes - bytes_written)); RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_bytes_lost_before_written_to_disk_stat, total_bytes - bytes_written); break; } len = ::write(logfilefd, &buf[bytes_written], total_bytes - bytes_written); if (len < 0) { Error(""Failed to write log to %s: [tried %d, wrote %d, %s]"", logfile->get_name(), total_bytes - bytes_written, bytes_written, strerror(errno)); RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_bytes_lost_before_written_to_disk_stat, total_bytes - bytes_written); break; } Debug(""log"", ""Successfully wrote some stuff to %s"", logfile->get_name()); bytes_written += len; } RecIncrRawStat(log_rsb, mutex->thread_holding, log_stat_bytes_written_to_disk_stat, bytes_written); if (logfile->m_log) { ink_atomic_increment(&logfile->m_log->m_bytes_written, bytes_written); } delete fdata; } // Time to work on periodic events?? // now = Thread::get_hrtime() / HRTIME_SECOND; if (now >= last_time + periodic_tasks_interval) { Debug(""log-preproc"", ""periodic tasks for %"" PRId64, (int64_t)now); periodic_tasks(now); last_time = Thread::get_hrtime() / HRTIME_SECOND; } // wait for more work; a spurious wake-up is ok since we'll just // check the queue and find there is nothing to do, then wait // again. // Log::flush_notify->wait(); } /* NOTREACHED */ Log::flush_notify->unlock(); return nullptr; } /*------------------------------------------------------------------------- Log::collate_thread_main This function defines the functionality of the log collation thread, whose purpose is to collate log buffers from other nodes. -------------------------------------------------------------------------*/ void * Log::collate_thread_main(void * /* args ATS_UNUSED */) { LogSock *sock; LogBufferHeader *header; LogFormat *format; LogObject *obj; int bytes_read; int sock_id; int new_client; Debug(""log-thread"", ""Log collation thread is alive ...""); Log::collate_notify.lock(); while (true) { ink_assert(Log::config != nullptr); // wait on the collation condition variable until we're sure that // we're a collation host. The while loop guards against spurious // wake-ups. // while (!Log::config->am_collation_host()) { Log::collate_notify.wait(); } // Ok, at this point we know we're a log collation host, so get to // work. We still need to keep checking whether we're a collation // host to account for a reconfiguration. // Debug(""log-sock"", ""collation thread starting, creating LogSock""); sock = new LogSock(LogSock::LS_CONST_MAX_CONNS); ink_assert(sock != nullptr); if (sock->listen(Log::config->collation_port) != 0) { LogUtils::manager_alarm(LogUtils::LOG_ALARM_ERROR, ""Collation server error; could not listen on port %d"", Log::config->collation_port); Warning(""Collation server error; could not listen on port %d"", Log::config->collation_port); delete sock; // // go to sleep ... // Log::collate_notify.wait(); continue; } while (true) { if (!Log::config->am_collation_host()) { break; } if (sock->pending_connect(0)) { Debug(""log-sock"", ""pending connection ...""); if ((new_client = sock->accept()) < 0) { Debug(""log-sock"", ""error accepting new collation client""); } else { Debug(""log-sock"", ""connection %d accepted"", new_client); if (!sock->authorized_client(new_client, Log::config->collation_secret)) { Warning(""Unauthorized client connecting to "" ""log collation port; connection refused.""); sock->close(new_client); } } } sock->check_connections(); if (!sock->pending_message_any(&sock_id, 0)) { continue; } Debug(""log-sock"", ""pending message ...""); header = (LogBufferHeader *)sock->read_alloc(sock_id, &bytes_read); if (!header) { Debug(""log-sock"", ""Error reading LogBuffer from collation client""); continue; } if (header->version != LOG_SEGMENT_VERSION) { Note(""Invalid LogBuffer received; invalid version - buffer = %u, current = %u"", header->version, LOG_SEGMENT_VERSION); delete[] header; continue; } Debug(""log-sock"", ""message accepted, size = %d"", bytes_read); obj = match_logobject(header); if (!obj) { Note(""LogObject not found with fieldlist id; "" ""writing LogBuffer to scrap file""); obj = global_scrap_object; } format = obj->m_format; Debug(""log-sock"", ""Using format '%s'"", format->name()); delete[] header; } Debug(""log"", ""no longer collation host, deleting LogSock""); delete sock; } /* NOTREACHED */ Log::collate_notify.unlock(); return nullptr; } /*------------------------------------------------------------------------- Log::match_logobject This routine matches the given buffer with the local list of LogObjects. If a match cannot be found, then we'll try to construct a local LogObject using the information provided in the header. If all else fails, we return NULL. -------------------------------------------------------------------------*/ LogObject * Log::match_logobject(LogBufferHeader *header) { if (!header) { return nullptr; } LogObject *obj; obj = Log::config->log_object_manager.get_object_with_signature(header->log_object_signature); if (!obj) { // object does not exist yet, create it // LogFormat fmt(""__collation_format__"", header->fmt_fieldlist(), header->fmt_printf()); if (fmt.valid()) { LogFileFormat file_format = header->log_object_flags & LogObject::BINARY ? LOG_FILE_BINARY : (header->log_object_flags & LogObject::WRITES_TO_PIPE ? LOG_FILE_PIPE : LOG_FILE_ASCII); obj = new LogObject(&fmt, Log::config->logfile_dir, header->log_filename(), file_format, nullptr, (Log::RollingEnabledValues)Log::config->rolling_enabled, Log::config->collation_preproc_threads, Log::config->rolling_interval_sec, Log::config->rolling_offset_hr, Log::config->rolling_size_mb, true); obj->set_remote_flag(); if (Log::config->log_object_manager.manage_object(obj)) { // object manager can't solve filename conflicts // delete the object and return NULL // delete obj; obj = nullptr; } } } return obj; } ",16168,True,3113.1756254470683,median "/* * Copyright 2009 Rensselaer Polytechnic Institute * 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 ""energy.h"" #include ""graph.h"" #include ""GCoptimization.h"" #include #include #include #define MAX_INTT 1000000000 /**************************************************************************************/ void GCoptimization::initialize_memory() { int i = 0; m_lookupPixVar = (PixelType *) new PixelType[m_num_pixels]; m_labelTable = (LabelType *) new LabelType[m_num_labels]; terminateOnError( !m_lookupPixVar || !m_labelTable,""Not enough memory""); for ( i = 0; i < m_num_labels; i++ ) m_labelTable[i] = i; for ( i = 0; i < m_num_pixels; i++ ) m_lookupPixVar[i] = -1; } /**************************************************************************************/ void GCoptimization::commonGridInitialization(PixelType width, PixelType height, int nLabels) { terminateOnError( (width < 0) || (height <0) || (nLabels <0 ),""Illegal negative parameters""); m_width = width; m_height = height; m_num_pixels = width*height; m_num_labels = nLabels; m_grid_graph = 1; srand(time(NULL)); } /**************************************************************************************/ void GCoptimization::commonNonGridInitialization(PixelType nupixels, int num_labels) { terminateOnError( (nupixels <0) || (num_labels <0 ),""Illegal negative parameters""); m_num_labels = num_labels; m_num_pixels = nupixels; m_grid_graph = 0; m_neighbors = (LinkedBlockList *) new LinkedBlockList[nupixels]; terminateOnError(!m_neighbors,""Not enough memory""); } /**************************************************************************************/ void GCoptimization::commonInitialization(int dataSetup, int smoothSetup) { int i; m_random_label_order = 1; m_dataInput = dataSetup; m_smoothInput = smoothSetup; if (m_dataInput == SET_INDIVIDUALLY ) { m_datacost = (EnergyTermType *) new EnergyTermType[m_num_labels*m_num_pixels]; terminateOnError(!m_datacost,""Not enough memory""); for ( i = 0; i < m_num_labels*m_num_pixels; i++ ) m_datacost[i] = (EnergyTermType) 0; m_dataType = ARRAY; } else m_dataType = NONE; if ( m_smoothInput == SET_INDIVIDUALLY ) { m_smoothcost = (EnergyTermType *) new EnergyTermType[m_num_labels*m_num_labels]; terminateOnError(!m_smoothcost,""Not enough memory""); for ( i = 0; i < m_num_labels*m_num_labels; i++ ) m_smoothcost[i] = (EnergyTermType) 0; m_smoothType = ARRAY; m_varying_weights = 0; } else m_smoothType = NONE; initialize_memory(); srand(time(NULL)); // } /**************************************************************************************/ /* Use this constructor only for grid graphs */ GCoptimization::GCoptimization(PixelType width,PixelType height,int nLabels,int dataSetup, int smoothSetup ) { commonGridInitialization(width,height,nLabels); m_labeling = (LabelType *) new LabelType[m_num_pixels]; terminateOnError(!m_labeling,""out of memory""); for ( int i = 0; i < m_num_pixels; i++ ) m_labeling[i] = (LabelType) 0; m_deleteLabeling = 1; commonInitialization(dataSetup,smoothSetup); } /**************************************************************************************/ /* Use this constructor only for grid graphs */ GCoptimization::GCoptimization(LabelType *m_answer,PixelType width,PixelType height,int nLabels, int dataSetup, int smoothSetup) { commonGridInitialization(width,height,nLabels); m_labeling = m_answer; for ( int i = 0; i < m_num_pixels; i++ ) terminateOnError(m_labeling[i] < 0 || m_labeling[i] >= nLabels,""Initial labels are out of valid range""); m_deleteLabeling = 0; commonInitialization(dataSetup,smoothSetup); } /**************************************************************************************/ /* Use this constructor for general graphs */ GCoptimization::GCoptimization(PixelType nupixels,int nLabels,int dataSetup, int smoothSetup ) { commonNonGridInitialization(nupixels, nLabels); m_labeling = (LabelType *) new LabelType[m_num_pixels]; terminateOnError(!m_labeling,""out of memory""); for ( int i = 0; i < nupixels; i++ ) m_labeling[i] = (LabelType) 0; m_deleteLabeling = 1; commonInitialization(dataSetup,smoothSetup); } /**************************************************************************************/ /* By YOusef: Use this constructor for general graphs */ GCoptimization::GCoptimization(PixelType nupixels,int nLabels,int dataSetup, int smoothSetup, long numNbrs ) { commonNonGridInitialization(nupixels, nLabels); m_labeling = (LabelType *) new LabelType[m_num_pixels]; terminateOnError(!m_labeling,""out of memory""); for ( int i = 0; i < nupixels; i++ ) m_labeling[i] = (LabelType) 0; m_deleteLabeling = 1; commonInitialization(dataSetup,smoothSetup); //number of edges between neighbors nbr_count = 2*numNbrs; TTY = (Neighbor **) new Neighbor[nbr_count]; terminateOnError(!TTY,""out of memory""); nbr_index = 0; /////////////////////////////////////////////// } /**************************************************************************************/ /* Use this constructor for general graphs */ GCoptimization::GCoptimization(LabelType *m_answer, PixelType nupixels,int nLabels,int dataSetup, int smoothSetup) { commonNonGridInitialization(nupixels, nLabels); m_labeling = m_answer; for ( int i = 0; i < m_num_pixels; i++ ) terminateOnError(m_labeling[i] < 0 || m_labeling[i] >= nLabels,""Initial labels are out of valid range""); m_deleteLabeling = 0; commonInitialization(dataSetup,smoothSetup); } /**************************************************************************************/ void GCoptimization::setData(EnergyTermType* dataArray) { terminateOnError(m_dataType != NONE, ""ERROR: you already set the data, or said you'll use member function setDataCost() to set data""); // m_dataType = ARRAY; } /**************************************************************************************/ void GCoptimization::setData(dataFnPix dataFn) { terminateOnError(m_dataType != NONE, ""ERROR: you already set the data, or said you'll use member function setDataCost() to set data""); m_dataFnPix = dataFn; m_dataType = FUNCTION_PIX; } /**************************************************************************************/ void GCoptimization::setData(dataFnCoord dataFn) { terminateOnError(m_dataType != NONE, ""ERROR: you already set the data, or said you'll use member function setDataCost() to set data""); terminateOnError( !m_grid_graph,""Cannot use data function based on coordinates for non-grid graph""); m_dataFnCoord = dataFn; m_dataType = FUNCTION_COORD; } /**************************************************************************************/ void GCoptimization::setSmoothness(EnergyTermType* V) { terminateOnError(m_smoothType != NONE, ""ERROR: you already set smoothness, or said you'll use member function setSmoothCost() to set Smoothness Costs""); m_smoothType = ARRAY; // m_varying_weights = 0; } /**************************************************************************************/ void GCoptimization::setSmoothness(EnergyTermType* V,EnergyTermType* hCue, EnergyTermType* vCue) { terminateOnError(m_smoothType != NONE, ""ERROR: you already set smoothness, or said you'll use member function setSmoothCost() to set Smoothness Costs""); terminateOnError(!m_grid_graph, ""ERROR: for a grid graph, you can't use vertical and horizontal cues. Use setNeighbors() member function to encode spatially varying cues""); m_varying_weights = 1; m_smoothType = ARRAY; // } /**************************************************************************************/ void GCoptimization::setSmoothness(smoothFnCoord horz_cost, smoothFnCoord vert_cost) { terminateOnError(m_smoothType != NONE, ""ERROR: you already set smoothness, or said you'll use member function setSmoothCost() to set Smoothness Costs""); terminateOnError( !m_grid_graph,""Cannot use smoothness function based on coordinates for non-grid graph""); m_smoothType = FUNCTION_COORD; m_horz_cost = horz_cost; m_vert_cost = vert_cost; } /**************************************************************************************/ void GCoptimization::setSmoothness(smoothFnPix cost) { terminateOnError(m_smoothType != NONE, ""ERROR: you already set smoothness, or said you'll use member function setSmoothCost() to set Smoothness Costs""); m_smoothType = FUNCTION_PIX; m_smoothFnPix = cost; } /**************************************************************************************/ // /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveDataEnergy() { if ( m_dataType == ARRAY) return(giveDataEnergyArray()); else if ( m_dataType == FUNCTION_PIX ) return(giveDataEnergyFnPix()); else if (m_dataType == FUNCTION_COORD ) return(giveDataEnergyFnCoord()); else terminateOnError(1,""Did not initialize the data costs yet""); return(0); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveDataEnergyArray() { EnergyType eng = (EnergyType) 0; for ( int i = 0; i < m_num_pixels; i++ ) if (m_labeling[i] != m_num_labels+1) { float yyy = m_datacost(i,m_labeling[i]); eng = eng + yyy; //eng = eng + m_datacost(i,m_labeling[i]); } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveDataEnergyFnPix() { EnergyType eng = (EnergyType) 0; for ( int i = 0; i < m_num_pixels; i++ ) eng = eng + m_dataFnPix(i,m_labeling[i]); return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveDataEnergyFnCoord() { EnergyType eng = (EnergyType) 0; for ( int y = 0; y < m_height; y++ ) for ( int x = 0; x < m_width; x++ ) eng = eng + m_dataFnCoord(x,y,m_labeling[x+y*m_width]); return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy() { if ( m_grid_graph ) { if ( m_smoothType == ARRAY ) { if (m_varying_weights) return(giveSmoothEnergy_G_ARRAY_VW()); else return(giveSmoothEnergy_G_ARRAY()); } else if ( m_smoothType == FUNCTION_PIX ) return(giveSmoothEnergy_G_FnPix()); else if ( m_smoothType == FUNCTION_COORD ) return(giveSmoothEnergy_G_FnCoord()); else terminateOnError(1,""Did not initialize smoothness costs yet, can't compute smooth energy""); } else { if ( m_smoothType == ARRAY ) return(giveSmoothEnergy_NG_ARRAY()); else if ( m_smoothType == FUNCTION_PIX ) return(giveSmoothEnergy_NG_FnPix()); else terminateOnError(1,""Did not initialize smoothness costs yet, can't compute smooth energy""); } return(0); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_NG_FnPix() { EnergyType eng = (EnergyType) 0; int i; Neighbor *temp; for ( i = 0; i < m_num_pixels; i++ ) if ( !m_neighbors[i].isEmpty() ) { m_neighbors[i].setCursorFront(); while ( m_neighbors[i].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node ) eng = eng + m_smoothFnPix(i,temp->to_node, m_labeling[i],m_labeling[temp->to_node]); } } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_NG_ARRAY() { EnergyType eng = (EnergyType) 0; int i; Neighbor *temp; for ( i = 0; i < m_num_pixels; i++ ) if ( !m_neighbors[i].isEmpty() ) { m_neighbors[i].setCursorFront(); while ( m_neighbors[i].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node ) eng = eng + m_smoothcost(m_labeling[i],m_labeling[temp->to_node])*(temp->weight); } } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_G_ARRAY_VW() { EnergyType eng = (EnergyType) 0; int x,y,pix; // printf(""\\nIn right place""); for ( y = 0; y < m_height; y++ ) for ( x = 1; x < m_width; x++ ) if ((m_labeling[x+y*m_width-1] != m_num_labels +1) &&(m_labeling[x+y*m_width] != m_num_labels +1) ) { pix = x+y*m_width; eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-1])*m_horizWeights[pix-1]; } for ( y = 1; y < m_height; y++ ) for ( x = 0; x < m_width; x++ )if ((m_labeling[x+y*m_width-m_width] != m_num_labels +1) &&(m_labeling[x+y*m_width] != m_num_labels +1) ) { pix = x+y*m_width; eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-m_width])*m_vertWeights[pix-m_width]; } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_G_ARRAY() { EnergyType eng = (EnergyType) 0; int x,y,pix; for ( y = 0; y < m_height; y++ ) for ( x = 1; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-1]); } for ( y = 1; y < m_height; y++ ) for ( x = 0; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_smoothcost(m_labeling[pix],m_labeling[pix-m_width]); } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_G_FnPix() { EnergyType eng = (EnergyType) 0; int x,y,pix; for ( y = 0; y < m_height; y++ ) for ( x = 1; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_smoothFnPix(pix,pix-1,m_labeling[pix],m_labeling[pix-1]); } for ( y = 1; y < m_height; y++ ) for ( x = 0; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_smoothFnPix(pix,pix-m_width,m_labeling[pix],m_labeling[pix-m_width]); } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::giveSmoothEnergy_G_FnCoord() { EnergyType eng = (EnergyType) 0; int x,y,pix; for ( y = 0; y < m_height; y++ ) for ( x = 1; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_horz_cost(x-1,y,m_labeling[pix],m_labeling[pix-1]); } for ( y = 1; y < m_height; y++ ) for ( x = 0; x < m_width; x++ ) { pix = x+y*m_width; eng = eng + m_vert_cost(x,y-1,m_labeling[pix],m_labeling[pix-m_width]); } return(eng); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::compute_energy() { return(giveDataEnergy()+giveSmoothEnergy()); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::expansion(int max_num_iterations) { return(start_expansion(max_num_iterations)); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::expansion() { return(start_expansion(MAX_INTT)); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::start_expansion(int max_num_iterations ) { int curr_cycle = 1; EnergyType new_energy,old_energy; new_energy = compute_energy(); old_energy = new_energy+1; while ( old_energy > new_energy && curr_cycle <= max_num_iterations) { old_energy = new_energy; new_energy = oneExpansionIteration(); curr_cycle++; } return(new_energy); } /****************************************************************************/ void GCoptimization::scramble_label_table() { LabelType r1,r2,temp; int num_times,cnt; num_times = m_num_labels*2; for ( cnt = 0; cnt < num_times; cnt++ ) { r1 = rand()%m_num_labels; r2 = rand()%m_num_labels; temp = m_labelTable[r1]; m_labelTable[r1] = m_labelTable[r2]; m_labelTable[r2] = temp; } } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::alpha_expansion(LabelType label) { terminateOnError( label < 0 || label >= m_num_labels,""Illegal Label to Expand On""); perform_alpha_expansion(label); return(compute_energy()); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::alpha_expansion(LabelType alpha_label, PixelType *pixels, int num ) { PixelType i,size = 0; Energy *e = new Energy(); for ( i = 0; i 0 ) { Energy::Var *variables = (Energy::Var *) new Energy::Var[size]; for ( i = 0; i < size; i++ ) variables[i] = e ->add_variable(); if ( m_dataType == ARRAY ) add_t_links_ARRAY(e,variables,size,alpha_label); else if ( m_dataType == FUNCTION_PIX ) add_t_links_FnPix(e,variables,size,alpha_label); else add_t_links_FnCoord(e,variables,size,alpha_label); if ( m_grid_graph ) { if ( m_smoothType == ARRAY ) { if (m_varying_weights) set_up_expansion_energy_G_ARRAY_VW_pix(size,alpha_label,e,variables,pixels,num); else set_up_expansion_energy_G_ARRAY_pix(size,alpha_label,e,variables,pixels,num); } else if ( m_smoothType == FUNCTION_PIX ) { std::cerr<<""GraphCut:AlphaExpansion:smmoth_type->Smooth type FUNCTION_PIX not supported""<Smooth type not supported""<not m_grid_graph - unsupported""< minimize(); for ( i = 0; i < num; i++ ) { if ( m_labeling[pixels[i]] != alpha_label ) { if ( e->get_var(variables[i]) == 0 ) m_labeling[pixels[i]] = alpha_label; } m_lookupPixVar[pixels[i]] = -1; } delete [] variables; } delete e; return(compute_energy()); } /**************************************************************************************/ void GCoptimization::add_t_links_ARRAY(Energy *e,Energy::Var *variables,int size,LabelType alpha_label) { for ( int i = 0; i < size; i++ ) e -> add_term1(variables[i], m_datacost(m_lookupPixVar[i],alpha_label), m_datacost(m_lookupPixVar[i],m_labeling[m_lookupPixVar[i]])); } /**************************************************************************************/ void GCoptimization::add_t_links_FnPix(Energy *e,Energy::Var *variables,int size,LabelType alpha_label) { for ( int i = 0; i < size; i++ ) e -> add_term1(variables[i], m_dataFnPix(m_lookupPixVar[i],alpha_label), m_dataFnPix(m_lookupPixVar[i],m_labeling[m_lookupPixVar[i]])); } /**************************************************************************************/ void GCoptimization::add_t_links_FnCoord(Energy *e,Energy::Var *variables,int size,LabelType alpha_label) { int x,y; for ( int i = 0; i < size; i++ ) { y = m_lookupPixVar[i]/m_width; x = m_lookupPixVar[i] - y*m_width; e -> add_term1(variables[i], m_dataFnCoord(x,y,alpha_label), m_dataFnCoord(x,y,m_labeling[m_lookupPixVar[i]])); } } /**************************************************************************************/ void GCoptimization::perform_alpha_expansion(LabelType alpha_label) { PixelType i,size = 0; Energy *e = new Energy(); for ( i = 0; i < m_num_pixels; i++ ) { if ( m_labeling[i] != alpha_label ) { m_lookupPixVar[size] = i; size++; } } if ( size > 0 ) { Energy::Var *variables = (Energy::Var *) new Energy::Var[size]; for ( i = 0; i < size; i++ ) { variables[i] = e ->add_variable(); } if ( m_dataType == ARRAY ) add_t_links_ARRAY(e,variables,size,alpha_label); else if ( m_dataType == FUNCTION_PIX ) add_t_links_FnPix(e,variables,size,alpha_label); else add_t_links_FnCoord(e,variables,size,alpha_label); if ( m_grid_graph ) { if ( m_smoothType == ARRAY ) { if (m_varying_weights) set_up_expansion_energy_G_ARRAY_VW(size,alpha_label,e,variables); else set_up_expansion_energy_G_ARRAY(size,alpha_label,e,variables); } else if ( m_smoothType == FUNCTION_PIX ) set_up_expansion_energy_G_FnPix(size,alpha_label,e,variables); else set_up_expansion_energy_G_FnCoord(size,alpha_label,e,variables); } else { if ( m_smoothType == ARRAY ) set_up_expansion_energy_NG_ARRAY(size,alpha_label,e,variables); else if ( m_smoothType == FUNCTION_PIX ) set_up_expansion_energy_NG_FnPix(size,alpha_label,e,variables); } e -> minimize(); for ( i = 0,size = 0; i < m_num_pixels; i++ ) { if ( m_labeling[i] != alpha_label ) { if ( e->get_var(variables[size]) == 0 ) m_labeling[i] = alpha_label; size++; } } delete [] variables; } delete e; } /**********************************************************************************************/ /* Performs alpha-expansion for non regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_NG_ARRAY(int size, LabelType alpha_label,Energy *e,Energy::Var *variables ) { EnergyTermType weight; Neighbor *tmp; int i,nPix,pix;; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; m_lookupPixVar[pix] = i; if ( !m_neighbors[pix].isEmpty() ) { m_neighbors[pix].setCursorFront(); while ( m_neighbors[pix].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node; weight = tmp->weight; if ( m_labeling[nPix] != alpha_label ) { if ( pix < nPix ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight, m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight); } else e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight); } } } } /**********************************************************************************************/ /* Performs alpha-expansion for non regular grid graph for case when energy terms are */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_NG_FnPix(int size, LabelType alpha_label,Energy *e,Energy::Var *variables ) { Neighbor *tmp; int i,nPix,pix; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; m_lookupPixVar[pix] = i; if ( !m_neighbors[pix].isEmpty() ) { m_neighbors[pix].setCursorFront(); while ( m_neighbors[pix].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node; if ( m_labeling[nPix] != alpha_label ) { if ( pix < nPix ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label), m_smoothFnPix(pix,nPix,m_labeling[pix],m_labeling[nPix])); } else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label)); } } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_ARRAY_VW(int size, LabelType alpha_label,Energy *e, Energy::Var *variables ) { int i,nPix,pix,x,y; EnergyTermType weight; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; y = pix/m_width; x = pix - y*m_width; m_lookupPixVar[pix] = i; if ( x < m_width - 1 ) { nPix = pix + 1; weight = m_horizWeights[pix]; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight, m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight); } if ( y < m_height - 1 ) { nPix = pix + m_width; weight = m_vertWeights[pix]; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight , m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight , m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*m_horizWeights[nPix], m_smoothcost(m_labeling[pix],alpha_label)*m_horizWeights[nPix]); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label)*m_vertWeights[nPix], m_smoothcost(m_labeling[pix],alpha_label)*m_vertWeights[nPix]); } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_ARRAY(int size, LabelType alpha_label,Energy *e, Energy::Var *variables ) { int i,nPix,pix,x,y; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; y = pix/m_width; x = pix - y*m_width; m_lookupPixVar[pix] = i; if ( x < m_width - 1 ) { nPix = pix + 1; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label), m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label), m_smoothcost(m_labeling[pix],m_labeling[nPix])); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label)); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label) , m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label) , m_smoothcost(m_labeling[pix],m_labeling[nPix]) ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label)); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label) ); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label), m_smoothcost(m_labeling[pix],alpha_label)); } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_ARRAY_VW_pix(int size, LabelType alpha_label,Energy *e, Energy::Var *variables, PixelType *pixels, int num ) { int i,nPix,pix,x,y; EnergyTermType weight; for ( i = 0; i < num; i++ ) { pix = pixels[i]; if ( m_labeling[pix]!= alpha_label ) { y = pix/m_width; x = pix - y*m_width; if ( x < m_width - 1 ) { nPix = pix + 1; weight = m_horizWeights[pix]; if ( m_labeling[nPix] != alpha_label && m_lookupPixVar[nPix] != -1 ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight, m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight); } if ( y < m_height - 1 ) { nPix = pix + m_width; weight = m_vertWeights[pix]; if ( m_labeling[nPix] != alpha_label && m_lookupPixVar[nPix] != -1 ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight , m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],alpha_label)*weight , m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(m_labeling[pix],m_labeling[nPix])*weight); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label || m_lookupPixVar[nPix] == -1) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*m_horizWeights[nPix], m_smoothcost(m_labeling[pix],m_labeling[nPix])*m_horizWeights[nPix]); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label || m_lookupPixVar[nPix] == -1) e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label)*m_vertWeights[nPix], m_smoothcost(m_labeling[pix],m_labeling[nPix])*m_vertWeights[nPix]); } } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_ARRAY_pix(int size, LabelType alpha_label,Energy *e, Energy::Var *variables, PixelType *pixels, int num) { int i,nPix,pix,x,y; for ( i = 0; i < num; i++ ) { pix = pixels[i]; y = pix/m_width; x = pix - y*m_width; if ( m_labeling[pix]!= alpha_label ) { if ( x < m_width - 1 ) { nPix = pix + 1; if ( m_labeling[nPix] != alpha_label && m_lookupPixVar[pix] != -1) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label), m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label), m_smoothcost(m_labeling[pix],m_labeling[nPix])); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],m_labeling[nPix])); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( m_labeling[nPix] != alpha_label && m_lookupPixVar[pix] != -1) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label) , m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],alpha_label) , m_smoothcost(m_labeling[pix],m_labeling[nPix]) ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],m_labeling[nPix])); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label || m_lookupPixVar[nPix] == -1) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(m_labeling[pix],m_labeling[nPix]) ); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label || m_lookupPixVar[nPix] == -1) e ->add_term1(variables[i],m_smoothcost(alpha_label,alpha_label), m_smoothcost(m_labeling[pix],m_labeling[nPix])); } } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_FnPix(int size, LabelType alpha_label,Energy *e, Energy::Var *variables ) { int i,nPix,pix,x,y; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; y = pix/m_width; x = pix - y*m_width; m_lookupPixVar[pix] = i; if ( x < m_width - 1 ) { nPix = pix + 1; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label), m_smoothFnPix(pix,nPix,m_labeling[pix],m_labeling[nPix])); else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label)); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label) , m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label) , m_smoothFnPix(pix,nPix,m_labeling[pix],m_labeling[nPix]) ); else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label)); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label) ); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,m_labeling[pix],alpha_label)); } } } /**********************************************************************************************/ /* Performs alpha-expansion for regular grid graph for case when energy terms are NOT */ /* specified by a function */ void GCoptimization::set_up_expansion_energy_G_FnCoord(int size, LabelType alpha_label,Energy *e, Energy::Var *variables ) { int i,nPix,pix,x,y; for ( i = size - 1; i >= 0; i-- ) { pix = m_lookupPixVar[i]; y = pix/m_width; x = pix - y*m_width; m_lookupPixVar[pix] = i; if ( x < m_width - 1 ) { nPix = pix + 1; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_horz_cost(x,y,alpha_label,alpha_label), m_horz_cost(x,y,alpha_label,m_labeling[nPix]), m_horz_cost(x,y,m_labeling[pix],alpha_label), m_horz_cost(x,y,m_labeling[pix],m_labeling[nPix])); else e ->add_term1(variables[i],m_horz_cost(x,y,alpha_label,alpha_label), m_horz_cost(x,y,m_labeling[pix],alpha_label)); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( m_labeling[nPix] != alpha_label ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_vert_cost(x,y,alpha_label,alpha_label) , m_vert_cost(x,y,alpha_label,m_labeling[nPix]), m_vert_cost(x,y,m_labeling[pix],alpha_label) , m_vert_cost(x,y,m_labeling[pix],m_labeling[nPix]) ); else e ->add_term1(variables[i],m_vert_cost(x,y,alpha_label,alpha_label), m_vert_cost(x,y,m_labeling[pix],alpha_label)); } if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_horz_cost(x-1,y,alpha_label,m_labeling[nPix]), m_horz_cost(x-1,y,m_labeling[pix],alpha_label) ); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label ) e ->add_term1(variables[i],m_vert_cost(x,y-1,alpha_label,alpha_label), m_vert_cost(x,y-1,m_labeling[pix],alpha_label)); } } } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::oneExpansionIteration() { int next; terminateOnError( m_dataType == NONE,""You have to set up the data cost before running optimization""); terminateOnError( m_smoothType == NONE,""You have to set up the smoothness cost before running optimization""); if (m_random_label_order) scramble_label_table(); for (next = 0; next < m_num_labels; next++ ) { perform_alpha_expansion(m_labelTable[next]); } return(compute_energy()); } /**************************************************************************************/ void GCoptimization::setNeighbors(PixelType pixel1, int pixel2, EnergyTermType weight) { assert(pixel1 < m_num_pixels && pixel1 >= 0 && pixel2 < m_num_pixels && pixel2 >= 0); assert(m_grid_graph == 0); /*Neighbor *temp1 = (Neighbor *) new Neighbor; Neighbor *temp2 = (Neighbor *) new Neighbor; temp1->weight = weight; temp1->to_node = pixel2; temp2->weight = weight; temp2->to_node = pixel1; m_neighbors[pixel1].addFront(temp1); m_neighbors[pixel1].addFront(temp2);*/ TTY[nbr_index] = (Neighbor *) new Neighbor; terminateOnError(!TTY[nbr_index],""out of memory""); TTY[nbr_index]->weight = weight; TTY[nbr_index]->to_node = pixel2; m_neighbors[pixel1].addFront(TTY[nbr_index]); nbr_index++; TTY[nbr_index] = (Neighbor *) new Neighbor; terminateOnError(!TTY[nbr_index],""out of memory""); TTY[nbr_index]->weight = weight; TTY[nbr_index]->to_node = pixel2; m_neighbors[pixel2].addFront(TTY[nbr_index]); nbr_index++; } /**************************************************************************************/ void GCoptimization::setNeighbors(PixelType pixel1, int pixel2) { assert(pixel1 < m_num_pixels && pixel1 >= 0 && pixel2 < m_num_pixels && pixel2 >= 0); assert(m_grid_graph == 0); Neighbor *temp1 = (Neighbor *) new Neighbor; Neighbor *temp2 = (Neighbor *) new Neighbor; temp1->weight = (EnergyTermType) 1; temp1->to_node = pixel2; temp2->weight = (EnergyTermType) 1; temp2->to_node = pixel1; m_neighbors[pixel1].addFront(temp1); m_neighbors[pixel2].addFront(temp2); } /**************************************************************************************/ GCoptimization::~GCoptimization() { // if ( m_deleteLabeling ) delete [] m_labeling; if ( m_dataInput == SET_INDIVIDUALLY ) delete [] m_datacost; if ( m_smoothInput == SET_INDIVIDUALLY ) delete [] m_smoothcost; if ( ! m_grid_graph ) { for(int i=0; i new_energy && curr_cycle <= max_num_iterations) { old_energy = new_energy; new_energy = oneSwapIteration(); curr_cycle++; } return(new_energy); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::oneSwapIteration() { int next,next1; if (m_random_label_order) scramble_label_table(); for (next = 0; next < m_num_labels; next++ ) for (next1 = m_num_labels - 1; next1 >= 0; next1-- ) if ( m_labelTable[next] < m_labelTable[next1] ) perform_alpha_beta_swap(m_labelTable[next],m_labelTable[next1]); return(compute_energy()); } /**************************************************************************************/ GCoptimization::EnergyType GCoptimization::alpha_beta_swap(LabelType alpha_label, LabelType beta_label) { terminateOnError( alpha_label < 0 || alpha_label >= m_num_labels || beta_label < 0 || beta_label >= m_num_labels, ""Illegal Label to Expand On""); perform_alpha_beta_swap(alpha_label,beta_label); return(compute_energy()); } /**************************************************************************************/ void GCoptimization::add_t_links_ARRAY_swap(Energy *e,Energy::Var *variables,int size, LabelType alpha_label, LabelType beta_label, PixelType *pixels) { for ( int i = 0; i < size; i++ ) e -> add_term1(variables[i], m_datacost(pixels[i],alpha_label), m_datacost(pixels[i],beta_label)); } /**************************************************************************************/ void GCoptimization::add_t_links_FnPix_swap(Energy *e,Energy::Var *variables,int size, LabelType alpha_label, LabelType beta_label, PixelType *pixels) { for ( int i = 0; i < size; i++ ) e -> add_term1(variables[i], m_dataFnPix(pixels[i],alpha_label), m_dataFnPix(pixels[i],beta_label)); } /**************************************************************************************/ void GCoptimization::add_t_links_FnCoord_swap(Energy *e,Energy::Var *variables,int size, LabelType alpha_label, LabelType beta_label, PixelType *pixels) { int x,y; for ( int i = 0; i < size; i++ ) { y = pixels[i]/m_width; x = pixels[i] - y*m_width; e -> add_term1(variables[i], m_dataFnCoord(x,y,alpha_label),m_dataFnCoord(x,y,beta_label)); } } /**************************************************************************************/ void GCoptimization::perform_alpha_beta_swap(LabelType alpha_label, LabelType beta_label) { PixelType i,size = 0; Energy *e = new Energy(); PixelType *pixels = new PixelType[m_num_pixels]; for ( i = 0; i < m_num_pixels; i++ ) { if ( m_labeling[i] == alpha_label || m_labeling[i] == beta_label) { pixels[size] = i; m_lookupPixVar[i] = size; size++; } } if ( size == 0 ) { delete e; delete [] pixels; return; } Energy::Var *variables = (Energy::Var *) new Energy::Var[size]; for ( i = 0; i < size; i++ ) variables[i] = e ->add_variable(); if ( m_dataType == ARRAY ) add_t_links_ARRAY_swap(e,variables,size,alpha_label,beta_label,pixels); else if ( m_dataType == FUNCTION_PIX ) add_t_links_FnPix_swap(e,variables,size,alpha_label,beta_label,pixels); else add_t_links_FnCoord_swap(e,variables,size,alpha_label,beta_label,pixels); if ( m_grid_graph ) { if ( m_smoothType == ARRAY ) { if (m_varying_weights) set_up_swap_energy_G_ARRAY_VW(size,alpha_label,beta_label,pixels,e,variables); else set_up_swap_energy_G_ARRAY(size,alpha_label,beta_label,pixels,e,variables); } else if ( m_smoothType == FUNCTION_PIX ) set_up_swap_energy_G_FnPix(size,alpha_label,beta_label,pixels,e,variables); else set_up_swap_energy_G_FnCoord(size,alpha_label,beta_label,pixels,e,variables); } else { if ( m_smoothType == ARRAY ) set_up_swap_energy_NG_ARRAY(size,alpha_label,beta_label,pixels,e,variables); else if ( m_smoothType == FUNCTION_PIX ) set_up_swap_energy_NG_FnPix(size,alpha_label,beta_label,pixels,e,variables); } e -> minimize(); for ( i = 0; i < size; i++ ) if ( e->get_var(variables[i]) == 0 ) m_labeling[pixels[i]] = alpha_label; else m_labeling[pixels[i]] = beta_label; delete [] variables; delete [] pixels; delete e; } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_NG_ARRAY(int size,LabelType alpha_label,LabelType beta_label, PixelType *pixels,Energy* e, Energy::Var *variables) { PixelType nPix,pix,i; EnergyTermType weight; Neighbor *tmp; for ( i = 0; i < size; i++ ) { pix = pixels[i]; if ( !m_neighbors[pix].isEmpty() ) { m_neighbors[pix].setCursorFront(); while ( m_neighbors[pix].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node; weight = tmp->weight; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) { if ( pix < nPix ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,beta_label)*weight, m_smoothcost(beta_label,alpha_label)*weight, m_smoothcost(beta_label,beta_label)*weight); } else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(beta_label,m_labeling[nPix])*weight); } } } } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_NG_FnPix(int size,LabelType alpha_label,LabelType beta_label, PixelType *pixels,Energy* e, Energy::Var *variables) { PixelType nPix,pix,i; Neighbor *tmp; for ( i = 0; i < size; i++ ) { pix = pixels[i]; if ( !m_neighbors[pix].isEmpty() ) { m_neighbors[pix].setCursorFront(); while ( m_neighbors[pix].hasNext() ) //int ll = m_neighbors[i].getBlockSize(); //for(int kk=0; kkto_node; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) { if ( pix < nPix ) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,alpha_label,beta_label), m_smoothFnPix(pix,nPix,beta_label,alpha_label), m_smoothFnPix(pix,nPix,beta_label,beta_label) ); } else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,beta_label,m_labeling[nPix])); } } } } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_G_FnPix(int size,LabelType alpha_label,LabelType beta_label, PixelType *pixels,Energy* e, Energy::Var *variables) { PixelType nPix,pix,i,x,y; for ( i = 0; i < size; i++ ) { pix = pixels[i]; y = pix/m_width; x = pix - y*m_width; if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,alpha_label,beta_label), m_smoothFnPix(pix,nPix,beta_label,alpha_label), m_smoothFnPix(pix,nPix,beta_label,beta_label) ); else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,beta_label,m_labeling[nPix])); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothFnPix(pix,nPix,alpha_label,alpha_label), m_smoothFnPix(pix,nPix,alpha_label,beta_label), m_smoothFnPix(pix,nPix,beta_label,alpha_label), m_smoothFnPix(pix,nPix,beta_label,beta_label) ); else e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,beta_label,m_labeling[nPix])); } if ( x < m_width - 1 ) { nPix = pix + 1; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,beta_label,m_labeling[nPix])); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_smoothFnPix(pix,nPix,alpha_label,m_labeling[nPix]), m_smoothFnPix(pix,nPix,beta_label,m_labeling[nPix])); } } } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_G_FnCoord(int size,LabelType alpha_label,LabelType beta_label,PixelType *pixels, Energy* e, Energy::Var *variables) { PixelType nPix,pix,i,x,y; for ( i = 0; i < size; i++ ) { pix = pixels[i]; y = pix/m_width; x = pix - y*m_width; if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_horz_cost(x-1,y,alpha_label,alpha_label), m_horz_cost(x-1,y,alpha_label,beta_label), m_horz_cost(x-1,y,beta_label,alpha_label), m_horz_cost(x-1,y,beta_label,beta_label) ); else e ->add_term1(variables[i],m_horz_cost(x-1,y,alpha_label,m_labeling[nPix]), m_horz_cost(x-1,y,beta_label,m_labeling[nPix])); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_vert_cost(x,y-1,alpha_label,alpha_label), m_vert_cost(x,y-1,alpha_label,beta_label), m_vert_cost(x,y-1,beta_label,alpha_label), m_vert_cost(x,y-1,beta_label,beta_label) ); else e ->add_term1(variables[i],m_vert_cost(x,y-1,alpha_label,m_labeling[nPix]), m_vert_cost(x,y-1,beta_label,m_labeling[nPix])); } if ( x < m_width - 1 ) { nPix = pix + 1; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_horz_cost(x,y,alpha_label,m_labeling[nPix]), m_horz_cost(x,y,beta_label,m_labeling[nPix])); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_vert_cost(x,y,alpha_label,m_labeling[nPix]), m_vert_cost(x,y,beta_label,m_labeling[nPix])); } } } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_G_ARRAY_VW(int size,LabelType alpha_label,LabelType beta_label, PixelType *pixels,Energy* e, Energy::Var *variables) { PixelType nPix,pix,i,x,y; EnergyTermType weight; for ( i = 0; i < size; i++ ) { pix = pixels[i]; y = pix/m_width; x = pix - y*m_width; if ( x > 0 ) { nPix = pix - 1; weight = m_horizWeights[nPix]; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,beta_label)*weight, m_smoothcost(beta_label,alpha_label)*weight, m_smoothcost(beta_label,beta_label)*weight ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(beta_label,m_labeling[nPix])*weight); } if ( y > 0 ) { nPix = pix - m_width; weight = m_vertWeights[nPix]; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label)*weight, m_smoothcost(alpha_label,beta_label)*weight, m_smoothcost(beta_label,alpha_label)*weight, m_smoothcost(beta_label,beta_label)*weight ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*weight, m_smoothcost(beta_label,m_labeling[nPix])*weight); } if ( x < m_width - 1 ) { nPix = pix + 1; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*m_horizWeights[pix], m_smoothcost(beta_label,m_labeling[nPix])*m_horizWeights[pix]); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix])*m_vertWeights[pix], m_smoothcost(beta_label,m_labeling[nPix])*m_vertWeights[pix]); } } } /**************************************************************************************/ void GCoptimization::set_up_swap_energy_G_ARRAY(int size,LabelType alpha_label,LabelType beta_label, PixelType *pixels,Energy* e, Energy::Var *variables) { PixelType nPix,pix,i,x,y; for ( i = 0; i < size; i++ ) { pix = pixels[i]; y = pix/m_width; x = pix - y*m_width; if ( x > 0 ) { nPix = pix - 1; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label), m_smoothcost(alpha_label,beta_label), m_smoothcost(beta_label,alpha_label), m_smoothcost(beta_label,beta_label) ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(beta_label,m_labeling[nPix])); } if ( y > 0 ) { nPix = pix - m_width; if ( m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) e ->add_term2(variables[i],variables[m_lookupPixVar[nPix]], m_smoothcost(alpha_label,alpha_label), m_smoothcost(alpha_label,beta_label), m_smoothcost(beta_label,alpha_label), m_smoothcost(beta_label,beta_label) ); else e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(beta_label,m_labeling[nPix])); } if ( x < m_width - 1 ) { nPix = pix + 1; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label) ) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(beta_label,m_labeling[nPix])); } if ( y < m_height - 1 ) { nPix = pix + m_width; if ( !(m_labeling[nPix] == alpha_label || m_labeling[nPix] == beta_label)) e ->add_term1(variables[i],m_smoothcost(alpha_label,m_labeling[nPix]), m_smoothcost(beta_label,m_labeling[nPix])); } } } /**************************************************************************************/ void GCoptimization::setLabelOrder(bool RANDOM_LABEL_ORDER) { m_random_label_order = RANDOM_LABEL_ORDER; } /****************************************************************************/ /* This procedure checks if an error has occured, terminates program if yes */ void GCoptimization::terminateOnError(bool error_condition,const char *message) { if (error_condition) { std::cerr<<""GraphCut:GCoptimization:errorFn->erros""<> through `@ConfigurationProperties`. Spring Boot uses a very particular `PropertySource` order that is designed to allow sensible overriding of values. Properties are considered in the following order (with values from lower items overriding earlier ones): . Default properties (specified by setting `SpringApplication.setDefaultProperties`). . {spring-framework-api}/context/annotation/PropertySource.html[`@PropertySource`] annotations on your `@Configuration` classes. Please note that such property sources are not added to the `Environment` until the application context is being refreshed. This is too late to configure certain properties such as `+logging.*+` and `+spring.main.*+` which are read before refresh begins. . Config data (such as `application.properties` files). . A `RandomValuePropertySource` that has properties only in `+random.*+`. . OS environment variables. . Java System properties (`System.getProperties()`). . JNDI attributes from `java:comp/env`. . `ServletContext` init parameters. . `ServletConfig` init parameters. . Properties from `SPRING_APPLICATION_JSON` (inline JSON embedded in an environment variable or system property). . Command line arguments. . `properties` attribute on your tests. Available on {spring-boot-test-module-api}/context/SpringBootTest.html[`@SpringBootTest`] and the <>. . {spring-framework-api}/test/context/TestPropertySource.html[`@TestPropertySource`] annotations on your tests. . <> in the `$HOME/.config/spring-boot` directory when devtools is active. Config data files are considered in the following order: . <> packaged inside your jar (`application.properties` and YAML variants). . <> packaged inside your jar (`application-\\{profile}.properties` and YAML variants). . <> outside of your packaged jar (`application.properties` and YAML variants). . <> outside of your packaged jar (`application-\\{profile}.properties` and YAML variants). NOTE: It is recommended to stick with one format for your entire application. If you have configuration files with both `.properties` and `.yml` format in the same location, `.properties` takes precedence. To provide a concrete example, suppose you develop a `@Component` that uses a `name` property, as shown in the following example: include::code:MyBean[] On your application classpath (for example, inside your jar) you can have an `application.properties` file that provides a sensible default property value for `name`. When running in a new environment, an `application.properties` file can be provided outside of your jar that overrides the `name`. For one-off testing, you can launch with a specific command line switch (for example, `java -jar app.jar --name=""Spring""`). TIP: The `env` and `configprops` endpoints can be useful in determining why a property has a particular value. You can use these two endpoints to diagnose unexpected property values. See the ""<>"" section for details. [[features.external-config.command-line-args]] === Accessing Command Line Properties By default, `SpringApplication` converts any command line option arguments (that is, arguments starting with `--`, such as `--server.port=9000`) to a `property` and adds them to the Spring `Environment`. As mentioned previously, command line properties always take precedence over file-based property sources. If you do not want command line properties to be added to the `Environment`, you can disable them by using `SpringApplication.setAddCommandLineProperties(false)`. [[features.external-config.application-json]] === JSON Application Properties Environment variables and system properties often have restrictions that mean some property names cannot be used. To help with this, Spring Boot allows you to encode a block of properties into a single JSON structure. When your application starts, any `spring.application.json` or `SPRING_APPLICATION_JSON` properties will be parsed and added to the `Environment`. For example, the `SPRING_APPLICATION_JSON` property can be supplied on the command line in a UN{asterisk}X shell as an environment variable: [source,shell,indent=0,subs=""verbatim""] ---- $ SPRING_APPLICATION_JSON='{""my"":{""name"":""test""}}' java -jar myapp.jar ---- In the preceding example, you end up with `my.name=test` in the Spring `Environment`. The same JSON can also be provided as a system property: [source,shell,indent=0,subs=""verbatim""] ---- $ java -Dspring.application.json='{""my"":{""name"":""test""}}' -jar myapp.jar ---- Or you could supply the JSON by using a command line argument: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myapp.jar --spring.application.json='{""my"":{""name"":""test""}}' ---- If you are deploying to a classic Application Server, you could also use a JNDI variable named `java:comp/env/spring.application.json`. NOTE: Although `null` values from the JSON will be added to the resulting property source, the `PropertySourcesPropertyResolver` treats `null` properties as missing values. This means that the JSON cannot override properties from lower order property sources with a `null` value. [[features.external-config.files]] === External Application Properties [[features.external-config.files]] Spring Boot will automatically find and load `application.properties` and `application.yaml` files from the following locations when your application starts: . From the classpath .. The classpath root .. The classpath `/config` package . From the current directory .. The current directory .. The `/config` subdirectory in the current directory .. Immediate child directories of the `/config` subdirectory The list is ordered by precedence (with values from lower items overriding earlier ones). Documents from the loaded files are added as `PropertySources` to the Spring `Environment`. If you do not like `application` as the configuration file name, you can switch to another file name by specifying a configprop:spring.config.name[] environment property. For example, to look for `myproject.properties` and `myproject.yaml` files you can run your application as follows: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.name=myproject ---- You can also refer to an explicit location by using the configprop:spring.config.location[] environment property. This properties accepts a comma-separated list of one or more locations to check. The following example shows how to specify two distinct files: [source,shell,indent=0,subs=""verbatim""] ---- $ java -jar myproject.jar --spring.config.location=\\ optional:classpath:/default.properties,\\ optional:classpath:/override.properties ---- TIP: Use the prefix `optional:` if the <> and you do not mind if they do not exist. WARNING: `spring.config.name`, `spring.config.location`, and `spring.config.additional-location` are used very early to determine which files have to be loaded. They must be defined as an environment property (typically an OS environment variable, a system property, or a command-line argument). If `spring.config.location` contains directories (as opposed to files), they should end in `/`. At runtime they will be appended with the names generated from `spring.config.name` before being loaded. Files specified in `spring.config.location` are imported directly. NOTE: Both directory and file location values are also expanded to check for <>. For example, if you have a `spring.config.location` of `classpath:myconfig.properties`, you will also find appropriate `classpath:myconfig-.properties` files are loaded. In most situations, each configprop:spring.config.location[] item you add will reference a single file or directory. Locations are processed in the order that they are defined and later ones can override the values of earlier ones. [[features.external-config.files.location-groups]] If you have a complex location setup, and you use profile-specific configuration files, you may need to provide further hints so that Spring Boot knows how they should be grouped. A location group is a collection of locations that are all considered at the same level. For example, you might want to group all classpath locations, then all external locations. Items within a location group should be separated with `;`. See the example in the ""`<>`"" section for more details. Locations configured by using `spring.config.location` replace the default locations. For example, if `spring.config.location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:custom-config/` . `optional:file:./custom-config/` If you prefer to add additional locations, rather than replacing them, you can use `spring.config.additional-location`. Properties loaded from additional locations can override those in the default locations. For example, if `spring.config.additional-location` is configured with the value `optional:classpath:/custom-config/,optional:file:./custom-config/`, the complete set of locations considered is: . `optional:classpath:/;optional:classpath:/config/` . `optional:file:./;optional:file:./config/;optional:file:./config/*/` . `optional:classpath:custom-config/` . `optional:file:./custom-config/` This search ordering lets you specify default values in one configuration file and then selectively override those values in another. You can provide default values for your application in `application.properties` (or whatever other basename you choose with `spring.config.name`) in one of the default locations. These default values can then be overridden at runtime with a different file located in one of the custom locations. NOTE: If you use environment variables rather than system properties, most operating systems disallow period-separated key names, but you can use underscores instead (for example, configprop:spring.config.name[format=envvar] instead of configprop:spring.config.name[]). See <> for details. NOTE: If your application runs in a servlet container or application server, then JNDI properties (in `java:comp/env`) or servlet context initialization parameters can be used instead of, or as well as, environment variables or system properties. [[features.external-config.files.optional-prefix]] ==== Optional Locations By default, when a specified config data location does not exist, Spring Boot will throw a `ConfigDataLocationNotFoundException` and your application will not start. If you want to specify a location, but you do not mind if it does not always exist, you can use the `optional:` prefix. You can use this prefix with the `spring.config.location` and `spring.config.additional-location` properties, as well as with <> declarations. For example, a `spring.config.import` value of `optional:file:./myconfig.properties` allows your application to start, even if the `myconfig.properties` file is missing. If you want to ignore all `ConfigDataLocationNotFoundExceptions` and always continue to start your application, you can use the `spring.config.on-not-found` property. Set the value to `ignore` using `SpringApplication.setDefaultProperties(...)` or with a system/environment variable. [[features.external-config.files.wildcard-locations]] ==== Wildcard Locations If a config file location includes the `{asterisk}` character for the last path segment, it is considered a wildcard location. Wildcards are expanded when the config is loaded so that immediate subdirectories are also checked. Wildcard locations are particularly useful in an environment such as Kubernetes when there are multiple sources of config properties. For example, if you have some Redis configuration and some MySQL configuration, you might want to keep those two pieces of configuration separate, while requiring that both those are present in an `application.properties` file. This might result in two separate `application.properties` files mounted at different locations such as `/config/redis/application.properties` and `/config/mysql/application.properties`. In such a case, having a wildcard location of `config/*/`, will result in both files being processed. By default, Spring Boot includes `config/*/` in the default search locations. It means that all subdirectories of the `/config` directory outside of your jar will be searched. You can use wildcard locations yourself with the `spring.config.location` and `spring.config.additional-location` properties. NOTE: A wildcard location must contain only one `{asterisk}` and end with `{asterisk}/` for search locations that are directories or `*/` for search locations that are files. Locations with wildcards are sorted alphabetically based on the absolute path of the file names. TIP: Wildcard locations only work with external directories. You cannot use a wildcard in a `classpath:` location. [[features.external-config.files.profile-specific]] ==== Profile Specific Files As well as `application` property files, Spring Boot will also attempt to load profile-specific files using the naming convention `application-\\{profile}`. For example, if your application activates a profile named `prod` and uses YAML files, then both `application.yml` and `application-prod.yml` will be considered. Profile-specific properties are loaded from the same locations as standard `application.properties`, with profile-specific files always overriding the non-specific ones. If several profiles are specified, a last-wins strategy applies. For example, if profiles `prod,live` are specified by the configprop:spring.profiles.active[] property, values in `application-prod.properties` can be overridden by those in `application-live.properties`. [NOTE] ==== The last-wins strategy applies at the <> level. A configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` will not have the same override rules as `classpath:/cfg/;classpath:/ext/`. For example, continuing our `prod,live` example above, we might have the following files: ---- /cfg application-live.properties /ext application-live.properties application-prod.properties ---- When we have a configprop:spring.config.location[] of `classpath:/cfg/,classpath:/ext/` we process all `/cfg` files before all `/ext` files: . `/cfg/application-live.properties` . `/ext/application-prod.properties` . `/ext/application-live.properties` When we have `classpath:/cfg/;classpath:/ext/` instead (with a `;` delimiter) we process `/cfg` and `/ext` at the same level: . `/ext/application-prod.properties` . `/cfg/application-live.properties` . `/ext/application-live.properties` ==== The `Environment` has a set of default profiles (by default, `[default]`) that are used if no active profiles are set. In other words, if no profiles are explicitly activated, then properties from `application-default` are considered. NOTE: Properties files are only ever loaded once. If you have already directly <> a profile specific property files then it will not be imported a second time. [[features.external-config.files.importing]] ==== Importing Additional Data Application properties may import further config data from other locations using the `spring.config.import` property. Imports are processed as they are discovered, and are treated as additional documents inserted immediately below the one that declares the import. For example, you might have the following in your classpath `application.properties` file: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: application: name: ""myapp"" config: import: ""optional:file:./dev.properties"" ---- This will trigger the import of a `dev.properties` file in current directory (if such a file exists). Values from the imported `dev.properties` will take precedence over the file that triggered the import. In the above example, the `dev.properties` could redefine `spring.application.name` to a different value. An import will only be imported once no matter how many times it is declared. The order an import is defined inside a single document within the properties/yaml file does not matter. For instance, the two examples below produce the same result: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- spring: config: import: ""my.properties"" my: property: ""value"" ---- [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: property: ""value"" spring: config: import: ""my.properties"" ---- In both of the above examples, the values from the `my.properties` file will take precedence over the file that triggered its import. Several locations can be specified under a single `spring.config.import` key. Locations will be processed in the order that they are defined, with later imports taking precedence. NOTE: When appropriate, <> are also considered for import. The example above would import both `my.properties` as well as any `my-.properties` variants. [TIP] ==== Spring Boot includes pluggable API that allows various different location addresses to be supported. By default you can import Java Properties, YAML and ""`<>`"". Third-party jars can offer support for additional technologies (there is no requirement for files to be local). For example, you can imagine config data being from external stores such as Consul, Apache ZooKeeper or Netflix Archaius. If you want to support your own locations, see the `ConfigDataLocationResolver` and `ConfigDataLoader` classes in the `org.springframework.boot.context.config` package. ==== [[features.external-config.files.importing-extensionless]] ==== Importing Extensionless Files Some cloud platforms cannot add a file extension to volume mounted files. To import these extensionless files, you need to give Spring Boot a hint so that it knows how to load them. You can do this by putting an extension hint in square brackets. For example, suppose you have a `/etc/config/myconfig` file that you wish to import as yaml. You can import it from your `application.properties` using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""file:/etc/config/myconfig[.yaml]"" ---- [[features.external-config.files.configtree]] ==== Using Configuration Trees When running applications on a cloud platform (such as Kubernetes) you often need to read config values that the platform supplies. It is not uncommon to use environment variables for such purposes, but this can have drawbacks, especially if the value is supposed to be kept secret. As an alternative to environment variables, many cloud platforms now allow you to map configuration into mounted data volumes. For example, Kubernetes can volume mount both https://kubernetes.io/docs/tasks/configure-pod-container/configure-pod-configmap/#populate-a-volume-with-data-stored-in-a-configmap[`ConfigMaps`] and https://kubernetes.io/docs/concepts/configuration/secret/#using-secrets-as-files-from-a-pod[`Secrets`]. There are two common volume mount patterns that can be used: . A single file contains a complete set of properties (usually written as YAML). . Multiple files are written to a directory tree, with the filename becoming the '`key`' and the contents becoming the '`value`'. For the first case, you can import the YAML or Properties file directly using `spring.config.import` as described <>. For the second case, you need to use the `configtree:` prefix so that Spring Boot knows it needs to expose all the files as properties. As an example, let's imagine that Kubernetes has mounted the following volume: [indent=0] ---- etc/ config/ myapp/ username password ---- The contents of the `username` file would be a config value, and the contents of `password` would be a secret. To import these properties, you can add the following to your `application.properties` or `application.yaml` file: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/"" ---- You can then access or inject `myapp.username` and `myapp.password` properties from the `Environment` in the usual way. NOTE: Filenames with dot notation are also correctly mapped. For example, in the above example, a file named `myapp.username` in `/etc/config` would result in a `myapp.username` property in the `Environment`. TIP: Configuration tree values can be bound to both string `String` and `byte[]` types depending on the contents expected. If you have multiple config trees to import from the same parent folder you can use a wildcard shortcut. Any `configtree:` location that ends with `/*/` will import all immediate children as config trees. For example, given the following volume: [indent=0] ---- etc/ config/ dbconfig/ db/ username password mqconfig/ mq/ username password ---- You can use `configtree:/etc/config/*/` as the import location: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/etc/config/*/"" ---- This will add `db.username`, `db.password`, `mq.username` and `mq.password` properties. NOTE: Directories loaded using a wildcard are sorted alphabetically. If you need a different order, then you should list each location as a separate import Configuration trees can also be used for Docker secrets. When a Docker swarm service is granted access to a secret, the secret gets mounted into the container. For example, if a secret named `db.password` is mounted at location `/run/secrets/`, you can make `db.password` available to the Spring environment using the following: [source,yaml,indent=0,subs=""verbatim"",configprops,configblocks] ---- spring: config: import: ""optional:configtree:/run/secrets/"" ---- [[features.external-config.files.property-placeholders]] ==== Property Placeholders The values in `application.properties` and `application.yml` are filtered through the existing `Environment` when they are used, so you can refer back to previously defined values (for example, from System properties). The standard `$\\{name}` property-placeholder syntax can be used anywhere within a value. For example, the following file will set `app.description` to ""`MyApp is a Spring Boot application`"": [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- app: name: ""MyApp"" description: ""${app.name} is a Spring Boot application"" ---- TIP: You can also use this technique to create ""`short`"" variants of existing Spring Boot properties. See the _<>_ how-to for details. [[features.external-config.files.multi-document]] ==== Working with Multi-Document Files Spring Boot allows you to split a single physical file into multiple logical documents which are each added independently. Documents are processed in order, from top to bottom. Later documents can override the properties defined in earlier ones. For `application.yml` files, the standard YAML multi-document syntax is used. Three consecutive hyphens represent the end of one document, and the start of the next. For example, the following file has two logical documents: [source,yaml,indent=0,subs=""verbatim""] ---- spring: application: name: ""MyApp"" --- spring: application: name: ""MyCloudApp"" config: activate: on-cloud-platform: ""kubernetes"" ---- For `application.properties` files a special `#---` comment is used to mark the document splits: [source,properties,indent=0,subs=""verbatim""] ---- spring.application.name=MyApp #--- spring.application.name=MyCloudApp spring.config.activate.on-cloud-platform=kubernetes ---- NOTE: Property file separators must not have any leading whitespace and must have exactly three hyphen characters. The lines immediately before and after the separator must not be comments. TIP: Multi-document property files are often used in conjunction with activation properties such as `spring.config.activate.on-profile`. See the <> for details. WARNING: Multi-document property files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. [[features.external-config.files.activation-properties]] ==== Activation Properties It is sometimes useful to only activate a given set of properties when certain conditions are met. For example, you might have properties that are only relevant when a specific profile is active. You can conditionally activate a properties document using `spring.config.activate.*`. The following activation properties are available: .activation properties [cols=""1,4""] |=== | Property | Note | `on-profile` | A profile expression that must match for the document to be active. | `on-cloud-platform` | The `CloudPlatform` that must be detected for the document to be active. |=== For example, the following specifies that the second document is only active when running on Kubernetes, and only when either the ""`prod`"" or ""`staging`"" profiles are active: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- myprop: ""always-set"" --- spring: config: activate: on-cloud-platform: ""kubernetes"" on-profile: ""prod | staging"" myotherprop: ""sometimes-set"" ---- [[features.external-config.encrypting]] === Encrypting Properties Spring Boot does not provide any built in support for encrypting property values, however, it does provide the hook points necessary to modify values contained in the Spring `Environment`. The `EnvironmentPostProcessor` interface allows you to manipulate the `Environment` before the application starts. See <> for details. If you need a secure way to store credentials and passwords, the https://cloud.spring.io/spring-cloud-vault/[Spring Cloud Vault] project provides support for storing externalized configuration in https://www.vaultproject.io/[HashiCorp Vault]. [[features.external-config.yaml]] === Working with YAML https://yaml.org[YAML] is a superset of JSON and, as such, is a convenient format for specifying hierarchical configuration data. The `SpringApplication` class automatically supports YAML as an alternative to properties whenever you have the https://bitbucket.org/asomov/snakeyaml[SnakeYAML] library on your classpath. NOTE: If you use ""`Starters`"", SnakeYAML is automatically provided by `spring-boot-starter`. [[features.external-config.yaml.mapping-to-properties]] ==== Mapping YAML to Properties YAML documents need to be converted from their hierarchical format to a flat structure that can be used with the Spring `Environment`. For example, consider the following YAML document: [source,yaml,indent=0,subs=""verbatim""] ---- environments: dev: url: ""https://dev.example.com"" name: ""Developer Setup"" prod: url: ""https://another.example.com"" name: ""My Cool App"" ---- In order to access these properties from the `Environment`, they would be flattened as follows: [source,properties,indent=0,subs=""verbatim""] ---- environments.dev.url=https://dev.example.com environments.dev.name=Developer Setup environments.prod.url=https://another.example.com environments.prod.name=My Cool App ---- Likewise, YAML lists also need to be flattened. They are represented as property keys with `[index]` dereferencers. For example, consider the following YAML: [source,yaml,indent=0,subs=""verbatim""] ---- my: servers: - ""dev.example.com"" - ""another.example.com"" ---- The preceding example would be transformed into these properties: [source,properties,indent=0,subs=""verbatim""] ---- my.servers[0]=dev.example.com my.servers[1]=another.example.com ---- TIP: Properties that use the `[index]` notation can be bound to Java `List` or `Set` objects using Spring Boot's `Binder` class. For more details see the ""`<>`"" section below. WARNING: YAML files cannot be loaded by using the `@PropertySource` or `@TestPropertySource` annotations. So, in the case that you need to load values that way, you need to use a properties file. [[features.external-config.yaml.directly-loading]] [[features.external-config.yaml.directly-loading]] ==== Directly Loading YAML Spring Framework provides two convenient classes that can be used to load YAML documents. The `YamlPropertiesFactoryBean` loads YAML as `Properties` and the `YamlMapFactoryBean` loads YAML as a `Map`. You can also use the `YamlPropertySourceLoader` class if you want to load YAML as a Spring `PropertySource`. [[features.external-config.random-values]] === Configuring Random Values The `RandomValuePropertySource` is useful for injecting random values (for example, into secrets or test cases). It can produce integers, longs, uuids, or strings, as shown in the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: secret: ""${random.value}"" number: ""${random.int}"" bignumber: ""${random.long}"" uuid: ""${random.uuid}"" number-less-than-ten: ""${random.int(10)}"" number-in-range: ""${random.int[1024,65536]}"" ---- The `+random.int*+` syntax is `OPEN value (,max) CLOSE` where the `OPEN,CLOSE` are any character and `value,max` are integers. If `max` is provided, then `value` is the minimum value and `max` is the maximum value (exclusive). [[features.external-config.system-environment]] === Configuring System Environment Properties Spring Boot supports setting a prefix for environment properties. This is useful if the system environment is shared by multiple Spring Boot applications with different configuration requirements. The prefix for system environment properties can be set directly on `SpringApplication`. For example, if you set the prefix to `input`, a property such as `remote.timeout` will also be resolved as `input.remote.timeout` in the system environment. [[features.external-config.typesafe-configuration-properties]] === Type-safe Configuration Properties Using the `@Value(""$\\{property}"")` annotation to inject configuration properties can sometimes be cumbersome, especially if you are working with multiple properties or your data is hierarchical in nature. Spring Boot provides an alternative method of working with properties that lets strongly typed beans govern and validate the configuration of your application. TIP: See also the <>. [[features.external-config.typesafe-configuration-properties.java-bean-binding]] ==== JavaBean properties binding It is possible to bind a bean declaring standard JavaBean properties as shown in the following example: include::code:MyProperties[] The preceding POJO defines the following properties: * `my.service.enabled`, with a value of `false` by default. * `my.service.remote-address`, with a type that can be coerced from `String`. * `my.service.security.username`, with a nested ""security"" object whose name is determined by the name of the property. In particular, the type is not used at all there and could have been `SecurityProperties`. * `my.service.security.password`. * `my.service.security.roles`, with a collection of `String` that defaults to `USER`. NOTE: The properties that map to `@ConfigurationProperties` classes available in Spring Boot, which are configured through properties files, YAML files, environment variables, and other mechanisms, are public API but the accessors (getters/setters) of the class itself are not meant to be used directly. [NOTE] ==== Such arrangement relies on a default empty constructor and getters and setters are usually mandatory, since binding is through standard Java Beans property descriptors, just like in Spring MVC. A setter may be omitted in the following cases: * Maps, as long as they are initialized, need a getter but not necessarily a setter, since they can be mutated by the binder. * Collections and arrays can be accessed either through an index (typically with YAML) or by using a single comma-separated value (properties). In the latter case, a setter is mandatory. We recommend to always add a setter for such types. If you initialize a collection, make sure it is not immutable (as in the preceding example). * If nested POJO properties are initialized (like the `Security` field in the preceding example), a setter is not required. If you want the binder to create the instance on the fly by using its default constructor, you need a setter. Some people use Project Lombok to add getters and setters automatically. Make sure that Lombok does not generate any particular constructor for such a type, as it is used automatically by the container to instantiate the object. Finally, only standard Java Bean properties are considered and binding on static properties is not supported. ==== [[features.external-config.typesafe-configuration-properties.constructor-binding]] ==== Constructor binding The example in the previous section can be rewritten in an immutable fashion as shown in the following example: include::code:MyProperties[] In this setup, the `@ConstructorBinding` annotation is used to indicate that constructor binding should be used. This means that the binder will expect to find a constructor with the parameters that you wish to have bound. If you are using Java 16 or later, constructor binding can be used with records. In this case, unless your record has multiple constructors, there is no need to use `@ConstructorBinding`. Nested members of a `@ConstructorBinding` class (such as `Security` in the example above) will also be bound through their constructor. Default values can be specified using `@DefaultValue` and the same conversion service will be applied to coerce the `String` value to the target type of a missing property. By default, if no properties are bound to `Security`, the `MyProperties` instance will contain a `null` value for `security`. If you wish you return a non-null instance of `Security` even when no properties are bound to it, you can use an empty `@DefaultValue` annotation to do so: include::code:nonnull/MyProperties[tag=*] NOTE: To use constructor binding the class must be enabled using `@EnableConfigurationProperties` or configuration property scanning. You cannot use constructor binding with beans that are created by the regular Spring mechanisms (for example `@Component` beans, beans created by using `@Bean` methods or beans loaded by using `@Import`) TIP: If you have more than one constructor for your class you can also use `@ConstructorBinding` directly on the constructor that should be bound. NOTE: The use of `java.util.Optional` with `@ConfigurationProperties` is not recommended as it is primarily intended for use as a return type. As such, it is not well-suited to configuration property injection. For consistency with properties of other types, if you do declare an `Optional` property and it has no value, `null` rather than an empty `Optional` will be bound. [[features.external-config.typesafe-configuration-properties.enabling-annotated-types]] ==== Enabling @ConfigurationProperties-annotated types Spring Boot provides infrastructure to bind `@ConfigurationProperties` types and register them as beans. You can either enable configuration properties on a class-by-class basis or enable configuration property scanning that works in a similar manner to component scanning. Sometimes, classes annotated with `@ConfigurationProperties` might not be suitable for scanning, for example, if you're developing your own auto-configuration or you want to enable them conditionally. In these cases, specify the list of types to process using the `@EnableConfigurationProperties` annotation. This can be done on any `@Configuration` class, as shown in the following example: include::code:MyConfiguration[] To use configuration property scanning, add the `@ConfigurationPropertiesScan` annotation to your application. Typically, it is added to the main application class that is annotated with `@SpringBootApplication` but it can be added to any `@Configuration` class. By default, scanning will occur from the package of the class that declares the annotation. If you want to define specific packages to scan, you can do so as shown in the following example: include::code:MyApplication[] [NOTE] ==== When the `@ConfigurationProperties` bean is registered using configuration property scanning or through `@EnableConfigurationProperties`, the bean has a conventional name: `-`, where `` is the environment key prefix specified in the `@ConfigurationProperties` annotation and `` is the fully qualified name of the bean. If the annotation does not provide any prefix, only the fully qualified name of the bean is used. The bean name in the example above is `com.example.app-com.example.app.SomeProperties`. ==== We recommend that `@ConfigurationProperties` only deal with the environment and, in particular, does not inject other beans from the context. For corner cases, setter injection can be used or any of the `*Aware` interfaces provided by the framework (such as `EnvironmentAware` if you need access to the `Environment`). If you still want to inject other beans using the constructor, the configuration properties bean must be annotated with `@Component` and use JavaBean-based property binding. [[features.external-config.typesafe-configuration-properties.using-annotated-types]] ==== Using @ConfigurationProperties-annotated types This style of configuration works particularly well with the `SpringApplication` external YAML configuration, as shown in the following example: [source,yaml,indent=0,subs=""verbatim""] ---- my: service: remote-address: 192.168.1.1 security: username: ""admin"" roles: - ""USER"" - ""ADMIN"" ---- To work with `@ConfigurationProperties` beans, you can inject them in the same way as any other bean, as shown in the following example: include::code:MyService[] TIP: Using `@ConfigurationProperties` also lets you generate metadata files that can be used by IDEs to offer auto-completion for your own keys. See the <> for details. [[features.external-config.typesafe-configuration-properties.third-party-configuration]] ==== Third-party Configuration As well as using `@ConfigurationProperties` to annotate a class, you can also use it on public `@Bean` methods. Doing so can be particularly useful when you want to bind properties to third-party components that are outside of your control. To configure a bean from the `Environment` properties, add `@ConfigurationProperties` to its bean registration, as shown in the following example: include::code:ThirdPartyConfiguration[] Any JavaBean property defined with the `another` prefix is mapped onto that `AnotherComponent` bean in manner similar to the preceding `SomeProperties` example. [[features.external-config.typesafe-configuration-properties.relaxed-binding]] ==== Relaxed Binding Spring Boot uses some relaxed rules for binding `Environment` properties to `@ConfigurationProperties` beans, so there does not need to be an exact match between the `Environment` property name and the bean property name. Common examples where this is useful include dash-separated environment properties (for example, `context-path` binds to `contextPath`), and capitalized environment properties (for example, `PORT` binds to `port`). As an example, consider the following `@ConfigurationProperties` class: include::code:MyPersonProperties[] With the preceding code, the following properties names can all be used: .relaxed binding [cols=""1,4""] |=== | Property | Note | `my.main-project.person.first-name` | Kebab case, which is recommended for use in `.properties` and `.yml` files. | `my.main-project.person.firstName` | Standard camel case syntax. | `my.main-project.person.first_name` | Underscore notation, which is an alternative format for use in `.properties` and `.yml` files. | `MY_MAINPROJECT_PERSON_FIRSTNAME` | Upper case format, which is recommended when using system environment variables. |=== NOTE: The `prefix` value for the annotation _must_ be in kebab case (lowercase and separated by `-`, such as `my.main-project.person`). .relaxed binding rules per property source [cols=""2,4,4""] |=== | Property Source | Simple | List | Properties Files | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values | YAML Files | Camel case, kebab case, or underscore notation | Standard YAML list syntax or comma-separated values | Environment Variables | Upper case format with underscore as the delimiter (see <>). | Numeric values surrounded by underscores (see <>) | System properties | Camel case, kebab case, or underscore notation | Standard list syntax using `[ ]` or comma-separated values |=== TIP: We recommend that, when possible, properties are stored in lower-case kebab format, such as `my.person.first-name=Rod`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.maps]] ===== Binding Maps When binding to `Map` properties you may need to use a special bracket notation so that the original `key` value is preserved. If the key is not surrounded by `[]`, any characters that are not alpha-numeric, `-` or `.` are removed. For example, consider binding the following properties to a `Map`: [source,properties,indent=0,subs=""verbatim"",role=""primary""] .Properties ---- my.map.[/key1]=value1 my.map.[/key2]=value2 my.map./key3=value3 ---- [source,yaml,indent=0,subs=""verbatim"",role=""secondary""] .Yaml ---- my: map: ""[/key1]"": ""value1"" ""[/key2]"": ""value2"" ""/key3"": ""value3"" ---- NOTE: For YAML files, the brackets need to be surrounded by quotes for the keys to be parsed properly. The properties above will bind to a `Map` with `/key1`, `/key2` and `key3` as the keys in the map. The slash has been removed from `key3` because it was not surrounded by square brackets. You may also occasionally need to use the bracket notation if your `key` contains a `.` and you are binding to non-scalar value. For example, binding `a.b=c` to `Map` will return a Map with the entry `{""a""={""b""=""c""}}` whereas `[a.b]=c` will return a Map with the entry `{""a.b""=""c""}`. [[features.external-config.typesafe-configuration-properties.relaxed-binding.environment-variables]] ===== Binding from Environment Variables Most operating systems impose strict rules around the names that can be used for environment variables. For example, Linux shell variables can contain only letters (`a` to `z` or `A` to `Z`), numbers (`0` to `9`) or the underscore character (`_`). By convention, Unix shell variables will also have their names in UPPERCASE. Spring Boot's relaxed binding rules are, as much as possible, designed to be compatible with these naming restrictions. To convert a property name in the canonical-form to an environment variable name you can follow these rules: * Replace dots (`.`) with underscores (`_`). * Remove any dashes (`-`). * Convert to uppercase. For example, the configuration property `spring.main.log-startup-info` would be an environment variable named `SPRING_MAIN_LOGSTARTUPINFO`. Environment variables can also be used when binding to object lists. To bind to a `List`, the element number should be surrounded with underscores in the variable name. For example, the configuration property `my.service[0].other` would use an environment variable named `MY_SERVICE_0_OTHER`. [[features.external-config.typesafe-configuration-properties.merging-complex-types]] ==== Merging Complex Types When lists are configured in more than one place, overriding works by replacing the entire list. For example, assume a `MyPojo` object with `name` and `description` attributes that are `null` by default. The following example exposes a list of `MyPojo` objects from `MyProperties`: include::code:list/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- If the `dev` profile is not active, `MyProperties.list` contains one `MyPojo` entry, as previously defined. If the `dev` profile is enabled, however, the `list` _still_ contains only one entry (with a name of `my another name` and a description of `null`). This configuration _does not_ add a second `MyPojo` instance to the list, and it does not merge the items. When a `List` is specified in multiple profiles, the one with the highest priority (and only that one) is used. Consider the following example: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: list: - name: ""my name"" description: ""my description"" - name: ""another name"" description: ""another description"" --- spring: config: activate: on-profile: ""dev"" my: list: - name: ""my another name"" ---- In the preceding example, if the `dev` profile is active, `MyProperties.list` contains _one_ `MyPojo` entry (with a name of `my another name` and a description of `null`). For YAML, both comma-separated lists and YAML lists can be used for completely overriding the contents of the list. For `Map` properties, you can bind with property values drawn from multiple sources. However, for the same property in multiple sources, the one with the highest priority is used. The following example exposes a `Map` from `MyProperties`: include::code:map/MyProperties[] Consider the following configuration: [source,yaml,indent=0,subs=""verbatim"",configblocks] ---- my: map: key1: name: ""my name 1"" description: ""my description 1"" --- spring: config: activate: on-profile: ""dev"" my: map: key1: name: ""dev name 1"" key2: name: ""dev name 2"" description: ""dev description 2"" ---- If the `dev` profile is not active, `MyProperties.map` contains one entry with key `key1` (with a name of `my name 1` and a description of `my description 1`). If the `dev` profile is enabled, however, `map` contains two entries with keys `key1` (with a name of `dev name 1` and a description of `my description 1`) and `key2` (with a name of `dev name 2` and a description of `dev description 2`). NOTE: The preceding merging rules apply to properties from all property sources, and not just files. [[features.external-config.typesafe-configuration-properties.conversion]] ==== Properties Conversion Spring Boot attempts to coerce the external application properties to the right type when it binds to the `@ConfigurationProperties` beans. If you need custom type conversion, you can provide a `ConversionService` bean (with a bean named `conversionService`) or custom property editors (through a `CustomEditorConfigurer` bean) or custom `Converters` (with bean definitions annotated as `@ConfigurationPropertiesBinding`). NOTE: As this bean is requested very early during the application lifecycle, make sure to limit the dependencies that your `ConversionService` is using. Typically, any dependency that you require may not be fully initialized at creation time. You may want to rename your custom `ConversionService` if it is not required for configuration keys coercion and only rely on custom converters qualified with `@ConfigurationPropertiesBinding`. [[features.external-config.typesafe-configuration-properties.conversion.durations]] ===== Converting Durations Spring Boot has dedicated support for expressing durations. If you expose a `java.time.Duration` property, the following formats in application properties are available: * A regular `long` representation (using milliseconds as the default unit unless a `@DurationUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Duration.html#parse-java.lang.CharSequence-[used by `java.time.Duration`] * A more readable format where the value and the unit are coupled (`10s` means 10 seconds) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a session timeout of 30 seconds, `30`, `PT30S` and `30s` are all equivalent. A read timeout of 500ms can be specified in any of the following form: `500`, `PT0.5S` and `500ms`. You can also use any of the supported units. These are: * `ns` for nanoseconds * `us` for microseconds * `ms` for milliseconds * `s` for seconds * `m` for minutes * `h` for hours * `d` for days The default unit is milliseconds and can be overridden using `@DurationUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DurationUnit`) if it is not milliseconds. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.conversion.periods]] ===== Converting periods In addition to durations, Spring Boot can also work with `java.time.Period` type. The following formats can be used in application properties: * An regular `int` representation (using days as the default unit unless a `@PeriodUnit` has been specified) * The standard ISO-8601 format {java-api}/java/time/Period.html#parse-java.lang.CharSequence-[used by `java.time.Period`] * A simpler format where the value and the unit pairs are coupled (`1y3d` means 1 year and 3 days) The following units are supported with the simple format: * `y` for years * `m` for months * `w` for weeks * `d` for days NOTE: The `java.time.Period` type never actually stores the number of weeks, it is a shortcut that means ""`7 days`"". [[features.external-config.typesafe-configuration-properties.conversion.data-sizes]] ===== Converting Data Sizes Spring Framework has a `DataSize` value type that expresses a size in bytes. If you expose a `DataSize` property, the following formats in application properties are available: * A regular `long` representation (using bytes as the default unit unless a `@DataSizeUnit` has been specified) * A more readable format where the value and the unit are coupled (`10MB` means 10 megabytes) Consider the following example: include::code:javabeanbinding/MyProperties[] To specify a buffer size of 10 megabytes, `10` and `10MB` are equivalent. A size threshold of 256 bytes can be specified as `256` or `256B`. You can also use any of the supported units. These are: * `B` for bytes * `KB` for kilobytes * `MB` for megabytes * `GB` for gigabytes * `TB` for terabytes The default unit is bytes and can be overridden using `@DataSizeUnit` as illustrated in the sample above. If you prefer to use constructor binding, the same properties can be exposed, as shown in the following example: include::code:constructorbinding/MyProperties[] TIP: If you are upgrading a `Long` property, make sure to define the unit (using `@DataSizeUnit`) if it is not bytes. Doing so gives a transparent upgrade path while supporting a much richer format. [[features.external-config.typesafe-configuration-properties.validation]] ==== @ConfigurationProperties Validation Spring Boot attempts to validate `@ConfigurationProperties` classes whenever they are annotated with Spring's `@Validated` annotation. You can use JSR-303 `javax.validation` constraint annotations directly on your configuration class. To do so, ensure that a compliant JSR-303 implementation is on your classpath and then add constraint annotations to your fields, as shown in the following example: include::code:MyProperties[] TIP: You can also trigger validation by annotating the `@Bean` method that creates the configuration properties with `@Validated`. To ensure that validation is always triggered for nested properties, even when no properties are found, the associated field must be annotated with `@Valid`. The following example builds on the preceding `MyProperties` example: include::code:nested/MyProperties[] You can also add a custom Spring `Validator` by creating a bean definition called `configurationPropertiesValidator`. The `@Bean` method should be declared `static`. The configuration properties validator is created very early in the application's lifecycle, and declaring the `@Bean` method as static lets the bean be created without having to instantiate the `@Configuration` class. Doing so avoids any problems that may be caused by early instantiation. TIP: The `spring-boot-actuator` module includes an endpoint that exposes all `@ConfigurationProperties` beans. Point your web browser to `/actuator/configprops` or use the equivalent JMX endpoint. See the ""<>"" section for details. [[features.external-config.typesafe-configuration-properties.vs-value-annotation]] ==== @ConfigurationProperties vs. @Value The `@Value` annotation is a core container feature, and it does not provide the same features as type-safe configuration properties. The following table summarizes the features that are supported by `@ConfigurationProperties` and `@Value`: [cols=""4,2,2""] |=== | Feature |`@ConfigurationProperties` |`@Value` | <> | Yes | Limited (see <>) | <> | Yes | No | `SpEL` evaluation | No | Yes |=== [[features.external-config.typesafe-configuration-properties.vs-value-annotation.note]] NOTE: If you do want to use `@Value`, we recommend that you refer to property names using their canonical form (kebab-case using only lowercase letters). This will allow Spring Boot to use the same logic as it does when relaxed binding `@ConfigurationProperties`. For example, `@Value(""{demo.item-price}"")` will pick up `demo.item-price` and `demo.itemPrice` forms from the `application.properties` file, as well as `DEMO_ITEMPRICE` from the system environment. If you used `@Value(""{demo.itemPrice}"")` instead, `demo.item-price` and `DEMO_ITEMPRICE` would not be considered. If you define a set of configuration keys for your own components, we recommend you group them in a POJO annotated with `@ConfigurationProperties`. Doing so will provide you with structured, type-safe object that you can inject into your own beans. `SpEL` expressions from <> are not processed at time of parsing these files and populating the environment. However, it is possible to write a `SpEL` expression in `@Value`. If the value of a property from an application property file is a `SpEL` expression, it will be evaluated when consumed through `@Value`. ",12216,False,2154.066149916866,median "/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #define FBGEMM_EXPORTS #include ""fbgemm/QuantUtilsAvx2.h"" #include #include //for std::min/std::max #include //for nearbyint #include //for numeric_limits #include ""./MaskAvx2.h"" #include ""fbgemm/Fbgemm.h"" //for ReQuantizeOutput namespace fbgemm { using namespace std; //////////////////////////////////////////////////////////////////////////////// // Utility functions template void QuantizeAvx2( const float* src, T* dst, int len, const TensorQuantizationParams& qparams) { #if defined(__AVX2__) && (defined(__FMA__) || defined(_MSC_VER)) constexpr int VLEN = 8; constexpr float min_val = std::numeric_limits::min(); constexpr float max_val = std::numeric_limits::max(); std::size_t i = 0; float inverse_scale = 1.f / qparams.scale; __m256 inverse_scale_v = _mm256_set1_ps(inverse_scale); __m256i shuffle_mask_v = _mm256_set_epi8( 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x08, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x08, 0x04, 0x00); __m256i permute_mask_v = _mm256_set_epi32(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00); for (; i < len / VLEN * VLEN; i += VLEN) { __m256 src_v = _mm256_loadu_ps(src + i); __m256 transformed_v = _mm256_fmadd_ps( src_v, inverse_scale_v, _mm256_set1_ps(qparams.zero_point)); __m256 clipped_v = _mm256_min_ps( _mm256_max_ps(transformed_v, _mm256_set1_ps(min_val)), _mm256_set1_ps(max_val)); __m256i rounded_v = _mm256_cvtps_epi32(clipped_v); // An instruction sequence to save 8 32-bit integers as 8 8-bit integers rounded_v = _mm256_shuffle_epi8(rounded_v, shuffle_mask_v); rounded_v = _mm256_permutevar8x32_epi32(rounded_v, permute_mask_v); _mm_storel_epi64( reinterpret_cast<__m128i*>(dst + i), _mm256_castsi256_si128(rounded_v)); } // Handle remainder using mask instructions so that // the main loop and remainder loop have the same behavior int rem = len - i; if (rem > 0) { __m256i mask_v = _mm256_load_si256(reinterpret_cast( internal::avx2_ps_or_epi32_masks[rem])); __m128i store_mask_v = _mm_load_si128( reinterpret_cast(internal::sse_epi8_masks[rem])); __m256 src_v = _mm256_maskload_ps(src + i, mask_v); __m256 transformed_v = _mm256_fmadd_ps( src_v, inverse_scale_v, _mm256_set1_ps(qparams.zero_point)); __m256 clipped_v = _mm256_min_ps( _mm256_max_ps(transformed_v, _mm256_set1_ps(min_val)), _mm256_set1_ps(max_val)); __m256i rounded_v = _mm256_cvtps_epi32(clipped_v); // An instruction sequence to save ""rem"" number of 32-bit integers // as ""rem"" number of 8-bit integers rounded_v = _mm256_shuffle_epi8(rounded_v, shuffle_mask_v); rounded_v = _mm256_permutevar8x32_epi32(rounded_v, permute_mask_v); _mm_maskmoveu_si128( _mm256_castsi256_si128(rounded_v), store_mask_v, reinterpret_cast(dst + i)); } #endif } // Instantiate QuantizeAvx2 for known datatypes template void QuantizeAvx2( const float* src, uint8_t* dst, int len, const TensorQuantizationParams& qparams); template void QuantizeAvx2( const float* src, int8_t* dst, int len, const TensorQuantizationParams& qparams); void FindMinMax(const float* a, float* min, float* max, int len) { if (len <= 0) { *min = 0.0f; *max = 0.0f; return; } float temp_min = *a, temp_max = *a; int i = 0; #ifdef __AVX__ __m256 min_v = _mm256_set1_ps(*a), max_v = _mm256_set1_ps(*a); constexpr int VLEN = 8; if (len >= VLEN) { for (; i < len / VLEN * VLEN; i += VLEN) { min_v = _mm256_min_ps(min_v, _mm256_loadu_ps(a + i)); max_v = _mm256_max_ps(max_v, _mm256_loadu_ps(a + i)); } float min_buf[VLEN], max_buf[VLEN]; _mm256_storeu_ps(min_buf, min_v); _mm256_storeu_ps(max_buf, max_v); for (int j = 0; j < VLEN; ++j) { temp_min = std::min(temp_min, min_buf[j]); temp_max = std::max(temp_max, max_buf[j]); } } #endif for (; i < len; i++) { temp_min = std::min(temp_min, a[i]); temp_max = std::max(temp_max, a[i]); } *min = temp_min; *max = temp_max; } //////////////////////////////////////////////////////////////////////////////// // Requantization (with floats) #ifdef __AVX2__ void RequantizeAvx2( const int32_t* src, uint8_t* dst, int len, const RequantizationParams& params) { DoNothing<> doNothingObj{}; int32_t Bq_zero_point[] = {0}; ReQuantizeOutput requantizeObj( doNothingObj, ¶ms.real_multiplier, params.target_qparams.zero_point, 0, // Aq_zero_point Bq_zero_point, // Bq_zero_point nullptr, // row_offsets nullptr, // col_offsets nullptr, // bias len); // ncol requantizeObj.f(dst, src, {0, 1, 0, len}, 0, 0); } void RequantizeFixedPointAvx2( const int32_t* src, uint8_t* dst, int len, const RequantizationParams& params) { constexpr int VLEN = 8; __m256i b = _mm256_set1_epi32(params.multiplier); // AVX2 doesn't support arithmetic right shift. // As a work around, we convert 64-bit multiplied results to uint64_t by // adding 0x8000000000000000ULL, logical right shift, and subtract by // (0x8000000000000000ULL >> right_shift). __m256i pre_shift_nudge = _mm256_set1_epi64x( (1ll << (params.right_shift - 1)) + 0x8000000000000000ULL); __m256i post_shift_nudge = _mm256_set1_epi64x( params.target_qparams.zero_point - (0x8000000000000000ULL >> params.right_shift)); __m256i min_v = _mm256_set1_epi32(numeric_limits::min()); __m256i max_v = _mm256_set1_epi32(numeric_limits::max()); __m256i shuffle_mask_v = _mm256_set_epi8( 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x08, 0x04, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x08, 0x04, 0x00); __m256i permute_mask_v = _mm256_set_epi32(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00); int i = 0; for (; i < len / VLEN * VLEN; i += VLEN) { __m256i a_v = _mm256_loadu_si256((const __m256i*)(src + i)); // a = a0 | a1 | a2 | a3 | a4 | a5 | a6 | a7 // b = b0 | b1 | b3 | b3 | b4 | b5 | b6 | b7 __m256i a_even_v = a_v; __m256i a_odd_v = _mm256_srli_si256(a_v, 4); __m256i ab_even_v = _mm256_mul_epi32(a_even_v, b); __m256i ab_odd_v = _mm256_mul_epi32(a_odd_v, b); __m256i even_rounded_v = _mm256_add_epi64(ab_even_v, pre_shift_nudge); __m256i odd_rounded_v = _mm256_add_epi64(ab_odd_v, pre_shift_nudge); __m256i even_result_v = _mm256_add_epi64( _mm256_srli_epi64(even_rounded_v, params.right_shift), post_shift_nudge); __m256i odd_result_v = _mm256_add_epi64( _mm256_srli_epi64(odd_rounded_v, params.right_shift), post_shift_nudge); odd_result_v = _mm256_slli_si256(odd_result_v, 4); // even_result_v has numbers we want in its even 32-bit SIMD lanes, and // odd_result_v has numbers we want in its odd 32-bit SIMD lanes. // Use blend to combine them. __m256i result_v = _mm256_blend_epi32(even_result_v, odd_result_v, 0xaa); __m256i clipped_v = _mm256_max_epi32(min_v, _mm256_min_epi32(max_v, result_v)); clipped_v = _mm256_shuffle_epi8(clipped_v, shuffle_mask_v); clipped_v = _mm256_permutevar8x32_epi32(clipped_v, permute_mask_v); #if defined(_M_X64) *(int64_t*)(dst + i) = _mm256_extract_epi64(clipped_v, 0); #else *(int32_t*)(dst + i) = _mm256_extract_epi32(clipped_v, 0); #endif } #if defined(_M_X64) for (; i < len; ++i) { int64_t ab_64 = static_cast(src[i]) * static_cast(params.multiplier); int64_t nudge = 1ll << std::max(0, params.right_shift - 1); int64_t quantized_down = params.target_qparams.zero_point + ((ab_64 + nudge) >> params.right_shift); dst[i] = std::min(std::max(quantized_down, 0l), 255l); } #else for (; i < len; ++i) { int32_t ab_64 = static_cast(src[i]) * static_cast(params.multiplier); int32_t nudge = 1ll << std::max(0, params.right_shift - 1); int32_t quantized_down = params.target_qparams.zero_point + ((ab_64 + nudge) >> params.right_shift); dst[i] = std::min(std::max(quantized_down, 0l), 255l); } #endif } #endif template < bool A_SYMMETRIC, bool B_SYMMETRIC, QuantizationGranularity Q_GRAN, bool HAS_BIAS, bool FUSE_RELU, typename BIAS_TYPE> void requantizeOutputProcessingAvx2( uint8_t* out, const int32_t* inp, const block_type_t& block, int ld_out, int ld_in, const requantizationParams_t& r) { // Adoption of implementation at QNNPACK/src/requantization/fp32-sse2.c // using AVX2 instructions int quant_param_idx = 0; if (Q_GRAN == QuantizationGranularity::GROUP) { int ncol_per_group = r.ncols / r.groups; int g = block.col_start / ncol_per_group; quant_param_idx = g; } __m256 multiplier_v = _mm256_set1_ps(r.C_multiplier[quant_param_idx]); // Broadcasted reciprocal of act_times_w_scale __m256 act_times_w_rcp_v; if (!(Q_GRAN == QuantizationGranularity::OUT_CHANNEL)) { if (is_same::value) { act_times_w_rcp_v = _mm256_set1_ps(1.0 / r.act_times_w_scale[quant_param_idx]); } } __m256i min_v = _mm256_set1_epi8(static_cast(0)); __m256i max_v = _mm256_set1_epi8(static_cast(255)); assert( (A_SYMMETRIC == (r.A_zero_point == 0)) && ""A_SYMMETRIC == true if and only if A_zero_point == 0""); assert( (B_SYMMETRIC == ((Q_GRAN == QuantizationGranularity::TENSOR && r.B_zero_point[0] == 0) || r.row_offsets == nullptr)) && ""B_SYMMETRIC == true if and only if B_zero_point == 0 "" ""or r.row_offsets == nullptr""); assert( (HAS_BIAS == (r.bias != nullptr)) && ""HAS_BIAS == true if and only if bias != nullptr""); __m256i A_zero_point_v = _mm256_set1_epi32(r.A_zero_point); __m256i C_zero_point_epi16_v = _mm256_set1_epi16(r.C_zero_point); __m256i C_zero_point_epi8_v = _mm256_set1_epi8(r.C_zero_point); __m256i permute_mask_v = _mm256_set_epi32(0x07, 0x03, 0x06, 0x02, 0x05, 0x01, 0x04, 0x00); constexpr int VLEN = 8; for (int i = block.row_start; i < block.row_start + block.row_size; ++i) { // Scale row_offset with Bq_zero_point int32_t row_offset = 0; if (B_SYMMETRIC) { row_offset = 0; } else if ( Q_GRAN == QuantizationGranularity::TENSOR || Q_GRAN == QuantizationGranularity::GROUP) { row_offset = r.row_offsets[i - block.row_start] * r.B_zero_point[quant_param_idx]; } else { assert( Q_GRAN == QuantizationGranularity::OUT_CHANNEL && ""unknown quantization granularity""); } __m256i row_offset_v = _mm256_set1_epi32(row_offset); int j = block.col_start; for (; j < block.col_start + (block.col_size / (VLEN * 4) * (VLEN * 4)); j += (VLEN * 4)) { __m256i x_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start))); __m256i y_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start) + 1 * VLEN)); __m256i z_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start) + 2 * VLEN)); __m256i w_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start) + 3 * VLEN)); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256( reinterpret_cast(r.col_offsets + j))); x_v = _mm256_sub_epi32(x_v, col_off_v); col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256( reinterpret_cast(r.col_offsets + j + VLEN))); y_v = _mm256_sub_epi32(y_v, col_off_v); col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256(reinterpret_cast( r.col_offsets + j + 2 * VLEN))); z_v = _mm256_sub_epi32(z_v, col_off_v); col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256(reinterpret_cast( r.col_offsets + j + 3 * VLEN))); w_v = _mm256_sub_epi32(w_v, col_off_v); } if (!B_SYMMETRIC) { if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256( reinterpret_cast(r.B_zero_point + j))); } x_v = _mm256_sub_epi32(x_v, row_offset_v); if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256( reinterpret_cast(r.B_zero_point + j + VLEN))); } y_v = _mm256_sub_epi32(y_v, row_offset_v); if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256(reinterpret_cast( r.B_zero_point + j + 2 * VLEN))); } z_v = _mm256_sub_epi32(z_v, row_offset_v); if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256(reinterpret_cast( r.B_zero_point + j + 3 * VLEN))); } w_v = _mm256_sub_epi32(w_v, row_offset_v); } __m256 xf_v, yf_v, zf_v, wf_v; if (HAS_BIAS) { if (is_same::value) { __m256 x_bias_v, y_bias_v, z_bias_v, w_bias_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_bias_v = _mm256_div_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 0 * VLEN)), _mm256_loadu_ps(r.act_times_w_scale + j + 0 * VLEN)); y_bias_v = _mm256_div_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 1 * VLEN)), _mm256_loadu_ps(r.act_times_w_scale + j + 1 * VLEN)); z_bias_v = _mm256_div_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 2 * VLEN)), _mm256_loadu_ps(r.act_times_w_scale + j + 2 * VLEN)); w_bias_v = _mm256_div_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 3 * VLEN)), _mm256_loadu_ps(r.act_times_w_scale + j + 3 * VLEN)); } else { x_bias_v = _mm256_mul_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 0 * VLEN)), act_times_w_rcp_v); y_bias_v = _mm256_mul_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 1 * VLEN)), act_times_w_rcp_v); z_bias_v = _mm256_mul_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 2 * VLEN)), act_times_w_rcp_v); w_bias_v = _mm256_mul_ps( _mm256_loadu_ps( reinterpret_cast(r.bias + j + 3 * VLEN)), act_times_w_rcp_v); } xf_v = _mm256_add_ps(_mm256_cvtepi32_ps(x_v), x_bias_v); yf_v = _mm256_add_ps(_mm256_cvtepi32_ps(y_v), y_bias_v); zf_v = _mm256_add_ps(_mm256_cvtepi32_ps(z_v), z_bias_v); wf_v = _mm256_add_ps(_mm256_cvtepi32_ps(w_v), w_bias_v); } else { x_v = _mm256_add_epi32( x_v, _mm256_loadu_si256( reinterpret_cast(r.bias + j + 0 * VLEN))); y_v = _mm256_add_epi32( y_v, _mm256_loadu_si256( reinterpret_cast(r.bias + j + 1 * VLEN))); z_v = _mm256_add_epi32( z_v, _mm256_loadu_si256( reinterpret_cast(r.bias + j + 2 * VLEN))); w_v = _mm256_add_epi32( w_v, _mm256_loadu_si256( reinterpret_cast(r.bias + j + 3 * VLEN))); xf_v = _mm256_cvtepi32_ps(x_v); yf_v = _mm256_cvtepi32_ps(y_v); zf_v = _mm256_cvtepi32_ps(z_v); wf_v = _mm256_cvtepi32_ps(w_v); } } else { xf_v = _mm256_cvtepi32_ps(x_v); yf_v = _mm256_cvtepi32_ps(y_v); zf_v = _mm256_cvtepi32_ps(z_v); wf_v = _mm256_cvtepi32_ps(w_v); } /* * Convert int32_t input to FP32 and multiply by FP32 scale. * Both operations involve statistically unbiased roundings (with * default MXCSR rounding mode): * - Large int32_t values can't be exactly represented as FP32. * CVTDQ2PS instruction on x86 would round it according to nearest * FP32 value with ties to even (assuming default MXCSR rounding * mode). * - Product of two FP32 values is generally not exactly * representation as an FP32 value, and will be rounded to nearest * FP32 value with ties to even with default MXCSR rounding mode. */ __m256 x_scaled_v, y_scaled_v, z_scaled_v, w_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps(xf_v, _mm256_loadu_ps(r.C_multiplier + j + 0 * VLEN)); y_scaled_v = _mm256_mul_ps(yf_v, _mm256_loadu_ps(r.C_multiplier + j + 1 * VLEN)); z_scaled_v = _mm256_mul_ps(zf_v, _mm256_loadu_ps(r.C_multiplier + j + 2 * VLEN)); w_scaled_v = _mm256_mul_ps(wf_v, _mm256_loadu_ps(r.C_multiplier + j + 3 * VLEN)); } else { x_scaled_v = _mm256_mul_ps(xf_v, multiplier_v); y_scaled_v = _mm256_mul_ps(yf_v, multiplier_v); z_scaled_v = _mm256_mul_ps(zf_v, multiplier_v); w_scaled_v = _mm256_mul_ps(wf_v, multiplier_v); } /* * Convert scaled FP32 result to int32_t using CVTPS2DQ instruction. * CVTPS2DQ instruction rounds result according to nearest FP32 value * with ties to even (assuming default MXCSR rounding mode). However, * when conversion overflows, it produces INT32_MIN as a result. For * large positive inputs the result of conversion can become negative, * which affects the final requantization result. Note that on x86 * SSE2 we have e.g. int32_t(float(INT32_MAX)) == INT32_MIN! This * happens because float(INT32_MAX) rounds to 2**31, which overflows * int32_t when it is converted back to integer. * * Thankfully, we can prove that overflow never happens in this * requantization scheme. The largest positive input is INT32_MAX * (2**31 - 1), which turns into 2**31 when converted to float. The * largest scale value is 0x1.FFFFFEp-1. When multiplied together, the * result is 2147483520 (compare to INT32_MAX = 2147483647), which * fits into int32_t without overflow. */ __m256i x_rounded_v = _mm256_cvtps_epi32(x_scaled_v); __m256i y_rounded_v = _mm256_cvtps_epi32(y_scaled_v); __m256i z_rounded_v = _mm256_cvtps_epi32(z_scaled_v); __m256i w_rounded_v = _mm256_cvtps_epi32(w_scaled_v); /* * Standard final sequence on x86 AVX2: * - Pack to int16_t and saturate * - Add zero point * - Pack to uint8_t and saturate * - Clamp between qmin and qmax */ __m256i xy_packed_v = _mm256_adds_epi16( _mm256_packs_epi32(x_rounded_v, y_rounded_v), C_zero_point_epi16_v); __m256i zw_packed_v = _mm256_adds_epi16( _mm256_packs_epi32(z_rounded_v, w_rounded_v), C_zero_point_epi16_v); __m256i xyzw_packed_v = _mm256_packus_epi16(xy_packed_v, zw_packed_v); __m256i xyzw_clamped_v = _mm256_max_epu8( FUSE_RELU ? C_zero_point_epi8_v : min_v, _mm256_min_epu8(xyzw_packed_v, max_v)); /* * xyzw_clamped_v has results in the following layout so we need to * permute: x0-3 y0-3 z0-3 w0-3 x4-7 y4-7 z4-7 w4-7 */ xyzw_clamped_v = _mm256_permutevar8x32_epi32(xyzw_clamped_v, permute_mask_v); /* * 4x CVTDQ2PS * 4x MULPS * 4x CVTPS2DQ * 2x PACKSSDW * 1x PACKUSWB * 2x PADDW * 1x PMAXUB * 1x PMINUB * 1x PERMD * --------------------- * 20 instructions total */ _mm256_storeu_si256( reinterpret_cast<__m256i*>(out + i * ld_out + j), xyzw_clamped_v); } // j loop vectorized and unrolled 4x for (; j < block.col_start + (block.col_size / VLEN * VLEN); j += VLEN) { __m256i x_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start))); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256( reinterpret_cast(r.col_offsets + j))); x_v = _mm256_sub_epi32(x_v, col_off_v); } if (!B_SYMMETRIC) { if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256( reinterpret_cast(r.B_zero_point + j))); } x_v = _mm256_sub_epi32(x_v, row_offset_v); } __m256 xf_v; if (HAS_BIAS) { if (is_same::value) { __m256 x_bias_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_bias_v = _mm256_div_ps( _mm256_loadu_ps(reinterpret_cast(r.bias + j)), _mm256_loadu_ps(r.act_times_w_scale + j)); } else { x_bias_v = _mm256_mul_ps( _mm256_loadu_ps(reinterpret_cast(r.bias + j)), act_times_w_rcp_v); } xf_v = _mm256_add_ps(_mm256_cvtepi32_ps(x_v), x_bias_v); } else { x_v = _mm256_add_epi32( x_v, _mm256_loadu_si256(reinterpret_cast(r.bias + j))); xf_v = _mm256_cvtepi32_ps(x_v); } } else { xf_v = _mm256_cvtepi32_ps(x_v); } __m256 x_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps(xf_v, _mm256_loadu_ps(r.C_multiplier + j)); } else { x_scaled_v = _mm256_mul_ps(xf_v, multiplier_v); } __m256i x_rounded_v = _mm256_cvtps_epi32(x_scaled_v); __m256i x_packed_v = _mm256_adds_epi16( _mm256_packs_epi32(x_rounded_v, _mm256_setzero_si256()), C_zero_point_epi16_v); x_packed_v = _mm256_packus_epi16(x_packed_v, _mm256_setzero_si256()); __m256i x_clamped_v = _mm256_max_epu8( FUSE_RELU ? C_zero_point_epi8_v : min_v, _mm256_min_epu8(x_packed_v, max_v)); /* * x_clamped_v has results in the following layout so we need to * permute: x0-3 garbage0-11 x4-7 garbage12-23 */ x_clamped_v = _mm256_permutevar8x32_epi32(x_clamped_v, permute_mask_v); /* * 1x CVTDQ2PS * 1x MULPS * 1x CVTPS2DQ * 1x PACKSSDW * 1x PACKUSWB * 1x PADDW * 1x PMAXUB * 1x PMINUB * 1x PERMD * --------------------- * 9 instructions total */ _mm_storel_epi64( reinterpret_cast<__m128i*>(out + i * ld_out + j), _mm256_castsi256_si128(x_clamped_v)); } // j loop vectorized int remainder = block.col_start + block.col_size - j; if (remainder > 0) { __m256i mask_v = _mm256_load_si256(reinterpret_cast( internal::avx2_ps_or_epi32_masks[remainder])); __m256i x_v = _mm256_maskload_epi32( inp + (i - block.row_start) * ld_in + (j - block.col_start), mask_v); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_maskload_epi32(r.col_offsets + j, mask_v)); x_v = _mm256_sub_epi32(x_v, col_off_v); } if (!B_SYMMETRIC) { if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_maskload_epi32(r.B_zero_point + j, mask_v)); } x_v = _mm256_sub_epi32(x_v, row_offset_v); } __m256 xf_v; if (HAS_BIAS) { if (is_same::value) { __m256 x_bias_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_bias_v = _mm256_div_ps( _mm256_maskload_ps( reinterpret_cast(r.bias + j), mask_v), _mm256_maskload_ps(r.act_times_w_scale + j, mask_v)); } else { x_bias_v = _mm256_mul_ps( _mm256_maskload_ps( reinterpret_cast(r.bias + j), mask_v), act_times_w_rcp_v); } xf_v = _mm256_add_ps(_mm256_cvtepi32_ps(x_v), x_bias_v); } else { x_v = _mm256_add_epi32( x_v, _mm256_maskload_epi32( reinterpret_cast(r.bias + j), mask_v)); xf_v = _mm256_cvtepi32_ps(x_v); } } else { xf_v = _mm256_cvtepi32_ps(x_v); } __m256 x_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps(xf_v, _mm256_maskload_ps(r.C_multiplier + j, mask_v)); } else { x_scaled_v = _mm256_mul_ps(xf_v, multiplier_v); } __m256i x_rounded_v = _mm256_cvtps_epi32(x_scaled_v); __m256i x_packed_v = _mm256_adds_epi16( _mm256_packs_epi32(x_rounded_v, _mm256_setzero_si256()), C_zero_point_epi16_v); x_packed_v = _mm256_packus_epi16(x_packed_v, _mm256_setzero_si256()); __m256i x_clamped_v = _mm256_max_epu8( FUSE_RELU ? C_zero_point_epi8_v : min_v, _mm256_min_epu8(x_packed_v, max_v)); /* * x_clamped_v has results in the following layout so we need to * permute: x0-3 garbage0-11 x4-7 garbage12-23 */ x_clamped_v = _mm256_permutevar8x32_epi32(x_clamped_v, permute_mask_v); /* * 1x CVTDQ2PS * 1x MULPS * 1x CVTPS2DQ * 1x PACKSSDW * 1x PACKUSWB * 1x PADDW * 1x PMAXUB * 1x PMINUB * 1x PERMD * --------------------- * 9 instructions total */ alignas(64) uint8_t x_clamped_buffer[32]; _mm256_store_si256( reinterpret_cast<__m256i*>(x_clamped_buffer), x_clamped_v); for (int k = 0; k < remainder; ++k) { out[i * ld_out + j + k] = x_clamped_buffer[k]; } } // j loop remainder } // i loop } template < bool A_SYMMETRIC, bool B_SYMMETRIC, QuantizationGranularity Q_GRAN, bool HAS_BIAS, bool FUSE_RELU> void requantizeForFloatAvx2( float* out, const int32_t* inp, const block_type_t& block, int ld_out, int ld_in, const requantizationForFloatParams_t& r) { // Adoption of implementation at QNNPACK/src/requantization/fp32-sse2.c // using AVX2 instructions int quant_param_idx = 0; if (Q_GRAN == QuantizationGranularity::GROUP) { int ncol_per_group = r.ncols / r.groups; int g = block.col_start / ncol_per_group; quant_param_idx = g; } __m256 multiplier_v = _mm256_set1_ps(r.A_scale * r.B_scale[quant_param_idx]); assert( (A_SYMMETRIC == (r.A_zero_point == 0)) && ""A_SYMMETRIC == true if and only if A_zero_point == 0""); assert( (B_SYMMETRIC == ((Q_GRAN == QuantizationGranularity::TENSOR && r.B_zero_point[0] == 0) || r.row_offsets == nullptr)) && ""B_SYMMETRIC == true if and only if B_zero_point == 0 "" ""or r.row_offsets == nullptr""); assert( (HAS_BIAS == (r.bias != nullptr)) && ""HAS_BIAS == true if and only if bias != nullptr""); __m256i A_zero_point_v = _mm256_set1_epi32(r.A_zero_point); constexpr int VLEN = 8; for (int i = block.row_start; i < block.row_start + block.row_size; ++i) { // Scale row_offset with Bq_zero_point int32_t row_offset = 0; if (B_SYMMETRIC) { row_offset = 0; } else if ( Q_GRAN == QuantizationGranularity::TENSOR || Q_GRAN == QuantizationGranularity::GROUP) { row_offset = r.row_offsets[i - block.row_start] * r.B_zero_point[quant_param_idx]; } else { assert( Q_GRAN == QuantizationGranularity::OUT_CHANNEL && ""unknown quantization granularity""); } __m256i row_offset_v = _mm256_set1_epi32(row_offset); int j = block.col_start; for (; j < block.col_start + (block.col_size / VLEN * VLEN); j += VLEN) { __m256i x_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start))); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256( reinterpret_cast(r.col_offsets + j))); x_v = _mm256_sub_epi32(x_v, col_off_v); } if (!B_SYMMETRIC) { if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_loadu_si256( reinterpret_cast(r.B_zero_point + j))); } x_v = _mm256_sub_epi32(x_v, row_offset_v); } __m256 x_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps( _mm256_cvtepi32_ps(x_v), _mm256_mul_ps( _mm256_set1_ps(r.A_scale), _mm256_loadu_ps(r.B_scale + j))); } else { x_scaled_v = _mm256_mul_ps(_mm256_cvtepi32_ps(x_v), multiplier_v); } if (HAS_BIAS) { x_scaled_v = _mm256_add_ps(x_scaled_v, _mm256_loadu_ps(r.bias + j)); } if (FUSE_RELU) { x_scaled_v = _mm256_max_ps(_mm256_setzero_ps(), x_scaled_v); } _mm256_storeu_ps(out + i * ld_out + j, x_scaled_v); } // j loop vectorized int remainder = block.col_start + block.col_size - j; if (remainder > 0) { __m256i mask_v = _mm256_load_si256(reinterpret_cast( internal::avx2_ps_or_epi32_masks[remainder])); __m256i x_v = _mm256_maskload_epi32( inp + (i - block.row_start) * ld_in + (j - block.col_start), mask_v); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_maskload_epi32(r.col_offsets + j, mask_v)); x_v = _mm256_sub_epi32(x_v, col_off_v); } if (!B_SYMMETRIC) { if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { row_offset_v = _mm256_mullo_epi32( _mm256_set1_epi32(r.row_offsets[i - block.row_start]), _mm256_maskload_epi32(r.B_zero_point + j, mask_v)); } x_v = _mm256_sub_epi32(x_v, row_offset_v); } __m256 x_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps( _mm256_cvtepi32_ps(x_v), _mm256_mul_ps( _mm256_set1_ps(r.A_scale), _mm256_maskload_ps(r.B_scale + j, mask_v))); } else { x_scaled_v = _mm256_mul_ps(_mm256_cvtepi32_ps(x_v), multiplier_v); } if (HAS_BIAS) { x_scaled_v = _mm256_add_ps(x_scaled_v, _mm256_maskload_ps(r.bias + j, mask_v)); } if (FUSE_RELU) { x_scaled_v = _mm256_max_ps(_mm256_setzero_ps(), x_scaled_v); } _mm256_maskstore_ps(out + i * ld_out + j, mask_v, x_scaled_v); } // j loop remainder } // i loop } template < bool A_SYMMETRIC, bool B_SYMMETRIC, QuantizationGranularity Q_GRAN, bool HAS_BIAS, bool FUSE_RELU, int C_PER_G, typename BIAS_TYPE> void requantizeOutputProcessingGConvAvx2( uint8_t* out, const int32_t* inp, const block_type_t& block, int ld_out, int ld_in, const requantizationParams_t& r) { // Adoption of implementation at QNNPACK/src/requantization/fp32-sse2.c // using AVX2 instructions int quant_param_idx = 0; if (Q_GRAN == QuantizationGranularity::GROUP) { int ncol_per_group = r.ncols / r.groups; int g = block.col_start / ncol_per_group; quant_param_idx = g; } __m256 multiplier_v = _mm256_set1_ps(r.C_multiplier[quant_param_idx]); // Broadcasted reciprocal of act_times_w_scale __m256 act_times_w_rcp_v; if (!(Q_GRAN == QuantizationGranularity::OUT_CHANNEL)) { if (is_same::value) { act_times_w_rcp_v = _mm256_set1_ps(1.0 / r.act_times_w_scale[quant_param_idx]); } } __m256i min_v = _mm256_set1_epi8(static_cast(0)); __m256i max_v = _mm256_set1_epi8(static_cast(255)); assert( (A_SYMMETRIC == (r.A_zero_point == 0)) && ""A_SYMMETRIC == true if and only if A_zero_point == 0""); assert( (B_SYMMETRIC == ((Q_GRAN == QuantizationGranularity::TENSOR && r.B_zero_point[0] == 0) || r.row_offsets == nullptr)) && ""B_SYMMETRIC == true if and only if B_zero_point == 0 "" ""or r.row_offsets == nullptr""); assert( (HAS_BIAS == (r.bias != nullptr)) && ""HAS_BIAS == true if and only if bias != nullptr""); __m256i A_zero_point_v = _mm256_set1_epi32(r.A_zero_point); __m256i C_zero_point_epi16_v = _mm256_set1_epi16(r.C_zero_point); __m256i C_zero_point_epi8_v = _mm256_set1_epi8(r.C_zero_point); __m256i permute_mask_v = _mm256_set_epi32(0x07, 0x03, 0x06, 0x02, 0x05, 0x01, 0x04, 0x00); constexpr int VLEN = 8; for (int i = block.row_start; i < block.row_start + block.row_size; ++i) { int j = block.col_start; for (; j < block.col_start + (block.col_size / VLEN * VLEN); j += VLEN) { __m256i x_v = _mm256_loadu_si256(reinterpret_cast( inp + (i - block.row_start) * ld_in + (j - block.col_start))); if (!A_SYMMETRIC) { __m256i col_off_v = _mm256_mullo_epi32( A_zero_point_v, _mm256_loadu_si256( reinterpret_cast(r.col_offsets + j))); x_v = _mm256_sub_epi32(x_v, col_off_v); } if (!B_SYMMETRIC) { __m256i row_offset_v; if (C_PER_G == 2) { // When C_PER_G == 2, we need to handle 4 groups at a time to fully // utilize 32B AVX2 vector register (C_PER_G * 4 * sizeof(int32_t) == // 32B) // Load row_offsets for 4 groups and broadcast by 2 times. row_offset_v = _mm256_castps_si256(_mm256_moveldup_ps(_mm256_permutevar8x32_ps( _mm256_castps128_ps256( _mm_loadu_ps(reinterpret_cast( r.row_offsets + (i - block.row_start) * 4))), permute_mask_v))); } // When C_PER_G == 4, we need to handle 2 groups at a time to fully // utilize 32B AVX2 vector register (C_PER_G * 2 * sizeof(int32_t) == // 32B) // When C_PER_G == 8, we just need 1 group at a time on the other hand. // Groups 0 and 1 when C_PER_G == 4 // Group 0 when C_PER_G == 8 else if (C_PER_G == 4) { // Load row_offsets for 2 groups and broadcast by 4 times each because // we have 4 channels per group. // groups 0 and 1 row_offset_v = _mm256_insertf128_si256( _mm256_castsi128_si256( _mm_set1_epi32(r.row_offsets[(i - block.row_start) * 2 + 0])), _mm_set1_epi32(r.row_offsets[(i - block.row_start) * 2 + 1]), 1); } else if (C_PER_G == 8) { row_offset_v = _mm256_set1_epi32(r.row_offsets[(i - block.row_start)]); } else { assert(C_PER_G == 16); row_offset_v = _mm256_set1_epi32(r.row_offsets[(i - block.row_start)]); } __m256i B_zero_point_v = _mm256_set1_epi32(r.B_zero_point[0]); if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { B_zero_point_v = _mm256_loadu_si256( reinterpret_cast(r.B_zero_point + j)); } else if (Q_GRAN == QuantizationGranularity::GROUP) { if (C_PER_G == 2) { B_zero_point_v = _mm256_castps_si256(_mm256_moveldup_ps(_mm256_permutevar8x32_ps( _mm256_castps128_ps256( _mm_loadu_ps(reinterpret_cast( r.B_zero_point + quant_param_idx))), permute_mask_v))); } else if (C_PER_G == 4) { B_zero_point_v = _mm256_insertf128_si256( _mm256_castsi128_si256( _mm_set1_epi32(r.B_zero_point[quant_param_idx])), _mm_set1_epi32(r.B_zero_point[quant_param_idx + 1]), 1); } else if (C_PER_G == 8) { B_zero_point_v = _mm256_set1_epi32(r.B_zero_point[quant_param_idx]); } else { B_zero_point_v = _mm256_set1_epi32(r.B_zero_point[quant_param_idx]); } } row_offset_v = _mm256_mullo_epi32(row_offset_v, B_zero_point_v); x_v = _mm256_sub_epi32(x_v, row_offset_v); } __m256 xf_v; if (HAS_BIAS) { if (is_same::value) { __m256 x_bias_v = _mm256_loadu_ps(reinterpret_cast(r.bias + j)); if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_bias_v = _mm256_div_ps( x_bias_v, _mm256_loadu_ps(r.act_times_w_scale + j)); } else if (Q_GRAN == QuantizationGranularity::GROUP) { __m256 diviser_v; if (C_PER_G == 2) { diviser_v = _mm256_moveldup_ps(_mm256_permutevar8x32_ps( _mm256_castps128_ps256( _mm_loadu_ps(r.act_times_w_scale + quant_param_idx)), permute_mask_v)); } else if (C_PER_G == 4) { diviser_v = _mm256_insertf128_ps( _mm256_castps128_ps256( _mm_set1_ps(r.act_times_w_scale[quant_param_idx + 0])), _mm_set1_ps(r.act_times_w_scale[quant_param_idx + 1]), 1); } else if (C_PER_G == 8) { diviser_v = _mm256_set1_ps(r.act_times_w_scale[quant_param_idx]); } else { assert(C_PER_G == 16); diviser_v = _mm256_set1_ps(r.act_times_w_scale[quant_param_idx]); } x_bias_v = _mm256_div_ps(x_bias_v, diviser_v); } else { x_bias_v = _mm256_mul_ps(x_bias_v, act_times_w_rcp_v); } xf_v = _mm256_add_ps(_mm256_cvtepi32_ps(x_v), x_bias_v); } else { x_v = _mm256_add_epi32( x_v, _mm256_loadu_si256(reinterpret_cast(r.bias + j))); xf_v = _mm256_cvtepi32_ps(x_v); } } else { xf_v = _mm256_cvtepi32_ps(x_v); } /* * Convert int32_t input to FP32 and multiply by FP32 scale. * Both operations involve statistically unbiased roundings (with * default MXCSR rounding mode): * - Large int32_t values can't be exactly represented as FP32. * CVTDQ2PS instruction on x86 would round it according to nearest * FP32 value with ties to even (assuming default MXCSR rounding * mode). * - Product of two FP32 values is generally not exactly * representation as an FP32 value, and will be rounded to nearest * FP32 value with ties to even with default MXCSR rounding mode. */ __m256 x_scaled_v; if (Q_GRAN == QuantizationGranularity::OUT_CHANNEL) { x_scaled_v = _mm256_mul_ps(xf_v, _mm256_loadu_ps(r.C_multiplier + j)); } else if (Q_GRAN == QuantizationGranularity::GROUP) { if (C_PER_G == 2) { multiplier_v = _mm256_moveldup_ps(_mm256_permutevar8x32_ps( _mm256_castps128_ps256( _mm_loadu_ps(r.C_multiplier + quant_param_idx)), permute_mask_v)); } else if (C_PER_G == 4) { multiplier_v = _mm256_insertf128_ps( _mm256_castps128_ps256( _mm_set1_ps(r.C_multiplier[quant_param_idx])), _mm_set1_ps(r.C_multiplier[quant_param_idx + 1]), 1); } else if (C_PER_G == 8) { multiplier_v = _mm256_set1_ps(r.C_multiplier[quant_param_idx]); } else { multiplier_v = _mm256_set1_ps(r.C_multiplier[quant_param_idx]); } x_scaled_v = _mm256_mul_ps(xf_v, multiplier_v); } else { x_scaled_v = _mm256_mul_ps(xf_v, multiplier_v); } /* * Convert scaled FP32 result to int32_t using CVTPS2DQ instruction. * CVTPS2DQ instruction rounds result according to nearest FP32 value * with ties to even (assuming default MXCSR rounding mode). However, * when conversion overflows, it produces INT32_MIN as a result. For * large positive inputs the result of conversion can become negative, * which affects the final requantization result. Note that on x86 * SSE2 we have e.g. int32_t(float(INT32_MAX)) == INT32_MIN! This * happens because float(INT32_MAX) rounds to 2**31, which overflows * int32_t when it is converted back to integer. * * Thankfully, we can prove that overflow never happens in this * requantization scheme. The largest positive input is INT32_MAX * (2**31 - 1), which turns into 2**31 when converted to float. The * largest scale value is 0x1.FFFFFEp-1. When multiplied together, the * result is 2147483520 (compare to INT32_MAX = 2147483647), which * fits into int32_t without overflow. */ __m256i x_rounded_v = _mm256_cvtps_epi32(x_scaled_v); /* * Standard final sequence on x86 AVX2: * - Pack to int16_t and saturate * - Add zero point * - Pack to uint8_t and saturate * - Clamp between qmin and qmax */ __m256i x_packed_v = _mm256_adds_epi16( _mm256_packs_epi32(x_rounded_v, _mm256_setzero_si256()), C_zero_point_epi16_v); x_packed_v = _mm256_packus_epi16(x_packed_v, _mm256_setzero_si256()); __m256i x_clamped_v = _mm256_max_epu8( FUSE_RELU ? C_zero_point_epi8_v : min_v, _mm256_min_epu8(x_packed_v, max_v)); /* * x_clamped_v has results in the following layout so we need to * permute: x0-3 garbage0-11 x4-7 garbage12-23 */ x_clamped_v = _mm256_permutevar8x32_epi32(x_clamped_v, permute_mask_v); /* * 1x CVTDQ2PS * 1x MULPS * 1x CVTPS2DQ * 1x PACKSSDW * 1x PACKUSWB * 1x PADDW * 1x PMAXUB * 1x PMINUB * 1x PERMD * --------------------- * 9 instructions total */ _mm_storel_epi64( reinterpret_cast<__m128i*>(out + i * ld_out + j), _mm256_castsi256_si128(x_clamped_v)); } // j loop vectorized int remainder = block.col_start + block.col_size - j; assert(remainder == 0); } // i loop } #define INSTANTIATE_REQUANTIZE_BIAS_TYPE( \\ A_SYM, B_SYM, Q_GRAN, BIAS, RELU, BIAS_TYPE) \\ template void FBGEMM_API \\ requantizeOutputProcessingAvx2( \\ uint8_t * out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationParams_t& r); \\ template void requantizeOutputProcessingGConvAvx2< \\ A_SYM, \\ B_SYM, \\ Q_GRAN, \\ BIAS, \\ RELU, \\ 2, \\ BIAS_TYPE>( \\ uint8_t * out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationParams_t& r); \\ template void requantizeOutputProcessingGConvAvx2< \\ A_SYM, \\ B_SYM, \\ Q_GRAN, \\ BIAS, \\ RELU, \\ 4, \\ BIAS_TYPE>( \\ uint8_t * out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationParams_t& r); \\ template void requantizeOutputProcessingGConvAvx2< \\ A_SYM, \\ B_SYM, \\ Q_GRAN, \\ BIAS, \\ RELU, \\ 8, \\ BIAS_TYPE>( \\ uint8_t * out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationParams_t& r); \\ template void requantizeOutputProcessingGConvAvx2< \\ A_SYM, \\ B_SYM, \\ Q_GRAN, \\ BIAS, \\ RELU, \\ 16, \\ BIAS_TYPE>( \\ uint8_t * out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationParams_t& r); #define INSTANTIATE_REQUANTIZE(A_SYM, B_SYM, Q_GRAN, BIAS, RELU) \\ INSTANTIATE_REQUANTIZE_BIAS_TYPE(A_SYM, B_SYM, Q_GRAN, BIAS, RELU, float) \\ INSTANTIATE_REQUANTIZE_BIAS_TYPE(A_SYM, B_SYM, Q_GRAN, BIAS, RELU, int32_t) \\ template void requantizeForFloatAvx2( \\ float* out, \\ const int32_t* inp, \\ const block_type_t& block, \\ int ld_out, \\ int ld_in, \\ const requantizationForFloatParams_t& r); #define INSTANTIATE_A_SYM(B_SYM, Q_GRAN, BIAS, RELU) \\ INSTANTIATE_REQUANTIZE(true, B_SYM, Q_GRAN, BIAS, RELU) \\ INSTANTIATE_REQUANTIZE(false, B_SYM, Q_GRAN, BIAS, RELU) #define INSTANTIATE_B_SYM(Q_GRAN, BIAS, RELU) \\ INSTANTIATE_A_SYM(true, Q_GRAN, BIAS, RELU) \\ INSTANTIATE_A_SYM(false, Q_GRAN, BIAS, RELU) #define INSTANTIATE_Q_GRANS(BIAS, RELU) \\ INSTANTIATE_B_SYM(QuantizationGranularity::TENSOR, BIAS, RELU) \\ INSTANTIATE_B_SYM(QuantizationGranularity::GROUP, BIAS, RELU) \\ INSTANTIATE_B_SYM(QuantizationGranularity::OUT_CHANNEL, BIAS, RELU) #define INSTANTIATE_BIAS(RELU) \\ INSTANTIATE_Q_GRANS(true, RELU) \\ INSTANTIATE_Q_GRANS(false, RELU) INSTANTIATE_BIAS(true) INSTANTIATE_BIAS(false) #undef INSTANTIATE_A_SYM #undef INSTANTIATE_B_SYM #undef INSTANTIATE_Q_GRANS #undef INSTANTIATE_BIAS } // namespace fbgemm ",16159,True,3519.852602514907,median "= SAP S/4HANA OData Connector 2.1 Reference Support Category: https://www.mulesoft.com/legal/versioning-back-support-policy#anypoint-connectors[Premium] For software requirements and compatibility information, see the xref:release-notes::connector/sap-s4-hana-connector-release-notes-mule-4.adoc[SAP S/4HANA OData Connector Release Notes]. --- [[Config]] == Default Configuration === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required |Name | String | The name for this configuration. Connectors reference the configuration with this name. | | x | Connection a| * <> * <> | The connection types to provide to this configuration. | | x | Time Zone a| String | The timezone with which the Date objects returned from S/4Hana will be converted. | UTC | | Batch Buffer Size a| Number | Defines the maximum memory the connector will use to keep batch requests in memory. If more than that is consumed it will start to buffer the content on disk. | 512 | | Buffer Unit a| Enumeration, one of: ** BYTE ** KB ** MB ** GB | The unit in which batchBufferSize size is expressed. | KB | | Encoding a| String | | | | Name a| String | The identifier of this element used to reference it in other components | | x | Expiration Policy a| <> | Configures the minimum amount of time that a dynamic configuration instance can remain idle before the runtime considers it eligible for expiration. This does not mean that the platform expires the instance at the exact moment that it becomes eligible. The runtime purges the instances when it sees fit. | | |=== == Connection Types [[Config_BasicAuthentication]] === Basic Authentication Basic authentication is the simplest way of enforcing access controls because it does not require cookies, session identifiers, or login pages. Instead, it uses standard fields in the HTTP header, which removes the need for handshakes. This mechanism provides no confidentiality protection for the transmitted credentials. The credentials are merely encoded with Base64 in transit, but not encrypted or hashed in any way. ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Service base URL a| String | The base URL of the SAP S/4HANA service to access from the connector. All other endpoints are derived from this base URL. | | x | Username a| String | The account username with which to log into SAP S/4HANA. | | x | Password a| String | The account password with which to log into SAP S/4HANA. | | x | Discovery Service Enabled a| Boolean | Feature switch for service discovery. If disabled, the service discovery relative path is not applied. | `true` | | Service discovery relative path a| String | URL to use for automatic services discovery. | sap/opu/odata/IWFND/CATALOGSERVICE;v=0002/ServiceCollection | | Service directory a| String | Common HTTP directory for all SAP services. You can leave this parameter blank and specify the HTTP directory individually for every service in the unlisted services list. | | | Unlisted services a| Array of String | List of services to add to the list of discovered services. If the `Service directory` parameter is not specified, then the HTTP directory needs to be prepended before every service name in this list, in the following format: {directory}/{service-name}. | | | Default headers a| Array of <> | Default HTTP headers to include in the message. | | | Default query parameters a| Array of <> | Default query parameters to include in the request. | | | Proxy configuration a| <> | Proxy configuration for the connector. | | | TLS configuration a| <> | Protocol to use for communication. Valid values are `HTTP` and `HTTPS`. When using HTTPS the HTTP communication is secured using TLS or SSL. If HTTPS was configured as the protocol then you must configure at least the keystore in the `tls:context` child element of this `listener-config`. | `HTTP` | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | |=== [[Config_Oauth2ClientCredentialsAuthentication]] === OAuth 2.0 Client Credentials Authentication ==== Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Service base URL a| String | The base URL of the service on SAP S/4HANA to access from the connector. All other endpoints are derived from this base URL. | | x | Discovery Service Enabled a| Boolean | Feature switch for service discovery. If disabled, Service discovery relative path is not applied. | `true` | | Service discovery relative path a| String | URL that is used for automatic services discovery | `sap/opu/odata/IWFND/CATALOGSERVICE;v=0002/ServiceCollection` | | Service directory a| String | Common HTTP directory for all SAP services. You can leave this parameter blank and specify the HTTP directory individually for every service in the unlisted services list. | | | Unlisted services a| Array of String | List of services added to the list of discovered services. If the `Service directory` parameter is not specified then the HTTP directory needs to be prepended before every service name in this list, in the following format: {directory}/{service-name}. | | | Default headers a| Array of <> | Default HTTP headers to include in the message. | | | Default query parameters a| Array of <> | Default Query parameters to include in the request. | | | Proxy configuration a| <> | Proxy configuration for the connector. | | | TLS configuration a| <> | Protocol to use for communication. Valid values are `HTTP` and `HTTPS`. When using HTTPS the HTTP communication is secured using TLS or SSL. If HTTPS was configured as the protocol then you must configure at least the keystore in the `tls:context` child element of this `listener-config`. | `HTTP` | | Reconnection a| <> | When the application is deployed, a connectivity test is performed on all connectors. If set to `true`, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Client Id a| String | The OAuth client ID as registered with the service provider. | | x | Client Secret a| String | The OAuth client secret as registered with the service provider. | | x | Token Url a| String | The service provider's token endpoint URL. | https://{host-name}/{oauth-service}/{generate-token-resource} | | Scopes a| String | The OAuth scopes requested during the dance. If not provided, it defaults to those in the annotation. | | | Object Store a| String | A reference to the object store used to store each resource owner ID's data. If not specified, Mule automatically provisions the default object store. | | |=== == Supported Operations * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> * <> [[BatchCreateEntity]] == Batch Create Entity `` This operation adds a create entity request into the batch. This is a dynamic operation that returns what the OData specification states will be returned by the operation. The result of the operation will be an empty JSON if this request was not processed by the server successfully. The result will be available only after executing the *Execute batch* operation. Accessing the result before the *Execute batch* operation is executed results in an error. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Streaming Strategy a| * <> * <> * non-repeatable-stream | Configure to use repeatable streams. | | | Batch ID a| String | Batch identifier | | x | Change set ID a| String | Change set identifier | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity a| Object | The entity to be affected in the SAP S/4HANA instance. This entity must be of the type defined in the type parameter. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters to include in the request. The custom query parameters specified here will overwrite the default query parameters specified in the configuration. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Any |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_CHANGE_SET_ID * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[BatchDeleteEntity]] == Batch Delete Entity `` Adds a delete entity request into the batch. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Batch ID a| String | Batch identifier | | x | Change set ID a| String | Change set identifier. | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity key a| Object | The object that identifies the entity sought, which may itself be an object. This is defined by the type of entity selected. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters to include in the request. The custom query parameters specified here will overwrite the default query parameters specified in the configuration. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_CHANGE_SET_ID * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[BatchExecuteFunction]] == Batch Execute Function `` This operation adds an execute function request (invoke request) to the batch. The result of the operation will be an empty JSON if this request was not processed by the server successfully. The result will be available only after executing the *Execute batch* operation. Accessing the result before the *Execute batch* operation is executed will cause an error. You are required to specify the change set identifier for the *Change set ID* parameter only if *Execute Batch Function* is executed using a POST HTTP method, otherwise do not specify the changet set identifier. The connector throws an exception: * If the change set identifier is not specified and the POST HTTP method is used * When the change set identifier is specified and the *Execute Batch Function* uses GET HTTP method === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Streaming Strategy a| * <> * <> * non-repeatable-stream | Configure to use repeatable streams. | | | Batch ID a| String | Batch identifier | | x | Change set ID a| String | Change set identifier | | | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Function Name a| String | The name of the function to execute. | | x | Input parameters a| Object | The parameters of the function wrapped into a single object. | | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters to include in the request. The custom query parameters specified here will overwrite the default query parameters specified in the configuration. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Any |=== === For Configurations * <> === Throws * S4HANA:BATCH_PROCESSING_ERROR * S4HANA:CONNECTIVITY * S4HANA:INVALID_FUNCTION_PARAMETER * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_CHANGE_SET_ID * S4HANA:NO_SUCH_FUNCTION * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[BatchGetEntity]] == Batch Get Entity `` Adds a query operation request with a defined key into the batch. This is a dynamic operation, returning whatever the OData specification states will be returned by the operation. Result of the operation will be an empty JSON if this request was not processed by the server successfully. The result will be available only after the Execute batch operation is executed. Accessing the result before the Execute batch operation is executed will lead to an error. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Streaming Strategy a| * <> * <> * non-repeatable-stream | Configure to use repeatable streams. | | | Batch ID a| String | Batch identifier | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Returned Fields a| String | Comma-separated list of selection clauses. Each selection clause may be a Property name, Navigation Property name, or the ""*"" character. The ""*"" syntax causes all Properties on an Entry to be included without traversing associations. Use forward slash ""/"" to select fields of expanded navigation properties. If no field is selected, then all fields are returned. | | | Expanded properties a| String | Comma-separated list of Navigation Properties. Additionally, each Navigation Property can be followed by a forward slash and another Navigation Property to enable identification of a multi-level relationship. Properties of the expanded navigation property will not be part of the payload unless selected. | | | Entity key a| Object | The object that identifies the entity sought, which may itself be an object. This is defined by the type of entity selected. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters to include in the request. The custom query parameters specified here will overwrite the default query parameters specified in the configuration. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Any |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[BatchQuery]] == Batch Query Entity `` Adds a query operation request into the batch, filtering the results by the parameters defined. If no filter is added, then all results will be listed. Result of the operation will be an empty JSON if this request was not processed by the server successfully. The result will be available only after the Execute batch operation is executed. Accessing the result before the Execute batch operation is executed will lead to an error. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Streaming Strategy a| * <> * <> * non-repeatable-stream | Configure to use repeatable streams. | | | Batch ID a| String | Batch identifier | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Returned Fields a| String | Comma-separated list of selection clauses. Each selection clause may be a Property name, Navigation Property name, or the ""*"" character. The ""*"" syntax causes all Properties on an Entry to be included without traversing associations. Use forward slash ""/"" to select fields of expanded navigation properties. If no field is selected, then all fields are returned. | | | Expanded properties a| String | Comma-separated list of Navigation Properties. Additionally each Navigation Property can be followed by a forward slash and another Navigation Property to enable identification of a multi-level relationship. Properties of expanded navigation property will not be part of the payload unless selected. | | | Filter a| String | The condition to filter the resulting list of entities. | | | Order by a| String | Allows information to be requested in either ascending or descending order by using the `asc` or `desc` suffixes. If `asc` or `desc` are not specified, then the resources will be ordered in ascending order. | `asc` | | Maximum returned elements a| Number | Limits the number of records to be retrieved by this query. | | | Skipped record amount a| Number | The number of records to skip before starting to return results. | `0` | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Any |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:RETRY_EXHAUSTED [[BatchUpdateEntity]] == Batch Update Entity `` Adds an update entity request into the batch. This operation works through a PATCH request. This means that any fields that are missing will not be updated. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Batch ID a| String | Batch identifier | | x | Change set ID a| String | Change set identifier | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity a| Object | The entity to be affected in the SAP S/4HANA instance. This entity must be of the type defined in the type parameter. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_CHANGE_SET_ID * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[CreateChangeSet]] == Create Change Set `` Creates a new change set in the batch and returns its identifier. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Batch ID a| String | Batch identifier | | x | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |String |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:RETRY_EXHAUSTED [[CreateEntity]] == Create Entity `` Executes a create operation within the connected SAP S/4HANA instance. This is a dynamic operation, returning whatever the OData specification states will be returned by the operation. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity a| Object | The entity to be affected in the SAP S/4HANA instance. This entity must be of the type defined in the type parameter. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| <> |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_ENTITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_ENTITY_KEY * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED [[DeleteEntity]] == Delete Entity `` Executes a delete operation within the connected SAP S/4HANA instance. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity key a| Object | The object that identifies the entity sought, which may itself be an object. This is defined by the type of entity selected. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_ENTITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_ENTITY_KEY * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED [[ExecuteBatch]] == Execute Batch `` Executes the batch and returns a summary containing results for all requests of the batch. After this operation is successfully executed, it will be possible to read a detailed result of each batch operation which was a part of this batch. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Service a| String | The SAP S/4HANA's service. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component. | | x | Batch ID a| String | Batch identifier | | x | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |<> |=== === For Configurations * <> === Throws * S4HANA:BATCH_PROCESSING_ERROR * S4HANA:CONNECTIVITY * S4HANA:NO_SUCH_BATCH_ID * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED [[ExecuteFunction]] == Execute Function `` Executes an OData-defined function in the SAP S/4HANA instance. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Function Name a| String | The name of the function to execute. | | x | Input parameters a| Object | The parameters of the function wrapped into a single object. | | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Any | Attributes Type a| <> |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_FUNCTION_PARAMETER * S4HANA:NO_SUCH_FUNCTION * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED [[GetEntity]] == Get Entity by Key `` Executes a retrieve operation on the SAP S/4HANA instance filtering the result by key. If no elements are found an error is thrown. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Returned Fields a| String | Comma-separated list of selection clauses. Each selection clause may be a Property name, Navigation Property name, or the ""*"" character. The ""*"" syntax causes all Properties on an Entry to be included without traversing associations. Use forward slash ""/"" to select fields of expanded navigation properties. If no field is selected, then all fields are returned. | | | Expanded properties a| String | Comma-separated list of Navigation Properties. Additionally each Navigation Property can be followed by a forward slash and another Navigation Property to enable identifying a multi-level relationship. Properties of expanded navigation property will not be part of the payload unless selected. | | | Entity key a| Object | The object that identifies the entity sought, which may itself be an object. This is defined by the type of entity selected. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Object | Attributes Type a| <> |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_ENTITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_ENTITY_FIELD * S4HANA:NO_SUCH_ENTITY_KEY * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_NAVIGATION_PROPERTY * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED [[InitiateBatch]] == Initiate Batch `` Prepares a new batch and returns its identifier. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |String |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:RETRY_EXHAUSTED [[Query]] == Query `` Executes a retrieve operation on the SAP S/4HANA instance filtering the results by the parameters defined. If no filter is added, then all results will be listed. This is a paginated operation. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Streaming Strategy a| * <> * <> * non-repeatable-iterable | Configure to use repeatable streams. | | | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Returned Fields a| String | Comma-separated list of selection clauses. Each selection clause may be a Property name, Navigation Property name, or the ""*"" character. The ""*"" syntax causes all Properties on an Entry to be included without traversing associations. Use forward slash ""/"" to select fields of expanded navigation properties. If no field is selected, then all fields are returned. | | | Expanded properties a| String | Comma-separated list of Navigation Properties. Additionally each Navigation Property can be followed by a forward slash and another Navigation Property to enable identifying a multi-level relationship. Properties of expanded navigation property will not be part of the payload unless selected. | | | Filter a| String | The condition to filter the resulting list of entities. | | | Order by a| String | Allows to request information in either ascending or descending order by using the ?asc? or ?desc? suffixes. If asc or desc not specified, then the resources will be ordered in ascending order. | | | Maximum returned elements a| Number | Limits the amount of records to be retrieved by this query. | | | Skipped record amount a| Number | The amount of records to skip before starting returning results. | 0 | | Page size a| Number | The size of the pages retrieved by the query. | 100 | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Target Variable a| String | The name of a variable to store the operation's output. | | | Target Value a| String | An expression to evaluate against the operation's output and store the expression outcome in the target variable. | #[payload] | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors. | | |=== === Output [%autowidth.spread] |=== |Type |Array of Object |=== === For Configurations * <> === Throws * S4HANA:INVALID_ENTITY * S4HANA:INVALID_FILTER * S4HANA:INVALID_KEY * S4HANA:INVALID_PAGE_SIZE * S4HANA:INVALID_SKIP_SIZE * S4HANA:INVALID_TOP_SIZE * S4HANA:NO_SUCH_ENTITY_FIELD * S4HANA:NO_SUCH_ENTITY_KEY * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_NAVIGATION_PROPERTY * S4HANA:NO_SUCH_SERVICE * S4HANA:NO_SUCH_SORTING_FIELD * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED [[Unauthorize]] == Unauthorize `` Deletes all the access token information of a given resource owner ID so that it's impossible to execute any operation for that user without repeating the authorization dance. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x |=== === For Configurations * <> [[UpdateEntity]] == Update Entity `` Executes an update operation within the connected SAP S/4HANA instance. This operation will work through PATCH requests. This means that any fields that are missing will not be updated. === Parameters [%header%autowidth.spread] |=== | Name | Type | Description | Default Value | Required | Configuration | String | The name of the configuration to use. | | x | Config Ref a| ConfigurationProvider | The name of the configuration to use to execute this component | | x | Service a| String | The type of service. This is defined from the services available in the SAP S/4HANA instance. | | x | Entity type a| String | The type of entity over which the operation is executed. This is defined from the types of entities available in the selected service. | | x | Entity a| Object | The entity to be affected in the SAP S/4HANA instance. This entity must be of the type defined in the type parameter. | #[payload] | | Custom headers a| Object | Custom headers to include in the request. The custom headers specified here will overwrite the default headers specified in the configuration. | | | Custom query parameters a| Object | Custom query parameters that the request will include. The ones specified here will overwrite the default ones specified in the config. | | | Reconnection Strategy a| * <> * <> | A retry strategy in case of connectivity errors | | |=== === For Configurations * <> === Throws * S4HANA:CONNECTIVITY * S4HANA:INVALID_ENTITY * S4HANA:INVALID_KEY * S4HANA:NO_SUCH_ENTITY_KEY * S4HANA:NO_SUCH_ENTITY_TYPE * S4HANA:NO_SUCH_SERVICE * S4HANA:RETRY_EXHAUSTED * S4HANA:SERVER_ERROR * S4HANA:TIMEOUT * S4HANA:UNAUTHORIZED == Types [[DefaultHeader]] === Default Header [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Key a| String | The key | | x | Value a| String | The value | | x |=== [[DefaultQueryParam]] === Default Query Param [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Key a| String | The key | | x | Value a| String | The value | | x |=== [[ProxyConfiguration]] === Proxy Configuration [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Host a| String | Host where the proxy requests is sent. | | x | Port a| Number | Port where the proxy requests is sent. | | x | Username a| String | The username to authenticate against the proxy. | | | Password a| String | The password to authenticate against the proxy. | | | Non Proxy Hosts a| Array of String | A list of hosts against which the proxy should not be used. | | | Ntlm Domain a| String | The domain to authenticate against the proxy. | | |=== [[Tls]] === TLS [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Enabled Protocols a| String | A comma-separated list of protocols enabled for this context. | | | Enabled Cipher Suites a| String | A comma-separated list of cipher suites enabled for this context. | | | Trust Store a| <> | | | | Key Store a| <> | | | | Revocation Check a| * <> * <> * <> | | | |=== [[TrustStore]] === Truststore [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Path a| String | The location (which will be resolved relative to the current classpath and file system, if possible) of the truststore. | | | Password a| String | The password used to protect the truststore. | | | Type a| String | The type of store used. | | | Algorithm a| String | The algorithm used by the truststore. | | | Insecure a| Boolean | If `true`, no certificate validations will be performed, rendering connections vulnerable to attacks. Use at your own risk. | | |=== [[KeyStore]] === Keystore [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Path a| String | The location (which will be resolved relative to the current classpath and file system, if possible) of the keystore. | | | Type a| String | The type of store used. | | | Alias a| String | When the keystore contains many private keys, this attribute indicates the alias of the key that should be used. If not defined, the first key in the file will be used by default. | | | Key Password a| String | The password used to protect the private key. | | | Password a| String | The password used to protect the keystore. | | | Algorithm a| String | The algorithm used by the keystore. | | |=== [[StandardRevocationCheck]] === Standard Revocation Check [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Only End Entities a| Boolean | Only verify the last element of the certificate chain. | | | Prefer Crls a| Boolean | Try CRL instead of OCSP first. | | | No Fallback a| Boolean | Do not use the secondary checking method (the one not selected before). | | | Soft Fail a| Boolean | Avoid verification failure when the revocation server can not be reached or is busy. | | |=== [[CustomOcspResponder]] === Custom OCSP Responder [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Url a| String | The URL of the OCSP responder. | | | Cert Alias a| String | Alias of the signing certificate for the OCSP response (must be in the truststore), if present. | | |=== [[CrlFile]] === CRL File [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Path a| String | The path to the CRL file. | | |=== [[Reconnection]] === Reconnection [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Fails Deployment a| Boolean | When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn't pass after exhausting the associated reconnection strategy. | | | Reconnection Strategy a| * <> * <> | The reconnection strategy to use. | | |=== [[Reconnect]] === Reconnect [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often in milliseconds to reconnect. | | | Blocking a| Boolean | If `false`, the reconnection strategy will run in a separate, non-blocking thread. | | | Count a| Number | How many reconnection attempts to make. | | |=== [[ReconnectForever]] === Reconnect Forever [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Frequency a| Number | How often in milliseconds to reconnect. | | | Blocking a| Boolean | If `false`, the reconnection strategy will run in a separate, non-blocking thread. | | |=== [[ExpirationPolicy]] === Expiration Policy [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Max Idle Time a| Number | A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it's considered eligible for expiration. | | | Time Unit a| Enumeration, one of: ** NANOSECONDS ** MICROSECONDS ** MILLISECONDS ** SECONDS ** MINUTES ** HOURS ** DAYS | A time unit that qualifies the maxIdleTime attribute | | |=== [[RepeatableInMemoryStream]] === Repeatable In Memory Stream [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Initial Buffer Size a| Number | The amount of memory that will be allocated to consume the stream and provide random access to it. If the stream contains more data than can be fit into this buffer, then the buffer expands according to the bufferSizeIncrement attribute, with an upper limit of maxInMemorySize. | | | Buffer Size Increment a| Number | This specifies how much the buffer size expands if it exceeds its initial size. Setting a value of zero or lower means that the buffer should not expand, meaning that a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised when the buffer gets full. | | | Max Buffer Size a| Number | The maximum amount of memory to use. If more than that is used then a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised. A value lower than or equal to zero means no limit. | | | Buffer Unit a| Enumeration, one of: ** BYTE ** KB ** MB ** GB | The unit in which all these attributes are expressed | | |=== [[RepeatableFileStoreStream]] === Repeatable File Store Stream [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | In Memory Size a| Number | Defines the maximum memory that the stream should use to keep data in memory. If more than that is consumed then it will start to buffer the content on disk. | | | Buffer Unit a| Enumeration, one of: ** BYTE ** KB ** MB ** GB | The unit in which maxInMemorySize is expressed | | |=== [[ResponseAttributes]] === Response Attributes [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Headers a| Object | | | | Status Code a| Number | | | |=== [[BulkOperationResult]] === Bulk Operation Result [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Id a| Any | | | | Items a| Array of <> | | | | Successful a| Boolean | | | |=== [[BulkItem]] === Bulk Item [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Exception a| Any | | | | Id a| Any | | | | Message a| String | | | | Payload a| Any | | | | Status Code a| String | | | | Successful a| Boolean | | | |=== [[RepeatableInMemoryIterable]] === Repeatable In Memory Iterable [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | Initial Buffer Size a| Number | The amount of instances that is initially be allowed to be kept in memory to consume the stream and provide random access to it. If the stream contains more data than can fit into this buffer, then the buffer expands according to the bufferSizeIncrement attribute, with an upper limit of maxInMemorySize.| 100 instances| | Buffer Size Increment a| Number | This is by how much the buffer size expands if it exceeds its initial size. Setting a value of zero or lower means that the buffer should not expand, meaning that a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised when the buffer gets full.| 100 instances| | Max Buffer Size a| Number | The maximum amount of memory to use. If more than that is used then a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised. A value lower than or equal to zero means no limit. | | |=== [[RepeatableFileStoreIterable]] === Repeatable File Store Iterable [%header%autowidth.spread] |=== | Field | Type | Description | Default Value | Required | In Memory Objects a| Number | The maximum amount of instances that will be kept in memory. If more than that is required, then it will start to buffer the content on disk. | | | Buffer Unit a| Enumeration, one of: ** BYTE ** KB ** MB ** GB | The unit in which maxInMemorySize is expressed | | |=== == See Also https://help.mulesoft.com[MuleSoft Help Center] ",12267,True,2957.501187719779,median "= Mod Manager - User Guide :site-section: UserGuide :toc: :toclevels: 5 :toc-title: :toc-placement: preamble :sectnums: :imagesDir: images :stylesDir: stylesheets :xrefstyle: full :experimental: ifdef::env-github[] :tip-caption: :bulb: :note-caption: :information_source: endif::[] :repoURL: https://github.com/AY1920S2-CS2103T-F10-4/main By: `Team AY1920S2-CS2103T-F10-4` Since: `Jan 2020` Licence: `MIT` == Introduction // tag::introduction[] Welcome to *Mod Manager*! *Mod Manager* is a desktop application that assists students in *managing tasks, schedules, and contacts for their modules* in a semester. More importantly, *Mod Manager* is *optimized for those who prefer to work with a Command Line Interface* (CLI) while still having the benefits of a Graphical User Interface (GUI). If you can type fast, Mod Manager can get your management of tasks, schedules and contacts done faster than traditional GUI apps. Interested? Jump to the <> to get started. Enjoy! // end::introduction[] == About // tag::about[] This user guide helps you to master how to use Mod Manager. It explains the features and commands supported by Mod Manager, with examples to illustrate how the application works. // end::about[] Note the following symbols used in this document: .Symbols used in this User Guide [%autowidth] |===== ^|*Symbol* |*Meaning* ^|kbd:[Enter] | The enter button on the keyboard. ^|image:InfoIcon.png[width=""40""] | Information that you need to know. |===== == Quick Start === Installing Mod Manager Here are the steps to get you started with using Mod Manager: . Ensure you have Java `11` or above installed in your Computer. . Download the latest `ModManager.jar` link:{repoURL}/releases[here]. . Copy the file to the folder you want to use as the home folder for your Mod Manager. . Double-click the file to start the application. The GUI should appear in a few seconds. + .GUI for Mod Manager image::Gui.png[width=""800""] + . Type the command in the command box and press kbd:[Enter] to execute it. + e.g. typing *`help`* and pressing kbd:[Enter] will open the help window. + Here are some example commands that you can try: * `*cmd* all` : lists all available commands in our Mod Manager. * `*mod* add /code CS3233 /desc Competitive Programming` : adds the module CS3233 to the module list. * `*class* add /code CS3233 /type LEC /at TUESDAY 14:00 16:00 /venue i3-Aud` : adds a lecture class to the module CS3233. * `*task* add /code CS3233 /desc Complete Pset 10 /on 30/04/2020 /at 23:59`: adds a task to the module CS3233. * `*facil* add /name Steven Halim /email stevenha@comp.nus.edu.sg /code CS3233`: adds a facilitator to the module CS3233. If you are rushing to write an email to your lecturer, you can refer to this conveniently. * `*cal* view /week this` : views your schedules for the current week. You should see the CS3233 lecture group that you added above. * `*exit*` : exits the application. . Refer to <> for details of each command. === Using Mod Manager This section offers an overview of Mod Manager's layout so that you can find what you need easily. There are two main areas in Mod Manager: . A __result display box__ and __command box__ at the bottom of the screen. . A __main viewing area__ that occupies most of the screen. The *_command box_* is the area for you to enter commands. The result of each command will be shown in the *_result display box_*, immediately above the command box. .The result display box and command box image::commandAndResultBox.png[] The *_main viewing area_* shows all the contents for one of the four tabs at any point in time. The four tabs are **Module**, **Facilitators**, **Tasks** and **Calendar** * **Module** tab contains information about lessons, tasks and facilitators for a particular module. It also shows the list of modules you currently have. + .**Module** tab image::Ui.png[] * **Facilitators** tab contains information about all the facilitators you currently have. + .**Facilitators** tab image::Facil.png[] * **Tasks** tab contains information about all the tasks you currently have. Completed tasks are shown in green, whereas the rest are uncompleted tasks. + .**Tasks** tab image::Task.png[] * **Calendar** tab shows tasks and lessons in a week. + .**Calendar** tab image::Calendar.png[] [[Features]] == Features This section describes the main features of Mod Manager and how to use them. The features are grouped into six categories: . <> features . <> feature . <> feature . <> feature . <> feature . <> feature Additionally, the <> features section offers a preview of what you can expect in **Mod Manager v2.0**. ==== *Command Format* This document uses the following notation to describe command formats: * Words in `UPPER_CASE` are the parameters to be supplied by the user. + e.g. In the command format `*mod* add /code MOD_CODE`, `MOD_CODE` is a parameter which can be used as `*mod* add /code CS2103T`. * Items in square brackets are optional. + e.g `/code MOD_CODE [/desc DESCRIPTION]` can be used as `/code CS2103T /desc Software Engineering` or as `/code CS2103T`. * Items with `...`​ after them can be used multiple times, including 0 times. + e.g. `[MORE_DESCRIPTIONS]...` can be used as `{nbsp}` (i.e. 0 times), `Software` (once), `Software Engineering` (twice), `SWE AI Algorithms` etc. * Parameters can be used in any order unless otherwise specified. e.g. if the command specifies `/code MOD_CODE /desc DESCRIPTION`, `/desc DESCRIPTION /code MOD_CODE` is also acceptable. ==== === General features This section is about some general operations in Mod Manager. ==== Viewing help : `*help*` You can open the help window that displays a link to our user guide. Format: * `*help*` //tag::undo[] ==== Undoing previous commands : `*undo*` During a usage session with Mod Manager, you may make mistakes while adding/editing/deleting an entry. It would be nice if you can reverse the effect in a neat way. The `*undo*` command is here to give you that convenience. All of your commands are recorded, so with `*undo*`, you can reverse the effect of previous add/edit/delete commands one by one, starting with the most previous command. As of the current version, you can only use `*undo*` to reverse the effects of add/edit/delete commands. Format: * `*undo*` Example: Let's say you are editing a task of module ST2334 with ID number 401. It is the task highlighted with the red box. Don't bother with the command if you haven't read the section on <> yet. This is just a quick demonstration. .Editing a task as per usual image::undo-1.png[] After that, you realize you didn't mean to make this change, so you type `*undo*`. .Before `undo` image::undo-2.png[] After you press kbd:[Enter], the effect will be reverted and the change is undone. The task is back to before your editing. .After `undo` image::undo-3.png[] //end::undo[] ==== Redoing previously undone commands : `*redo*` We understand that you can change your mind right after undo-ing, so we give have the `*redo*` command to assist you. You can reverse the effect of the most previous `*undo*` command with `*redo*`. Format: * `*redo*` Example: Let's say you have just used `*undo*` to a task edit command. .Before `redo` image::redo-1.png[] After you press kbd:[Enter], the previously undone effect will come back. .After `redo` image::redo-2.png[] ==== Listing commands : `*cmd*` *Listing all commands*: Sometimes, you might forget what commands are available in Mod Manager. To give you a quick reminder of all the command groups provided, we have the `*cmd* all` command. The command groups available in Mod Manager are the words in bold you have seen throughout this document. These include: `*facil*, *mod*, *task*, ...` Format: * `*cmd* all` Example: Type `*cmd* all` into the Command Box. .Before executing `*cmd* all` image::cmdAll1.png[] Press kbd:[Enter] and you will be able to see all the command groups listed. .After executing `*cmd* all` image::cmdAll2.png[] *Listing commands for a specific feature*: Seeing all the command groups might not be sufficient to remind you of the specific command formats. That's why there is `*cmd* group`. It will list all valid command formats of a group for you, so you can get back to work. You can use `*cmd* all` first to get a glimpse of all the command groups we have. Format: * `*cmd* group COMMAND_GROUP` Example: `*cmd* group class` You want to know what commands there are in command group `class`. Type `*cmd* group class` into the Command Box. .Before executing `*cmd* group class` image::cmdGroup1.png[] Hit kbd:[Enter] and you will see the commands associated in the command group `class`. Since there are quite a few commands there, you might want to scroll down through the list. .After executing `*cmd* group class` image::cmdGroup2.png[] ==== Navigating through past commands with up/down key During a Mod Manager usage session, you may want to repeat some commands but you feel quite lazy to type again. Therefore, we bring you the ability to use the `up/down` arrow key on your keyboard to find the past command that you need. Example: Let's say you want to use command ""mod view CS2103T"" again, but you have already executed 5 more commands ever since. Just simply press the `up` key on your keyboard a few times and you will see it in the command box. If you have been pressing `up` and accidentally bypassed the command you need, just press `down` until you see it again. For this feature, you can try out very quickly. Just open Mod Manager, type in a few commands and press `up/down` like you mean it. That's the best and only way to truly feel the convenience of Mod Manager. //tag::clear[] ==== Clearing all entries : `*clear*` You can clear all entries from Mod Manager. All the lists of modules, classes, facilitators and tasks that you have will be cleared. Please use this command cautiously, you cannot `undo` after it! Format: * `*clear*` Example: Suppose your semester has ended and you do not want to see any information related to those modules you have taken in that semester anymore. You can type `*clear*` as shown below. .Before `*clear*` image::BeforeClear.png[] After pressing kbd:[Enter], Mod Manager is empty. All the entries you have are cleared. .After `*clear*` image::AfterClear.png[] //end::clear[] //tag::exit[] ==== Exiting the program : `*exit*` You can exit the program. Upon closing the application, the Mod Manager data will be saved automatically in your hard disk. Format: * `*exit*` //end::exit[] === Module feature : `*mod*` // tag::module[] // tag::mod[] The commands in this section carry out operations on the module list in Mod Manager. Executing these commands will bring you to the Module tab. // end::mod[] ==== Adding a module You can add a module to Mod Manager. Format: * `*mod* add /code MOD_CODE [/desc DESCRIPTION]` Command properties: **** * MOD_CODE should be 2-3 letters followed by 4 numbers (and a possible trailing letter) with no spaces. * DESCRIPTION should not exceed 64 characters. **** Examples: You can add a module to the module list. To add a module with the module code `CS2103T` and description `Software Engineering`, you can type the following command: `*mod* add /code CS2103T /desc Software Engineering` .Before `*mod* add /code CS2103T /desc Software Engineering` image::ModAddBefore1.png[] .After `*mod* add /code CS2103T /desc Software Engineering` image::ModAddAfter1.png[] You can also add a module without description. To add a module with the module code `CS2101`, you can type the following command: `*mod* add /code CS2101` .Before `*mod* add /code CS2101` image::ModAddBefore2.png[] .After `*mod* add /code CS2101` image::ModAddAfter2.png[] ==== Viewing all modules You can view a list of all modules. Format: * `*mod* list` Example: You can view all modules in Mod Manager. To see a list of all modules, you can type the following command: `*mod* list` .After `*mod* list` image::ModListAfter1.png[] // tag::mod-view[] ==== Viewing information of a module You can view all classes, tasks and facilitators for a module. Format: * `*mod* view INDEX` * `*mod* view MOD_CODE` Command properties: **** * Views the module at the specified `INDEX` or with the specified `MOD_CODE`. The index refers to the index number shown in the displayed module list. The index *must be a positive integer* 1, 2, 3, ... **** Examples: You can view a module using the index in the module list. To view all classes, tasks and facilitators for the second module in the module list, you can type the following command: `*mod* view 2` .Before `*mod* view 2` image::ModViewBefore1.png[] .After `*mod* view 2` image::ModViewAfter1.png[] Alternatively, you can view a module using the module code. To view all classes, tasks and facilitators for the module `CS2103T`, you can type the following command: `*mod* view CS2103T` .Before `*mod* view CS2103T` image::ModViewBefore2.png[] .After `*mod* view CS2103T` image::ModViewAfter2.png[] // end::mod-view[] ==== Editing a module You can edit the information of a module. Format: * `*mod* edit INDEX [/code NEW_MODE_CODE] [/desc DESCRIPTION]` * `*mod* edit MOD_CODE [/code NEW_MODE_CODE] [/desc DESCRIPTION]` Command properties: **** * Edits the module at the specified `INDEX` or with the specified `MOD_CODE`. The index refers to the index number shown in the displayed module list. The index *must be a positive integer* 1, 2, 3, ... * At least one of the optional fields must be provided. * Existing values will be updated to the input values. * MOD_CODE should be 2-3 letters followed by 4 numbers (and a possible trailing letter) with no spaces. * DESCRIPTION should not exceed 64 characters. * You can remove the description linked to the module by typing `/desc` without specifying any input after it. **** Examples: You can edit a module using the index in the module list. To update the module code of the first module in the module list to `CS2113T`, you can type the following command: `*mod* edit 1 /code CS2113T` .Before `*mod* edit 1 /code CS2113T` image::ModEditBefore1.png[] .After `*mod* edit 1 /code CS2113T` image::ModEditAfter1.png[] Alternatively, you can edit a module using the module code. To update the description of the module `CS2101` to `Effective Communication for Computing Professionals`, you can type the following command: `*mod* edit CS2101 /desc Effective Communication for Computing Professionals` .Before `*mod* edit CS2101 /desc Effective Communication for Computing Professionals` image::ModEditBefore2.png[] .After `*mod* edit CS2101 /desc Effective Communication for Computing Professionals` image::ModEditAfter2.png[] You can also remove the description of a module without specifying any input after the prefix `/desc`. To remove the description of the third module in the module list, you can type the following command: `*mod* edit 3 /desc` .Before `*mod* edit 3 /desc` image::ModEditBefore3.png[] .After `*mod* edit 3 /desc` image::ModEditAfter3.png[] ==== Deleting a module You can delete a module from Mod Manager. All classes, tasks and facilitators for that module will also be deleted. Format: * `*mod* delete INDEX` * `*mod* delete MOD_CODE` Command properties: **** * Deletes the module at the specified `INDEX` or with the specified `MOD_CODE`. The index refers to the index number shown in the displayed module list. The index *must be a positive integer* 1, 2, 3, ... **** Examples: You can delete a module using the index in the module list. To delete the second module in the module list, you can type the following command: `*mod* delete 2` .Before `*mod* delete 2` image::ModDeleteBefore1.png[] .After `*mod* delete 2` image::ModDeleteAfter1.png[] Alternatively, you can delete a module using the module code. To delete the module with the module code `CS2103T`, you can type the following command: `*mod* delete CS2103T` .Before `*mod* delete CS2103T` image::ModDeleteBefore2.png[] .After `*mod* delete CS2103T` image::ModDeleteAfter2.png[] // end::module[] // tag::class[] === Class feature : `*class*` You can add, find, edit or delete classes within Mod Manager. + When managing your classes, you should take note of the following areas in the main viewing area. To find the main viewing area, you can refer to section 3.1. .Explanation of how to look at classes image::ClassExplain.png[] ==== Adding a class You can add a class to a module. Format: * `*class* add /code MOD_CODE /type CLASS_TYPE /at DAY START_TIME END_TIME [/venue VENUE]` + Command properties: **** * MOD_CODE must be an existing and valid module code in the list of modules. * CLASS_TYPE available for use are LEC, TUT, SEC, REC and LAB. * DAY available for use are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY and SUNDAY. * START_TIME and END_TIME should be in 24 hour HH:mm format. * VENUE is optional. **** Example: You have a CS2103T lecture on Friday from 14:00 to 16:00 at i3-Aud. Before adding that class, Mod Manager looks like what you see in the figure below. + .Before adding a class image::ClassAddBefore.png[] To add that class, you can type: + `*class* add /code CS2103T /type LEC /at FRIDAY 14:00 16:00 /venue i3-Aud`. + You will see a new class added to the module CS2103T as shown in the figure below. .After adding a class image::ClassAddAfter.png[] ==== Finding classes by day You can find classes occurring on a particular day. Format: * `*class* find /at DAY` Command properties: **** * DAY available for use are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY and SUNDAY. **** Example: To know what classes you have on Friday, you can type `*class* find /at friday` and you will be able to see the classes in the result display box as shown in the figure below. .After finding class by day image::ClassFindDay.png[] ==== Finding next class You can find the next class that will start soon. Format: * `*class* find /next` Example: After typing `*class* find /next`, you will be directed to the module's page and you will see the class as shown in the figure below. .After finding next class image::ClassFindNext.png[] ==== Editing a class You can edit the information of the class. The class to be edited is selected by its index in the displayed module's class list. You can view the module's class list by using `*mod* view MOD_CODE` as stated in section 3.2.3. Format: * `*class* edit INDEX /code MOD_CODE [/code NEW_MOD_CODE] [/type CLASS_TYPE] [/at DAY START_TIME END_TIME] [/venue VENUE]` + Command properties: **** * The index refers to the index number shown in the displayed module list. The index *must be a positive integer* 1, 2, 3, ... * MOD_CODE must be an existing and valid module code in the list of modules. * CLASS_TYPE available for use are LEC, TUT, SEC, REC and LAB. * DAY available for use are MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY and SUNDAY. * START_TIME and END_TIME should be in 24 hour HH:mm format. * At least one of the optional fields must be provided. **** Example: Let's say that the venue of the CS2103T lecture you just added changed to Home. You can edit the class by typing `*class* edit 1 /code CS2103T /venue Home`. Mod Manager will direct you to the module's page and it will reflect the updated venue as seen below. .After editing a class image::ClassEdit.png[] ==== Deleting a class You can delete the class from the module. The class to be deleted is selected by its index in the displayed module's class list. You can view the module's class list by using `*mod* view MOD_CODE` as stated in section 3.2.3. Format: * `*class* delete INDEX /code MOD_CODE` Command properties: **** * The index *must be a positive integer* 1, 2, 3, ... **** Example: You can delete the CS2103T lecture by typing `*class* delete 1 /code CS2103T`. The class will not appear in the class list under the module CS2103T as seen below. .After deleting a class image::ClassDelete.png[] // end::class[] // start::task[] === Task feature : `*task*` The commands in this section carry out operations on the task list in Mod Manager. Executing these commands will bring you to the Tasks tab. ==== Adding a task You can add a task to a module. Format: * `*task* add /code MOD_CODE /desc DESCRIPTION [/on DATE] [/at TIME]` Example: `*task* add /code CS3230 /desc Programming Assignment 2 /on 20/02/2020 /at 23:59` Command properties: **** * MOD_CODE must be an existing and valid module code in the list of modules. * A module can be linked to any number of tasks (including 0). * `DATE` and `TIME` are optional fields, however, there can only be a `TIME` field if a `DATE` field is provided. For example, `/at 23:59` without `/on DATE` is not allowed. * `DATE` follows `_dd/MM/yyyy_` format. It should be a valid date, e.g. Day 32 or Month 13 is not allowed. A special date is reserved in Mod Manager for a special functional purpose: 01/01/1970. If you choose to use this date as your input, Mod Manager won't (for now) show an error message, but is not guaranteed to exhibit a normal behaviour. * `TIME` follows `_HH:mm_` format. It should be a valid time period between 00:01 and 23:59, e.g. 00:00 and 24:00 are not allowed - if you input these values, they will be ignored. * Similar tasks across modules are allowed. However, tasks within a same module must have different descriptions. They can occupy the same time period. **** //tag::task-edit-delete[] ==== Editing a task From here on, you will be introduced to Mod Manager's task ID system. **** * A task can be uniquely identified in the system by two things: its associated module and a 3-digit number (from 100-999). * A complete task ID will consist of two elements: `MOD_CODE` and `ID_NUMBER`. * Examples of valid task ID: `CS2103T 848`, `CS4231 132`. * You can find out a task's ID by looking at the general task list - can be viewed with <>, or the task list of a specific module - can be viewed with <>. **** You can edit a task's description, its date and time details, or both by providing the correct task ID and the updated information. Format: * `*task* edit MOD_CODE ID_NUMBER [/desc DESCRIPTION] [/on DATE] [/at TIME]` Mod Manager will find the task associated with the module code and task ID number provided and update the information correspondingly. The properties of `DESCRIPTION`, `DATE` and `TIME` are described in the <> section. Example: `*task* edit CS2101 344 /desc OP2 /on 08/04/2020` Type the command into the command box. The task to edit in this example is marked by the red rectangle. .Before `*task* edit` image::task-edit-1.png[] After pressing kbd:[Enter], you will see that the task has been edited. .After `*task* edit` image::task-edit-2.png[] Since you may want to remove the date and time of a task, Mod Manager provides you a way to do so. Note that if you try to remove the date and time from a task without these values, Format: * `*task* edit MOD_CODE ID_NUMBER [/desc DESCRIPTION] /on non` Example: `*task* edit ST2334 401 /on non` .A task whose date and time that you want to remove image::task-edit-3.png[] Again, press kbd:[Enter] and you will see its date and time has been removed. Its order in the list may be changed due to the sorting property of the <>. .The task's date and time removed image::task-edit-4.png[] ==== Deleting a task You can delete a task from Mod Manager's system. Format: * `*task* delete MOD_CODE ID_NUMBER` Example: `*task* delete CS2101 344` .The task to delete image::task-delete-1.png[] Press kbd:[Enter] and the task will be gone from the list. .Task deleted from the list image::task-delete-2.png[] //end::task-edit-delete[] //tag::task-mark-as-done-UG[] ==== Marking a task as done You can mark the task as done in the module in Mod Manager. NOTE: A newly added task will be not done by default. NOTE: Editing a task will not change the done/not done status of the task. NOTE: Tasks that are already marked as done cannot be re-marked as done. Format: * `*task* done /code MOD_CODE /id ID_NUMBER` + Command properties: **** * MOD_CODE should belong to a valid and existing module in Mod Manager. * ID_NUMBER should belong to a valid task for the module above. **** Example: You can mark a task as done in the module. To mark the task with task ID `ID_NUMBER` in module `MOD_CODE` to be done, you can type in the following command: `*task* done /code CS2105 /id 224` and hit kbd:[Enter] .Before `*task* done /code CS2105 /id 224` image::TaskDoneBeforeCloseUp.png[] .After `*task* done /code CS2105 /id 224` image::TaskDoneAfterCloseUp.png[] The <> has changed to green; which means our task has been marked as done. Hooray! We just completed a task. //end::task-mark-as-done-UG[] ==== Viewing all tasks across all modules You can view a list of all tasks across all modules in Mod Manager. This is great when you need an overview of all tasks that you need to complete at present. Format: * `*task* list` Example: By typing the command above, you should see a list of tasks, such as the following: .`*task* list` shows a list of all tasks in Mod Manager image::TaskList.png[] ==== Viewing tasks for a specific module If you want to find tasks for a specific module in Mod Manager, this is the command for you to use! Format: * `*task* module /code CS2103T` Command properties: **** * MOD_CODE should belong to a valid and existing module in Mod Manager. **** NOTE: Alternatively, you can also view the tasks for a specific module in the `Module` tab (the <>). Example: If you want a list of current tasks for the module `CS3230`, you can type in the following command: `*task* module /code CS3230` and hit kbd:[Enter] It is not compulsory for you to be at the Tasks tab before typing in this command. Mod Manager will automatically redirect you to the Tasks tab if you are currently at another tab. .All tasks belonging to the module `CS3230` are listed image::TaskListModule.png[] ==== Viewing all tasks not done/finished Previously, we know that we can mark a task as done, so as to organise, manage, and plan our tasks better. Now, with this command, you can see all the tasks that have not yet been finished. Format: `*task* undone` .Before `*task* undone`, all tasks are listed image::TaskListNotDoneBefore.png[] By typing the command above and hit kbd:[Enter], you should only see uncompleted tasks, which are in dark red color: .Only uncompleted tasks are shown image::TaskListNotDoneAfter.png[] //tag::task-find-description-UG[] ==== Finding tasks by description You are browsing through the task list. But there are too many tasks! You suddenly remember a specific task that you want to do, but you can only vaguely remember its description, e.g. something related to assignment. This command is exactly what you need. In your case, you can find all tasks that contain the word `assignment`, which may include `Programming Assignment`, `written assignment`, `Take-home Lab Assignment` (note that it can be case-insensitive). If you remember multiple words in your wanted tasks, you may also type in multiple words as you want. Tasks that meet at least one of the keywords you provided will be shown to you. Format: * `*task* find DESCRIPTION [MORE_DESCRIPTIONS]...` Command properties: **** * The `find` works across modules, so no `/code` command are required. For example, you may want to find all the `assignment` currently due. * Searching for description is case insensitive. e.g `programming` will match `Programming`. * The order of the descriptions does not matter. e.g. `Programming Assignment` will match `Assignment Programming`. * Tasks are only searched in the description. * Words can be partially matched e.g. `assign` will match `assignment`. * Tasks matching at least one description will be returned (i.e. `OR` search). e.g. `assign home` will return both `Programming Assignment 2` and `Homework 3`. **** Examples: To find tasks that contain the word `oral`, `assign`, or `tut` in their description, you can type in the following command: `*task* find oral assign tut` and press kbd:[Enter] .After `*task* find oral assign tut`, all matching tasks are displayed image::TaskFindAfter.png[] Explanation: + - `Oral Presentation 2` contains `Oral` which matches `oral` (case-insensitive). + - `Programming Assignment 2` contains `Assignment` which matches `assign` (case-insensitive, and words can be partial match) + - Similarly, `Assignment 3` will match `assign`, and `Tutorial` will match `tut` + - As long as a task's description matches *one* of the keywords provided, it will be shown. + You can try typing in `*task* find assign tut oral` and press kbd:[Enter]. This will return the same list of tasks, since the ordering of the keywords does not matter. Other examples: * `*task* find homework` + Finds all tasks that contain the word `homework` in their description * `*task* find math coding` + Finds all tasks that contain the word `math` *or* `coding` in their description //end::task-find-description-UG[] ==== Searching tasks by date With this command, you can search for all tasks that occur on your specified date, month, or year. NOTE: Tasks are only searched for its date. Tasks that do not have dates or times will not be found in this list. Format: * `*task* search [/date DATE] [/month MONTH] [/year YEAR]` Command properties: **** * The `search` works across modules, so no `/code` commands are required. * If no optional fields are provided, Mod Manager will output all tasks that have a specified time period. * Invalid inputs such as `/date monday`, `/month December`, `/year this year` are not allowed. Please use numbers for `/date`, `/month`, and `/year` instead. * Invalid date, month, or year is not allowed. For example: + - `/date 32`, `/date 0`: `date` can only range from `1` to `31`. - `/month 13`, `/month 0`: `month` can only range from `1` to `12`. - `/year 0`, `/year 99999`: the `search` only accept `year` ranging from `1` to `9999` - `/date 30 /month 2`: there is no 30/2 in any year - `/date 29 /month 2 /year 2019`: this is not possible since `2019` is not a leap year. However, `/date 29 /month 2` (year is not provided) is okay. * Tasks matching *all* conditions will be returned (i.e. `AND` search). e.g. `/month 5 /year 2020` will only match tasks that are in May 2020. **** Example: You can search for tasks that are due on the submission date of CS2103T for AY19/20 S2 (13 April). To find tasks happening on 13 April, you can type `*task* search /date 13 /month 4` and press kbd:[Enter]. This will return all tasks that are happening on 13 April. .Before `*task* search /date 13 /month 4`, all tasks are listed image::TaskSearchBefore.png[] .After `*task* search /date 13 /month 4`, only matching tasks are listed image::TaskSearchAfter.png[] Explanation: the two tasks both have date as `13` and month as `4`. Other examples: * `*task* search /date 1` + Searches for all tasks happening on the first day of the month, in any year. Who wants to study on New Year's Day really? * `*task* search /month 4 /year 2020` + Searches for all tasks in the current month (at the time of writing, April 2020). * `*task* search /year 2020` + Searches for all tasks in this year (at the time of writing). This will be useful if Mod Manager is used over a long period of time. * `*task* search /date 14 /month 2 /year 2021` + Searches for all tasks happening on 14/02/2021. === Facilitator feature : `*facil*` // tag::facilitator[] The commands in this section carry out operations on the facilitator list in Mod Manager. Executing these commands will bring you to the Facilitators tab. ==== Adding a facilitator You can add a facilitator to Mod Manager. Format: * `*facil* add /name FACILITATOR_NAME [/phone PHONE] [/email EMAIL] [/office OFFICE] /code MOD_CODE [MORE_MOD_CODES]...` * `*facil* add /name FACILITATOR_NAME [/phone PHONE] [/email EMAIL] [/office OFFICE] /code MOD_CODE [/code MORE_MOD_CODES]...` Command properties: **** * At least one of the optional fields (phone, email, office) must be provided. * A facilitator can be linked to one or more modules. A module with the module code provided must exist in Mod Manager. * To add multiple module codes, you can include the prefix `/code` once before all module codes (e.g. `/code CS2103T CS3243`) or multiple times once before each module code (e.g. `/code CS2103T /code CS3243`). **** Examples: You can add a facilitator to the facilitator list. To add a facilitator with the name `Akshay Narayan`, phone `98765432` and email `dcsaksh@nus.edu.sg` to the modules `CS2103T` and `CS3243`, you can type the following command: `*facil* add /name Akshay Narayan /phone 98765432 /email dcsaksh@nus.edu.sg /code CS2103T CS3243` .Before `*facil* add /name Akshay Narayan /phone 98765432 /email dcsaksh@nus.edu.sg /code CS2103T CS3243` image::FacilAddBefore1.png[] .After `*facil* add /name Akshay Narayan /phone 98765432 /email dcsaksh@nus.edu.sg /code CS2103T CS3243` image::FacilAddAfter1.png[] You can also add a facilitator to multiple modules by typing the prefix `/code` multiple times. To add a facilitator with the name `Aaron Tan`, email `tantc@comp.nus.edu.sg` and office `COM1-0312` to the modules `CS1231` and `CS2100`, you can type the following command: `*facil* add /name Aaron Tan /email tantc@comp.nus.edu.sg /office COM1-0312 /code CS1231 /code CS2100` .Before `*facil* add /name Aaron Tan /email tantc@comp.nus.edu.sg /office COM1-0312 /code CS1231 /code CS2100` image::FacilAddBefore2.png[] .After `*facil* add /name Aaron Tan /email tantc@comp.nus.edu.sg /office COM1-0312 /code CS1231 /code CS2100` image::FacilAddAfter2.png[] ==== Viewing all facilitators You can view a list of all facilitators sorted in alphabetical order. Format: * `*facil* list` Example: You can view all facilitators in Mod Manager. To see a list of all facilitators sorted in alphabetical order, you can type the following command: `*facil* list` .After `*facil* list` image::FacilListAfter1.png[] ==== Finding a facilitator by name You can find facilitators by name. Format: * `*facil* find FACILITATOR_NAME [MORE_FACILITATOR_NAMES]...` Command properties: **** * The search is case insensitive. e.g `hans` will match `Hans`. * The order of the name does not matter. e.g. `Hans Bo` will match `Bo Hans`. * Only the name is searched. * Partial words will be matched e.g. `Han` will match `Hans`. * Facilitators matching at least one name will be returned (i.e. `OR` search). e.g. `Hans Bo` will return `Hans Gruber`, `Bo Yang`. **** Examples: You can search for facilitators by name. To view all facilitators whose name contains `Akshay`, you can type the following command: `*facil* find Akshay` .Before `*facil* find Akshay` image::FacilFindBefore1.png[] .After `*facil* find Akshay` image::FacilFindAfter1.png[] You can also search for multiple facilitators or search with partial names. To view a list of facilitators whose name contains `yan` or `tan`, you can type the following command: `*facil* find yan tan` .Before `*facil* find yan tan` image::FacilFindBefore2.png[] .After `*facil* find yan tan` image::FacilFindAfter2.png[] ==== Editing a facilitator You can edit the information of a facilitator. Format: * `*facil* edit INDEX [/name FACILITATOR_NAME] [/phone PHONE] [/email EMAIL] [/office OFFICE] [/code MOD_CODE...]` * `*facil* edit FACILITATOR_NAME [/name FACILITATOR_NAME] [/phone PHONE] [/email EMAIL] [/office OFFICE] [/code MOD_CODE...]` Command properties: **** * Edits the facilitator at the specified `INDEX`. The index refers to the index number shown in the last displayed facilitator list in the Facilitators tab. The index *must be a positive integer* 1, 2, 3, ... * At least one of the optional fields must be provided. * Existing values will be updated to the input values. * When editing module codes, the existing module codes of the facilitator will be removed i.e adding of module code is not cumulative. * A module with the module code provided must exist in Mod Manager. * You can remove the phone, email or office linked to the facilitator by typing `/phone`, `/email` or `/office` respectively without specifying any input after it. **** Examples: You can edit the information of a facilitator using the index in the last shown facilitator list. To update the name and email of the first facilitator in the last shown facilitator list in the Facilitators tab to `Akshay` and `hisnewemail@nus.edu.sg` respectively, you can type the following command: `*facil* edit 1 /name Akshay /email hisnewemail@nus.edu.sg` .Before `*facil* edit 1 /name Akshay /email hisnewemail@nus.edu.sg` image::FacilEditBefore1.png[] .After `*facil* edit 1 /name Akshay /email hisnewemail@nus.edu.sg` image::FacilEditAfter1.png[] Alternatively, you can edit the information of a facilitator using the name of the facilitator. To update the office of the facilitator with the name `Akshay Narayan` to `COM2-0203`, you can type the following command: `*facil* edit Akshay Narayan /office COM2-0203` .Before `*facil* edit Akshay Narayan /office COM2-0203` image::FacilEditBefore2.png[] .After `*facil* edit Akshay Narayan /office COM2-0203` image::FacilEditAfter2.png[] You can also remove the information of a facilitator without specifying any input after the prefix `/phone`, `/email` or `/office`. To remove the phone of the second facilitator in the last shown facilitator list in the Facilitators tab, type the following command: `*facil* edit 2 /phone` .Before `*facil* edit 2 /phone` image::FacilEditBefore3.png[] .After `*facil* edit 2 /phone` image::FacilEditAfter3.png[] ==== Deleting a facilitator You can delete a facilitator from Mod Manager. Format: * `*facil* delete INDEX` * `*facil* delete FACILITATOR_NAME` Command properties: **** * Deletes the facilitator at the specified `INDEX`. The index refers to the index number shown in the last displayed facilitator list in the Facilitators tab. The index *must be a positive integer* 1, 2, 3, ... **** Examples: You can delete a facilitator using the index in the last shown facilitator list. To delete the first facilitator in the last shown facilitator list in the Facilitators tab, you can type the following command: `*facil* delete 1` .Before `*facil* delete 1` image::FacilDeleteBefore1.png[] .After `*facil* delete 1` image::FacilDeleteAfter1.png[] Alternatively, you can delete a facilitator using the name of the facilitator. To delete the facilitator with the name `Akshay Narayan`, you can type the following command: `*facil* delete Akshay Narayan` .Before `*facil* delete Akshay Narayan` image::FacilDeleteBefore2.png[] .After `*facil* delete Akshay Narayan` image::FacilDeleteAfter2.png[] // end::facilitator[] //tag::calendar[] === Calendar feature : `*cal*` The commands in this section carry out operations related to the calendar in Mod Manager. Executing these commands will bring you to the Calendar tab. ==== Viewing calendar for current week You can view the calendar for the current week. It displays the tasks and classes you have in the current week. Format: * `*cal* view /week this` Example: After typing `*cal* view /week this`, the calendar for the current week will be displayed to you as shown below. The red cards represent the tasks you have not done, the green cards represent the tasks you have already done and the blue cards represent the classes you have in the current week. .Outcome of `*cal* view /week this` image::CalView1.png[] ==== Viewing calendar for next week You can view the calendar for next week. It displays the tasks and classes you have in the next week. Format: * `*cal* view /week next` Example: After typing `*cal* view /week next`, the calendar for the next week will be displayed to you as shown below. The red cards represent the tasks you have not done, the green cards represent the tasks you have already done and the blue cards represent the classes you have in next week. .Outcome of `*cal* view /week next` image::CalView2.png[] ==== Finding empty slots You can find the empty slots from current day to end of the week of the current day. The empty slots are time periods where you do not have classes or tasks. Format: * `*cal* find empty` Example: You can get the list of empty slots after typing `*cal* find empty`. The list will be displayed in the result display box as seen below. The command will not change the week of the calendar you are viewing. .Outcome of `*cal* find empty` image::CalFind1.png[] The full message in the result display box in the above figure is: **** Here's the list of empty slots from today to Sunday: + THURSDAY: + 00:00-08:00 12:00-16:00 18:00-23:59 + FRIDAY: + 00:00-10:00 13:00-14:00 16:00-23:59 + SATURDAY: + 00:00-23:59 + SUNDAY: + 00:00-23:59 **** //end::calendar[] === Upcoming features `[coming in v2.0]` // tag::upcoming[] These features will be available in the next version of Mod Manager. ==== Categorising tasks `[coming in v2.0]` You can add tags to a task. ==== Adding a priority level to a task `[coming in v2.0]` You can add a priority level to a task. ==== Receiving reminders `[coming in v2.0]` You can receive reminders for deadlines and events the next day. // end::upcoming[] // tag::upcoming-tasks[] ==== Finding upcoming tasks `[coming in v2.0]` You can find upcoming tasks, such as assignment submission and final exam in Mod Manager. // end::upcoming-tasks[] ==== Viewing of the recently edited item after an `add`, `edit` or `delete` command `[coming in v2.0]` After an `add`, `edit` or `delete` operation, the view will be scrolled to that recently created or modified item, so that you can refer to the information easily. The newly created or modified details will be highlighted and focused so that you know what has been changed. == FAQ === How do I transfer my data to another computer? Install the app in the other computer and overwrite the empty data file it creates with the file that contains the data of your previous Mod Manager folder. == Glossary This glossary aims to provide a definition for the special vocabulary used in this user guide. [[dashboard]] Dashboard:: The default tab in view when the application starts (i.e. the `Module` tab). //tag::taskcard[] [[taskcard]] Task card:: A task card represents a task with details such as the module it belongs to, description, and time period (if provided upon creation). A dark red card represents a task that is not done. image::TaskCardNotDone.png[] A green card represents a done task. image::TaskCardDone.png[] //end::taskcard[] == Command Summary .Summary of command formats [%autowidth] |===== |*Category* |*Commands* .3+|Calendar | `*cal* find empty` | `*cal* view /week next` | `*cal* view /week this` .5+|Class | `*class* add /code MOD_CODE /type CLASS_TYPE /at DAY START_TIME END_TIME [/venue VENUE]` | `*class* delete INDEX /code MOD_CODE` | `*class* edit INDEX /code MOD_CODE [/code NEW_MOD_CODE] [/type CLASS_TYPE] [/at DAY START_TIME END_TIME] [/venue VENUE]` | `*class* find /at DAY` | `*class* find /next` .5+|Facilitator | `*facil* add /name FACILITATOR_NAME [/phone PHONE] [/email EMAIL] [/office OFFICE] /code MOD_CODE [MORE_MOD_CODES]...` + `*facil* add /name FACILITATOR_NAME [/email EMAIL] [/phone PHONE] [/office OFFICE] /code MOD_CODE [/code MORE_MOD_CODES]...` | `*facil* delete FACILITATOR_NAME` + `*facil* delete INDEX` + | `*facil* edit FACILITATOR_NAME [/name FACILITATOR_NAME] [/email EMAIL] [/phone PHONE] [/office OFFICE] [/code MOD_CODE...]` + `*facil* edit INDEX [/name FACILITATOR_NAME] [/email EMAIL] [/phone PHONE] [/office OFFICE] [/code MOD_CODE...]` | `*facil* find FACILITATOR_NAME [MORE_FACILITATOR_NAMES]...` | `*facil* list` .7+|General | `*clear*` | `*cmd* all` | `*cmd* group COMMAND_WORD` | `*exit*` | `*help*` | `*redo*` | `*undo*` .5+|Module | `*mod* add /code MOD_CODE [/desc DESCRIPTION]` | `*mod* delete INDEX` + `*mod* delete MOD_CODE` | `*mod* edit INDEX [/code NEW_MODE_CODE] [/desc DESCRIPTION]` + `*mod* edit MOD_CODE [/code NEW_MODE_CODE] [/desc DESCRIPTION]` | `*mod* list` | `*mod* view INDEX` + `*mod* view MOD_CODE` .9+|Task | `*task* add /code MOD_CODE /desc DESCRIPTION [/on DATE] [/at TIME]` | `*task* delete MOD_CODE ID_NUMBER` | `*task* done /code MOD_CODE /id ID_NUMBER` | `*task* edit MOD_CODE ID_NUMBER [/desc DESCRIPTION] [/on DATE] [/at TIME]` + `*task* edit MOD_CODE ID_NUMBER [/desc DESCRIPTION] /on non` | `*task* find DESCRIPTION [MORE_DESCRIPTIONS]...` + | `*task* list` | `*task* module /code MOD_CODE` | `*task* search [/date DATE] [/month MONTH] [/year YEAR]` | `*task* undone` |===== .Summary of common command parameters [%autowidth] |===== |*Parameter* | *Constraints* |`DESCRIPTION` |`DESCRIPTION` should not exceed 64 characters. This includes `Module` 's and `Task` 's description. |`MOD_CODE` |`MOD_CODE` should be 2-3 letters followed by 4 digits (and a possible trailing letter) with no spaces. |===== ",12420,True,2533.0236341813256,median "// // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // ""License""); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // ""AS IS"" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // = Writing JUnit Tests in NetBeans IDE :jbake-type: tutorial :jbake-tags: tutorials :jbake-status: published :icons: font :syntax: true :source-highlighter: pygments :toc: left :toc-title: :description: Writing JUnit Tests in NetBeans IDE - Apache NetBeans :keywords: Apache NetBeans, Tutorials, Writing JUnit Tests in NetBeans IDE This tutorial introduces the basics of writing and running JUnit unit tests in NetBeans IDE. Testing an application is an integral part of the development cycle, and writing and maintaining unit tests can help ensure that the individual methods in your source code work correctly. The IDE's integrated support for the JUnit unit testing framework enables you to quickly and easily create JUnit tests and test suites. In this tutorial you create simple JUnit 3 and JUnit 4 unit tests and test suites for a Java class library project. The first part of the tutorial shows how to create tests in JUnit 3. The second part shows how to create the same tests in JUnit 4 using JUnit annotations. It is not necessary to complete both parts of the tutorial because the tests are the same, but seeing how the tests are written in both versions enables you to see some of the changes introduced in JUnit 4. For more on using JUnit, see link:http://www.junit.org[+www.junit.org+]. NOTE: To follow this tutorial, you need the link:https://netbeans.org/projects/samples/downloads/download/Samples/Java/JUnitSampleSol.zip[JUnitSampleSol Project]. == Creating the Project To complete this tutorial you first create a Java class library project called JUnit-Sample. After you create the project, you copy two classes from the sample project JUnitSampleSol to your project JUnit-Sample. === Creating the Java Class Library Project 1. Choose File > New Project from the main menu. 2. Select Java Class Library from the Java category and click Next. 3. Type *JUnit-Sample* for the project and set the project location. 4. Deselect the Use Dedicated Folder option, if selected. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users or projects. Click Finish. The first time that you create a JUnit test the IDE prompts you to select a version and then adds a Test Libraries node and the JUnit library. == Creating the Java Classes In this exercise you copy the files ``Utils.java`` and ``Vectors.java`` from the sample project JUnitSampleSol into the class library project that you created. 1. In the Projects window, right-click the Source Packages node of the *JUnit-Sample* project and choose New > Java Package from the popup menu. 2. Type *sample* as the package name. Click Finish. 3. Open the *JUnitSampleSol* project (if not already open) and expand the Source Packages node in the Projects window. [.feature] -- image::images/projects-window.png[] -- . Copy the classes ``Utils.java`` and ``Vectors.java`` in the JUnitSampleSol project and paste them into the ``sample`` source package in JUnit-Sample. If you look at the source code for the classes, you can see that ``Utils.java`` has three methods ( ``computeFactorial`` , ``concatWords`` , and ``normalizeWord`` ) and that ``Vectors.java`` has two methods ( ``equal`` and ``scalarMultiplication`` ). The next step is to create test classes for each class and write some test cases for the methods. NOTE: You can close the JUnitSampleSol project because you will not need it again. The JUnitSampleSol project contains all the tests described in this document. == Writing JUnit 3 Unit Tests In this part of the tutorial you create basic JUnit 3 unit tests for the classes ``Vectors.java`` and ``Utils.java`` . You will use the IDE to create skeleton test classes that are based on the classes in your project. You will then modify the generated test methods and add new test methods. The IDE prompts you to choose a JUnit version the first time that you use the IDE to create tests for you in the project. The version that you select becomes the default JUnit version and the IDE will generate all subsequent tests and test suites for that version. === Creating a Test Class for ``Vectors.java`` In this exercise you create a JUnit test skeleton for ``Vectors.java`` . You will also select JUnit as the test framework and JUnit 3 as the version. NOTE: If you are using NetBeans IDE 7.1 or earlier you do not need to specify the test framework because JUnit is specified by default. From NetBeans IDE 7.2 onwards, you have the option of specifying JUnit or TestNG as the test framework. 1. Right-click ``Vectors.java`` and choose Tools > Create Tests. 2. Modify the name of the test class to *VectorsJUnit3Test* in the Create Tests dialog. When you change the name of the test class, you will see a warning about changing the name. The default name is based on the name of the class you are testing, with the word Test appended to the name. For example, for the class ``MyClass.java`` , the default name of the test class is ``MyClassTest.java`` . Usually it is best to keep the default name, but for this tutorial you will change the name because you will also create JUnit 4 tests in the same package and the names of the test classes must be unique. . Select JUnit in the Framework dropdown list. . Deselect Test Initializer and Test Finalizer. Click OK. [.feature] -- image::images/junit3-vectors-createtests.png[] -- . Select JUnit 3.x in the Select JUnit Version dialog box. [.feature] -- image::images/junit3-select-version.png[] -- When you select JUnit 3.x the IDE adds the JUnit 3 library to the project. When you click Select, the IDE creates the ``VectorsJUnit3Test.java`` test class in the ``sample`` package under the Test Packages node in the Projects window. [.feature] -- image::images/projects-window2.png[] -- A project requires a directory for test packages to create tests. The default location for the test packages directory is at the root level of the project, but depending on the type of project you can specify a different location for the directory in the project's Properties dialog. If you look at the generated test class ``VectorsJUnit3Test.java`` in the editor, you can see that the IDE generated the following test class with test methods for the methods ``equal`` and ``scalarMultiplication`` . [source,java] ---- public class VectorsJUnit3Test extends TestCase { /** * Test of equal method, of class Vectors. */ public void testEqual() { System.out.println(""equal""); int[] a = null; int[] b = null; boolean expResult = false; boolean result = Vectors.equal(a, b); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail(""The test case is a prototype.""); } /** * Test of scalarMultiplication method, of class Vectors. */ public void testScalarMultiplication() { System.out.println(""scalarMultiplication""); int[] a = null; int[] b = null; int expResult = 0; int result = Vectors.scalarMultiplication(a, b); assertEquals(expResult, result); // TODO review the generated test code and remove the default call to fail. fail(""The test case is a prototype.""); } } ---- The method body of each generated test is provided solely as a guide and needs to be modified to be an actual test case. You can deselect Default Method Bodies in the Create Tests dialog if you do not want the code generated for you. When the IDE generates the names for the test methods, each method name is prepended with ``test`` because JUnit 3 uses naming conventions and reflection to identify tests. To identify test methods, each test method is required to follow the syntax ``test__`` . NOTE: In JUnit 4, it is no longer necessary to use this test method naming syntax because you can use annotations to identify test methods and the test class is no longer required to extend ``TestCase`` . === Writing Test Methods for ``Vectors.java`` In this exercise you modify the generated test methods to make them functioning tests and modify the default output messages. You do not need to modify the output messages to run the tests, but you may want to modify the output to help identify the results displayed in the JUnit Test Results output window. 1. Open ``VectorsJUnit3Test.java`` in the editor. 2. Modify the test skeleton for ``testScalarMultiplication`` by changing the value of the ``println`` and removing the generated variables. The test method should now look like the following (changes displayed in bold): [source,java] ---- public void testScalarMultiplication() { System.out.println(""** VectorsJUnit3Test: testScalarMultiplication()*""); assertEquals(expResult, result); } ---- . Now add some assertions to test the method. [source,java] ---- public void testScalarMultiplication() { System.out.println(""* VectorsJUnit3Test: testScalarMultiplication()""); *assertEquals( 0, Vectors.scalarMultiplication(new int[] { 0, 0}, new int[] { 0, 0})); assertEquals( 39, Vectors.scalarMultiplication(new int[] { 3, 4}, new int[] { 5, 6})); assertEquals(-39, Vectors.scalarMultiplication(new int[] {-3, 4}, new int[] { 5,-6})); assertEquals( 0, Vectors.scalarMultiplication(new int[] { 5, 9}, new int[] {-9, 5})); assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, 8}, new int[] { 6, 8}));* } ---- This test method uses the JUnit ``assertEquals`` method. To use the assertion, you supply the input variables and the expected result. To pass the test, the test method must successfully return all the expected results based on the supplied variables when running the tested method. You should add a sufficient number of assertions to cover the various possible permutations. . Modify the test skeleton for ``testEqual`` by deleting the generated method bodies and adding the following ``println`` . [source,java] ---- *System.out.println(""* VectorsJUnit3Test: testEqual()"");* ---- The test method should now look like the following: [source,java] ---- public void testEqual() { System.out.println(""* VectorsJUnit3Test: testEqual()""); } ---- . Modify the ``testEqual`` method by adding the following assertions (displayed in bold). [source,java] ---- public void testEqual() { System.out.println(""* VectorsJUnit3Test: testEqual()""); *assertTrue(Vectors.equal(new int[] {}, new int[] {})); assertTrue(Vectors.equal(new int[] {0}, new int[] {0})); assertTrue(Vectors.equal(new int[] {0, 0}, new int[] {0, 0})); assertTrue(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 0})); assertTrue(Vectors.equal(new int[] {5, 6, 7}, new int[] {5, 6, 7})); assertFalse(Vectors.equal(new int[] {}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 1})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 1, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {1, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 1}, new int[] {0, 0, 3}));* } ---- This test uses the JUnit ``assertTrue`` and ``assertFalse`` methods to test a variety of possible results. For the test of this method to pass, the ``assertTrue`` must all be true and ``assertFalse`` must all be false. . Save your changes. Compare: <> === Creating a Test Class for ``Utils.java`` You now create the test skeletons for ``Utils.java`` . When you created the test in the previous exercise, the IDE prompted you for the version of JUnit. You are not prompted to select a version this time. 1. Right-click ``Utils.java`` and choose Tools > Create Tests. 2. Select JUnit in the Framework dropdown list if not selected. 3. Select Test Initializer and Test Finalizer in the dialog box, if not selected. 4. Modify the name of the test class to *UtilsJUnit3Test* in the Create Tests dialog box. Click OK. When you click OK, the IDE creates the test file ``UtilsJUnit3Test.java`` in the Test Packages > samples directory. You can see that in addition to creating the test skeletons ``testComputeFactorial`` , ``testConcatWords`` , and ``testNormalizeWord`` for the methods in ``Utils.java`` , the IDE also creates the test initializer method ``setUp`` and the test finalizer method ``tearDown`` . === Writing Test Methods for ``Utils.java`` In this exercise you add some test cases that illustrate some common JUnit test elements. You also add a ``println`` to the methods because some methods do not print any output by default. By adding a ``println`` to the methods you can later look in the JUnit test result window to see if the methods were run and the order in which they were run. ==== Test Initializers and Finalizers The ``setUp`` and ``tearDown`` methods are used to initialize and finalize test conditions. You do not need the ``setUp`` and ``tearDown`` methods to test ``Utils.java`` , but they are included here to demonstrate how they work. The ``setUp`` method is a test initialization method and is run before each test case in the test class. A test initialization method is not required for running tests, but if you need to initialize some variables before you run a test, you use the test initializer method. The ``tearDown`` method is a test finalizer method and is run after each test case in the test class. A test finalizer method is not required for running tests, but you may need a finalizer to clean up any data that was required when running the test cases. Make the following changes (displayed in bold) to add a ``println`` to each method. [source,java] ---- @Override protected void setUp() throws Exception { super.setUp(); *System.out.println(""* UtilsJUnit3Test: setUp() method"");* } @Override protected void tearDown() throws Exception { super.tearDown(); *System.out.println(""* UtilsJUnit3Test: tearDown() method"");* } ---- When you run the test the ``println`` text for each methods will appear in the JUnit Test Results output window. If you do not add the ``println`` , there is no output to show that the methods were run. ==== Testing Using a Simple Assertion This simple test case tests the ``concatWords`` method. Instead of using the generated test method ``testConcatWords`` , you will add a new test method called ``testHelloWorld`` that uses a single simple assertion to test if the method concatenates the strings correctly. The ``assertEquals`` in the test case uses the syntax ``assertEquals(_EXPECTED_RESULT, ACTUAL_RESULT_)`` to test if the expected result is equal to the actual result. In this case, if the input to the method ``concatWords`` is "" ``Hello`` "", "" ``, `` "", "" ``world`` "" and "" ``!`` "", the expected result should equal ``""Hello, world!""`` . 1. Delete the generated test method ``testConcatWords`` in ``UtilsJUnit3Test.java`` . 2. Add the following method to test the ``concatWords`` method.*public void testHelloWorld() { assertEquals(""Hello, world!"", Utils.concatWords(""Hello"", "", "", ""world"", ""!"")); }* . Add a ``println`` statement to display text about the test in the JUnit Test Results window. [source,java] ---- public void testHelloWorld() { *System.out.println(""* UtilsJUnit3Test: test method 1 - testHelloWorld()"");* assertEquals(""Hello, world!"", Utils.concatWords(""Hello"", "", "", ""world"", ""!"")); ---- Compare: <> ==== Testing Using a Timeout This test demonstrates how to check if a method is taking too long to complete. If the method is taking too long, the test thread is interrupted and the test fails. You can specify the time limit in the test. The test method invokes the ``computeFactorial`` method in ``Utils.java`` . You can assume that the ``computeFactorial`` method is correct, but in this case you want to test if the computation is completed within 1000 milliseconds. The ``computeFactorial`` thread and a test thread are started at the same time. The test thread will stop after 1000 milliseconds and throw a ``TimeoutException`` unless the ``computeFactorial`` thread completes first. You will add a message so that a message is displayed if a ``TimeoutException`` is thrown. 1. Delete the generated test method ``testComputeFactorial`` . 2. Add the ``testWithTimeout`` method that calculates the factorial of a randomly generated number.*public void testWithTimeout() throws InterruptedException, TimeoutException { final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println(""computing "" + factorialOf + '!'); Thread testThread = new Thread() { public void run() { System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); } }; }* . Fix your imports to import ``java.util.concurrent.TimeoutException`` . . Add the following code (displayed in bold) to the method to interrupt the thread and display a message if the test takes too long to execute. [source,java] ---- Thread testThread = new Thread() { public void run() { System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); } }; *testThread.start(); Thread.sleep(1000); testThread.interrupt(); if (testThread.isInterrupted()) { throw new TimeoutException(""the test took too long to complete""); }* } ---- You can modify the ``Thread.sleep`` line to change the number of milliseconds before the timeout is thrown. . Add the following ``println`` (displayed in bold) to print the text about the test in the JUnit Test Results window. [source,java] ---- public void testWithTimeout() throws InterruptedException, TimeoutException { *System.out.println(""* UtilsJUnit3Test: test method 2 - testWithTimeout()"");* final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println(""computing "" + factorialOf + '!'); ---- Compare: <> ==== Testing for an Expected Exception This test demonstrates how to test for an expected exception. The method fails if it does not throw the specified expected exception. In this case you are testing that the ``computeFactorial`` method throws an ``IllegalArgumentException`` if the input variable is a negative number (-5). 1. Add the following ``testExpectedException`` method that invokes the ``computeFactorial`` method with an input of -5.*public void testExpectedException() { try { final int factorialOf = -5; System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); fail(""IllegalArgumentException was expected""); } catch (IllegalArgumentException ex) { } }* . Add the following ``println`` (displayed in bold) to print the text about the test in the JUnit Test Results window. [source,java] ---- public void testExpectedException() { *System.out.println(""* UtilsJUnit3Test: test method 3 - testExpectedException()"");* try { ---- Compare: <> ==== Disabling a Test This test demonstrates how to temporarily disable a test method. In JUnit 3, if a method name does not start with ``test`` it is not recognized as a test method. In this case you prepend ``DISABLED_`` to the name of the test method to disable it. 1. Delete the generated test method ``testNormalizeWord`` . 2. Add the following test method to the test class.*public void testTemporarilyDisabled() throws Exception { System.out.println(""* UtilsJUnit3Test: test method 4 - checkExpectedException()""); assertEquals(""Malm\\u00f6"", Utils.normalizeWord(""Malmo\\u0308"")); }* The test method ``testTemporarilyDisabled`` will run if you run the test class. . Prepend ``DISABLED_`` (displayed in bold) to the name of the test method. [source,java] ---- public void *DISABLED_*testTemporarilyDisabled() throws Exception { System.out.println(""* UtilsJUnit3Test: test method 4 - checkExpectedException()""); assertEquals(""Malm\\u00f6"", Utils.normalizeWord(""Malmo\\u0308"")); } ---- Compare: <> Now that you have written the tests, you can run the test and see the test output in the JUnit Test Results window. === Running the Tests When you run a JUnit test the results are displayed in the Test Results window of the IDE. You can run individual JUnit test classes or you can choose Run > Test _PROJECT_NAME_ from the main menu to run all the tests for the project. If you choose Run > Test, the IDE runs all the test classes in the Test Packages folder. To run an individual test class, right-click the test class under the Test Packages node and choose Run File. 1. Choose Run > Set Main Project in the main menu and select the JUnit-Sample project. 2. Choose Run > Test Project (JUnit-Sample) from the main menu. 3. Choose Window > IDE Tools > Test Results to open the Test Results window. When you run the test you will see one of the following results in the JUnit Test Results window. [.feature] -- image:images/junit3-test-pass-sm.png[role=""left"", link=""images/junit3-test-pass.png""] -- In this image (click the image to see a larger image) you can see that the project passed all the tests. The left pane displays the results of the individual test methods and the right pane displays the test output. If you look at the output you can see the order that the tests were run. The ``println`` that you added to each of the test methods printed out the name of the test to the output window. You can also see that in ``UtilJUnit3Test`` the ``setUp`` method was run before each test method and the ``tearDown`` method was run after each method. [.feature] -- image:images/junit3-test-fail-sm.png[role=""left"", link=""images/junit3-test-fail.png""] -- In this image (click the image to see a larger image) you can see that the project failed one of the tests. The ``testTimeout`` method took too long to complete and the test thread was interrupted, causing that test to fail. It took longer than 1000 milliseconds to compute the factorial of the randomly generated number (22991). The next step after you create your unit test classes is to create test suites. See <> to see how to run specified tests as a group so you do not have to run each test individually. == Writing JUnit 4 Tests In this exercise you create JUnit 4 unit tests for the classes ``Vectors.java`` and ``Utils.java`` . The JUnit 4 test cases are the same as the JUnit 3 test cases, but you will see that the syntax for writing the tests is simpler. You will use the IDE's wizards to create test skeletons based on the classes in your project. The first time that you use the IDE to create some test skeletons for you, the IDE prompts you to choose the JUnit version. *Note.* If you already selected JUnit 3.x as the default version for your tests, you need to change the default version to JUnit 4.x. To change the default JUnit version, expand the Test Libraries node, right-click the JUnit library and choose Remove. You can now use the Add Library dialog box to explicitly add the JUnit 4 library or you can select version 4.x when you are prompted to select the JUnit version when you create a new test. You can still run JUnit 3 tests, but any new tests you create will use JUnit 4. === Creating a Test Class for ``Vectors.java`` In this exercise you will create the JUnit test skeletons for ``Vectors.java`` . NOTE: If you are using NetBeans IDE 7.1 or earlier you do not need to specify the test framework because JUnit is specified by default. From NetBeans IDE 7.2 onwards, you have the option of specifying JUnit or TestNG as the test framework. 1. Right-click ``Vectors.java`` and choose Tools > Create Tests. 2. Modify the name of the test class to *VectorsJUnit4Test* in the Create Tests dialog. When you change the name of the test class, you will see a warning about changing the name. The default name is based on the name of the class you are testing, with the word Test appended to the name. For example, for the class ``MyClass.java`` , the default name of the test class is ``MyClassTest.java`` . Unlike JUnit 3, in JUnit 4, test are not required to end with the word Test. Usually it is best to keep the default name, but because you are creating all the JUnit tests in the same package in this tutorial the names of the test classes have to be unique. . Select JUnit in the Framework dropdown list. . Deselect Test Initializer and Test Finalizer. Click OK. [.feature] -- image::images/junit4-vectors-createtests.png[] -- . Select JUnit 4.x in the Select JUnit Version dialog box. Click Select. [.feature] -- image::images/junit4-select-version.png[] -- When you click OK, the IDE creates the ``VectorsJUnit4Test.java`` test class in the ``sample`` package under the Test Packages node in the Projects window. [.feature] -- image::images/projects-window3.png[] -- NOTE: A project requires a directory for test packages to create tests. The default location for the test packages directory is at the root level of the project, but you can specify a different location for the directory in the project's Properties dialog. If you look at ``VectorsJUnit3Test.java`` in the editor, you can see that the IDE generated the test methods ``testEqual`` and ``testScalarMultiplication`` . In ``VectorsJUnit4Test.java`` , each test method is annotated with ``@Test`` . The IDE generated the names for the test methods based on the names of the method in ``Vectors.java`` but the name of the test method is not required to have ``test`` prepended. The default body of each generated test method is provided solely as a guide and needs to be modified to be actual test cases. You can deselect Default Method Bodies in the Create Tests dialog if you do not want the bodies of the method generated for you. The IDE also generated the following test class initializer and finalizer methods: [source,java] ---- @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } ---- The IDE generates the class initializer and finalizer methods by default when creating JUnit 4 test classes. The annotations ``@BeforeClass`` and ``@AfterClass`` are used to mark methods that should be run before and after running the test class. You can delete the methods because you will not need them to test ``Vectors.java`` . You can configure the methods that are generated by default by configuring the JUnit options in the Options window. NOTE: For JUnit 4 tests, notice that by default the IDE adds a static import declaration for ``org.junit.Assert.*`` . === Writing Test Methods for ``Vectors.java`` In this exercise you modify each of the generated test methods to test the methods using the JUnit ``assert`` method and to change the names of the test methods. In JUnit 4 you have greater flexibility when naming test methods because test methods are indicated by the ``@Test`` annotation and do not require the word ``test`` prepended to test method names. 1. Open ``VectorsJUnit4Test.java`` in the editor. 2. Modify the test method for ``testScalarMultiplication`` by changing the name of the method, the value of the ``println`` and removing the generated variables. The test method should now look like the following (changes displayed in bold): [source,java] ---- @Test public void *ScalarMultiplicationCheck*() { System.out.println(""** VectorsJUnit4Test: ScalarMultiplicationCheck()*""); assertEquals(expResult, result); } ---- NOTE: When writing tests it is not necessary to change the printed output. You do this in this exercise so that it is easier to identify the test results in the output window. . Now add some assertions to test the method. [source,java] ---- @Test public void ScalarMultiplicationCheck() { System.out.println(""* VectorsJUnit4Test: ScalarMultiplicationCheck()""); *assertEquals( 0, Vectors.scalarMultiplication(new int[] { 0, 0}, new int[] { 0, 0})); assertEquals( 39, Vectors.scalarMultiplication(new int[] { 3, 4}, new int[] { 5, 6})); assertEquals(-39, Vectors.scalarMultiplication(new int[] {-3, 4}, new int[] { 5,-6})); assertEquals( 0, Vectors.scalarMultiplication(new int[] { 5, 9}, new int[] {-9, 5})); assertEquals(100, Vectors.scalarMultiplication(new int[] { 6, 8}, new int[] { 6, 8}));* } ---- In this test method you use the JUnit ``assertEquals`` method. To use the assertion, you supply the input variables and the expected result. To pass the test, the test method must successfully return all the expected results based on the supplied variables when running the tested method. You should add a sufficient number of assertions to cover the various possible permutations. . Change the name of the ``testEqual`` test method to ``equalsCheck`` . . Delete the the generated method body of the ``equalsCheck`` test method. . Add the following ``println`` to the ``equalsCheck`` test method.*System.out.println(""* VectorsJUnit4Test: equalsCheck()"");* The test method should now look like the following: [source,java] ---- @Test public void equalsCheck() { System.out.println(""* VectorsJUnit4Test: equalsCheck()""); } ---- . Modify the ``equalsCheck`` method by adding the following assertions (displayed in bold). [source,java] ---- @Test public void equalsCheck() { System.out.println(""* VectorsJUnit4Test: equalsCheck()""); *assertTrue(Vectors.equal(new int[] {}, new int[] {})); assertTrue(Vectors.equal(new int[] {0}, new int[] {0})); assertTrue(Vectors.equal(new int[] {0, 0}, new int[] {0, 0})); assertTrue(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 0})); assertTrue(Vectors.equal(new int[] {5, 6, 7}, new int[] {5, 6, 7})); assertFalse(Vectors.equal(new int[] {}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0})); assertFalse(Vectors.equal(new int[] {0, 0}, new int[] {0})); assertFalse(Vectors.equal(new int[] {0}, new int[] {})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 0, 1})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {0, 1, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 0}, new int[] {1, 0, 0})); assertFalse(Vectors.equal(new int[] {0, 0, 1}, new int[] {0, 0, 3}));* } ---- This test uses the JUnit ``assertTrue`` and ``assertFalse`` methods to test a variety of possible results. For the test of this method to pass, the ``assertTrue`` must all be true and ``assertFalse`` must all be false. Compare: <> === Creating a Test Class for ``Utils.java`` You will now create the JUnit test methods for ``Utils.java`` . When you created the test class in the previous exercise, the IDE prompted you for the version of JUnit. You are not prompted to select a version this time because you already selected the JUnit version and all subsequent JUnit tests are created in that version. NOTE: You can still write and run JUnit 3 tests if you select JUnit 4 as the version, but the IDE uses the JUnit 4 template for generating test skeletons. 1. Right-click ``Utils.java`` and choose Tools > Create Tests. 2. Select JUnit in the Framework dropdown list if not selected. 3. Select Test Initializer and Test Finalizer in the dialog box if not selected. 4. Modify the name of the test class to *UtilsJUnit4Test* in the Create Tests dialog box. Click OK. When you click OK, the IDE creates the test file ``UtilsJUnit4Test.java`` in the Test Packages > sample directory. You can see that the IDE generated the test methods ``testComputeFactorial`` , ``testConcatWords`` , and ``testNormalizeWord`` for the methods in ``Utils.java`` . The IDE also generated initializer and finalizer methods for the test and the test class. === Writing Test Methods for ``Utils.java`` In this exercise you will add test cases that illustrate some common JUnit test elements. You will also add a ``println`` to the methods because some methods do not print any output to the JUnit Test Results window to indicate that they were run, or to indicate that the method passed the test. By adding a ``println`` to the methods you can see if the methods were run and the order in which they were run. ==== Test Initializers and Finalizers When you created the test class for ``Utils.java`` the IDE generated annotated initializer and finalizer methods. You can choose any name for the name of the method because there is no required naming convention. NOTE: You do not need the initializer and finalizer methods to test ``Utils.java`` , but they are included in this tutorial to demonstrate how they work. In JUnit 4 you can use annotations to mark the following types of initializer and finalizer methods. * *Test Class Initializer.* The ``@BeforeClass`` annotation marks a method as a test class initialization method. A test class initialization method is run only once, and before any of the other methods in the test class. For example, instead of creating a database connection in a test initializer and creating a new connection before each test method, you may want to use a test class initializer to open a connection before running the tests. You could then close the connection with the test class finalizer. * *Test Class Finalizer.* The ``@AfterClass`` annotation marks a method as a test class finalizer method. A test class finalizer method is run only once, and after all of the other methods in the test class are finished. * *Test Initializer.* The ``@Before`` annotation marks a method as a test initialization method. A test initialization method is run before each test case in the test class. A test initialization method is not required to run tests, but if you need to initialize some variables before you run a test, you use a test initializer method. * *Test Finalizer.* The ``@After`` annotation marks a method as a test finalizer method. A test finalizer method is run after each test case in the test class. A test finalizer method is not required to run tests, but you may need a finalizer to clean up any data that was required when running the test cases. Make the following changes (displayed in bold) in ``UtilsJUnit4Test.java`` . [source,java] ---- @BeforeClass public static void setUpClass() throws Exception { *System.out.println(""* UtilsJUnit4Test: @BeforeClass method"");* } @AfterClass public static void tearDownClass() throws Exception { *System.out.println(""* UtilsJUnit4Test: @AfterClass method"");* } @Before public void setUp() { *System.out.println(""* UtilsJUnit4Test: @Before method"");* } @After public void tearDown() { *System.out.println(""* UtilsJUnit4Test: @After method"");* } ---- Compare: <> When you run the test class the ``println`` text you added is displayed in the output pane of the JUnit Test Results window. If you do not add the ``println`` , there is no output to indicate that the initializer and finalizer methods were run. ==== Testing Using a Simple Assertion This simple test case tests the ``concatWords`` method. Instead of using the generated test method ``testConcatWords`` , you will add a new test method called ``helloWorldCheck`` that uses a single simple assertion to test if the method concatenates the strings correctly. The ``assertEquals`` in the test case uses the syntax ``assertEquals(_EXPECTED_RESULT, ACTUAL_RESULT_)`` to test if the expected result is equal to the actual result. In this case, if the input to the method ``concatWords`` is "" ``Hello`` "", "" ``,`` "", "" ``world`` "" and "" ``!`` "", the expected result should equal ``""Hello, world!""`` . 1. Delete the generated test method ``testConcatWords`` . 2. Add the following ``helloWorldCheck`` method to test ``Utils.concatWords`` .*@Test public void helloWorldCheck() { assertEquals(""Hello, world!"", Utils.concatWords(""Hello"", "", "", ""world"", ""!"")); }* . Add a ``println`` statement to display text about the test in the JUnit Test Results window. [source,java] ---- @Test public void helloWorldCheck() { *System.out.println(""* UtilsJUnit4Test: test method 1 - helloWorldCheck()"");* assertEquals(""Hello, world!"", Utils.concatWords(""Hello"", "", "", ""world"", ""!"")); ---- Compare: <> ==== Testing Using a Timeout This test demonstrates how to check if a method is taking too long to complete. If the method is taking too long, the test thread is interrupted and the test fails. You can specify the time limit in the test. The test method invokes the ``computeFactorial`` method in ``Utils.java`` . You can assume that the ``computeFactorial`` method is correct, but in this case you want to test if the computation is completed within 1000 milliseconds. You do this by interrupting the test thread after 1000 milliseconds. If the thread is interrupted the test method throws a ``TimeoutException`` . 1. Delete the generated test method ``testComputeFactorial`` . 2. Add the ``testWithTimeout`` method that calculates the factorial of a randomly generated number.*@Test public void testWithTimeout() { final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println(""computing "" + factorialOf + '!'); System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); }* . Add the following code (displayed in bold) to set the timeout and to interrupt the thread if the method takes too long to execute. [source,java] ---- @Test*(timeout=1000)* public void testWithTimeout() { final int factorialOf = 1 + (int) (30000 * Math.random()); ---- You can see that the timeout is set to 1000 milliseconds. . Add the following ``println`` (displayed in bold) to print the text about the test in the JUnit Test Results window. [source,java] ---- @Test(timeout=1000) public void testWithTimeout() { *System.out.println(""* UtilsJUnit4Test: test method 2 - testWithTimeout()"");* final int factorialOf = 1 + (int) (30000 * Math.random()); System.out.println(""computing "" + factorialOf + '!'); ---- Compare: <> ==== Testing for an Expected Exception This test demonstrates how to test for an expected exception. The method fails if it does not throw the specified expected exception. In this case you are testing that the ``computeFactorial`` method throws an ``IllegalArgumentException`` if the input variable is a negative number (-5). 1. Add the following ``testExpectedException`` method that invokes the ``computeFactorial`` method with an input of -5.*@Test public void checkExpectedException() { final int factorialOf = -5; System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); }* . Add the following property (displayed in bold) to the ``@Test`` annotation to specify that the test is expected to throw ``IllegalArgumentException`` . [source,java] ---- @Test*(expected=IllegalArgumentException.class)* public void checkExpectedException() { final int factorialOf = -5; System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); } ---- . Add the following ``println`` (displayed in bold) to print the text about the test in the JUnit Test Results window. [source,java] ---- @Test (expected=IllegalArgumentException.class) public void checkExpectedException() { *System.out.println(""* UtilsJUnit4Test: test method 3 - checkExpectedException()"");* final int factorialOf = -5; System.out.println(factorialOf + ""! = "" + Utils.computeFactorial(factorialOf)); } ---- Compare: <> ==== Disabling a Test This test demonstrates how to temporarily disable a test method. In JUnit 4 you simply add the ``@Ignore`` annotation to disable the test. 1. Delete the generated test method ``testNormalizeWord`` . 2. Add the following test method to the test class.*@Test public void temporarilyDisabledTest() throws Exception { System.out.println(""* UtilsJUnit4Test: test method 4 - checkExpectedException()""); assertEquals(""Malm\\u00f6"", Utils.normalizeWord(""Malmo\\u0308"")); }* The test method ``temporarilyDisabledTest`` will run if you run the test class. . Add the ``@Ignore`` annotation (displayed in bold) above ``@Test`` to disable the test.*@Ignore* [source,java] ---- @Test public void temporarilyDisabledTest() throws Exception { System.out.println(""* UtilsJUnit4Test: test method 4 - checkExpectedException()""); assertEquals(""Malm\\u00f6"", Utils.normalizeWord(""Malmo\\u0308"")); } ---- . Fix your imports to import ``org.junit.Ignore`` . Compare: <> Now that you have written the tests you can run the test and see the test output in the JUnit Test Results window. === Running the Tests You can run JUnit tests on the entire application or on individual files and see the results in the IDE. The easiest way to run all the unit tests for the project is to choose Run > Test __ from the main menu. If you choose this method, the IDE runs all the test classes in the Test Packages. To run an individual test class, right-click the test class under the Test Packages node and choose Run File. 1. Right-click ``UtilsJUnit4Test.java`` in the Projects window. 2. Choose Test File. 3. Choose Window > IDE Tools > Test Results to open the Test Results window. When you run ``UtilsJUnit4Test.java`` the IDE only runs the tests in the test class. If the class passes all the tests you will see something similar to the following image in the JUnit Test Results window. [.feature] -- image:images/junit4-utilstest-pass-sm.png[role=""left"", link=""images/junit4-utilstest-pass.png""] -- In this image (click the image to see a larger image) you can see that the IDE ran the JUnit test on ``Utils.java`` and that the class passed all the tests. The left pane displays the results of the individual test methods and the right pane displays the test output. If you look at the output you can see the order that the tests were run. The ``println`` that you added to each of the test methods printed out the name of the test to Test Results window and the Output window. You can see that in ``UtilsJUnit4Test`` the test class initializer method annotated with ``@BeforeClass`` was run before any of the other methods and it was run only once. The test class finalizer method annotated with ``@AfterClass`` was run last, after all the other methods in the class. The test initializer method annotated with ``@Before`` was run before each test method. The controls in the left side of the Test Results window enable you to easily run the test again. You can use the filter to toggle between displaying all test results or only the failed tests. The arrows enable you to skip to the next failure or the previous failure. When you right-click a test result in the Test Results window, the popup menu enables you to choose to go to the test's source, run the test again or debug the test. The next step after creating your unit test classes is to create test suites. See <> to see how to run specified tests as a group so you do not have to run each test individually. == Creating Test Suites When creating tests for a project you will generally end up with many test classes. While you can run test classes individually or run all the tests in a project, in many cases you will want to run a subset of the tests or run tests in a specific order. You can do this by creating one or more test suites. For example, you can create test suites that test specific aspects of your code or specific conditions. A test suite is basically a class with a method that invokes the specified test cases, such as specific test classes, test methods in test classes and other test suites. A test suite can be included as part of a test class but best practices recommends creating individual test suite classes. You can create JUnit 3 and JUnit 4 test suites for your project manually or the IDE can generate the suites for you. When you use the IDE to generate a test suite, by default the IDE generates code to invoke all the test classes in the same package as the test suite. After the test suite is created you can modify the class to specify the tests you want to run as part of that suite. === Creating JUnit 3 Test Suites If you selected JUnit 3 as the version for your tests, the IDE can generate JUnit 3 test suites based on the test classes in the test package. In JUnit 3 you specify the test classes to include in the test suite by creating an instance of ``TestSuite`` and using the ``addTest`` method for each test. 1. Right-click the *JUnit-Sample* project node in the Projects window and choose New > Other to open the New File wizard. 2. Select Test Suite in the Unit Tests category. Click Next. 3. Type *JUnit3TestSuite* for the Class Name. 4. Select the ``sample`` package to create the test suite in the sample folder in the test packages folder. 5. Deselect Test Initializer and Test Finalizer. Click Finish. image::images/junit-testsuite-wizard.png[] When you click Finish, the IDE creates the test suite class in the ``sample`` package and opens the class in the editor. The test suite will contain the following code. [source,java] ---- public class JUnit3TestSuite extends TestCase { public JUnit3TestSuite(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(""JUnit3TestSuite""); return suite; } } ---- . Modify the ``suite()`` method to add the test classes that will be run as part of the suite. [source,java] ---- public JUnit3TestSuite(String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(""JUnit3TestSuite""); *suite.addTest(new TestSuite(sample.VectorsJUnit3Test.class)); suite.addTest(new TestSuite(sample.UtilsJUnit3Test.class));* return suite; } ---- . Save your changes. === Creating JUnit 4 Test Suites If you selected JUnit 4 for the version of your tests, the IDE can generate JUnit 4 test suites. JUnit 4 is back-compatible so you can run JUnit 4 test suites that contain JUnit 4 and JUnit 3 tests. In JUnit 4 test suites you specify the test classes to include as values of the ``@Suite`` annotation. NOTE: To run JUnit 3 test suites as part of a JUnit 4 test suite requires JUnit 4.4 or higher. 1. Right-click the project node in the Projects window and choose New > Other to open the New File wizard. 2. Select Test Suite in the Unit Tests category. Click Next. 3. Type *JUnit4TestSuite* for the file name. 4. Select the ``sample`` package to create the test suite in the sample folder in the test packages folder. 5. Deselect Test Initializer and Test Finalizer. Click Finish. When you click Finish, the IDE creates the test suite class in the ``sample`` package and opens the class in the editor. The test suite contains code similar to the following. [source,java] ---- @RunWith(Suite.class) @Suite.SuiteClasses(value={UtilsJUnit4Test.class, VectorsJUnit4Test.class}) public class JUnit4TestSuite { } ---- When you run the test suite the IDE will run the test classes in the order that they are listed. === Running Test Suites You run a test suite the same way you run any individual test class. 1. Expand the Test Packages node in the Projects window. 2. Right-click the test suite class and choose Test File. When you run the test suite the IDE runs the tests included in the suite in the order they are listed. The results are displayed in the JUnit Test Results window. [.feature] -- image:images/junit3-suite-results-sm.png[role=""left"", link=""images/junit3-suite-results.png""] -- In this image (click the image to see a larger image) you can see the test results for a JUnit 3 test suite. The test suite ran the ``UtilsJUnit3Test`` and ``VectorsJUnit3Test`` test classes as a single test and displayed the test results in the left pane as the results of a single test. The output in the right pane is the same as when you run the test individually. [.feature] -- image:images/junit4-suite-results-sm.png[role=""left"", link=""images/junit4-suite-results.png""] -- In this image (click the image to see a larger image) you can see the test results for a JUnit 4 test suite. The test suite ran the ``UtilsJUnit4Test`` and ``VectorsJUnit4Test`` test classes as a single test and displayed the test results in the left pane as the results of a single test. The output in the right pane is the same as when you run the test individually. [.feature] -- image:images/junitmix3and4-suite-results-sm.png[role=""left"", link=""images/junitmix3and4-suite-results.png""] -- In this image (click the image to see a larger image) you can see the test results for a mixed test suite. This test suite includes the JUnit 4 test suite and one of the JUnit 3 test classes. The test suite ran the ``UtilsJUnit3Test.java`` and ``JUnit4TestSuite.java`` test classes as a single test and displayed the test results in the left pane as the results of a single test. The output in the right pane is the same as running the test individually. == Conclusion This tutorial has given you a basic introduction to creating JUnit unit tests and test suites in NetBeans IDE. The IDE supports JUnit 3 and JUnit 4, and this document demonstrated some of the changes introduced in JUnit 4 that are designed to make creating and running tests simpler. As demonstrated in this tutorial, one of the main improvements in JUnit 4 is support for annotations. In JUnit 4 you can now use annotations to do the following: * Identify a test using the ``@Test`` annotation instead of naming convention * Identify ``setUp`` and ``tearDown`` methods with ``@Before`` and ``@After`` annotations * Identify ``setUp`` and ``tearDown`` methods that apply to the entire test class. Methods annotated with ``@BeforeClass`` are run only once, before any test methods in the class are run. Methods annotated with ``@AfterClass`` are also run only once, after all the test methods have finished. * Identify expected exceptions * Identify tests that should be skipped using the ``@Ignore`` annotation * Specify a timeout parameter for a test For more information about using JUnit and other changes introduced in JUnit 4, see the following resources: * link:http://tech.groups.yahoo.com/group/junit/[JUnit group at Yahoo groups] * link:http://www.junit.org[junit.org] Testing code often helps ensure that small changes made in the code do not break the application. Automated testing tools like JUnit streamline the process of testing and frequent testing can help catch coding errors early. ",12474,True,2818.1093757617555,median "[[scoreCalculation]] = Score calculation :doctype: book :imagesdir: .. :sectnums: :toc: left :icons: font :experimental: [[scoreTerminology]] == Score terminology [[whatIsAScore]] === What is a score? Every `@PlanningSolution` class has a score. The score is an objective way to compare two solutions. The solution with the higher score is better. The `Solver` aims to find the solution with the highest `Score` of all possible solutions. The _best solution_ is the solution with the highest `Score` that `Solver` has encountered during solving, which might be the __optimal solution__. OptaPlanner cannot automatically know which solution is best for your business, so you need to tell it how to calculate the score of a given `@PlanningSolution` instance according to your business needs. If you forget or are unable to implement an important business constraint, the solution is probably useless: image::ScoreCalculation/optimalWithIncompleteConstraints.png[align=""center""] [[formalizeTheBusinessConstraints]] === Formalize the business constraints To implement a verbal business constraint, it needs to be formalized as a score constraint. Luckily, defining constraints in OptaPlanner is very flexible through the following score techniques: * **Score signum (positive or negative)**: maximize or minimize a constraint type * **Score weight**: put a cost/profit on a constraint type * **Score level (hard, soft, ...)**: prioritize a group of constraint types * *Pareto scoring* (rarely used) Take the time to acquaint yourself with the first three techniques. Once you understand them, formalizing most business constraints becomes straightforward. [NOTE] ==== Do not presume that your business knows all its score constraints in advance. Expect score constraints to be added, changed or removed after the first releases. ==== [[scoreConstraintSignum]] === Score constraint signum (positive or negative) All score techniques are based on constraints. A constraint can be a simple pattern (such as __Maximize the apple harvest in the solution__) or a more complex pattern. A positive constraint is a constraint you want to maximize. A negative constraint is a constraint you want to minimize image::ScoreCalculation/positiveAndNegativeConstraints.png[align=""center""] The image above illustrates that **the optimal solution always has the highest score**, regardless if the constraints are positive or negative. Most planning problems have only negative constraints and therefore have a negative score. In that case, the score is the sum of the weight of the negative constraints being broken, with a perfect score of 0. For example in n queens, the score is the negative of the number of queen pairs which can attack each other. Negative and positive constraints can be combined, even in the same score level. When a constraint activates (because the negative constraint is broken or the positive constraint is fulfilled) on a certain planning entity set, it is called a __constraint match__. [[scoreConstraintWeight]] === Score constraint weight Not all score constraints are equally important. If breaking one constraint is equally bad as breaking another constraint x times, then those two constraints have a different weight (but they are in the same score level). For example in vehicle routing, you can make one _unhappy driver_ constraint match count as much as two _fuel tank usage_ constraint matches: image::ScoreCalculation/scoreWeighting.png[align=""center""] Score weighting is easy in use cases where you can __put a price tag on everything__. In that case, the positive constraints maximize revenue and the negative constraints minimize expenses, so together they maximize profit. Alternatively, score weighting is also often used to create social <>. For example, a nurse, who requests a free day, pays a higher weight on New Years eve than on a normal day. The weight of a constraint match can depend on the planning entities involved. For example in cloud balancing, the weight of the soft constraint match for an active `Computer` is the maintenance `cost` of that `Computer` (which differs per computer). Putting a good weight on a constraint is often a difficult analytical decision, because it is about making choices and trade-offs against other constraints. Different stakeholders have different priorities. *Don't waste time with constraint weight discussions at the start of an implementation, instead add a <> and allow users to change them through a UI.* A non-accurate weight is less damaging than mediocre algorithms: image::ScoreCalculation/scoreTradeoffInPerspective.png[align=""center""] Most use cases use a `Score` with `int` weights, such as <>. [[scoreLevel]] === Score constraint level (hard, soft, ...) Sometimes a score constraint outranks another score constraint, no matter how many times the latter is broken. In that case, those score constraints are in different levels. For example, a nurse cannot do two shifts at the same time (due to the constraints of physical reality), so this outranks all nurse happiness constraints. Most use cases have only two score levels, hard and soft. The levels of two scores are compared lexicographically. The first score level gets compared first. If those differ, the remaining score levels are ignored. For example, a score that breaks `0` hard constraints and `1000000` soft constraints is better than a score that breaks `1` hard constraint and `0` soft constraints. image::ScoreCalculation/scoreLevels.png[align=""center""] If there are two (or more) score levels, for example <>, then a score is _feasible_ if no hard constraints are broken. [NOTE] ==== By default, OptaPlanner will always assign all planning variables a planning value. If there is no feasible solution, this means the best solution will be infeasible. To instead leave some of the planning entities unassigned, apply <>. ==== For each constraint, you need to pick a score level, a score weight and a score signum. For example: `-1soft` which has score level of ``soft``, a weight of `1` and a negative signum. Do not use a big constraint weight when your business actually wants different score levels. That hack, known as __score folding__, is broken: image::ScoreCalculation/scoreFoldingIsBroken.png[align=""center""] [NOTE] ==== Your business might tell you that your hard constraints all have the same weight, because they cannot be broken (so the weight does not matter). This is not true because if no feasible solution exists for a specific dataset, the least infeasible solution allows the business to estimate how many business resources they are lacking. For example in cloud balancing, how many new computers to buy. Furthermore, it will likely create a <>. For example in cloud balance if a `Computer` has seven CPU too little for its ``Process``es, then it must be weighted seven times as much as if it had only one CPU too little. ==== Three or more score levels are also supported. For example: a company might decide that profit outranks employee satisfaction (or vice versa), while both are outranked by the constraints of physical reality. [NOTE] ==== To model <>, there is no need to use lots of score levels (even though OptaPlanner can handle many score levels). ==== Most use cases use a `Score` with two or three weights, such as <> and <>. [[paretoScoring]] === Pareto scoring (AKA multi-objective optimization scoring) Far less common is the use case of pareto optimization, which is also known as _multi-objective optimization_. In pareto scoring, score constraints are in the same score level, yet they are not weighted against each other. When two scores are compared, each of the score constraints are compared individually and the score with the most dominating score constraints wins. Pareto scoring can even be combined with score levels and score constraint weighting. Consider this example with positive constraints, where we want to get the most apples and oranges. Since it is impossible to compare apples and oranges, we cannot weigh them against each other. Yet, despite that we cannot compare them, we can state that two apples are better than one apple. Similarly, we can state that two apples and one orange are better than just one orange. So despite our inability to compare some Scores conclusively (at which point we declare them equal), we can find a set of optimal scores. Those are called pareto optimal. image::ScoreCalculation/paretoOptimizationScoring.png[align=""center""] Scores are considered equal far more often. It is left up to a human to choose the better out of a set of best solutions (with equal scores) found by OptaPlanner. In the example above, the user must choose between solution A (three apples and one orange) and solution B (one apple and six oranges). It is guaranteed that OptaPlanner has not found another solution which has more apples or more oranges or even a better combination of both (such as two apples and three oranges). To implement pareto scoring in OptaPlanner, <> (and replace the ``BestSolutionRecaller``). Future versions will provide out-of-the-box support. [NOTE] ==== A pareto ``Score``'s `compareTo` method is not transitive because it does a pareto comparison. For example: having two apples is greater than one apple. One apple is equal to One orange. Yet, two apples are not greater than one orange (but actually equal). Pareto comparison violates the contract of the interface ``java.lang.Comparable``'s `compareTo` method, but Planners systems are __pareto comparison safe__, unless explicitly stated otherwise in this documentation. ==== [[combiningScoreTechniques]] === Combining score techniques All the score techniques mentioned above, can be combined seamlessly: image::ScoreCalculation/scoreComposition.png[align=""center""] [[scoreInterface]] === `Score` interface A score is represented by the `Score` interface, which naturally extends ``Comparable``: [source,java,options=""nowrap""] ---- public interface Score<...> extends Comparable<...> { ... } ---- The `Score` implementation to use depends on your use case. Your score might not efficiently fit in a single `long` value. OptaPlanner has several built-in `Score` implementations, but you can implement a custom `Score` too. Most use cases tend to use the built-in ``HardSoftScore``. image::ScoreCalculation/scoreClassDiagram.png[align=""center""] All Score implementations also have an `initScore` (which is an ``int``).It is mostly intended for internal use in OptaPlanner: it is the negative number of uninitialized planning variables. From a user's perspective this is ``0``, unless a Construction Heuristic is terminated before it could initialize all planning variables (in which case `Score.isSolutionInitialized()` returns ``false``). The `Score` implementation (for example ``HardSoftScore``) must be the same throughout a `Solver` runtime. The `Score` implementation is configured in the solution domain class: [source,java,options=""nowrap""] ---- @PlanningSolution public class CloudBalance { ... @PlanningScore private HardSoftScore score; } ---- [[avoidFloatingPointNumbersInScoreCalculation]] === Avoid floating point numbers in score calculation Avoid the use of `float` or `double` in score calculation. Use `BigDecimal` or scaled `long` instead. Floating point numbers (``float`` and ``double``) cannot represent a decimal number correctly. For example: a `double` cannot hold the value `0.05` correctly. Instead, it holds the nearest representable value. Arithmetic (including addition and subtraction) with floating point numbers, especially for planning problems, leads to incorrect decisions: image::ScoreCalculation/scoreWeightType.png[align=""center""] Additionally, floating point number addition is not associative: [source,java,options=""nowrap""] ---- System.out.println( ((0.01 + 0.02) + 0.03) == (0.01 + (0.02 + 0.03)) ); // returns false ---- This leads to __score corruption__. Decimal numbers (``BigDecimal``) have none of these problems. [NOTE] ==== BigDecimal arithmetic is considerably slower than ``int``, `long` or `double` arithmetic. In experiments we have seen the score calculation take five times longer. Therefore, in many cases, it can be worthwhile to multiply _all_ numbers for a single score weight by a plural of ten, so the score weight fits in a scaled `int` or ``long``. For example, if we multiply all weights by ``1000``, a fuelCost of `0.07` becomes a fuelCostMillis of `70` and no longer uses a decimal score weight. ==== [[scoreType]] == Choose a score type Depending on the number of score levels and type of score weights you need, choose a `Score` type. Most use cases use a ``HardSoftScore``. [NOTE] ==== To properly write a `Score` to a database (with JPA/Hibernate) or to XML/JSON (with XStream/JAXB/Jackson), see <>. ==== [[simpleScore]] === `SimpleScore` A `SimpleScore` has a single `int` value, for example ``-123``. It has a single score level. [source,java,options=""nowrap""] ---- @PlanningScore private SimpleScore score; ---- Variants of this `Score` type: * `SimpleLongScore` uses a `long` value instead of an `int` value. * `SimpleBigDecimalScore` uses a `BigDecimal` value instead of an `int` value. [[hardSoftScore]] === `HardSoftScore` (Recommended) A `HardSoftScore` has a hard `int` value and a soft `int` value, for example ``-123hard/-456soft``. It has two score levels (hard and soft). [source,java,options=""nowrap""] ---- @PlanningScore private HardSoftScore score; ---- Variants of this `Score` type: * `HardSoftLongScore` uses `long` values instead of `int` values. * `HardSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[hardMediumSoftScore]] === `HardMediumSoftScore` A `HardMediumSoftScore` which has a hard `int` value, a medium `int` value and a soft `int` value, for example ``-123hard/-456medium/-789soft``. It has three score levels (hard, medium and soft). The hard level determines if the solution is feasible, and the medium level and soft level score values determine how well the solution meets business goals. Higher medium values take precedence over soft values irrespective of the soft value. [source,java,options=""nowrap""] ---- @PlanningScore private HardMediumSoftScore score; ---- Variants of this `Score` type: * `HardMediumSoftLongScore` uses `long` values instead of `int` values. * `HardMediumSoftBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[bendableScore]] === `BendableScore` A `BendableScore` has a configurable number of score levels. It has an array of hard `int` values and an array of soft `int` values, for example with two hard levels and three soft levels, the score can be ``[-123/-456]hard/[-789/-012/-345]soft``. In that case, it has five score levels. A solution is feasible if all hard levels are at least zero. A BendableScore with one hard level and one soft level is equivalent to a HardSoftScore, while a BendableScore with one hard level and two soft levels is equivalent to a HardMediumSoftScore. [source,java,options=""nowrap""] ---- @PlanningScore(bendableHardLevelsSize = 2, bendableSoftLevelsSize = 3) private BendableScore score; ---- The number of hard and soft score levels need to be set at compilation time. It is not flexible to change during solving. [NOTE] ==== Do not use a `BendableScore` with seven levels just because you have seven constraints. It is extremely rare to use a different score level for each constraint, because that means one constraint match on soft 0 outweighs even a million constraint matches of soft 1. Usually, multiple constraints share the same level and are weighted against each other. Use <> to get the weight of individual constraints in the same level. ==== Variants of this `Score` type: * `BendableLongScore` uses `long` values instead of `int` values. * `BendableBigDecimalScore` uses `BigDecimal` values instead of `int` values. [[customScore]] === Implementing a custom score Internally, each `Score` implementation also has a `ScoreDefinition` implementation. For example: `SimpleScore` is defined by ``SimpleScoreDefinition``. The `ScoreDefinition` interface defines the score representation. To implement a custom ``Score``, also implement such a custom ``ScoreDefinition``. Extend `AbstractScoreDefinition` (preferably by copy pasting ``HardSoftScoreDefinition``) and start from there. Then hook your custom `ScoreDefinition` in the domain: [source,java,options=""nowrap""] ---- @PlanningScore(scoreDefinitionClass = MyCustomScoreDefinition.class) private MyCustomScore score; ---- To have it integrate seamlessly with <>, <>, <>, ..., you'll need to write custom glue code too. [[calculateTheScore]] == Calculate the `Score` [[scoreCalculationTypes]] === Score calculation types There are several ways to calculate the `Score` of a solution: * **<>**: Implement all constraints together in a single method in Java (or another JVM language). Does not scale. * **<>**: Implement each constraint as a separate Constraint Stream in Java (or another JVM language). Fast and scalable. * **<>** (not recommended): Implement multiple low-level methods in Java (or another JVM language). Fast and scalable. Very difficult to implement and maintain. * **<>**: Implement each constraint as a separate score rule in DRL. Scalable. Every score calculation type can work with any Score definition (such as ``HardSoftScore`` or ``HardMediumSoftScore``). All score calculation types are Object Oriented and can reuse existing Java code. [IMPORTANT] ==== The score calculation must be read-only. It must not change the planning entities or the problem facts in any way. For example, it must not call a setter method on a planning entity in the score calculation. OptaPlanner does not recalculate the score of a solution if it can predict it (unless an <> is enabled). For example, after a winning step is done, there is no need to calculate the score because that move was done and undone earlier. As a result, there is no guarantee that changes applied during score calculation actually happen. To update planning entities when the planning variable change, use <> instead. ==== [[easyJavaScoreCalculation]] === Easy Java score calculation An easy way to implement your score calculation in Java. * Advantages: ** Plain old Java: no learning curve ** Opportunity to delegate score calculation to an existing code base or legacy system * Disadvantages: ** Slower ** Does not scale because there is no <> Implement the one method of the interface ``EasyScoreCalculator``: [source,java,options=""nowrap""] ---- public interface EasyScoreCalculator> { Score_ calculateScore(Solution_ solution); } ---- For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensEasyScoreCalculator implements EasyScoreCalculator { @Override public SimpleScore calculateScore(NQueens nQueens) { int n = nQueens.getN(); List queenList = nQueens.getQueenList(); int score = 0; for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { Queen leftQueen = queenList.get(i); Queen rightQueen = queenList.get(j); if (leftQueen.getRow() != null && rightQueen.getRow() != null) { if (leftQueen.getRowIndex() == rightQueen.getRowIndex()) { score--; } if (leftQueen.getAscendingDiagonalIndex() == rightQueen.getAscendingDiagonalIndex()) { score--; } if (leftQueen.getDescendingDiagonalIndex() == rightQueen.getDescendingDiagonalIndex()) { score--; } } } } return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- To configure values of an `EasyScoreCalculator` dynamically in the solver configuration (so the <> can tweak those parameters), add the `easyScoreCalculatorCustomProperties` element and use <>: [source,xml,options=""nowrap""] ---- ...MyEasyScoreCalculator ---- [[incrementalJavaScoreCalculation]] === Incremental Java score calculation A way to implement your score calculation incrementally in Java. * Advantages: ** Very fast and scalable *** Currently the fastest if implemented correctly * Disadvantages: ** Hard to write *** A scalable implementation heavily uses maps, indexes, ... (things the Drools rule engine can do for you) *** You have to learn, design, write and improve all these performance optimizations yourself ** Hard to read *** Regular score constraint changes can lead to a high maintenance cost Implement all the methods of the interface `IncrementalScoreCalculator`: [source,java,options=""nowrap""] ---- public interface IncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution); void beforeEntityAdded(Object entity); void afterEntityAdded(Object entity); void beforeVariableChanged(Object entity, String variableName); void afterVariableChanged(Object entity, String variableName); void beforeEntityRemoved(Object entity); void afterEntityRemoved(Object entity); Score_ calculateScore(); } ---- image::ScoreCalculation/incrementalScoreCalculatorSequenceDiagram.png[align=""center""] For example in n queens: [source,java,options=""nowrap""] ---- public class NQueensAdvancedIncrementalScoreCalculator extends IncrementalScoreCalculator { private Map> rowIndexMap; private Map> ascendingDiagonalIndexMap; private Map> descendingDiagonalIndexMap; private int score; public void resetWorkingSolution(NQueens nQueens) { int n = nQueens.getN(); rowIndexMap = new HashMap>(n); ascendingDiagonalIndexMap = new HashMap>(n * 2); descendingDiagonalIndexMap = new HashMap>(n * 2); for (int i = 0; i < n; i++) { rowIndexMap.put(i, new ArrayList(n)); ascendingDiagonalIndexMap.put(i, new ArrayList(n)); descendingDiagonalIndexMap.put(i, new ArrayList(n)); if (i != 0) { ascendingDiagonalIndexMap.put(n - 1 + i, new ArrayList(n)); descendingDiagonalIndexMap.put((-i), new ArrayList(n)); } } score = 0; for (Queen queen : nQueens.getQueenList()) { insert(queen); } } public void beforeEntityAdded(Object entity) { // Do nothing } public void afterEntityAdded(Object entity) { insert((Queen) entity); } public void beforeVariableChanged(Object entity, String variableName) { retract((Queen) entity); } public void afterVariableChanged(Object entity, String variableName) { insert((Queen) entity); } public void beforeEntityRemoved(Object entity) { retract((Queen) entity); } public void afterEntityRemoved(Object entity) { // Do nothing } private void insert(Queen queen) { Row row = queen.getRow(); if (row != null) { int rowIndex = queen.getRowIndex(); List rowIndexList = rowIndexMap.get(rowIndex); score -= rowIndexList.size(); rowIndexList.add(queen); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); score -= ascendingDiagonalIndexList.size(); ascendingDiagonalIndexList.add(queen); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); score -= descendingDiagonalIndexList.size(); descendingDiagonalIndexList.add(queen); } } private void retract(Queen queen) { Row row = queen.getRow(); if (row != null) { List rowIndexList = rowIndexMap.get(queen.getRowIndex()); rowIndexList.remove(queen); score += rowIndexList.size(); List ascendingDiagonalIndexList = ascendingDiagonalIndexMap.get(queen.getAscendingDiagonalIndex()); ascendingDiagonalIndexList.remove(queen); score += ascendingDiagonalIndexList.size(); List descendingDiagonalIndexList = descendingDiagonalIndexMap.get(queen.getDescendingDiagonalIndex()); descendingDiagonalIndexList.remove(queen); score += descendingDiagonalIndexList.size(); } } public SimpleScore calculateScore() { return SimpleScore.valueOf(score); } } ---- Configure it in the solver configuration: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.nqueens.optional.score.NQueensAdvancedIncrementalScoreCalculator ---- [IMPORTANT] ==== A piece of incremental score calculator code can be difficult to write and to review. <> by using an ``EasyScoreCalculator`` to fulfill the assertions triggered by the ``environmentMode``. ==== To configure values of an `IncrementalScoreCalculator` dynamically in the solver configuration (so the <> can tweak those parameters), add the `incrementalScoreCalculatorCustomProperties` element and use <>: [source,xml,options=""nowrap""] ---- ...MyIncrementalScoreCalculator ---- [[constraintMatchAwareIncrementalScoreCalculator]] ==== `ConstraintMatchAwareIncrementalScoreCalculator` Optionally, also implement the `ConstraintMatchAwareIncrementalScoreCalculator` interface to: * Explain a score by splitting it up per score constraint with `ScoreExplanation.getConstraintMatchTotalMap()`. * Visualize or sort planning entities by how many constraints each one breaks with `ScoreExplanation.getIndictmentMap()`. * Receive a detailed analysis if the `IncrementalScoreCalculator` is corrupted in `FAST_ASSERT` or `FULL_ASSERT` `environmentMode`, [source,java,options=""nowrap""] ---- public interface ConstraintMatchAwareIncrementalScoreCalculator> { void resetWorkingSolution(Solution_ workingSolution, boolean constraintMatchEnabled); Collection> getConstraintMatchTotals(); Map> getIndictmentMap(); } ---- For example in machine reassignment, create one `ConstraintMatchTotal` per constraint type and call `addConstraintMatch()` for each constraint match: [source,java,options=""nowrap""] ---- public class MachineReassignmentIncrementalScoreCalculator implements ConstraintMatchAwareIncrementalScoreCalculator { ... @Override public void resetWorkingSolution(MachineReassignment workingSolution, boolean constraintMatchEnabled) { resetWorkingSolution(workingSolution); // ignore constraintMatchEnabled, it is always presumed enabled } @Override public Collection> getConstraintMatchTotals() { ConstraintMatchTotal maximumCapacityMatchTotal = new DefaultConstraintMatchTotal<>(CONSTRAINT_PACKAGE, ""maximumCapacity"", HardSoftLongScore.ZERO); ... for (MrMachineScorePart machineScorePart : machineScorePartMap.values()) { for (MrMachineCapacityScorePart machineCapacityScorePart : machineScorePart.machineCapacityScorePartList) { if (machineCapacityScorePart.maximumAvailable < 0L) { maximumCapacityMatchTotal.addConstraintMatch( Arrays.asList(machineCapacityScorePart.machineCapacity), HardSoftLongScore.valueOf(machineCapacityScorePart.maximumAvailable, 0)); } } } ... List> constraintMatchTotalList = new ArrayList<>(4); constraintMatchTotalList.add(maximumCapacityMatchTotal); ... return constraintMatchTotalList; } @Override public Map> getIndictmentMap() { return null; // Calculate it non-incrementally from getConstraintMatchTotals() } } ---- That `getConstraintMatchTotals()` code often duplicates some of the logic of the normal `IncrementalScoreCalculator` methods. Constraint Streams and Drools Score Calculation don't have this disadvantage, because they are constraint match aware automatically when needed, without any extra domain-specific code. [[initializingScoreTrend]] === `InitializingScoreTrend` The `InitializingScoreTrend` specifies how the Score will change as more and more variables are initialized (while the already initialized variables do not change). Some optimization algorithms (such Construction Heuristics and Exhaustive Search) run faster if they have such information. For the Score (or each <> separately), specify a trend: * `ANY` (default): Initializing an extra variable can change the score positively or negatively. Gives no performance gain. * `ONLY_UP` (rare): Initializing an extra variable can only change the score positively. Implies that: ** There are only positive constraints ** And initializing the next variable cannot unmatch a positive constraint that was matched by a previous initialized variable. * ``ONLY_DOWN``: Initializing an extra variable can only change the score negatively. Implies that: ** There are only negative constraints ** And initializing the next variable cannot unmatch a negative constraint that was matched by a previous initialized variable. Most use cases only have negative constraints. Many of those have an `InitializingScoreTrend` that only goes down: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN ---- Alternatively, you can also specify the trend for each score level separately: [source,xml,options=""nowrap""] ---- org.optaplanner.examples.cloudbalancing.score.CloudBalancingConstraintProvider ONLY_DOWN/ONLY_DOWN ---- [[invalidScoreDetection]] === Invalid score detection When you put the <> in `FULL_ASSERT` (or ``FAST_ASSERT``), it will detect score corruption in the <>. However, that will not verify that your score calculator actually implements your score constraints as your business desires. For example, one constraint might consistently match the wrong pattern. To verify the constraints against an independent implementation, configure a ``assertionScoreDirectorFactory``: [source,xml,options=""nowrap""] ---- FAST_ASSERT ... org.optaplanner.examples.nqueens.optional.score.NQueensConstraintProviderorg.optaplanner.examples.nqueens.optional.score.NQueensConstraintProvider org.optaplanner.examples.nqueens.optional.score.NQueensEasyScoreCalculator ---- This way, the `NQueensConstraintProvider` implementation is validated by the ``EasyScoreCalculator``. [NOTE] ==== This works well to isolate score corruption, but to verify that the constraint implement the real business needs, <> is usually better. ==== [[scoreCalculationPerformanceTricks]] == Score calculation performance tricks [[scoreCalculationPerformanceTricksOverview]] === Overview The `Solver` will normally spend most of its execution time running the score calculation (which is called in its deepest loops). Faster score calculation will return the same solution in less time with the same algorithm, which normally means a better solution in equal time. [[scoreCalculationSpeed]] === Score calculation speed After solving a problem, the `Solver` will log the __score calculation speed per second__. This is a good measurement of Score calculation performance, despite that it is affected by non score calculation execution time. It depends on the problem scale of the problem dataset. Normally, even for high scale problems, it is higher than ``1000``, except if you are using an ``EasyScoreCalculator``. [IMPORTANT] ==== When improving your score calculation, focus on maximizing the score calculation speed, instead of maximizing the best score. A big improvement in score calculation can sometimes yield little or no best score improvement, for example when the algorithm is stuck in a local or global optima. If you are watching the calculation speed instead, score calculation improvements are far more visible. Furthermore, watching the calculation speed allows you to remove or add score constraints, and still compare it with the original's calculation speed. Comparing the best score with the original's best score is pointless: it's comparing apples and oranges. ==== [[incrementalScoreCalculation]] === Incremental score calculation (with deltas) When a solution changes, incremental score calculation (AKA delta based score calculation) calculates the delta with the previous state to find the new ``Score``, instead of recalculating the entire score on every solution evaluation. For example, when a single queen A moves from row `1` to ``2``, it will not bother to check if queen B and C can attack each other, since neither of them changed: image::ScoreCalculation/incrementalScoreCalculationNQueens04.png[align=""center""] Similarly in employee rostering: image::ScoreCalculation/incrementalScoreCalculationEmployeeRostering.png[align=""center""] This is a huge performance and scalability gain. *<> or <> give you this huge scalability gain without forcing you to write a complicated incremental score calculation algorithm.* Just let the rule engine do the hard work. Notice that the speedup is relative to the size of your planning problem (your __n__), making incremental score calculation far more scalable. [[avoidCallingRemoteServicesDuringScoreCalculation]] === Avoid calling remote services during score calculation Do not call remote services in your score calculation (except if you are bridging `EasyScoreCalculator` to a legacy system). The network latency will kill your score calculation performance. Cache the results of those remote services if possible. If some parts of a constraint can be calculated once, when the `Solver` starts, and never change during solving, then turn them into <>. [[pointlessConstraints]] === Pointless constraints If you know a certain constraint can never be broken (or it is always broken), do not write a score constraint for it. For example in n queens, the score calculation does not check if multiple queens occupy the same column, because a ``Queen``'s `column` never changes and every solution starts with each `Queen` on a different ``column``. [NOTE] ==== Do not go overboard with this. If some datasets do not use a specific constraint but others do, just return out of the constraint as soon as you can. There is no need to dynamically change your score calculation based on the dataset. ==== [[buildInHardConstraint]] === Built-in hard constraint Instead of implementing a hard constraint, it can sometimes be built in. For example, if `Lecture` A should never be assigned to `Room` X, but it uses `ValueRangeProvider` on Solution, so the `Solver` will often try to assign it to `Room` X too (only to find out that it breaks a hard constraint). Use <> or <> to define that Course A should only be assigned a `Room` different than X. This can give a good performance gain in some use cases, not just because the score calculation is faster, but mainly because most optimization algorithms will spend less time evaluating infeasible solutions. However, usually this is not a good idea because there is a real risk of trading short term benefits for long term harm: * Many optimization algorithms rely on the freedom to break hard constraints when changing planning entities, to get out of local optima. * Both implementation approaches have limitations (feature compatibility, disabling automatic performance optimizations), as explained in their documentation. [[otherScoreCalculationPerformanceTricks]] === Other score calculation performance tricks * Verify that your score calculation happens in the correct `Number` type. If you are making the sum of `int` values, do not sum it in a `double` which takes longer. * For optimal performance, always use server mode (``java -server``). We have seen performance increases of 50% by turning on server mode. * For optimal performance, use the latest Java version. For example, in the past we have seen performance increases of 30% by switching from java 1.5 to 1.6. * Always remember that premature optimization is the root of all evil. Make sure your design is flexible enough to allow configuration based tweaking. [[scoreTrap]] === Score trap Make sure that none of your score constraints cause a score trap. A trapped score constraint uses the same weight for different constraint matches, when it could just as easily use a different weight. It effectively lumps its constraint matches together, which creates a flatlined score function for that constraint. This can cause a solution state in which several moves need to be done to resolve or lower the weight of that single constraint. Some examples of score traps: * You need two doctors at each table, but you are only moving one doctor at a time. So the solver has no incentive to move a doctor to a table with no doctors. Punish a table with no doctors more than a table with only one doctor in that score constraint in the score function. * Two exams need to be conducted at the same time, but you are only moving one exam at a time. So the solver has to move one of those exams to another timeslot without moving the other in the same move. Add a coarse-grained move that moves both exams at the same time. For example, consider this score trap. If the blue item moves from an overloaded computer to an empty computer, the hard score should improve. The trapped score implementation fails to do that: image::ScoreCalculation/scoreTrap.png[align=""center""] The Solver should eventually get out of this trap, but it will take a lot of effort (especially if there are even more processes on the overloaded computer). Before they do that, they might actually start moving more processes into that overloaded computer, as there is no penalty for doing so. [NOTE] ==== Avoiding score traps does not mean that your score function should be smart enough to avoid local optima. Leave it to the optimization algorithms to deal with the local optima. Avoiding score traps means to avoid, for each score constraint individually, a flatlined score function. ==== [IMPORTANT] ==== Always specify the degree of infeasibility. The business will often say ""if the solution is infeasible, it does not matter how infeasible it is."" While that is true for the business, it is not true for score calculation as it benefits from knowing how infeasible it is. In practice, soft constraints usually do this naturally and it is just a matter of doing it for the hard constraints too. ==== There are several ways to deal with a score trap: * Improve the score constraint to make a distinction in the score weight. For example, penalize `-1hard` for every missing CPU, instead of just `-1hard` if any CPU is missing. * If changing the score constraint is not allowed from the business perspective, add a lower score level with a score constraint that makes such a distinction. For example, penalize `-1subsoft` for every missing CPU, on top of `-1hard` if any CPU is missing. The business ignores the subsoft score level. * Add coarse-grained moves and union select them with the existing fine-grained moves. A coarse-grained move effectively does multiple moves to directly get out of a score trap with a single move. For example, move multiple items from the same container to another container. [[stepLimitBenchmark]] === `stepLimit` benchmark Not all score constraints have the same performance cost. Sometimes one score constraint can kill the score calculation performance outright. Use the <> to do a one minute run and check what happens to the score calculation speed if you comment out all but one of the score constraints. [[fairnessScoreConstraints]] === Fairness score constraints Some use cases have a business requirement to provide a fair schedule (usually as a soft score constraint), for example: * Fairly distribute the workload amongst the employees, to avoid envy. * Evenly distribute the workload amongst assets, to improve reliability. Implementing such a constraint can seem difficult (especially because there are different ways to formalize fairness), but usually the _squared workload_ implementation behaves most desirable. For each employee/asset, count the workload `w` and subtract `w²` from the score. image::ScoreCalculation/fairnessScoreConstraint.png[align=""center""] As shown above, the _squared workload_ implementation guarantees that if you select two employees from a given solution and make their distribution between those two employees fairer, then the resulting new solution will have a better overall score. Do not just use the difference from the average workload, as that can lead to unfairness, as demonstrated below. image::ScoreCalculation/fairnessScoreConstraintPitfall.png[align=""center""] [NOTE] ==== Instead of the __squared workload__, it is also possible to use the https://en.wikipedia.org/wiki/Variance[variance] (squared difference to the average) or the http://en.wikipedia.org/wiki/Standard_deviation[standard deviation] (square root of the variance). This has no effect on the score comparison, because the average will not change during planning. It is just more work to implement (because the average needs to be known) and trivially slower (because the calculation is a bit longer). ==== When the workload is perfectly balanced, the user often likes to see a `0` score, instead of the distracting `-34soft` in the image above (for the last solution which is almost perfectly balanced). To nullify this, either add the average multiplied by the number of entities to the score or instead show the variance or standard deviation in the UI. [[constraintConfiguration]] == Constraint configuration: adjust constraint weights dynamically Deciding the correct <> and <> for each constraint is not easy. It often involves negotiating with different stakeholders and their priorities. Furthermore, quantifying the impact of soft constraints is often a new experience for business managers, so they 'll need a number of iterations to get it right. Don't get stuck between a rock and a hard place. Provide a UI to adjust the constraint weights and visualize the resulting solution, so the business managers can tweak the constraint weights themselves: image::ScoreCalculation/parameterizeTheScoreWeights.png[align=""center""] [[createAConstraintConfiguration]] === Create a constraint configuration First, create a new class to hold the constraint weights and other constraint parameters. Annotate it with `@ConstraintConfiguration`: [source,java,options=""nowrap""] ---- @ConstraintConfiguration public class ConferenceConstraintConfiguration { ... } ---- There will be exactly one instance of this class per planning solution. The planning solution and the constraint configuration have a one to one relationship, but they serve a different purpose, so they aren't merged into a single class. A `@ConstraintConfiguration` class can extend a parent `@ConstraintConfiguration` class, which can be useful in international use cases with many regional constraints. Add the constraint configuration on the planning solution and annotate that field or property with `@ConstraintConfigurationProvider`: [source,java,options=""nowrap""] ---- @PlanningSolution public class ConferenceSolution { @ConstraintConfigurationProvider private ConferenceConstraintConfiguration constraintConfiguration; ... } ---- The `@ConstraintConfigurationProvider` annotation automatically exposes the constraint configuration as a <>, there is no need to add a `@ProblemFactProperty` annotation. The constraint configuration class holds the <>, but it can also hold constraint parameters. For example in conference scheduling, the minimum pause constraint has a constraint weight (like any other constraint), but it also has a constraint parameter that defines the length of the minimum pause between two talks of the same speaker. That pause length depends on the conference (= the planning problem): in some big conferences 20 minutes isn't enough to go from one room to the other. That pause length is a field in the constraint configuration without a `@ConstraintWeight` annotation. [[constraintWeight]] === Add a constraint weight for each constraint In the constraint configuration class, add a `@ConstraintWeight` field or property for each constraint: [source,java,options=""nowrap""] ---- @ConstraintConfiguration(constraintPackage = ""...conferencescheduling.score"") public class ConferenceConstraintConfiguration { @ConstraintWeight(""Speaker conflict"") private HardMediumSoftScore speakerConflict = HardMediumSoftScore.ofHard(10); @ConstraintWeight(""Theme track conflict"") private HardMediumSoftScore themeTrackConflict = HardMediumSoftScore.ofSoft(10); @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ... } ---- The type of the constraint weights must be the same score class as <>. For example in conference scheduling, `ConferenceSolution.getScore()` and `ConferenceConstraintConfiguration.getSpeakerConflict()` both return a `HardMediumSoftScore`. A constraint weight cannot be null. Give each constraint weight a default value, but expose them in a UI so the business users can tweak them. The example above uses the `ofHard()`, `ofMedium()` and `ofSoft()` methods to do that. Notice how it defaults the _content conflict_ constraint as ten times more important than the _theme track conflict_ constraint. Normally, a constraint weight only uses one score level, but it's possible to use multiple score levels (at a small performance cost). Each constraint has a constraint package and a constraint name, together they form the constraint id. These connect the constraint weight with the constraint implementation. *For each constraint weight, there must be a constraint implementation with the same package and the same name.* * The `@ConstraintConfiguration` annotation has a `constraintPackage` property that defaults to the package of the constraint configuration class. Most cases with <>, need to override that because the DRLs use another package. For example, the DRL below uses the package `...conferencescheduling.score`, so the constraint configuration above specifies a `constraintPackage`. Cases with <>, normally don't need to specify it. * The `@ConstraintWeight` annotation has a `value` which is the constraint name (for example ""Speaker conflict""). It inherits the constraint package from the `@ConstraintConfiguration`, but it can override that, for example `@ConstraintWeight(constraintPackage = ""...region.france"", ...)` to use a different constraint package than some of the other weights. So every constraint weight ends up with a constraint package and a constraint name. Each constraint weight links with a constraint implementation, for example in <>: [source,options=""nowrap""] ---- package ...conferencescheduling.solver; rule ""Speaker conflict"" when ... then scoreHolder.penalize(kcontext); end rule ""Theme track conflict"" when ... then scoreHolder.penalize(kcontext, ...); end rule ""Content conflict"" when ... then scoreHolder.penalize(kcontext, ...); end ---- Each of the constraint weights defines the score level and score weight of their constraint. The constraint implementation calls `reward()` or `penalize()` and the constraint weight is automatically applied. If the constraint implementation provides a match weight, that *match weight is multiplied with the constraint weight*. For example, the _content conflict_ constraint weight defaults to `100soft` and the constraint implementation penalizes each match based on the number of shared content tags: [source,java,options=""nowrap""] ---- @ConstraintWeight(""Content conflict"") private HardMediumSoftScore contentConflict = HardMediumSoftScore.ofSoft(100); ---- [source,options=""nowrap""] ---- rule ""Content conflict"" when $talk1 : Talk(...) $talk2 : Talk(...) then scoreHolder.penalize(kcontext, $talk2.overlappingContentCount($talk1)); end ---- So when 2 overlapping talks share only 1 content tag, the score is impacted by `-100soft`. But when 2 overlapping talks share 3 content tags, the match weight is `3`, so the score is impacted by `-300soft`. [[explainingTheScore]] == Explaining the score: which constraints are broken? The easiest way to explain the score during development is to print the return value of `explainScore()`, but only use that method for diagnostic purposes: [source,java,options=""nowrap""] ---- System.out.println(scoreManager.explainScore(solution)); ---- For example in conference scheduling, this prints that talk `S51` is responsible for breaking the hard constraint `Speaker required room tag`: ---- Explanation of score (-1hard/-806soft): Constraint match totals: -1hard: constraint (Speaker required room tag) has 1 matches: -1hard: justifications ([S51]) -340soft: constraint (Theme track conflict) has 32 matches: -20soft: justifications ([S68, S66]) -20soft: justifications ([S61, S44]) ... ... Indictments (top 5 of 72): -1hard/-22soft: justification (S51) has 12 matches: -1hard: constraint (Speaker required room tag) -10soft: constraint (Theme track conflict) ... ... ---- [IMPORTANT] ==== Do not attempt to parse this string or use it in your UI or exposed services. Instead use the ConstraintMatch API below and do it properly. ==== [[usingScoreCalculationOutsideTheSolver]] === Using score calculation outside the `Solver` If other parts of your application, for example your webUI, need to calculate the score of a solution, use the `ScoreManager` API: [source,java,options=""nowrap""] ---- ScoreManager scoreManager = ScoreManager.create(solverFactory); ScoreExplanation scoreExplanation = scoreManager.explain(cloudBalance); ---- Then use it when you need to calculate the `Score` of a solution: [source,java,options=""nowrap""] ---- HardSoftScore score = scoreExplanation.getScore(); ---- Furthermore, the `ScoreExplanation` can help explain the score through constraint match totals and/or indictments: image::ScoreCalculation/scoreVisualization.png[align=""center""] [[constraintMatchTotal]] === Constraint match total: break down the score by constraint To break down the score per constraint, get the ``ConstraintMatchTotal``s from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Collection> constraintMatchTotals = scoreExplanation.getConstraintMatchTotalMap().values(); for (ConstraintMatchTotal constraintMatchTotal : constraintMatchTotals) { String constraintName = constraintMatchTotal.getConstraintName(); // The score impact of that constraint HardSoftScore totalScore = constraintMatchTotal.getScore(); for (ConstraintMatch constraintMatch : constraintMatchTotal.getConstraintMatchSet()) { List justificationList = constraintMatch.getJustificationList(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `ConstraintMatchTotal` represents one constraint and has a part of the overall score. The sum of all the `ConstraintMatchTotal.getScore()` equals the overall score. [NOTE] ==== <> and <> supports constraint matches automatically, but <> requires <>. ==== [[indictmentHeatMap]] === Indictment heat map: visualize the hot planning entities To show a heat map in the UI that highlights the planning entities and problem facts have an impact on the ``Score``, get the `Indictment` map from the ``ScoreExplanation``: [source,java,options=""nowrap""] ---- Map> indictmentMap = scoreExplanation.getIndictmentMap(); for (CloudProcess process : cloudBalance.getProcessList()) { Indictment indictment = indictmentMap.get(process); if (indictment == null) { continue; } // The score impact of that planning entity HardSoftScore totalScore = indictment.getScore(); for (ConstraintMatch constraintMatch : indictment.getConstraintMatchSet()) { String constraintName = constraintMatch.getConstraintName(); HardSoftScore score = constraintMatch.getScore(); ... } } ---- Each `Indictment` is the sum of all constraints where that justification object is involved with. The sum of all the `Indictment.getScoreTotal()` differs from the overall score, because multiple ``Indictment``s can share the same `ConstraintMatch`. [NOTE] ==== <> and <> supports constraint matches automatically, but <> requires <>. ==== [[testingScoreConstraints]] == Testing score constraints It's recommended to write a unit test for each score constraint individually to check that it behaves correctly. Different score calculation types come with different tools for testing. For more, see <> or <>. ",12093,False,2112.321205424248,median "#include ""nmos/connection_api.h"" #include #include #include ""cpprest/http_utils.h"" #include ""cpprest/json_validator.h"" #include ""nmos/activation_mode.h"" #include ""nmos/activation_utils.h"" #include ""nmos/api_downgrade.h"" #include ""nmos/api_utils.h"" #include ""nmos/is04_versions.h"" #include ""nmos/is05_versions.h"" #include ""nmos/json_schema.h"" #include ""nmos/media_type.h"" #include ""nmos/model.h"" #include ""nmos/sdp_utils.h"" #include ""nmos/slog.h"" #include ""nmos/transport.h"" #include ""nmos/thread_utils.h"" #include ""nmos/version.h"" #include ""sdp/sdp.h"" namespace nmos { web::http::experimental::listener::api_router make_unmounted_connection_api(nmos::node_model& model, transport_file_parser parse_transport_file, details::connection_resource_patch_validator validate_merged, slog::base_gate& gate); web::http::experimental::listener::api_router make_connection_api(nmos::node_model& model, transport_file_parser parse_transport_file, details::connection_resource_patch_validator validate_merged, slog::base_gate& gate) { using namespace web::http::experimental::listener::api_router_using_declarations; api_router connection_api; connection_api.support(U(""/?""), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U(""x-nmos/"") }, req, res)); return pplx::task_from_result(true); }); connection_api.support(U(""/x-nmos/?""), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U(""connection/"") }, req, res)); return pplx::task_from_result(true); }); const auto versions = with_read_lock(model.mutex, [&model] { return nmos::is05_versions::from_settings(model.settings); }); connection_api.support(U(""/x-nmos/"") + nmos::patterns::connection_api.pattern + U(""/?""), methods::GET, [versions](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body(nmos::make_api_version_sub_routes(versions), req, res)); return pplx::task_from_result(true); }); connection_api.mount(U(""/x-nmos/"") + nmos::patterns::connection_api.pattern + U(""/"") + nmos::patterns::version.pattern, make_unmounted_connection_api(model, parse_transport_file, validate_merged, gate)); return connection_api; } web::http::experimental::listener::api_router make_connection_api(nmos::node_model& model, slog::base_gate& gate) { return make_connection_api(model, &parse_rtp_transport_file, {}, gate); } inline bool is_connection_api_permitted_downgrade(const nmos::resource& resource, const nmos::resource& connection_resource, const nmos::api_version& version) { if (resource.version.major != version.major) return false; if (resource.version.minor <= version.minor) return true; // ""Where a transport type is added in a new version of the Connection Management API specification, earlier versioned APIs must not list any Senders or Receivers which make use of this new transport type."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/docs/5.0._Upgrade_Path.html#requirements-for-connection-management-apis typedef const std::map> versions_transport_bases_t; versions_transport_bases_t versions_transport_bases { { nmos::is05_versions::v1_0, { nmos::transports::rtp } }, { nmos::is05_versions::v1_1, { nmos::transports::websocket, nmos::transports::mqtt } } }; const nmos::transport transport_subclassification(nmos::fields::transport(resource.data)); const nmos::transport transport_base = nmos::transport_base(transport_subclassification); const auto first = versions_transport_bases.begin(); const auto last = versions_transport_bases.upper_bound(version); return last != std::find_if(first, last, [&transport_base](const versions_transport_bases_t::value_type& vtb) { return vtb.second.end() != vtb.second.find(transport_base); }); } inline utility::string_t make_connection_api_resource_location(const nmos::resource& resource, const utility::string_t& sub_path = {}) { return U(""/x-nmos/connection/"") + nmos::make_api_version(resource.version) + U(""/single/"") + nmos::resourceType_from_type(resource.type) + U(""/"") + resource.id + sub_path; } namespace details { static const web::json::experimental::json_validator& staged_core_validator() { // hmm, could be based on supported API versions from settings, like other APIs' validators? static const web::json::experimental::json_validator validator { nmos::experimental::load_json_schema, boost::copy_range>(boost::range::join( is05_versions::all | boost::adaptors::transformed(experimental::make_connectionapi_sender_staged_patch_request_schema_uri), is05_versions::all | boost::adaptors::transformed(experimental::make_connectionapi_receiver_staged_patch_request_schema_uri) )) }; return validator; } // Validate against specification schema // throws web::json::json_exception on failure, which results in a 400 Bad Request void validate_staged_core(const nmos::api_version& version, const nmos::type& type, const web::json::value& staged) { // Validate JSON syntax according to the schema staged_core_validator().validate(staged, experimental::make_connectionapi_staged_patch_request_schema_uri(version, type)); } // Extend an existing schema with ""auto"" as a valid value web::json::value make_auto_schema(const web::json::value& schema) { using web::json::value_of; const bool keep_order = true; return value_of({ { U(""anyOf""), value_of({ value_of({ { U(""type""), U(""string"") }, { U(""pattern""), U(""^auto$"") } }, keep_order), schema }) } }); } static const std::map>& rtp_auto_constraints() { // These are the constraints that support ""auto"" in /staged; cf. resolve_rtp_auto // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/sender_transport_params_rtp.html // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/receiver_transport_params_rtp.html static const std::map> auto_constraints { { nmos::types::sender, { nmos::fields::source_ip, nmos::fields::destination_ip, nmos::fields::source_port, nmos::fields::destination_port, nmos::fields::fec_destination_ip, nmos::fields::fec1D_destination_port, nmos::fields::fec2D_destination_port, nmos::fields::fec1D_source_port, nmos::fields::fec2D_source_port, nmos::fields::rtcp_destination_ip, nmos::fields::rtcp_destination_port, nmos::fields::rtcp_source_port } }, { nmos::types::receiver, { nmos::fields::interface_ip, nmos::fields::destination_port, nmos::fields::fec_destination_ip, nmos::fields::fec_mode, nmos::fields::fec1D_destination_port, nmos::fields::fec2D_destination_port, nmos::fields::rtcp_destination_ip, nmos::fields::rtcp_destination_port } } }; return auto_constraints; } static const std::map>& websocket_auto_constraints() { // These are the constraints that support ""auto"" in /staged // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/sender_transport_params_websocket.html // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/receiver_transport_params_websocket.html static const std::map> auto_constraints { { nmos::types::sender, { nmos::fields::connection_uri, nmos::fields::connection_authorization } }, { nmos::types::receiver, { nmos::fields::connection_authorization } } }; return auto_constraints; } static const std::map>& mqtt_auto_constraints() { // These are the constraints that support ""auto"" in /staged // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/sender_transport_params_mqtt.html // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/receiver_transport_params_mqtt.html static const std::map> auto_constraints { { nmos::types::sender, { nmos::fields::destination_host, nmos::fields::destination_port, nmos::fields::broker_protocol, nmos::fields::broker_authorization } }, { nmos::types::receiver, { nmos::fields::source_host, nmos::fields::source_port, nmos::fields::broker_protocol, nmos::fields::broker_authorization } } }; return auto_constraints; } static const std::map>& auto_constraints(const nmos::transport& transport_base) { if (nmos::transports::rtp == transport_base) return rtp_auto_constraints(); if (nmos::transports::websocket == transport_base) return websocket_auto_constraints(); if (nmos::transports::mqtt == transport_base) return mqtt_auto_constraints(); static const std::map> no_auto_constraints; return no_auto_constraints; } // Make a json schema from /constraints and /transporttype web::json::value make_constraints_schema(const nmos::type& type, const web::json::value& constraints, const nmos::transport& transport_base) { using web::json::value; using web::json::value_of; const bool keep_order = true; auto items = value::array(); auto& type_auto_constraints = auto_constraints(transport_base).at(type); for (const auto& leg : constraints.as_array()) { auto properties = value::object(); for (const auto& constraint : leg.as_object()) { if (type_auto_constraints.end() != type_auto_constraints.find(constraint.first)) { properties[constraint.first] = make_auto_schema(constraint.second); } else { properties[constraint.first] = constraint.second; } } web::json::push_back(items, value_of({ { U(""type""), U(""object"") }, { U(""properties""), properties } }, keep_order)); } return value_of({ { U(""$schema""), U(""http://json-schema.org/draft-04/schema#"") }, { U(""type""), U(""object"") }, { U(""properties""), value_of({ { U(""transport_params""), value_of({ { U(""type""), U(""array"") }, { U(""items""), items } }, keep_order) } }, keep_order) } }, keep_order); } // Validate staged endpoint against constraints void validate_staged_constraints(const nmos::type& type, const web::json::value& constraints, const nmos::transport& transport_base, const web::json::value& staged) { const auto schema = make_constraints_schema(type, constraints, transport_base); const auto uri = web::uri{ U(""/constraints"") }; // Validate staged JSON syntax according to the schema const web::json::experimental::json_validator validator { [&](const web::uri&) { return schema; }, { uri } }; // Validate JSON syntax according to the schema validator.validate(staged, uri); } // Apparently, the response to errors in the transport file should be 500 Internal Error rather than 400 Bad Request // See https://github.com/AMWA-TV/nmos-device-connection-management/issues/40 inline std::logic_error transport_file_error(const std::string& message) { return std::logic_error(""Transport file error - "" + message); } std::pair get_transport_type_data(const web::json::value& transport_file) { // ""'data' and 'type' must both be strings or both be null"" // See https://specs.amwa.tv/is-05/releases/v1.0.2/APIs/schemas/with-refs/v1.0-receiver-response-schema.html // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/receiver-transport-file.html if (!transport_file.has_field(nmos::fields::data)) throw transport_file_error(""data is required""); auto& transport_data = transport_file.at(nmos::fields::data); if (!transport_data.is_null()) { if (!transport_file.has_field(nmos::fields::type)) throw transport_file_error(""type is required""); auto& transport_type = transport_file.at(nmos::fields::type); if (transport_type.is_null() || transport_type.as_string().empty()) throw transport_file_error(""type is required""); return{ transport_type.as_string(), transport_data.as_string() }; } else { // Check for unexpected transport file type? In the future, could be a range of supported types... // Or only allow the type to be omitted? Or null? return{}; } } typedef std::pair connection_resource_patch_response; inline connection_resource_patch_response make_connection_resource_patch_error_response(web::http::status_code code, const utility::string_t& error = {}, const utility::string_t& debug = {}) { return{ code, make_error_response_body(code, error, debug) }; } inline connection_resource_patch_response make_connection_resource_patch_error_response(web::http::status_code code, const std::exception& debug) { return make_connection_resource_patch_error_response(code, {}, utility::s2us(debug.what())); } // Basic theory of implementation of PATCH /staged // // 1. Reject any patch, other than cancellation, when a scheduled activation is outstanding. // 2. Validate the patch, apply it and notify anyone who cares via model condition variable, e.g. a scheduling thread. // 3. Then return the response. // // That would work, except for those pesky immediate activations... // // Actual implementation of PATCH /staged // // Since immediate activations may take some time, we want to release the model lock so we can e.g. accept patch requests // on *other* senders or receivers. // But if we release the model lock at any point during an in-flight immediate activation, then we also have to handle // patch requests on the *same* sender or receiver arriving while this immediate activation is in flight. // And (according to the spec, probably) we're supposed to block rather than reject them... // // Similarly we also have to handle get requests while the immediate activation is in flight. Here there are two choices, // we need to either return the previous staged parameters or block until the immediate activation is completed. // Might as well do the latter, having necessarily implemented it for patch... // // To achieve this, we need to write something into the model to be able to identify when an immediate activation is in // flight, and when it's completed, i.e. a kind of 'per-resource lock'. // // We could choose a number of different ways of storing the in-flight activation 'lock' and data in the model, but what // I've done is to use the staged endpoint like this: // // * Activation mode is set to ""activate_immediate"". This is the per-resource 'lock' which allows concurrent patch and // get requests to be blocked (and therefore this in-flight state never to be returned). // * Activation requested_time is set to current timestamp. This uniquely identifies this immediate activation (in case // some other thread decides to trample all over our in-flight activation). // * Activation activation_time is set to null. This indicates this activation is not complete. // // Then notify the scheduling thread, release the model lock and wait for the immediate activation to be done. // // If it's successful, the activation_time should be set (e.g. by nmos::set_connection_resource_active) and will be used // in the response. // If it fails, the requested_time should be changed (e.g. set to null) so that an error response is sent; the mode must // also be set back to null to unblock concurrent patch operations (nmos::set_connection_resource_not_pending does both). // // This obviously requires co-operation from other threads that are manipulating these connection resources. // nmos::connection_activation_thread can usually be used to schedule sender/receiver activations. // // By the time we reacquire the model lock anything may have happened, but we can identify with the above whether to send // a success response or an error, and in the success case, release the 'per-resource lock' by updating the staged // activation mode, requested_time and activation_time. connection_resource_patch_response handle_connection_resource_patch(nmos::node_model& model, nmos::write_lock& lock, const nmos::api_version& version, const std::pair& id_type, const web::json::value& patch, const nmos::tai& request_time, transport_file_parser parse_transport_file, details::connection_resource_patch_validator validate_merged, slog::base_gate& gate) { using namespace web::http::experimental::listener::api_router_using_declarations; // lock.owns_lock() must be true initially auto& resources = model.connection_resources; // Validate JSON syntax according to the schema details::validate_staged_core(version, id_type.second, patch); const auto patch_state = details::get_activation_state(nmos::fields::activation(patch)); auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 and IS-05 resources not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { // Prevent changes to already-scheduled activations and in-flight immediate activations const auto& staged_activation = nmos::fields::activation(nmos::fields::endpoint_staged(resource->data)); const auto staged_state = details::get_activation_state(staged_activation); if (details::scheduled_activation_pending == staged_state && details::activation_not_pending != patch_state) { // ""When the resource is locked because an activation has been scheduled[, 423 Locked is returned]. // A resource may be unlocked by setting `mode` in `activation` to `null`."" slog::log(gate, SLOG_FLF) << ""Rejecting PATCH request for "" << id_type << "" due to a pending scheduled activation""; return details::make_connection_resource_patch_error_response(status_codes::Locked); } else if (details::immediate_activation_pending == staged_state) { const auto& requested_time_or_null = nmos::fields::requested_time(staged_activation); // ""If a 'bulk' request includes multiple sets of parameters for the same Sender or Receiver ID the behaviour is defined by the implementation. // In order to maximise interoperability clients are encouraged not to include the same Sender or Receiver ID multiple times in the same 'bulk' request."" // See https://specs.amwa.tv/is-05/releases/v1.0.2/docs/4.0._Behaviour.html#salvo-operation if (!requested_time_or_null.is_null() && request_time == web::json::as(requested_time_or_null)) { slog::log(gate, SLOG_FLF) << ""Rejecting PATCH request for "" << id_type << "" due to a pending immediate activation from the same bulk request""; return details::make_connection_resource_patch_error_response(status_codes::BadRequest); } // ""If an API implementation receives a new PATCH request to the /staged resource while an activation is in progress it SHOULD block the request until the previous activation is complete."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/docs/4.0._Behaviour.html#in-progress-activations else if (!details::wait_immediate_activation_not_pending(model, lock, id_type) || model.shutdown) { slog::log(gate, SLOG_FLF) << ""Rejecting PATCH request for "" << id_type << "" due to a pending immediate activation""; return details::make_connection_resource_patch_error_response(status_codes::InternalError); // or ServiceUnavailable? probably not NotFound even if that's true after the timeout? } // find resource again just in case, since waiting releases and reacquires the lock resource = find_resource(resources, id_type); } } else { // experimental extension, proposed for v1.1, to distinguish from Not Found return details::make_connection_resource_patch_error_response(status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); // hmm, no way to pass the Location header back } } if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 and IS-05 resources not found""); } // Merge this patch request into a *copy* of the current staged endpoint // so that the merged parameters can be validated against the constraints // before the current values are overwritten. // On successful staging/activation, this copy will also be used for the response. auto merged = nmos::fields::endpoint_staged(resource->data); // ""In the case where the transport file and transport parameters are updated in the same PATCH request // transport parameters specified in the request object take precedence over those in the transport file."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/APIs/ConnectionAPI.html#single_receivers__receiverid__staged_patch // ""In all other cases the most recently received PATCH request takes priority."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/4.1._Behaviour_-_RTP_Transport_Type.html#interpretation-of-sdp-files // First, validate and merge the transport file (this resource must be a receiver) // See https://specs.amwa.tv/is-05/releases/v1.0.0/APIs/ConnectionAPI.html#single_receivers__receiverid__staged_patch auto& transport_file = nmos::fields::transport_file(patch); if (!transport_file.is_null() && !transport_file.as_object().empty()) { const auto transport_type_data = details::get_transport_type_data(transport_file); if (!transport_type_data.first.empty()) { slog::log(gate, SLOG_FLF) << ""Processing transport file""; try { // Validate and parse the transport file for this receiver const auto transport_file_params = parse_transport_file(*matching_resource, *resource, transport_type_data.first, transport_type_data.second, gate); // Merge the transport file into the transport parameters auto& transport_params = nmos::fields::transport_params(merged); web::json::merge_patch(transport_params, transport_file_params); } catch (const web::json::json_exception& e) { throw transport_file_error(e.what()); } catch (const std::runtime_error& e) { throw transport_file_error(e.what()); } } } // Second, merge the transport parameters (in fact, all fields, including ""sender_id"", ""master_enabled"", etc.) web::json::merge_patch(merged, patch); // Then, prepare the activation response details::merge_activation(merged[nmos::fields::activation], nmos::fields::activation(patch), request_time); // Validate merged JSON according to the constraints slog::log(gate, SLOG_FLF) << ""Validating staged transport parameters against constraints""; const nmos::transport transport_subclassification(nmos::fields::transport(matching_resource->data)); details::validate_staged_constraints(resource->type, nmos::fields::endpoint_constraints(resource->data), nmos::transport_base(transport_subclassification), merged); // Perform any final validation if (validate_merged) { validate_merged(*matching_resource, *resource, merged, gate); } // Finally, update the staged endpoint modify_resource(resources, id_type.first, [&merged](nmos::resource& resource) { resource.data[nmos::fields::version] = web::json::value::string(nmos::make_version()); nmos::fields::endpoint_staged(resource.data) = merged; // In the case of an immediate activation, this is not yet a valid response // to a 'subsequent' GET request on the staged endpoint; that should be dealt with // by calling details::handle_immediate_activation_pending }); if (details::staging_only == patch_state) slog::log(gate, SLOG_FLF) << ""Staged endpoint updated for "" << id_type; else if (details::activation_not_pending == patch_state) slog::log(gate, SLOG_FLF) << ""Scheduled activation cancelled for "" << id_type; else if (details::scheduled_activation_pending == patch_state) slog::log(gate, SLOG_FLF) << ""Scheduled activation requested for "" << id_type; else if (details::immediate_activation_pending == patch_state) slog::log(gate, SLOG_FLF) << ""Immediate activation requested for "" << id_type; // details::notify_connection_resource_patch also needs to be called! return{ details::scheduled_activation_pending == patch_state ? status_codes::Accepted : status_codes::OK, std::move(merged) }; } else { return details::make_connection_resource_patch_error_response(status_codes::NotFound); } } void notify_connection_resource_patch(const nmos::node_model& model, slog::base_gate& gate) { slog::log(gate, SLOG_FLF) << ""Notifying connection activation thread""; model.notify(); } void handle_connection_resource_patch(web::http::http_response res, nmos::node_model& model, const nmos::api_version& version, const std::pair& id_type, const web::json::value& patch, transport_file_parser parse_transport_file, details::connection_resource_patch_validator validate_merged, slog::base_gate& gate) { auto lock = model.write_lock(); const auto request_time = tai_now(); // during write lock to ensure uniqueness auto result = handle_connection_resource_patch(model, lock, version, id_type, patch, request_time, parse_transport_file, validate_merged, gate); if (web::http::is_success_status_code(result.first)) { notify_connection_resource_patch(model, gate); // immediate activations need to be processed before sending the response if (details::immediate_activation_pending == details::get_activation_state(nmos::fields::activation(patch))) { details::handle_immediate_activation_pending(model, lock, id_type, result.second[nmos::fields::activation], gate); } set_reply(res, result.first, result.second); } else { // don't replace an existing response body which might contain richer error information set_reply(res, result.first, !result.second.is_null() ? result.second : nmos::make_error_response_body(result.first)); } } void handle_connection_resource_transportfile(web::http::http_response res, const nmos::node_model& model, const nmos::api_version& version, const std::pair& id_type, const utility::string_t& accept, slog::base_gate& gate) { using namespace web::http::experimental::listener::api_router_using_declarations; auto lock = model.read_lock(); auto& resources = model.connection_resources; auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 and IS-05 resources not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { auto& transportfile = nmos::fields::endpoint_transportfile(resource->data); if (!transportfile.is_null()) { // The transportfile endpoint data in the resource must have either ""data"" and ""type"", or an ""href"" for the redirect auto& data = nmos::fields::transportfile_data(transportfile); if (!data.is_null()) { slog::log(gate, SLOG_FLF) << ""Returning transport file for "" << id_type; const auto transportfile_type = nmos::fields::transportfile_type(transportfile); // hmm, parsing of the Accept header could be much better and should take account of quality values const auto accept_type = web::http::details::get_mime_type(accept); // allow application/json as well as the more precise application/sdp+json const std::set sdp_json_types{ nmos::media_types::application_json.name, nmos::media_types::application_sdp_json.name }; if (nmos::media_types::application_sdp.name == transportfile_type && 0 != sdp_json_types.count(accept_type)) { // Experimental extension - SDP as JSON res.headers().set_content_type(accept_type); set_reply(res, status_codes::OK, sdp::parse_session_description(utility::us2s(data.as_string()))); } else { // This automatically performs conversion to UTF-8 if required (i.e. on Windows) set_reply(res, status_codes::OK, data.as_string(), transportfile_type); } // ""It is strongly recommended that the following caching headers are included via the /transportfile endpoint (or whatever this endpoint redirects to). // This is important to ensure that connection management clients do not cache the contents of transport files which are liable to change."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/4.0._Behaviour.html#transport-files--caching res.headers().set_cache_control(U(""no-cache"")); } else { slog::log(gate, SLOG_FLF) << ""Redirecting to transport file for "" << id_type; set_reply(res, status_codes::TemporaryRedirect); res.headers().add(web::http::header_names::location, nmos::fields::transportfile_href(transportfile)); } } else { // Either this sender uses a transport type which does not require a transport file in which case a 404 response is required // or the sender does use a transport file, but is inactive and not currently configured in which case a 404 is also allowed // (or this is an internal server error, but since a 5xx response is not defined, assume one of the former cases) slog::log(gate, SLOG_FLF) << ""Transport file requested for "" << id_type << "" which does not have one""; // An HTTP 404 response is returned if ""the transport type does not require a transport file, or if the sender is not currently configured"" // and ""may also be returned when the `master_enable` parameter is `false` in /active, if the sender only maintains a transport file when transmitting."" // See https://specs.amwa.tv/is-05/releases/v1.1.1/APIs/ConnectionAPI.html#http-status-code-404-6 set_error_reply(res, status_codes::NotFound, U(""Sender is not configured with a transport file"")); } } else { // experimental extension, proposed for v1.1, to distinguish from Not Found set_error_reply(res, status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); res.headers().add(web::http::header_names::location, make_connection_api_resource_location(*resource, U(""/transportfile""))); } } else if (details::is_erased_resource(resources, id_type)) { set_error_reply(res, status_codes::NotFound, U(""Not Found; "") + details::make_erased_resource_error()); } else { set_reply(res, status_codes::NotFound); } } } // Activate an IS-05 sender or receiver by transitioning the 'staged' settings into the 'active' resource void set_connection_resource_active(nmos::resource& connection_resource, std::function resolve_auto, const nmos::tai& activation_time) { using web::json::value; using web::json::value_of; auto& resource = connection_resource; const auto at = value::string(nmos::make_version(activation_time)); resource.data[nmos::fields::version] = at; auto& staged = nmos::fields::endpoint_staged(resource.data); auto& staged_activation = staged[nmos::fields::activation]; const nmos::activation_mode staged_mode{ nmos::fields::mode(staged_activation).as_string() }; // Set the time of activation (will be included in the PATCH response for an immediate activation) staged_activation[nmos::fields::activation_time] = at; auto& active = nmos::fields::endpoint_active(resource.data); // ""On activation all instances of ""auto"" must be resolved into the actual values that will be used, unless // there is an error condition. If there is an error condition that means `auto` cannot be resolved, the active // transport parameters must not change, and the underlying sender must continue as before."" // Therefore, in case it throws an exception, resolve_auto is called on a copy of the /staged resource data, // before making any changes to the /active resource data. // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/ConnectionAPI.html#single_senders__senderid__active_get // and https://specs.amwa.tv/is-05/releases/v1.1.0/docs/2.2._APIs_-_Server_Side_Implementation.html#use-of-auto auto activating = staged; resolve_auto(activating); // ""When a set of 'staged' settings is activated, these settings transition into the 'active' resource."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/1.0._Overview.html#active active = activating; // Unclear whether the activation in the active endpoint should have values for mode, requested_time // (and even activation_time?) or whether they should be null? The examples have them with values. // See https://specs.amwa.tv/is-05/releases/v1.0.0/examples/v1.0-receiver-active-get-200.html // and https://specs.amwa.tv/is-05/releases/v1.0.0/examples/v1.0-sender-active-get.html if (nmos::activation_modes::activate_scheduled_absolute == staged_mode || nmos::activation_modes::activate_scheduled_relative == staged_mode) { set_connection_resource_not_pending(resource); } // nmos::details::handle_immediate_activation_pending finishes the transition of the staged parameters back to null // in the case of an immediate activation, as explained above nmos::details::handle_connection_resource_patch! } // Clear any pending activation of an IS-05 sender or receiver // (This function should not be called after nmos::set_connection_resource_active.) void set_connection_resource_not_pending(nmos::resource& connection_resource) { auto& staged = nmos::fields::endpoint_staged(connection_resource.data); auto& staged_activation = staged[nmos::fields::activation]; // ""This parameter returns to null on the staged endpoint once an activation is completed."" // ""This field returns to null once the activation is completed on the staged endpoint."" // ""On the staged endpoint this field returns to null once the activation is completed."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/APIs/schemas/with-refs/v1.0-activation-response-schema.html // ""A resource may be unlocked by setting `mode` in `activation` to `null`, which will cancel the pending activation."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/ConnectionAPI.html#http-status-code-423 staged_activation = nmos::make_activation(); } // Update the IS-04 sender or receiver after the active connection is changed in any way // (This function should be called after nmos::set_connection_resource_active.) void set_resource_subscription(nmos::resource& node_resource, bool active, const nmos::id& connected_id, const nmos::tai& activation_time) { using web::json::value; using web::json::value_of; auto& resource = node_resource; const auto at = value::string(nmos::make_version(activation_time)); // ""The 'receiver_id' key MUST be set to `null` in all cases except where a unicast push-based Sender is configured to transmit to an NMOS Receiver, and the 'active' key is set to 'true'."" // ""The 'sender_id' key MUST be set to `null` in all cases except where the Receiver is currently configured to receive from an NMOS Sender, and the 'active' key is set to 'true'. // See https://specs.amwa.tv/is-04/releases/v1.2.2/docs/4.3._Behaviour_-_Nodes.html#api-resources const auto ci = active && !connected_id.empty() ? value::string(connected_id) : value::null(); // ""When the 'active' parameters of a Sender or Receiver are modified, or when a re-activation of the same parameters // is performed, the 'version' attribute of the relevant IS-04 Sender or Receiver must be incremented."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/3.1._Interoperability_-_NMOS_IS-04.html#version-increments resource.data[nmos::fields::version] = at; // Senders indicate the connected receiver_id, receivers indicate the connected sender_id // (depending on the API version) if (nmos::is04_versions::v1_2 <= resource.version) { nmos::fields::subscription(resource.data) = value_of({ { nmos::fields::active, active }, { nmos::types::sender == resource.type ? nmos::fields::receiver_id : nmos::fields::sender_id, ci } }); } else if (nmos::types::receiver == resource.type) { nmos::fields::subscription(resource.data) = value_of({ { nmos::fields::sender_id, ci } }); } } // Validate and parse the specified transport file for the specified receiver web::json::value parse_rtp_transport_file(const nmos::resource& receiver, const nmos::resource& connection_receiver, const utility::string_t& transport_file_type, const utility::string_t& transport_file_data, slog::base_gate& gate) { if (transport_file_type != nmos::media_types::application_sdp.name) { throw std::runtime_error(""unexpected type: "" + utility::us2s(transport_file_type)); } const auto session_description = sdp::parse_session_description(utility::us2s(transport_file_data)); auto sdp_transport_params = nmos::parse_session_description(session_description); // Validate transport file according to the IS-04 receiver validate_sdp_parameters(receiver.data, sdp_transport_params.first); // could equally use nmos::fields::interface_bindings(receiver.data) or nmos::fields::transport_params(nmos::fields::endpoint_staged(connection_receiver.data)) const auto legs = nmos::fields::endpoint_constraints(connection_receiver.data).size(); if (1 == legs && 2 == sdp_transport_params.second.size()) { web::json::pop_back(sdp_transport_params.second); } // ""Where a Receiver supports SMPTE 2022-7 but is required to Receive a non-SMPTE 2022-7 stream, // only the first set of transport parameters should be used. rtp_enabled in the second set of parameters // must be set to false"" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/4.1._Behaviour_-_RTP_Transport_Type.html#operation-with-smpte-2022-7 if (2 == legs && 1 == sdp_transport_params.second.size()) { web::json::push_back(sdp_transport_params.second, web::json::value_of({ { U(""rtp_enabled""), false } })); } return sdp_transport_params.second; } // ""On activation all instances of ""auto"" should be resolved into the actual values that will be used"" // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/ConnectionAPI.html#single_senders__senderid__active_get // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/sender_transport_params_rtp.html // and https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/schemas/with-refs/receiver_transport_params_rtp.html // ""In many cases this is a simple operation, and the behaviour is very clearly defined in the relevant transport parameter schemas. // For example a port number may be offset from the RTP port number by a pre-determined value. The specification makes suggestions // of a sensible default value for ""auto"" to resolve to, but the Sender or Receiver may choose any value permitted by the schema // and constraints."" // This function implements those sensible defaults for the RTP transport type. // ""In some cases the behaviour is more complex, and may be determined by the vendor."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/docs/2.2._APIs_-_Server_Side_Implementation.html#use-of-auto // and https://specs.amwa.tv/is-05/releases/v1.1.0/docs/4.1._Behaviour_-_RTP_Transport_Type.html#use-of-auto // This function therefore does not select a value for e.g. sender ""source_ip"" or receiver ""interface_ip"". void resolve_rtp_auto(const nmos::type& type, web::json::value& transport_params, int auto_rtp_port) { if (nmos::types::sender == type) { for (auto& params : transport_params.as_array()) { // nmos::fields::source_ip // nmos::fields::destination_ip details::resolve_auto(params, nmos::fields::source_port, [&] { return auto_rtp_port; }); details::resolve_auto(params, nmos::fields::destination_port, [&] { return auto_rtp_port; }); details::resolve_auto(params, nmos::fields::fec_destination_ip, [&] { return params[nmos::fields::destination_ip]; }); details::resolve_auto(params, nmos::fields::fec1D_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 2; }); details::resolve_auto(params, nmos::fields::fec2D_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 4; }); details::resolve_auto(params, nmos::fields::fec1D_source_port, [&] { return params[nmos::fields::source_port].as_integer() + 2; }); details::resolve_auto(params, nmos::fields::fec2D_source_port, [&] { return params[nmos::fields::source_port].as_integer() + 4; }); details::resolve_auto(params, nmos::fields::rtcp_destination_ip, [&] { return params[nmos::fields::destination_ip]; }); details::resolve_auto(params, nmos::fields::rtcp_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 1; }); details::resolve_auto(params, nmos::fields::rtcp_source_port, [&] { return params[nmos::fields::source_port].as_integer() + 1; }); } } else if (nmos::types::receiver == type) { for (auto& params : transport_params.as_array()) { // nmos::fields::interface_ip details::resolve_auto(params, nmos::fields::destination_port, [&] { return auto_rtp_port; }); details::resolve_auto(params, nmos::fields::fec_destination_ip, [&] { return !nmos::fields::multicast_ip(params).is_null() ? params[nmos::fields::multicast_ip] : params[nmos::fields::interface_ip]; }); // nmos::fields::fec_mode details::resolve_auto(params, nmos::fields::fec1D_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 2; }); details::resolve_auto(params, nmos::fields::fec2D_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 4; }); details::resolve_auto(params, nmos::fields::rtcp_destination_ip, [&] { return !nmos::fields::multicast_ip(params).is_null() ? params[nmos::fields::multicast_ip] : params[nmos::fields::interface_ip]; }); details::resolve_auto(params, nmos::fields::rtcp_destination_port, [&] { return params[nmos::fields::destination_port].as_integer() + 1; }); } } } web::http::experimental::listener::api_router make_unmounted_connection_api(nmos::node_model& model, transport_file_parser parse_transport_file, details::connection_resource_patch_validator validate_merged, slog::base_gate& gate_) { using namespace web::http::experimental::listener::api_router_using_declarations; api_router connection_api; // check for supported API version const auto versions = with_read_lock(model.mutex, [&model] { return nmos::is05_versions::from_settings(model.settings); }); connection_api.support(U("".*""), details::make_api_version_handler(versions, gate_)); connection_api.support(U(""/?""), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U(""bulk/""), U(""single/"") }, req, res)); return pplx::task_from_result(true); }); connection_api.support(U(""/bulk/?""), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U(""senders/""), U(""receivers/"") }, req, res)); return pplx::task_from_result(true); }); // ""The API should actively return an HTTP 405 if a GET is called on the [/bulk/senders and /bulk/receivers] endpoint[s]."" // This is provided for free by the api_router which also identifies the handler for POST as a ""near miss"" // See https://specs.amwa.tv/is-05/releases/v1.0.0/APIs/ConnectionAPI.html#bulk_senders_get // and https://specs.amwa.tv/is-05/releases/v1.0.0/APIs/ConnectionAPI.html#bulk_receivers_get connection_api.support(U(""/bulk/"") + nmos::patterns::connectorType.pattern + U(""/?""), methods::POST, [&model, parse_transport_file, validate_merged, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); return details::extract_json(req, gate).then([&model, req, res, parameters, parse_transport_file, validate_merged, gate](value body) mutable { auto lock = model.write_lock(); const auto request_time = tai_now(); // during write lock to ensure uniqueness const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); auto& patches = body.as_array(); slog::log(gate, SLOG_FLF) << ""Bulk operation requested for "" << patches.size() << "" "" << resourceType; std::vector results; results.reserve(patches.size()); // ""Where a server implementation supports concurrent application of settings changes to // underlying Senders and Receivers, it may choose to perform 'bulk' resource operations // in a parallel fashion internally. This is an implementation decision and is not a // requirement of this specification."" // See https://specs.amwa.tv/is-05/releases/v1.0.0/docs/4.0._Behaviour.html const auto type = nmos::type_from_resourceType(resourceType); const auto handle_connection_resource_exception = [&](const std::pair& id_type) { // try-catch based on the exception handler in nmos::add_api_finally_handler try { throw; } catch (const web::json::json_exception& e) { slog::log(gate, SLOG_FLF) << ""JSON error for "" << id_type << "" in bulk request: "" << e.what(); return details::make_connection_resource_patch_error_response(status_codes::BadRequest, e); } catch (const web::http::http_exception& e) { slog::log(gate, SLOG_FLF) << ""HTTP error for "" << id_type << "" in bulk request: "" << e.what() << "" ["" << e.error_code() << ""]""; return details::make_connection_resource_patch_error_response(status_codes::BadRequest, e); } catch (const std::runtime_error& e) { slog::log(gate, SLOG_FLF) << ""Implementation error for "" << id_type << "" in bulk request: "" << e.what(); return details::make_connection_resource_patch_error_response(status_codes::NotImplemented, e); } catch (const std::logic_error& e) { slog::log(gate, SLOG_FLF) << ""Implementation error for "" << id_type << "" in bulk request: "" << e.what(); return details::make_connection_resource_patch_error_response(status_codes::InternalError, e); } catch (const std::exception& e) { slog::log(gate, SLOG_FLF) << ""Unexpected exception for "" << id_type << "" in bulk request: "" << e.what(); return details::make_connection_resource_patch_error_response(status_codes::InternalError, e); } catch (...) { slog::log(gate, SLOG_FLF) << ""Unexpected unknown exception for "" << id_type << "" in bulk request""; return details::make_connection_resource_patch_error_response(status_codes::InternalError); } }; for (auto& patch : patches) { const auto id = nmos::fields::id(patch); details::connection_resource_patch_response result; try { result = details::handle_connection_resource_patch(model, lock, version, { id, type }, patch[nmos::fields::params], request_time, parse_transport_file, validate_merged, gate); } catch (...) { result = handle_connection_resource_exception({ id, type }); } results.push_back(result); } if (0 != patches.size()) details::notify_connection_resource_patch(model, gate); auto rit = results.begin(); for (auto pit = patches.begin(); patches.end() != pit; ++pit, ++rit) { auto& patch = *pit; auto& result = *rit; const auto id = nmos::fields::id(patch); if (web::http::is_success_status_code(result.first)) { auto& response_activation = result.second[nmos::fields::activation]; // only pending immediate activations need to be processed before sending the response if (details::immediate_activation_pending == details::get_activation_state(response_activation)) { try { details::handle_immediate_activation_pending(model, lock, { id, type }, response_activation, gate); } catch (...) { result = handle_connection_resource_exception({ id, type }); } } } if (web::http::is_success_status_code(result.first)) { // make a bulk response success item // see https://specs.amwa.tv/is-05/releases/v1.0.1/APIs/schemas/with-refs/v1.0-bulk-response-schema.html result.second = value_of({ { nmos::fields::id, id }, { U(""code""), result.first } }); } else { // don't replace an existing response body which might contain richer error information if (result.second.is_null()) { result.second = nmos::make_error_response_body(result.first); } // make a bulk response error item from the standard NMOS error response result.second[nmos::fields::id] = value::string(id); } } set_reply(res, status_codes::OK, web::json::serialize_array(results | boost::adaptors::transformed( [](const details::connection_resource_patch_response& result) { return result.second; } )), web::http::details::mime_types::application_json); return true; }); }); connection_api.support(U(""/single/?""), methods::GET, [](http_request req, http_response res, const string_t&, const route_parameters&) { set_reply(res, status_codes::OK, nmos::make_sub_routes_body({ U(""senders/""), U(""receivers/"") }, req, res)); return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/?""), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); auto lock = model.read_lock(); auto& resources = model.connection_resources; const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const auto match = [&](const nmos::resource& resource) { auto matching_resource = find_resource(model.node_resources, { resource.id, resource.type }); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 resource not found""); } return resource.type == nmos::type_from_resourceType(resourceType) && nmos::is_connection_api_permitted_downgrade(*matching_resource, resource, version); }; size_t count = 0; // experimental extension, to support human-readable HTML rendering of NMOS responses if (experimental::details::is_html_response_preferred(req, web::http::details::mime_types::application_json)) { set_reply(res, status_codes::OK, web::json::serialize_array(resources | boost::adaptors::filtered(match) | boost::adaptors::transformed( [&count, &req](const nmos::resource& resource) { ++count; return experimental::details::make_html_response_a_tag(resource.id + U(""/""), req); } )), web::http::details::mime_types::application_json); } else { set_reply(res, status_codes::OK, web::json::serialize_array(resources | boost::adaptors::filtered(match) | boost::adaptors::transformed( [&count](const nmos::resource& resource) { ++count; return value(resource.id + U(""/"")); } ) ), web::http::details::mime_types::application_json); } slog::log(gate, SLOG_FLF) << ""Returning "" << count << "" matching "" << resourceType; return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/?""), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); auto lock = model.read_lock(); auto& resources = model.connection_resources; const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const std::pair id_type{ resourceId, nmos::type_from_resourceType(resourceType) }; auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 resource not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { std::set sub_routes{ U(""constraints/""), U(""staged/""), U(""active/"") }; if (nmos::types::sender == resource->type) sub_routes.insert(U(""transportfile/"")); // The transporttype endpoint is introduced in v1.1 if (nmos::is05_versions::v1_1 <= version) sub_routes.insert(U(""transporttype/"")); set_reply(res, status_codes::OK, nmos::make_sub_routes_body(std::move(sub_routes), req, res)); } else { // experimental extension, proposed for v1.1, to distinguish from Not Found set_error_reply(res, status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); res.headers().add(web::http::header_names::location, make_connection_api_resource_location(*resource)); } } else if (details::is_erased_resource(resources, id_type)) { set_error_reply(res, status_codes::NotFound, U(""Not Found; "") + details::make_erased_resource_error()); } else { set_reply(res, status_codes::NotFound); } return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/constraints/?""), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); auto lock = model.read_lock(); auto& resources = model.connection_resources; const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const std::pair id_type{ resourceId, nmos::type_from_resourceType(resourceType) }; auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 resource not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { slog::log(gate, SLOG_FLF) << ""Returning constraints for "" << id_type; // hmm, parsing of the Accept header could be much better and should take account of quality values const auto accept = req.headers().find(web::http::header_names::accept); const auto accept_or_empty = req.headers().end() != accept ? accept->second : utility::string_t{}; const auto accept_type = web::http::details::get_mime_type(accept_or_empty); if (nmos::media_types::application_schema_json.name == accept_type) { // Experimental extension - constraints as JSON Schema const nmos::transport transport_subclassification(nmos::fields::transport(matching_resource->data)); res.headers().set_content_type(accept_type); set_reply(res, status_codes::OK, nmos::details::make_constraints_schema(resource->type, nmos::fields::endpoint_constraints(resource->data), nmos::transport_base(transport_subclassification))); } else { set_reply(res, status_codes::OK, nmos::fields::endpoint_constraints(resource->data)); } } else { // experimental extension, proposed for v1.1, to distinguish from Not Found set_error_reply(res, status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); res.headers().add(web::http::header_names::location, make_connection_api_resource_location(*resource, U(""/constraints""))); } } else if (details::is_erased_resource(resources, id_type)) { set_error_reply(res, status_codes::NotFound, U(""Not Found; "") + details::make_erased_resource_error()); } else { set_reply(res, status_codes::NotFound); } return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/staged/?""), methods::PATCH, [&model, parse_transport_file, validate_merged, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); return details::extract_json(req, gate).then([&model, req, res, parameters, parse_transport_file, validate_merged, gate](value body) mutable { const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const std::pair id_type{ resourceId, nmos::type_from_resourceType(resourceType) }; slog::log(gate, SLOG_FLF) << ""Operation requested for single "" << id_type; details::handle_connection_resource_patch(res, model, version, id_type, body, parse_transport_file, validate_merged, gate); return true; }); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/"") + nmos::patterns::stagingType.pattern + U(""/?""), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); auto lock = model.read_lock(); auto& resources = model.connection_resources; const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const string_t stagingType = parameters.at(nmos::patterns::stagingType.name); const std::pair id_type{ resourceId, nmos::type_from_resourceType(resourceType) }; auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 resource not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { if (nmos::fields::endpoint_staged.key == stagingType) { const auto staged_state = details::get_activation_state(nmos::fields::activation(nmos::fields::endpoint_staged(resource->data))); if (details::immediate_activation_pending == staged_state) { // ""Any GET requests to `/staged` during this time [while an activation is in progress] MAY also be blocked until the activation is complete."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/docs/4.0._Behaviour.html#in-progress-activations if (!details::wait_immediate_activation_not_pending(model, lock, id_type) || model.shutdown) { slog::log(gate, SLOG_FLF) << ""Rejecting GET request for "" << id_type << "" due to a pending immediate activation""; set_reply(res, status_codes::InternalError); // or ServiceUnavailable? probably not NotFound even if that's true after the timeout? return pplx::task_from_result(true); } // find resource again just in case, since waiting releases and reacquires the lock resource = find_resource(resources, id_type); } } } else { // experimental extension, proposed for v1.1, to distinguish from Not Found set_error_reply(res, status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); res.headers().add(web::http::header_names::location, make_connection_api_resource_location(*resource, U(""/"") + stagingType)); return pplx::task_from_result(true); } } if (resources.end() != resource) { slog::log(gate, SLOG_FLF) << ""Returning "" << stagingType << "" data for "" << id_type; const web::json::field_as_value endpoint_staging{ stagingType }; set_reply(res, status_codes::OK, endpoint_staging(resource->data)); } else if (details::is_erased_resource(resources, id_type)) { set_error_reply(res, status_codes::NotFound, U(""Not Found; "") + details::make_erased_resource_error()); } else { set_reply(res, status_codes::NotFound); } return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::senderType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/transportfile/?""), methods::GET, [&model, &gate_](http_request req, http_response res, const string_t&, const route_parameters& parameters) { nmos::api_gate gate(gate_, req, parameters); const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const std::pair id_type{ resourceId, nmos::types::sender }; const auto accept = req.headers().find(web::http::header_names::accept); const auto accept_or_empty = req.headers().end() != accept ? accept->second : utility::string_t{}; details::handle_connection_resource_transportfile(res, model, version, id_type, accept_or_empty, gate); return pplx::task_from_result(true); }); connection_api.support(U(""/single/"") + nmos::patterns::connectorType.pattern + U(""/"") + nmos::patterns::resourceId.pattern + U(""/transporttype/?""), methods::GET, [&model](http_request req, http_response res, const string_t&, const route_parameters& parameters) { // The transporttype endpoint is introduced in v1.1 const nmos::api_version version = nmos::parse_api_version(parameters.at(nmos::patterns::version.name)); if (nmos::is05_versions::v1_1 > version) { set_reply(res, status_codes::NotFound); return pplx::task_from_result(true); } auto lock = model.read_lock(); auto& resources = model.connection_resources; const string_t resourceType = parameters.at(nmos::patterns::connectorType.name); const string_t resourceId = parameters.at(nmos::patterns::resourceId.name); const std::pair id_type{ resourceId, nmos::type_from_resourceType(resourceType) }; auto resource = find_resource(resources, id_type); if (resources.end() != resource) { auto matching_resource = find_resource(model.node_resources, id_type); if (model.node_resources.end() == matching_resource) { throw std::logic_error(""matching IS-04 resource not found""); } if (nmos::is_connection_api_permitted_downgrade(*matching_resource, *resource, version)) { // ""Returns the URN base for the transport type employed by this sender with any subclassifications or versions removed."" // See https://specs.amwa.tv/is-05/releases/v1.1.0/APIs/ConnectionAPI.html#single_senders__senderid__transporttype_get const nmos::transport transport_subclassification(nmos::fields::transport(matching_resource->data)); set_reply(res, status_codes::OK, web::json::value::string(nmos::transport_base(transport_subclassification).name)); } else { // experimental extension, proposed for v1.1, to distinguish from Not Found set_error_reply(res, status_codes::Conflict, U(""Conflict; "") + details::make_permitted_downgrade_error(*resource, version)); res.headers().add(web::http::header_names::location, make_connection_api_resource_location(*resource, U(""/transporttype""))); } } else if (details::is_erased_resource(resources, id_type)) { set_error_reply(res, status_codes::NotFound, U(""Not Found; "") + details::make_erased_resource_error()); } else { set_reply(res, status_codes::NotFound); } return pplx::task_from_result(true); }); return connection_api; } } ",16283,True,3639.2655830397784,median "== Video Options === Composite Video Mode ==== `sdtv_mode` The `sdtv_mode` command defines the TV standard used for composite video output. On the original Raspberry Pi, composite video is output on the RCA socket. On other Raspberry Pi's, except for Pi Zero and Compute Module, composite video is output along with sound on the 4 pole TRRS (""headphone"") socket. On the Pi Zero, there is an unpopulated header labelled ""TV"" which outputs composite video. On the Compute Module, composite video is available via the TVDAC pin. The default value of `sdtv_mode` is `0`. |=== | sdtv_mode | result | 0 | Normal NTSC | 1 | Japanese version of NTSC -- no pedestal | 2 | Normal PAL | 3 | Brazilian version of PAL -- 525/60 rather than 625/50, different subcarrier | 16 | Progressive scan NTSC | 18 | Progressive scan PAL |=== ==== `sdtv_aspect` The `sdtv_aspect` command defines the aspect ratio for composite video output. The default value is `1`. |=== | sdtv_aspect | result | 1 | 4:3 | 2 | 14:9 | 3 | 16:9 |=== ==== `sdtv_disable_colourburst` Setting `sdtv_disable_colourburst` to `1` disables colourburst on composite video output. The picture will be displayed in monochrome, but it may appear sharper. ==== `enable_tvout` (Raspberry Pi 4, Model B Only) On the Raspberry Pi 4, composite output is disabled by default, due to the way the internal clocks are interrelated and allocated. Because composite video requires a very specific clock, setting that clock to the required speed on the Pi 4 means that other clocks connected to it are detrimentally affected, which slightly slows down the entire system. Since composite video is a less commonly used function, we decided to disable it by default to prevent this system slowdown. To enable composite output, use the `enable_tvout=1` option. As described above, this will detrimentally affect performance to a small degree. On older Pi models, the composite behaviour remains the same. === HDMI Mode NOTE: Because the Raspberry Pi 4B has two HDMI ports, some HDMI commands can be applied to either port. You can use the syntax `:`, where port is 0 or 1, to specify which port the setting should apply to. If no port is specified, the default is 0. If you specify a port number on a command that does not require a port number, the port is ignored. Further details on the syntax and alternatives mechanisms can be found in the HDMI sub-section on the xref:config_txt.adoc#conditional-filters[conditionals section] of the documentation. In order to support dual 4k displays, the Raspberrry Pi 4 has xref:config_txt.adoc#raspberry-pi-4-hdmi-pipeline[updated video hardware], which imposes minor restrictions on the modes supported. ==== `hdmi_safe` Setting `hdmi_safe` to `1` will lead to ""safe mode"" settings being used to try to boot with maximum HDMI compatibility. This is the same as setting the following parameters: ---- hdmi_force_hotplug=1 hdmi_ignore_edid=0xa5000080 config_hdmi_boost=4 hdmi_group=2 hdmi_mode=4 disable_overscan=0 overscan_left=24 overscan_right=24 overscan_top=24 overscan_bottom=24 ---- ==== `hdmi_ignore_edid` Setting `hdmi_ignore_edid` to `0xa5000080` enables the ignoring of EDID/display data if your display does not have an accurate https://en.wikipedia.org/wiki/Extended_display_identification_data[EDID]. It requires this unusual value to ensure that it is not triggered accidentally. ==== `hdmi_edid_file` Setting `hdmi_edid_file` to `1` will cause the GPU to read EDID data from the `edid.dat` file, located in the boot partition, instead of reading it from the monitor. More information is available https://forums.raspberrypi.com/viewtopic.php?p=173430#p173430[on the forums]. ==== `hdmi_edid_filename` On the Raspberry Pi 4B, you can use the `hdmi_edid_filename` command to specify the filename of the EDID file to use, and also to specify which port the file is to be applied to. This also requires `hdmi_edid_file=1` to enable EDID files. For example: ---- hdmi_edid_file=1 hdmi_edid_filename:0=FileForPortZero.edid hdmi_edid_filename:1=FileForPortOne.edid ---- ==== `hdmi_force_edid_audio` Setting `hdmi_force_edid_audio` to `1` pretends that all audio formats are supported by the display, allowing passthrough of DTS/AC3 even when this is not reported as supported. ==== `hdmi_ignore_edid_audio` Setting `hdmi_ignore_edid_audio` to `1` pretends that all audio formats are unsupported by the display. This means ALSA will default to the analogue audio (headphone) jack. ==== `hdmi_force_edid_3d` Setting `hdmi_force_edid_3d` to `1` pretends that all CEA modes support 3D, even when the EDID does not indicate support for this. ==== `hdmi_ignore_cec_init` Setting `hdmi_ignore_cec_init` to `1` will stop the initial active source message being sent during bootup. This prevents a CEC-enabled TV from coming out of standby and channel-switching when you are rebooting your Raspberry Pi. ==== `hdmi_ignore_cec` Setting `hdmi_ignore_cec` to `1` pretends that https://en.wikipedia.org/wiki/Consumer_Electronics_Control#CEC[CEC] is not supported at all by the TV. No CEC functions will be supported. ==== `cec_osd_name` The `cec_osd_name` command sets the initial CEC name of the device. The default is Raspberry Pi. ==== `hdmi_pixel_encoding` The `hdmi_pixel_encoding` command forces the pixel encoding mode. By default, it will use the mode requested from the EDID, so you shouldn't need to change it. |=== | hdmi_pixel_encoding | result | 0 | default (RGB limited for CEA, RGB full for DMT) | 1 | RGB limited (16-235) | 2 | RGB full (0-255) | 3 | YCbCr limited (16-235) | 4 | YCbCr full (0-255) |=== ==== `hdmi_max_pixel_freq` The pixel frequency is used by the firmware and KMS to filter HDMI modes. Note, this is not the same as the frame rate. It specifies the maximum frequency that a valid mode can have, thereby culling out higher frequency modes. So for example, if you wish to disable all 4K modes, you could specify a maximum frequency of 200000000, since all 4K modes have frequencies greater than this. ==== `hdmi_blanking` The `hdmi_blanking` command controls what happens when the operating system asks for the display to be put into standby mode, using DPMS, to save power. If this option is not set or set to 0, the HDMI output is blanked but not switched off. In order to mimic the behaviour of other computers, you can set the HDMI output to switch off as well by setting this option to 1: the attached display will go into a low power standby mode. NOTE: On the Raspberry Pi 4, setting `hdmi_blanking=1` will not cause the HDMI output to be switched off, since this feature has not yet been implemented. This feature may cause issues when using applications which don't use the framebuffer, such as `omxplayer`. |=== | hdmi_blanking | result | 0 | HDMI output will be blanked | 1 | HDMI output will be switched off and blanked |=== ==== `hdmi_drive` The `hdmi_drive` command allows you to choose between HDMI and DVI output modes. |=== | hdmi_drive | result | 1 | Normal DVI mode (no sound) | 2 | Normal HDMI mode (sound will be sent if supported and enabled) |=== ==== `config_hdmi_boost` Configures the signal strength of the HDMI interface. The minimum value is `0` and the maximum is `11`. The default value for the original Model B and A is `2`. The default value for the Model B+ and all later models is `5`. If you are seeing HDMI issues (speckling, interference) then try `7`. Very long HDMI cables may need up to `11`, but values this high should not be used unless absolutely necessary. This option is ignored on the Raspberry Pi 4. ==== `hdmi_group` The `hdmi_group` command defines the HDMI output group to be either CEA (Consumer Electronics Association, the standard typically used by TVs) or DMT (Display Monitor Timings, the standard typically used by monitors). This setting should be used in conjunction with `hdmi_mode`. |=== | hdmi_group | result | 0 | Auto-detect from EDID | 1 | CEA | 2 | DMT |=== ==== `hdmi_mode` Together with `hdmi_group`, `hdmi_mode` defines the HDMI output format. Format mode numbers are derived from the https://web.archive.org/web/20171201033424/https://standards.cta.tech/kwspub/published_docs/CTA-861-G_FINAL_revised_2017.pdf[CTA specification]. To set a custom display mode not listed here, see more information on https://forums.raspberrypi.com/viewtopic.php?f=29&t=24679[the forums]. NOTE: Not all modes are available on all models. These values are valid if `hdmi_group=1` (CEA): [cols="",,,^,""] |=== | hdmi_mode | Resolution | Frequency | Screen Aspect | Notes | 1 | VGA (640x480) | 60Hz | 4:3 | | 2 | 480p | 60Hz | 4:3 | | 3 | 480p | 60Hz | 16:9 | | 4 | 720p | 60Hz | 16:9 | | 5 | 1080i | 60Hz | 16:9 | | 6 | 480i | 60Hz | 4:3 | | 7 | 480i | 60Hz | 16:9 | | 8 | 240p | 60Hz | 4:3 | | 9 | 240p | 60Hz | 16:9 | | 10 | 480i | 60Hz | 4:3 | pixel quadrupling | 11 | 480i | 60Hz | 16:9 | pixel quadrupling | 12 | 240p | 60Hz | 4:3 | pixel quadrupling | 13 | 240p | 60Hz | 16:9 | pixel quadrupling | 14 | 480p | 60Hz | 4:3 | pixel doubling | 15 | 480p | 60Hz | 16:9 | pixel doubling | 16 | 1080p | 60Hz | 16:9 | | 17 | 576p | 50Hz | 4:3 | | 18 | 576p | 50Hz | 16:9 | | 19 | 720p | 50Hz | 16:9 | | 20 | 1080i | 50Hz | 16:9 | | 21 | 576i | 50Hz | 4:3 | | 22 | 576i | 50Hz | 16:9 | | 23 | 288p | 50Hz | 4:3 | | 24 | 288p | 50Hz | 16:9 | | 25 | 576i | 50Hz | 4:3 | pixel quadrupling | 26 | 576i | 50Hz | 16:9 | pixel quadrupling | 27 | 288p | 50Hz | 4:3 | pixel quadrupling | 28 | 288p | 50Hz | 16:9 | pixel quadrupling | 29 | 576p | 50Hz | 4:3 | pixel doubling | 30 | 576p | 50Hz | 16:9 | pixel doubling | 31 | 1080p | 50Hz | 16:9 | | 32 | 1080p | 24Hz | 16:9 | | 33 | 1080p | 25Hz | 16:9 | | 34 | 1080p | 30Hz | 16:9 | | 35 | 480p | 60Hz | 4:3 | pixel quadrupling | 36 | 480p | 60Hz | 16:9 | pixel quadrupling | 37 | 576p | 50Hz | 4:3 | pixel quadrupling | 38 | 576p | 50Hz | 16:9 | pixel quadrupling | 39 | 1080i | 50Hz | 16:9 | reduced blanking | 40 | 1080i | 100Hz | 16:9 | | 41 | 720p | 100Hz | 16:9 | | 42 | 576p | 100Hz | 4:3 | | 43 | 576p | 100Hz | 16:9 | | 44 | 576i | 100Hz | 4:3 | | 45 | 576i | 100Hz | 16:9 | | 46 | 1080i | 120Hz | 16:9 | | 47 | 720p | 120Hz | 16:9 | | 48 | 480p | 120Hz | 4:3 | | 49 | 480p | 120Hz | 16:9 | | 50 | 480i | 120Hz | 4:3 | | 51 | 480i | 120Hz | 16:9 | | 52 | 576p | 200Hz | 4:3 | | 53 | 576p | 200Hz | 16:9 | | 54 | 576i | 200Hz | 4:3 | | 55 | 576i | 200Hz | 16:9 | | 56 | 480p | 240Hz | 4:3 | | 57 | 480p | 240Hz | 16:9 | | 58 | 480i | 240Hz | 4:3 | | 59 | 480i | 240Hz | 16:9 | | 60 | 720p | 24Hz | 16:9 | | 61 | 720p | 25Hz | 16:9 | | 62 | 720p | 30Hz | 16:9 | | 63 | 1080p | 120Hz | 16:9 | | 64 | 1080p | 100Hz | 16:9 | | 65 | Custom | | | | 66 | 720p | 25Hz | 64:27 | Pi 4 | 67 | 720p | 30Hz | 64:27 | Pi 4 | 68 | 720p | 50Hz | 64:27 | Pi 4 | 69 | 720p | 60Hz | 64:27 | Pi 4 | 70 | 720p | 100Hz | 64:27 | Pi 4 | 71 | 720p | 120Hz | 64:27 | Pi 4 | 72 | 1080p | 24Hz | 64:27 | Pi 4 | 73 | 1080p | 25Hz | 64:27 | Pi 4 | 74 | 1080p | 30Hz | 64:27 | Pi 4 | 75 | 1080p | 50Hz | 64:27 | Pi 4 | 76 | 1080p | 60Hz | 64:27 | Pi 4 | 77 | 1080p | 100Hz | 64:27 | Pi 4 | 78 | 1080p | 120Hz | 64:27 | Pi 4 | 79 | 1680x720 | 24Hz | 64:27 | Pi 4 | 80 | 1680x720 | 25z | 64:27 | Pi 4 | 81 | 1680x720 | 30Hz | 64:27 | Pi 4 | 82 | 1680x720 | 50Hz | 64:27 | Pi 4 | 83 | 1680x720 | 60Hz | 64:27 | Pi 4 | 84 | 1680x720 | 100Hz | 64:27 | Pi 4 | 85 | 1680x720 | 120Hz | 64:27 | Pi 4 | 86 | 2560x720 | 24Hz | 64:27 | Pi 4 | 87 | 2560x720 | 25Hz | 64:27 | Pi 4 | 88 | 2560x720 | 30Hz | 64:27 | Pi 4 | 89 | 2560x720 | 50Hz | 64:27 | Pi 4 | 90 | 2560x720 | 60Hz | 64:27 | Pi 4 | 91 | 2560x720 | 100Hz | 64:27 | Pi 4 | 92 | 2560x720 | 120Hz | 64:27 | Pi 4 | 93 | 2160p | 24Hz | 16:9 | Pi 4 | 94 | 2160p | 25Hz | 16:9 | Pi 4 | 95 | 2160p | 30Hz | 16:9 | Pi 4 | 96 | 2160p | 50Hz | 16:9 | Pi 4 | 97 | 2160p | 60Hz | 16:9 | Pi 4 | 98 | 4096x2160 | 24Hz | 256:135 | Pi 4 | 99 | 4096x2160 | 25Hz | 256:135 | Pi 4 | 100 | 4096x2160 | 30Hz | 256:135 | Pi 4 | 101 | 4096x2160 | 50Hz | 256:135 | Pi 4 | 102 | 4096x2160 | 60Hz | 256:135 | Pi 4 | 103 | 2160p | 24Hz | 64:27 | Pi 4 | 104 | 2160p | 25Hz | 64:27 | Pi 4 | 105 | 2160p | 30Hz | 64:27 | Pi 4 | 106 | 2160p | 50Hz | 64:27 | Pi 4 | 107 | 2160p | 60Hz | 64:27 | Pi 4 |=== Pixel doubling and quadrupling indicates a higher clock rate, with each pixel repeated two or four times respectively. These values are valid if `hdmi_group=2` (DMT): [cols="",,,^,""] |=== | hdmi_mode | Resolution | Frequency | Screen Aspect | Notes | 1 | 640x350 | 85Hz | | | 2 | 640x400 | 85Hz | 16:10 | | 3 | 720x400 | 85Hz | | | 4 | 640x480 | 60Hz | 4:3 | | 5 | 640x480 | 72Hz | 4:3 | | 6 | 640x480 | 75Hz | 4:3 | | 7 | 640x480 | 85Hz | 4:3 | | 8 | 800x600 | 56Hz | 4:3 | | 9 | 800x600 | 60Hz | 4:3 | | 10 | 800x600 | 72Hz | 4:3 | | 11 | 800x600 | 75Hz | 4:3 | | 12 | 800x600 | 85Hz | 4:3 | | 13 | 800x600 | 120Hz | 4:3 | | 14 | 848x480 | 60Hz | 16:9 | | 15 | 1024x768 | 43Hz | 4:3 | incompatible with the Raspberry Pi | 16 | 1024x768 | 60Hz | 4:3 | | 17 | 1024x768 | 70Hz | 4:3 | | 18 | 1024x768 | 75Hz | 4:3 | | 19 | 1024x768 | 85Hz | 4:3 | | 20 | 1024x768 | 120Hz | 4:3 | | 21 | 1152x864 | 75Hz | 4:3 | | 22 | 1280x768 | 60Hz | 15:9 | reduced blanking | 23 | 1280x768 | 60Hz | 15:9 | | 24 | 1280x768 | 75Hz | 15:9 | | 25 | 1280x768 | 85Hz | 15:9 | | 26 | 1280x768 | 120Hz | 15:9 | reduced blanking | 27 | 1280x800 | 60 | 16:10 | reduced blanking | 28 | 1280x800 | 60Hz | 16:10 | | 29 | 1280x800 | 75Hz | 16:10 | | 30 | 1280x800 | 85Hz | 16:10 | | 31 | 1280x800 | 120Hz | 16:10 | reduced blanking | 32 | 1280x960 | 60Hz | 4:3 | | 33 | 1280x960 | 85Hz | 4:3 | | 34 | 1280x960 | 120Hz | 4:3 | reduced blanking | 35 | 1280x1024 | 60Hz | 5:4 | | 36 | 1280x1024 | 75Hz | 5:4 | | 37 | 1280x1024 | 85Hz | 5:4 | | 38 | 1280x1024 | 120Hz | 5:4 | reduced blanking | 39 | 1360x768 | 60Hz | 16:9 | | 40 | 1360x768 | 120Hz | 16:9 | reduced blanking | 41 | 1400x1050 | 60Hz | 4:3 | reduced blanking | 42 | 1400x1050 | 60Hz | 4:3 | | 43 | 1400x1050 | 75Hz | 4:3 | | 44 | 1400x1050 | 85Hz | 4:3 | | 45 | 1400x1050 | 120Hz | 4:3 | reduced blanking | 46 | 1440x900 | 60Hz | 16:10 | reduced blanking | 47 | 1440x900 | 60Hz | 16:10 | | 48 | 1440x900 | 75Hz | 16:10 | | 49 | 1440x900 | 85Hz | 16:10 | | 50 | 1440x900 | 120Hz | 16:10 | reduced blanking | 51 | 1600x1200 | 60Hz | 4:3 | | 52 | 1600x1200 | 65Hz | 4:3 | | 53 | 1600x1200 | 70Hz | 4:3 | | 54 | 1600x1200 | 75Hz | 4:3 | | 55 | 1600x1200 | 85Hz | 4:3 | | 56 | 1600x1200 | 120Hz | 4:3 | reduced blanking | 57 | 1680x1050 | 60Hz | 16:10 | reduced blanking | 58 | 1680x1050 | 60Hz | 16:10 | | 59 | 1680x1050 | 75Hz | 16:10 | | 60 | 1680x1050 | 85Hz | 16:10 | | 61 | 1680x1050 | 120Hz | 16:10 | reduced blanking | 62 | 1792x1344 | 60Hz | 4:3 | | 63 | 1792x1344 | 75Hz | 4:3 | | 64 | 1792x1344 | 120Hz | 4:3 | reduced blanking | 65 | 1856x1392 | 60Hz | 4:3 | | 66 | 1856x1392 | 75Hz | 4:3 | | 67 | 1856x1392 | 120Hz | 4:3 | reduced blanking | 68 | 1920x1200 | 60Hz | 16:10 | reduced blanking | 69 | 1920x1200 | 60Hz | 16:10 | | 70 | 1920x1200 | 75Hz | 16:10 | | 71 | 1920x1200 | 85Hz | 16:10 | | 72 | 1920x1200 | 120Hz | 16:10 | reduced blanking | 73 | 1920x1440 | 60Hz | 4:3 | | 74 | 1920x1440 | 75Hz | 4:3 | | 75 | 1920x1440 | 120Hz | 4:3 | reduced blanking | 76 | 2560x1600 | 60Hz | 16:10 | reduced blanking | 77 | 2560x1600 | 60Hz | 16:10 | | 78 | 2560x1600 | 75Hz | 16:10 | | 79 | 2560x1600 | 85Hz | 16:10 | | 80 | 2560x1600 | 120Hz | 16:10 | reduced blanking | 81 | 1366x768 | 60Hz | 16:9 | xref:config_txt.adoc#raspberry-pi-4-hdmi-pipeline[NOT on Raspberry Pi 4] | 82 | 1920x1080 | 60Hz | 16:9 | 1080p | 83 | 1600x900 | 60Hz | 16:9 | reduced blanking | 84 | 2048x1152 | 60Hz | 16:9 | reduced blanking | 85 | 1280x720 | 60Hz | 16:9 | 720p | 86 | 1366x768 | 60Hz | 16:9 | reduced blanking |=== NOTE: There is a https://forums.raspberrypi.com/viewtopic.php?f=26&t=20155&p=195443#p195443[pixel clock limit].The highest supported mode on models prior to the Raspberry Pi 4 is 1920x1200 at 60Hz with reduced blanking, whilst the Raspberry Pi 4 can support up to 4096x2160 (known as 4k) at 60Hz. Also note that if you are using both HDMI ports of the Raspberry Pi 4 for 4k output, then you are limited to 30Hz on both. ==== `hdmi_timings` This allows setting of raw HDMI timing values for a custom mode, selected using `hdmi_group=2` and `hdmi_mode=87`. [source] ---- hdmi_timings= ---- [source] ---- = horizontal pixels (width) = invert hsync polarity = horizontal forward padding from DE acitve edge = hsync pulse width in pixel clocks = vertical back padding from DE active edge = vertical pixels height (lines) = invert vsync polarity = vertical forward padding from DE active edge = vsync pulse width in pixel clocks = vertical back padding from DE active edge = leave at zero = leave at zero = leave at zero = screen refresh rate in Hz = leave at zero = clock frequency (width*height*framerate) = * ---- `*` The aspect ratio can be set to one of eight values (choose the closest for your screen): [source] ---- HDMI_ASPECT_4_3 = 1 HDMI_ASPECT_14_9 = 2 HDMI_ASPECT_16_9 = 3 HDMI_ASPECT_5_4 = 4 HDMI_ASPECT_16_10 = 5 HDMI_ASPECT_15_9 = 6 HDMI_ASPECT_21_9 = 7 HDMI_ASPECT_64_27 = 8 ---- ==== `hdmi_force_mode` Setting to `1` will remove all other modes except the ones specified by `hdmi_mode` and `hdmi_group` from the internal list, meaning they will not appear in any enumerated lists of modes. This option may help if a display seems to be ignoring the `hdmi_mode` and `hdmi_group` settings. ==== `edid_content_type` Forces the EDID content type to a specific value. The options are: * `0` = `EDID_ContentType_NODATA`, content type none. * `1` = `EDID_ContentType_Graphics`, content type graphics, ITC must be set to 1 * `2` = `EDID_ContentType_Photo`, content type photo * `3` = `EDID_ContentType_Cinema`, content type cinema * `4` = `EDID_ContentType_Game`, content type game ==== `hdmi_enable_4kp60` (Raspberry Pi 4, Model B Only) By default, when connected to a 4K monitor, the Raspberry Pi 4B will select a 30hz refresh rate. Use this option to allow selection of 60Hz refresh rates. Note, this will increase power consumption and increase the temperature of the Raspberry Pi. It is not possible to output 4Kp60 on both micro HDMI ports simultaneously. === Which Values are Valid for my Monitor? Your HDMI monitor may only support a limited set of formats. To find out which formats are supported, use the following method: . Set the output format to VGA 60Hz (`hdmi_group=1` and `hdmi_mode=1`) and boot up your Raspberry Pi . Enter the following command to give a list of CEA-supported modes: `/opt/vc/bin/tvservice -m CEA` . Enter the following command to give a list of DMT-supported modes: `/opt/vc/bin/tvservice -m DMT` . Enter the following command to show your current state: `/opt/vc/bin/tvservice -s` . Enter the following commands to dump more detailed information from your monitor: `/opt/vc/bin/tvservice -d edid.dat; /opt/vc/bin/edidparser edid.dat` The `edid.dat` should also be provided when troubleshooting problems with the default HDMI mode. [[custom-mode]] === Custom Mode If your monitor requires a mode that is not in one of the tables above, then it's possible to define a custom CVT mode for it instead: [source] ---- hdmi_cvt= ---- |=== | Value | Default | Description | width | (required) | width in pixels | height | (required) | height in pixels | framerate | (required) | framerate in Hz | aspect | 3 | aspect ratio 1=4:3, 2=14:9, 3=16:9, 4=5:4, 5=16:10, 6=15:9 | margins | 0 | 0=margins disabled, 1=margins enabled | interlace | 0 | 0=progressive, 1=interlaced | rb | 0 | 0=normal, 1=reduced blanking |=== Fields at the end can be omitted to use the default values. Note that this simply *creates* the mode (group 2 mode 87). In order to make the Pi use this by default, you must add some additional settings. For example, the following selects an 800 × 480 resolution and enables audio drive: ---- hdmi_cvt=800 480 60 6 hdmi_group=2 hdmi_mode=87 hdmi_drive=2 ---- This may not work if your monitor does not support standard CVT timings. === LCD Displays and Touchscreens ==== `ignore_lcd` By default the Raspberry Pi LCD display is used when it is detected on the I2C bus. `ignore_lcd=1` will skip this detection phase, and therefore the LCD display will not be used. ==== `display_default_lcd` If a Raspberry Pi DSI LCD is detected it will be used as the default display and will show the framebuffer. Setting `display_default_lcd=0` will ensure the LCD is not the default display, which usually implies the HDMI output will be the default. The LCD can still be used by choosing its display number from supported applications, for example, omxplayer. ==== `lcd_framerate` Specify the framerate of the Raspberry Pi LCD display, in Hertz/fps. Defaults to 60Hz. ==== `lcd_rotate` This flips the display using the LCD's inbuilt flip functionality, which is a cheaper operation that using the GPU-based rotate operation. For example, `lcd_rotate=2` will compensate for an upside down display. ==== `disable_touchscreen` Enable/disable the touchscreen. `disable_touchscreen=1` will disable the touchscreen on the official Raspberry Pi LCD display. ==== `enable_dpi_lcd` Enable LCD displays attached to the DPI GPIOs. This is to allow the use of third-party LCD displays using the parallel display interface. ==== `dpi_group`, `dpi_mode`, `dpi_output_format` The `dpi_group` and `dpi_mode` `config.txt` parameters are used to set either predetermined modes (DMT or CEA modes as used by HDMI above). A user can generate custom modes in much the same way as for HDMI (see `dpi_timings` section). `dpi_output_format` is a bitmask specifying various parameters used to set up the display format. ==== `dpi_timings` This allows setting of raw DPI timing values for a custom mode, selected using `dpi_group=2` and `dpi_mode=87`. [source] ---- dpi_timings= ---- [source] ---- = horizontal pixels (width) = invert hsync polarity = horizontal forward padding from DE acitve edge = hsync pulse width in pixel clocks = vertical back padding from DE active edge = vertical pixels height (lines) = invert vsync polarity = vertical forward padding from DE active edge = vsync pulse width in pixel clocks = vertical back padding from DE active edge = leave at zero = leave at zero = leave at zero = screen refresh rate in Hz = leave at zero = clock frequency (width*height*framerate) = * ---- `*` The aspect ratio can be set to one of eight values (choose the closest for your screen): ---- HDMI_ASPECT_4_3 = 1 HDMI_ASPECT_14_9 = 2 HDMI_ASPECT_16_9 = 3 HDMI_ASPECT_5_4 = 4 HDMI_ASPECT_16_10 = 5 HDMI_ASPECT_15_9 = 6 HDMI_ASPECT_21_9 = 7 HDMI_ASPECT_64_27 = 8 ---- === Generic Display Options ==== `hdmi_force_hotplug` Setting `hdmi_force_hotplug` to `1` pretends that the HDMI hotplug signal is asserted, so it appears that a HDMI display is attached. In other words, HDMI output mode will be used, even if no HDMI monitor is detected. ==== `hdmi_ignore_hotplug` Setting `hdmi_ignore_hotplug` to `1` pretends that the HDMI hotplug signal is not asserted, so it appears that a HDMI display is not attached. In other words, composite output mode will be used, even if an HDMI monitor is detected. ==== `disable_overscan` Set `disable_overscan` to `1` to disable the default values of xref:configuration.adoc#underscan[overscan] that is set by the firmware. The default value of overscan for the left, right, top, and bottom edges is `48` for HD CEA modes, `32` for SD CEA modes, and `0` for DMT modes. The default value for `disable_overscan` is `0`. NOTE: Any further additional overscan options such as `overscan_scale` or overscan edges can still be applied after this option. ==== `overscan_left` The `overscan_left` command specifies the number of pixels to add to the firmware default value of overscan on the left edge of the screen. The default value is `0`. Increase this value if the text flows off the left edge of the screen; decrease it if there is a black border between the left edge of the screen and the text. ==== `overscan_right` The `overscan_right` command specifies the number of pixels to add to the firmware default value of overscan on the right edge of the screen. The default value is `0`. Increase this value if the text flows off the right edge of the screen; decrease it if there is a black border between the right edge of the screen and the text. ==== `overscan_top` The `overscan_top` command specifies the number of pixels to add to the firmware default value of overscan on the top edge of the screen. The default value is `0`. Increase this value if the text flows off the top edge of the screen; decrease it if there is a black border between the top edge of the screen and the text. ==== `overscan_bottom` The `overscan_bottom` command specifies the number of pixels to add to the firmware default value of overscan on the bottom edge of the screen. The default value is `0`. Increase this value if the text flows off the bottom edge of the screen; decrease it if there is a black border between the bottom edge of the screen and the text. ==== `overscan_scale` Set `overscan_scale` to `1` to force any non-framebuffer layers to conform to the overscan settings. The default value is `0`. *NOTE:* this feature is generally not recommended: it can reduce image quality because all layers on the display will be scaled by the GPU. Disabling overscan on the display itself is the recommended option to avoid images being scaled twice (by the GPU and the display). ==== `framebuffer_width` The `framebuffer_width` command specifies the console framebuffer width in pixels. The default is the display width minus the total horizontal overscan. ==== `framebuffer_height` The `framebuffer_height` command specifies the console framebuffer height in pixels. The default is the display height minus the total vertical overscan. C4 ==== `max_framebuffer_heigh`t, `max_framebuffer_width` Specifies the maximum dimensions that the internal frame buffer is allowed to be. ==== `framebuffer_depth` Use `framebuffer_depth` to specify the console framebuffer depth in bits per pixel. The default value is `16`. |=== | framebuffer_depth | result | notes | 8 | 8bit framebuffer | Default RGB palette makes screen unreadable | 16 | 16bit framebuffer | | 24 | 24bit framebuffer | May result in a corrupted display | 32 | 32bit framebuffer | May need to be used in conjunction with `framebuffer_ignore_alpha=1` |=== ==== `framebuffer_ignore_alpha` Set `framebuffer_ignore_alpha` to `1` to disable the alpha channel. Can help with the display of a 32bit `framebuffer_depth`. ==== `framebuffer_priority` In a system with multiple displays, using the legacy (pre-KMS) graphics driver, this forces a specific internal display device to be the first Linux framebuffer (i.e. `/dev/fb0`). The options that can be set are: |=== | Display | ID | Main LCD | 0 | Secondary LCD | 1 | HDMI 0 | 2 | Composite | 3 | HDMI 1 | 7 |=== ==== `max_framebuffers` This configuration entry sets the maximum number of firmware framebuffers that can be created. Valid options are 0,1, and 2. By default on devices before the Pi4 this is set to 1, so will need to be increased to 2 when using more than one display, for example HDMI and a DSI or DPI display. The Raspberry Pi4 configuration sets this to 2 by default as it has two HDMI ports. Generally in most cases it is safe to set this to 2, as framebuffers will only be created when an attached device is actually detected. Setting this value to 0 can be used to reduce memory requirements when used in headless mode as it will prevent any framebuffers from being allocated. ==== `test_mode` The `test_mode` command displays a test image and sound during boot (over the composite video and analogue audio outputs only) for the given number of seconds, before continuing to boot the OS as normal. This is used as a manufacturing test; the default value is `0`. ==== `display_hdmi_rotate` Use `display_hdmi_rotate` to rotate or flip the HDMI display orientation. The default value is `0`. |=== | display_hdmi_rotate | result | 0 | no rotation | 1 | rotate 90 degrees clockwise | 2 | rotate 180 degrees clockwise | 3 | rotate 270 degrees clockwise | 0x10000 | horizontal flip | 0x20000 | vertical flip |=== Note that the 90 and 270 degree rotation options require additional memory on the GPU, so these will not work with the 16MB GPU split. If using the VC4 FKMS V3D driver (this is the default on the Raspberry Pi 4), then 90 and 270 degree rotations are not supported. The Screen Configuration utility xref:configuration.adoc#rotating-your-display[provides display rotations] for this driver. ==== `display_lcd_rotate` For the legacy graphics driver (default on models prior to the Pi4), use `display_lcd_rotate` to rotate or flip the LCD orientation. Parameters are the same as `display_hdmi_rotate`. See also `lcd_rotate`. ==== `display_rotate` `display_rotate` is deprecated in the latest firmware but has been retained for backwards compatibility. Please use `display_lcd_rotate` and `display_hdmi_rotate` instead. Use `display_rotate` to rotate or flip the screen orientation. Parameters are the same as `display_hdmi_rotate`. ==== `disable_fw_kms_setup` By default, the firmware parses the EDID of any HDMI attached display, picks an appropriate video mode, then passes the resolution and frame rate of the mode, along with overscan parameters, to the Linux kernel via settings on the kernel command line. In rare circumstances, this can have the effect of choosing a mode that is not in the EDID, and may be incompatible with the device. You can use `disable_fw_kms_setup=1` to disable the passing of these parameters and avoid this problem. The Linux video mode system (KMS) will then parse the EDID itself and pick an appropriate mode. === Other Options ==== `dispmanx_offline` Forces `dispmanx` composition to be done offline in two offscreen framebuffers. This can allow more `dispmanx` elements to be composited, but is slower and may limit screen framerate to typically 30fps. ",12374,True,2536.841104486165,median "tag::aggregations[] If set, the {dfeed} performs aggregation searches. Support for aggregations is limited and should be used only with low cardinality data. For more information, see {ml-docs}/ml-configuring-aggregation.html[Aggregating data for faster performance]. end::aggregations[] tag::allow-lazy-open[] Advanced configuration option. Specifies whether this job can open when there is insufficient {ml} node capacity for it to be immediately assigned to a node. The default value is `false`; if a {ml} node with capacity to run the job cannot immediately be found, the <> returns an error. However, this is also subject to the cluster-wide `xpack.ml.max_lazy_ml_nodes` setting; see <>. If this option is set to `true`, the <> does not return an error and the job waits in the `opening` state until sufficient {ml} node capacity is available. end::allow-lazy-open[] tag::allow-no-datafeeds[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfeeds} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `datafeeds` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-datafeeds[] tag::allow-no-jobs[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no jobs that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `jobs` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-jobs[] tag::allow-no-match[] Specifies what to do when the request: + -- * Contains wildcard expressions and there are no {dfanalytics-jobs} that match. * Contains the `_all` string or no identifiers and there are no matches. * Contains wildcard expressions and there are only partial matches. The default value is `true`, which returns an empty `data_frame_analytics` array when there are no matches and the subset of results when there are partial matches. If this parameter is `false`, the request returns a `404` status code when there are no matches or only partial matches. -- end::allow-no-match[] tag::analysis[] Defines the type of {dfanalytics} you want to perform on your source index. For example: `outlier_detection`. See <>. end::analysis[] tag::analysis-config[] The analysis configuration, which specifies how to analyze the data. After you create a job, you cannot change the analysis configuration; all the properties are informational. end::analysis-config[] tag::analysis-limits[] Limits can be applied for the resources required to hold the mathematical models in memory. These limits are approximate and can be set per job. They do not control the memory used by other processes, for example the {es} Java processes. end::analysis-limits[] tag::assignment-explanation-anomaly-jobs[] For open {anomaly-jobs} only, contains messages relating to the selection of a node to run the job. end::assignment-explanation-anomaly-jobs[] tag::assignment-explanation-datafeeds[] For started {dfeeds} only, contains messages relating to the selection of a node. end::assignment-explanation-datafeeds[] tag::assignment-explanation-dfanalytics[] Contains messages relating to the selection of a node. end::assignment-explanation-dfanalytics[] tag::background-persist-interval[] Advanced configuration option. The time between each periodic persistence of the model. The default value is a randomized value between 3 to 4 hours, which avoids all jobs persisting at exactly the same time. The smallest allowed value is 1 hour. + -- TIP: For very large models (several GB), persistence could take 10-20 minutes, so do not set the `background_persist_interval` value too low. -- end::background-persist-interval[] tag::bucket-allocation-failures-count[] The number of buckets for which new entities in incoming data were not processed due to insufficient model memory. This situation is also signified by a `hard_limit: memory_status` property value. end::bucket-allocation-failures-count[] tag::bucket-count[] The number of buckets processed. end::bucket-count[] tag::bucket-count-anomaly-jobs[] The number of bucket results produced by the job. end::bucket-count-anomaly-jobs[] tag::bucket-span[] The size of the interval that the analysis is aggregated into, typically between `5m` and `1h`. The default value is `5m`. If the {anomaly-job} uses a {dfeed} with {ml-docs}/ml-configuring-aggregation.html[aggregations], this value must be divisible by the interval of the date histogram aggregation. For more information, see {ml-docs}/ml-buckets.html[Buckets]. end::bucket-span[] tag::bucket-span-results[] The length of the bucket in seconds. This value matches the `bucket_span` that is specified in the job. end::bucket-span-results[] tag::bucket-time-exponential-average[] Exponential moving average of all bucket processing times, in milliseconds. end::bucket-time-exponential-average[] tag::bucket-time-exponential-average-hour[] Exponentially-weighted moving average of bucket processing times calculated in a 1 hour time window, in milliseconds. end::bucket-time-exponential-average-hour[] tag::bucket-time-maximum[] Maximum among all bucket processing times, in milliseconds. end::bucket-time-maximum[] tag::bucket-time-minimum[] Minimum among all bucket processing times, in milliseconds. end::bucket-time-minimum[] tag::bucket-time-total[] Sum of all bucket processing times, in milliseconds. end::bucket-time-total[] tag::by-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to their own history. It is used for finding unusual values in the context of the split. end::by-field-name[] tag::calendar-id[] A string that uniquely identifies a calendar. end::calendar-id[] tag::categorization-analyzer[] If `categorization_field_name` is specified, you can also define the analyzer that is used to interpret the categorization field. This property cannot be used at the same time as `categorization_filters`. The categorization analyzer specifies how the `categorization_field` is interpreted by the categorization process. The syntax is very similar to that used to define the `analyzer` in the <>. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. + The `categorization_analyzer` field can be specified either as a string or as an object. If it is a string it must refer to a <> or one added by another plugin. If it is an object it has the following properties: + .Properties of `categorization_analyzer` [%collapsible%open] ===== `char_filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=char-filter] `tokenizer`:::: (string or object) include::{docdir}/ml/ml-shared.asciidoc[tag=tokenizer] `filter`:::: (array of strings or objects) include::{docdir}/ml/ml-shared.asciidoc[tag=filter] ===== end::categorization-analyzer[] tag::categorization-examples-limit[] The maximum number of examples stored per category in memory and in the results data store. The default value is 4. If you increase this value, more examples are available, however it requires that you have more storage available. If you set this value to `0`, no examples are stored. + NOTE: The `categorization_examples_limit` only applies to analysis that uses categorization. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-examples-limit[] tag::categorization-field-name[] If this property is specified, the values of the specified field will be categorized. The resulting categories must be used in a detector by setting `by_field_name`, `over_field_name`, or `partition_field_name` to the keyword `mlcategory`. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. end::categorization-field-name[] tag::categorization-filters[] If `categorization_field_name` is specified, you can also define optional filters. This property expects an array of regular expressions. The expressions are used to filter out matching sequences from the categorization field values. You can use this functionality to fine tune the categorization by excluding sequences from consideration when categories are defined. For example, you can exclude SQL statements that appear in your log files. For more information, see {ml-docs}/ml-configuring-categories.html[Categorizing log messages]. This property cannot be used at the same time as `categorization_analyzer`. If you only want to define simple regular expression filters that are applied prior to tokenization, setting this property is the easiest method. If you also want to customize the tokenizer or post-tokenization filtering, use the `categorization_analyzer` property instead and include the filters as `pattern_replace` character filters. The effect is exactly the same. end::categorization-filters[] tag::categorization-status[] The status of categorization for the job. Contains one of the following values: + -- * `ok`: Categorization is performing acceptably well (or not being used at all). * `warn`: Categorization is detecting a distribution of categories that suggests the input data is inappropriate for categorization. Problems could be that there is only one category, more than 90% of categories are rare, the number of categories is greater than 50% of the number of categorized documents, there are no frequently matched categories, or more than 50% of categories are dead. -- end::categorization-status[] tag::categorized-doc-count[] The number of documents that have had a field categorized. end::categorized-doc-count[] tag::char-filter[] One or more <>. In addition to the built-in character filters, other plugins can provide more character filters. This property is optional. If it is not specified, no character filters are applied prior to categorization. If you are customizing some other aspect of the analyzer and you need to achieve the equivalent of `categorization_filters` (which are not permitted when some other aspect of the analyzer is customized), add them here as <>. end::char-filter[] tag::chunking-config[] {dfeeds-cap} might be required to search over long time periods, for several months or years. This search is split into time chunks in order to ensure the load on {es} is managed. Chunking configuration controls how the size of these time chunks are calculated and is an advanced configuration option. + .Properties of `chunking_config` [%collapsible%open] ==== `mode`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=mode] `time_span`::: (<>) include::{docdir}/ml/ml-shared.asciidoc[tag=time-span] ==== end::chunking-config[] tag::class-assignment-objective[] Defines the objective to optimize when assigning class labels: `maximize_accuracy` or `maximize_minimum_recall`. When maximizing accuracy, class labels are chosen to maximize the number of correct predictions. When maximizing minimum recall, labels are chosen to maximize the minimum recall for any class. Defaults to `maximize_minimum_recall`. end::class-assignment-objective[] tag::compute-feature-influence[] Specifies whether the feature influence calculation is enabled. Defaults to `true`. end::compute-feature-influence[] tag::custom-rules[] An array of custom rule objects, which enable you to customize the way detectors operate. For example, a rule may dictate to the detector conditions under which results should be skipped. For more examples, see {ml-docs}/ml-configuring-detector-custom-rules.html[Customizing detectors with custom rules]. end::custom-rules[] tag::custom-rules-actions[] The set of actions to be triggered when the rule applies. If more than one action is specified the effects of all actions are combined. The available actions include: * `skip_result`: The result will not be created. This is the default value. Unless you also specify `skip_model_update`, the model will be updated as usual with the corresponding series value. * `skip_model_update`: The value for that series will not be used to update the model. Unless you also specify `skip_result`, the results will be created as usual. This action is suitable when certain values are expected to be consistently anomalous and they affect the model in a way that negatively impacts the rest of the results. end::custom-rules-actions[] tag::custom-rules-scope[] An optional scope of series where the rule applies. A rule must either have a non-empty scope or at least one condition. By default, the scope includes all series. Scoping is allowed for any of the fields that are also specified in `by_field_name`, `over_field_name`, or `partition_field_name`. To add a scope for a field, add the field name as a key in the scope object and set its value to an object with the following properties: end::custom-rules-scope[] tag::custom-rules-scope-filter-id[] The id of the filter to be used. end::custom-rules-scope-filter-id[] tag::custom-rules-scope-filter-type[] Either `include` (the rule applies for values in the filter) or `exclude` (the rule applies for values not in the filter). Defaults to `include`. end::custom-rules-scope-filter-type[] tag::custom-rules-conditions[] An optional array of numeric conditions when the rule applies. A rule must either have a non-empty scope or at least one condition. Multiple conditions are combined together with a logical `AND`. A condition has the following properties: end::custom-rules-conditions[] tag::custom-rules-conditions-applies-to[] Specifies the result property to which the condition applies. The available options are `actual`, `typical`, `diff_from_typical`, `time`. If your detector uses `lat_long`, `metric`, `rare`, or `freq_rare` functions, you can only specify conditions that apply to `time`. end::custom-rules-conditions-applies-to[] tag::custom-rules-conditions-operator[] Specifies the condition operator. The available options are `gt` (greater than), `gte` (greater than or equals), `lt` (less than) and `lte` (less than or equals). end::custom-rules-conditions-operator[] tag::custom-rules-conditions-value[] The value that is compared against the `applies_to` field using the `operator`. end::custom-rules-conditions-value[] tag::custom-settings[] Advanced configuration option. Contains custom meta data about the job. For example, it can contain custom URL information as shown in {ml-docs}/ml-configuring-url.html[Adding custom URLs to {ml} results]. end::custom-settings[] tag::data-description[] The data description defines the format of the input data when you send data to the job by using the <> API. Note that when configure a {dfeed}, these properties are automatically set. When data is received via the <> API, it is not stored in {es}. Only the results for {anomaly-detect} are retained. + .Properties of `data_description` [%collapsible%open] ==== `format`::: (string) Only `JSON` format is supported at this time. `time_field`::: (string) The name of the field that contains the timestamp. The default value is `time`. `time_format`::: (string) include::{docdir}/ml/ml-shared.asciidoc[tag=time-format] ==== end::data-description[] tag::datafeed-id[] A numerical character string that uniquely identifies the {dfeed}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::datafeed-id[] tag::datafeed-id-wildcard[] Identifier for the {dfeed}. It can be a {dfeed} identifier or a wildcard expression. end::datafeed-id-wildcard[] tag::dead-category-count[] The number of categories created by categorization that will never be assigned again because another category's definition makes it a superset of the dead category. (Dead categories are a side effect of the way categorization has no prior training.) end::dead-category-count[] tag::delayed-data-check-config[] Specifies whether the {dfeed} checks for missing data and the size of the window. For example: `{""enabled"": true, ""check_window"": ""1h""}`. + The {dfeed} can optionally search over indices that have already been read in an effort to determine whether any data has subsequently been added to the index. If missing data is found, it is a good indication that the `query_delay` option is set too low and the data is being indexed after the {dfeed} has passed that moment in time. See {ml-docs}/ml-delayed-data-detection.html[Working with delayed data]. + This check runs only on real-time {dfeeds}. + .Properties of `delayed_data_check_config` [%collapsible%open] ==== `check_window`:: (<>) The window of time that is searched for late data. This window of time ends with the latest finalized bucket. It defaults to `null`, which causes an appropriate `check_window` to be calculated when the real-time {dfeed} runs. In particular, the default `check_window` span calculation is based on the maximum of `2h` or `8 * bucket_span`. `enabled`:: (boolean) Specifies whether the {dfeed} periodically checks for delayed data. Defaults to `true`. ==== end::delayed-data-check-config[] tag::dependent-variable[] Defines which field of the document is to be predicted. This parameter is supplied by field name and must match one of the fields in the index being used to train. If this field is missing from a document, then that document will not be used for training, but a prediction with the trained model will be generated for it. It is also known as continuous target variable. end::dependent-variable[] tag::desc-results[] If true, the results are sorted in descending order. end::desc-results[] tag::description-dfa[] A description of the job. end::description-dfa[] tag::dest[] The destination configuration, consisting of `index` and optionally `results_field` (`ml` by default). + .Properties of `dest` [%collapsible%open] ==== `index`::: (Required, string) Defines the _destination index_ to store the results of the {dfanalytics-job}. `results_field`::: (Optional, string) Defines the name of the field in which to store the results of the analysis. Defaults to `ml`. ==== end::dest[] tag::detector-description[] A description of the detector. For example, `Low event rate`. end::detector-description[] tag::detector-field-name[] The field that the detector uses in the function. If you use an event rate function such as `count` or `rare`, do not specify this field. + -- NOTE: The `field_name` cannot contain double quotes or backslashes. -- end::detector-field-name[] tag::detector-index[] A unique identifier for the detector. This identifier is based on the order of the detectors in the `analysis_config`, starting at zero. end::detector-index[] tag::dfas-alpha[] Regularization factor to penalize deeper trees when training decision trees. end::dfas-alpha[] tag::dfas-downsample-factor[] The value of the downsample factor. end::dfas-downsample-factor[] tag::dfas-eta-growth[] Specifies the rate at which the `eta` increases for each new tree that is added to the forest. For example, a rate of `1.05` increases `eta` by 5%. end::dfas-eta-growth[] tag::dfas-feature-bag-fraction[] The fraction of features that is used when selecting a random bag for each candidate split. end::dfas-feature-bag-fraction[] tag::dfas-iteration[] The number of iterations on the analysis. end::dfas-iteration[] tag::dfas-max-attempts[] If the algorithm fails to determine a non-trivial tree (more than a single leaf), this parameter determines how many of such consecutive failures are tolerated. Once the number of attempts exceeds the threshold, the forest training stops. end::dfas-max-attempts[] tag::dfas-max-optimization-rounds[] A multiplier responsible for determining the maximum number of hyperparameter optimization steps in the Bayesian optimization procedure. The maximum number of steps is determined based on the number of undefined hyperparameters times the maximum optimization rounds per hyperparameter. end::dfas-max-optimization-rounds[] tag::dfas-num-folds[] The maximum number of folds for the cross-validation procedure. end::dfas-num-folds[] tag::dfas-num-splits[] Determines the maximum number of splits for every feature that can occur in a decision tree when the tree is trained. end::dfas-num-splits[] tag::dfas-soft-limit[] Tree depth limit is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-limit[] tag::dfas-soft-tolerance[] Tree depth tolerance is used for calculating the tree depth penalty. This is a soft limit, it can be exceeded. end::dfas-soft-tolerance[] tag::dfas-timestamp[] The timestamp when the statistics were reported in milliseconds since the epoch. end::dfas-timestamp[] tag::dfas-timing-stats[] An object containing time statistics about the {dfanalytics-job}. end::dfas-timing-stats[] tag::dfas-timing-stats-elapsed[] Runtime of the analysis in milliseconds. end::dfas-timing-stats-elapsed[] tag::dfas-timing-stats-iteration[] Runtime of the latest iteration of the analysis in milliseconds. end::dfas-timing-stats-iteration[] tag::dfas-validation-loss[] An object containing information about validation loss. end::dfas-validation-loss[] tag::dfas-validation-loss-fold[] Validation loss values for every added decision tree during the forest growing procedure. end::dfas-validation-loss-fold[] tag::dfas-validation-loss-type[] The type of the loss metric. For example, `binomial_logistic`. end::dfas-validation-loss-type[] tag::earliest-record-timestamp[] The timestamp of the earliest chronologically input document. end::earliest-record-timestamp[] tag::empty-bucket-count[] The number of buckets which did not contain any data. If your data contains many empty buckets, consider increasing your `bucket_span` or using functions that are tolerant to gaps in data such as `mean`, `non_null_sum` or `non_zero_count`. end::empty-bucket-count[] tag::eta[] Advanced configuration option. The shrinkage applied to the weights. Smaller values result in larger forests which have a better generalization error. However, the smaller the value the longer the training will take. For more information about shrinkage, see https://en.wikipedia.org/wiki/Gradient_boosting#Shrinkage[this wiki article]. By default, this value is calculated during hyperparameter optimization. end::eta[] tag::exclude-frequent[] Contains one of the following values: `all`, `none`, `by`, or `over`. If set, frequent entities are excluded from influencing the anomaly results. Entities can be considered frequent over time or frequent in a population. If you are working with both over and by fields, then you can set `exclude_frequent` to `all` for both fields, or to `by` or `over` for those specific fields. end::exclude-frequent[] tag::exclude-interim-results[] If `true`, the output excludes interim results. By default, interim results are included. end::exclude-interim-results[] tag::failed-category-count[] The number of times that categorization wanted to create a new category but couldn't because the job had hit its `model_memory_limit`. This count does not track which specific categories failed to be created. Therefore you cannot use this value to determine the number of unique categories that were missed. end::failed-category-count[] tag::feature-bag-fraction[] Advanced configuration option. Defines the fraction of features that will be used when selecting a random bag for each candidate split. By default, this value is calculated during hyperparameter optimization. end::feature-bag-fraction[] tag::feature-influence-threshold[] The minimum {olscore} that a document needs to have in order to calculate its {fiscore}. Value range: 0-1 (`0.1` by default). end::feature-influence-threshold[] tag::filter[] One or more <>. In addition to the built-in token filters, other plugins can provide more token filters. This property is optional. If it is not specified, no token filters are applied prior to categorization. end::filter[] tag::filter-id[] A string that uniquely identifies a filter. end::filter-id[] tag::forecast-total[] The number of individual forecasts currently available for the job. A value of `1` or more indicates that forecasts exist. end::forecast-total[] tag::frequency[] The interval at which scheduled queries are made while the {dfeed} runs in real time. The default value is either the bucket span for short bucket spans, or, for longer bucket spans, a sensible fraction of the bucket span. For example: `150s`. When `frequency` is shorter than the bucket span, interim results for the last (partial) bucket are written then eventually overwritten by the full bucket results. If the {dfeed} uses aggregations, this value must be divisible by the interval of the date histogram aggregation. end::frequency[] tag::frequent-category-count[] The number of categories that match more than 1% of categorized documents. end::frequent-category-count[] tag::from[] Skips the specified number of {dfanalytics-jobs}. The default value is `0`. end::from[] tag::function[] The analysis function that is used. For example, `count`, `rare`, `mean`, `min`, `max`, and `sum`. For more information, see {ml-docs}/ml-functions.html[Function reference]. end::function[] tag::gamma[] Advanced configuration option. Regularization parameter to prevent overfitting on the training data set. Multiplies a linear penalty associated with the size of individual trees in the forest. The higher the value the more training will prefer smaller trees. The smaller this parameter the larger individual trees will be and the longer training will take. By default, this value is calculated during hyperparameter optimization. end::gamma[] tag::groups[] A list of job groups. A job can belong to no groups or many. end::groups[] tag::indices[] An array of index names. Wildcards are supported. For example: `[""it_ops_metrics"", ""server*""]`. + -- NOTE: If any indices are in remote clusters then `node.remote_cluster_client` must not be set to `false` on any {ml} nodes. -- end::indices[] tag::indices-options[] Specifies index expansion options that are used during search. + -- For example: ``` { ""expand_wildcards"": [""all""], ""ignore_unavailable"": true, ""allow_no_indices"": ""false"", ""ignore_throttled"": true } ``` For more information about these options, see <>. -- end::indices-options[] tag::inference-config-classification-num-top-classes[] Specifies the number of top class predictions to return. Defaults to 0. end::inference-config-classification-num-top-classes[] tag::inference-config-classification-num-top-feature-importance-values[] Specifies the maximum number of {ml-docs}/ml-feature-importance.html[{feat-imp}] values per document. By default, it is zero and no {feat-imp} calculation occurs. end::inference-config-classification-num-top-feature-importance-values[] tag::inference-config-classification-top-classes-results-field[] Specifies the field to which the top classes are written. Defaults to `top_classes`. end::inference-config-classification-top-classes-results-field[] tag::inference-config-classification-prediction-field-type[] Specifies the type of the predicted field to write. Acceptable values are: `string`, `number`, `boolean`. When `boolean` is provided `1.0` is transformed to `true` and `0.0` to `false`. end::inference-config-classification-prediction-field-type[] tag::inference-config-regression-num-top-feature-importance-values[] Specifies the maximum number of {ml-docs}/ml-feature-importance.html[{feat-imp}] values per document. By default, it is zero and no {feat-imp} calculation occurs. end::inference-config-regression-num-top-feature-importance-values[] tag::inference-config-results-field[] The field that is added to incoming documents to contain the inference prediction. Defaults to `predicted_value`. end::inference-config-results-field[] tag::influencers[] A comma separated list of influencer field names. Typically these can be the by, over, or partition fields that are used in the detector configuration. You might also want to use a field name that is not specifically named in a detector, but is available as part of the input data. When you use multiple detectors, the use of influencers is recommended as it aggregates results for each influencer entity. end::influencers[] tag::input-bytes[] The number of bytes of input data posted to the {anomaly-job}. end::input-bytes[] tag::input-field-count[] The total number of fields in input documents posted to the {anomaly-job}. This count includes fields that are not used in the analysis. However, be aware that if you are using a {dfeed}, it extracts only the required fields from the documents it retrieves before posting them to the job. end::input-field-count[] tag::input-record-count[] The number of input documents posted to the {anomaly-job}. end::input-record-count[] tag::invalid-date-count[] The number of input documents with either a missing date field or a date that could not be parsed. end::invalid-date-count[] tag::is-interim[] If `true`, this is an interim result. In other words, the results are calculated based on partial input data. end::is-interim[] tag::job-id-anomaly-detection[] Identifier for the {anomaly-job}. end::job-id-anomaly-detection[] tag::job-id-data-frame-analytics[] Identifier for the {dfanalytics-job}. end::job-id-data-frame-analytics[] tag::job-id-anomaly-detection-default[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. If you do not specify one of these options, the API returns information for all {anomaly-jobs}. end::job-id-anomaly-detection-default[] tag::job-id-data-frame-analytics-default[] Identifier for the {dfanalytics-job}. If you do not specify this option, the API returns information for the first hundred {dfanalytics-jobs}. end::job-id-data-frame-analytics-default[] tag::job-id-anomaly-detection-list[] An identifier for the {anomaly-jobs}. It can be a job identifier, a group name, or a comma-separated list of jobs or groups. end::job-id-anomaly-detection-list[] tag::job-id-anomaly-detection-wildcard[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, or a wildcard expression. end::job-id-anomaly-detection-wildcard[] tag::job-id-anomaly-detection-wildcard-list[] Identifier for the {anomaly-job}. It can be a job identifier, a group name, a comma-separated list of jobs or groups, or a wildcard expression. end::job-id-anomaly-detection-wildcard-list[] tag::job-id-anomaly-detection-define[] Identifier for the {anomaly-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-anomaly-detection-define[] tag::job-id-data-frame-analytics-define[] Identifier for the {dfanalytics-job}. This identifier can contain lowercase alphanumeric characters (a-z and 0-9), hyphens, and underscores. It must start and end with alphanumeric characters. end::job-id-data-frame-analytics-define[] tag::job-id-datafeed[] The unique identifier for the job to which the {dfeed} sends data. end::job-id-datafeed[] tag::lambda[] Advanced configuration option. Regularization parameter to prevent overfitting on the training data set. Multiplies an L2 regularisation term which applies to leaf weights of the individual trees in the forest. The higher the value the more training will attempt to keep leaf weights small. This makes the prediction function smoother at the expense of potentially not being able to capture relevant relationships between the features and the {depvar}. The smaller this parameter the larger individual trees will be and the longer training will take. By default, this value is calculated during hyperparameter optimization. end::lambda[] tag::last-data-time[] The timestamp at which data was last analyzed, according to server time. end::last-data-time[] tag::latency[] The size of the window in which to expect data that is out of time order. The default value is 0 (no latency). If you specify a non-zero value, it must be greater than or equal to one second. For more information about time units, see <>. + -- NOTE: Latency is only applicable when you send data by using the <> API. -- end::latency[] tag::latest-empty-bucket-timestamp[] The timestamp of the last bucket that did not contain any data. end::latest-empty-bucket-timestamp[] tag::latest-record-timestamp[] The timestamp of the latest chronologically input document. end::latest-record-timestamp[] tag::latest-sparse-record-timestamp[] The timestamp of the last bucket that was considered sparse. end::latest-sparse-record-timestamp[] tag::max-empty-searches[] If a real-time {dfeed} has never seen any data (including during any initial training period) then it will automatically stop itself and close its associated job after this many real-time searches that return no documents. In other words, it will stop after `frequency` times `max_empty_searches` of real-time operation. If not set then a {dfeed} with no end time that sees no data will remain started until it is explicitly stopped. By default this setting is not set. end::max-empty-searches[] tag::max-trees[] Advanced configuration option. Defines the maximum number of trees the forest is allowed to contain. The maximum value is 2000. By default, this value is calculated during hyperparameter optimization. end::max-trees[] tag::method[] The method that {oldetection} uses. Available methods are `lof`, `ldof`, `distance_kth_nn`, `distance_knn`, and `ensemble`. The default value is `ensemble`, which means that {oldetection} uses an ensemble of different methods and normalises and combines their individual {olscores} to obtain the overall {olscore}. end::method[] tag::missing-field-count[] The number of input documents that are missing a field that the {anomaly-job} is configured to analyze. Input documents with missing fields are still processed because it is possible that not all fields are missing. + -- NOTE: If you are using {dfeeds} or posting data to the job in JSON format, a high `missing_field_count` is often not an indication of data issues. It is not necessarily a cause for concern. -- end::missing-field-count[] tag::mode[] There are three available modes: + -- * `auto`: The chunk size is dynamically calculated. This is the default and recommended value. * `manual`: Chunking is applied according to the specified `time_span`. * `off`: No chunking is applied. -- end::mode[] tag::model-bytes[] The number of bytes of memory used by the models. This is the maximum value since the last time the model was persisted. If the job is closed, this value indicates the latest size. end::model-bytes[] tag::model-bytes-exceeded[] The number of bytes over the high limit for memory usage at the last allocation failure. end::model-bytes-exceeded[] tag::model-id[] The unique identifier of the trained {infer} model. end::model-id[] tag::model-memory-limit[] The approximate maximum amount of memory resources that are required for analytical processing. Once this limit is approached, data pruning becomes more aggressive. Upon exceeding this limit, new entities are not modeled. The default value for jobs created in version 6.1 and later is `1024mb`. This value will need to be increased for jobs that are expected to analyze high cardinality fields, but the default is set to a relatively small size to ensure that high resource usage is a conscious decision. The default value for jobs created in versions earlier than 6.1 is `4096mb`. + If you specify a number instead of a string, the units are assumed to be MiB. Specifying a string is recommended for clarity. If you specify a byte size unit of `b` or `kb` and the number does not equate to a discrete number of megabytes, it is rounded down to the closest MiB. The minimum valid value is 1 MiB. If you specify a value less than 1 MiB, an error occurs. For more information about supported byte size units, see <>. + If your `elasticsearch.yml` file contains an `xpack.ml.max_model_memory_limit` setting, an error occurs when you try to create jobs that have `model_memory_limit` values greater than that setting. For more information, see <>. end::model-memory-limit[] tag::model-memory-limit-anomaly-jobs[] The upper limit for model memory usage, checked on increasing values. end::model-memory-limit-anomaly-jobs[] tag::model-memory-status[] The status of the mathematical models, which can have one of the following values: + -- * `ok`: The models stayed below the configured value. * `soft_limit`: The models used more than 60% of the configured memory limit and older unused models will be pruned to free up space. * `hard_limit`: The models used more space than the configured memory limit. As a result, not all incoming data was processed. -- end::model-memory-status[] tag::model-plot-config[] This advanced configuration option stores model information along with the results. It provides a more detailed view into {anomaly-detect}. + -- WARNING: If you enable model plot it can add considerable overhead to the performance of the system; it is not feasible for jobs with many entities. Model plot provides a simplified and indicative view of the model and its bounds. It does not display complex features such as multivariate correlations or multimodal data. As such, anomalies may occasionally be reported which cannot be seen in the model plot. Model plot config can be configured when the job is created or updated later. It must be disabled if performance issues are experienced. -- end::model-plot-config[] tag::model-plot-config-enabled[] If true, enables calculation and storage of the model bounds for each entity that is being analyzed. By default, this is not enabled. end::model-plot-config-enabled[] tag::model-plot-config-terms[] Limits data collection to this comma separated list of partition or by field values. If terms are not specified or it is an empty string, no filtering is applied. For example, ""CPU,NetworkIn,DiskWrites"". Wildcards are not supported. Only the specified `terms` can be viewed when using the Single Metric Viewer. end::model-plot-config-terms[] tag::model-snapshot-id[] A numerical character string that uniquely identifies the model snapshot. For example, `1575402236000 `. end::model-snapshot-id[] tag::model-snapshot-retention-days[] Advanced configuration option. The period of time (in days) that model snapshots are retained. Age is calculated relative to the timestamp of the newest model snapshot. The default value is `1`, which means snapshots that are one day (twenty-four hours) older than the newest snapshot are deleted. end::model-snapshot-retention-days[] tag::model-timestamp[] The timestamp of the last record when the model stats were gathered. end::model-timestamp[] tag::multivariate-by-fields[] This functionality is reserved for internal use. It is not supported for use in customer environments and is not subject to the support SLA of official GA features. + -- If set to `true`, the analysis will automatically find correlations between metrics for a given `by` field value and report anomalies when those correlations cease to hold. For example, suppose CPU and memory usage on host A is usually highly correlated with the same metrics on host B. Perhaps this correlation occurs because they are running a load-balanced application. If you enable this property, then anomalies will be reported when, for example, CPU usage on host A is high and the value of CPU usage on host B is low. That is to say, you'll see an anomaly when the CPU of host A is unusual given the CPU of host B. NOTE: To use the `multivariate_by_fields` property, you must also specify `by_field_name` in your detector. -- end::multivariate-by-fields[] tag::n-neighbors[] Defines the value for how many nearest neighbors each method of {oldetection} uses to calculate its {olscore}. When the value is not set, different values are used for different ensemble members. This default behavior helps improve the diversity in the ensemble; only override it if you are confident that the value you choose is appropriate for the data set. end::n-neighbors[] tag::node-address[] The network address of the node. end::node-address[] tag::node-attributes[] Lists node attributes such as `ml.machine_memory` or `ml.max_open_jobs` settings. end::node-attributes[] tag::node-datafeeds[] For started {dfeeds} only, this information pertains to the node upon which the {dfeed} is started. end::node-datafeeds[] tag::node-ephemeral-id[] The ephemeral ID of the node. end::node-ephemeral-id[] tag::node-id[] The unique identifier of the node. end::node-id[] tag::node-jobs[] Contains properties for the node that runs the job. This information is available only for open jobs. end::node-jobs[] tag::node-transport-address[] The host and port where transport HTTP connections are accepted. end::node-transport-address[] tag::open-time[] For open jobs only, the elapsed time for which the job has been open. end::open-time[] tag::out-of-order-timestamp-count[] The number of input documents that are out of time sequence and outside of the latency window. This information is applicable only when you provide data to the {anomaly-job} by using the <>. These out of order documents are discarded, since jobs require time series data to be in ascending chronological order. end::out-of-order-timestamp-count[] tag::outlier-fraction[] The proportion of the data set that is assumed to be outlying prior to {oldetection}. For example, 0.05 means it is assumed that 5% of values are real outliers and 95% are inliers. end::outlier-fraction[] tag::over-field-name[] The field used to split the data. In particular, this property is used for analyzing the splits with respect to the history of all splits. It is used for finding unusual values in the population of all splits. For more information, see {ml-docs}/ml-configuring-pop.html[Performing population analysis]. end::over-field-name[] tag::partition-field-name[] The field used to segment the analysis. When you use this property, you have completely independent baselines for each value of this field. end::partition-field-name[] tag::prediction-field-name[] Defines the name of the prediction field in the results. Defaults to `_prediction`. end::prediction-field-name[] tag::processed-field-count[] The total number of fields in all the documents that have been processed by the {anomaly-job}. Only fields that are specified in the detector configuration object contribute to this count. The timestamp is not included in this count. end::processed-field-count[] tag::processed-record-count[] The number of input documents that have been processed by the {anomaly-job}. This value includes documents with missing fields, since they are nonetheless analyzed. If you use {dfeeds} and have aggregations in your search query, the `processed_record_count` is the number of aggregation results processed, not the number of {es} documents. end::processed-record-count[] tag::randomize-seed[] Defines the seed to the random generator that is used to pick which documents will be used for training. By default it is randomly generated. Set it to a specific value to ensure the same documents are used for training assuming other related parameters (for example, `source`, `analyzed_fields`, etc.) are the same. end::randomize-seed[] tag::query[] The {es} query domain-specific language (DSL). This value corresponds to the query object in an {es} search POST body. All the options that are supported by {es} can be used, as this object is passed verbatim to {es}. By default, this property has the following value: `{""match_all"": {""boost"": 1}}`. end::query[] tag::query-delay[] The number of seconds behind real time that data is queried. For example, if data from 10:04 a.m. might not be searchable in {es} until 10:06 a.m., set this property to 120 seconds. The default value is randomly selected between `60s` and `120s`. This randomness improves the query performance when there are multiple jobs running on the same node. For more information, see {ml-docs}/ml-delayed-data-detection.html[Handling delayed data]. end::query-delay[] tag::rare-category-count[] The number of categories that match just one categorized document. end::rare-category-count[] tag::renormalization-window-days[] Advanced configuration option. The period over which adjustments to the score are applied, as new data is seen. The default value is the longer of 30 days or 100 `bucket_spans`. end::renormalization-window-days[] tag::results-index-name[] A text string that affects the name of the {ml} results index. The default value is `shared`, which generates an index named `.ml-anomalies-shared`. end::results-index-name[] tag::results-retention-days[] Advanced configuration option. The period of time (in days) that results are retained. Age is calculated relative to the timestamp of the latest bucket result. If this property has a non-null value, once per day at 00:30 (server time), results that are the specified number of days older than the latest bucket result are deleted from {es}. The default value is null, which means all results are retained. end::results-retention-days[] tag::retain[] If `true`, this snapshot will not be deleted during automatic cleanup of snapshots older than `model_snapshot_retention_days`. However, this snapshot will be deleted when the job is deleted. The default value is `false`. end::retain[] tag::script-fields[] Specifies scripts that evaluate custom expressions and returns script fields to the {dfeed}. The detector configuration objects in a job can contain functions that use these script fields. For more information, see {ml-docs}/ml-configuring-transform.html[Transforming data with script fields] and <>. end::script-fields[] tag::scroll-size[] The `size` parameter that is used in {es} searches. The default value is `1000`. end::scroll-size[] tag::search-bucket-avg[] The average search time per bucket, in milliseconds. end::search-bucket-avg[] tag::search-count[] The number of searches run by the {dfeed}. end::search-count[] tag::search-exp-avg-hour[] The exponential average search time per hour, in milliseconds. end::search-exp-avg-hour[] tag::search-time[] The total time the {dfeed} spent searching, in milliseconds. end::search-time[] tag::size[] Specifies the maximum number of {dfanalytics-jobs} to obtain. The default value is `100`. end::size[] tag::snapshot-id[] Identifier for the model snapshot. end::snapshot-id[] tag::sparse-bucket-count[] The number of buckets that contained few data points compared to the expected number of data points. If your data contains many sparse buckets, consider using a longer `bucket_span`. end::sparse-bucket-count[] tag::standardization-enabled[] If `true`, the following operation is performed on the columns before computing outlier scores: (x_i - mean(x_i)) / sd(x_i). Defaults to `true`. For more information about this concept, see {wikipedia}/Feature_scaling#Standardization_(Z-score_Normalization)[Wikipedia]. end::standardization-enabled[] tag::state-anomaly-job[] The status of the {anomaly-job}, which can be one of the following values: + -- * `closed`: The job finished successfully with its model state persisted. The job must be opened before it can accept further data. * `closing`: The job close action is in progress and has not yet completed. A closing job cannot accept further data. * `failed`: The job did not finish successfully due to an error. This situation can occur due to invalid input data, a fatal error occurring during the analysis, or an external interaction such as the process being killed by the Linux out of memory (OOM) killer. If the job had irrevocably failed, it must be force closed and then deleted. If the {dfeed} can be corrected, the job can be closed and then re-opened. * `opened`: The job is available to receive and process data. * `opening`: The job open action is in progress and has not yet completed. -- end::state-anomaly-job[] tag::state-datafeed[] The status of the {dfeed}, which can be one of the following values: + -- * `starting`: The {dfeed} has been requested to start but has not yet started. * `started`: The {dfeed} is actively receiving data. * `stopping`: The {dfeed} has been requested to stop gracefully and is completing its final action. * `stopped`: The {dfeed} is stopped and will not receive data until it is re-started. -- end::state-datafeed[] tag::summary-count-field-name[] If this property is specified, the data that is fed to the job is expected to be pre-summarized. This property value is the name of the field that contains the count of raw data points that have been summarized. The same `summary_count_field_name` applies to all detectors in the job. + -- NOTE: The `summary_count_field_name` property cannot be used with the `metric` function. -- end::summary-count-field-name[] tag::tags[] A comma delimited string of tags. A {infer} model can have many tags, or none. When supplied, only {infer} models that contain all the supplied tags are returned. end::tags[] tag::timeout-start[] Controls the amount of time to wait until the {dfanalytics-job} starts. Defaults to 20 seconds. end::timeout-start[] tag::timeout-stop[] Controls the amount of time to wait until the {dfanalytics-job} stops. Defaults to 20 seconds. end::timeout-stop[] tag::time-format[] The time format, which can be `epoch`, `epoch_ms`, or a custom pattern. The default value is `epoch`, which refers to UNIX or Epoch time (the number of seconds since 1 Jan 1970). The value `epoch_ms` indicates that time is measured in milliseconds since the epoch. The `epoch` and `epoch_ms` time formats accept either integer or real values. + + NOTE: Custom patterns must conform to the Java `DateTimeFormatter` class. When you use date-time formatting patterns, it is recommended that you provide the full date, time and time zone. For example: `yyyy-MM-dd'T'HH:mm:ssX`. If the pattern that you specify is not sufficient to produce a complete timestamp, job creation fails. end::time-format[] tag::time-span[] The time span that each search will be querying. This setting is only applicable when the mode is set to `manual`. For example: `3h`. end::time-span[] tag::timestamp-results[] The start time of the bucket for which these results were calculated. end::timestamp-results[] tag::tokenizer[] The name or definition of the <> to use after character filters are applied. This property is compulsory if `categorization_analyzer` is specified as an object. Machine learning provides a tokenizer called `ml_classic` that tokenizes in the same way as the non-customizable tokenizer in older versions of the product. If you want to use that tokenizer but change the character or token filters, specify `""tokenizer"": ""ml_classic""` in your `categorization_analyzer`. end::tokenizer[] tag::total-by-field-count[] The number of `by` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-by-field-count[] tag::total-category-count[] The number of categories created by categorization. end::total-category-count[] tag::total-over-field-count[] The number of `over` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-over-field-count[] tag::total-partition-field-count[] The number of `partition` field values that were analyzed by the models. This value is cumulative for all detectors in the job. end::total-partition-field-count[] tag::training-percent[] Defines what percentage of the eligible documents that will be used for training. Documents that are ignored by the analysis (for example those that contain arrays with more than one value) won’t be included in the calculation for used percentage. Defaults to `100`. end::training-percent[] tag::use-null[] Defines whether a new series is used as the null series when there is no value for the by or partition fields. The default value is `false`. end::use-null[] ",12386,True,2550.884736948769,median "== Migration Changes === Migrating to 9.0.0 ===== Improved handling of user locale A number of improvements have been made to how the locale for the login page is selected, as well as when the locale is updated for a user. See the link:{adminguide_link}#_user_locale_selection[{adminguide_name}] for more details. === Migrating to 8.0.2 ==== More Authentication flows changes REQUIRED and ALTERNATIVE executions not supported at same flow:: In previous version, it was possible to have REQUIRED and ALTERNATIVE executions in the same authentication flow at the same level. There were some issues with this approach and we did the refactoring in the Authentication SPI, which means that this is not considered valid anymore. If ALTERNATIVE and REQUIRED executions are configured at the same level, the ALTERNATIVE executions are considered disabled. So when migrating to the newest version, your existing authentication flows will be automatically migrated preserved the same behavior as existed in the previous version. If they contain ALTERNATIVE executions at the same level as some REQUIRED executions, then the ALTERNATIVE executions will be added to the separate REQUIRED subflow. This should ensure same/similar behavior of the particular authentication flow as in the previous version. We always recommend to doublecheck the configuration of your authentication flow and test it to doublecheck that everything works as expected. This recommendation is true in particular if you have some more customized authentication flows with custom authenticator implementations. === Migrating to 8.0.0 ==== New Default Hostname provider The old request and fixed hostname providers have been replaced with a new default hostname provider. The request and fixed hostname providers are now deprecated and it is recommended to switch to the default hostname provider as soon as possible. ==== Upgrade to Wildfly 18 The {project_name} server was upgraded to use Wildfly 18 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are a few changes related to the migration, which are worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 18 server. For example, Infinispan is now 9.4.16.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ==== Deploying Scripts to the Server Until now, administrators were allowed to upload scripts to the server through the {project_name} Administration Console as well as through the RESTful Admin API. For now on, this capability is *disabled* by default and users should prefer to deploy scripts directly to the server. For more details, please take a look at link:{developerguide_jsproviders_link}[{developerguide_jsproviders_name}]. ==== Client Credentials in the JavaScript adapter In the previous releases, developers were allowed to provide client credentials to the JavaScript adapter. For now on, this capability was *removed*, because client-side apps are not safe to keep secrets. ==== Authentication flows changes We did some refactoring and improvements related to the authentication flows, which requires some attention during migration. OPTIONAL execution requirement removed:: Regarding migration, the most important change is removing the support for the OPTIONAL requirement from authentication executions and replacing it with the CONDITIONAL requirement, which allows more flexibility. The existing OPTIONAL authenticators configured in the previous version will be replaced with the CONDITIONAL subflows. These subflows will have the `Condition - User Configured` condition configured as first execution, and the previously OPTIONAL authenticator (for example `OTP Form`) as second execution. From the user's point of view, the behavior during authentication should be same as in the previous version. Changes in the Java SPI:: There are some changes in the Java Authentication SPI and Credential Provider SPI. The interface `Authenticator` is not changed, but you may be affected if you're developing more advanced authenticators, which introduce some new credential types (subclasses of `CredentialModel`). There are changes on the `CredentialProvider` interface and introduction of some new interfaces like `CredentialValidator`. Also you may be affected if your authenticator supported the OPTIONAL execution requirement. It is recommended to double check the latest authentication examples in the server development guide for more details. Freemarker template changes:: There are also some changes in the freemarker templates. You may be affected if you have your own theme with custom freemarker templates for login forms or some account forms, especially for the forms related to OTP. It is recommended to double check changes in the Freemarker templates in the latest {project_name} and align your templates according to it. ==== User credentials changes We added more flexibility around storing of user credentials. Among other things, every user can have multiple credentials of the same type, for example multiple OTP credentials. There are some changes in the database schema in relation to that, however the credentials from the previous version should be automatically updated to the new format and users should be still able to login with their passwords or OTP credentials set in the previous version. === Migrating to 7.0.0 ==== Upgrade to Wildfly 17 The {project_name} server was upgraded to use Wildfly 17 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are a few changes related to the migration, which are worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 17 server. For example, Infinispan is now 9.4.14.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. === Migrating to 6.0.0 ==== Upgrade to Wildfly 16 The {project_name} server was upgraded to use Wildfly 16 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 16 server. For example, Infinispan is now 9.4.8.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ==== New optional client scope We have added a new `microprofile-jwt` optional client scope to handle the claims defined in the https://wiki.eclipse.org/MicroProfile/JWT_Auth[MicroProfile/JWT Auth Specification]. This new client scope defines protocol mappers to set the username of the authenticated user to the `upn` claim and to set the realm roles to the `groups` claim. ==== Ability to propagate prompt=none to default IDP We have added a new switch in the OIDC identity provider configuration named `Accepts prompt=none forward from client` to identify IDPs that are able to handle forwarded requests that include the `prompt=none` query parameter. Until now, when receiving an auth request with `prompt=none` a realm would return a `login_required` error if the user is not authenticated in the realm without checking if the user has been authenticated by an IDP. From now on, if a default IDP can be determined for the auth request (either by the use of the `kc_idp_hint` query param or by setting up a default IDP for the realm) and if the `Accepts prompt=none forward from client` switch has been enabled for the IDP, the auth request is forwarded to the IDP to check if the user has been authenticated there. It is important to note that this switch is only taken into account if a default IDP is specified, in which case we know where to forward the auth request without having to prompt the user to select an IDP. If a default IDP cannot be determined we cannot assume which one will be used to fulfill the auth request so the request forwarding is not performed. === Migrating to 5.0.0 ==== Upgrade to Wildfly 15 The {project_name} server was upgraded to use Wildfly 15 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 15 server. For example, Infinispan is now 9.4.3.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. === Migrating to 4.8.2 ==== Google Identity Provider updated to use Google Sign-in authentication system The Google Identity Provider implementation in {project_name} up to version 4.8.1 relies on the Google+ API endpoints endpoints for authorization and obtaining the user profile. From March 2019 onwards, Google is removing support for the Google+ API in favor of the new Google Sign-in authentication system. The {project_name} identity provider has been updated to use the new endpoints so if this integration is in use make sure you upgrade to {project_name} version 4.8.2 or later. If you run into an error saying that the application identifier was not found in the directory, you will have to register the client application again in the https://console.developers.google.com/apis/credentials[Google API Console] portal to obtain a new application id and secret. It is possible that you will need to adjust custom mappers for non-standard claims that were provided by Google+ user information endpoint and are provided under different name by Google Sign-in API. Please consult Google documentation for the most up-to-date information on available claims. ==== LinkedIn Social Broker Updated to Version 2 of LinkedIn APIs Accordingly with LinkedIn, all developers need to migrate to version 2.0 of their APIs and OAuth 2.0. As such, we have updated our LinkedIn Social Broker. Existing deployments using this broker may start experiencing errors when fetching user's profile using version 2 of LinkedIn APIs. This error may be related with the lack of permissions granted to the client application used to configure the broker which may not be authorized to access the Profile API or request specific OAuth2 scopes during the authentication process. Even for newly created LinkedIn client applications, you need to make sure that the client is able to request the `r_liteprofile` and `r_emailaddress` OAuth2 scopes, at least, as well that the client application can fetch current member's profile from the `https://api.linkedin.com/v2/me` endpoint. Due to these privacy restrictions imposed by LinkedIn in regards to access to member's information and the limited set of claims returned by the current member's Profile API, the LinkedIn Social Broker is now using the member's email address as the default username. That means that the `r_emailaddress` is always set when sending authorization requests during the authentication. === Migrating to 4.6.0 ==== New default client scopes We have added new realm default client scopes `roles` and `web-origins`. These client scopes contain protocol mappers to add the roles of the user and allowed web origins to the token. During migration, these client scopes should be automatically added to all the OpenID Connect clients as default client scopes. Hence no setup should be required after database migration is finished. ===== Protocol mapper SPI addition Related to this, there is a small addition in the (unsupported) Protocol Mappers SPI. You can be affected only if you implemented a custom ProtocolMapper. There is a new `getPriority()` method on the ProtocolMapper interface. The method has the default implementation set to return 0. If your protocol mapper implementation relies on the roles in the access token `realmAccess` or `resourceAccess` properties, you may need to increase the priority of your mapper. ===== Audience resolving Audiences of all the clients, for which authenticated user has at least one client role in the token, are automatically added to the `aud` claim in the access token now. On the other hand, an access token may not automatically contain the audience of the frontend client, for which it was issued. Read the link:{adminguide_link}#_audience[{adminguide_name}] for more details. ==== JavaScript Adapter Promise To use native JavaScript promise with the JavaScript adapter it is now required to set `promiseType` to `native` in the init options. In the past if native promise was available a wrapper was returned that provided both the legacy Keycloak promise and the native promise. This was causing issues as the error handler was not always set prior to the native error event, which resulted in `Uncaught (in promise)` error. ==== Microsoft Identity Provider updated to use the Microsoft Graph API The Microsoft Identity Provider implementation in {project_name} up to version 4.5.0 relies on the Live SDK endpoints for authorization and obtaining the user profile. From November 2018 onwards, Microsoft is removing support for the Live SDK API in favor of the new Microsoft Graph API. The {project_name} identity provider has been updated to use the new endpoints so if this integration is in use make sure you upgrade to {project_name} version 4.6.0 or later. Legacy client applications registered under ""Live SDK applications"" won't work with the Microsoft Graph endpoints due to changes in the id format of the applications. If you run into an error saying that the application identifier was not found in the directory, you will have to register the client application again in the https://account.live.com/developers/applications/create[Microsoft Application Registration] portal to obtain a new application id. ==== Upgrade to Wildfly 14 The {project_name} server was upgraded to use Wildfly 14 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 14 server. For example, Infinispan is now 9.3.1.Final. Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. ifeval::[{project_product}==true] * There is a need to add `protocolVersion` property with the value `2.6` to the configuration of the `remote-store` element in the {project_name} configuration. This is required as there is a need to downgrade the version of HotRod protocol to be compatible with the version used by {jdgserver_name} {jdgserver_version}. endif::[] === Migrating to 4.4.0 ==== Upgrade to Wildfly 13 The {project_name} server was upgraded to use Wildfly 13 as the underlying container. This does not directly involve any specific {project_name} server functionality, but there are few changes related to the migration, which worth mentioning. Dependency updates:: The dependencies were updated to the versions used by Wildfly 13 server. For example, Infinispan is now 9.2.4.Final and Undertow is 2.0.9.Final Configuration changes:: There are few configuration changes in the `standalone(-ha).xml` and `domain.xml` files. You should follow the <<_install_new_version>> section to handle the migration of configuration files automatically. If more detail is needed, because, for example, you did some configuration changes on your own, here is a list of the most important changes: * Element `eviction` on infinispan caches is now deprecated (unused) and was replaced by element `object-memory` * There is no `jndi-attribute` on `cache-container` element in infinispan subsystem. Cross-Datacenter Replication changes:: * You will need to upgrade {jdgserver_name} server to version {jdgserver_version}. The older version may still work, but it is not guaranteed as we don't test it anymore. * You don't need to configure security anymore in the {jdgserver_name} server configuration file. ifeval::[{project_community}==true] * There is a need to remove `transaction` element from the configuration of replicated caches in the {jdgserver_name} server configuration file. This is needed because of the infinispan bug https://issues.redhat.com/browse/ISPN-9323. endif::[] === Migration to 4.3.0 ==== Hostname configuration In previous versions it was recommended to use a filter to specify permitted hostnames. It is now possible to set a fixed hostname which makes it easier to make sure the valid hostname is used and also allows internal applications to invoke {project_name} through an alternative URL, for example an internal IP address. It is recommended that you switch to this approach in production. === Migrating to 4.0.0 ==== Client Templates changed to Client Scopes We added support for Client Scopes, which requires some attention during migration. Client Templates changed to Client Scopes:: Client Templates were changed to Client Scopes. If you had any Client Templates, their protocol mappers and role scope mappings will be preserved. Spaces replaced in the names:: Client templates with the space character in the name were renamed by replacing spaces with an underscore, because spaces are not allowed in the name of client scopes. For example, a client template `my template` will be changed to client scope `my_template`. Linking Client Scopes to Clients:: For clients which had the client template, the corresponding client scope is now added as `Default Client Scope` to the client. So protocol mappers and role scope mappings will be preserved on the client. Realm Default Client Scopes not linked with existing clients:: During the migration, the list of built-in client scopes is added to each realm as well as list of `Realm Default Client Scopes`. However, existing clients are NOT upgraded and new client scopes are NOT automatically added to them. Also all the protocol mappers and role scope mappings are kept on existing clients. In the new version, when you create a new client, it automatically has Realm Default Client Scopes attached to it and it does not have any protocol mappers attached to it. We did not change existing clients during migration as it would be impossible to properly detect customizations, which you will have for protocol mappers of the clients, for example. If you want to update existing clients (remove protocol mappers from them and link them with client scopes), you will need to do it manually. Consents need to be confirmed again:: The client scopes change required the refactoring of consents. Consents now point to client scopes, not to roles or protocol mappers. Because of this change, the previously confirmed persistent consents by users are not valid anymore and users need to confirm the consent page again after the migration. Some configuration switches removed:: The switch `Scope Param Required` was removed from Role Detail. The switches `Consent Required` and `Consent Text` were removed from the Protocol Mapper details. Those switches were replaced by the Client Scope feature. ==== Changes to Authorization Services We added support for UMA 2.0. This version of the UMA specification introduced some important changes on how permissions are obtained from the server. Here are the main changes introduced by UMA 2.0 support. See link:{authorizationguide_link}[{authorizationguide_name}] for details. Authorization API was removed:: Prior to UMA 2.0 (UMA 1.0), client applications were using the Authorization API to obtain permissions from the server in the format of a RPT. The new version of UMA specification has removed the Authorization API which was also removed from {project_name}. In UMA 2.0, RPTs can now be obtained from the token endpoint by using a specific grant type. See link:{authorizationguide_link}#_service_obtaining_permissions[{authorizationguide_name}] for details. Entitlement API was removed:: With the introduction of UMA 2.0, we decided to leverage the token endpoint and UMA grant type to allow obtaining RPTs from {project_name} and avoid having different APIs. The functionality provided by the Entitlement API was kept the same and is still possible to obtain permissions for a set of one or more resources and scopes or all permissions from the server in case no resource or scope is provided. See link:{authorizationguide_link}#_service_obtaining_permissions[{authorizationguide_name}] for details. Changes to UMA Discovery Endpoint:: UMA Discovery document changed, see link:{authorizationguide_link}#_service_authorization_api[{authorizationguide_name}] for details. Changes to {project_name} Authorization JavaScript Adapter:: The {project_name} Authorization JavaScript Adapter (keycloak-authz.js) changed in order to comply with the changes introduced by UMA 2.0 while keeping the same behavior as before. The main change is on how you invoke both `authorization` and `entitlement` methods which now expect a specific object type representing an authorization request. This new object type provides more flexibility on how permissions can be obtained from the server by supporting the different parameters supported by the UMA grant type. See link:{authorizationguide_link}#_enforcer_js_adapter[{authorizationguide_name}] for details. One of the main changes introduced by this release is that you are no longer required to exchange access tokens with RPTs in order to access resources protected by a resource server (when not using UMA). Depending on how the policy enforcer is configured on the resource server side, you can just send regular access tokens as a bearer token and permissions will still be enforced. Changes to {project_name} Authorization Client Java API:: When upgrading to the new version of {project_name} Authorization Client Java API, you'll notice that some representation classes were moved to a different package in `org.keycloak:keycloak-core`. === Migrating to 3.4.2 ==== Added session_state parameter to OpenID Connect Authentication Response The OpenID Connect Session Management specification requires that the parameter `session_state` is present in the OpenID Connect Authentication Response. In past releases, we did not have this parameter, but now {project_name} adds this parameter by default, as required by the specification. However, some OpenID Connect / OAuth2 adapters, and especially older {project_name} adapters, may have issues with this new parameter. For example, the parameter will be always present in the browser URL after successful authentication to the client application. In these cases, it may be useful to disable adding the `session_state` parameter to the authentication response. This can be done for the particular client in the {project_name} admin console, in client details in the section with `OpenID Connect Compatibility Modes`, described in <<_compatibility_with_older_adapters>>. There is the `Exclude Session State From Authentication Response` switch, which can be turned on to prevent adding the `session_state` parameter to the Authentication Response. NOTE: The parameter `session_state` was added in 3.4.2, however the switch `Exclude Session State From Authentication Response` was added in 4.0.0.Beta1. If your {project_name} server is on 3.4.2 or 3.4.3 and you have issues with `session_state` parameter, you will need to upgrade the server to 4.0.0.Beta1 or newer. === Migrating to 3.2.0 ==== New Password Hashing algorithms We've added two new password hashing algorithms (pbkdf2-sha256 and pbkdf2-sha512). New realms will use the pbkdf2-sha256 hashing algorithm with 27500 hashing iterations. Since pbkdf2-sha256 is slightly faster than pbkdf2 the iterations was increased to 27500 from 20000. Existing realms are upgraded if the password policy contains the default value for hashing algorithm (not specified) and iteration (20000). If you have changed the hashing iterations you need to manually change to pbkdf2-sha256 if you'd like to use the more secure hashing algorithm. ==== ID Token requires scope=openid OpenID Connect specification requires that parameter `scope` with value `openid` is used in initial authorization request. So in {project_name} 2.1.0 we changed our adapters to use `scope=openid` in the redirect URI to {project_name}. Now we changed the server part too and ID token will be sent to the application just if `scope=openid` is really used. If it's not used, then ID token will be skipped and just Access token and Refresh token will be sent to the application. This also allows that you can omit the generation of ID Token on purpose - for example for space or performance purposes. Direct grants (OAuth2 Resource Owner Password Credentials Grant) and Service accounts login (OAuth2 Client credentials grant) also don't use ID Token by default now. You need to explicitly add `scope=openid` parameter to have ID Token included. ==== Authentication sessions and Action tokens We are working on support for multiple datacenters. As the initial step, we introduced authentication session and action tokens. Authentication session replaces Client session, which was used in previous versions. Action tokens are currently used especially for the scenarios, where the authenticator or requiredActionProvider requires sending email to the user and requires user to click on the link in email. Here are concrete changes related to this, which may affect you for the migration. First change related to this is introducing new Infinispan caches `authenticationSessions` and `actionTokens` in `standalone.xml` or `standalone-ha.xml`. If you use our migration CLI, you don't need to care much as your `standalone(-ha).xml` files will be migrated automatically. Second change is changing of some signatures in methods of authentication SPI. This may affect you if you use custom `Authenticator` or `RequiredActionProvider`. Classes `AuthenticationFlowContext` and `RequiredActionContext` now allow to retrieve authentication session instead of client session. We also added some initial support for sticky sessions. You may want to change your loadbalancer/proxy server and configure it if you don't want to suffer from it and want to have better performance. The route is added to the new `AUTH_SESSION_ID` cookie. More info in the clustering documentation. Another change is, that `token.getClientSession()` was removed. This may affect you for example if you're using Client Initiated Identity Broker Linking feature. The `ScriptBasedAuthenticator` changed the binding name from `clientSession` to `authenticationSession`, so you would need to update your scripts if you're using this authenticator. Finally we added some new timeouts to the admin console. This allows you for example to specify different timeouts for the email actions triggered by admin and by user himself. === Migrating to 2.5.1 ==== Migration of old offline tokens If you migrate from version 2.2.0 or older and you used offline tokens, then your offline tokens didn't have KID in the token header. We added KID to the token header in 2.3.0 together with the ability to have multiple realm keys, so {project_name} is able to find the correct key based on the token KID. For the offline tokens without KID, {project_name} 2.5.1 will always use the active realm key to find the proper key for the token verification. In other words, migration of old offline tokens will work. So for example, your user requested offline token in 1.9.8, then you migrate from 1.9.8 to 2.5.1 and then your user will be still able to refresh his old offline token in 2.5.1 version. But there is limitation, that once you change the realm active key, the users won't be able to refresh old offline tokens anymore. So you shouldn't change the active realm key until all your users with offline tokens refreshed their tokens. Obviously newly refreshed tokens will have KID in the header, so after all users exchange their old offline tokens, you are free to change the active realm key. === Migrating to 2.5.0 ==== Changes to the Infinispan caches The `realms` cache defined in the infinispan subsystem in `standalone.xml` or `standalone-ha.xml` configuration file, now has the eviction with the 10000 records by default. This is the same default like the `users` cache. Also the `authorization` cache now doesn't have any eviction on it by default. === Migrating to 2.4.0 ==== Server SPI split into Server SPI and Sever SPI Private The keycloak-server-spi module has been split into keycloak-server-spi and keycloak-server-spi-private. APIs within keycloak-server-spi will not change between minor releases, while we reserve the right and may quite likely change APIs in keycloak-server-spi-private between minor releases. ==== Key encryption algorithm in SAML assertions Key in SAML assertions and documents are now encrypted using RSA-OAEP encryption scheme. If you want to use encrypted assertions, make sure that service providers understand this encryption scheme. In the unlikely case that SP would not be able to handle the new scheme, {project_name} can be made to use legacy RSA-v1.5 encryption scheme when started with system property `keycloak.saml.key_trans.rsa_v1.5` set to `true`. ==== Infinispan caches realms and users are always local Even if you use {project_name} in cluster, the caches `realms` and `users` defined in infinispan subsystem in `standalone-ha.xml` are always local caches now. There is separate cache `work`, which handles sending invalidation messages between cluster nodes and informing whole cluster what records in underlying `realms` and `users` caches should be invalidated. === Migrating to 2.3.0 ==== Default max results on paginated endpoints All Admin REST API endpoints that support pagination now have a default max results set to 100. If you want to return more than 100 entries you need to explicitly specify that with `?max=`. ==== `realm-public-key` adapter property not recommended In 2.3.0 release we added support for Public Key Rotation. When admin rotates the realm keys in Keycloak admin console, the Client Adapter will be able to recognize it and automatically download new public key from Keycloak. However this automatic download of new keys is done just if you don't have `realm-public-key` option in your adapter with the hardcoded public key. For this reason, we don't recommend to use `realm-public-key` option in adapter configuration anymore. Note this option is still supported, but it may be useful just if you really want to have hardcoded public key in your adapter configuration and never download the public key from Keycloak. In theory, one reason for this can be to avoid man-in-the-middle attack if you have untrusted network between adapter and Keycloak, however in that case, it is much better option to use HTTPS, which will secure all the requests between adapter and Keycloak. ==== Added Infinispan cache `keys` In this release, we added new cache `keys` to the infinispan subsystem, which is defined in `standalone.xml` or `standalone-ha.xml` configuration file. It has also some eviction and expiration defined. This cache is internally used for caching the external public keys of the entities trusted by the server (Identity providers or clients, which uses authentication with signed JWT). === Migrating to 2.2.0 ==== `databaseSchema` property deprecated The `databaseSchema` property for both JPA and Mongo is now deprecated and has been replaced by `initializeEmpty` and `migrationStrategy`. `initializeEmpty` can bet set to `true` or `false` and controls if an empty database should be initialized. `migrationStrategy` can be set to `update`, `validate` and `manual`. `manual` is only supported for relational databases and will write an SQL file with the required changes to the database schema. Please note that for Oracle database, the created SQL file contains `SET DEFINE OFF` command understood by Oracle SQL clients. Should the script be consumed by any other client, please replace the lines with equivalent command of the tool of your choice that disables variable expansion or remove it completely if such functionality is not applicable. ==== Changes in Client's Valid Redirect URIs The following scenarios are affected: * When a Valid Redirect URI with query component is saved in a Client (e.g. `\\http://localhost/auth?foo=bar`), `redirect_uri` in authorization request must exactly match this URI (or other registered URI in this Client). * When a Valid Redirect URI without a query component is saved in a Client, `redirect_uri` must exactly match as well. * Wildcards in registered Valid Redirect URIs are no longer supported when query component is present in this URI, so the `redirect_uri` needs to exactly match this saved URI as well. * Fragments in registered Valid Redirect URIs (like `\\http://localhost/auth#fragment`) are no longer allowed. ==== Authenticate by default removed from Identity Providers Identity providers no longer has an option to set it as a default authentication provider. Instead go to Authentication, select the `Browser` flow and configure the `Identity Provider Redirector`. It has an option to set the default identity provider. === Migrating to 2.0.0 ==== Upgrading from 1.0.0.Final no longer supported Upgrading from 1.0.0.Final is no longer supported. To upgrade to this version upgrade to 1.9.8.Final prior to upgrading to 2.0.0. === Migrating to 1.9.5 ==== Default password hashing interval increased to 20K The default password hashing interval for new realms has been increased to 20K (from 1 previously). This change will have an impact on performance when users authenticate. For example with the old default (1) it takes less than 1 ms to hash a password, but with the new default (20K) the same operation can take 50-100 ms. === Migrating to 1.9.3 ==== Add User script renamed The script to add admin users to Keycloak has been renamed to `add-user-keycloak`. === Migrating to 1.9.2 ==== Adapter option auth-server-url-for-backend-requests removed We've removed the option auth-server-url-for-backend-requests as there were issues in some scenarios when it was used. In more details, it was possible to access the Keycloak server from 2 different contexts (internal and external), which was causing issues in token validations etc. If you still want to use the optimization of network, which this option provided (avoid the application to send backchannel requests through loadbalancer but send them to local Keycloak server directly) you may need to handle it at hosts configuration (DNS) level. === Migrating to 1.9.0 ==== Themes and providers directory moved We've moved the themes and providers directories from `standalone/configuration/themes` and `standalone/configuration/providers` to `themes` and `providers` respectively. If you have added custom themes and providers you need to move them to the new location. You also need to update `keycloak-server.json` as it's changed due to this. ==== Adapter Subsystems only bring in dependencies if Keycloak is on Previously, if you had installed our SAML or OIDC Keycloak subsystem adapters into WildFly or JBoss EAP, we would automatically include Keycloak client jars into EVERY application irregardless if you were using Keycloak or not. These libraries are now only added to your deployment if you have Keycloak authentication turned on for that adapter (via the subsystem, or auth-method in web.xml) ==== Client Registration service endpoints moved The Client Registration service endpoints have been moved from `{realm-name}/clients` to `{realm-name}/clients-registrations`. ==== Session state parameter in authentication response renamed In the OpenID Connect authentication response we used to return the session state as `session-state` this is not correct according to the specification and has been renamed to `session_state`. ==== Deprecated OpenID Connect endpoints In 1.2 we deprecated a number of endpoints that where not consistent with the OpenID Connect specifications, these have now been removed. This also applies to the validate token endpoints that was replaced with the new introspect endpoint in 1.8. ==== Updates to theme templates Feedback in template.ftl has been moved and format has changed slightly. ==== Module and Source Code Re-org Most of our modules and source code have been consolidated into two maven modules: keycloak-server-spi and keycloak-services. SPI interfaces are in server-spi, implementations are in keycloak-services. All JPA dependent modules have been consolidated under keycloak-model-jpa. Same goes with mongo and Infinispan under modules keycloak-model-mongo and keycloak-model-infinispan. ==== For adapters, session id changed after login To plug a security attack vector, for platforms that support it (Tomcat 8, Undertow/WildFly, Jetty 9), the Keycloak OIDC and SAML adapters will change the session id after login. You can turn off this behavior check adapter config switches. ==== SAML SP Client Adapter Changes Keycloak SAML SP Client Adapter now requires a specific endpoint, `/saml` to be registered with your IDP. === Migrating to 1.8.0 ==== Admin account In previous releases we shipped with a default admin user with a default password, this has now been removed. If you are doing a new installation of 1.8 you will have to create an admin user as a first step. ==== OAuth2 Token Introspection In order to add more compliance with OAuth2 specification, we added a new endpoint for token introspection. The new endpoint can reached at `/realms/{realm-name}/protocols/openid-connect/token/introspect` and it is solely based on `RFC-7662`. The `/realms/{realm-name}/protocols/openid-connect/validate` endpoint is now deprecated and we strongly recommend you to move to the new introspection endpoint as soon as possible. The reason for this change is that RFC-7662 provides a more standard and secure introspection endpoint. The new token introspection URL can now be obtained from OpenID Connect Provider's configuration at `/realms/{realm-name}/.well-known/openid-configuration`. There you will find a claim with name `token_introspection_endpoint` within the response. Only `confidential clients` are allowed to invoke the new endpoint, where these clients will be usually acting as a resource server and looking for token metadata in order to perform local authorization checks. === Migrating to 1.7.0.CR1 ==== Direct access grants disabled by default for clients In order to add more compliance with OpenID Connect specification, we added flags into admin console to Client Settings page, where you can enable/disable various kinds of OpenID Connect/OAuth2 flows (Standard flow, Implicit flow, Direct Access Grants, Service Accounts). As part of this, we have `Direct Access Grants` (corresponds to OAuth2 `Resource Owner Password Credentials Grant`) disabled by default for new clients. Clients migrated from previous version have `Direct Access Grants` enabled just if they had flag `Direct Grants Only` on. The `Direct Grants Only` flag was removed as if you enable Direct Access Grants and disable both Standard+Implicit flow, you will achieve same effect. We also added built-in client `admin-cli` to each realm. This client has `Direct Access Grants` enabled. So if you're using Admin REST API or Keycloak admin-client, you should update your configuration to use `admin-cli` instead of `security-admin-console` as the latter one doesn't have direct access grants enabled anymore by default. ==== Option 'Update Profile On First Login' moved from Identity provider to Review Profile authenticator In this version, we added `First Broker Login`, which allows you to specify what exactly should be done when new user is logged through Identity provider (or Social provider), but there is no existing Keycloak user yet linked to the social account. As part of this work, we added option `First Login Flow` to identity providers where you can specify the flow and then you can configure this flow under `Authentication` tab in admin console. We also removed the option `Update Profile On First Login` from the Identity provider settings and moved it to the configuration of `Review Profile` authenticator. So once you specify which flow should be used for your Identity provider (by default it's `First Broker Login` flow), you go to `Authentication` tab, select the flow and then you configure the option under `Review Profile` authenticator. ==== Element 'form-error-page' in web.xml not supported anymore form-error-page in web.xml will no longer work for client adapter authentication errors. You must define an error-page for the various HTTP error codes. See documentation for more details if you want to catch and handle adapter error conditions. ==== IdentityProviderMapper changes There is no change in the interface itself or method signatures. However there is some change in behavior. We added `First Broker Login` flow in this release and the method `IdentityProviderMapper.importNewUser` is now called after `First Broker Login` flow is finished. So if you want to have any attribute available in `Review Profile` page, you would need to use the method `preprocessFederatedIdentity` instead of `importNewUser` . You can set any attribute by invoke `BrokeredIdentityContext.setUserAttribute` and that will be available on `Review profile` page. === Migrating to 1.6.0.Final ==== Option that refresh tokens are not reusable anymore Old versions of Keycloak allowed reusing refresh tokens multiple times. Keycloak still permits this, but also have an option `Revoke refresh token` to disallow it. Option is under token settings in admin console. When a refresh token is used to obtain a new access token a new refresh token is also included. When option is enabled, then this new refresh token should be used next time the access token is refreshed. It won't be possible to reuse old refresh token multiple times. ==== Some packages renamed We did a bit of restructure and renamed some packages. It is mainly about renaming internal packages of util classes. The most important classes used in your application ( for example AccessToken or KeycloakSecurityContext ) as well as the SPI are still unchanged. However there is slight chance that you will be affected and will need to update imports of your classes. For example if you are using multitenancy and KeycloakConfigResolver, you will be affected as for example class HttpFacade was moved to different package - it is `org.keycloak.adapters.spi.HttpFacade` now. ==== Persisting user sessions We added support for offline tokens in this release, which means that we are persisting ""offline"" user sessions into database now. If you are not using offline tokens, nothing will be persisted for you, so you don't need to care about worse performance for more DB writes. However in all cases, you will need to update `standalone/configuration/keycloak-server.json` and add `userSessionPersister` like this: [source,json] ---- ""userSessionPersister"": { ""provider"": ""jpa"" }, ---- If you want sessions to be persisted in Mongo instead of classic RDBMS, use provider `mongo` instead. === Migrating to 1.5.0.Final ==== Realm and User cache providers Infinispan is now the default and only realm and user cache providers. In non-clustered mode a local Infinispan cache is used. We've also removed our custom in-memory cache and the no cache providers. If you have realmCache or userCache set in keycloak-server.json to mem or none please remove these. As Infinispan is the only provider there's no longer any need for the realmCache and userCache objects so these can be removed. ==== Uses Session providers Infinispan is now the default and only user session provider. In non-clustered mode a local Infinispan cache is used. We've also removed the JPA and Mongo user session providers. If you have userSession set in keycloak-server.json to mem, jpa or mongo please remove it. As Infinispan is the only provider there's no longer any need for the userSession object so it can be removed. For anyone that wants to achieve increased durability of user sessions this can be achieved by configuring the user session cache with more than one owner or use a replicated cache. It's also possible to configure Infinispan to persist caches, although that would have impacts on performance. ==== Contact details removed from registration and account management In the default theme we have now removed the contact details from the registration page and account management. The admin console now lists all the users attributes, not just contact specific attributes. The admin console also has the ability to add/remove attributes to a user. If you want to add contact details, please refer to the address theme included in the examples. === Migrating to 1.3.0.Final ==== Direct Grant API always enabled In the past Direct Grant API (or Resource Owner Password Credentials) was disabled by default and there was an option on a realm to enable it. The Direct Grant API is now always enabled and the option to enable/disable for a realm is removed. ==== Database changed There are again few database changes. Remember to backup your database prior to upgrading. ==== UserFederationProvider changed There are few minor changes in UserFederationProvider interface. You may need to sync your implementation when upgrade to newer version and upgrade few methods, which has changed signature. Changes are really minor, but were needed to improve performance of federation. ==== WildFly 9.0.0.Final Following on from the distribution changes that was done in the last release the standalone download of Keycloak is now based on WildFly 9.0.0.Final. This also affects the overlay which can only be deployed to WildFly 9.0.0.Final or JBoss EAP 6.4.0.GA. WildFly 8.2.0.Final is no longer supported for the server. ==== WildFly, JBoss EAP and JBoss AS7 adapters There are now 3 separate adapter downloads for WildFly, JBoss EAP and JBoss AS7: * eap6 * wf9 * wf8 * as7 Make sure you grab the correct one. You also need to update standalone.xml as the extension module and subsystem definition has changed. See link:{adapterguide_link}[{adapterguide_name}] for details. === Migrating from 1.2.0.Beta1 to 1.2.0.RC1 ==== Distribution changes Keycloak is now available in 3 downloads: standalone, overlay and demo bundle. The standalone is intended for production and non-JEE developers. Overlay is aimed at adding Keycloak to an existing WildFly 8.2 or EAP 6.4 installation and is mainly for development. Finally we have a demo (or dev) bundle that is aimed at developers getting started with Keycloak. This bundle contains a WildFly server, with Keycloak server and adapter included. It also contains all documentation and examples. ==== Database changed This release contains again a number of changes to the database. The biggest one is Application and OAuth client merge. Remember to backup your database prior to upgrading. ==== Application and OAuth client merge Application and OAuth clients are now merged into `Clients`. The UI of admin console is updated and database as well. Your data from database should be automatically updated. The previously set Applications will be converted into Clients with `Consent required` switch off and OAuth Clients will be converted into Clients with this switch on. === Migrating from 1.1.0.Final to 1.2.0.Beta1 ==== Database changed This release contains a number of changes to the database. Remember to backup your database prior to upgrading. ==== `iss` in access and id tokens The value of `iss` claim in access and id tokens have changed from `realm name` to `realm url`. This is required by OpenID Connect specification. If you're using our adapters there's no change required, other than if you've been using bearer-only without specifying `auth-server-url` you have to add it now. If you're using another library (or RSATokenVerifier) you need to make the corresponding changes when verifying `iss`. ==== OpenID Connect endpoints To comply with OpenID Connect specification the authentication and token endpoints have been changed to having a single authentication endpoint and a single token endpoint. As per-spec `response_type` and `grant_type` parameters are used to select the required flow. The old endpoints (`/realms/{realm-name}/protocols/openid-connect/login`, `/realms/{realm-name}/protocols/openid-connect/grants/access`, `/realms/{realm-name}/protocols/openid-connect/refresh`, `/realms/{realm-name}/protocols/openid-connect/access/codes`) are now deprecated and will be removed in a future version. ==== Theme changes The layout of themes has changed. The directory hierarchy used to be `type/name` this is now changed to `name/type`. For example a login theme named `sunrise` used to be deployed to `standalone/configuration/themes/login/sunrise`, which is now moved to `standalone/configuration/themes/sunrise/login`. This change was done to make it easier to have groups of the different types for the same theme into one folder. If you deployed themes as a JAR in the past you had to create a custom theme loader which required Java code. This has been simplified to only requiring a plain text file (`META-INF/keycloak-themes.json`) to describe the themes included in a JAR. ==== Claims changes Previously there was `Claims` tab in admin console for application and OAuth clients. This was used to configure which attributes should go into access token for particular application/client. This was removed and replaced with protocol mappers which are more flexible. You don't need to care about migration of database from previous version. We did migration scripts for both RDBMS and Mongo, which should ensure that claims configured for particular application/client will be converted into corresponding protocol mappers (Still it's safer to backup DB before migrating to newer version though). Same applies for exported JSON representation from previous version. ==== Social migration to identity brokering We refactored social providers SPI and replaced it with Identity Brokering SPI, which is more flexible. The `Social` tab in admin console is renamed to `Identity Provider` tab. Again you don't need to care about migration of database from previous version similarly like for Claims/protocol mappers. Both configuration of social providers and ""social links"" to your users will be converted to corresponding Identity providers. Only required action from you would be to change allowed `Redirect URI` in the admin console of particular 3rd party social providers. You can first go to the Keycloak admin console and copy Redirect URI from the page where you configure the identity provider. Then you can simply paste this as allowed Redirect URI to the admin console of 3rd party provider (IE. Facebook admin console). === Migrating from 1.1.0.Beta1 to 1.1.0.Beta2 * Adapters are now a separate download. They are not included in appliance and war distribution. We have too many now and the distro is getting bloated. * `org.keycloak.adapters.tomcat7.KeycloakAuthenticatorValve` +`org.keycloak.adapters.tomcat.KeycloakAuthenticatorValve` * JavaScript adapter now has idToken and idTokenParsed properties. If you use idToken to retrieve first name, email, etc. you need to change this to idTokenParsed. * The as7-eap-subsystem and keycloak-wildfly-subsystem have been merged into one keycloak-subsystem. If you have an existing standalone.xml or domain.xml, you will need edit near the top of the file and change the extension module name to org.keycloak.keycloak-subsystem. For AS7 only, the extension module name is org.keycloak.keycloak-as7-subsystem. * Server installation is no longer supported on AS7. You can still use AS7 as an application client. === Migrating from 1.0.x.Final to 1.1.0.Beta1 * RealmModel JPA and Mongo storage schema has changed * UserSessionModel JPA and Mongo storage schema has changed as these interfaces have been refactored * Upgrade your adapters, old adapters are not compatible with Keycloak 1.1. We interpreted JSON Web Token and OIDC ID Token specification incorrectly. 'aud' claim must be the client id, we were storing the realm name in there and validating it. === Migrating from 1.0 RC-1 to RC-2 * A lot of info level logging has been changed to debug. Also, a realm no longer has the jboss-logging audit listener by default. If you want log output when users login, logout, change passwords, etc. enable the jboss-logging audit listener through the admin console. === Migrating from 1.0 Beta 4 to RC-1 * logout REST API has been refactored. The GET request on the logout URI does not take a session_state parameter anymore. You must be logged in in order to log out the session. You can also POST to the logout REST URI. This action requires a valid refresh token to perform the logout. The signature is the same as refresh token minus the grant type form parameter. See documentation for details. === Migrating from 1.0 Beta 1 to Beta 4 * LDAP/AD configuration is changed. It is no longer under the ""Settings"" page. It is now under Users->Federation. Add Provider will show you an ""ldap"" option. * Authentication SPI has been removed and rewritten. The new SPI is UserFederationProvider and is more flexible. * `ssl-not-required` +`ssl-required` +`all` +`external` +`none` * DB Schema has changed again. * Created applications now have a full scope by default. This means that you don't have to configure the scope of an application if you don't want to. * Format of JSON file for importing realm data was changed. Now role mappings is available under the JSON record of particular user. === Migrating from 1.0 Alpha 4 to Beta 1 * DB Schema has changed. We have added export of the database to Beta 1, but not the ability to import the database from older versions. This will be supported in future releases. * For all clients except bearer-only applications, you must specify at least one redirect URI. Keycloak will not allow you to log in unless you have specified a valid redirect URI for that application. * Direct Grant API +`ON` * standalone/configuration/keycloak-server.json * JavaScript adapter * Session Timeout === Migrating from 1.0 Alpha 2 to Alpha 3 * SkeletonKeyToken, SkeletonKeyScope, SkeletonKeyPrincipal, and SkeletonKeySession have been renamed to: AccessToken, AccessScope, KeycloakPrincipal, and KeycloakAuthenticatedSession respectively. * ServletOAuthClient.getBearerToken() method signature has changed. It now returns an AccessTokenResponse so that you can obtain a refresh token too. * Adapters now check the access token expiration with every request. If the token is expired, they will attempt to invoke a refresh on the auth server using a saved refresh token. * Subject in AccessToken has been changed to the User ID. === Migrating from 1.0 Alpha 1 to Alpha 2 * DB Schema has changed. We don't have any data migration utilities yet as of Alpha 2. * JBoss and WildFly adapters are now installed via a {appserver_name} subsystem. Please review the adapter installation documentation. Edits to standalone.xml are now required. * There is a new credential type ""secret"". Unlike other credential types, it is stored in plain text in the database and can be viewed in the admin console. * There is no longer required Application or OAuth Client credentials. These client types are now hard coded to use the ""secret"" credential type. * Because of the ""secret"" credential change to Application and OAuth Client, you'll have to update your keycloak.json configuration files and regenerate a secret within the Application or OAuth Client credentials tab in the administration console. ",12499,False,1987.5237852010507,median "//===-- llvm/CodeGen/DwarfUnit.cpp - Dwarf Type and Compile Units ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file contains support for constructing a dwarf compile unit. // //===----------------------------------------------------------------------===// #include ""DwarfUnit.h"" #include ""DwarfAccelTable.h"" #include ""DwarfCompileUnit.h"" #include ""DwarfDebug.h"" #include ""DwarfExpression.h"" #include ""llvm/ADT/APFloat.h"" #include ""llvm/CodeGen/MachineFunction.h"" #include ""llvm/IR/Constants.h"" #include ""llvm/IR/DIBuilder.h"" #include ""llvm/IR/DataLayout.h"" #include ""llvm/IR/GlobalVariable.h"" #include ""llvm/IR/Instructions.h"" #include ""llvm/IR/Mangler.h"" #include ""llvm/MC/MCAsmInfo.h"" #include ""llvm/MC/MCContext.h"" #include ""llvm/MC/MCSection.h"" #include ""llvm/MC/MCStreamer.h"" #include ""llvm/Support/CommandLine.h"" #include ""llvm/Target/TargetFrameLowering.h"" #include ""llvm/Target/TargetLoweringObjectFile.h"" #include ""llvm/Target/TargetMachine.h"" #include ""llvm/Target/TargetRegisterInfo.h"" #include ""llvm/Target/TargetSubtargetInfo.h"" using namespace llvm; #define DEBUG_TYPE ""dwarfdebug"" static cl::opt GenerateDwarfTypeUnits(""generate-type-units"", cl::Hidden, cl::desc(""Generate DWARF4 type units.""), cl::init(false)); DIEDwarfExpression::DIEDwarfExpression(const AsmPrinter &AP, DwarfUnit &DU, DIELoc &DIE) : DwarfExpression(*AP.MF->getSubtarget().getRegisterInfo(), AP.getDwarfDebug()->getDwarfVersion()), AP(AP), DU(DU), DIE(DIE) {} void DIEDwarfExpression::EmitOp(uint8_t Op, const char* Comment) { DU.addUInt(DIE, dwarf::DW_FORM_data1, Op); } void DIEDwarfExpression::EmitSigned(int64_t Value) { DU.addSInt(DIE, dwarf::DW_FORM_sdata, Value); } void DIEDwarfExpression::EmitUnsigned(uint64_t Value) { DU.addUInt(DIE, dwarf::DW_FORM_udata, Value); } bool DIEDwarfExpression::isFrameRegister(unsigned MachineReg) { return MachineReg == TRI.getFrameRegister(*AP.MF); } /// Unit - Unit constructor. DwarfUnit::DwarfUnit(unsigned UID, dwarf::Tag UnitTag, DICompileUnit Node, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU) : UniqueID(UID), CUNode(Node), UnitDie(UnitTag), DebugInfoOffset(0), Asm(A), DD(DW), DU(DWU), IndexTyDie(nullptr), Section(nullptr) { assert(UnitTag == dwarf::DW_TAG_compile_unit || UnitTag == dwarf::DW_TAG_type_unit); DIEIntegerOne = new (DIEValueAllocator) DIEInteger(1); } DwarfTypeUnit::DwarfTypeUnit(unsigned UID, DwarfCompileUnit &CU, AsmPrinter *A, DwarfDebug *DW, DwarfFile *DWU, MCDwarfDwoLineTable *SplitLineTable) : DwarfUnit(UID, dwarf::DW_TAG_type_unit, CU.getCUNode(), A, DW, DWU), CU(CU), SplitLineTable(SplitLineTable) { if (SplitLineTable) addSectionOffset(UnitDie, dwarf::DW_AT_stmt_list, 0); } /// ~Unit - Destructor for compile unit. DwarfUnit::~DwarfUnit() { for (unsigned j = 0, M = DIEBlocks.size(); j < M; ++j) DIEBlocks[j]->~DIEBlock(); for (unsigned j = 0, M = DIELocs.size(); j < M; ++j) DIELocs[j]->~DIELoc(); } /// createDIEEntry - Creates a new DIEEntry to be a proxy for a debug /// information entry. DIEEntry *DwarfUnit::createDIEEntry(DIE &Entry) { DIEEntry *Value = new (DIEValueAllocator) DIEEntry(Entry); return Value; } /// getDefaultLowerBound - Return the default lower bound for an array. If the /// DWARF version doesn't handle the language, return -1. int64_t DwarfUnit::getDefaultLowerBound() const { switch (getLanguage()) { default: break; case dwarf::DW_LANG_C89: case dwarf::DW_LANG_C99: case dwarf::DW_LANG_C: case dwarf::DW_LANG_C_plus_plus: case dwarf::DW_LANG_ObjC: case dwarf::DW_LANG_ObjC_plus_plus: return 0; case dwarf::DW_LANG_Fortran77: case dwarf::DW_LANG_Fortran90: case dwarf::DW_LANG_Fortran95: return 1; // The languages below have valid values only if the DWARF version >= 4. case dwarf::DW_LANG_Java: case dwarf::DW_LANG_Python: case dwarf::DW_LANG_UPC: case dwarf::DW_LANG_D: if (dwarf::DWARF_VERSION >= 4) return 0; break; case dwarf::DW_LANG_Ada83: case dwarf::DW_LANG_Ada95: case dwarf::DW_LANG_Cobol74: case dwarf::DW_LANG_Cobol85: case dwarf::DW_LANG_Modula2: case dwarf::DW_LANG_Pascal83: case dwarf::DW_LANG_PLI: if (dwarf::DWARF_VERSION >= 4) return 1; break; // The languages below have valid values only if the DWARF version >= 5. case dwarf::DW_LANG_OpenCL: case dwarf::DW_LANG_Go: case dwarf::DW_LANG_Haskell: case dwarf::DW_LANG_C_plus_plus_03: case dwarf::DW_LANG_C_plus_plus_11: case dwarf::DW_LANG_OCaml: case dwarf::DW_LANG_Rust: case dwarf::DW_LANG_C11: case dwarf::DW_LANG_Swift: case dwarf::DW_LANG_Dylan: case dwarf::DW_LANG_C_plus_plus_14: if (dwarf::DWARF_VERSION >= 5) return 0; break; case dwarf::DW_LANG_Modula3: case dwarf::DW_LANG_Julia: case dwarf::DW_LANG_Fortran03: case dwarf::DW_LANG_Fortran08: if (dwarf::DWARF_VERSION >= 5) return 1; break; } return -1; } /// Check whether the DIE for this MDNode can be shared across CUs. static bool isShareableAcrossCUs(DIDescriptor D) { // When the MDNode can be part of the type system, the DIE can be shared // across CUs. // Combining type units and cross-CU DIE sharing is lower value (since // cross-CU DIE sharing is used in LTO and removes type redundancy at that // level already) but may be implementable for some value in projects // building multiple independent libraries with LTO and then linking those // together. return (isa(D) || (isa(D) && !cast(D)->isDefinition())) && !GenerateDwarfTypeUnits; } /// getDIE - Returns the debug information entry map slot for the /// specified debug variable. We delegate the request to DwarfDebug /// when the DIE for this MDNode can be shared across CUs. The mappings /// will be kept in DwarfDebug for shareable DIEs. DIE *DwarfUnit::getDIE(DIDescriptor D) const { if (isShareableAcrossCUs(D)) return DU->getDIE(D); return MDNodeToDieMap.lookup(D); } /// insertDIE - Insert DIE into the map. We delegate the request to DwarfDebug /// when the DIE for this MDNode can be shared across CUs. The mappings /// will be kept in DwarfDebug for shareable DIEs. void DwarfUnit::insertDIE(DIDescriptor Desc, DIE *D) { if (isShareableAcrossCUs(Desc)) { DU->insertDIE(Desc, D); return; } MDNodeToDieMap.insert(std::make_pair(Desc, D)); } /// addFlag - Add a flag that is true. void DwarfUnit::addFlag(DIE &Die, dwarf::Attribute Attribute) { if (DD->getDwarfVersion() >= 4) Die.addValue(Attribute, dwarf::DW_FORM_flag_present, DIEIntegerOne); else Die.addValue(Attribute, dwarf::DW_FORM_flag, DIEIntegerOne); } /// addUInt - Add an unsigned integer attribute data and value. /// void DwarfUnit::addUInt(DIE &Die, dwarf::Attribute Attribute, Optional Form, uint64_t Integer) { if (!Form) Form = DIEInteger::BestForm(false, Integer); DIEValue *Value = Integer == 1 ? DIEIntegerOne : new (DIEValueAllocator) DIEInteger(Integer); Die.addValue(Attribute, *Form, Value); } void DwarfUnit::addUInt(DIE &Block, dwarf::Form Form, uint64_t Integer) { addUInt(Block, (dwarf::Attribute)0, Form, Integer); } /// addSInt - Add an signed integer attribute data and value. /// void DwarfUnit::addSInt(DIE &Die, dwarf::Attribute Attribute, Optional Form, int64_t Integer) { if (!Form) Form = DIEInteger::BestForm(true, Integer); DIEValue *Value = new (DIEValueAllocator) DIEInteger(Integer); Die.addValue(Attribute, *Form, Value); } void DwarfUnit::addSInt(DIELoc &Die, Optional Form, int64_t Integer) { addSInt(Die, (dwarf::Attribute)0, Form, Integer); } /// addString - Add a string attribute data and value. We always emit a /// reference to the string pool instead of immediate strings so that DIEs have /// more predictable sizes. In the case of split dwarf we emit an index /// into another table which gets us the static offset into the string /// table. void DwarfUnit::addString(DIE &Die, dwarf::Attribute Attribute, StringRef String) { if (!isDwoUnit()) return addLocalString(Die, Attribute, String); addIndexedString(Die, Attribute, String); } void DwarfUnit::addIndexedString(DIE &Die, dwarf::Attribute Attribute, StringRef String) { unsigned idx = DU->getStringPool().getIndex(*Asm, String); DIEValue *Value = new (DIEValueAllocator) DIEInteger(idx); DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String); Die.addValue(Attribute, dwarf::DW_FORM_GNU_str_index, Str); } /// addLocalString - Add a string attribute data and value. This is guaranteed /// to be in the local string pool instead of indirected. void DwarfUnit::addLocalString(DIE &Die, dwarf::Attribute Attribute, StringRef String) { const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); MCSymbol *Symb = DU->getStringPool().getSymbol(*Asm, String); DIEValue *Value; if (Asm->MAI->doesDwarfUseRelocationsAcrossSections()) Value = new (DIEValueAllocator) DIELabel(Symb); else Value = new (DIEValueAllocator) DIEDelta(Symb, TLOF.getDwarfStrSection()->getBeginSymbol()); DIEValue *Str = new (DIEValueAllocator) DIEString(Value, String); Die.addValue(Attribute, dwarf::DW_FORM_strp, Str); } /// addLabel - Add a Dwarf label attribute data and value. /// void DwarfUnit::addLabel(DIE &Die, dwarf::Attribute Attribute, dwarf::Form Form, const MCSymbol *Label) { DIEValue *Value = new (DIEValueAllocator) DIELabel(Label); Die.addValue(Attribute, Form, Value); } void DwarfUnit::addLabel(DIELoc &Die, dwarf::Form Form, const MCSymbol *Label) { addLabel(Die, (dwarf::Attribute)0, Form, Label); } /// addSectionOffset - Add an offset into a section attribute data and value. /// void DwarfUnit::addSectionOffset(DIE &Die, dwarf::Attribute Attribute, uint64_t Integer) { if (DD->getDwarfVersion() >= 4) addUInt(Die, Attribute, dwarf::DW_FORM_sec_offset, Integer); else addUInt(Die, Attribute, dwarf::DW_FORM_data4, Integer); } unsigned DwarfTypeUnit::getOrCreateSourceID(StringRef FileName, StringRef DirName) { return SplitLineTable ? SplitLineTable->getFile(DirName, FileName) : getCU().getOrCreateSourceID(FileName, DirName); } /// addOpAddress - Add a dwarf op address data and value using the /// form given and an op of either DW_FORM_addr or DW_FORM_GNU_addr_index. /// void DwarfUnit::addOpAddress(DIELoc &Die, const MCSymbol *Sym) { if (!DD->useSplitDwarf()) { addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_addr); addLabel(Die, dwarf::DW_FORM_udata, Sym); } else { addUInt(Die, dwarf::DW_FORM_data1, dwarf::DW_OP_GNU_addr_index); addUInt(Die, dwarf::DW_FORM_GNU_addr_index, DD->getAddressPool().getIndex(Sym)); } } void DwarfUnit::addLabelDelta(DIE &Die, dwarf::Attribute Attribute, const MCSymbol *Hi, const MCSymbol *Lo) { DIEValue *Value = new (DIEValueAllocator) DIEDelta(Hi, Lo); Die.addValue(Attribute, dwarf::DW_FORM_data4, Value); } /// addDIEEntry - Add a DIE attribute data and value. /// void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIE &Entry) { addDIEEntry(Die, Attribute, createDIEEntry(Entry)); } void DwarfUnit::addDIETypeSignature(DIE &Die, const DwarfTypeUnit &Type) { // Flag the type unit reference as a declaration so that if it contains // members (implicit special members, static data member definitions, member // declarations for definitions in this CU, etc) consumers don't get confused // and think this is a full definition. addFlag(Die, dwarf::DW_AT_declaration); Die.addValue(dwarf::DW_AT_signature, dwarf::DW_FORM_ref_sig8, new (DIEValueAllocator) DIETypeSignature(Type)); } void DwarfUnit::addDIEEntry(DIE &Die, dwarf::Attribute Attribute, DIEEntry *Entry) { const DIE *DieCU = Die.getUnitOrNull(); const DIE *EntryCU = Entry->getEntry().getUnitOrNull(); if (!DieCU) // We assume that Die belongs to this CU, if it is not linked to any CU yet. DieCU = &getUnitDie(); if (!EntryCU) EntryCU = &getUnitDie(); Die.addValue(Attribute, EntryCU == DieCU ? dwarf::DW_FORM_ref4 : dwarf::DW_FORM_ref_addr, Entry); } /// Create a DIE with the given Tag, add the DIE to its parent, and /// call insertDIE if MD is not null. DIE &DwarfUnit::createAndAddDIE(unsigned Tag, DIE &Parent, DIDescriptor N) { assert(Tag != dwarf::DW_TAG_auto_variable && Tag != dwarf::DW_TAG_arg_variable); Parent.addChild(make_unique((dwarf::Tag)Tag)); DIE &Die = *Parent.getChildren().back(); if (N) insertDIE(N, &Die); return Die; } /// addBlock - Add block data. /// void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIELoc *Loc) { Loc->ComputeSize(Asm); DIELocs.push_back(Loc); // Memoize so we can call the destructor later on. Die.addValue(Attribute, Loc->BestForm(DD->getDwarfVersion()), Loc); } void DwarfUnit::addBlock(DIE &Die, dwarf::Attribute Attribute, DIEBlock *Block) { Block->ComputeSize(Asm); DIEBlocks.push_back(Block); // Memoize so we can call the destructor later on. Die.addValue(Attribute, Block->BestForm(), Block); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, unsigned Line, StringRef File, StringRef Directory) { if (Line == 0) return; unsigned FileID = getOrCreateSourceID(File, Directory); assert(FileID && ""Invalid file id""); addUInt(Die, dwarf::DW_AT_decl_file, None, FileID); addUInt(Die, dwarf::DW_AT_decl_line, None, Line); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DIVariable V) { assert(V); addSourceLine(Die, V->getLine(), V->getScope()->getFilename(), V->getScope()->getDirectory()); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DIGlobalVariable G) { assert(G); addSourceLine(Die, G->getLine(), G->getFilename(), G->getDirectory()); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DISubprogram SP) { assert(SP); addSourceLine(Die, SP->getLine(), SP->getFilename(), SP->getDirectory()); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DIType Ty) { assert(Ty); addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DIObjCProperty Ty) { assert(Ty); addSourceLine(Die, Ty->getLine(), Ty->getFilename(), Ty->getDirectory()); } /// addSourceLine - Add location information to specified debug information /// entry. void DwarfUnit::addSourceLine(DIE &Die, DINameSpace NS) { addSourceLine(Die, NS->getLine(), NS->getFilename(), NS->getDirectory()); } /// addRegisterOp - Add register operand. bool DwarfUnit::addRegisterOpPiece(DIELoc &TheDie, unsigned Reg, unsigned SizeInBits, unsigned OffsetInBits) { DIEDwarfExpression Expr(*Asm, *this, TheDie); Expr.AddMachineRegPiece(Reg, SizeInBits, OffsetInBits); return true; } /// addRegisterOffset - Add register offset. bool DwarfUnit::addRegisterOffset(DIELoc &TheDie, unsigned Reg, int64_t Offset) { DIEDwarfExpression Expr(*Asm, *this, TheDie); return Expr.AddMachineRegIndirect(Reg, Offset); } /* Byref variables, in Blocks, are declared by the programmer as ""SomeType VarName;"", but the compiler creates a __Block_byref_x_VarName struct, and gives the variable VarName either the struct, or a pointer to the struct, as its type. This is necessary for various behind-the-scenes things the compiler needs to do with by-reference variables in Blocks. However, as far as the original *programmer* is concerned, the variable should still have type 'SomeType', as originally declared. The function getBlockByrefType dives into the __Block_byref_x_VarName struct to find the original type of the variable, which is then assigned to the variable's Debug Information Entry as its real type. So far, so good. However now the debugger will expect the variable VarName to have the type SomeType. So we need the location attribute for the variable to be an expression that explains to the debugger how to navigate through the pointers and struct to find the actual variable of type SomeType. The following function does just that. We start by getting the ""normal"" location for the variable. This will be the location of either the struct __Block_byref_x_VarName or the pointer to the struct __Block_byref_x_VarName. The struct will look something like: struct __Block_byref_x_VarName { ... struct __Block_byref_x_VarName *forwarding; ... SomeType VarName; ... }; If we are given the struct directly (as our starting point) we need to tell the debugger to: 1). Add the offset of the forwarding field. 2). Follow that pointer to get the real __Block_byref_x_VarName struct to use (the real one may have been copied onto the heap). 3). Add the offset for the field VarName, to find the actual variable. If we started with a pointer to the struct, then we need to dereference that pointer first, before the other steps. Translating this into DWARF ops, we will need to append the following to the current location description for the variable: DW_OP_deref -- optional, if we start with a pointer DW_OP_plus_uconst DW_OP_deref DW_OP_plus_uconst That is what this function does. */ /// addBlockByrefAddress - Start with the address based on the location /// provided, and generate the DWARF information necessary to find the /// actual Block variable (navigating the Block struct) based on the /// starting location. Add the DWARF information to the die. For /// more information, read large comment just above here. /// void DwarfUnit::addBlockByrefAddress(const DbgVariable &DV, DIE &Die, dwarf::Attribute Attribute, const MachineLocation &Location) { DIType Ty = DV.getType(); DIType TmpTy = Ty; uint16_t Tag = Ty->getTag(); bool isPointer = false; StringRef varName = DV.getName(); if (Tag == dwarf::DW_TAG_pointer_type) { DIDerivedType DTy = cast(Ty); TmpTy = resolve(DTy->getBaseType()); isPointer = true; } // Find the __forwarding field and the variable field in the __Block_byref // struct. DIArray Fields = cast(TmpTy)->getElements(); DIDerivedType varField; DIDerivedType forwardingField; for (unsigned i = 0, N = Fields.size(); i < N; ++i) { DIDerivedType DT = cast(Fields[i]); StringRef fieldName = DT->getName(); if (fieldName == ""__forwarding"") forwardingField = DT; else if (fieldName == varName) varField = DT; } // Get the offsets for the forwarding field and the variable field. unsigned forwardingFieldOffset = forwardingField->getOffsetInBits() >> 3; unsigned varFieldOffset = varField->getOffsetInBits() >> 2; // Decode the original location, and use that as the start of the byref // variable's location. DIELoc *Loc = new (DIEValueAllocator) DIELoc(); bool validReg; if (Location.isReg()) validReg = addRegisterOpPiece(*Loc, Location.getReg()); else validReg = addRegisterOffset(*Loc, Location.getReg(), Location.getOffset()); if (!validReg) return; // If we started with a pointer to the __Block_byref... struct, then // the first thing we need to do is dereference the pointer (DW_OP_deref). if (isPointer) addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); // Next add the offset for the '__forwarding' field: // DW_OP_plus_uconst ForwardingFieldOffset. Note there's no point in // adding the offset if it's 0. if (forwardingFieldOffset > 0) { addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); addUInt(*Loc, dwarf::DW_FORM_udata, forwardingFieldOffset); } // Now dereference the __forwarding field to get to the real __Block_byref // struct: DW_OP_deref. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); // Now that we've got the real __Block_byref... struct, add the offset // for the variable's field to get to the location of the actual variable: // DW_OP_plus_uconst varFieldOffset. Again, don't add if it's 0. if (varFieldOffset > 0) { addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); addUInt(*Loc, dwarf::DW_FORM_udata, varFieldOffset); } // Now attach the location information to the DIE. addBlock(Die, Attribute, Loc); } /// Return true if type encoding is unsigned. static bool isUnsignedDIType(DwarfDebug *DD, DIType Ty) { if (DIDerivedType DTy = dyn_cast(Ty)) { dwarf::Tag T = (dwarf::Tag)Ty->getTag(); // Encode pointer constants as unsigned bytes. This is used at least for // null pointer constant emission. // (Pieces of) aggregate types that get hacked apart by SROA may also be // represented by a constant. Encode them as unsigned bytes. // FIXME: reference and rvalue_reference /probably/ shouldn't be allowed // here, but accept them for now due to a bug in SROA producing bogus // dbg.values. if (T == dwarf::DW_TAG_array_type || T == dwarf::DW_TAG_class_type || T == dwarf::DW_TAG_pointer_type || T == dwarf::DW_TAG_ptr_to_member_type || T == dwarf::DW_TAG_reference_type || T == dwarf::DW_TAG_rvalue_reference_type || T == dwarf::DW_TAG_structure_type || T == dwarf::DW_TAG_union_type) return true; assert(T == dwarf::DW_TAG_typedef || T == dwarf::DW_TAG_const_type || T == dwarf::DW_TAG_volatile_type || T == dwarf::DW_TAG_restrict_type || T == dwarf::DW_TAG_enumeration_type); if (DITypeRef Deriv = DTy->getBaseType()) return isUnsignedDIType(DD, DD->resolve(Deriv)); // FIXME: Enums without a fixed underlying type have unknown signedness // here, leading to incorrectly emitted constants. assert(DTy->getTag() == dwarf::DW_TAG_enumeration_type); return false; } DIBasicType BTy = cast(Ty); unsigned Encoding = BTy->getEncoding(); assert((Encoding == dwarf::DW_ATE_unsigned || Encoding == dwarf::DW_ATE_unsigned_char || Encoding == dwarf::DW_ATE_signed || Encoding == dwarf::DW_ATE_signed_char || Encoding == dwarf::DW_ATE_float || Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || (Ty->getTag() == dwarf::DW_TAG_unspecified_type && Ty->getName() == ""decltype(nullptr)"")) && ""Unsupported encoding""); return Encoding == dwarf::DW_ATE_unsigned || Encoding == dwarf::DW_ATE_unsigned_char || Encoding == dwarf::DW_ATE_UTF || Encoding == dwarf::DW_ATE_boolean || Ty->getTag() == dwarf::DW_TAG_unspecified_type; } /// If this type is derived from a base type then return base type size. static uint64_t getBaseTypeSize(DwarfDebug *DD, DIDerivedType Ty) { unsigned Tag = Ty->getTag(); if (Tag != dwarf::DW_TAG_member && Tag != dwarf::DW_TAG_typedef && Tag != dwarf::DW_TAG_const_type && Tag != dwarf::DW_TAG_volatile_type && Tag != dwarf::DW_TAG_restrict_type) return Ty->getSizeInBits(); auto *BaseType = DD->resolve(Ty->getBaseType()); assert(BaseType && ""Unexpected invalid base type""); // If this is a derived type, go ahead and get the base type, unless it's a // reference then it's just the size of the field. Pointer types have no need // of this since they're a different type of qualification on the type. if (BaseType->getTag() == dwarf::DW_TAG_reference_type || BaseType->getTag() == dwarf::DW_TAG_rvalue_reference_type) return Ty->getSizeInBits(); if (auto *DT = dyn_cast(BaseType)) return getBaseTypeSize(DD, DT); return BaseType->getSizeInBits(); } /// addConstantFPValue - Add constant value entry in variable DIE. void DwarfUnit::addConstantFPValue(DIE &Die, const MachineOperand &MO) { assert(MO.isFPImm() && ""Invalid machine operand!""); DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); APFloat FPImm = MO.getFPImm()->getValueAPF(); // Get the raw data form of the floating point. const APInt FltVal = FPImm.bitcastToAPInt(); const char *FltPtr = (const char *)FltVal.getRawData(); int NumBytes = FltVal.getBitWidth() / 8; // 8 bits per byte. bool LittleEndian = Asm->getDataLayout().isLittleEndian(); int Incr = (LittleEndian ? 1 : -1); int Start = (LittleEndian ? 0 : NumBytes - 1); int Stop = (LittleEndian ? NumBytes : -1); // Output the constant to DWARF one byte at a time. for (; Start != Stop; Start += Incr) addUInt(*Block, dwarf::DW_FORM_data1, (unsigned char)0xFF & FltPtr[Start]); addBlock(Die, dwarf::DW_AT_const_value, Block); } /// addConstantFPValue - Add constant value entry in variable DIE. void DwarfUnit::addConstantFPValue(DIE &Die, const ConstantFP *CFP) { // Pass this down to addConstantValue as an unsigned bag of bits. addConstantValue(Die, CFP->getValueAPF().bitcastToAPInt(), true); } /// addConstantValue - Add constant value entry in variable DIE. void DwarfUnit::addConstantValue(DIE &Die, const ConstantInt *CI, DIType Ty) { addConstantValue(Die, CI->getValue(), Ty); } /// addConstantValue - Add constant value entry in variable DIE. void DwarfUnit::addConstantValue(DIE &Die, const MachineOperand &MO, DIType Ty) { assert(MO.isImm() && ""Invalid machine operand!""); addConstantValue(Die, isUnsignedDIType(DD, Ty), MO.getImm()); } void DwarfUnit::addConstantValue(DIE &Die, bool Unsigned, uint64_t Val) { // FIXME: This is a bit conservative/simple - it emits negative values always // sign extended to 64 bits rather than minimizing the number of bytes. addUInt(Die, dwarf::DW_AT_const_value, Unsigned ? dwarf::DW_FORM_udata : dwarf::DW_FORM_sdata, Val); } void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, DIType Ty) { addConstantValue(Die, Val, isUnsignedDIType(DD, Ty)); } // addConstantValue - Add constant value entry in variable DIE. void DwarfUnit::addConstantValue(DIE &Die, const APInt &Val, bool Unsigned) { unsigned CIBitWidth = Val.getBitWidth(); if (CIBitWidth <= 64) { addConstantValue(Die, Unsigned, Unsigned ? Val.getZExtValue() : Val.getSExtValue()); return; } DIEBlock *Block = new (DIEValueAllocator) DIEBlock(); // Get the raw data form of the large APInt. const uint64_t *Ptr64 = Val.getRawData(); int NumBytes = Val.getBitWidth() / 8; // 8 bits per byte. bool LittleEndian = Asm->getDataLayout().isLittleEndian(); // Output the constant to DWARF one byte at a time. for (int i = 0; i < NumBytes; i++) { uint8_t c; if (LittleEndian) c = Ptr64[i / 8] >> (8 * (i & 7)); else c = Ptr64[(NumBytes - 1 - i) / 8] >> (8 * ((NumBytes - 1 - i) & 7)); addUInt(*Block, dwarf::DW_FORM_data1, c); } addBlock(Die, dwarf::DW_AT_const_value, Block); } // Add a linkage name to the DIE. void DwarfUnit::addLinkageName(DIE &Die, StringRef LinkageName) { if (!LinkageName.empty()) addString(Die, DD->getDwarfVersion() >= 4 ? dwarf::DW_AT_linkage_name : dwarf::DW_AT_MIPS_linkage_name, GlobalValue::getRealLinkageName(LinkageName)); } /// addTemplateParams - Add template parameters into buffer. void DwarfUnit::addTemplateParams(DIE &Buffer, DIArray TParams) { // Add template parameters. for (unsigned i = 0, e = TParams.size(); i != e; ++i) { DIDescriptor Element = TParams[i]; if (auto *TTP = dyn_cast(Element)) constructTemplateTypeParameterDIE(Buffer, TTP); else if (auto *TVP = dyn_cast(Element)) constructTemplateValueParameterDIE(Buffer, TVP); } } /// getOrCreateContextDIE - Get context owner's DIE. DIE *DwarfUnit::getOrCreateContextDIE(DIScope Context) { if (!Context || isa(Context)) return &getUnitDie(); if (auto *T = dyn_cast(Context)) return getOrCreateTypeDIE(T); if (auto *NS = dyn_cast(Context)) return getOrCreateNameSpace(NS); if (auto *SP = dyn_cast(Context)) return getOrCreateSubprogramDIE(SP); return getDIE(Context); } DIE *DwarfUnit::createTypeDIE(DICompositeType Ty) { DIScope Context = resolve(Ty->getScope()); DIE *ContextDIE = getOrCreateContextDIE(Context); if (DIE *TyDIE = getDIE(Ty)) return TyDIE; // Create new type. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); constructTypeDIE(TyDIE, Ty); updateAcceleratorTables(Context, Ty, TyDIE); return &TyDIE; } /// getOrCreateTypeDIE - Find existing DIE or create new DIE for the /// given DIType. DIE *DwarfUnit::getOrCreateTypeDIE(const MDNode *TyNode) { if (!TyNode) return nullptr; auto *Ty = cast(TyNode); assert(Ty == resolve(Ty->getRef()) && ""type was not uniqued, possible ODR violation.""); // DW_TAG_restrict_type is not supported in DWARF2 if (Ty->getTag() == dwarf::DW_TAG_restrict_type && DD->getDwarfVersion() <= 2) return getOrCreateTypeDIE( resolve(DITypeRef(cast(Ty)->getBaseType()))); // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIScope Context = resolve(Ty->getScope()); DIE *ContextDIE = getOrCreateContextDIE(Context); assert(ContextDIE); if (DIE *TyDIE = getDIE(Ty)) return TyDIE; // Create new type. DIE &TyDIE = createAndAddDIE(Ty->getTag(), *ContextDIE, Ty); updateAcceleratorTables(Context, Ty, TyDIE); if (auto *BT = dyn_cast(Ty)) constructTypeDIE(TyDIE, BT); else if (DICompositeType CTy = dyn_cast(Ty)) { if (GenerateDwarfTypeUnits && !Ty->isForwardDecl()) if (MDString *TypeId = CTy->getRawIdentifier()) { DD->addDwarfTypeUnitType(getCU(), TypeId->getString(), TyDIE, CTy); // Skip updating the accelerator tables since this is not the full type. return &TyDIE; } constructTypeDIE(TyDIE, CTy); } else { constructTypeDIE(TyDIE, cast(Ty)); } return &TyDIE; } void DwarfUnit::updateAcceleratorTables(DIScope Context, DIType Ty, const DIE &TyDIE) { if (!Ty->getName().empty() && !Ty->isForwardDecl()) { bool IsImplementation = 0; if (auto *CT = dyn_cast(Ty)) { // A runtime language of 0 actually means C/C++ and that any // non-negative value is some version of Objective-C/C++. IsImplementation = CT->getRuntimeLang() == 0 || CT->isObjcClassComplete(); } unsigned Flags = IsImplementation ? dwarf::DW_FLAG_type_implementation : 0; DD->addAccelType(Ty->getName(), TyDIE, Flags); if (!Context || isa(Context) || isa(Context) || isa(Context)) addGlobalType(Ty, TyDIE, Context); } } /// addType - Add a new type attribute to the specified entity. void DwarfUnit::addType(DIE &Entity, DIType Ty, dwarf::Attribute Attribute) { assert(Ty && ""Trying to add a type that doesn't exist?""); // Check for pre-existence. DIEEntry *Entry = getDIEEntry(Ty); // If it exists then use the existing value. if (Entry) { addDIEEntry(Entity, Attribute, Entry); return; } // Construct type. DIE *Buffer = getOrCreateTypeDIE(Ty); // Set up proxy. Entry = createDIEEntry(*Buffer); insertDIEEntry(Ty, Entry); addDIEEntry(Entity, Attribute, Entry); } /// getParentContextString - Walks the metadata parent chain in a language /// specific manner (using the compile unit language) and returns /// it as a string. This is done at the metadata level because DIEs may /// not currently have been added to the parent context and walking the /// DIEs looking for names is more expensive than walking the metadata. std::string DwarfUnit::getParentContextString(DIScope Context) const { if (!Context) return """"; // FIXME: Decide whether to implement this for non-C++ languages. if (getLanguage() != dwarf::DW_LANG_C_plus_plus) return """"; std::string CS; SmallVector Parents; while (!isa(Context)) { Parents.push_back(Context); if (Context->getScope()) Context = resolve(Context->getScope()); else // Structure, etc types will have a NULL context if they're at the top // level. break; } // Reverse iterate over our list to go from the outermost construct to the // innermost. for (SmallVectorImpl::reverse_iterator I = Parents.rbegin(), E = Parents.rend(); I != E; ++I) { const MDScope *Ctx = *I; StringRef Name = Ctx->getName(); if (Name.empty() && isa(Ctx)) Name = ""(anonymous namespace)""; if (!Name.empty()) { CS += Name; CS += ""::""; } } return CS; } /// constructTypeDIE - Construct basic type die from DIBasicType. void DwarfUnit::constructTypeDIE(DIE &Buffer, DIBasicType BTy) { // Get core information. StringRef Name = BTy->getName(); // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); // An unspecified type only has a name attribute. if (BTy->getTag() == dwarf::DW_TAG_unspecified_type) return; addUInt(Buffer, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, BTy->getEncoding()); uint64_t Size = BTy->getSizeInBits() >> 3; addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); } /// constructTypeDIE - Construct derived type die from DIDerivedType. void DwarfUnit::constructTypeDIE(DIE &Buffer, DIDerivedType DTy) { // Get core information. StringRef Name = DTy->getName(); uint64_t Size = DTy->getSizeInBits() >> 3; uint16_t Tag = Buffer.getTag(); // Map to main type, void will not have a type. DIType FromTy = resolve(DTy->getBaseType()); if (FromTy) addType(Buffer, FromTy); // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); // Add size if non-zero (derived types might be zero-sized.) if (Size && Tag != dwarf::DW_TAG_pointer_type && Tag != dwarf::DW_TAG_ptr_to_member_type) addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); if (Tag == dwarf::DW_TAG_ptr_to_member_type) addDIEEntry( Buffer, dwarf::DW_AT_containing_type, *getOrCreateTypeDIE(resolve(cast(DTy)->getClassType()))); // Add source line info if available and TyDesc is not a forward declaration. if (!DTy->isForwardDecl()) addSourceLine(Buffer, DTy); } /// constructSubprogramArguments - Construct function argument DIEs. void DwarfUnit::constructSubprogramArguments(DIE &Buffer, DITypeArray Args) { for (unsigned i = 1, N = Args.size(); i < N; ++i) { DIType Ty = resolve(Args[i]); if (!Ty) { assert(i == N-1 && ""Unspecified parameter must be the last argument""); createAndAddDIE(dwarf::DW_TAG_unspecified_parameters, Buffer); } else { DIE &Arg = createAndAddDIE(dwarf::DW_TAG_formal_parameter, Buffer); addType(Arg, Ty); if (Ty->isArtificial()) addFlag(Arg, dwarf::DW_AT_artificial); } } } /// constructTypeDIE - Construct type DIE from DICompositeType. void DwarfUnit::constructTypeDIE(DIE &Buffer, DICompositeType CTy) { // Add name if not anonymous or intermediate type. StringRef Name = CTy->getName(); uint64_t Size = CTy->getSizeInBits() >> 3; uint16_t Tag = Buffer.getTag(); switch (Tag) { case dwarf::DW_TAG_array_type: constructArrayTypeDIE(Buffer, CTy); break; case dwarf::DW_TAG_enumeration_type: constructEnumTypeDIE(Buffer, CTy); break; case dwarf::DW_TAG_subroutine_type: { // Add return type. A void return won't have a type. auto Elements = cast(CTy)->getTypeArray(); if (Elements.size()) if (auto RTy = resolve(Elements[0])) addType(Buffer, RTy); bool isPrototyped = true; if (Elements.size() == 2 && !Elements[1]) isPrototyped = false; constructSubprogramArguments(Buffer, Elements); // Add prototype flag if we're dealing with a C language and the // function has been prototyped. uint16_t Language = getLanguage(); if (isPrototyped && (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || Language == dwarf::DW_LANG_ObjC)) addFlag(Buffer, dwarf::DW_AT_prototyped); if (CTy->isLValueReference()) addFlag(Buffer, dwarf::DW_AT_reference); if (CTy->isRValueReference()) addFlag(Buffer, dwarf::DW_AT_rvalue_reference); } break; case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_class_type: { // Add elements to structure type. DIArray Elements = CTy->getElements(); for (unsigned i = 0, N = Elements.size(); i < N; ++i) { DIDescriptor Element = Elements[i]; if (!Element) continue; if (auto *SP = dyn_cast(Element)) getOrCreateSubprogramDIE(SP); else if (DIDerivedType DDTy = dyn_cast(Element)) { if (DDTy->getTag() == dwarf::DW_TAG_friend) { DIE &ElemDie = createAndAddDIE(dwarf::DW_TAG_friend, Buffer); addType(ElemDie, resolve(DDTy->getBaseType()), dwarf::DW_AT_friend); } else if (DDTy->isStaticMember()) { getOrCreateStaticMemberDIE(DDTy); } else { constructMemberDIE(Buffer, DDTy); } } else if (DIObjCProperty Property = dyn_cast(Element)) { DIE &ElemDie = createAndAddDIE(Property->getTag(), Buffer); StringRef PropertyName = Property->getName(); addString(ElemDie, dwarf::DW_AT_APPLE_property_name, PropertyName); if (Property->getType()) addType(ElemDie, Property->getType()); addSourceLine(ElemDie, Property); StringRef GetterName = Property->getGetterName(); if (!GetterName.empty()) addString(ElemDie, dwarf::DW_AT_APPLE_property_getter, GetterName); StringRef SetterName = Property->getSetterName(); if (!SetterName.empty()) addString(ElemDie, dwarf::DW_AT_APPLE_property_setter, SetterName); if (unsigned PropertyAttributes = Property->getAttributes()) addUInt(ElemDie, dwarf::DW_AT_APPLE_property_attribute, None, PropertyAttributes); DIEEntry *Entry = getDIEEntry(Element); if (!Entry) { Entry = createDIEEntry(ElemDie); insertDIEEntry(Element, Entry); } } } if (CTy->isAppleBlockExtension()) addFlag(Buffer, dwarf::DW_AT_APPLE_block); // This is outside the DWARF spec, but GDB expects a DW_AT_containing_type // inside C++ composite types to point to the base class with the vtable. if (DICompositeType ContainingType = dyn_cast_or_null(resolve(CTy->getVTableHolder()))) addDIEEntry(Buffer, dwarf::DW_AT_containing_type, *getOrCreateTypeDIE(ContainingType)); if (CTy->isObjcClassComplete()) addFlag(Buffer, dwarf::DW_AT_APPLE_objc_complete_type); // Add template parameters to a class, structure or union types. // FIXME: The support isn't in the metadata for this yet. if (Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) addTemplateParams(Buffer, CTy->getTemplateParams()); break; } default: break; } // Add name if not anonymous or intermediate type. if (!Name.empty()) addString(Buffer, dwarf::DW_AT_name, Name); if (Tag == dwarf::DW_TAG_enumeration_type || Tag == dwarf::DW_TAG_class_type || Tag == dwarf::DW_TAG_structure_type || Tag == dwarf::DW_TAG_union_type) { // Add size if non-zero (derived types might be zero-sized.) // TODO: Do we care about size for enum forward declarations? if (Size) addUInt(Buffer, dwarf::DW_AT_byte_size, None, Size); else if (!CTy->isForwardDecl()) // Add zero size if it is not a forward declaration. addUInt(Buffer, dwarf::DW_AT_byte_size, None, 0); // If we're a forward decl, say so. if (CTy->isForwardDecl()) addFlag(Buffer, dwarf::DW_AT_declaration); // Add source line info if available. if (!CTy->isForwardDecl()) addSourceLine(Buffer, CTy); // No harm in adding the runtime language to the declaration. unsigned RLang = CTy->getRuntimeLang(); if (RLang) addUInt(Buffer, dwarf::DW_AT_APPLE_runtime_class, dwarf::DW_FORM_data1, RLang); } } /// constructTemplateTypeParameterDIE - Construct new DIE for the given /// DITemplateTypeParameter. void DwarfUnit::constructTemplateTypeParameterDIE(DIE &Buffer, DITemplateTypeParameter TP) { DIE &ParamDIE = createAndAddDIE(dwarf::DW_TAG_template_type_parameter, Buffer); // Add the type if it exists, it could be void and therefore no type. if (TP->getType()) addType(ParamDIE, resolve(TP->getType())); if (!TP->getName().empty()) addString(ParamDIE, dwarf::DW_AT_name, TP->getName()); } /// constructTemplateValueParameterDIE - Construct new DIE for the given /// DITemplateValueParameter. void DwarfUnit::constructTemplateValueParameterDIE(DIE &Buffer, DITemplateValueParameter VP) { DIE &ParamDIE = createAndAddDIE(VP->getTag(), Buffer); // Add the type if there is one, template template and template parameter // packs will not have a type. if (VP->getTag() == dwarf::DW_TAG_template_value_parameter) addType(ParamDIE, resolve(VP->getType())); if (!VP->getName().empty()) addString(ParamDIE, dwarf::DW_AT_name, VP->getName()); if (Metadata *Val = VP->getValue()) { if (ConstantInt *CI = mdconst::dyn_extract(Val)) addConstantValue(ParamDIE, CI, resolve(VP->getType())); else if (GlobalValue *GV = mdconst::dyn_extract(Val)) { // For declaration non-type template parameters (such as global values and // functions) DIELoc *Loc = new (DIEValueAllocator) DIELoc(); addOpAddress(*Loc, Asm->getSymbol(GV)); // Emit DW_OP_stack_value to use the address as the immediate value of the // parameter, rather than a pointer to it. addUInt(*Loc, dwarf::DW_FORM_data1, dwarf::DW_OP_stack_value); addBlock(ParamDIE, dwarf::DW_AT_location, Loc); } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_template_param) { assert(isa(Val)); addString(ParamDIE, dwarf::DW_AT_GNU_template_name, cast(Val)->getString()); } else if (VP->getTag() == dwarf::DW_TAG_GNU_template_parameter_pack) { addTemplateParams(ParamDIE, cast(Val)); } } } /// getOrCreateNameSpace - Create a DIE for DINameSpace. DIE *DwarfUnit::getOrCreateNameSpace(DINameSpace NS) { // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIE *ContextDIE = getOrCreateContextDIE(NS->getScope()); if (DIE *NDie = getDIE(NS)) return NDie; DIE &NDie = createAndAddDIE(dwarf::DW_TAG_namespace, *ContextDIE, NS); StringRef Name = NS->getName(); if (!Name.empty()) addString(NDie, dwarf::DW_AT_name, NS->getName()); else Name = ""(anonymous namespace)""; DD->addAccelNamespace(Name, NDie); addGlobalName(Name, NDie, NS->getScope()); addSourceLine(NDie, NS); return &NDie; } /// getOrCreateSubprogramDIE - Create new DIE using SP. DIE *DwarfUnit::getOrCreateSubprogramDIE(DISubprogram SP, bool Minimal) { // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE (as is the case for member function // declarations). DIE *ContextDIE = Minimal ? &getUnitDie() : getOrCreateContextDIE(resolve(SP->getScope())); if (DIE *SPDie = getDIE(SP)) return SPDie; if (auto *SPDecl = SP->getDeclaration()) { if (!Minimal) { // Add subprogram definitions to the CU die directly. ContextDIE = &getUnitDie(); // Build the decl now to ensure it precedes the definition. getOrCreateSubprogramDIE(SPDecl); } } // DW_TAG_inlined_subroutine may refer to this DIE. DIE &SPDie = createAndAddDIE(dwarf::DW_TAG_subprogram, *ContextDIE, SP); // Stop here and fill this in later, depending on whether or not this // subprogram turns out to have inlined instances or not. if (SP->isDefinition()) return &SPDie; applySubprogramAttributes(SP, SPDie); return &SPDie; } bool DwarfUnit::applySubprogramDefinitionAttributes(DISubprogram SP, DIE &SPDie) { DIE *DeclDie = nullptr; StringRef DeclLinkageName; if (auto *SPDecl = SP->getDeclaration()) { DeclDie = getDIE(SPDecl); assert(DeclDie && ""This DIE should've already been constructed when the "" ""definition DIE was created in "" ""getOrCreateSubprogramDIE""); DeclLinkageName = SPDecl->getLinkageName(); } // Add function template parameters. addTemplateParams(SPDie, SP->getTemplateParams()); // Add the linkage name if we have one and it isn't in the Decl. StringRef LinkageName = SP->getLinkageName(); assert(((LinkageName.empty() || DeclLinkageName.empty()) || LinkageName == DeclLinkageName) && ""decl has a linkage name and it is different""); if (DeclLinkageName.empty()) addLinkageName(SPDie, LinkageName); if (!DeclDie) return false; // Refer to the function declaration where all the other attributes will be // found. addDIEEntry(SPDie, dwarf::DW_AT_specification, *DeclDie); return true; } void DwarfUnit::applySubprogramAttributes(DISubprogram SP, DIE &SPDie, bool Minimal) { if (!Minimal) if (applySubprogramDefinitionAttributes(SP, SPDie)) return; // Constructors and operators for anonymous aggregates do not have names. if (!SP->getName().empty()) addString(SPDie, dwarf::DW_AT_name, SP->getName()); // Skip the rest of the attributes under -gmlt to save space. if (Minimal) return; addSourceLine(SPDie, SP); // Add the prototype if we have a prototype and we have a C like // language. uint16_t Language = getLanguage(); if (SP->isPrototyped() && (Language == dwarf::DW_LANG_C89 || Language == dwarf::DW_LANG_C99 || Language == dwarf::DW_LANG_ObjC)) addFlag(SPDie, dwarf::DW_AT_prototyped); DISubroutineType SPTy = SP->getType(); assert(SPTy->getTag() == dwarf::DW_TAG_subroutine_type && ""the type of a subprogram should be a subroutine""); auto Args = SPTy->getTypeArray(); // Add a return type. If this is a type like a C/C++ void type we don't add a // return type. if (Args.size()) if (auto Ty = resolve(Args[0])) addType(SPDie, Ty); unsigned VK = SP->getVirtuality(); if (VK) { addUInt(SPDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, VK); DIELoc *Block = getDIELoc(); addUInt(*Block, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); addUInt(*Block, dwarf::DW_FORM_udata, SP->getVirtualIndex()); addBlock(SPDie, dwarf::DW_AT_vtable_elem_location, Block); ContainingTypeMap.insert( std::make_pair(&SPDie, resolve(SP->getContainingType()))); } if (!SP->isDefinition()) { addFlag(SPDie, dwarf::DW_AT_declaration); // Add arguments. Do not add arguments for subprogram definition. They will // be handled while processing variables. constructSubprogramArguments(SPDie, Args); } if (SP->isArtificial()) addFlag(SPDie, dwarf::DW_AT_artificial); if (!SP->isLocalToUnit()) addFlag(SPDie, dwarf::DW_AT_external); if (SP->isOptimized()) addFlag(SPDie, dwarf::DW_AT_APPLE_optimized); if (unsigned isa = Asm->getISAEncoding()) addUInt(SPDie, dwarf::DW_AT_APPLE_isa, dwarf::DW_FORM_flag, isa); if (SP->isLValueReference()) addFlag(SPDie, dwarf::DW_AT_reference); if (SP->isRValueReference()) addFlag(SPDie, dwarf::DW_AT_rvalue_reference); if (SP->isProtected()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (SP->isPrivate()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); else if (SP->isPublic()) addUInt(SPDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (SP->isExplicit()) addFlag(SPDie, dwarf::DW_AT_explicit); } /// constructSubrangeDIE - Construct subrange DIE from DISubrange. void DwarfUnit::constructSubrangeDIE(DIE &Buffer, DISubrange SR, DIE *IndexTy) { DIE &DW_Subrange = createAndAddDIE(dwarf::DW_TAG_subrange_type, Buffer); addDIEEntry(DW_Subrange, dwarf::DW_AT_type, *IndexTy); // The LowerBound value defines the lower bounds which is typically zero for // C/C++. The Count value is the number of elements. Values are 64 bit. If // Count == -1 then the array is unbounded and we do not emit // DW_AT_lower_bound and DW_AT_count attributes. int64_t LowerBound = SR->getLowerBound(); int64_t DefaultLowerBound = getDefaultLowerBound(); int64_t Count = SR->getCount(); if (DefaultLowerBound == -1 || LowerBound != DefaultLowerBound) addUInt(DW_Subrange, dwarf::DW_AT_lower_bound, None, LowerBound); if (Count != -1) // FIXME: An unbounded array should reference the expression that defines // the array. addUInt(DW_Subrange, dwarf::DW_AT_count, None, Count); } DIE *DwarfUnit::getIndexTyDie() { if (IndexTyDie) return IndexTyDie; // Construct an integer type to use for indexes. IndexTyDie = &createAndAddDIE(dwarf::DW_TAG_base_type, UnitDie); addString(*IndexTyDie, dwarf::DW_AT_name, ""sizetype""); addUInt(*IndexTyDie, dwarf::DW_AT_byte_size, None, sizeof(int64_t)); addUInt(*IndexTyDie, dwarf::DW_AT_encoding, dwarf::DW_FORM_data1, dwarf::DW_ATE_unsigned); return IndexTyDie; } /// constructArrayTypeDIE - Construct array type DIE from DICompositeType. void DwarfUnit::constructArrayTypeDIE(DIE &Buffer, DICompositeType CTy) { if (CTy->isVector()) addFlag(Buffer, dwarf::DW_AT_GNU_vector); // Emit the element type. addType(Buffer, resolve(CTy->getBaseType())); // Get an anonymous type for index type. // FIXME: This type should be passed down from the front end // as different languages may have different sizes for indexes. DIE *IdxTy = getIndexTyDie(); // Add subranges to array type. DIArray Elements = CTy->getElements(); for (unsigned i = 0, N = Elements.size(); i < N; ++i) { // FIXME: Should this really be such a loose cast? if (auto *Element = dyn_cast_or_null(Elements[i])) if (Element->getTag() == dwarf::DW_TAG_subrange_type) constructSubrangeDIE(Buffer, cast(Element), IdxTy); } } /// constructEnumTypeDIE - Construct an enum type DIE from DICompositeType. void DwarfUnit::constructEnumTypeDIE(DIE &Buffer, DICompositeType CTy) { DIArray Elements = CTy->getElements(); // Add enumerators to enumeration type. for (unsigned i = 0, N = Elements.size(); i < N; ++i) { auto *Enum = dyn_cast_or_null(Elements[i]); if (Enum) { DIE &Enumerator = createAndAddDIE(dwarf::DW_TAG_enumerator, Buffer); StringRef Name = Enum->getName(); addString(Enumerator, dwarf::DW_AT_name, Name); int64_t Value = Enum->getValue(); addSInt(Enumerator, dwarf::DW_AT_const_value, dwarf::DW_FORM_sdata, Value); } } DIType DTy = resolve(CTy->getBaseType()); if (DTy) { addType(Buffer, DTy); addFlag(Buffer, dwarf::DW_AT_enum_class); } } /// constructContainingTypeDIEs - Construct DIEs for types that contain /// vtables. void DwarfUnit::constructContainingTypeDIEs() { for (DenseMap::iterator CI = ContainingTypeMap.begin(), CE = ContainingTypeMap.end(); CI != CE; ++CI) { DIE &SPDie = *CI->first; DIDescriptor D(CI->second); if (!D) continue; DIE *NDie = getDIE(D); if (!NDie) continue; addDIEEntry(SPDie, dwarf::DW_AT_containing_type, *NDie); } } /// constructMemberDIE - Construct member DIE from DIDerivedType. void DwarfUnit::constructMemberDIE(DIE &Buffer, DIDerivedType DT_) { // Downcast to MDDerivedType. const MDDerivedType *DT = cast(DT_); DIE &MemberDie = createAndAddDIE(DT->getTag(), Buffer); StringRef Name = DT->getName(); if (!Name.empty()) addString(MemberDie, dwarf::DW_AT_name, Name); addType(MemberDie, resolve(DT->getBaseType())); addSourceLine(MemberDie, DT); if (DT->getTag() == dwarf::DW_TAG_inheritance && DT->isVirtual()) { // For C++, virtual base classes are not at fixed offset. Use following // expression to extract appropriate offset from vtable. // BaseAddr = ObAddr + *((*ObAddr) - Offset) DIELoc *VBaseLocationDie = new (DIEValueAllocator) DIELoc(); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_dup); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_constu); addUInt(*VBaseLocationDie, dwarf::DW_FORM_udata, DT->getOffsetInBits()); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_minus); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_deref); addUInt(*VBaseLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus); addBlock(MemberDie, dwarf::DW_AT_data_member_location, VBaseLocationDie); } else { uint64_t Size = DT->getSizeInBits(); uint64_t FieldSize = getBaseTypeSize(DD, DT); uint64_t OffsetInBytes; if (FieldSize && Size != FieldSize) { // Handle bitfield, assume bytes are 8 bits. addUInt(MemberDie, dwarf::DW_AT_byte_size, None, FieldSize/8); addUInt(MemberDie, dwarf::DW_AT_bit_size, None, Size); uint64_t Offset = DT->getOffsetInBits(); uint64_t AlignMask = ~(DT->getAlignInBits() - 1); uint64_t HiMark = (Offset + FieldSize) & AlignMask; uint64_t FieldOffset = (HiMark - FieldSize); Offset -= FieldOffset; // Maybe we need to work from the other end. if (Asm->getDataLayout().isLittleEndian()) Offset = FieldSize - (Offset + Size); addUInt(MemberDie, dwarf::DW_AT_bit_offset, None, Offset); // Here DW_AT_data_member_location points to the anonymous // field that includes this bit field. OffsetInBytes = FieldOffset >> 3; } else // This is not a bitfield. OffsetInBytes = DT->getOffsetInBits() >> 3; if (DD->getDwarfVersion() <= 2) { DIELoc *MemLocationDie = new (DIEValueAllocator) DIELoc(); addUInt(*MemLocationDie, dwarf::DW_FORM_data1, dwarf::DW_OP_plus_uconst); addUInt(*MemLocationDie, dwarf::DW_FORM_udata, OffsetInBytes); addBlock(MemberDie, dwarf::DW_AT_data_member_location, MemLocationDie); } else addUInt(MemberDie, dwarf::DW_AT_data_member_location, None, OffsetInBytes); } if (DT->isProtected()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (DT->isPrivate()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); // Otherwise C++ member and base classes are considered public. else if (DT->isPublic()) addUInt(MemberDie, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (DT->isVirtual()) addUInt(MemberDie, dwarf::DW_AT_virtuality, dwarf::DW_FORM_data1, dwarf::DW_VIRTUALITY_virtual); // Objective-C properties. if (MDNode *PNode = DT->getObjCProperty()) if (DIEEntry *PropertyDie = getDIEEntry(PNode)) MemberDie.addValue(dwarf::DW_AT_APPLE_property, dwarf::DW_FORM_ref4, PropertyDie); if (DT->isArtificial()) addFlag(MemberDie, dwarf::DW_AT_artificial); } /// getOrCreateStaticMemberDIE - Create new DIE for C++ static member. DIE *DwarfUnit::getOrCreateStaticMemberDIE(DIDerivedType DT_) { const MDDerivedType *DT = cast_or_null(DT_); if (!DT) return nullptr; // Construct the context before querying for the existence of the DIE in case // such construction creates the DIE. DIE *ContextDIE = getOrCreateContextDIE(resolve(DT->getScope())); assert(dwarf::isType(ContextDIE->getTag()) && ""Static member should belong to a type.""); if (DIE *StaticMemberDIE = getDIE(DT)) return StaticMemberDIE; DIE &StaticMemberDIE = createAndAddDIE(DT->getTag(), *ContextDIE, DT); DIType Ty = resolve(DT->getBaseType()); addString(StaticMemberDIE, dwarf::DW_AT_name, DT->getName()); addType(StaticMemberDIE, Ty); addSourceLine(StaticMemberDIE, DT); addFlag(StaticMemberDIE, dwarf::DW_AT_external); addFlag(StaticMemberDIE, dwarf::DW_AT_declaration); // FIXME: We could omit private if the parent is a class_type, and // public if the parent is something else. if (DT->isProtected()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_protected); else if (DT->isPrivate()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_private); else if (DT->isPublic()) addUInt(StaticMemberDIE, dwarf::DW_AT_accessibility, dwarf::DW_FORM_data1, dwarf::DW_ACCESS_public); if (const ConstantInt *CI = dyn_cast_or_null(DT->getConstant())) addConstantValue(StaticMemberDIE, CI, Ty); if (const ConstantFP *CFP = dyn_cast_or_null(DT->getConstant())) addConstantFPValue(StaticMemberDIE, CFP); return &StaticMemberDIE; } void DwarfUnit::emitHeader(bool UseOffsets) { // Emit size of content not including length itself Asm->OutStreamer.AddComment(""Length of Unit""); Asm->EmitInt32(getHeaderSize() + UnitDie.getSize()); Asm->OutStreamer.AddComment(""DWARF version number""); Asm->EmitInt16(DD->getDwarfVersion()); Asm->OutStreamer.AddComment(""Offset Into Abbrev. Section""); // We share one abbreviations table across all units so it's always at the // start of the section. Use a relocatable offset where needed to ensure // linking doesn't invalidate that offset. const TargetLoweringObjectFile &TLOF = Asm->getObjFileLowering(); if (!UseOffsets) Asm->emitSectionOffset(TLOF.getDwarfAbbrevSection()->getBeginSymbol()); else Asm->EmitInt32(0); Asm->OutStreamer.AddComment(""Address Size (in bytes)""); Asm->EmitInt8(Asm->getDataLayout().getPointerSize()); } void DwarfUnit::initSection(const MCSection *Section) { assert(!this->Section); this->Section = Section; } void DwarfTypeUnit::emitHeader(bool UseOffsets) { DwarfUnit::emitHeader(UseOffsets); Asm->OutStreamer.AddComment(""Type Signature""); Asm->OutStreamer.EmitIntValue(TypeSignature, sizeof(TypeSignature)); Asm->OutStreamer.AddComment(""Type DIE Offset""); // In a skeleton type unit there is no type DIE so emit a zero offset. Asm->OutStreamer.EmitIntValue(Ty ? Ty->getOffset() : 0, sizeof(Ty->getOffset())); } bool DwarfTypeUnit::isDwoUnit() const { // Since there are no skeleton type units, all type units are dwo type units // when split DWARF is being used. return DD->useSplitDwarf(); } ",16331,True,3043.342775743189,median "/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the ""OpenStudio"" trademark, ""OS"", ""os"", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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 ""SchedulesView.hpp"" #include ""ScheduleDayView.hpp"" #include ""OSAppBase.hpp"" #include ""../shared_gui_components/OSCheckBox.hpp"" #include ""OSItem.hpp"" #include ""OSItemSelectorButtons.hpp"" #include ""../shared_gui_components/OSLineEdit.hpp"" #include ""../model/Model.hpp"" #include ""../model/Model_Impl.hpp"" #include ""../model/ScheduleRule.hpp"" #include ""../model/ScheduleRuleset.hpp"" #include ""../model/ScheduleRuleset_Impl.hpp"" #include ""../model/ScheduleRule_Impl.hpp"" #include ""../model/ScheduleTypeLimits.hpp"" #include ""../model/ScheduleTypeLimits_Impl.hpp"" #include ""../utilities/time/Date.hpp"" #include ""../utilities/time/Time.hpp"" #include ""../utilities/units/QuantityConverter.hpp"" #include ""../utilities/units/Quantity.hpp"" #include ""../utilities/units/OSOptionalQuantity.hpp"" #include ""../utilities/units/OSQuantityVector.hpp"" #include ""../utilities/core/Assert.hpp"" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace openstudio { /******************************************************************************/ // SchedulesView /******************************************************************************/ const std::vector SchedulesView::colors = SchedulesView::initializeColors(); std::vector SchedulesView::initializeColors() { std::vector _colors(13); _colors[0] = QColor(170,68,153); _colors[1] = QColor(51,34,136); _colors[2] = QColor(17,119,51); _colors[3] = QColor(153,153,51); _colors[4] = QColor(221,204,119); _colors[5] = QColor(204,102,119); _colors[6] = QColor(136,34,85); _colors[7] = QColor(68,170,153); _colors[8] = QColor(102,153,204); _colors[9] = QColor(102,17,0); _colors[10] = QColor(170,68,102); _colors[11] = QColor(80,80,80); _colors[12] = QColor(136,204,238); return _colors; } SchedulesView::SchedulesView(bool isIP, const model::Model & model) : QWidget(), m_model(model), m_leftVLayout(nullptr), m_contentLayout(nullptr), m_isIP(isIP) { qint64 time0 = QDateTime::currentMSecsSinceEpoch(); qDebug() << ""TIME START:"" << time0 << "" "" ; setObjectName(""GrayWidgetWithLeftTopBorders""); auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(1, 1, 0, 0); mainHLayout->setSpacing(0); setLayout(mainHLayout); auto leftScrollArea = new QScrollArea(); leftScrollArea->setFrameStyle(QFrame::NoFrame); auto outerLeftVLayout = new QVBoxLayout(); outerLeftVLayout->setContentsMargins(0, 0, 0, 0); outerLeftVLayout->addWidget(leftScrollArea, 10); outerLeftVLayout->addStretch(); auto selectorButtons = new OSItemSelectorButtons(); selectorButtons->enableCopyButton(); selectorButtons->enablePurgeButton(); selectorButtons->enableRemoveButton(); connect(selectorButtons, &OSItemSelectorButtons::itemDropped, this, &SchedulesView::itemDropped); connect(selectorButtons, &OSItemSelectorButtons::addClicked, this, &SchedulesView::addScheduleClicked); connect(selectorButtons, &OSItemSelectorButtons::copyClicked, this, &SchedulesView::copySelectedScheduleClicked); connect(selectorButtons, &OSItemSelectorButtons::removeClicked, this, &SchedulesView::removeSelectedScheduleClicked); connect(selectorButtons, &OSItemSelectorButtons::purgeClicked, this, &SchedulesView::purgeUnusedScheduleRulesetsClicked); connect(selectorButtons, &OSItemSelectorButtons::downloadComponentsClicked, this, &SchedulesView::downloadComponentsClicked); connect(this, &SchedulesView::toggleUnitsClicked, this, &SchedulesView::toggleUnits); outerLeftVLayout->addWidget(selectorButtons); mainHLayout->addLayout(outerLeftVLayout); auto vLine = new QWidget(); vLine->setObjectName(""VLine""); vLine->setStyleSheet(""QWidget#VLine { background: #445051;}""); vLine->setFixedWidth(2); mainHLayout->addWidget(vLine); auto leftScrollWidget = new QWidget(); leftScrollArea->setWidget(leftScrollWidget); leftScrollArea->setWidgetResizable(true); leftScrollWidget->setObjectName(""GrayWidget""); m_leftVLayout = new QVBoxLayout(); m_leftVLayout->setContentsMargins(0, 0, 0, 0); m_leftVLayout->setSpacing(0); m_leftVLayout->addStretch(); leftScrollWidget->setLayout(m_leftVLayout); m_contentLayout = new QHBoxLayout(); m_contentLayout->setContentsMargins(0, 0, 0, 0); mainHLayout->addLayout(m_contentLayout, 100); // m_model.getImpl().get()->addWorkspaceObjectPtr.connect(this); connect(OSAppBase::instance(), &OSAppBase::workspaceObjectAddedPtr, this, &SchedulesView::onModelObjectAdded, Qt::QueuedConnection); m_model.getImpl().get()->removeWorkspaceObjectPtr.connect(this); //connect(OSAppBase::instance(), &OSAppBase::workspaceObjectRemovedPtr, this, &SchedulesView::onModelObjectRemoved, Qt::QueuedConnection); // get all schedules std::vector schedules = m_model.getConcreteModelObjects(); // sort by name std::sort(schedules.begin(), schedules.end(), WorkspaceObjectNameGreater()); showEmptyPage(); for (auto it = schedules.begin(); it < schedules.end(); ++it) { addSchedule(*it); std::vector rules = it->scheduleRules(); for (auto ruleIt = rules.begin(); ruleIt < rules.end(); ++ruleIt) { addScheduleRule(*ruleIt); } } updateRowColors(); if (!schedules.empty()){ setCurrentSchedule(schedules.back()); } qint64 time1 = QDateTime::currentMSecsSinceEpoch(); qDebug() << ""TIME END:"" << time1 << "" , TOTAL:"" << (time1 - time0); } void SchedulesView::closeAllTabs() const { for (int i = 0; i < m_leftVLayout->count() - 1; i++) { ScheduleTab * scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); scheduleTab->scheduleTabContent()->hide(); } } ScheduleTab * SchedulesView::tabForSchedule(const model::ScheduleRuleset schedule) const { for (int i = 0; i < m_leftVLayout->count() - 1; i++) { ScheduleTab * scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); if (scheduleTab->schedule().handle() == schedule.handle()) { return scheduleTab; } } return nullptr; } void SchedulesView::updateRowColors() { QString evenStyle; evenStyle.append(""QWidget#ThermalZoneTab {""); evenStyle.append(""background: #F2F2F2; ""); evenStyle.append(""border-bottom: 1px solid black; ""); evenStyle.append(""}""); evenStyle.append(""QWidget#SideBar {background: #DEDEDE;}""); QString oddStyle; oddStyle.append(""QWidget#ThermalZoneTab {""); oddStyle.append(""background: #E6E6E6; ""); oddStyle.append(""border-bottom: 1px solid black; ""); oddStyle.append(""}""); oddStyle.append(""QWidget#SideBar {background: #CECECE;}""); for (int i = 0; i < m_leftVLayout->count() - 1; i++) { ScheduleTab * scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); if (i % 2 == 0) { scheduleTab->setStyleSheet(evenStyle); } else { scheduleTab->setStyleSheet(oddStyle); } } } void SchedulesView::addSchedule(model::ScheduleRuleset & schedule) { auto scheduleTab = new ScheduleTab(schedule, this); connect(scheduleTab, &ScheduleTab::scheduleClicked, this, &SchedulesView::setCurrentSchedule); m_leftVLayout->insertWidget(0, scheduleTab); } void SchedulesView::addScheduleRule(model::ScheduleRule & rule) { model::ScheduleRuleset scheduleRuleset = rule.scheduleRuleset(); ScheduleTab * tab = tabForSchedule(scheduleRuleset); if (tab) { tab->scheduleTabContent()->scheduleRefresh(scheduleRuleset.handle()); // Handle as dummy rule.getImpl().get()->onRemoveFromWorkspace.connect(tab->scheduleTabContent()); } } void SchedulesView::onModelObjectAdded(std::shared_ptr workspaceObjectImpl, const openstudio::IddObjectType&, const openstudio::UUID&) { boost::optional schedule = m_model.getModelObject(workspaceObjectImpl->handle()); if (schedule) { this->addSchedule(schedule.get()); this->setCurrentSchedule(schedule.get()); } boost::optional rule = m_model.getModelObject(workspaceObjectImpl->handle()); if (rule) { rule->getImpl().get()->onRemoveFromWorkspace.connect(this); addScheduleRule(rule.get()); } } void SchedulesView::onModelObjectRemoved(std::shared_ptr workspaceObjectImpl, const openstudio::IddObjectType&, const openstudio::UUID&) { if (workspaceObjectImpl->iddObject().type() == IddObjectType::OS_Schedule_Ruleset) { int removedIndex = -1; bool wasSelected = false; ScheduleTab * scheduleTab = nullptr; for (int i = 0; i < m_leftVLayout->count() - 1; i++) { scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); if (scheduleTab->schedule().handle() == workspaceObjectImpl->handle()) { m_leftVLayout->removeWidget(scheduleTab); wasSelected = scheduleTab->selected(); removedIndex = i; delete scheduleTab; break; } } if (wasSelected) { int newIndex = -1; if (removedIndex > 0) { newIndex = removedIndex - 1; } else if (removedIndex == 0) { if (m_leftVLayout->count() > 1) { newIndex = 0; } } if (newIndex > -1) { ScheduleTab * scheduleTab = qobject_cast(m_leftVLayout->itemAt(newIndex)->widget()); if (!scheduleTab->schedule().handle().isNull()){ this->setCurrentSchedule(scheduleTab->schedule()); } else { this->showEmptyPage(); } } else { this->showEmptyPage(); } } } } void SchedulesView::setCurrentSchedule(const model::ScheduleRuleset & schedule) { this->updateRowColors(); for (int i = 0; i < m_leftVLayout->count() - 1; i++) { ScheduleTab * scheduleTab; scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); if (scheduleTab->schedule() == schedule) { if (!scheduleTab->selected()) { scheduleTab->setSelected(true); scheduleTab->expand(); } else { scheduleTab->toggle(); } } else { scheduleTab->setSelected(false); scheduleTab->collapse(); } scheduleTab->update(); } //showScheduleRuleset(schedule); // DLM: I don't think that the code below works because it gets called when the scene is not visible showDefaultScheduleDay(schedule); } void SchedulesView::showAddRulePage(const model::ScheduleRuleset & scheduleRuleset) { this->setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } auto newProfileView = new NewProfileView(scheduleRuleset, this, NewProfileView::SCHEDULERULE); m_contentLayout->addWidget(newProfileView, 100); this->setUpdatesEnabled(true); boost::optional mo; emit modelObjectSelected(mo, true); } void SchedulesView::showScheduleRuleset(const model::ScheduleRuleset & schedule) { this->setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } auto scheduleRulesetNameView = new ScheduleRulesetNameView(schedule, this); m_contentLayout->addWidget(scheduleRulesetNameView, 100); this->setUpdatesEnabled(true); boost::optional mo; emit modelObjectSelected(mo, true); } void SchedulesView::showScheduleRule(model::ScheduleRule scheduleRule) { setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } auto scheduleView = new ScheduleRuleView(m_isIP, scheduleRule, this); connect(this, &SchedulesView::toggleUnitsClicked, scheduleView, &ScheduleRuleView::toggleUnitsClicked); m_contentLayout->addWidget(scheduleView); scheduleView->show(); setUpdatesEnabled(true); boost::optional mo = scheduleRule.daySchedule(); emit modelObjectSelected(mo, true); } void SchedulesView::onScheduleRuleRemoved(const Handle& handle) { // DLM: todo, show something else? showEmptyPage(); } void SchedulesView::showDefaultScheduleDay(const model::ScheduleRuleset & schedule) { setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } auto scheduleView = new DefaultScheduleDayView(m_isIP, schedule, this); connect(this, &SchedulesView::toggleUnitsClicked, scheduleView, &DefaultScheduleDayView::toggleUnitsClicked); m_contentLayout->addWidget(scheduleView); scheduleView->show(); setUpdatesEnabled(true); boost::optional mo = schedule.defaultDaySchedule(); emit modelObjectSelected(mo, true); } void SchedulesView::showSummerScheduleDay(model::ScheduleRuleset schedule) { setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } if (!schedule.isSummerDesignDayScheduleDefaulted()) { auto scheduleView = new SizingScheduleDayView(m_isIP, schedule, this, SizingScheduleDayView::SUMMER); connect(this, &SchedulesView::toggleUnitsClicked, scheduleView, &SizingScheduleDayView::toggleUnitsClicked); m_contentLayout->addWidget(scheduleView); scheduleView->show(); boost::optional mo = schedule.summerDesignDaySchedule(); emit modelObjectSelected(mo, true); } else { auto newProfileView = new NewProfileView(schedule, this, NewProfileView::SUMMER); m_contentLayout->addWidget(newProfileView, 100); boost::optional mo; emit modelObjectSelected(mo, true); } setUpdatesEnabled(true); } void SchedulesView::showWinterScheduleDay(model::ScheduleRuleset schedule) { setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } if (!schedule.isWinterDesignDayScheduleDefaulted()) { auto scheduleView = new SizingScheduleDayView(m_isIP, schedule, this, SizingScheduleDayView::WINTER); connect(this, &SchedulesView::toggleUnitsClicked, scheduleView, &SizingScheduleDayView::toggleUnitsClicked); m_contentLayout->addWidget(scheduleView); scheduleView->show(); boost::optional mo = schedule.winterDesignDaySchedule(); emit modelObjectSelected(mo, true); } else { auto newProfileView = new NewProfileView(schedule, this, NewProfileView::WINTER); m_contentLayout->addWidget(newProfileView, 100); boost::optional mo; emit modelObjectSelected(mo, true); } setUpdatesEnabled(true); } void SchedulesView::showEmptyPage() { this->setUpdatesEnabled(false); QLayoutItem *child; while ((child = m_contentLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } auto emptyWidget = new QWidget(); m_contentLayout->addWidget(emptyWidget, 100); this->setUpdatesEnabled(true); boost::optional mo; emit modelObjectSelected(mo, true); } boost::optional SchedulesView::currentSchedule() { for (int i = 0; i < m_leftVLayout->count() - 1; i++) { ScheduleTab * scheduleTab; scheduleTab = qobject_cast(m_leftVLayout->itemAt(i)->widget()); if (scheduleTab->selected()) { if (boost::optional schedule = scheduleTab->schedule()) { if (!schedule->handle().isNull()) { return schedule; } } } } return boost::none; } void SchedulesView::paintEvent(QPaintEvent * event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } // ***** SLOTS ***** void SchedulesView::toggleUnits(bool displayIP) { m_isIP = displayIP; } bool SchedulesView::isIP() const { return m_isIP; } /******************************************************************************/ // ScheduleTab /******************************************************************************/ ScheduleTab::ScheduleTab(const model::ScheduleRuleset & schedule, SchedulesView * schedulesView, QWidget * parent) : QWidget(parent), //m_mouseDown(false), m_selected(false), m_schedule(schedule), m_schedulesView(schedulesView) { auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->setSpacing(0); setLayout(mainVLayout); m_header = new ScheduleTabHeader(this); m_header->setText(QString::fromStdString(m_schedule.name().get())); mainVLayout->addWidget(m_header); auto line1 = new QFrame(); line1->setFrameShape(QFrame::HLine); line1->setFixedHeight(1); mainVLayout->addWidget(line1); m_content = new ScheduleTabContent(this); mainVLayout->addWidget(m_content); m_content->setVisible(false); auto line2 = new QFrame(); line2->setFrameShape(QFrame::HLine); line2->setFixedHeight(1); mainVLayout->addWidget(line2); } void ScheduleTab::expand() { m_content->show(); m_header->expand(); } void ScheduleTab::collapse() { m_content->hide(); m_header->collapse(); } void ScheduleTab::toggle() { m_header->toggle(); m_content->setVisible(!m_content->isVisible()); } ScheduleTabHeader * ScheduleTab::scheduleTabHeader() const { return m_header; } ScheduleTabContent * ScheduleTab::scheduleTabContent() const { return m_content; } SchedulesView * ScheduleTab::schedulesView() const { return m_schedulesView; } model::ScheduleRuleset ScheduleTab::schedule() { return m_schedule; } void ScheduleTab::setSelected(bool selected) { m_header->setSelected(selected); m_selected = selected; } bool ScheduleTab::selected() { return m_selected; } //void ScheduleTab::paintEvent ( QPaintEvent * event ) //{ // QStyleOption opt; // opt.init(this); // QPainter p(this); // style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); //} //void ScheduleTab::leaveEvent ( QEvent * event ) //{ // m_mouseDown = false; // // event->accept(); //} //void ScheduleTab::resizeEvent ( QResizeEvent * event ) //{ //} //void ScheduleTab::onRemoveClicked() //{ //} //void ScheduleTab::onObjectChanged() //{ //} //void ScheduleTab::refresh() //{ //} /******************************************************************************/ // ScheduleTabHeader /******************************************************************************/ ScheduleTabHeader::ScheduleTabHeader(ScheduleTab * scheduleTab, QWidget * parent) : QWidget(parent), m_scheduleTab(scheduleTab), m_mouseDown(false), m_dirty(true) { setObjectName(""ScheduleTabHeader""); auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(5, 5, 5, 5); mainHLayout->setSpacing(5); setLayout(mainHLayout); QString style; style.append(""QWidget#ScheduleTabHeader { ""); style.append(""background-color: #CECECE;""); style.append(""}""); setStyleSheet(style); m_mainLabel = new QLabel(this); mainHLayout->addWidget(m_mainLabel, 10); m_mainLabel->setWordWrap(true); //m_mainLabel->setFixedWidth(120); mainHLayout->addStretch(); m_toggleButton = new QPushButton(); m_toggleButton->setFlat(true); m_toggleButton->setCheckable(true); m_toggleButton->setChecked(false); m_toggleButton->setEnabled(false); connect(m_toggleButton, &QPushButton::toggled, this, &ScheduleTabHeader::toggleHeaderClicked); mainHLayout->addWidget(m_toggleButton); style.clear(); style.append(""QPushButton { ""); style.append(""border: none; ""); style.append(""background-image: url(\\"":/images/toggle_arrow.png\\""); ""); style.append(""} ""); style.append(""QPushButton:checked { ""); style.append(""background-image: url(\\"":/images/toggle_arrow_closed.png\\""); ""); style.append(""} ""); m_toggleButton->setFixedSize(11, 11); m_toggleButton->setStyleSheet(style); setFixedHeight(50); m_selectionWidget = new QWidget(this); m_selectionWidget->setFixedHeight(50); style.clear(); style.append(""QWidget { ""); style.append(""background-color: qlineargradient(x1:0,y1:0,x2:0,y2:1,""); style.append("" stop: 0.0 #636161,""); style.append("" stop: 0.10 #636161,""); style.append("" stop: 0.15 #A3A3A3,""); style.append("" stop: 1.0 #A3A3A3);""); style.append(""}""); m_selectionWidget->setStyleSheet(style); m_selectionWidget->hide(); refresh(); connect(this, &ScheduleTabHeader::scheduleClicked, m_scheduleTab, &ScheduleTab::scheduleClicked); m_scheduleTab->schedule().getImpl().get()->onChange.connect(this); } void ScheduleTabHeader::expand() { m_toggleButton->setChecked(false); } void ScheduleTabHeader::collapse() { m_toggleButton->setChecked(true); } void ScheduleTabHeader::toggle() { m_toggleButton->toggle(); } void ScheduleTabHeader::refresh() { m_dirty = true; QTimer::singleShot(0, this, SLOT(refreshNow())); } void ScheduleTabHeader::refreshNow() { if (m_dirty) { setText(QString::fromStdString(m_scheduleTab->schedule().name().get())); m_dirty = false; } } void ScheduleTabHeader::mouseReleaseEvent(QMouseEvent * event) { if (m_mouseDown) { emit scheduleClicked(scheduleTab()->schedule()); } m_mouseDown = false; event->accept(); } void ScheduleTabHeader::mousePressEvent(QMouseEvent * event) { m_mouseDown = true; event->accept(); } ScheduleTab * ScheduleTabHeader::scheduleTab() const { return m_scheduleTab; } void ScheduleTabHeader::setSelected(bool selected) { m_mainLabel->raise(); m_toggleButton->raise(); if (selected) { m_selectionWidget->show(); } else { m_selectionWidget->hide(); } } void ScheduleTabHeader::setText(const QString & text) { m_mainLabel->setText(text); } void ScheduleTabHeader::resizeEvent(QResizeEvent * event) { m_selectionWidget->resize(event->size().width(), 67); QWidget::resizeEvent(event); } void ScheduleTabHeader::paintEvent(QPaintEvent * event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); } /******************************************************************************/ // ScheduleTabContent /******************************************************************************/ ScheduleTabContent::ScheduleTabContent(ScheduleTab * scheduleTab, QWidget * parent) : QWidget(parent), m_scheduleTab(scheduleTab) { auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(5, 5, 5, 5); mainVLayout->setSpacing(5); setLayout(mainVLayout); QLabel * designDayLabel = new QLabel(""Design Day Profiles""); mainVLayout->addWidget(designDayLabel); auto summerDesignDayLayout = new QHBoxLayout(); summerDesignDayLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->addLayout(summerDesignDayLayout); auto summerTab = new ScheduleTabDefault(m_scheduleTab, ScheduleTabDefault::SUMMER); summerDesignDayLayout->addWidget(summerTab); auto winterDesignDayLayout = new QHBoxLayout(); winterDesignDayLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->addLayout(winterDesignDayLayout); auto winterTab = new ScheduleTabDefault(m_scheduleTab, ScheduleTabDefault::WINTER); winterDesignDayLayout->addWidget(winterTab); auto runPeriodLayout = new QHBoxLayout(); runPeriodLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->addLayout(runPeriodLayout); auto runPeriodButton = new QPushButton(); runPeriodButton->setText(""Run Period Profiles""); runPeriodButton->setObjectName(""Button""); QString style; style.append(""QWidget#Button { ""); style.append(""background: none; border: none; ""); style.append(""} ""); style.append(""QWidget#Button:hover { ""); style.append(""color: #2C3233;""); style.append(""}""); runPeriodButton->setStyleSheet(style); runPeriodButton->setToolTip(""Click to add new run period profile""); runPeriodLayout->addWidget(runPeriodButton); runPeriodLayout->addStretch(); connect(runPeriodButton, &QPushButton::clicked, this, &ScheduleTabContent::onScheduleRuleClicked); connect(this, &ScheduleTabContent::scheduleRuleClicked, m_scheduleTab->schedulesView(), &SchedulesView::showAddRulePage); auto addButton = new QPushButton(); addButton->setStyleSheet(""QPushButton { border: none; background-image: url(\\"":/images/add-small.png\\""); }""); addButton->setFixedSize(20, 20); connect(addButton, &QPushButton::clicked, this, &ScheduleTabContent::onScheduleRuleClicked); runPeriodLayout->addWidget(addButton); m_ruleLayout = new QVBoxLayout(); m_ruleLayout->setContentsMargins(0, 0, 0, 0); m_ruleLayout->setSpacing(0); mainVLayout->addLayout(m_ruleLayout); auto defaultLayout = new QHBoxLayout(); defaultLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->addLayout(defaultLayout); auto defaultTab = new ScheduleTabDefault(m_scheduleTab, ScheduleTabDefault::DEFAULT); defaultLayout->addWidget(defaultTab); } void ScheduleTabContent::refresh() { if (m_dirty) { model::ScheduleRuleset scheduleRuleset = m_scheduleTab->schedule(); QLayoutItem *child; while ((child = m_ruleLayout->takeAt(0)) != nullptr) { delete child->widget(); delete child; } std::vector scheduleRules = scheduleRuleset.scheduleRules(); for (auto it = scheduleRules.begin(); it < scheduleRules.end(); ++it) { auto scheduleTabRule = new ScheduleTabRule(m_scheduleTab, *it); m_ruleLayout->addWidget(scheduleTabRule); } m_dirty = false; } } void ScheduleTabContent::scheduleRefresh(const Handle& handle) { m_dirty = true; QTimer::singleShot(0, this, SLOT(refresh())); } void ScheduleTabContent::onScheduleRuleClicked() { emit scheduleRuleClicked(scheduleTab()->schedule()); } void ScheduleTabContent::onDefaultScheduleClicked() { emit defaultScheduleClicked(scheduleTab()->schedule()); } void ScheduleTabContent::addScheduleRule(const model::ScheduleRule & scheduleRule) { auto scheduleTabRule = new ScheduleTabRule(m_scheduleTab, scheduleRule); m_ruleLayout->insertWidget(0, scheduleTabRule); } ScheduleTab * ScheduleTabContent::scheduleTab() const { return m_scheduleTab; } /******************************************************************************/ // ScheduleTabRule /******************************************************************************/ ScheduleTabRule::ScheduleTabRule(ScheduleTab * scheduleTab, const model::ScheduleRule & scheduleRule, QWidget * parent) : QWidget(parent), m_scheduleTab(scheduleTab), m_scheduleRule(scheduleRule), m_mouseDown(false), m_dirty(true), m_hovering(false) { setFixedHeight(25); connect(this, &ScheduleTabRule::clicked, m_scheduleTab->schedulesView(), &SchedulesView::showScheduleRule); auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(10, 0, 0, 0); setLayout(mainHLayout); m_label = new QLabel(); m_label->setMouseTracking(true); mainHLayout->addWidget(m_label); scheduleRefresh(); m_scheduleRule.getImpl().get()->onChange.connect(this); setMouseTracking(true); } void ScheduleTabRule::refresh() { if (m_dirty) { QString stringLabel(""Priority ""); stringLabel.append(QString::number(m_scheduleRule.ruleIndex() + 1)); m_label->setText(stringLabel); QString tooltip(""Click to edit ""); tooltip.append(QString::fromStdString(m_scheduleRule.name().get())); setToolTip(tooltip); m_dirty = false; } } void ScheduleTabRule::scheduleRefresh() { m_dirty = true; QTimer::singleShot(0, this, SLOT(refresh())); } void ScheduleTabRule::paintEvent(QPaintEvent * event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); int i = m_scheduleRule.ruleIndex(); if (i > 12) { i = 12; } if (m_hovering) { p.setBrush(QBrush(QColor(207, 207, 207))); p.setPen(Qt::NoPen); p.drawRect(0, 0, size().width() - 1, size().height() - 1); } p.setBrush(QBrush(m_scheduleTab->schedulesView()->colors[i])); p.setPen(Qt::SolidLine); p.drawRect(0, 0, 5, size().height() - 1); p.setBrush(QBrush(QColor(Qt::black))); if (m_scheduleRule.ruleIndex() == 0) { p.drawLine(0, 0, size().width(), 0); } p.drawLine(0, size().height() - 1, size().width(), size().height() - 1); } void ScheduleTabRule::mouseMoveEvent(QMouseEvent * event) { m_hovering = true; update(); event->accept(); } void ScheduleTabRule::mouseReleaseEvent(QMouseEvent * event) { if (m_mouseDown) { emit clicked(m_scheduleRule); } m_mouseDown = false; event->accept(); } void ScheduleTabRule::mousePressEvent(QMouseEvent * event) { m_mouseDown = true; event->accept(); } void ScheduleTabRule::leaveEvent(QEvent * event) { m_mouseDown = false; m_hovering = false; update(); event->accept(); } /******************************************************************************/ // ScheduleTabDefault /******************************************************************************/ ScheduleTabDefault::ScheduleTabDefault(ScheduleTab * scheduleTab, ScheduleTabDefaultType type) : QWidget(scheduleTab), m_mouseDown(false), m_scheduleTab(scheduleTab), m_type(type), m_hovering(false) { setFixedHeight(25); connect(this, &ScheduleTabDefault::defaultClicked, m_scheduleTab->schedulesView(), &SchedulesView::showDefaultScheduleDay); connect(this, &ScheduleTabDefault::winterClicked, m_scheduleTab->schedulesView(), &SchedulesView::showWinterScheduleDay); connect(this, &ScheduleTabDefault::summerClicked, m_scheduleTab->schedulesView(), &SchedulesView::showSummerScheduleDay); auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(10, 0, 0, 0); setLayout(mainHLayout); //m_label = new QLabel(""Default""); switch (m_type) { case SUMMER: m_label = new QLabel(""Summer""); setToolTip(""Click to edit summer design day profile""); break; case WINTER: m_label = new QLabel(""Winter""); setToolTip(""Click to edit winter design day profile""); break; default: m_label = new QLabel(""Default""); setToolTip(""Click to edit default profile""); } m_label->setMouseTracking(true); mainHLayout->addWidget(m_label); setMouseTracking(true); } void ScheduleTabDefault::paintEvent(QPaintEvent * event) { QStyleOption opt; opt.init(this); QPainter p(this); style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this); if (m_hovering) { p.setBrush(QBrush(QColor(207, 207, 207))); p.setPen(Qt::NoPen); p.drawRect(0, 0, size().width() - 1, size().height() - 1); } p.setPen(Qt::SolidLine); // DLM: don't draw color squares for summer and winter design days if (m_type == DEFAULT) { p.setBrush(QBrush(m_scheduleTab->schedulesView()->colors[12])); p.drawRect(0, 0, 5, size().height() - 1); } p.setBrush(QBrush(QColor(Qt::black))); p.drawLine(0, 0, size().width(), 0); p.drawLine(0, size().height() - 1, size().width(), size().height() - 1); } void ScheduleTabDefault::mouseReleaseEvent(QMouseEvent * event) { if (m_mouseDown) { model::ScheduleRuleset schedule = m_scheduleTab->schedule(); switch (m_type) { case DEFAULT: emit defaultClicked(schedule); break; case SUMMER: emit summerClicked(schedule); break; case WINTER: emit winterClicked(schedule); break; } } m_mouseDown = false; event->accept(); } void ScheduleTabDefault::mouseMoveEvent(QMouseEvent * event) { m_hovering = true; update(); event->accept(); } void ScheduleTabDefault::mousePressEvent(QMouseEvent * event) { m_mouseDown = true; event->accept(); } void ScheduleTabDefault::leaveEvent(QEvent * event) { m_mouseDown = false; m_hovering = false; update(); event->accept(); } /******************************************************************************/ // NewProfileView /******************************************************************************/ NewProfileView::NewProfileView(const model::ScheduleRuleset & scheduleRuleset, SchedulesView * schedulesView, NewProfileViewType type) : QWidget(schedulesView), m_schedulesView(schedulesView), m_scheduleRuleset(scheduleRuleset), m_type(type) { auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(10, 10, 10, 10); mainVLayout->setSpacing(10); setLayout(mainVLayout); auto scheduleRulesetNameWidget = new ScheduleRulesetNameWidget(scheduleRuleset); mainVLayout->addWidget(scheduleRulesetNameWidget); switch (m_type) { case SUMMER: { auto label = new QLabel(); QString text; text.append(""The summer design day profile is not set, therefore the default run period profile will be used.""); text.append("" Create a new profile to override the default run period profile.""); label->setText(text); label->setWordWrap(true); mainVLayout->addWidget(label); mainVLayout->addSpacing(10); break; } case WINTER: { auto label = new QLabel(); QString text; text.append(""The winter design day profile is not set, therefore the default run period profile will be used.""); text.append("" Create a new profile to override the default run period profile.""); label->setText(text); label->setWordWrap(true); mainVLayout->addWidget(label); mainVLayout->addSpacing(10); break; } default: break; } auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(0, 0, 0, 0); auto box = new QWidget(); auto innerVLayout = new QVBoxLayout(); innerVLayout->setContentsMargins(0, 0, 0, 0); box->setLayout(innerVLayout); mainHLayout->addWidget(box); mainVLayout->addLayout(mainHLayout); if (m_type == SCHEDULERULE) { auto selectLabel = new QLabel(); selectLabel->setText(""Create a new profile.""); innerVLayout->addWidget(selectLabel); } auto gridLayout = new QGridLayout(); gridLayout->setContentsMargins(0, 0, 0, 0); QLabel * label = new QLabel(""Make a New Profile Based on:""); gridLayout->addWidget(label, 0, 0); m_scheduleRuleComboBox = new QComboBox(); populateComboBox(scheduleRuleset); gridLayout->addWidget(m_scheduleRuleComboBox, 0, 1); auto addButton = new QPushButton(); addButton->setText(""Add""); addButton->setObjectName(""StandardBlueButton""); gridLayout->addWidget(addButton, 1, 1); gridLayout->setColumnStretch(2, 100); innerVLayout->addLayout(gridLayout); connect(addButton, &QPushButton::clicked, this, &NewProfileView::onAddClicked); connect(this, &NewProfileView::addRuleClicked, schedulesView, &SchedulesView::addRuleClicked); connect(this, &NewProfileView::addSummerProfileClicked, schedulesView, &SchedulesView::addSummerProfileClicked); connect(this, &NewProfileView::addWinterProfileClicked, schedulesView, &SchedulesView::addWinterProfileClicked); innerVLayout->addStretch(); mainHLayout->addStretch(); } void NewProfileView::onAddClicked() { int currentIndex = m_scheduleRuleComboBox->currentIndex(); UUID handle = toUUID(m_scheduleRuleComboBox->itemData(currentIndex).toString()); switch (m_type) { case SUMMER: emit addSummerProfileClicked(m_scheduleRuleset, handle); break; case WINTER: emit addWinterProfileClicked(m_scheduleRuleset, handle); break; default: emit addRuleClicked(m_scheduleRuleset, handle); } } void NewProfileView::populateComboBox(const model::ScheduleRuleset & scheduleRuleset) { m_scheduleRuleComboBox->addItem("""", toQString(UUID())); m_scheduleRuleComboBox->addItem(""Default Day Schedule"", toQString(scheduleRuleset.defaultDaySchedule().handle())); if (!scheduleRuleset.isSummerDesignDayScheduleDefaulted()){ m_scheduleRuleComboBox->addItem(""Summer Design Day Schedule"", toQString(scheduleRuleset.summerDesignDaySchedule().handle())); } if (!scheduleRuleset.isWinterDesignDayScheduleDefaulted()){ m_scheduleRuleComboBox->addItem(""Winter Design Day Schedule"", toQString(scheduleRuleset.winterDesignDaySchedule().handle())); } for (const auto& rule : scheduleRuleset.scheduleRules()){ m_scheduleRuleComboBox->addItem(toQString(rule.name().get()), toQString(rule.daySchedule().handle())); } m_scheduleRuleComboBox->setCurrentIndex(0); } /******************************************************************************/ // ScheduleRulesetNameView /******************************************************************************/ ScheduleRulesetNameView::ScheduleRulesetNameView(const model::ScheduleRuleset & scheduleRuleset, SchedulesView * schedulesView) : QWidget(schedulesView), m_schedulesView(schedulesView), m_scheduleRuleset(scheduleRuleset) { auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(10, 10, 10, 10); mainVLayout->setSpacing(10); setLayout(mainVLayout); auto scheduleRulesetNameWidget = new ScheduleRulesetNameWidget(scheduleRuleset); mainVLayout->addWidget(scheduleRulesetNameWidget); mainVLayout->addStretch(); } /******************************************************************************/ // DefaultScheduleDayView /******************************************************************************/ DefaultScheduleDayView::DefaultScheduleDayView(bool isIP, const model::ScheduleRuleset & scheduleRuleset, SchedulesView * schedulesView) : QWidget(schedulesView) { // Layout auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(0, 0, 0, 0); mainHLayout->setSpacing(0); setLayout(mainHLayout); auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(10, 10, 10, 10); mainVLayout->setSpacing(10); mainHLayout->addLayout(mainVLayout, 100); // Name auto scheduleRulesetNameWidget = new ScheduleRulesetNameWidget(scheduleRuleset); mainVLayout->addWidget(scheduleRulesetNameWidget); QLabel * label = new QLabel(""Default day profile.""); label->setObjectName(""H2""); auto hLayout = new QHBoxLayout(); hLayout->setContentsMargins(60, 0, 0, 10); hLayout->addWidget(label); mainVLayout->addLayout(hLayout); // Schedule Day ScheduleDayView * scheduleDayView = new ScheduleDayView(isIP, scheduleRuleset.defaultDaySchedule(), schedulesView); connect(this, &DefaultScheduleDayView::toggleUnitsClicked, scheduleDayView, &ScheduleDayView::toggleUnitsClicked); mainVLayout->addWidget(scheduleDayView); // Year Overview auto vLine2 = new QWidget(); vLine2->setObjectName(""VLine""); vLine2->setStyleSheet(""QWidget#VLine { background: #445051;}""); vLine2->setFixedWidth(2); mainHLayout->addWidget(vLine2); auto yearOverview = new YearOverview(scheduleRuleset); mainHLayout->addWidget(yearOverview); } /******************************************************************************/ // SizingScheduleDayView /******************************************************************************/ SizingScheduleDayView::SizingScheduleDayView(bool isIP, const model::ScheduleRuleset & scheduleRuleset, SchedulesView * schedulesView, SizingScheduleDayType type) : QWidget(schedulesView), m_type(type) { // Layout auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(0, 0, 0, 0); mainHLayout->setSpacing(0); setLayout(mainHLayout); auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(10, 10, 10, 10); mainVLayout->setSpacing(10); mainHLayout->addLayout(mainVLayout, 100); // Name auto scheduleRulesetNameWidget = new ScheduleRulesetNameWidget(scheduleRuleset); mainVLayout->addWidget(scheduleRulesetNameWidget); // Schedule Day if (m_type == SUMMER) { if (!scheduleRuleset.isSummerDesignDayScheduleDefaulted()) { QLabel * label = new QLabel(""Summer design day profile.""); label->setObjectName(""H2""); auto hLayout = new QHBoxLayout(); hLayout->setContentsMargins(60, 0, 0, 10); hLayout->addWidget(label); mainVLayout->addLayout(hLayout); model::ScheduleDay scheduleDay = scheduleRuleset.summerDesignDaySchedule(); auto scheduleDayView = new ScheduleDayView(isIP, scheduleDay, schedulesView); connect(this, &SizingScheduleDayView::toggleUnitsClicked, scheduleDayView, &ScheduleDayView::toggleUnitsClicked); mainVLayout->addWidget(scheduleDayView); } } else { if (!scheduleRuleset.isWinterDesignDayScheduleDefaulted()) { QLabel * label = new QLabel(""Winter design day profile.""); label->setObjectName(""H2""); auto hLayout = new QHBoxLayout(); hLayout->setContentsMargins(60, 0, 0, 10); hLayout->addWidget(label); mainVLayout->addLayout(hLayout); model::ScheduleDay scheduleDay = scheduleRuleset.winterDesignDaySchedule(); auto scheduleDayView = new ScheduleDayView(isIP, scheduleDay, schedulesView); connect(this, &SizingScheduleDayView::toggleUnitsClicked, scheduleDayView, &ScheduleDayView::toggleUnitsClicked); mainVLayout->addWidget(scheduleDayView); } } } /******************************************************************************/ // ScheduleRuleView /******************************************************************************/ ScheduleRuleView::ScheduleRuleView(bool isIP, const model::ScheduleRule & scheduleRule, SchedulesView * schedulesView) : QWidget(schedulesView), m_schedulesView(schedulesView), m_scheduleRule(scheduleRule), m_dirty(false) { m_yearDescription = m_scheduleRule.model().getUniqueModelObject(); // Layout auto mainHLayout = new QHBoxLayout(); mainHLayout->setContentsMargins(0,0,0,0); mainHLayout->setSpacing(0); setLayout(mainHLayout); auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(10,10,10,10); mainVLayout->setSpacing(10); mainHLayout->addLayout(mainVLayout,100); // Name model::ScheduleRuleset scheduleRuleset = scheduleRule.scheduleRuleset(); auto scheduleRulesetNameWidget = new ScheduleRulesetNameWidget(scheduleRuleset); mainVLayout->addWidget(scheduleRulesetNameWidget); // Rule Settings auto ruleHLayout = new QHBoxLayout(); ruleHLayout->setContentsMargins(60,0,0,10); ruleHLayout->setSpacing(0); mainVLayout->addLayout(ruleHLayout); auto ruleWidget = new QWidget(); ruleHLayout->addWidget(ruleWidget); ruleHLayout->addStretch(10); auto removeButton = new QPushButton(); removeButton->setObjectName(""DeleteButton""); removeButton->setFlat(true); removeButton->setFixedSize(24,24); connect(removeButton, &QPushButton::clicked, this, &ScheduleRuleView::onRemoveClicked); ruleHLayout->addWidget(removeButton,0,Qt::AlignTop); ruleHLayout->addSpacing(20); auto ruleVLayout = new QVBoxLayout(); ruleVLayout->setContentsMargins(0,0,0,0); ruleVLayout->setSpacing(5); ruleWidget->setLayout(ruleVLayout); auto nameHLayout = new QHBoxLayout(); nameHLayout->setContentsMargins(0,0,0,0); auto colorWidget = new QWidget(); colorWidget->setFixedWidth(20); QString colorStyle; colorStyle.append(""QWidget { background-color: ""); int colorIndex = m_scheduleRule.ruleIndex(); if( colorIndex > 12 ) { colorIndex = 12; } QColor color = m_schedulesView->colors[colorIndex]; colorStyle.append(color.name()); colorStyle.append(""; }""); colorWidget->setStyleSheet(colorStyle); nameHLayout->addWidget(colorWidget); QString priorityString(""Priority ""); priorityString.append(QString::number(m_scheduleRule.ruleIndex() + 1)); auto priorityLabel = new QLabel(priorityString); nameHLayout->addWidget(priorityLabel); nameHLayout->addSpacing(10); m_nameEditField = new OSLineEdit2(); m_nameEditField->bind( m_scheduleRule, OptionalStringGetter(std::bind(&model::ScheduleRule::name, &m_scheduleRule,true)), boost::optional(std::bind(&model::ScheduleRule::setName, &m_scheduleRule,std::placeholders::_1)) ); nameHLayout->addWidget(m_nameEditField); ruleVLayout->addLayout(nameHLayout); auto dateHLayout = new QHBoxLayout(); QLabel * dateRangeLabel = new QLabel(""Date Range:""); dateHLayout->addWidget(dateRangeLabel); m_startDateEdit = new QDateTimeEdit(); m_startDateEdit->setDisplayFormat(""MM/dd""); m_startDateEdit->setCalendarPopup(true); dateHLayout->addWidget(m_startDateEdit); connect(m_startDateEdit, &QDateTimeEdit::dateTimeChanged, this, &ScheduleRuleView::onStartDateTimeChanged); m_endDateEdit = new QDateTimeEdit(); m_endDateEdit->setDisplayFormat(""MM/dd""); m_endDateEdit->setCalendarPopup(true); dateHLayout->addWidget(m_endDateEdit); connect(m_endDateEdit, &QDateTimeEdit::dateTimeChanged, this, &ScheduleRuleView::onEndDateTimeChanged); dateHLayout->addStretch(); ruleVLayout->addLayout(dateHLayout); auto weekHLayout = new QHBoxLayout(); QLabel * applyToLabel = new QLabel(""Apply to:""); weekHLayout->addWidget(applyToLabel); weekHLayout->addStretch(); m_sundayButton = new OSCheckBox2(); m_sundayButton->setText(""S""); m_sundayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applySunday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplySunday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_sundayButton); weekHLayout->addSpacing(10); m_mondayButton = new OSCheckBox2(); m_mondayButton->setText(""M""); m_mondayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applyMonday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplyMonday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_mondayButton); weekHLayout->addSpacing(10); m_tuesdayButton = new OSCheckBox2(); m_tuesdayButton->setText(""T""); m_tuesdayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applyTuesday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplyTuesday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_tuesdayButton); weekHLayout->addSpacing(10); m_wednesdayButton = new OSCheckBox2(); m_wednesdayButton->setText(""W""); m_wednesdayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applyWednesday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplyWednesday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_wednesdayButton); weekHLayout->addSpacing(10); m_thursdayButton = new OSCheckBox2(); m_thursdayButton->setText(""T""); m_thursdayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applyThursday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplyThursday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_thursdayButton); weekHLayout->addSpacing(10); m_fridayButton = new OSCheckBox2(); m_fridayButton->setText(""F""); m_fridayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applyFriday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplyFriday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_fridayButton); weekHLayout->addSpacing(10); m_saturdayButton = new OSCheckBox2(); m_saturdayButton->setText(""S""); m_saturdayButton->bind( m_scheduleRule, std::bind(&model::ScheduleRule::applySaturday,&m_scheduleRule), boost::optional(std::bind(&model::ScheduleRule::setApplySaturday,&m_scheduleRule,std::placeholders::_1))); weekHLayout->addWidget(m_saturdayButton); ruleVLayout->addLayout(weekHLayout); // Schedule Day m_scheduleDayView = new ScheduleDayView(isIP,m_scheduleRule.daySchedule(),m_schedulesView); connect(this, &ScheduleRuleView::toggleUnitsClicked, m_scheduleDayView, &ScheduleDayView::toggleUnitsClicked); connect(this, &ScheduleRuleView::toggleUnitsClicked, m_scheduleDayView, &ScheduleDayView::onToggleUnitsClicked); mainVLayout->addWidget(m_scheduleDayView); // Year Overview auto vLine2 = new QWidget(); vLine2->setObjectName(""VLine""); vLine2->setStyleSheet(""QWidget#VLine { background: #445051;}""); vLine2->setFixedWidth(2); mainHLayout->addWidget(vLine2); YearOverview * yearOverview = new YearOverview(m_scheduleRule.scheduleRuleset()); mainHLayout->addWidget(yearOverview); // Connect m_scheduleRule.getImpl().get()->onChange.connect(this); m_yearDescription->getImpl().get()->onChange.connect(this); connect(this, &ScheduleRuleView::startDateTimeChanged, m_schedulesView, &SchedulesView::startDateTimeChanged); connect(this, &ScheduleRuleView::endDateTimeChanged, m_schedulesView, &SchedulesView::endDateTimeChanged); connect(this, &ScheduleRuleView::removeScheduleRuleClicked, m_schedulesView, &SchedulesView::removeScheduleRuleClicked); // Refresh scheduleRefresh(); } void ScheduleRuleView::onRemoveClicked() { std::cout << ""ScheduleRuleView::onRemoveClicked: "" << m_scheduleRule << std::endl; //m_scheduleRule.remove(); m_scheduleRule.getImpl(); emit removeScheduleRuleClicked(m_scheduleRule); } model::ScheduleRule ScheduleRuleView::scheduleRule() const { return m_scheduleRule; } void ScheduleRuleView::refresh() { if( m_dirty ) { m_startDateEdit->blockSignals(true); m_endDateEdit->blockSignals(true); QDate minDate(QDate(m_yearDescription->assumedYear(),1,1)); QDate maxDate(QDate(m_yearDescription->assumedYear(),12,31)); m_startDateEdit->setDateRange(minDate,maxDate); m_endDateEdit->setDateRange(minDate,maxDate); boost::optional startDate = m_scheduleRule.startDate(); if( startDate ) { QDate qstartDate(startDate->year(),startDate->monthOfYear().value(),startDate->dayOfMonth()); m_startDateEdit->setDate(qstartDate); m_startDateEdit->calendarWidget()->setSelectedDate(qstartDate); } boost::optional endDate = m_scheduleRule.endDate(); if( endDate ) { QDate qendDate(endDate->year(),endDate->monthOfYear().value(),endDate->dayOfMonth()); m_endDateEdit->setDate(qendDate); m_endDateEdit->calendarWidget()->setSelectedDate(qendDate); } m_startDateEdit->blockSignals(false); m_endDateEdit->blockSignals(false); m_dirty = false; } } void ScheduleRuleView::scheduleRefresh() { m_dirty = true; QTimer::singleShot(0,this,SLOT(refresh())); } void ScheduleRuleView::onStartDateTimeChanged(const QDateTime & newDate) { emit startDateTimeChanged(m_scheduleRule,newDate); } void ScheduleRuleView::onEndDateTimeChanged(const QDateTime & newDate) { emit endDateTimeChanged(m_scheduleRule,newDate); } /******************************************************************************/ // ScheduleRulesetNameWidget /******************************************************************************/ ScheduleRulesetNameWidget::ScheduleRulesetNameWidget(const model::ScheduleRuleset & scheduleRuleset) : QWidget(), m_scheduleRuleset(scheduleRuleset) { auto mainVLayout = new QVBoxLayout(); mainVLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->setSpacing(10); setLayout(mainVLayout); QLabel * label; // Name auto hLayout = new QHBoxLayout(); hLayout->setContentsMargins(0, 0, 0, 0); hLayout->setSpacing(10); mainVLayout->addLayout(hLayout); label = new QLabel(""Schedule Name:""); label->setObjectName(""H2""); hLayout->addWidget(label); auto lineEdit = new OSLineEdit2(); // lineEdit->bind(m_scheduleRuleset, ""name""); opt_scheduleRuleset = m_scheduleRuleset; lineEdit->bind( *opt_scheduleRuleset, OptionalStringGetter(std::bind(&model::ScheduleRuleset::name, opt_scheduleRuleset.get_ptr(),true)), boost::optional(std::bind(&model::ScheduleRuleset::setName, opt_scheduleRuleset.get_ptr(),std::placeholders::_1)) ); hLayout->addWidget(lineEdit); // Schedule Type label = new QLabel(""Schedule Type:""); label->setObjectName(""H2""); hLayout->addWidget(label); QString scheduleTypeString(""""); boost::optional scheduleTypeLimits = scheduleRuleset.scheduleTypeLimits(); if (scheduleTypeLimits){ //boost::optional numericType = scheduleTypeLimits->numericType(); //if (numericType){ // scheduleTypeString.append(toQString(*numericType)); //} scheduleTypeString.append(toQString(scheduleTypeLimits->name().get())); } else { scheduleTypeString.append(""""); } scheduleTypeString.append(""""); label = new QLabel(scheduleTypeString); hLayout->addWidget(label); hLayout->addStretch(); // line QFrame * line; line = new QFrame(); line->setFrameShape(QFrame::HLine); line->setFrameShadow(QFrame::Sunken); mainVLayout->addWidget(line); } /******************************************************************************/ // YearOverview /******************************************************************************/ YearOverview::YearOverview(const model::ScheduleRuleset & scheduleRuleset, QWidget * parent) : QWidget(parent), m_scheduleRuleset(scheduleRuleset), m_dirty(false) { refreshActiveRuleIndices(); auto mainScrollLayout = new QVBoxLayout(); mainScrollLayout->setContentsMargins(0, 0, 0, 0); setLayout(mainScrollLayout); auto scrollArea = new QScrollArea(); scrollArea->setFrameStyle(QFrame::NoFrame); scrollArea->setWidgetResizable(true); scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); mainScrollLayout->addWidget(scrollArea); auto scrollWidget = new QWidget(); scrollArea->setWidget(scrollWidget); auto mainLayout = new QVBoxLayout(); mainLayout->setContentsMargins(0, 0, 0, 0); scrollWidget->setLayout(mainLayout); auto gridLayout = new QGridLayout(); gridLayout->setContentsMargins(0, 0, 0, 0); m_januaryView = new MonthView(this); m_januaryView->setMonth(1); gridLayout->addWidget(m_januaryView, 0, 0); m_februaryView = new MonthView(this); m_februaryView->setMonth(2); gridLayout->addWidget(m_februaryView, 1, 0); m_marchView = new MonthView(this); m_marchView->setMonth(3); gridLayout->addWidget(m_marchView, 2, 0); m_aprilView = new MonthView(this); m_aprilView->setMonth(4); gridLayout->addWidget(m_aprilView, 3, 0); m_mayView = new MonthView(this); m_mayView->setMonth(5); gridLayout->addWidget(m_mayView, 4, 0); m_juneView = new MonthView(this); m_juneView->setMonth(6); gridLayout->addWidget(m_juneView, 5, 0); m_julyView = new MonthView(this); m_julyView->setMonth(7); gridLayout->addWidget(m_julyView, 6, 0); m_augustView = new MonthView(this); m_augustView->setMonth(8); gridLayout->addWidget(m_augustView, 7, 0); m_septemberView = new MonthView(this); m_septemberView->setMonth(9); gridLayout->addWidget(m_septemberView, 8, 0); m_octoberView = new MonthView(this); m_octoberView->setMonth(10); gridLayout->addWidget(m_octoberView, 9, 0); m_novemberView = new MonthView(this); m_novemberView->setMonth(11); gridLayout->addWidget(m_novemberView, 10, 0); m_decemberView = new MonthView(this); m_decemberView->setMonth(12); gridLayout->addWidget(m_decemberView, 11, 0); mainLayout->addLayout(gridLayout); mainLayout->addStretch(10); //m_scheduleRuleset.model().getImpl().get()->addWorkspaceObjectPtr.connect(this); connect(OSAppBase::instance(), &OSAppBase::workspaceObjectAddedPtr, this, &YearOverview::onModelAdd, Qt::QueuedConnection); std::vector scheduleRules = m_scheduleRuleset.scheduleRules(); for (auto it = scheduleRules.begin(); it < scheduleRules.end(); ++it) { it->getImpl().get()->onChange.connect(this); } model::YearDescription yearDescription = m_scheduleRuleset.model().getUniqueModelObject(); yearDescription.getImpl().get()->onChange.connect(this); refresh(); } void YearOverview::refreshActiveRuleIndices() { int year = m_scheduleRuleset.model().getUniqueModelObject().assumedYear(); Date startDate(1, 1, year); Date endDate(12, 31, year); m_activeRuleIndices = m_scheduleRuleset.getActiveRuleIndices(startDate, endDate); m_dirty = false; } void YearOverview::onModelAdd(std::shared_ptr wo, const openstudio::IddObjectType& iddType, const openstudio::UUID& uuid) { boost::optional scheduleRule = m_scheduleRuleset.model().getModelObject(wo->handle()); if (scheduleRule) { if (scheduleRule->scheduleRuleset().handle() == m_scheduleRuleset.handle()) { scheduleRule->getImpl().get()->onChange.connect(this); } } } std::vector YearOverview::activeRuleIndices() const { return m_activeRuleIndices; } void YearOverview::scheduleRefresh() { m_dirty = true; QTimer::singleShot(0, this, SLOT(refresh())); } void YearOverview::refresh() { if (m_dirty) { refreshActiveRuleIndices(); m_januaryView->update(); m_februaryView->update(); m_marchView->update(); m_aprilView->update(); m_mayView->update(); m_juneView->update(); m_julyView->update(); m_augustView->update(); m_septemberView->update(); m_octoberView->update(); m_novemberView->update(); m_decemberView->update(); } update(); } model::ScheduleRuleset YearOverview::scheduleRuleset() const { return m_scheduleRuleset; } /******************************************************************************/ // MonthView /******************************************************************************/ MonthView::MonthView(YearOverview * yearOverview) : QWidget(yearOverview), m_yearOverview(yearOverview), m_month(0) { auto mainVLayout = new QVBoxLayout(); setLayout(mainVLayout); mainVLayout->setContentsMargins(0, 0, 0, 0); mainVLayout->setSpacing(0); m_monthLabel = new QLabel(""January""); mainVLayout->addWidget(m_monthLabel, 0, Qt::AlignCenter); mainVLayout->addSpacing(5); m_calendarWidget = new ScheduleCalendarWidget(this); m_calendarWidget->setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader); m_calendarWidget->setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames); m_calendarWidget->setNavigationBarVisible(false); m_calendarWidget->setSelectionMode(QCalendarWidget::NoSelection); mainVLayout->addWidget(m_calendarWidget); auto line1 = new QFrame(); line1->setFrameShape(QFrame::HLine); line1->setFixedHeight(1); mainVLayout->addWidget(line1); } int MonthView::month() const { return m_month; } YearOverview * MonthView::yearOverview() const { return m_yearOverview; } void MonthView::setMonth(int month) { m_month = month; std::string monthName = monthOfYear(month).valueName(); m_monthLabel->setText(QString::fromStdString(monthName)); update(); } void MonthView::update() { int year = m_yearOverview->scheduleRuleset().model().getUniqueModelObject().assumedYear(); QDate startDate(year, m_month, 1); QDate endDate(year, m_month, startDate.daysInMonth()); m_calendarWidget->setMinimumDate(startDate); m_calendarWidget->setMaximumDate(endDate); m_calendarWidget->update(); QWidget::update(); } /******************************************************************************/ // ScheduleCalendarWidget /******************************************************************************/ ScheduleCalendarWidget::ScheduleCalendarWidget(MonthView * monthView) : QCalendarWidget(monthView), m_monthView(monthView) { } void ScheduleCalendarWidget::paintCell(QPainter * painter, const QRect & rect, const QDate & date) const { painter->setBrush(QBrush(QColor(230, 230, 230))); if (date.month() == m_monthView->month()) { int dayOfYear = date.dayOfYear(); int ruleIndex = m_monthView->yearOverview()->activeRuleIndices()[dayOfYear - 1]; QColor ruleColor = SchedulesView::colors[12]; if (ruleIndex > 12) { ruleIndex = 12; } if (ruleIndex > -1) { ruleColor = SchedulesView::colors[ruleIndex]; } QString dateString = QString::number(date.day()); painter->setBrush(QBrush(ruleColor)); painter->drawRect(rect); painter->drawText(rect, Qt::AlignHCenter | Qt::AlignVCenter, dateString); } else { painter->drawRect(rect); } } } // openstudio ",16151,True,2941.7088281202837,median "[[box-component]] = Box Component :docTitle: Box :artifactId: camel-box :description: Upload, download and manage files, folders, groups, collaborations, etc. on box.com. :since: 2.14 :supportLevel: Stable :component-header: Both producer and consumer are supported include::{cq-version}@camel-quarkus:ROOT:partial$reference/components/box.adoc[opts=optional] *Since Camel {since}* *{component-header}* The Box component provides access to all of the Box.com APIs accessible using https://github.com/box/box-java-sdk/[https://github.com/box/box-java-sdk]. It allows producing messages to upload and download files, create, edit, and manage folders, etc. It also supports APIs that allow polling for updates to user accounts and even changes to enterprise accounts, etc. Box.com requires the use of OAuth2.0 for all client application authentication. In order to use camel-box with your account, you'll need to create a new application within Box.com at https://developer.box.com/[https://developer.box.com]. The Box application's client id and secret will allow access to Box APIs which require a current user. A user access token is generated and managed by the API for an end user. Maven users will need to add the following dependency to their pom.xml for this component: [source,xml] ---- org.apache.camel camel-box ${camel-version} ---- == Connection Authentication Types The Box component supports three different types of authenticated connections. === Standard Authentication *Standard Authentication* uses the *OAuth 2.0 three-legged authentication process* to authenticate its connections with Box.com. This type of authentication enables Box *managed users* and *external users* to access, edit, and save their Box content through the Box component. === App Enterprise Authentication *App Enterprise Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as a *Service Account* for a *Box Application*. This type of authentication enables a service account to access, edit, and save the Box content of its *Box Application* through the Box component. === App User Authentication *App User Authentication* uses the *OAuth 2.0 with JSON Web Tokens (JWT)* to authenticate its connections as an *App User* for a *Box Application*. This type of authentication enables app users to access, edit, and save their Box content in its *Box Application* through the Box component. == Box Options // component options: START The Box component supports 19 options, which are listed below. [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *configuration* (common) | To use the shared configuration | | BoxConfiguration | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *userId* (common) | The user ID to use for an App User. | | String | *bridgeErrorHandler* (consumer) | Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions occurred while the consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored. | false | boolean | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *autowiredEnabled* (advanced) | Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc. | true | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== // component options: END // endpoint options: START The Box endpoint is configured using URI syntax: ---- box:apiName/methodName ---- with the following path and query parameters: === Path Parameters (2 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *apiName* | *Required* What kind of operation to perform. There are 10 enums and the value can be one of: COLLABORATIONS, COMMENTS, EVENT_LOGS, FILES, FOLDERS, GROUPS, EVENTS, SEARCH, TASKS, USERS | | BoxApiName | *methodName* | *Required* What sub operation to use for the selected operation | | String |=== === Query Parameters (19 parameters): [width=""100%"",cols=""2,5,^1,2"",options=""header""] |=== | Name | Description | Default | Type | *clientId* (common) | Box application client ID | | String | *enterpriseId* (common) | The enterprise ID to use for an App Enterprise. | | String | *inBody* (common) | Sets the name of a parameter to be passed in the exchange In Body | | String | *userId* (common) | The user ID to use for an App User. | | String | *exceptionHandler* (consumer) | To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored. | | ExceptionHandler | *exchangePattern* (consumer) | Sets the exchange pattern when the consumer creates an exchange. There are 3 enums and the value can be one of: InOnly, InOut, InOptionalOut | | ExchangePattern | *lazyStartProducer* (producer) | Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel's routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing. | false | boolean | *httpParams* (advanced) | Custom HTTP params for settings like proxy host | | Map | *authenticationType* (authentication) | The type of authentication for connection. Types of Authentication: STANDARD_AUTHENTICATION - OAuth 2.0 (3-legged) SERVER_AUTHENTICATION - OAuth 2.0 with JSON Web Tokens | APP_USER_AUTHENTICATION | String | *accessTokenCache* (security) | Custom Access Token Cache for storing and retrieving access tokens. | | IAccessTokenCache | *clientSecret* (security) | Box application client secret | | String | *encryptionAlgorithm* (security) | The type of encryption algorithm for JWT. Supported Algorithms: RSA_SHA_256 RSA_SHA_384 RSA_SHA_512. There are 3 enums and the value can be one of: RSA_SHA_256, RSA_SHA_384, RSA_SHA_512 | RSA_SHA_256 | EncryptionAlgorithm | *maxCacheEntries* (security) | The maximum number of access tokens in cache. | 100 | int | *privateKeyFile* (security) | The private key for generating the JWT signature. | | String | *privateKeyPassword* (security) | The password for the private key. | | String | *publicKeyId* (security) | The ID for public key for validating the JWT signature. | | String | *sslContextParameters* (security) | To configure security using SSLContextParameters. | | SSLContextParameters | *userName* (security) | Box user name, MUST be provided | | String | *userPassword* (security) | Box user password, MUST be provided if authSecureStorage is not set, or returns null on first call | | String |=== === API Parameters (10 APIs): The Box endpoint is an API based component and has additional parameters based on which API name and API method is used. The API name and API method is located in the endpoint URI as the apiName/methodName path parameters: ---- box:apiName/methodName ---- There are 10 API names as listed in the table below: [width=""100%"",cols=""2,2,6"",options=""header""] |=== | API Name | Type | Description | *collaborations* | Producer | Provides operations to manage Box collaborations | *comments* | Producer | Provides operations to manage Box comments | *event-logs* | Producer | Provides operations to read Box enterprise (admin) event logs | *events* | Consumer | Provides operations to manage Box events | *files* | Producer | Provides operations to manage Box files | *folders* | Producer | Provides operations to manage Box folders | *groups* | Producer | Provides operations to manage Box groups | *search* | Producer | Provides operations to manage Box searches | *tasks* | Producer | Provides operations to manage Box tasks | *users* | Producer | Provides operations to manage Box users |=== Each API is documented in the following sections to come. ==== API: collaborations *Only producer is supported* The collaborations API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxCollaboration addFolderCollaboration(String folderId, com.box.sdk.BoxCollaborator collaborator, com.box.sdk.BoxCollaboration.Role role); com.box.sdk.BoxCollaboration addFolderCollaborationByEmail(String folderId, String email, com.box.sdk.BoxCollaboration.Role role); void deleteCollaboration(String collaborationId); com.box.sdk.BoxCollaboration.Info getCollaborationInfo(String collaborationId); java.util.Collection getFolderCollaborations(String folderId); com.box.sdk.BoxCollaboration updateCollaborationInfo(String collaborationId, com.box.sdk.BoxCollaboration.Info info); ---- The collaborations API is defined in the syntax as follows: ---- box:collaborations/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFolderCollaboration* | add | Add a collaboration to this folder | *addFolderCollaborationByEmail* | addByEmail | Add a collaboration to this folder | *deleteCollaboration* | delete | Delete collaboration | *getCollaborationInfo* | info | Get collaboration information | *getFolderCollaborations* | collaborations | Get information about all of the collaborations for folder | *updateCollaborationInfo* | updateInfo | Update collaboration information |=== The collaborations API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFolderCollaboration | *collaborator* | The collaborator to add | BoxCollaborator | addFolderCollaboration | *folderId* | The id of folder to add collaboration to | String | addFolderCollaboration | *role* | The role of the collaborator | Role | addFolderCollaborationByEmail | *email* | The email address of the collaborator to add | String | addFolderCollaborationByEmail | *folderId* | The id of folder to add collaboration to | String | addFolderCollaborationByEmail | *role* | The role of the collaborator | Role | deleteCollaboration | *collaborationId* | The id of comment to change | String | getCollaborationInfo | *collaborationId* | The id of collaboration | String | getFolderCollaborations | *folderId* | The id of folder to get collaborations information on | String | updateCollaborationInfo | *collaborationId* | The id of collaboration | String | updateCollaborationInfo | *info* | Collaboration information to update | Info |=== In addition to the parameters above, the collaborations API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: comments *Only producer is supported* The comments API has 6 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFile addFileComment(String fileId, String message); com.box.sdk.BoxComment changeCommentMessage(String commentId, String message); void deleteComment(String commentId); com.box.sdk.BoxComment.Info getCommentInfo(String commentId); java.util.List getFileComments(String fileId); com.box.sdk.BoxComment replyToComment(String commentId, String message); ---- The comments API is defined in the syntax as follows: ---- box:comments/methodName?[parameters] ---- The 6 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addFileComment* | add | Add comment to file | *changeCommentMessage* | updateMessage | Change comment message | *deleteComment* | delete | Delete comment | *getCommentInfo* | info | Get comment information | *getFileComments* | comments | Get a list of any comments on this file | *replyToComment* | reply | Reply to a comment |=== The comments API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addFileComment | *fileId* | The id of file | String | addFileComment | *message* | The comment's message | String | changeCommentMessage | *commentId* | The id of comment to change | String | changeCommentMessage | *message* | The new message for the comment | String | deleteComment | *commentId* | The id of comment to delete | String | getCommentInfo | *commentId* | The id of comment | String | getFileComments | *fileId* | The id of file | String | replyToComment | *commentId* | The id of comment to reply to | String | replyToComment | *message* | The message for the reply | String |=== In addition to the parameters above, the comments API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: event-logs *Only producer is supported* The event-logs API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.List getEnterpriseEvents(String position, java.util.Date after, java.util.Date before, com.box.sdk.BoxEvent.Type[] types); ---- The event-logs API is defined in the syntax as follows: ---- box:event-logs/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *getEnterpriseEvents* | events | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The event-logs API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | getEnterpriseEvents | *after* | The lower bound on the timestamp of the events returned | Date | getEnterpriseEvents | *before* | The upper bound on the timestamp of the events returned | Date | getEnterpriseEvents | *position* | *Optional* The starting position of the event stream. May be null in which case all events within bounds returned. | String | getEnterpriseEvents | *types* | *Optional* An optional list of event types to filter by | Type[] |=== In addition to the parameters above, the event-logs API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: events *Only consumer is supported* The events API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void listen(com.box.sdk.EventListener listener, Long startingPosition); ---- The events API is defined in the syntax as follows: ---- box:events/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *listen* | | Create an event stream with optional starting initial position and add listener that will be notified when an event is received |=== The events API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | listen | *startingPosition* | *Optional* The starting position of the event stream | Long |=== In addition to the parameters above, the events API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: files *Only producer is supported* The files API has 22 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- void checkUpload(String fileName, String parentFolderId, Long size); com.box.sdk.BoxFile copyFile(String fileId, String destinationFolderId, String newName); com.box.sdk.Metadata createFileMetadata(String fileId, com.box.sdk.Metadata metadata, String typeName); com.box.sdk.BoxSharedLink createFileSharedLink(String fileId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFile(String fileId); void deleteFileMetadata(String fileId); void deleteFileVersion(String fileId, Integer version); java.io.OutputStream downloadFile(String fileId, java.io.OutputStream output, Long rangeStart, Long rangeEnd, com.box.sdk.ProgressListener listener); java.io.OutputStream downloadPreviousFileVersion(String fileId, Integer version, java.io.OutputStream output, com.box.sdk.ProgressListener listener); java.net.URL getDownloadURL(String fileId); com.box.sdk.BoxFile.Info getFileInfo(String fileId, String[] fields); com.box.sdk.Metadata getFileMetadata(String fileId, String typeName); java.net.URL getFilePreviewLink(String fileId); byte[] getFileThumbnail(String fileId, com.box.sdk.BoxFile.ThumbnailFileType fileType, Integer minWidth, Integer minHeight, Integer maxWidth, Integer maxHeight); java.util.Collection getFileVersions(String fileId); com.box.sdk.BoxFile moveFile(String fileId, String destinationFolderId, String newName); com.box.sdk.BoxFileVersion promoteFileVersion(String fileId, Integer version); com.box.sdk.BoxFile renameFile(String fileId, String newFileName); com.box.sdk.BoxFile updateFileInfo(String fileId, com.box.sdk.BoxFile.Info info); com.box.sdk.Metadata updateFileMetadata(String fileId, com.box.sdk.Metadata metadata); com.box.sdk.BoxFile uploadFile(String parentFolderId, java.io.InputStream content, String fileName, java.util.Date created, java.util.Date modified, Long size, Boolean check, com.box.sdk.ProgressListener listener); com.box.sdk.BoxFile uploadNewFileVersion(String fileId, java.io.InputStream fileContent, java.util.Date modified, Long fileSize, com.box.sdk.ProgressListener listener); ---- The files API is defined in the syntax as follows: ---- box:files/methodName?[parameters] ---- The 22 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *checkUpload* | canUpload | Does a pre-verification before upload, to check if the filename already exists or if there is permission to upload | *copyFile* | copy | Copy file to destination folder while optionally giving it a new name | *createFileMetadata* | createMetadata | Create metadata for file in either the global properties template or the specified template type | *createFileSharedLink* | link | Create a shared link to file | *deleteFile* | delete | Delete the file | *deleteFileMetadata* | deleteMetadata | Delete the file properties metadata | *deleteFileVersion* | deleteVersion | Delete a file version | *downloadFile* | download | Download a file | *downloadPreviousFileVersion* | downloadVersion | Download a previous version of file | *getDownloadURL* | url | Get an expiring URL for downloading a file directly from Box | *getFileInfo* | info | Get file information | *getFileMetadata* | metadata | Gets the file properties metadata | *getFilePreviewLink* | | Get an expiring URL for creating an embedded preview session | *getFileThumbnail* | thumbnail | Retrieves a thumbnail, or smaller image representation, of this file | *getFileVersions* | versions | Get any previous versions of file | *moveFile* | move | Move file to destination folder while optionally giving it a new name | *promoteFileVersion* | promoteVersion | Promote a previous version of file | *renameFile* | rename | Rename file giving it the name newName | *updateFileInfo* | updateInfo | Update file information | *updateFileMetadata* | updateMetadata | Update the file properties metadata | *uploadFile* | upload | Upload a new file to parent folder | *uploadNewFileVersion* | uploadVersion | Upload a new version of file |=== The files API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | checkUpload | *fileName* | The name to give the uploaded file | String | checkUpload | *parentFolderId* | The id of parent folder | String | checkUpload | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | copyFile | *destinationFolderId* | The id of the destination folder | String | copyFile | *fileId* | The id of file to copy | String | copyFile | *newName* | *Optional* The new name for copied file; if newName is null, the copied file has same name as the original. | String | createFileMetadata | *fileId* | The id of the file to create metadata for | String | createFileMetadata | *metadata* | The new metadata values | Metadata | createFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | createFileSharedLink | *access* | The access level of the shared link | Access | createFileSharedLink | *fileId* | The id of the file to create shared link on | String | createFileSharedLink | *permissions* | *Optional* The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFileSharedLink | *unshareDate* | *Optional* The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFile | *fileId* | The id of file to delete | String | deleteFileMetadata | *fileId* | The id of file to delete | String | deleteFileVersion | *fileId* | The id of file with version to delete | String | deleteFileVersion | *version* | The version of file to delete; initial version of file has value of 0, second version of file is 1 and so on. | Integer | downloadFile | *fileId* | The id of file | String | downloadFile | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadFile | *output* | The stream to which the file contents will be written | OutputStream | downloadFile | *rangeEnd* | *Optional* The byte offset in file at which to stop the download; if null the entire contents of file will be downloaded. | Long | downloadFile | *rangeStart* | *Optional* The byte offset in file at which to start the download; if null the entire contents of file will be downloaded. | Long | downloadPreviousFileVersion | *fileId* | The id of file | String | downloadPreviousFileVersion | *listener* | *Optional* A listener for monitoring the download's progress; if null the download's progress will not be monitored. | ProgressListener | downloadPreviousFileVersion | *output* | The stream to which the version contents will be written | OutputStream | downloadPreviousFileVersion | *version* | The version of file to download; initial version of file has value of 0, second version of file is 1 and so on. | Integer | getDownloadURL | *fileId* | The id of file | String | getFileInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFileInfo | *fileId* | The id of file | String | getFileMetadata | *fileId* | The id of the file to retrieve metadata for | String | getFileMetadata | *typeName* | *Optional* The metadata template type name; if null the global properties template type is used. | String | getFilePreviewLink | *fileId* | The id of the file to get preview link on | String | getFileThumbnail | *fileId* | The id of the file to get thumbnail | String | getFileThumbnail | *fileType* | Either PNG of JPG | ThumbnailFileType | getFileThumbnail | *maxHeight* | Maximum height | Integer | getFileThumbnail | *maxWidth* | Maximum width | Integer | getFileThumbnail | *minHeight* | Minimum height | Integer | getFileThumbnail | *minWidth* | Minimum width | Integer | getFileVersions | *fileId* | The id of file | String | moveFile | *destinationFolderId* | The id of the destination folder | String | moveFile | *fileId* | The id of file to move | String | moveFile | *newName* | *Optional* The new name of moved file; if newName is null, the moved file has same name as the original. | String | promoteFileVersion | *fileId* | The id of file | String | promoteFileVersion | *version* | The version of file to promote; initial version of file has value of 0, second version of file is 1 and so on. | Integer | renameFile | *fileId* | The id of file to rename | String | renameFile | *newFileName* | The new name of file | String | updateFileInfo | *fileId* | The id of file to update | String | updateFileInfo | *info* | The updated information | Info | updateFileMetadata | *fileId* | The id of file to delete | String | updateFileMetadata | *metadata* | The new metadata values | Metadata | uploadFile | *check* | *Optional* If the file name is already used, call the uploadNewVersion instead. | Boolean | uploadFile | *content* | A stream containing contents of the file to upload | InputStream | uploadFile | *created* | *Optional* The content created date that will be given to the uploaded file | Date | uploadFile | *fileName* | The name to give the uploaded file | String | uploadFile | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadFile | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date | uploadFile | *parentFolderId* | The id of parent folder | String | uploadFile | *size* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *fileContent* | A stream containing contents of the file to upload | InputStream | uploadNewFileVersion | *fileId* | The id of file | String | uploadNewFileVersion | *fileSize* | *Optional* The size of the file's content used for monitoring the upload's progress | Long | uploadNewFileVersion | *listener* | *Optional* A listener for monitoring the upload's progress | ProgressListener | uploadNewFileVersion | *modified* | *Optional* The content modified date that will be given to the uploaded file | Date |=== In addition to the parameters above, the files API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: folders *Only producer is supported* The folders API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxFolder copyFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String folderName); com.box.sdk.BoxFolder createFolder(String parentFolderId, String[] path); com.box.sdk.BoxSharedLink createFolderSharedLink(String folderId, com.box.sdk.BoxSharedLink.Access access, java.util.Date unshareDate, com.box.sdk.BoxSharedLink.Permissions permissions); void deleteFolder(String folderId); com.box.sdk.BoxFolder getFolder(String[] path); com.box.sdk.BoxFolder.Info getFolderInfo(String folderId, String[] fields); java.util.Collection getFolderItems(String folderId, Long offset, Long limit, String[] fields); com.box.sdk.BoxFolder moveFolder(String folderId, String destinationFolderId, String newName); com.box.sdk.BoxFolder renameFolder(String folderId, String newFolderName); com.box.sdk.BoxFolder updateFolderInfo(String folderId, com.box.sdk.BoxFolder.Info info); ---- The folders API is defined in the syntax as follows: ---- box:folders/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *copyFolder* | copy | Copy folder to destination folder while optionally giving it a new name | *createFolder* | create | Create a folder specified by path from parent folder with given parentFolderId, creating intermediate directories as required | *createFolderSharedLink* | link | Create a shared link to folder | *deleteFolder* | delete | Delete folder | *getFolder* | folder | Return the Box folder referenced by path | *getFolderInfo* | info | Get folder information | *getFolderItems* | items | Returns a specific range of child items in folder and specifies which fields of each item to retrieve | *moveFolder* | move | Move folder to destination folder while optionally giving it a new name | *renameFolder* | rename | Rename folder giving it the name newName | *updateFolderInfo* | updateInfo | Update folder information |=== The folders API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | copyFolder | *destinationFolderId* | The id of the destination folder | String | copyFolder | *folderId* | The id of folder to copy | String | copyFolder | *newName* | *Optional* The new name for copied folder; if newName is null, the copied folder has same name as the original. | String | createFolder | *folderName* | The name of created folder | String | createFolder | *parentFolderId* | The id of parent folder | String | createFolder | *path* | Sequence of Box folder names from parent folder to returned folder | String[] | createFolderSharedLink | *access* | The access level of the shared link | Access | createFolderSharedLink | *folderId* | The id of folder to create shared link on | String | createFolderSharedLink | *permissions* | The permissions of the created link; if permissions is null then the created shared link is create with default permissions. | Permissions | createFolderSharedLink | *unshareDate* | The date and time at which time the created shared link will expire; if unsharedDate is null then a non-expiring link is created. | Date | deleteFolder | *folderId* | The id of folder to delete | String | getFolder | *path* | Sequence of Box folder names from root folder to returned folder | String[] | getFolderInfo | *fields* | *Optional* The information fields to retrieve; if null all information fields are retrieved. | String[] | getFolderInfo | *folderId* | The id of folder | String | getFolderItems | *fields* | *Optional* The item fields to retrieve for each child item; if null all item fields are retrieved. | String[] | getFolderItems | *folderId* | The id of folder | String | getFolderItems | *limit* | *Optional* The maximum number of children to retrieve after the offset; if null all child items are retrieved. | Long | getFolderItems | *offset* | *Optional* The index of first child item to retrieve; if null all child items are retrieved. | Long | moveFolder | *destinationFolderId* | The id of the destination folder | String | moveFolder | *folderId* | The id of folder to move | String | moveFolder | *newName* | *Optional* The new name of moved folder; if newName is null, the moved folder has same name as the original. | String | renameFolder | *folderId* | The id of folder to rename | String | renameFolder | *newFolderName* | The new name of folder | String | updateFolderInfo | *folderId* | The id of folder to update | String | updateFolderInfo | *info* | The updated information | Info |=== In addition to the parameters above, the folders API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: groups *Only producer is supported* The groups API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxGroupMembership addGroupMembership(String groupId, String userId, com.box.sdk.BoxGroupMembership.Role role); com.box.sdk.BoxGroup createGroup(String name, String provenance, String externalSyncIdentifier, String description, String invitabilityLevel, String memberViewabilityLevel); void deleteGroup(String groupId); void deleteGroupMembership(String groupMembershipId); com.box.sdk.BoxGroup.Info getGroupInfo(String groupId); com.box.sdk.BoxGroupMembership.Info getGroupMembershipInfo(String groupMembershipId); java.util.Collection getGroupMemberships(String groupId); com.box.sdk.BoxGroup updateGroupInfo(String groupId, com.box.sdk.BoxGroup.Info groupInfo); com.box.sdk.BoxGroupMembership updateGroupMembershipInfo(String groupMembershipId, com.box.sdk.BoxGroupMembership.Info info); ---- The groups API is defined in the syntax as follows: ---- box:groups/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addGroupMembership* | addMembership | Add a member to group with the specified role | *createGroup* | create | Create a new group with a specified name and optional additional parameters | *deleteGroup* | delete | Delete group | *deleteGroupMembership* | deleteMembership | Delete group membership | *getGroupInfo* | info | Get group information | *getGroupMembershipInfo* | membershipInfo | Get group membership information | *getGroupMemberships* | memberships | Get information about all of the group memberships for this group | *updateGroupInfo* | | Update group information | *updateGroupMembershipInfo* | updateMembershipInfo | Update group membership information |=== The groups API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addGroupMembership | *groupId* | The id of group | String | addGroupMembership | *role* | *Optional* The role of the user in this group. Can be null to assign the default role. | Role | addGroupMembership | *userId* | The id of user to be added to group | String | createGroup | *description* | *Optional* The description of the new group | String | createGroup | *externalSyncIdentifier* | *Optional* The external_sync_identifier of the new group | String | createGroup | *invitabilityLevel* | *Optional* The invitibility_level of the new group | String | createGroup | *memberViewabilityLevel* | *Optional* The member_viewability_level of the new group | String | createGroup | *name* | The name of the new group | String | createGroup | *provenance* | *Optional* The provenance of the new group | String | deleteGroup | *groupId* | The id of group to delete | String | deleteGroupMembership | *groupMembershipId* | The id of group membership to delete | String | getGroupInfo | *groupId* | The id of group | String | getGroupMembershipInfo | *groupMembershipId* | The id of group membership | String | getGroupMemberships | *groupId* | The id of group | String | updateGroupInfo | *groupId* | The id of group to update | String | updateGroupInfo | *groupInfo* | The updated information | Info | updateGroupMembershipInfo | *groupMembershipId* | The id of group membership to update | String | updateGroupMembershipInfo | *info* | The updated information | Info |=== In addition to the parameters above, the groups API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: search *Only producer is supported* The search API has 1 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- java.util.Collection searchFolder(String folderId, String query); ---- The search API is defined in the syntax as follows: ---- box:search/methodName?[parameters] ---- The 1 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *searchFolder* | search | Search folder and all descendant folders using the given query |=== The search API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | searchFolder | *folderId* | The id of folder searched | String | searchFolder | *query* | The search query | String |=== In addition to the parameters above, the search API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: tasks *Only producer is supported* The tasks API has 9 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.BoxTask addAssignmentToTask(String taskId, com.box.sdk.BoxUser assignTo); com.box.sdk.BoxTask addFileTask(String fileId, com.box.sdk.BoxTask.Action action, java.util.Date dueAt, String message); void deleteTask(String taskId); void deleteTaskAssignment(String taskAssignmentId); java.util.List getFileTasks(String fileId); com.box.sdk.BoxTaskAssignment.Info getTaskAssignmentInfo(String taskAssignmentId); java.util.List getTaskAssignments(String taskId); com.box.sdk.BoxTask.Info getTaskInfo(String taskId); com.box.sdk.BoxTask updateTaskInfo(String taskId, com.box.sdk.BoxTask.Info info); ---- The tasks API is defined in the syntax as follows: ---- box:tasks/methodName?[parameters] ---- The 9 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addAssignmentToTask* | addAssignment | Add assignment for task | *addFileTask* | add | Add task to file | *deleteTask* | delete | Delete task | *deleteTaskAssignment* | deleteAssignment | Delete task assignment | *getFileTasks* | tasks | Get a list of any tasks on file | *getTaskAssignmentInfo* | assignmentInfo | Get task assignment information | *getTaskAssignments* | assignments | Get a list of any assignments for task | *getTaskInfo* | info | Get task information | *updateTaskInfo* | updateInfo | Update task information |=== The tasks API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addAssignmentToTask | *assignTo* | The user to assign to task | BoxUser | addAssignmentToTask | *taskId* | The id of task to add assignment for | String | addFileTask | *action* | The action the task assignee will be prompted to do | Action | addFileTask | *dueAt* | The day at which this task is due | Date | addFileTask | *fileId* | The id of file to add task to | String | addFileTask | *message* | *Optional* An optional message to include with the task | String | deleteTask | *taskId* | The id of task to delete | String | deleteTaskAssignment | *taskAssignmentId* | The id of task assignment to delete | String | getFileTasks | *fileId* | The id of file | String | getTaskAssignmentInfo | *taskAssignmentId* | The id of task assignment | String | getTaskAssignments | *taskId* | The id of task | String | getTaskInfo | *taskId* | The id of task | String | updateTaskInfo | *info* | The updated information | Info | updateTaskInfo | *taskId* | The id of task | String |=== In addition to the parameters above, the tasks API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. ==== API: users *Only producer is supported* The users API has 10 method(s) which is represented by the following method signatures (an API method may have multiple signatures due to overloading): [source,java] ---- com.box.sdk.EmailAlias addUserEmailAlias(String userId, String email); com.box.sdk.BoxUser createAppUser(String name, com.box.sdk.CreateUserParams params); com.box.sdk.BoxUser createEnterpriseUser(String login, String name, com.box.sdk.CreateUserParams params); void deleteUser(String userId, boolean notifyUser, boolean force); void deleteUserEmailAlias(String userId, String emailAliasId); java.util.List getAllEnterpriseOrExternalUsers(String filterTerm, String[] fields); java.util.Collection getUserEmailAlias(String userId); com.box.sdk.BoxUser.Info getUserInfo(String userId); com.box.sdk.BoxFolder.Info moveFolderToUser(String userId, String sourceUserId); com.box.sdk.BoxUser updateUserInfo(String userId, com.box.sdk.BoxUser.Info info); ---- The users API is defined in the syntax as follows: ---- box:users/methodName?[parameters] ---- The 10 method(s) is listed in the table below. (API methods can have a shorthand alias name which can be used in the syntax instead of the name) [width=""100%"",cols=""2,2,6"",options=""header""] |=== | Method | Alias | Description | *addUserEmailAlias* | addEmailAlias | Add a new email alias to user's account | *createAppUser* | create | Provision a new app user in an enterprise with additional user information using Box Developer Edition | *createEnterpriseUser* | create | Provision a new user in an enterprise with additional user information | *deleteUser* | delete | Delete user from an enterprise account | *deleteUserEmailAlias* | deleteEmailAlias | Delete an email alias from user's account | *getAllEnterpriseOrExternalUsers* | users | Get any managed users that match the filter term as well as any external users that match the filter term | *getUserEmailAlias* | emailAlias | Get a collection of all the email aliases for user | *getUserInfo* | info | Get user information | *moveFolderToUser* | | Move root folder for specified user to current user | *updateUserInfo* | updateInfo | Update user information |=== The users API method(s) has the following set of parameters listed in the table below: [width=""100%"",cols=""2,2,4,2"",options=""header""] |=== | Method | Parameter | Description | Type | addUserEmailAlias | *email* | The email address to add as an alias | String | addUserEmailAlias | *userId* | The id of user | String | createAppUser | *name* | The name of the user | String | createAppUser | *params* | *Optional* Additional user information | CreateUserParams | createEnterpriseUser | *login* | The email address the user will use to login | String | createEnterpriseUser | *name* | The name of the user | String | createEnterpriseUser | *params* | *Optional* Additional user information | CreateUserParams | deleteUser | *force* | Whether or not this user should be deleted even if they still own files | Boolean | deleteUser | *notifyUser* | Whether or not to send an email notification to the user that their account has been deleted | Boolean | deleteUser | *userId* | The id of user to delete | String | deleteUserEmailAlias | *emailAliasId* | The id of the email alias to delete | String | deleteUserEmailAlias | *userId* | The id of user | String | getAllEnterpriseOrExternalUsers | *fields* | *Optional* The fields to retrieve. Leave this out for the standard fields. | String[] | getAllEnterpriseOrExternalUsers | *filterTerm* | *Optional* The filter term to lookup users by (login for external, login or name for managed); if null all managed users are returned. | String | getUserEmailAlias | *userId* | The id of user | String | getUserInfo | *userId* | The id of user | String | moveFolderToUser | *sourceUserId* | The user id of the user whose files will be the source for this operation | String | moveFolderToUser | *userId* | The id of user | String | updateUserInfo | *info* | The updated information | Info | updateUserInfo | *userId* | The id of user to update | String |=== In addition to the parameters above, the users API can also use from the 19 endpoint query option which is listed in the _Query Parameters_ section. Any of the parameters can be provided in either the endpoint URI, or dynamically in a message header. The message header name must be of the format `CamelBox.parameter`. The `inBody` parameter overrides message header, i.e. the endpoint parameter `inBody=myParameterNameHere` would override a `CamelBox.myParameterNameHere` header. // endpoint options: END == Samples The following route uploads new files to the user's root folder: [source,java] ---- from(""file:..."") .to(""box://files/upload/inBody=fileUploadRequest""); ---- The following route polls user's account for updates: [source,java] ---- from(""box://events/listen?startingPosition=-1"") .to(""bean:blah""); ---- The following route uses a producer with dynamic header options. The *fileId* property has the Box file id and the *output* property has the output stream of the file contents, so they are assigned to the *CamelBox.fileId* header and *CamelBox.output* header respectively as follows: [source,java] ---- from(""direct:foo"") .setHeader(""CamelBox.fileId"", header(""fileId"")) .setHeader(""CamelBox.output"", header(""output"")) .to(""box://files/download"") .to(""file://...""); ---- === More information See more details at the Box API reference: https://developer.box.com/reference include::camel-spring-boot::page$box-starter.adoc[] ",12292,True,2582.458569899793,median "#include #include #include #include #include #include #include #define MY_EPS 1e-6 namespace hector_ground_contact_estimator { GroundContactEstimator::GroundContactEstimator() { } GroundContactEstimator::GroundContactEstimator(pcl::PointCloud cloud) { world_pcl_ptr= cloud.makeShared(); world_kdtree.setInputCloud(world_pcl_ptr); ros::param::param(""/robot_length"", robot_length, 0.55); ros::param::param(""/robot_width"", robot_width, 0.40); ros::param::param(""/offset_CM/x"", offset_CM[0], 0.0); ros::param::param(""/offset_CM/y"", offset_CM[1], 0.0); ros::param::param(""/offset_CM/z"", offset_CM[2], 0.12); ros::param::param(""/minimum_distance"", minimum_distance, 0.08); ros::param::param(""/invalid_rating"", invalid_rating, 0.20); ros::param::param(""/invalid_angle"", invalid_angle, 65); ros::param::param(""/delta_for_contact"", delta_for_contact, 0.05); ros::param::param(""/first_SP_around_mid"", first_SP_around_mid, true); ros::param::param(""/tip_over"", tip_over, true); ros::param::param(""/check_each_axis"", check_each_axis, false); ros::param::param(""/distance_smoothing"", distance_smoothing, true); ros::param::param(""/angle_smoothing"", angle_smoothing, true); ros::param::param(""/smooth_max_angle"", smooth_max_angle, 20.0); ros::param::param(""/smooth_max_distance"", smooth_max_distance, 0.045); ros::param::param(""/draw_convex_hull_first_polygon"", draw_convex_hull_first_polygon, true); ros::param::param(""/draw_convex_hull_ground_points"", draw_convex_hull_ground_points, true); ros::param::param(""/draw_convex_hull_iterative"", draw_convex_hull_iterative, true); ros::param::param(""/draw_convex_hull_iterative_ground_points"", draw_convex_hull_iterative_ground_points, true); } GroundContactEstimator::~GroundContactEstimator() { } void GroundContactEstimator::updateCloud(pcl::PointCloud cloud) { world_pcl_ptr= cloud.makeShared(); } // returns a value how similar vectors are to each other. close to 0 is very similar, 0.50 would not be similar anymore. float vectorSimilarity(pcl::PointXYZ support_point_1, pcl::PointXYZ support_point_2, pcl::PointXYZ hull_p1, pcl::PointXYZ hull_p2){ // check angle similarity float angle1 = angleBetween(subtractPointsEigen(support_point_1, support_point_2), subtractPointsEigen(hull_p2, hull_p1)); float angle2 = angleBetween(subtractPointsEigen(support_point_1, support_point_2), subtractPointsEigen(hull_p1, hull_p2)); float angle = fmin(angle1, angle2); //[degree] //check distance similarity evaluated by point distances float distance1 = (distanceXYZ(support_point_1, hull_p1) + distanceXYZ(support_point_2, hull_p2)); float distance2 = (distanceXYZ(support_point_1, hull_p2) + distanceXYZ(support_point_2, hull_p1)); float distance = fmin(distance1, distance2); //[m] // 1 degree is same value as 2 centimeter offset // example 10 centimeters offset (eg 2 times 5cm) and 7 degree -> value will be 0.20 + 0.07 = 0.27 return distance*20.0 + angle/100.0; } // return the value of the least stable axis for the robot standing on flat ground float GroundContactEstimator::flatGroundPositionRating() { pcl::PointXYZ projected_robot_p0 = pcl::PointXYZ(0.0, 0.0, 0.0); pcl::PointXYZ projected_robot_p1 = pcl::PointXYZ(robot_length, 0.0, 0.0); pcl::PointXYZ projected_robot_p2 = pcl::PointXYZ(robot_length, robot_width, 0.0); pcl::PointXYZ projected_robot_p3 = pcl::PointXYZ(0.0, robot_width, 0.0); pcl::PointXYZ projected_robot_center = pcl::PointXYZ(robot_length / 2.0, robot_width / 2.0, 0.0); pcl::PointXYZ center_mass = addPointVector(projected_robot_center, offset_CM); std::vector projected_robot_hull; projected_robot_hull.push_back(projected_robot_p0); projected_robot_hull.push_back(projected_robot_p1); projected_robot_hull.push_back(projected_robot_p2); projected_robot_hull.push_back(projected_robot_p3); projected_robot_hull.push_back(projected_robot_p0); std::vector pos_rating = computeForceAngleStabilityMetric(center_mass, projected_robot_hull); std::vector::iterator it_min_pos_rating = std::min_element(pos_rating.begin(), pos_rating.end()); return *it_min_pos_rating; } //As proposed in ""Modeling the manipulator and flipper pose effects on tip over stability of a tracked mobile manipulator"" by Chioniso Dube // a low values indicated an instable condition, a high number inidicates a stable condition, 0 is the physical tip over value std::vector GroundContactEstimator::computeForceAngleStabilityMetric(const pcl::PointXYZ& center_of_mass_pcl, std::vector& convex_hull_points_pcl) { const Eigen::Vector3f center_of_mass = Eigen::Vector3f(center_of_mass_pcl.x,center_of_mass_pcl.y,center_of_mass_pcl.z); std::vector p; Eigen::Vector3f f_r= Eigen::Vector3f(0.0,0.0,-10.0); for(unsigned int i=0; i res; for(unsigned int i=0; i<(p.size()-1);++i) { Eigen::Vector3f p_i1; if(p.size()==1) p_i1 = p.at(0); else p_i1 = p.at(i+1); const Eigen::Vector3f ai=(p_i1-p.at(i)).normalized(); const Eigen::Matrix3f ident_mat =Eigen::Matrix3f::Identity(); const Eigen::Vector3f li=(ident_mat-ai*ai.transpose())*(p_i1-center_of_mass); const Eigen::Vector3f fi=(ident_mat-ai*ai.transpose())*f_r; const Eigen::Vector3f li_norm=li.normalized(); const Eigen::Vector3f fi_norm=fi.normalized(); const Eigen::Vector3f di= (-li)+(li.dot(fi_norm))*fi_norm; const float theta_i=acos(li_norm.dot(fi_norm)); const float sigma_i=((fi_norm.cross(li_norm)).dot(ai))?1.0:-1.0 ; const float beta=sigma_i*theta_i*di.norm()*f_r.norm(); res.push_back(beta); } return res; } // evaluates the second or third point of the supporting plane // if false is returned, there could not be a point found. bool GroundContactEstimator::findSupportPoint(const pcl::PointXYZ& tip_over_axis_point, const pcl::PointXYZ& tip_over_axis_vector, const pcl::PointCloud& pointcloud_robot, const pcl::PointXYZ& tip_over_direction, pcl::PointXYZ& support_point) { pcl::PointCloud cloud_projected; cloud_projected.resize(pointcloud_robot.size()); for(unsigned int i=0; i 180.0) ROS_ERROR(""[Terrain_model] angle>180 = %f"", angle); if (angle > 90.0) angle = 180.0-angle; // which side to the axis pcl::PointXYZ ps=pcl::PointXYZ(pointcloud_robot.at(i).x, pointcloud_robot.at(i).y, pointcloud_robot.at(i).z); const int side = sign(ccw(tip_over_axis_point, addPointVector(tip_over_axis_point, tip_over_axis_vector), ps)); if (angle < min_angle && side == orientation_to_axis) { pcl::PointXYZ current = pcl::PointXYZ(pointcloud_robot.at(i).x,pointcloud_robot.at(i).y,pointcloud_robot.at(i).z); if (distancePointStraight(tip_over_axis_point, tip_over_axis_vector, current) > minimum_distance) { min_angle=angle; min_angle_idx=i; } } else { //ROS_INFO(""find point angle %f minangle %f side b %b side %i ccw %i"", angle, min_angle,(side == directionccw),side,ccw ); } } // IF NO POINT COULD BE FOUND if (min_angle_idx == -1){ return false; } support_point=pcl::PointXYZ(pointcloud_robot.at(min_angle_idx).x,pointcloud_robot.at(min_angle_idx).y,pointcloud_robot.at(min_angle_idx).z); return true; } /* builds the convex hull with the given supportpoints */ std::vector GroundContactEstimator:: buildConvexHull(const pcl::PointCloud::Ptr cloud_positionRating, const pcl::PointXYZ& check_pos, const pcl::PointXYZ& support_point_1, const pcl::PointXYZ& support_point_2, const pcl::PointXYZ& support_point_3, const bool iterative, // if this is true, points on one side of supp1, supp2 will not be considerred pcl::PointCloud::Ptr ground_contact_points) // empty before call { const pcl::PointXYZ support_plane_normal= crossProduct(pcl::PointXYZ(support_point_1.x-support_point_2.x,support_point_1.y-support_point_2.y,support_point_1.z-support_point_2.z), pcl::PointXYZ(support_point_1.x-support_point_3.x,support_point_1.y-support_point_3.y,support_point_1.z-support_point_3.z)); //Find ground contact points for (unsigned int i = 0; i < cloud_positionRating->size(); i++) { pcl::PointXYZI& p = cloud_positionRating->at(i); const float dist = planeDistance(pcl::PointXYZ(p.x,p.y,p.z),support_plane_normal,support_point_1); if(fabs(dist) < delta_for_contact) { if (iterative == false){ ground_contact_points->push_back(pcl::PointXYZ(p.x,p.y,p.z)); } else { pcl::PointXYZ pointXYZ = pcl::PointXYZ(p.x, p.y, p.z); // only add points on the right side of the supporting points 1 and 2 if (sign(ccw(support_point_1, support_point_2, support_point_3)) == sign(ccw(support_point_1, support_point_2, pointXYZ)) || ccw(support_point_1, support_point_2, pointXYZ) == 0 //|| pointsEqual(support_point_1, pointXYZ, 0.0002)// should not be neccessary but due to floating numbers it is //|| pointsEqual(support_point_2, pointXYZ, 0.0002) ) { ground_contact_points->push_back(pointXYZ); } } } p.intensity=p.z; } // convex hull build here // first point is also last point std::vector convex_hull_points; pcl::PointCloud::Ptr cloud_hull (new pcl::PointCloud); pcl::ConvexHull chull; chull.setInputCloud(ground_contact_points); chull.setDimension(2); chull.reconstruct(*cloud_hull); for(unsigned int i = 0; ipoints.size(); ++i) { convex_hull_points.push_back(cloud_hull->at(i)); } convex_hull_points.push_back(cloud_hull->at(0)); //for consistency with previous data structure if (distance_smoothing){ //ROS_INFO(""distance smoothing""); // distance smoothing for (unsigned int i = 0; i < convex_hull_points.size() - 1; i = i){ // if (convex_hull_points.size() <= 4) break; // area needs to have 3 points if (i < convex_hull_points.size()-2){ if (distanceXYZ(convex_hull_points.at(i), convex_hull_points.at(i+1)) < smooth_max_distance){ // keep the point which is further away from the others (try not make area smaller) unsigned int offset = 0; float dist_p_i = 0.0; float dist_p_next = 0.0; for (unsigned int k = 0; k < convex_hull_points.size() - 1; k++){ dist_p_i = dist_p_i + pow(distanceXYZ(convex_hull_points.at(i), convex_hull_points.at(k)), 2); dist_p_next = dist_p_next + pow(distanceXYZ(convex_hull_points.at(i+1), convex_hull_points.at(k)),2); } /*if (distanceXYZ(convex_hull_points.at(i), check_pos) > distanceXYZ(convex_hull_points.at(i+1), check_pos)){ offset = 1; }*/ if (dist_p_i > dist_p_next){ offset = 1; } if (i == 0){ // do not delete first point offset = 1; } convex_hull_points.erase(convex_hull_points.begin()+(i+offset)); } else { i++; } } // same thing for last (= first) point else { if (distanceXYZ(convex_hull_points.at(i), convex_hull_points.at(i+1)) < smooth_max_distance){ // a point must be deleted float dist_p_i = 0.0; float dist_p_next = 0.0; for (unsigned int k = 0; k < convex_hull_points.size() - 1; k++){ dist_p_i = dist_p_i + pow(distanceXYZ(convex_hull_points.at(i), convex_hull_points.at(k)),2); dist_p_next = dist_p_next + pow(distanceXYZ(convex_hull_points.at(i+1), convex_hull_points.at(k)),2); } //if (dist_p_i < dist_p_next){ // delete the second last point not the last /*if (distanceXYZ(convex_hull_points.at(i), check_pos) < distanceXYZ(convex_hull_points.at(i+1), check_pos)){*/ // second last must be removed convex_hull_points.erase(convex_hull_points.begin()+(i)); //} /*else{ // last = first must be removed convex_hull_points.erase(convex_hull_points.begin()+(i+1)); convex_hull_points.at(0) = convex_hull_points.at(i); // ERROR: another point (first one must be pusheback to have enough points }*/ } break; // needed because loop is doing i = i // could also be i++ } } //ROS_INFO(""end distance smoothing""); } //ROS_INFO(""convex_hull_points.size = %i after distance smoothing, this should at least be 4 to have 3 points which is a valid triangle as area."", convex_hull_points.size()); /* for (unsigned int i = 0; i < convex_hull_points.size(); i++){ pcl::PointXYZ p = convex_hull_points.at(i); ROS_INFO(""P%i x = %f, y = %f, z = %f"", i, p.x, p.y, p.z); }*/ // angle smoothing if (angle_smoothing){ //ROS_INFO(""angle smoothing""); for (unsigned int i = 0; i < convex_hull_points.size() - 1; i = i){ // if (convex_hull_points.size() <= 4) break; // area needs to have 3 points if (i < convex_hull_points.size()-2){ Eigen::Vector3f direction1 = subtractPointsEigen(convex_hull_points.at(i + 1),convex_hull_points.at(i)); Eigen::Vector3f direction2 = subtractPointsEigen(convex_hull_points.at(i + 2),convex_hull_points.at(i+1)); float angle = angleBetween(direction1, direction2); // delete the point if angle is very low if (angle < smooth_max_angle){ convex_hull_points.erase(convex_hull_points.begin()+(i+1)); } else { ++i; } } // same thing for last (= first) point else { Eigen::Vector3f directionlast = subtractPointsEigen(convex_hull_points.at(i + 1),convex_hull_points.at(i)); Eigen::Vector3f directionfirst = subtractPointsEigen(convex_hull_points.at(1),convex_hull_points.at(0)); float angle = angleBetween(directionlast, directionfirst); if (angle < smooth_max_angle){ //delete last ( = first) point convex_hull_points.erase(convex_hull_points.begin()+(i+1)); convex_hull_points.at(0) = convex_hull_points.at(i); } break; // needed because loop is doing i = i // could also be i++ } } //ROS_INFO(""end angle smoothing""); } //ROS_INFO(""convex_hull_points.size = %i after angle smoothing, this should at least be 4 to have 3 points which is a valid triangle as area."", convex_hull_points.size()); /*for (unsigned int i = 0; i < convex_hull_points.size(); i++){ pcl::PointXYZ p = convex_hull_points.at(i); ROS_INFO(""P%i x = %f, y = %f, z = %f"", i, p.x, p.y, p.z); }*/ return convex_hull_points; } void GroundContactEstimator::computeRobotPosition(const pcl::PointXYZ support_point_1, const pcl::PointXYZ support_point_2, const pcl::PointXYZ support_point_3, const pcl::PointXYZ p0, const pcl::PointXYZ p1, const pcl::PointXYZ p2, const pcl::PointXYZ p3, const Eigen::Vector3f& offset_CM, pcl::PointXYZ& normal, pcl::PointXYZ& robot_point_0, pcl::PointXYZ& robot_point_1, pcl::PointXYZ& robot_point_2, pcl::PointXYZ& robot_point_3, pcl::PointXYZ& robot_point_mid, pcl::PointXYZ& robot_center_of_mass) { normal= crossProduct(pcl::PointXYZ(support_point_1.x-support_point_2.x,support_point_1.y-support_point_2.y,support_point_1.z-support_point_2.z), pcl::PointXYZ(support_point_1.x-support_point_3.x,support_point_1.y-support_point_3.y,support_point_1.z-support_point_3.z)); if (normal.z < 0){ normal.x = -normal.x; normal.y = -normal.y; normal.z = -normal.z; } float z0=(-(p0.x-support_point_2.x)*normal.x-(p0.y-support_point_2.y)*normal.y)/normal.z +support_point_2.z; float z1=(-(p1.x-support_point_2.x)*normal.x-(p1.y-support_point_2.y)*normal.y)/normal.z +support_point_2.z; float z2=(-(p2.x-support_point_2.x)*normal.x-(p2.y-support_point_2.y)*normal.y)/normal.z +support_point_2.z; float z3=(-(p3.x-support_point_2.x)*normal.x-(p3.y-support_point_2.y)*normal.y)/normal.z +support_point_2.z; robot_point_0 = pcl::PointXYZ(p0.x, p0.y, z0); robot_point_1 = pcl::PointXYZ(p1.x, p1.y, z1); robot_point_2 = pcl::PointXYZ(p2.x, p2.y, z2); robot_point_3 = pcl::PointXYZ(p3.x, p3.y, z3); robot_point_mid = addPointVector(robot_point_0, addPointVector(robot_point_1, addPointVector(robot_point_2, robot_point_3))); robot_point_mid.x = robot_point_mid.x / 4.0; robot_point_mid.y = robot_point_mid.y / 4.0; robot_point_mid.z = robot_point_mid.z / 4.0; // compute center_of_mass Eigen::Vector3f normal_vector = Eigen::Vector3f(normal.x, normal.y, normal.z); normal_vector.normalize(); normal.x = normal_vector.x(); normal.y = normal_vector.y(); normal.z = normal_vector.z(); // ERROR ? ACHTUNG EVENTUELL FLASCH RUM, DA ICH NICHT WEISS WIE RUM DER ROBOTER STEHT // EGAL, wenn offset_CM nur Werte in z hat // -------------------------------------------------------------------------------------------- // bezg p_pro 1 / 0 robot_center_of_mass = computeCenterOfMass(robot_point_0, robot_point_1, normal_vector, robot_point_mid, offset_CM); } pcl::PointXYZ GroundContactEstimator::computeCenterOfMass(const pcl::PointXYZ &p1_left, const pcl::PointXYZ &p2_left, const Eigen::Vector3f &normal, const pcl::PointXYZ &mid, const Eigen::Vector3f &offset){ Eigen::Vector3f axis_left = Eigen::Vector3f(p2_left.x - p1_left.x, p2_left.y - p1_left.y, p2_left.z - p1_left.z); axis_left.normalize(); Eigen::Vector3f my_normal = normal; my_normal.normalize(); float CMx = mid.x + (offset.z() * my_normal.x()) + (axis_left.x() * offset.x()); float CMy = mid.y + (offset.z() * my_normal.y()) + (axis_left.y() * offset.x()); float CMz = mid.z + (offset.z() * my_normal.z()) + (axis_left.z() * offset.x()); pcl::PointXYZ center_of_mass = pcl::PointXYZ(CMx, CMy, CMz); return center_of_mass; } void GroundContactEstimator::computeRobotCornerPoints(const pcl::PointXYZ& check_pos, const float orientation, pcl::PointXYZ& p0, pcl::PointXYZ& p1, pcl::PointXYZ& p2, pcl::PointXYZ& p3) { p0 = pcl::PointXYZ(+ 0.5*robot_length, + 0.5*robot_width, 0); p0 = rotatePointZ(p0, orientation); p0 = addPointVector(p0, check_pos); p1 = pcl::PointXYZ(- 0.5*robot_length, + 0.5*robot_width, 0); p1 = rotatePointZ(p1, orientation); p1 = addPointVector(p1, check_pos); p2 = pcl::PointXYZ(- 0.5*robot_length, - 0.5*robot_width, 0); p2 = rotatePointZ(p2, orientation); p2 = addPointVector(p2, check_pos); p3 = pcl::PointXYZ(+ 0.5*robot_length, - 0.5*robot_width, 0); p3 = rotatePointZ(p3, orientation); p3 = addPointVector(p3, check_pos); } bool GroundContactEstimator::fillRobotPointcloud(const pcl::PointXYZ& p0, const pcl::PointXYZ& p1, const pcl::PointXYZ& p2, const pcl::PointXYZ& p3, unsigned int& highest_Point_idx){ robot_pcl.reset(new pcl::PointCloud()); unsigned int n_counter=0; std::vector projected_robot_hull; projected_robot_hull.push_back(p0); projected_robot_hull.push_back(p1); projected_robot_hull.push_back(p2); projected_robot_hull.push_back(p3); bool hull_is_cw= (ccw(p0,p1,p2)<0); bool not_empty = false; const pcl::PointXYZ center = pcl::PointXYZ(0.25*(p0.x+p1.x+p2.x+p3.x),0.25*(p0.y+p1.y+p2.y+p3.y),0.25*(p0.z+p1.z+p2.z+p3.z)); const float radius = distanceXY(p0, center); pcl::PointCloud::Ptr local_cloud (new pcl::PointCloud); std::vector pointIdxRadiusSearch; std::vector pointRadiusSquaredDistance; world_kdtree.radiusSearch(center, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance); for (size_t i = 0; i < pointIdxRadiusSearch.size (); ++i) local_cloud->push_back(world_pcl_ptr->points[pointIdxRadiusSearch[i]]); for (unsigned int i = 0; i < local_cloud->size(); i++) { const pcl::PointXYZ& pp= local_cloud->at(i); bool c0 = hull_is_cw ? (ccw(p0,p1,pp)<0) : (ccw(p0,p1,pp)>0); bool c1 = hull_is_cw ? (ccw(p1,p2,pp)<0) : (ccw(p1,p2,pp)>0); bool c2 = hull_is_cw ? (ccw(p2,p3,pp)<0) : (ccw(p2,p3,pp)>0); bool c3 = hull_is_cw ? (ccw(p3,p0,pp)<0) : (ccw(p3,p0,pp)>0); if(c0 && c1 && c2 && c3) // point is in the area of the projected robot { pcl::PointXYZI p= pcl::PointXYZI(); p.x=pp.x; p.y=pp.y; p.z=pp.z; p.intensity=0.0; robot_pcl->push_back(p); if(n_counter==0) highest_Point_idx = 0; else if(p.z>robot_pcl->at(highest_Point_idx).z) highest_Point_idx=n_counter; ++n_counter; not_empty = true; } } return not_empty; } bool GroundContactEstimator::fillRobotPointcloud(const pcl::PointXYZ& p0, const pcl::PointXYZ& p1, const pcl::PointXYZ& p2, const pcl::PointXYZ& p3, float& max_height){ robot_pcl.reset(new pcl::PointCloud()); unsigned int n_counter=0; std::vector projected_robot_hull; projected_robot_hull.push_back(p0); projected_robot_hull.push_back(p1); projected_robot_hull.push_back(p2); projected_robot_hull.push_back(p3); bool hull_is_cw= (ccw(p0,p1,p2)<0); bool not_empty = false; const pcl::PointXYZ center = pcl::PointXYZ(0.25*(p0.x+p1.x+p2.x+p3.x),0.25*(p0.y+p1.y+p2.y+p3.y),0.25*(p0.z+p1.z+p2.z+p3.z)); const float radius = distanceXY(p0, center); pcl::PointCloud::Ptr local_cloud (new pcl::PointCloud); std::vector pointIdxRadiusSearch; std::vector pointRadiusSquaredDistance; world_kdtree.radiusSearch(center, radius, pointIdxRadiusSearch, pointRadiusSquaredDistance); for (size_t i = 0; i < pointIdxRadiusSearch.size (); ++i) local_cloud->push_back(world_pcl_ptr->points[pointIdxRadiusSearch[i]]); for (unsigned int i = 0; i < local_cloud->size(); i++) { const pcl::PointXYZ& pp= world_pcl_ptr->at(i); max_height = pp.z; bool c0 = hull_is_cw ? (ccw(p0,p1,pp)<0) : (ccw(p0,p1,pp)>0); bool c1 = hull_is_cw ? (ccw(p1,p2,pp)<0) : (ccw(p1,p2,pp)>0); bool c2 = hull_is_cw ? (ccw(p2,p3,pp)<0) : (ccw(p2,p3,pp)>0); bool c3 = hull_is_cw ? (ccw(p3,p0,pp)<0) : (ccw(p3,p0,pp)>0); if(c0 && c1 && c2 && c3) // point is in the area of the projected robot { pcl::PointXYZI p= pcl::PointXYZI(); p.x=pp.x; p.y=pp.y; p.z=pp.z; p.intensity=0.0; robot_pcl->push_back(p); if(p.z>max_height) max_height=p.z; ++n_counter; not_empty = true; } } return not_empty; } // -------------------------------------------------------------------------------------------------// // -------------------------------------------------------------------------------------------------// //-------------------------------------COMPUTE POSITION RATING--------------------------------------// //--------------------------------------------------------------------------------------------------// // -------------------------------------------------------------------------------------------------// // orientation in radiants bool GroundContactEstimator::computePositionRating(const pcl::PointXYZ& flat_robot_center, const float orientation, pcl::PointXYZ& robot_point_center, pcl::PointXYZ& robot_point_0, pcl::PointXYZ& robot_point_1, pcl::PointXYZ& robot_point_2, pcl::PointXYZ& robot_point_3, float &position_rating, // after tipping over int &unstable_axis // of the first polygon , pcl::visualization::PCLVisualizer* viewer, int viewport_1, int viewport_2, int viewport_3, int viewport_4, bool use_visualization) { position_rating = 0.0; unstable_axis = 0; // Points at the edges of the robot (flat ground) pcl::PointXYZ p0, p1, p2, p3; // Edge Points computeRobotCornerPoints(flat_robot_center, orientation, p0,p1,p2,p3); unsigned int highest_Point_idx; if(!fillRobotPointcloud(p0, p1, p2, p3, highest_Point_idx)) { ROS_WARN(""[ground contact estimator] No points for ground contact estimation available. Planning into empty space?""); return false; } pcl::PointXYZI& p_max_height= robot_pcl->at(highest_Point_idx); int support_point_1_idx = -1; float min_dist=-1.0; //choose highest point (+-delta) that is closest to CoM for (unsigned int i = 0; i < robot_pcl->size(); i++) { pcl::PointXYZI& p = robot_pcl->at(i); if(fabs(p.z-p_max_height.z)<0.03) { float dist=sqrt((p.x-flat_robot_center.x)*(p.x-flat_robot_center.x)+(p.y-flat_robot_center.y)*(p.y-flat_robot_center.y)); if(min_dist<0.0 || distat(support_point_1_idx).x,robot_pcl->at(support_point_1_idx).y,robot_pcl->at(support_point_1_idx).z); // is used after while loop, but initiated in it. pcl::PointXYZ support_point_2; pcl::PointXYZ support_point_3; pcl::PointCloud::Ptr ground_contact_points(new pcl::PointCloud()); std::vector convex_hull_points; int counter = 0; while (true){ // find SupportPoints ; runs multiple times if unstable axis occur // find supp P 2 const pcl::PointXYZ tip_over_axis_point = support_point_1; pcl::PointXYZ tip_over_axis_direction = (crossProduct(pcl::PointXYZ(support_point_1.x-flat_robot_center.x,support_point_1.y-flat_robot_center.y,0),pcl::PointXYZ(0,0,1))); pcl::PointXYZ tip_over_direction; if (tip_over_axis_direction.x < MY_EPS && tip_over_axis_direction.y < MY_EPS && tip_over_axis_direction.z < MY_EPS) //todo think about appropriate solution { tip_over_axis_direction = pcl::PointXYZ(1.0, 0.0, 0.0); // this is random. tip_over_direction = pcl::PointXYZ(0.0, 1.0, 0.0); // 90� from vector } else { tip_over_direction = pcl::PointXYZ(flat_robot_center.x - support_point_1.x, flat_robot_center.y - support_point_1.y, 0); } bool point_evaluated = findSupportPoint(tip_over_axis_point, tip_over_axis_direction, *robot_pcl, tip_over_direction, support_point_2); if (!point_evaluated){ ROS_WARN(""[ground contact estimator] no support_point found 2..., counter = %i "", counter); //ROS_INFO(""checkpos x = %f, y 0 %f, supportPoint1 x = %f, y = %f"", check_pos.x, check_pos.y, support_point_1.x, support_point_1.y); return false; } //find third point const pcl::PointXYZ tip_over_axis_point_3 = support_point_1; const pcl::PointXYZ tip_over_axis_direction_3= subtractPoints(support_point_2, support_point_1); pcl::PointXYZ tip_over_direction_3 ; if(ccw(support_point_1,support_point_2,flat_robot_center)>0) tip_over_direction_3 = crossProduct(tip_over_axis_direction_3, pcl::PointXYZ(0,0,-1)); else tip_over_direction_3 = crossProduct(tip_over_axis_direction_3, pcl::PointXYZ(0,0,1)); point_evaluated = findSupportPoint(tip_over_axis_point_3, tip_over_axis_direction_3, (*robot_pcl), tip_over_direction_3, support_point_3); if (!point_evaluated){ ROS_WARN(""[terrain_model::compute_position_rating] no support_point found 3 before tip over.""); return false; } convex_hull_points = buildConvexHull(robot_pcl, flat_robot_center, support_point_1, support_point_2, support_point_3, false, ground_contact_points); if(use_visualization) // draw ground contact { if (draw_convex_hull_ground_points){ for (unsigned int j = 0; j < ground_contact_points->size(); ++j) { std::string name =""groundContactArea""+boost::lexical_cast(j+1000*counter); viewer->addSphere(ground_contact_points->at(j), 0.015,0.1 ,0.9,0.9, name, viewport_4); } } } // check if check_pos is in hull bool center_in_hull = true; //ROS_INFO(""Elements in convex hull %i"", convex_hull_points.size()); for (unsigned int i = 0; i < convex_hull_points.size() -1; ++i) { if (sign(ccw(convex_hull_points.at(i), convex_hull_points.at(i+1), flat_robot_center)) == 1) { center_in_hull = false; } } if (center_in_hull == true || first_SP_around_mid == false){ //ROS_INFO(""check in hull is true""); // The checkpos is in the convex hull. nothing needs to be changed break; // endwhile } counter++; // this can be expanded to an iterative process if iterations takes a higher value than 1. // Normally the check_pos is directly in the supporting polygon. // If not after the first iteration, it most likely is. int iterations = 15; if (counter > iterations){ ROS_WARN(""After %i iterations, the position to check is not in the supportiny polygon, computing rating continues."", iterations); break; } // checkpos is not in hull if (center_in_hull == false){ ROS_INFO(""check in hull is false""); // find closest point to checkpos float dist = distanceXY(convex_hull_points.at(0), flat_robot_center); int index_of_closest_point = 0; for (unsigned int i = 1; i < convex_hull_points.size(); ++i){ float dist_to_check = distanceXY(convex_hull_points.at(i), flat_robot_center); if (dist_to_check < dist){ dist = dist_to_check; index_of_closest_point = i; } } support_point_1 = convex_hull_points.at(index_of_closest_point); ground_contact_points->clear(); } } // endwhile - the supporting polygon is around the check_pos now. // check if the position is instable due to an invalid steap angle float angle_of_area = angleToGround(support_point_1, support_point_2, support_point_3); if (angle_of_area > invalid_angle){ ROS_INFO(""the angle of the position is over %f degree, computePositionRating returned false"", invalid_angle); return false; } //Compute points and normal of robot pcl::PointXYZ normal; pcl::PointXYZ center_of_mass; computeRobotPosition(support_point_1, support_point_2, support_point_3, p0, p1, p2, p3, offset_CM, normal, robot_point_0, robot_point_1, robot_point_2, robot_point_3, robot_point_center, center_of_mass); if(use_visualization) { // draw robot lines viewer->addLine(robot_point_0,robot_point_1,1.0,1.0,1.0,""f0""); viewer->addLine(robot_point_1,robot_point_2,1.0,1.0,1.0,""f1""); viewer->addLine(robot_point_2,robot_point_3,1.0,1.0,1.0,""f2""); viewer->addLine(robot_point_3,robot_point_0,1.0,1.0,1.0,""f3""); } //Compute Force Angle Stability Metric std::vector rating =computeForceAngleStabilityMetric(center_of_mass,convex_hull_points); if(use_visualization) { for (unsigned int i=0; i(i); const pcl::PointXYZ p1(convex_hull_points[i].x,convex_hull_points[i].y,convex_hull_points[i].z); const pcl::PointXYZ p2(convex_hull_points[i+1].x,convex_hull_points[i+1].y,convex_hull_points[i+1].z); //ROS_INFO(""RATING r: %f p1: %f %f %f p2:%f %f %f"", c,p1.x,p1.y,p1.z,p2.x,p2.y,p2.z); ROS_INFO(""Rating num %i = %f"", i, rating.at(i)); if (draw_convex_hull_first_polygon){ if(caddLine(p1,p2,1,0,c/invalid_rating,name); else viewer->addLine(p1,p2,0,(c-invalid_rating)/invalid_rating,(invalid_rating*2-c)/invalid_rating,name); // draw convex hull (points only) std::string namech =""convexhullstart""+boost::lexical_cast(i); viewer->addSphere(convex_hull_points[i], 0.025,0,1,0, namech,2 /*viewport*/); } } viewer->addSphere(convex_hull_points[0], 0.025,1,0,0, ""convexhullstart"", 2); viewer->addSphere(flat_robot_center, 0.05,1,0,0, ""checkPosition"", viewport_4); viewer->addSphere(robot_point_center, 0.05,0,1,0, ""proMidx"", viewport_4); viewer->addSphere(center_of_mass, 0.05,0,0,1, ""CM"", viewport_4); } //endif use_visualization for (unsigned int j = 0; j < rating.size(); j++){ if (rating.at(j) < invalid_rating){ unstable_axis += 1; } } // -------------------------------------------------------------------------// // -----------------------TIP OVER------------------------------------------// // -------------------------------------------------------------------------// if (tip_over){ // iterative checking if still fine after flipping over invalid axis for (unsigned int i = 0; i < rating.size(); i++){ if (check_each_axis || rating.at(i) < invalid_rating){ // instabil if(use_visualization) { ROS_INFO(""Roboter kippt ueber Kante mit rating %f"", rating.at(i)); } support_point_1 = convex_hull_points.at(i); support_point_2 = convex_hull_points.at(i+1); const pcl::PointXYZ tip_over_axis_vector= subtractPoints(support_point_2, support_point_1); pcl::PointXYZ tip_over_direction = crossProduct(tip_over_axis_vector, pcl::PointXYZ(0,0,1)); bool point_evaluated = findSupportPoint(support_point_1, tip_over_axis_vector, (*robot_pcl), tip_over_direction, support_point_3); if (!point_evaluated){ //ROS_INFO(""after tipping over: S1 and S2 lie at the aend of area, no S3 could be found""); continue; // supp1 and 2 lie at the end of the area, no suppP3 could be found, invalide state, break for-loop and return initial max rating value } float angle_of_area_it = angleToGround(support_point_1, support_point_2, support_point_3); if (angle_of_area_it > invalid_angle){ //ROS_INFO(""after tipping over, angle would be too high: %f"", angle_of_area_it); continue; } pcl::PointCloud::Ptr cloud_positionRating_iterative(new pcl::PointCloud()); std::vector convex_hull_points_it = buildConvexHull(robot_pcl, flat_robot_center, support_point_1, support_point_2, support_point_3, true, cloud_positionRating_iterative); pcl::PointXYZ normal_it; pcl::PointXYZ robot_point_0_it; pcl::PointXYZ robot_point_1_it; pcl::PointXYZ robot_point_2_it; pcl::PointXYZ robot_point_3_it; pcl::PointXYZ robot_point_mid_it; pcl::PointXYZ center_of_mass_it; computeRobotPosition(support_point_1, support_point_2, support_point_3, p0, p1, p2, p3, offset_CM, normal_it, robot_point_0_it, robot_point_1_it, robot_point_2_it, robot_point_3_it, robot_point_mid_it, center_of_mass_it); float min_value = 100.0; unsigned int iterator = 0; for (unsigned int k = 0; k< convex_hull_points_it.size()-1; k++){ float value = vectorSimilarity(support_point_1, support_point_2, convex_hull_points_it.at(k), convex_hull_points_it.at(k+1)); //ROS_INFO(""vector_similarity = %f"", value); if (value < min_value){ min_value = value; iterator = k; } }// TODO if (min_value == 100.0){ ROS_ERROR(""[flor_terrain_classifier / model] after tipping over no edge could be removed from the rating""); } // edge that must be removed is at position k in the vector convex_hull_points_it.erase(convex_hull_points_it.begin()+ convex_hull_points_it.size()-1); for (unsigned int l = 0; l < iterator+1; l++){ // shift first of list to last of list pcl::PointXYZ temp = convex_hull_points_it.at(0); convex_hull_points_it.erase(convex_hull_points_it.begin()+0); convex_hull_points_it.push_back(temp); } if(use_visualization) { // draw supporting points viewer->addSphere(support_point_1, 0.02,1,0,0, ""sp1it_tippedOver""+boost::lexical_cast(i), viewport_4); viewer->addSphere(support_point_2, 0.02,0,1,0, ""sp2it_tippedOver""+boost::lexical_cast(i), viewport_4); viewer->addSphere(support_point_3, 0.02,0,0,1, ""sp3it_tippedOver""+boost::lexical_cast(i), viewport_4); if (draw_convex_hull_iterative_ground_points){ for (unsigned int j = 0; j < cloud_positionRating_iterative->size(); ++j){ std::string name =""groundContactAreait""+boost::lexical_cast(j)+""tippedOver""+boost::lexical_cast(i); viewer->addSphere(cloud_positionRating_iterative->at(j), 0.01,0,1,1, name, viewport_4); } } // draw center if (i == 0){ viewer->addSphere(robot_point_mid_it, 0.04,0,1,0, ""proMidxit"", viewport_4); viewer->addSphere(center_of_mass_it, 0.04,0,0,1, ""CMit"", viewport_4); // draw normal const pcl::PointXYZ p_uff(addPointVector(robot_point_center, normal)); viewer->addLine(robot_point_center,p_uff,1.0,1.0,1.0,""fnormalit"",viewport_4); } } //Compute Force Angle Stability Metric std::vector rating_iterative =computeForceAngleStabilityMetric(center_of_mass_it,convex_hull_points_it); if(use_visualization) { for (unsigned int k=0; k(k)+""tippedOver""+boost::lexical_cast(i); const pcl::PointXYZ p1(convex_hull_points_it[k].x,convex_hull_points_it[k].y,convex_hull_points_it[k].z); const pcl::PointXYZ p2(convex_hull_points_it[k+1].x,convex_hull_points_it[k+1].y,convex_hull_points_it[k+1].z); ROS_INFO(""Rating %f"", rating_iterative.at(k)); if (draw_convex_hull_iterative){ if(caddLine(p1,p2,1,0,c/invalid_rating,name,viewport_4); else viewer->addLine(p1,p2,0,(c-invalid_rating)/invalid_rating,(invalid_rating*2-c)/invalid_rating,name,viewport_4); // draw convex hull (points only) std::string namech =""convexhullstart_it""+boost::lexical_cast(k)+""tippedOver""+boost::lexical_cast(i); viewer->addSphere(convex_hull_points_it[k+1], 0.015,0,1,0, namech,2 /*viewport*/); } } if (draw_convex_hull_iterative){ viewer->addSphere(convex_hull_points_it[0], 0.015,1,0,0, ""convexhullstart_it_tippedOver""+boost::lexical_cast(i), 2 /*viewport*/); } } float min_rating_iterative =*std::min_element(rating_iterative.begin(),rating_iterative.end()); // wenn gekippt und es hier stabiler ist, übernehme den schlechtesen Wert der gekippten Position an // der entsprechenden Stelle if (min_rating_iterative > rating.at(i)){ rating.at(i) = min_rating_iterative; } } } } // usetippingover end position_rating = *std::min_element(rating.begin(),rating.end()); // draw groundpoints if(use_visualization) { pcl::visualization::PointCloudColorHandlerGenericField intensity_distribution(robot_pcl, ""intensity""); // viewer->addPointCloud(robot_pcl,intensity_distribution, ""positionRating_cloud"", viewport); // viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, ""positionRating"" + std::string(""_edges""), viewport); ROS_INFO(""CPR done: position_rating = %f, unstable_axis = %i"", position_rating, unstable_axis); } return true; } void GroundContactEstimator::extractRobotPointcloud(const pcl::PointXYZ& flat_robot_center, const float orientation, float& max_height) { // Points at the edges of the robot (flat ground) pcl::PointXYZ p0, p1, p2, p3; // Edge Points computeRobotCornerPoints(flat_robot_center, orientation, p0,p1,p2,p3); fillRobotPointcloud(p0, p1, p2, p3, max_height); } void GroundContactEstimator::computeSupportPoint1(const pcl::PointXYZ& flat_robot_center,float max_height, pcl::PointXYZ& support_point_1) { float min_dist=-1.0; int support_point_1_idx = 0; for (unsigned int i = 0; i < robot_pcl->size(); i++) { pcl::PointXYZI& p = robot_pcl->at(i); if(((p.z-max_height)<0.03)&&((p.z-max_height)>-0.03)) { float dist = sqrt((p.x-flat_robot_center.x)*(p.x-flat_robot_center.x)+(p.y-flat_robot_center.y)*(p.y-flat_robot_center.y)); if(min_dist<0.0 || distat(support_point_1_idx).x,robot_pcl->at(support_point_1_idx).y,robot_pcl->at(support_point_1_idx).z); } bool GroundContactEstimator::computePositionRatingRefactoring(const pcl::PointXYZ& flat_robot_center, const float orientation, pcl::PointXYZ& robot_point_center, pcl::PointXYZ& robot_point_0, pcl::PointXYZ& robot_point_1, pcl::PointXYZ& robot_point_2, pcl::PointXYZ& robot_point_3, float &position_rating, // after tipping over int &unstable_axis // of the first polygon , pcl::visualization::PCLVisualizer* viewer, int viewport_1, int viewport_2, int viewport_3, int viewport_4, bool use_visualization) { position_rating = 0.0; unstable_axis = 0; float max_height; extractRobotPointcloud(flat_robot_center, orientation, max_height); if(robot_pcl->size()==0) { ROS_WARN(""[ground contact estimator] No points for ground contact estimation available. Planning into empty space?""); return false; } pcl::PointXYZ support_point_1; computeSupportPoint1(flat_robot_center, max_height, support_point_1); // is used after while loop, but initiated in it. pcl::PointXYZ support_point_2; pcl::PointXYZ support_point_3; pcl::PointCloud::Ptr ground_contact_points(new pcl::PointCloud()); std::vector convex_hull_points; int counter = 0; while (true){ // find SupportPoints ; runs multiple times if unstable axis occur // find supp P 2 const pcl::PointXYZ tip_over_axis_point = support_point_1; pcl::PointXYZ tip_over_axis_vector = (crossProduct(pcl::PointXYZ(support_point_1.x-flat_robot_center.x,support_point_1.y-flat_robot_center.y,0),pcl::PointXYZ(0,0,1))); pcl::PointXYZ tip_over_direction; if (tip_over_axis_vector.x < MY_EPS && tip_over_axis_vector.y < MY_EPS && tip_over_axis_vector.z < MY_EPS) //todo think about appropriate solution { tip_over_axis_vector = pcl::PointXYZ(1.0, 0.0, 0.0); // this is random. tip_over_direction = pcl::PointXYZ(0.0, 1.0, 0.0); // 90� from vector } else { tip_over_direction = pcl::PointXYZ(flat_robot_center.x - support_point_1.x, flat_robot_center.y - support_point_1.y, 0); } bool point_evaluated = findSupportPoint(tip_over_axis_point, tip_over_axis_vector, *robot_pcl, tip_over_direction, support_point_2); if (!point_evaluated){ ROS_WARN(""[ground contact estimator] no support_point found 2..., counter = %i "", counter); //ROS_INFO(""checkpos x = %f, y 0 %f, supportPoint1 x = %f, y = %f"", check_pos.x, check_pos.y, support_point_1.x, support_point_1.y); return false; } //find third point const pcl::PointXYZ tip_over_axis_point_3 = support_point_1; const pcl::PointXYZ tip_over_axis_vector_3= subtractPoints(support_point_2, support_point_1); pcl::PointXYZ tip_over_direction_3 ; if(ccw(support_point_1,support_point_2,flat_robot_center)>0) tip_over_direction_3 = crossProduct(tip_over_axis_vector_3, pcl::PointXYZ(0,0,-1)); else tip_over_direction_3 = crossProduct(tip_over_axis_vector_3, pcl::PointXYZ(0,0,1)); point_evaluated = findSupportPoint(tip_over_axis_point_3, tip_over_axis_vector_3, (*robot_pcl), tip_over_direction_3, support_point_3); if (!point_evaluated){ ROS_WARN(""[terrain_model::compute_position_rating] no support_point found 3 before tip over.""); return false; } convex_hull_points = buildConvexHull(robot_pcl, flat_robot_center, support_point_1, support_point_2, support_point_3, false, ground_contact_points); if(use_visualization) // draw ground contact { if (draw_convex_hull_ground_points){ for (unsigned int j = 0; j < ground_contact_points->size(); ++j) { std::string name =""groundContactArea""+boost::lexical_cast(j+1000*counter); viewer->addSphere(ground_contact_points->at(j), 0.015,0.1 ,0.9,0.9, name, viewport_4); } } } // check if check_pos is in hull bool center_in_hull = true; //ROS_INFO(""Elements in convex hull %i"", convex_hull_points.size()); for (unsigned int i = 0; i < convex_hull_points.size() -1; ++i) { if (sign(ccw(convex_hull_points.at(i), convex_hull_points.at(i+1), flat_robot_center)) == 1) { center_in_hull = false; } } if (center_in_hull == true || first_SP_around_mid == false){ //ROS_INFO(""check in hull is true""); // The checkpos is in the convex hull. nothing needs to be changed break; // endwhile } counter++; // this can be expanded to an iterative process if iterations takes a higher value than 1. // Normally the check_pos is directly in the supporting polygon. // If not after the first iteration, it most likely is. int iterations = 15; if (counter > iterations){ ROS_WARN(""After %i iterations, the position to check is not in the supportiny polygon, computing rating continues."", iterations); break; } // checkpos is not in hull if (center_in_hull == false){ ROS_INFO(""check in hull is false""); // find closest point to checkpos float dist = distanceXY(convex_hull_points.at(0), flat_robot_center); int index_of_closest_point = 0; for (unsigned int i = 1; i < convex_hull_points.size(); ++i){ float dist_to_check = distanceXY(convex_hull_points.at(i), flat_robot_center); if (dist_to_check < dist){ dist = dist_to_check; index_of_closest_point = i; } } support_point_1 = convex_hull_points.at(index_of_closest_point); ground_contact_points->clear(); } } // endwhile - the supporting polygon is around the check_pos now. // check if the position is instable due to an invalid steap angle float angle_of_area = angleToGround(support_point_1, support_point_2, support_point_3); if (angle_of_area > invalid_angle){ ROS_INFO(""the angle of the position is over %f degree, computePositionRating returned false"", invalid_angle); return false; } //Compute points and normal of robot pcl::PointXYZ normal; pcl::PointXYZ center_of_mass; /*computeRobotPosition(support_point_1, support_point_2, support_point_3, p0, p1, p2, p3, offset_CM, normal, robot_point_0, robot_point_1, robot_point_2, robot_point_3, robot_point_center, center_of_mass);*/ //TODO REMOVE COMMENT if(use_visualization) { // draw robot lines viewer->addLine(robot_point_0,robot_point_1,1.0,1.0,1.0,""f0""); viewer->addLine(robot_point_1,robot_point_2,1.0,1.0,1.0,""f1""); viewer->addLine(robot_point_2,robot_point_3,1.0,1.0,1.0,""f2""); viewer->addLine(robot_point_3,robot_point_0,1.0,1.0,1.0,""f3""); } //Compute Force Angle Stability Metric std::vector rating =computeForceAngleStabilityMetric(center_of_mass,convex_hull_points); if(use_visualization) { for (unsigned int i=0; i(i); const pcl::PointXYZ p1(convex_hull_points[i].x,convex_hull_points[i].y,convex_hull_points[i].z); const pcl::PointXYZ p2(convex_hull_points[i+1].x,convex_hull_points[i+1].y,convex_hull_points[i+1].z); //ROS_INFO(""RATING r: %f p1: %f %f %f p2:%f %f %f"", c,p1.x,p1.y,p1.z,p2.x,p2.y,p2.z); ROS_INFO(""Rating num %i = %f"", i, rating.at(i)); if (draw_convex_hull_first_polygon){ if(caddLine(p1,p2,1,0,c/invalid_rating,name); else viewer->addLine(p1,p2,0,(c-invalid_rating)/invalid_rating,(invalid_rating*2-c)/invalid_rating,name); // draw convex hull (points only) std::string namech =""convexhullstart""+boost::lexical_cast(i); viewer->addSphere(convex_hull_points[i], 0.025,0,1,0, namech,2 /*viewport*/); } } viewer->addSphere(convex_hull_points[0], 0.025,1,0,0, ""convexhullstart"", 2); viewer->addSphere(flat_robot_center, 0.05,1,0,0, ""checkPosition"", viewport_4); viewer->addSphere(robot_point_center, 0.05,0,1,0, ""proMidx"", viewport_4); viewer->addSphere(center_of_mass, 0.05,0,0,1, ""CM"", viewport_4); } //endif use_visualization for (unsigned int j = 0; j < rating.size(); j++){ if (rating.at(j) < invalid_rating){ unstable_axis += 1; } } // -------------------------------------------------------------------------// // -----------------------TIP OVER------------------------------------------// // -------------------------------------------------------------------------// if (tip_over){ // iterative checking if still fine after flipping over invalid axis for (unsigned int i = 0; i < rating.size(); i++){ if (check_each_axis || rating.at(i) < invalid_rating){ // instabil if(use_visualization) { ROS_INFO(""Roboter kippt ueber Kante mit rating %f"", rating.at(i)); } support_point_1 = convex_hull_points.at(i); support_point_2 = convex_hull_points.at(i+1); const pcl::PointXYZ tip_over_axis_vector= subtractPoints(support_point_2, support_point_1); pcl::PointXYZ tip_over_direction = crossProduct(tip_over_axis_vector, pcl::PointXYZ(0,0,1)); bool point_evaluated = findSupportPoint(support_point_1, tip_over_axis_vector, (*robot_pcl), tip_over_direction, support_point_3); if (!point_evaluated){ //ROS_INFO(""after tipping over: S1 and S2 lie at the aend of area, no S3 could be found""); continue; // supp1 and 2 lie at the end of the area, no suppP3 could be found, invalide state, break for-loop and return initial max rating value } float angle_of_area_it = angleToGround(support_point_1, support_point_2, support_point_3); if (angle_of_area_it > invalid_angle){ //ROS_INFO(""after tipping over, angle would be too high: %f"", angle_of_area_it); continue; } pcl::PointCloud::Ptr cloud_positionRating_iterative(new pcl::PointCloud()); std::vector convex_hull_points_it = buildConvexHull(robot_pcl, flat_robot_center, support_point_1, support_point_2, support_point_3, true, cloud_positionRating_iterative); pcl::PointXYZ normal_it; pcl::PointXYZ robot_point_0_it; pcl::PointXYZ robot_point_1_it; pcl::PointXYZ robot_point_2_it; pcl::PointXYZ robot_point_3_it; pcl::PointXYZ robot_point_mid_it; pcl::PointXYZ center_of_mass_it; /*computeRobotPosition(support_point_1, support_point_2, support_point_3, p0, p1, p2, p3, offset_CM, normal_it, robot_point_0_it, robot_point_1_it, robot_point_2_it, robot_point_3_it, robot_point_mid_it, center_of_mass_it);*/ //TODO REMOVE COMMENT float min_value = 100.0; unsigned int iterator = 0; for (unsigned int k = 0; k< convex_hull_points_it.size()-1; k++){ float value = vectorSimilarity(support_point_1, support_point_2, convex_hull_points_it.at(k), convex_hull_points_it.at(k+1)); //ROS_INFO(""vector_similarity = %f"", value); if (value < min_value){ min_value = value; iterator = k; } }// TODO if (min_value == 100.0){ ROS_ERROR(""[flor_terrain_classifier / model] after tipping over no edge could be removed from the rating""); } // edge that must be removed is at position k in the vector convex_hull_points_it.erase(convex_hull_points_it.begin()+ convex_hull_points_it.size()-1); for (unsigned int l = 0; l < iterator+1; l++){ // shift first of list to last of list pcl::PointXYZ temp = convex_hull_points_it.at(0); convex_hull_points_it.erase(convex_hull_points_it.begin()+0); convex_hull_points_it.push_back(temp); } if(use_visualization) { // draw supporting points viewer->addSphere(support_point_1, 0.02,1,0,0, ""sp1it_tippedOver""+boost::lexical_cast(i), viewport_4); viewer->addSphere(support_point_2, 0.02,0,1,0, ""sp2it_tippedOver""+boost::lexical_cast(i), viewport_4); viewer->addSphere(support_point_3, 0.02,0,0,1, ""sp3it_tippedOver""+boost::lexical_cast(i), viewport_4); if (draw_convex_hull_iterative_ground_points){ for (unsigned int j = 0; j < cloud_positionRating_iterative->size(); ++j){ std::string name =""groundContactAreait""+boost::lexical_cast(j)+""tippedOver""+boost::lexical_cast(i); viewer->addSphere(cloud_positionRating_iterative->at(j), 0.01,0,1,1, name, viewport_4); } } // draw center if (i == 0){ viewer->addSphere(robot_point_mid_it, 0.04,0,1,0, ""proMidxit"", viewport_4); viewer->addSphere(center_of_mass_it, 0.04,0,0,1, ""CMit"", viewport_4); // draw normal const pcl::PointXYZ p_uff(addPointVector(robot_point_center, normal)); viewer->addLine(robot_point_center,p_uff,1.0,1.0,1.0,""fnormalit"",viewport_4); } } //Compute Force Angle Stability Metric std::vector rating_iterative =computeForceAngleStabilityMetric(center_of_mass_it,convex_hull_points_it); if(use_visualization) { for (unsigned int k=0; k(k)+""tippedOver""+boost::lexical_cast(i); const pcl::PointXYZ p1(convex_hull_points_it[k].x,convex_hull_points_it[k].y,convex_hull_points_it[k].z); const pcl::PointXYZ p2(convex_hull_points_it[k+1].x,convex_hull_points_it[k+1].y,convex_hull_points_it[k+1].z); ROS_INFO(""Rating %f"", rating_iterative.at(k)); if (draw_convex_hull_iterative){ if(caddLine(p1,p2,1,0,c/invalid_rating,name,viewport_4); else viewer->addLine(p1,p2,0,(c-invalid_rating)/invalid_rating,(invalid_rating*2-c)/invalid_rating,name,viewport_4); // draw convex hull (points only) std::string namech =""convexhullstart_it""+boost::lexical_cast(k)+""tippedOver""+boost::lexical_cast(i); viewer->addSphere(convex_hull_points_it[k+1], 0.015,0,1,0, namech,2 /*viewport*/); } } if (draw_convex_hull_iterative){ viewer->addSphere(convex_hull_points_it[0], 0.015,1,0,0, ""convexhullstart_it_tippedOver""+boost::lexical_cast(i), 2 /*viewport*/); } } float min_rating_iterative =*std::min_element(rating_iterative.begin(),rating_iterative.end()); // wenn gekippt und es hier stabiler ist, übernehme den schlechtesen Wert der gekippten Position an // der entsprechenden Stelle if (min_rating_iterative > rating.at(i)){ rating.at(i) = min_rating_iterative; } } } } // usetippingover end position_rating = *std::min_element(rating.begin(),rating.end()); // draw groundpoints if(use_visualization) { pcl::visualization::PointCloudColorHandlerGenericField intensity_distribution(robot_pcl, ""intensity""); // viewer->addPointCloud(robot_pcl,intensity_distribution, ""positionRating_cloud"", viewport); // viewer->setPointCloudRenderingProperties(pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 2, ""positionRating"" + std::string(""_edges""), viewport); ROS_INFO(""CPR done: position_rating = %f, unstable_axis = %i"", position_rating, unstable_axis); } return true; } } ",16339,True,3217.1579113790804,median "CLASS ltcl_syntax_cases DEFINITION DEFERRED. CLASS zcl_abapgit_syntax_highlighter DEFINITION LOCAL FRIENDS ltcl_syntax_cases. *----------------------------------------------------------------------* * CLASS ltcl_syntax_cases definition *----------------------------------------------------------------------* CLASS ltcl_syntax_cases DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. DATA: mt_after_parse TYPE zcl_abapgit_syntax_highlighter=>ty_match_tt, mt_after_order TYPE zcl_abapgit_syntax_highlighter=>ty_match_tt, mt_after_extend TYPE zcl_abapgit_syntax_highlighter=>ty_match_tt. METHODS: do_test IMPORTING iv_line TYPE string iv_filename TYPE string, generate_parse IMPORTING iv_token TYPE char01 iv_offset TYPE i iv_length TYPE i, generate_order IMPORTING iv_token TYPE char01 iv_offset TYPE i iv_length TYPE i iv_text_tag TYPE string, generate_extend IMPORTING iv_token TYPE char01 iv_offset TYPE i iv_length TYPE i iv_text_tag TYPE string, test_abap_01 FOR TESTING, test_abap_02 FOR TESTING, test_abap_03 FOR TESTING, test_abap_04 FOR TESTING, test_abap_05 FOR TESTING, test_abap_06 FOR TESTING, test_abap_07 FOR TESTING, test_abap_08 FOR TESTING, test_xml_01 FOR TESTING, test_xml_02 FOR TESTING, test_xml_03 FOR TESTING, test_xml_04 FOR TESTING, test_xml_05 FOR TESTING, test_xml_06 FOR TESTING, test_xml_07 FOR TESTING, test_xml_08 FOR TESTING. ENDCLASS. *----------------------------------------------------------------------* * CLASS ltcl_syntax_cases IMPLEMENTATION *----------------------------------------------------------------------* CLASS ltcl_syntax_cases IMPLEMENTATION. METHOD do_test. DATA: lt_matches_act TYPE zcl_abapgit_syntax_highlighter=>ty_match_tt, lo_syntax TYPE REF TO zcl_abapgit_syntax_highlighter. lo_syntax = zcl_abapgit_syntax_highlighter=>create( iv_filename ). lt_matches_act = lo_syntax->parse_line( iv_line ). SORT lt_matches_act BY offset. cl_abap_unit_assert=>assert_equals( exp = mt_after_parse act = lt_matches_act msg = | Error during parsing: { iv_line }| ). lo_syntax->order_matches( EXPORTING iv_line = iv_line CHANGING ct_matches = lt_matches_act ). cl_abap_unit_assert=>assert_equals( exp = mt_after_order act = lt_matches_act msg = | Error during ordering: { iv_line }| ). lo_syntax->extend_matches( EXPORTING iv_line = iv_line CHANGING ct_matches = lt_matches_act ). cl_abap_unit_assert=>assert_equals( exp = mt_after_extend act = lt_matches_act msg = | Error during extending: { iv_line }| ). ENDMETHOD. METHOD generate_parse. DATA ls_match TYPE zcl_abapgit_syntax_highlighter=>ty_match. ls_match-token = iv_token. ls_match-offset = iv_offset. ls_match-length = iv_length. APPEND ls_match TO mt_after_parse. ENDMETHOD. METHOD generate_order. DATA ls_match TYPE zcl_abapgit_syntax_highlighter=>ty_match. ls_match-token = iv_token. ls_match-offset = iv_offset. ls_match-length = iv_length. ls_match-text_tag = iv_text_tag. APPEND ls_match TO mt_after_order. ENDMETHOD. METHOD generate_extend. DATA ls_match TYPE zcl_abapgit_syntax_highlighter=>ty_match. ls_match-token = iv_token. ls_match-offset = iv_offset. ls_match-length = iv_length. ls_match-text_tag = iv_text_tag. APPEND ls_match TO mt_after_extend. ENDMETHOD. ****************************************************** * Test parsing and ordering of comments * ****************************************************** METHOD test_abap_01. DATA lv_line TYPE string. lv_line = '* commented out line with key word data'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'C' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'K' iv_offset = 12 iv_length = 3 ). generate_parse( iv_token = 'K' iv_offset = 16 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 21 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 26 iv_length = 3 ). generate_parse( iv_token = 'K' iv_offset = 30 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 35 iv_length = 4 ). "" Generate table with expected values after ordering generate_order( iv_token = 'C' iv_offset = 0 iv_length = 39 iv_text_tag = '' ). "" Generate table with expected values after ordering generate_extend( iv_token = 'C' iv_offset = 0 iv_length = 39 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ****************************************************** * Test parsing and ordering of remainder of string * ****************************************************** METHOD test_abap_02. DATA lv_line TYPE string. lv_line = 'data: lv_var_name type string.'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 0 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 18 iv_length = 4 ). "" Generate table with expected values after ordering generate_order( iv_token = 'K' iv_offset = 0 iv_length = 4 iv_text_tag = '' ). generate_order( iv_token = 'K' iv_offset = 18 iv_length = 4 iv_text_tag = '' ). "" Generate table with expected values after extending generate_extend( iv_token = 'K' iv_offset = 0 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 4 iv_length = 14 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 18 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 22 iv_length = 8 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ****************************************************** * Test parsing and ordering of key words & texts * ****************************************************** METHOD test_abap_03. DATA lv_line TYPE string. lv_line = 'call function ''FM_NAME''. "" Commented'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 0 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 5 iv_length = 8 ). generate_parse( iv_token = 'T' iv_offset = 14 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 22 iv_length = 1 ). generate_parse( iv_token = 'C' iv_offset = 25 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'K' iv_offset = 0 iv_length = 4 iv_text_tag = '' ). generate_order( iv_token = 'K' iv_offset = 5 iv_length = 8 iv_text_tag = '' ). generate_order( iv_token = 'T' iv_offset = 14 iv_length = 9 iv_text_tag = '''' ). generate_order( iv_token = 'C' iv_offset = 25 iv_length = 11 iv_text_tag = '' ). "" Generate table with expected values after extending generate_extend( iv_token = 'K' iv_offset = 0 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 4 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 5 iv_length = 8 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 13 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 14 iv_length = 9 iv_text_tag = '''' ). generate_extend( iv_token = '.' iv_offset = 23 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'C' iv_offset = 25 iv_length = 11 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ****************************************************** * Test parsing and ordering of key words in texts * ****************************************************** METHOD test_abap_04. DATA lv_line TYPE string. lv_line = 'constants: lc_var type string value ''simpletext data simpletext''.'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 0 iv_length = 9 ). generate_parse( iv_token = 'K' iv_offset = 18 iv_length = 4 ). generate_parse( iv_token = 'K' iv_offset = 30 iv_length = 5 ). generate_parse( iv_token = 'T' iv_offset = 36 iv_length = 1 ). generate_parse( iv_token = 'K' iv_offset = 48 iv_length = 4 ). generate_parse( iv_token = 'T' iv_offset = 63 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'K' iv_offset = 0 iv_length = 9 iv_text_tag = '' ). generate_order( iv_token = 'K' iv_offset = 18 iv_length = 4 iv_text_tag = '' ). generate_order( iv_token = 'K' iv_offset = 30 iv_length = 5 iv_text_tag = '' ). generate_order( iv_token = 'T' iv_offset = 36 iv_length = 28 iv_text_tag = '''' ). "" Generate table with expected values after ordering generate_extend( iv_token = 'K' iv_offset = 0 iv_length = 9 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 9 iv_length = 9 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 18 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 22 iv_length = 8 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 30 iv_length = 5 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 35 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 36 iv_length = 28 iv_text_tag = '''' ). generate_extend( iv_token = '.' iv_offset = 64 iv_length = 1 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ****************************************************** * Test parsing and ordering texts in curly brackets * ****************************************************** METHOD test_abap_05. DATA lv_line TYPE string. lv_line = 'a = |{ b }={ c }|.'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'T' iv_offset = 4 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 5 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 9 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 11 iv_length = 1 ). generate_parse( iv_token = 'K' iv_offset = 13 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 15 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 16 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'T' iv_offset = 4 iv_length = 1 iv_text_tag = '|' ). generate_order( iv_token = 'T' iv_offset = 10 iv_length = 1 iv_text_tag = '}' ). generate_order( iv_token = 'K' iv_offset = 13 iv_length = 1 iv_text_tag = '' ). generate_order( iv_token = 'T' iv_offset = 16 iv_length = 1 iv_text_tag = '}' ). "" Generate table with expected values after extending generate_extend( iv_token = '.' iv_offset = 0 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 4 iv_length = 1 iv_text_tag = '|' ). generate_extend( iv_token = '.' iv_offset = 5 iv_length = 5 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 10 iv_length = 1 iv_text_tag = '}' ). generate_extend( iv_token = '.' iv_offset = 11 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 13 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 14 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 16 iv_length = 1 iv_text_tag = '}' ). generate_extend( iv_token = '.' iv_offset = 17 iv_length = 1 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ****************************************************** * Test parsing and ordering of texts * ****************************************************** METHOD test_abap_06. DATA lv_line TYPE string. lv_line = 'lv_line = lc_constant && |XYZ { ''ab'' && |ac{ ''UU'' }| }|'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 22 iv_length = 2 ). generate_parse( iv_token = 'T' iv_offset = 25 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 30 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 32 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 35 iv_length = 1 ). generate_parse( iv_token = 'K' iv_offset = 37 iv_length = 2 ). generate_parse( iv_token = 'T' iv_offset = 40 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 43 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 45 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 48 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 50 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 51 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 53 iv_length = 1 ). generate_parse( iv_token = 'T' iv_offset = 54 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'K' iv_offset = 22 iv_length = 2 iv_text_tag = '' ). generate_order( iv_token = 'T' iv_offset = 25 iv_length = 5 iv_text_tag = '|' ). generate_order( iv_token = 'T' iv_offset = 32 iv_length = 4 iv_text_tag = '''' ). generate_order( iv_token = 'K' iv_offset = 37 iv_length = 2 iv_text_tag = '' ). generate_order( iv_token = 'T' iv_offset = 40 iv_length = 3 iv_text_tag = '|' ). generate_order( iv_token = 'T' iv_offset = 45 iv_length = 4 iv_text_tag = '''' ). generate_order( iv_token = 'T' iv_offset = 51 iv_length = 1 iv_text_tag = '}' ). generate_order( iv_token = 'T' iv_offset = 54 iv_length = 1 iv_text_tag = '}' ). "" Generate table with expected values after extending generate_extend( iv_token = '.' iv_offset = 00 iv_length = 22 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 22 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 24 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 25 iv_length = 5 iv_text_tag = '|' ). generate_extend( iv_token = '.' iv_offset = 30 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 32 iv_length = 4 iv_text_tag = '''' ). generate_extend( iv_token = '.' iv_offset = 36 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 37 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 39 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 40 iv_length = 3 iv_text_tag = '|' ). generate_extend( iv_token = '.' iv_offset = 43 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 45 iv_length = 4 iv_text_tag = '''' ). generate_extend( iv_token = '.' iv_offset = 49 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 51 iv_length = 1 iv_text_tag = '}' ). generate_extend( iv_token = '.' iv_offset = 52 iv_length = 2 iv_text_tag = '' ). generate_extend( iv_token = 'T' iv_offset = 54 iv_length = 1 iv_text_tag = '}' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ******************************************************** * Check that '*' in select statement is not a match * ******************************************************** METHOD test_abap_07. DATA lv_line TYPE string. lv_line = 'SELECT * FROM foo'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 0 iv_length = 6 ). generate_parse( iv_token = 'K' iv_offset = 9 iv_length = 4 ). "" Generate table with expected values after ordering generate_order( iv_token = 'K' iv_offset = 0 iv_length = 6 iv_text_tag = '' ). generate_order( iv_token = 'K' iv_offset = 9 iv_length = 4 iv_text_tag = '' ). "" Generate table with expected values after extending generate_extend( iv_token = 'K' iv_offset = 0 iv_length = 6 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 6 iv_length = 3 iv_text_tag = '' ). generate_extend( iv_token = 'K' iv_offset = 9 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 13 iv_length = 4 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ******************************************************** * Test parsing and ordering of key words in structures * ******************************************************** METHOD test_abap_08. DATA lv_line TYPE string. lv_line = 'lv_length = -length.'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'K' iv_offset = 13 iv_length = 5 ). generate_parse( iv_token = 'K' iv_offset = 20 iv_length = 6 ). "" Generate table with expected values after extending generate_extend( iv_token = '.' iv_offset = 0 iv_length = 27 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.abap' ). ENDMETHOD. ******************************************************** * Test parsing and ordering of tags in xml * ******************************************************** METHOD test_xml_01. DATA lv_line TYPE string. lv_line = 'Text'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'X' iv_offset = 4 iv_length = 1 ). generate_parse( iv_token = 'X' iv_offset = 9 iv_length = 1 ). generate_parse( iv_token = 'X' iv_offset = 14 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 5 iv_text_tag = '<' ). generate_order( iv_token = 'X' iv_offset = 9 iv_length = 6 iv_text_tag = '<' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 5 iv_text_tag = '<' ). generate_extend( iv_token = '.' iv_offset = 5 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 9 iv_length = 6 iv_text_tag = '<' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_02. DATA lv_line TYPE string. lv_line = ''. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'X' iv_offset = 5 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 6 iv_text_tag = '<' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 6 iv_text_tag = '<' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_03. DATA lv_line TYPE string. lv_line = ''. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'A' iv_offset = 4 iv_length = 10 ). generate_parse( iv_token = 'V' iv_offset = 15 iv_length = 7 ). generate_parse( iv_token = 'X' iv_offset = 23 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 4 iv_text_tag = '<' ). generate_order( iv_token = 'A' iv_offset = 4 iv_length = 10 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 15 iv_length = 7 iv_text_tag = '' ). generate_order( iv_token = 'X' iv_offset = 22 iv_length = 2 iv_text_tag = '>' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 4 iv_text_tag = '<' ). generate_extend( iv_token = 'A' iv_offset = 4 iv_length = 10 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 14 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 15 iv_length = 7 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 22 iv_length = 2 iv_text_tag = '>' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_04. DATA lv_line TYPE string. lv_line = ''. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'A' iv_offset = 5 iv_length = 8 ). generate_parse( iv_token = 'V' iv_offset = 14 iv_length = 5 ). generate_parse( iv_token = 'X' iv_offset = 20 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 5 iv_text_tag = '<' ). generate_order( iv_token = 'A' iv_offset = 5 iv_length = 8 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 14 iv_length = 5 iv_text_tag = '' ). generate_order( iv_token = 'X' iv_offset = 19 iv_length = 2 iv_text_tag = '>' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 5 iv_text_tag = '<' ). generate_extend( iv_token = 'A' iv_offset = 5 iv_length = 8 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 13 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 14 iv_length = 5 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 19 iv_length = 2 iv_text_tag = '>' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_05. DATA lv_line TYPE string. lv_line = '""text""'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'A' iv_offset = 7 iv_length = 6 ). generate_parse( iv_token = 'V' iv_offset = 14 iv_length = 4 ). generate_parse( iv_token = 'A' iv_offset = 18 iv_length = 6 ). generate_parse( iv_token = 'V' iv_offset = 25 iv_length = 4 ). generate_parse( iv_token = 'X' iv_offset = 29 iv_length = 1 ). generate_parse( iv_token = 'V' iv_offset = 30 iv_length = 6 ). generate_parse( iv_token = 'X' iv_offset = 36 iv_length = 1 ). generate_parse( iv_token = 'X' iv_offset = 44 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 7 iv_text_tag = '<' ). generate_order( iv_token = 'A' iv_offset = 7 iv_length = 6 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 14 iv_length = 4 iv_text_tag = '' ). generate_order( iv_token = 'A' iv_offset = 18 iv_length = 6 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 25 iv_length = 4 iv_text_tag = '' ). generate_order( iv_token = 'X' iv_offset = 29 iv_length = 1 iv_text_tag = '>' ). generate_order( iv_token = 'X' iv_offset = 36 iv_length = 9 iv_text_tag = '<' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 7 iv_text_tag = '<' ). generate_extend( iv_token = 'A' iv_offset = 7 iv_length = 6 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 13 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 14 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = 'A' iv_offset = 18 iv_length = 6 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 24 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 25 iv_length = 4 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 29 iv_length = 1 iv_text_tag = '>' ). generate_extend( iv_token = '.' iv_offset = 30 iv_length = 6 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 36 iv_length = 9 iv_text_tag = '<' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_06. DATA lv_line TYPE string. ""unclosed tag lv_line = ' ""/>'. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'X' iv_offset = 0 iv_length = 1 ). generate_parse( iv_token = 'A' iv_offset = 4 iv_length = 10 ). generate_parse( iv_token = 'V' iv_offset = 15 iv_length = 7 ). generate_parse( iv_token = 'X' iv_offset = 23 iv_length = 1 ). "" Generate table with expected values after ordering generate_order( iv_token = 'X' iv_offset = 0 iv_length = 4 iv_text_tag = '<' ). generate_order( iv_token = 'A' iv_offset = 4 iv_length = 10 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 15 iv_length = 7 iv_text_tag = '' ). generate_order( iv_token = 'X' iv_offset = 22 iv_length = 2 iv_text_tag = '>' ). "" Generate table with expected values after extending generate_extend( iv_token = 'X' iv_offset = 0 iv_length = 4 iv_text_tag = '<' ). generate_extend( iv_token = 'A' iv_offset = 4 iv_length = 10 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 14 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 15 iv_length = 7 iv_text_tag = '' ). generate_extend( iv_token = 'X' iv_offset = 22 iv_length = 2 iv_text_tag = '>' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. METHOD test_xml_08. ""invalid XML characters in a string DATA lv_line TYPE string. ""attribute at beginning of line lv_line = 'attribute=''>"" '''. ""#EC NOTEXT "" Generate table with expected values after parsing generate_parse( iv_token = 'A' iv_offset = 0 iv_length = 9 ). generate_parse( iv_token = 'V' iv_offset = 10 iv_length = 5 ). "" Generate table with expected values after ordering generate_order( iv_token = 'A' iv_offset = 0 iv_length = 9 iv_text_tag = '' ). generate_order( iv_token = 'V' iv_offset = 10 iv_length = 5 iv_text_tag = '' ). "" Generate table with expected values after extending generate_extend( iv_token = 'A' iv_offset = 0 iv_length = 9 iv_text_tag = '' ). generate_extend( iv_token = '.' iv_offset = 9 iv_length = 1 iv_text_tag = '' ). generate_extend( iv_token = 'V' iv_offset = 10 iv_length = 5 iv_text_tag = '' ). do_test( iv_line = lv_line iv_filename = '*.xml' ). ENDMETHOD. ENDCLASS. CLASS ltcl_syntax_basic_logic DEFINITION DEFERRED. CLASS zcl_abapgit_syntax_highlighter DEFINITION LOCAL FRIENDS ltcl_syntax_basic_logic. *----------------------------------------------------------------------* * CLASS ltcl_syntax_basic_logic DEFINITION *----------------------------------------------------------------------* * *----------------------------------------------------------------------* CLASS ltcl_syntax_basic_logic DEFINITION FINAL FOR TESTING RISK LEVEL HARMLESS DURATION SHORT. PRIVATE SECTION. DATA mo_syntax_highlighter TYPE REF TO zcl_abapgit_syntax_highlighter. METHODS: setup, process_line FOR TESTING, format_line FOR TESTING, apply_style FOR TESTING. ENDCLASS. *----------------------------------------------------------------------* * CLASS ltcl_syntax_highlighter IMPLEMENTATION *----------------------------------------------------------------------* CLASS ltcl_syntax_basic_logic IMPLEMENTATION. METHOD setup. mo_syntax_highlighter = zcl_abapgit_syntax_highlighter=>create( '*.abap' ). ENDMETHOD. METHOD format_line. DATA: lv_line TYPE string, lv_line_act TYPE string, lv_line_exp TYPE string. lv_line = 'call function ''FM_NAME''. "" Commented'. ""#EC NOTEXT lv_line_exp = 'call' && ""#EC NOTEXT ' function' && ""#EC NOTEXT ' 'FM_NAME'.' && ""#EC NOTEXT ' " Commented'. ""#EC NOTEXT lv_line_act = mo_syntax_highlighter->process_line( lv_line ). cl_abap_unit_assert=>assert_equals( exp = lv_line_exp act = lv_line_act msg = | Error during formating: { lv_line }| ). ENDMETHOD. METHOD apply_style. DATA lv_line_act TYPE string. "" Call the method and compare results lv_line_act = mo_syntax_highlighter->apply_style( iv_line = 'CALL FUNCTION' ""#EC NOTEXT iv_class = zcl_abapgit_syntax_abap=>c_css-keyword ). cl_abap_unit_assert=>assert_equals( act = lv_line_act exp = 'CALL FUNCTION' ""#EC NOTEXT msg = 'Failure during applying of style.' ). ""#EC NOTEXT ENDMETHOD. METHOD process_line. DATA lv_line_act TYPE string. "" Call the method with empty parameter and compare results lv_line_act = mo_syntax_highlighter->process_line( '' ). cl_abap_unit_assert=>assert_equals( act = lv_line_act exp = '' msg = 'Failure in method process_line.' ). ""#EC NOTEXT "" Call the method with non-empty line and compare results lv_line_act = mo_syntax_highlighter->process_line( '* CALL FUNCTION' ). ""#EC NOTEXT cl_abap_unit_assert=>assert_equals( act = lv_line_act exp = '* CALL FUNCTION' ""#EC NOTEXT msg = 'Failure in method process_line.' ). ""#EC NOTEXT ENDMETHOD. ENDCLASS. ",9948,True,2645.659781123114,median "[[flowableApps]] == Flowable applications Flowable provides several ui web applications to demonstrate and leverage the functionality provided by the Flowable project: * Flowable IDM: an Identity Management application that provides single sign-on authentication functionality for all the Flowable UI applications, and, for users with the IDM administrative privilege, it also provides functionality to manage users, groups and privileges. * Flowable Modeler: an application that allows users with modeler privileges to model processes, forms, decision tables and application definitions. * Flowable Task: a runtime task application that provides functionality to start process instances, edit task forms, complete tasks and query on tasks and process instances. * Flowable Admin: an administrative application that allows users with admin privilege to query the BPMN, DMN, form and content engines and provides several options to change process instances, tasks, jobs and so on. The admin application connects to the engines through the REST API that is deployed together with the Flowable Task app and the Flowable REST app. The Flowable IDM is required for all other apps to enable authentication. The WAR files for each app can be deployed to the same servlet container (such as Apache Tomcat), but can also be deployed on different servlet containers. Because the same cookie is used for authentication with each app, the apps need to run on the same domain. Flowable also provides the `flowable-rest.war` which contains the Flowable REST API. More about this can be read in the <> chapter. The apps are Spring Boot 2.0 based, which means that that the WAR files are actually executable and can be run as a normal standalone applications. See https://docs.spring.io/spring-boot/docs/current/reference/html/build-tool-plugins-maven-plugin.html#build-tool-plugins-maven-packaging[The Executable Jar Format] in the Spring Boot reference documentation. [[uiAppInstallation]] === Flowable UI Applications installation As mentioned before, all four UI apps can be deployed together on the same Tomcat server, and to get started this is probably the easiest approach. You can choose to only install the Modeler app, for example, but make sure the Flowable IDM app is always running/deployed as well. For this installation guide we'll describe the installation of all four apps to a Tomcat server. 1. Download a recent stable version of link:$$http://tomcat.apache.org$$[Apache Tomcat]. 2. Download the latest stable link:$$http://www.flowable.org/downloads.html$$[Flowable 6 version]. 3. Copy the flowable-admin.war, flowable-idm.war, flowable-modeler.war and flowable-task.war files from the Flowable distribution __wars__ folder to the Tomcat webapps folder. 4. Startup the Tomcat server by running the bin/startup.sh (Mac OS and Linux) or bin/startup.bat (Windows) script. 5. Open a web browser and go to link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]. All Flowable UI apps should now be running with an H2 in-memory database and the following login screen should be shown in your web browser: image::images/flowable_idm_login_screen.png[align=""center""] By default, the Flowable IDM application will create an admin user that has privileges to all the Flowable UI apps. You can login with admin/test and the browser should redirect to the Flowable Modeler application: image::images/flowable_modeler_startup_screen.png[align=""center""] Since the UI apps are Spring Boot executable apps it is possible to run them as standalone applications without the need of an application server. Starting single application looks like: ``` java -jar flowable-idm.war ``` Usually, you will want to change the default H2 in-memory database configuration to a MySQL or Postgres (or other persistent database) configuration. You can do this per app by changing the application.properties file in the _WEB-INF/classes/_ directory of each app. However, it is easier to use the Spring Boot https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration]. An example configuration can be found on link:$$https://github.com/flowable/flowable-engine/blob/master/modules/flowable-ui-task/flowable-ui-task-app/src/main/resources/flowable-default.properties$$[Github] To change the default configuration to MySQL the following changes are needed to the properties file: [source,linenums] ---- spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable?characterEncoding=UTF-8 spring.datasource.username=flowable spring.datasource.password=flowable ---- This configuration will expect a flowable database to be present in the MySQL server and the UI apps will automatically generate the necessary database tables. For Postgres the following changes are necessary: [source,linenums] ---- spring.datasource.driver-class-name=org.postgresql.Driver spring.datasource.url=jdbc:postgresql://localhost:5432/flowable spring.datasource.username=flowable spring.datasource.password=flowable ---- In addition to changing the configuration, make sure the database driver is available on the classpath. Again, you could do this for every web application separately by adding the driver JAR file to the WEB-INF/lib folder, but you can also copy the JAR file once to the Tomcat lib folder. For MySQL and Postgres the database drivers can be downloaded from: * MySQL: link:$$https://dev.mysql.com/downloads/connector/j$$[https://dev.mysql.com/downloads/connector/j] * Postgres: link:$$https://jdbc.postgresql.org/$$[https://jdbc.postgresql.org/] When running the apps as standalone applications the database driver can be added by using the `loader.path` property. ``` java -Dloader.path=/location/to/your/driverfolder -jar flowable-idm.war ``` See the https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html#executable-jar-property-launcher-features[`PropertiesLauncher` Features] in the Spring Boot reference documentation for more information. === Flowable UI Applications Configurations As the Flowable UI apps are Spring Boot applications you can use all the properties Spring Boot provides. In order to provide custom configuration for the apps have a look at the https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html[Externalized Configuration] section of the Spring Boot documentation. [TIP] ----- You can also use YAML based properties. ----- .Common UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.common.app.idm-url |idm.app.url |- |The URL to the IDM application, used for the user info and token info REST GET calls. It's also used as a fallback for the redirect url to the login page in the UI apps. |flowable.common.app.idm-redirect-url |idm.app.redirect.url |- |The redirect URL to the IDM application, used for the login redirect when the cookie isn't set or is invalid. |flowable.common.app.redirect-on-auth-success |app.redirect.url.on.authsuccess |- |The URL to which the redirect should occur after a successful authentication. |flowable.common.app.role-prefix |- |ROLE_ |The default role prefix that needs to be used by Spring Security. |flowable.common.app.tenant-id |- |- |The static tenant id used for the DefaultTenantProvider. The modeler app uses this to determine under which tenant id to store and publish models. When not provided, empty or only contains whitespace it defaults to the user's tenant id if available otherwise it uses no tenant id. |flowable.common.app.cache-login-tokens.max-age |cache.login-tokens.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-tokens.max-size |cache.login-tokens.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-login-users.max-age |cache.login-users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-login-users.max-size |cache.login-users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.cache-users.max-age |cache.users.max.age |30 |The max age in seconds after which the entry should be invalidated. |flowable.common.app.cache-users.max-size |cache.users.max.size |2048 |The maximum number of entries that the cache should contain. |flowable.common.app.idm-admin.password |idm.admin.password |- |The password used for executing the REST calls (with basic auth) to the IDM REST services. Default is test. |flowable.common.app.idm-admin.user |idm.admin.user |admin |The username used for executing the REST calls (with basic auth) to the IDM REST services. Default is admin |flowable.rest.app.authentication-mode |rest.authentication.mode |verify-privilege |Configures the way user credentials are verified when doing a REST API call: 'any-user' : the user needs to exist and the password need to match. Any user is allowed to do the call (this is the pre 6.3.0 behavior) 'verify-privilege' : the user needs to exist, the password needs to match and the user needs to have the 'rest-api' privilege If nothing set, defaults to 'verify-privilege' |=============== Some of the old properties have been moved to be managed by the Flowable Spring Boot starter (or Spring Boot itself) .Old properties managed by the Flowable Spring Boot Starter [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.async-executor-activate |engine.process.asyncexecutor.activate |true |Whether the async executor should be activated. |flowable.database-schema-update |engine.process.schema.update |true |The strategy that should be used for the database schema. |flowable.history-level |engine.process.history.level |- |The history level that needs to be used. |flowable.process.servlet.name |flowable.rest-api-servlet-name |Flowable BPMN Rest API |The name of the Process servlet. |flowable.process.servlet.path |flowable.rest-api-mapping |/process-api |The context path for the Process rest servlet. |flowable.content.storage.create-root |contentstorage.fs.create-root |true |If the root folder doesn't exist, should it be created? |flowable.content.storage.root-folder |contentstorage.fs.root-folder |- |Root folder location where content files will be stored, for example, task attachments or form file uploads. |flowable.idm.enabled |flowable.db-identity-used |true |Whether the idm engine needs to be started. |flowable.idm.password-encoder |security.passwordencoder |- |The type of the password encoder that needs to be used. |flowable.idm.ldap.base-dn |ldap.basedn |- |The base 'distinguished name' (DN) from which the searches for users and groups are started. Use 'user-base-dn' or 'group-base-dn' when needing to differentiate between user and group base DN. |flowable.idm.ldap.enabled |ldap.enabled |false |Whether to enable LDAP IDM Service. |flowable.idm.ldap.password |ldap.password |- |The password that is used to connect to the LDAP system. |flowable.idm.ldap.port |ldap.port |-1 |The port on which the LDAP system is running. |flowable.idm.ldap.server |ldap.server |- |The server host on which the LDAP system can be reached. For example 'ldap://localhost'. |flowable.idm.ldap.user |ldap.user |- |The user id that is used to connect to the LDAP system. |flowable.idm.ldap.attribute.email |ldap.attribute.email |- |Name of the attribute that matches the user email. This property is used when looking for an 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.first-name |ldap.attribute.firstname |- |Name of the attribute that matches the user first name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.group-id |ldap.attribute.groupid |- |Name of the attribute that matches the group id. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.group-name |ldap.attribute.groupname |- |Name of the attribute that matches the group name. This property is used when looking for a 'org.flowable.idm.api.Group' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.Group' object is done. |flowable.idm.ldap.attribute.last-name |ldap.attribute.lastname |- |Name of the attribute that matches the user last name. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. |flowable.idm.ldap.attribute.user-id |ldap.attribute.userid |- |Name of the attribute that matches the user id. This property is used when looking for a 'org.flowable.idm.api.User' object and the mapping between the LDAP object and the Flowable 'org.flowable.idm.api.User' object is done. This property is optional and is only needed if searching for 'org.flowable.idm.api.User' objects using the Flowable API. |flowable.idm.ldap.cache.group-size |ldap.cache.groupsize |-1 |Allows to set the size of the 'org.flowable.ldap.LDAPGroupCache'. This is an LRU cache that caches groups for users and thus avoids hitting the LDAP system each time the groups of a user needs to be known. The cache will not be instantiated if the value is less then zero. By default set to -1, so no caching is done. Note that the group cache is instantiated on the 'org.flowable.ldap.LDAPIdentityServiceImpl'. As such, if you have a custom implementation of the 'org.flowable.ldap.LDAPIdentityServiceImpl', do not forget to add the group cache functionality. |flowable.idm.ldap.query.all-groups |ldap.query.groupall |- |The query that is executed when searching for all groups. |flowable.idm.ldap.query.all-users |ldap.query.userall |- |The query that is executed when searching for all users. |flowable.idm.ldap.query.groups-for-user |ldap.query.groupsforuser |- |The query that is executed when searching for the groups of a specific user. For example: `(&(objectClass=groupOfUniqueNames)(uniqueMember={0}))` Here, all the objects in LDAP with the class 'groupOfUniqueNames' and where the provided DN is a 'uniqueMember' are returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different `org.flowable.ldap.LDAPQueryBuilder`, which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-full-name-like |ldap.query.userbyname |- |The query that is executed when searching for a user by full name. For example: `(&(objectClass=inetOrgPerson)(\\|({0}=**{1}**)({2}={3})))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching first name or last name will be returned Several things will be injected in the expression: {0} : the first name attribute {1} : the search text {2} : the last name attribute {3} : the search text If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.idm.ldap.query.user-by-id |ldap.query.userbyid |- |The query that is executed when searching for a user by userId. For example: `(&(objectClass=inetOrgPerson)(uid={0}))` Here, all the objects in LDAP with the class 'inetOrgPerson' and who have the matching 'uid' attribute value will be returned. As shown in the example, the user id is injected by the typical {@link java.text.MessageFormat}, ie by using _{0}_ If setting the query alone is insufficient for your specific LDAP setup, you can alternatively plug in a different 'org.flowable.ldap.LDAPQueryBuilder', which allows for more customization than only the query. |flowable.mail.server.host |email.host |localhost |The host of the mail server. |flowable.mail.server.password |email.password |- |The password for the mail server authentication. |flowable.mail.server.port |email.port |1025 |The port of the mail server. |flowable.mail.server.use-ssl |email.use-ssl |false |Sets whether SSL/TLS encryption should be enabled for the SMTP transport upon connection (SMTPS/POPS). |flowable.mail.server.use-tls |email.use-tls |false |Set or disable the STARTTLS encryption. |flowable.mail.server.username |email.username |- |The username that needs to be used for the mail server authentication. If empty no authentication would be used. |flowable.process.definition-cache-limit |flowable.process-definitions.cache.max |-1 |The maximum amount of process definitions available in the process definition cache. Per default it is 1 (all process definitions) |=============== .Old properties managed by Spring Boot [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |spring.datasource.driver-class-name |datasource.driver |- |Fully qualified name of the JDBC driver. Auto-detected based on the URL by default. |spring.datasource.jndi-name |datasource.jndi.name |- |JNDI location of the datasource. Class, url, username & password are ignored when set. |spring.datasource.password |datasource.password |- |Login password of the database. |spring.datasource.url |datasource.url |- |JDBC URL of the database. |spring.datasource.username |datasource.username |- |Login username of the database. |spring.datasource.hikari.connection-test-query |datasource.preferred-test-query |- |The SQL query to be executed to test the validity of connections. |spring.datasource.hikari.connection-timeout |datasource.connection.timeout |- |The maximum number of milliseconds that a client will wait for a connection from the pool. If this time is exceeded without a connection becoming available, a SQLException will be thrown when getting a connection. |spring.datasource.hikari.idle-timeout |datasource.connection.idletimeout |- |The maximum amount of time (in milliseconds) that a connection is allowed to sit idle in the pool. Whether a connection is retired as idle or not is subject to a maximum variation of +30 seconds, and average variation of +15 seconds. A connection will never be retired as idle before this timeout. A value of 0 means that idle connections are never removed from the pool. |spring.datasource.hikari.max-lifetime |datasource.connection.maxlifetime |- |This property controls the maximum lifetime of a connection in the pool. When a connection reaches this timeout, even if recently used, it will be retired from the pool. An in-use connection will never be retired, only when it is idle will it be removed. |spring.datasource.hikari.maximum-pool-size |datasource.connection.maxpoolsize |- |The property controls the maximum size that the pool is allowed to reach, including both idle and in-use connections. Basically this value will determine the maximum number of actual connections to the database backend. When the pool reaches this size, and no idle connections are available, calls to getConnection() will block for up to connectionTimeout milliseconds before timing out. |spring.datasource.hikari.minimum-idle |datasource.connection.minidle |- |The property controls the minimum number of idle connections that HikariCP tries to maintain in the pool, including both idle and in-use connections. If the idle connections dip below this value, HikariCP will make a best effort to restore them quickly and efficiently. |spring.servlet.multipart.max-file-size |file.upload.max.size |10MB |Max file size. Values can use the suffixes ""MB"" or ""KB"" to indicate megabytes or kilobytes, respectively. |=============== .Not used old properties [cols=""2*"",options=""header""] |=============== |Old property |Description |datasource.jndi.resource-ref |Spring Boot does not support configuring JNDI resourceRef. Use entire resource reference in the name. |email.use-credentials |In case you don't want to use credentials, set the password and user to empty. |=============== [[flowableIDMApp]] === Flowable IDM application The Flowable IDM application is used by all other three Flowable web applications for authentication and authorization and is therefore required to be available when you want to run the Modeler, Task or Admin application. The Flowable IDM application is a simple identity management application and is targeted at providing single sign-on capabilities to the Flowable web applications, including providing a central place to define users, groups and privileges. The IDM application boots the IDM engine at startup and will create the identity tables as defined in the IDM engine in the datasource defined in the properties configuration. When the Flowable IDM application is deployed and started, it will check if there's a user available in the ACT_ID_USER table, and if not it will use the `flowable.common.app.idm-admin.user` property to create a new default admin user in this table. It will also add all available privileges in the Flowable project to the newly created admin user: * access-idm: provides the privilege to manage users, groups and privileges * access-admin: allows the user to login to the Flowable Admin application, manage the Flowable engines and access the Actuator endpoints of all the applications * access-modeler: enables access to the Flowable Modeler application * access-task: provides the privilege to login to the Flowable Task application * access-rest-api: allows the user to do call the REST API. Otherwise a 403 (forbidden) http status will be returned. Note that _flowable.rest.app.authentication-mode_ nees to be set to _verify-privilege_, which is the default. When logging in to link:$$http://localhost:8080/flowable-idm$$[http://localhost:8080/flowable-idm] with admin/test for the first time the following user overview screen is shown: image::images/flowable_idm_startup_screen.png[align=""center""] In this screen users can be added, removed and updated. The groups section can be used to create, delete and update groups. In the group details view you can also add and remove users to and from the group. The privilege screen allows you to add and remove privileges from users and groups: image::images/flowable_idm_privilege_screen.png[align=""center""] There's no option to define new privileges yet, but you can add and remove users and groups for the existing four privileges. This are the IDM UI App specific properties. .IDM UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.idm.app.bootstrap |idm.bootstrap.enabled |true |Whether the IDM App needs to be bootstrapped. |flowable.idm.app.rest-enabled |rest.idm-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |flowable.idm.app.admin.email |admin.email |- |The email of the admin user. |flowable.idm.app.admin.first-name |admin.firstname |- |The first name of the admin user. |flowable.idm.app.admin.last-name |admin.lastname |- |The last name of the admin user. |flowable.idm.app.admin.password |admin.password |- |The password for the admin user. |flowable.idm.app.admin.user-id |admin.userid |- |The id of the admin user. |flowable.idm.app.security.remember-me-key |security.rememberme.key |testKey |The hash key that is used by Spring Security to hash the password values in the applications. Make sure that you change the value of this property. |flowable.idm.app.security.user-validity-period |cache.users.recheck.period |30000 |How long should a user be cached before invalidating it in the cache for the cacheable CustomUserDetailsService. |flowable.idm.app.security.cookie.domain |security.cookie.domain |- |The domain for the cookie. |flowable.idm.app.security.cookie.max-age |security.cookie.max-age |2678400 |The max age of the security cookie in seconds. Default is 31 days. |flowable.idm.app.security.cookie.refresh-age |security.cookie.refresh-age |86400 |The refresh age of the cookie in seconds. Default is 1 day. |=============== In addition to the default identity tables, the IDM application can also be configured to use an LDAP server. To connect to a LDAP server, additional properties in the application.properties file (or any other way of configuring the application) are needed: [source,linenums] ---- # # LDAP # flowable.idm.ldap.enabled=true flowable.idm.ldap.server=ldap://localhost flowable.idm.ldap.port=10389 flowable.idm.ldap.user=uid=admin, ou=system flowable.idm.ldap.password=secret flowable.idm.ldap.base-dn=o=flowable flowable.idm.ldap.query.user-by-id=(&(objectClass=inetOrgPerson)(uid={0})) flowable.idm.ldap.query.user-by-full-name-like=(&(objectClass=inetOrgPerson)(|({0}=*{1}*)({2}=*{3}*))) flowable.idm.ldap.query.all-users=(objectClass=inetOrgPerson) flowable.idm.ldap.query.groups-for-user=(&(objectClass=groupOfUniqueNames)(uniqueMember={0})) flowable.idm.ldap.query.all-groups=(objectClass=groupOfUniqueNames) flowable.idm.ldap.query.group-by-id=(&(objectClass=groupOfUniqueNames)(uniqueId={0})) flowable.idm.ldap.attribute.user-id=uid flowable.idm.ldap.attribute.first-name=cn flowable.idm.ldap.attribute.last-name=sn flowable.idm.ldap.attribute.group-id=cn flowable.idm.ldap.attribute.group-name=cn flowable.idm.ldap.cache.group-size=10000 flowable.idm.ldap.cache.group-expiration=180000 ---- When the `flowable.idm.ldap.enabled` property is set to true, the IDM app will expect the other LDAP properties to have been filled-in. In this example configuration the server configuration + LDAP queries for the Apache Directory Server are provided. For other LDAP servers, like Active Directory, other configuration values are needed. When LDAP is configured, authentication and group retrieval for a user will be done through the LDAP server. Only privileges will still be retrieved from the Flowable identity tables. So make sure each LDAP user has the correct privileges defined in the IDM application. If the IDM application is booted with LDAP configuration the bootstrap logic will check if there are already privileges present in the Flowable identity tables. If there are no privileges (only when booting the first time), the 4 default privileges will be created and the `flowable.idm.app.admin.user-id` property value (from application.properties or configured in the environment) will be used as the user id to get all 4 privileges. So make sure that the `flowable.idm.app.admin.user-id` property value is set to a valid LDAP user, otherwise nobody will be able to login to any of the Flowable UI apps. [[flowableModelerApp]] === Flowable Modeler application The Flowable Modeler application can be used to model BPMN processes, DMN decision table, Form definitions and create app definitions. The BPMN modeler uses the same Oryx and Angular foundation as in Flowable 5, but the functionality has now been moved into a separate Modeler application. When using the Flowable Modeler application, make sure the Flowable IDM application is deployed and running as well (for authentication and authorization purposes). When you login to the Modeler application (link:$$http://localhost:8080/flowable-modeler$$[http://localhost:8080/flowable-modeler]) with your user (or the default admin/test user), you will see the process overview screen. From here you can start creating new BPMN process models by clicking on the Create Process or Import Process button. image::images/flowable_modeler_createmodel_popup.png[align=""center"", width=""600""] When creating a process model (but also any other model), it's important to think carefully about the model key value. The model key is a unique identifier for the model across the full model repository. If you choose a model key that already exists in the model repository, an error message is shown and the model is not saved. After creating the model with the popup, the BPMN modeling canvas is shown. The BPMN editor is very similar to the Flowable 5 BPMN editor that was part of the Explorer application. All BPMN elements supported by the Flowable engine are available to be used in the design of a process model. image::images/flowable_modeler_design_screen.png[align=""center""] The BPMN editor is divided into 4 parts: * Palette: the palette of BPMN elements available to design a process model * Toolbar: actions to change the model canvas, such as zooming, layout and saving a model * Model canvas: the modeling canvas on which to drag and drop BPMN elements and design the process model * Properties panel: the properties for the main process model if no element is select and otherwise the properties of the selected BPMN element For a User task element there's a _Referenced form_ property in the properties panel. If you select this property, a popup is opened where you can select a form definition from the repository or create a new form. When creating a new form, a similar create dialog to the process model create dialog is presented. After filling in the name and form model key, the form editor is opened. image::images/flowable_modeler_formdesign_screen.png[align=""center""] Form fields can be dragged from the form palette on to the form canvas. In this example, a name textfield, two date fields and a remarks multiline textfield are added to the form canvas. When editing a form field, the label, id, required status and placeholder can be filled in. image::images/flowable_modeler_editfield_popup.png[align=""center"", width=""600""] The id field is an important value, because a process variable will be created with the form field value using the id property value. When filling in the label property, the id property is automatically filled. If needed, you can also provide the id property value yourself by checking the override id checkbox. After saving the form model and closing the form editor, you are automatically navigated back to the process model (when the form editor was opened via the BPMN editor). When selecting the User task element again and clicking on the _Referenced form_ property you will see that the newly created form definition is now attached to the User task. When clicking on the _Form_ tab in the header of the Modeler application, all form definitions available in the model repository are shown. image::images/flowable_modeler_formoverview_screen.png[align=""center""] You can preview every form definition by opening the details view of a form definition. In the details view, the form name, key and description can be edited and the history of form models is available. You can also duplicate the form definition to create a new form definition with the same form fields. Now let's open the vacation request process model in the BPMN editor again and add a Script task to the process model, that will calculate the number of days between the vacation start and end dates. Click on the _Script format_ property and fill in a value of _groovy_ to instruct the Flowable engine to use the Groovy scripting engine. Now click on the _Script_ property and fill in the script that calculates the number of days. image::images/flowable_modeler_script_popup.png[align=""center"", width=""600""] Now we have a _amountOfVacationDays_ process variable we can add a Decision task to the process model. A decision task can be used to execute a DMN decision table in the Flowable DMN engine. Through the _Decision table reference_ property, a new decision table model can be created and the DMN editor is opened. image::images/flowable_modeler_dmneditor_screen.png[align=""center""] The DMN editor provides a table editor with input columns, where input conditions can be defined with the process variables available in the process context, and output columns, where output variable values can be defined. In this very simple example there's one input column using the _amountOfVacationDays_ variable that checks if it's less than 10 or higher or equal to 10. When the amount of days is less than 10, an output variable _managerApprovalNeeded_ is returned with value false, and otherwise a value of true is returned. You can define multiple input columns and have multiple input conditions per rule. It's also possible to leave an input column empty, which means that it's evaluated to true for that part of the rule. You can define one or multiple output variables. Another important part of the DMN decision table definition is the hit policy. Currently, Flowable supports the First and Any hit policy. With the First hit policy, when the first rule is found that evaluates to true the DMN execution will stop and its output variables are returned. For the Any hit policy, all rules will be executed and the output variables for the last rule that evaluates to true are returned. When the DMN editor is saved and closed, the Modeler application navigates back to the BPMN editor and the newly created DMN decision table is now attached to the Decision task. The decision task will be generated in the BPMN XML like; [source,xml,linenums] ---- ---- With the _managerApprovalNeeded_ variable available in the process instance context, we can now create an exclusive gateway with a sequence flow condition that evaluates the calculated value of the DMN Engine. image::images/flowable_modeler_sequenceflowcondition_popup.png[align=""center"", width=""500""] The full BPMN process model now looks like this: image::images/flowable_modeler_vacationrequest_screen.png[align=""center""] With the process model completed, we can now create an app definition that combines one or more process models with all their associated models (for example, decision tables and form definitions) into a single artifact. An app definition can be exported as a BAR file (zip format) that can be deployed on the Flowable engine. When creating a vacation request app definition, the app editor will look something like the screen below. image::images/flowable_modeler_appeditor_screen.png[align=""center""] In the app editor, an icon and a theme color can be selected that will be used in the Flowable Task application to show the application in the dashboard. The important step is to add the vacation request process model, and by selecting the process model, automatically include any form definitions and DMN decision tables. image::images/flowable_modeler_modelselection_popup.png[align=""center""] A process model can be selected by clicking on the model thumbnail. When one or more models are selected, you can close the popup, save the app definition and close it. When navigating to the details view of the newly created vacation request app definition, the following details screen is shown: image::images/flowable_modeler_appdetails_screen.png[align=""center""] From this view, you can download the app definition in two different formats. The first download button (with the arrow pointing downwards) can be used to download the app definition with the JSON model files for each included model. This makes it easy to share app definitions between different Flowable Modeler applications. The second download button (with the arrow point to upper right) will provide a BAR file of the app definition models, which can be deployed on the Flowable engine. In the BAR file, only the deployable artifacts are included, such as the BPMN 2.0 XML file and the DMN XML file, and not the JSON model files. All files in a BAR file deployed on a Flowable engine are stored in the database, so therefore only the deployable files are included. From the app definition details view, you can also _Publish_ the app definition directly to the Flowable engine. The Flowable Modeler uses the URL defined in the application.properties file with the _flowable.modeler.app.deployment-api-url_ property key. By default, the deployment URL is configured so the app definition will be deployed on the Flowable Task application when it's running. However, this can be changed to use the Flowable REST application, for example. Make sure the Flowable Task application is running and click on the _Publish_ button. The app definition is now deployed as a BAR file to the Flowable Task application. This are the Modeler UI App specific properties. .Modeler UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.modeler.app.data-source-prefix |datasource.prefix |- |The prefix for the database tables. |flowable.modeler.app.deployment-api-url |deployment.api.url |http://localhost:8080/flowable-task/app-api |The root URI to the REST services of the Flowable engine, used by the Flowable Modeler application to deploy the application definition BAR file to the engine. Default url for the Flowable Task application is http://localhost:8080/flowable-task/app-api |flowable.modeler.app.rest-enabled |rest.modeler-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableTaskApp]] === Flowable Task application The Flowable Task application is the runtime application of the Flowable project and includes the Flowable BPMN, DMN, Form and Content engines by default. With the Flowable Task application, new process instances can be started, tasks can be completed, task forms can be rendered and so on. In the previous section, the vacation request app definition was deployed on the Flowable Task application REST API, and through that deployed on the Flowable engine. If you look in the Flowable database, you can see a new deployment entry has been added to the ACT_RE_DEPLOYMENT table for the BPMN Engine. Also, new entries haven been created in the ACT_DMN_DEPLOYMENT and ACT_FO_FORM_DEPLOYMENT tables for the DMN and Form engines. On the dashboard on link:$$http://localhost:8080/flowable-task$$[http://localhost:8080/flowable-task], you can see a vacation request app in addition to the default Task app, and any other apps that have been deployed to the Flowable engine already. image::images/flowable_task_dashboard_screen.png[align=""center""] When clicking on the vacation request app, the task list for the logged-in user is shown (which is probably empty for now). image::images/flowable_task_tasklist_screen.png[align=""center""] When clicking on the _Processes_ tab you can choose to start a new process instance by clicking on the _Start a process_ button. The list of available process definitions within the context of this app definition is now displayed. In the general Task app this works in a similar way, but in the Task app, all process definitions deployed on the Flowable engine are shown. After selecting the vacation request process definition, the _Start process_ button can be clicked to start a new vacation request process instance. The Flowable Task application automatically navigates to the process instance details view. You can see the _Provide vacation information_ task is active and, for example, comments can be added and the process instance state can be shown diagrammatically using the _Show diagram_ button. image::images/flowable_task_processdetails_screen.png[align=""center""] When navigating to the task list, you can also see the _Provide vacation information_ task listed there as well. The task details are shown in this view, with the vacation info form being rendered. You can also switch to the details view by clicking on the _Show details_ button. In the details view, comments can be added, users can involved in the task and attachments can be added to the task. You can also change the due date and the assignee of a task. image::images/flowable_task_taskdetails_screen.png[align=""center""] Let's fill in the form and complete the task. First, select a start date and end date that have more than 10 days in between, so we can validate that a _Manager approval_ task is being generated. After filling in the vacation info form and clicking the _Complete_ button, the Flowable task app navigates directly to the _Manager approval_ task view. When you also complete this task (without a task form), the process instance is completed. When navigating to the _Processes_ tab and clicking on the _Showing running processes_ section, you can select an option to show completed process instances. The list of completed process instances is now shown and when clicking on the just completed vacation request process you can see the two completed tasks. image::images/flowable_task_processhistory_screen.png[align=""center""] The completed form of each task is stored in the ACT_FO_FORM_INSTANCE table of the Flowable Form engine. So it's possible to look at the values of each completed form when you navigate to the completed task. image::images/flowable_task_completedform_screen.png[align=""center""] Make sure to switch back to showing running processes instead of the completed ones, otherwise you won't see newly started process instances. You can also filter tasks in the task list view. There are options to search on the name of a task, the task state, only tasks for a specific process definition and change the assignment filter. image::images/flowable_task_taskfilter_screen.png[align=""center"", width=""400""] By default, the assignment filter is set to _Tasks where I am involved_. This doesn't show the tasks where you are a candidate, such as tasks that are available to a specific candidate group before they are assigned to a specific person. To show candidate tasks you can select the _Tasks where I am one of the candidates_ assignment filter option. This are the Task UI App specific properties. .Task UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.experimental.debugger.enabled |debugger.enabled |false |Whether the process debugger should be enabled. |flowable.task.app.rest-enabled |rest.task-app.enabled |true |Enables the REST API (this is not the REST api used by the UI, but an api that's available over basic auth authentication). |=============== [[flowableAdminApp]] === Flowable Admin application The fourth UI application the Flowable project provides is the Flowable Admin application. This application provides ways to, for example, query deployments in the BPMN, DMN and Form Engines, but also shows the active state of a process instance with its active tasks and process variables. It also provides actions to assign a task to a different assignee and to complete an active task. The Flowable Admin application uses the REST API to communicate with the Flowable engines. By default, it is configured to connect to the Flowable Task REST API, but you can easily change this to use the Flowable REST app REST API instead. When going to link:$$http://localhost:8080/flowable-admin$$[http://localhost:8080/flowable-admin], the configuration screen is shown (which is also available by clicking on the arrow at the top right near the Flowable logo). image:images/flowable_admin_configuration_screen.png[align=""center""] For each engine, the REST endpoint can be configured with the basic authentication values. The configuration is done per engine, because it's possible to, for example, deploy the DMN Engine on a separate server from the BPMN Engine. When the configuration is defined with the correct values, the _Process Engine_ can be selected to administer the Flowable BPMN engine. By default, the deployments of the Flowable BPMN engine are shown. image::images/flowable_admin_deployments_screen.png[align=""center""] You can filter the deployments based on name and tenant identifier. In this view, it's also possible to deploy a new BPMN XML file or BAR file to the Flowable engine. When clicking on one of the deployments, the deployment details view is shown. image::images/flowable_admin_deploymentdetails_screen.png[align=""center""] More details of a deployment are shown here and also the process definitions that are part of this deployment on which you click to get more details. It's also possible to delete a deployment here. When you want to delete a deployed app definition, this is also the way to delete the app definition from the Flowable Task app dashboard. When clicking on one of the process definitions, the process definition details view is shown. image::images/flowable_admin_processdefinitiondetails_screen.png[align=""center""] In the process definition details view, the first page of process instances is shown, together with optional decision table definitions and form definitions that are used in the process definition. For the vacation request process definition, there's one connected decision table and one connected form definition. Clicking on the decision table definition navigates the Flowable Admin application to the DMN engine. You can always navigate back to the Process engine by clicking on the _Parent Deployment ID_ link. In addition to the deployments and definitions, you can also query on process instances, tasks, jobs and event subscriptions in the Process engine. The views all work in a similar way to what's already been described. This are the Admin UI App specific properties .Admin UI App Properties [cols=""4*"",options=""header""] |=============== |Property name |Old Property |Default value |Description |flowable.admin.app.data-source-prefix |datasource.prefix | |The prefix for the database tables. |flowable.admin.app.security.encryption.credentials-i-v-spec |security.encryption.credentials-i-v-spec |- |The string that needs to be used to create an IvParameterSpec object using it's the bytes. |flowable.admin.app.security.encryption.credentials-secret-spec |security.encryption.credentials-secret-spec |- |The string that needs to be used to create a SecretKeySpec using it's bytes. |flowable.admin.app.security.preemptive-basic-authentication | |false |Perform a preemptive basic authentication when issuing requests to the flowable REST API. **NB:** This is an experimental property and might be removed without notice. |=============== In addition to these properties, the Flowable admin application has a few more properties. The full content of the properties file can be viewed on {sc-flowable-ui-admin}/flowable-ui-admin-app/src/main/resources/application.properties[Github]. The additional properties are mainly used for defining the initial values for the REST endpoints for the different engines. The Admin application uses the initial values to make a connection to the Flowable engines, but the values can be overridden in the Admin application configuration view and these values are stored in the __ACT\\_ADM\\_SERVER\\_CONFIG__ table. An example of the BPMN Engine REST properties is shown below: [source,linenums] ---- flowable.admin.app.server-config.process.name=Flowable Process app flowable.admin.app.server-config.process.description=Flowable Process REST config flowable.admin.app.server-config.process.server-address=http://localhost flowable.admin.app.server-config.process.port=8080 flowable.admin.app.server-config.process.context-root=flowable-task flowable.admin.app.server-config.process.rest-root=process-api flowable.admin.app.server-config.process.user-name=admin flowable.admin.app.server-config.process.password=test ---- These values can be used when the Flowable Task app (with all the Flowable engines included) is managed by the Flowable Admin application. .Admin UI App Properties managed by Spring Boot [cols=""2*"",options=""header""] |=============== |Old property |Description |message.reloading.enabled |Using Spring Boot MessageSourceAutoConfiguration. Set the duration with `spring.messages.cache-duration`. |=============== === Internationalization The Flowable UI apps support internationalization (i18n). The project maintains the English translations. It is however possible to provide your own translation files in order to support other languages. The link:$$https://github.com/angular-translate/angular-translate[Angular Translate] library tries to load a specific translation file based on the browser's locale located in the _i18n_ folder (present in each UI module). When a matching translation file cannot be loaded the framework will fallback to the English translation. Mapping multiple browser locale keys to specific translations additional configuration can be provided (located in the Angular app config); [source,linenums] ---- // Initialize angular-translate $translateProvider.useStaticFilesLoader({ prefix: './i18n/', suffix: '.json' }) /* This can be used to map multiple browser language keys to a angular translate language key. */ // .registerAvailableLanguageKeys(['en'], { // 'en-*': 'en' // }) .useCookieStorage() .useSanitizeValueStrategy('sanitizeParameters') .uniformLanguageTag('bcp47') .determinePreferredLanguage(); ---- For example; your browser is configured for English (United States) and provides the language key _en-US_. Without the mapping Angular Translate will try to fetch the corresponding translation file _en-US.json_. (If this is not available it will fallback to 'en' and load the _en.json_ translation file) By uncommenting the _.registerAvailableLanguageKeys_ block you can map _en-US_ (and all other _en_ language keys) to the _en.json_ language file. === Production ready endpoints The https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html[Production ready endpoints] from Spring Boot are present for all applications. To have an overview of all the available Endpoints have a look at the https://docs.spring.io/spring-boot/docs/current/actuator-api/html/[Actuator Web API Documentation]. This properties are set per default: [source,linenums] ----- # Expose all actuator endpoints to the web # They are exposed, but only authenticated users can see /info and /health abd users with access-admin can see the others management.endpoints.web.exposure.include=* # Full health details should only be displayed when a user is authorized management.endpoint.health.show-details=when_authorized # Only users with role access-admin can access full health details management.endpoint.health.roles=access-admin ----- The security is configured in such way that the `info` and `health` endpoint are exposed to all authenticated users. Full details of the `health` endpoint can only be seen by users with the privilege `access-admin`. In case you want to change that you need to configure `management.endpoint.health.show-details`. All the rest of the endpoints are accessing only to users with the `access-admin` privilege. [[custom-bean-deployment]] === Custom bean deployment There are multiple ways of providing custom beans to the Flowable applications. [[custom-bean-deployment-spring-boot-auto]] ==== Using Spring Boot auto configuration The Flowable applications are Spring Boot 2 applications. Which means that normal Spring Boot auto configuration can be used to make the beans to Flowable. This can be done in the following manner ``` package com.your.own.package.configuration; @Configuration @AutoConfigureOrder(Ordered.LOWEST_PRECEDENCE) // Makes sure that this configuration will be processed last by Spring Boot @ConditionalOnBean(type = ""org.flowable.engine.ProcessEngine"") // The configuration will only be used when the ProcessEngine bean is present public class YourOwnConfiguration { @Configuration @ComponentScan (""com.your.own.package.beans"") public static class ComponentScanConfiguration { // This class is needed in order to conditionally perform the component scan (i.e. when the ProcessEngine bean is present) // It is an optional class, in case you don't need component scanning then you don't need to do this } @Bean public CustomBean customBean() { // create your bean } @Bean public EngineConfigurationConfigurer customProcessEngineConfigurationConfigurer() { return engineConfiguration -> { // You can use this to add extra configuration to the process engine } } } ``` Note that when using Spring Boot the configuration class can be under your own package and not under some Flowable package. In order to make this class an auto configuration class a file named `spring.factories` should be created in the `META-INF` folder of your jar. In this file you should add ``` org.springframework.boot.autoconfigure.EnableAutoConfiguration=\\ com.your.own.package.configuration.YourOwnCustomConfiguration ``` In order to use this approach you would need to include your jar in the `WEB-INF/lib` folder of the exploded war. Placing this jar in the lib folder of the servlet container (e.g. Tomcat) is not going to work due to the way Spring proxies the `@Configuration` classes. [[custom-bean-deployment-component-scan]] ==== Component scan Another way to provide custom Spring beans to the Flowable engine is to put them under a certain package and have the Flowable application component scan that package. Based on the used application this package is different: * `org.flowable.rest.app` for the `flowable-rest.war` * `org.flowable.ui.task.application` for the `flowable-task.war` The custom beans can be located in a single JAR and this jar should be present on the classpath when the applications are starting up. Depending where there JAR is placed, the lib folder of the servlet container (e.g. Tomcat) or the `WEB-INF/lib` folder of the exploded war, there are different possibilities. When using the lib folder of the servlet container then the created classes should be self contained, i.e. they should only use classes from within the jar. You can use any of the Spring `@Component` annotations (with the exception of `@Configuration`). The reason for not being able to use `@Configuration` classes is the fact that each configuration class is proxied by Spring with the help of the `ConfigurationClassPostProcessor`. However, the classloader loading the `@Configuration` class does not have access to the needed classes by Spring. When including the jar in the `WEB-INF/lib` folder of the exploded war then `@Configuration` classes and dependencies to other jars is possible. [[custom-bean-deployment-own-spring-boot]] ==== Creating your own Spring Boot application This approach is the most flexible and most powerful approach of all. In order to follow this approach have a look at the <> section of this documentation.",12229,False,2064.584962551645,median "//====== Copyright Valve Corporation, All rights reserved. ==================== #include ""steamnetworkingsockets_udp.h"" #include ""steamnetworkingconfig.h"" // memdbgon must be the last include file in a .cpp file!!! #include ""tier0/memdbgon.h"" const int k_cbSteamNetworkingMinPaddedPacketSize = 512; // Put everything in a namespace, so we don't violate the one definition rule namespace SteamNetworkingSocketsLib { #pragma pack( push, 1 ) /// A protobuf-encoded message that is padded to ensure a minimum length struct UDPPaddedMessageHdr { uint8 m_nMsgID; uint16 m_nMsgLength; }; struct UDPDataMsgHdr { enum { kFlag_ProtobufBlob = 0x01, // Protobuf-encoded message is inline (CMsgSteamSockets_UDP_Stats) }; uint8 m_unMsgFlags; uint32 m_unToConnectionID; // Recipient's portion of the connection ID uint16 m_unSeqNum; // [optional, if flags&kFlag_ProtobufBlob] varint-encoded protobuf blob size, followed by blob // Data frame(s) // End of packet }; #pragma pack( pop ) // // FIXME - legacy stuff. A very early version of the framing // within the end-to-end data payload. // const uint8 k_nDataFrameFlags_Size_Mask = 0xc0; const uint8 k_nDataFrameFlags_Size_RestOfPacket = 0x00; //const uint8 k_nDataFrameFlags_Size_8bits = 0x40; //const uint8 k_nDataFrameFlags_Size_8bitsAdd256 = 0x80; //const uint8 k_nDataFrameFlags_Size_16bits = 0xc0; const uint8 k_nDataFrameFlags_FrameType_Mask = 0x3c; const uint8 k_nDataFrameFlags_FrameType_Unreliable = 0x00; //const uint8 k_nDataFrameFlags_FrameType_Reliable = 0x10; //const uint8 k_nDataFrameFlags_FrameType_ReliableAck = 0x20; const uint8 k_nDataFrameFlags_Channel_Mask = 0x03; const uint8 k_nDataFrameFlags_Channel_Same = 0x00; const uint8 k_nDataFrameFlags_Channel_8bit = 0x02; //const uint8 k_nDataFrameFlags_Channel_16bit = 0x03; const int k_nMaxRecentLocalConnectionIDs = 256; static CUtlVectorFixed s_vecRecentLocalConnectionIDs; ///////////////////////////////////////////////////////////////////////////// // // Packet parsing / handling utils // ///////////////////////////////////////////////////////////////////////////// bool BCheckRateLimitReportBadPacket( SteamNetworkingMicroseconds usecNow ) { static SteamNetworkingMicroseconds s_usecLastReport; if ( s_usecLastReport + k_nMillion*2 > usecNow ) return false; s_usecLastReport = usecNow; return true; } void ReallyReportBadPacket( const netadr_t &adrFrom, const char *pszMsgType, const char *pszFmt, ... ) { char buf[ 2048 ]; va_list ap; va_start( ap, pszFmt ); V_vsprintf_safe( buf, pszFmt, ap ); va_end( ap ); V_StripTrailingWhitespaceASCII( buf ); if ( !pszMsgType || !pszMsgType[0] ) pszMsgType = ""message""; SpewMsg( ""Ignored bad %s from %s. %s\\n"", pszMsgType, CUtlNetAdrRender( adrFrom ).String(), buf ); } #define ReportBadPacketFrom( adrFrom, pszMsgType, /* fmt */ ... ) \\ ( BCheckRateLimitReportBadPacket( usecNow ) ? ReallyReportBadPacket( adrFrom, pszMsgType, __VA_ARGS__ ) : (void)0 ) #define ReportBadPacket( pszMsgType, /* fmt */ ... ) \\ ReportBadPacketFrom( adrFrom, pszMsgType, __VA_ARGS__ ) #define ParseProtobufBody( pvMsg, cbMsg, CMsgCls, msgVar ) \\ CMsgCls msgVar; \\ if ( !msgVar.ParseFromArray( pvMsg, cbMsg ) ) \\ { \\ ReportBadPacket( # CMsgCls, ""Protobuf parse failed."" ); \\ return; \\ } #define ParsePaddedPacket( pvPkt, cbPkt, CMsgCls, msgVar ) \\ CMsgCls msgVar; \\ { \\ if ( cbPkt < k_cbSteamNetworkingMinPaddedPacketSize ) \\ { \\ ReportBadPacket( # CMsgCls, ""Packet is %d bytes, must be padded to at least %d bytes."", cbPkt, k_cbSteamNetworkingMinPaddedPacketSize ); \\ return; \\ } \\ const UDPPaddedMessageHdr *hdr = static_cast< const UDPPaddedMessageHdr * >( pvPkt ); \\ int nMsgLength = LittleWord( hdr->m_nMsgLength ); \\ if ( nMsgLength <= 0 || int(nMsgLength+sizeof(UDPPaddedMessageHdr)) > cbPkt ) \\ { \\ ReportBadPacket( # CMsgCls, ""Invalid encoded message length %d. Packet is %d bytes."", nMsgLength, cbPkt ); \\ return; \\ } \\ if ( !msgVar.ParseFromArray( hdr+1, nMsgLength ) ) \\ { \\ ReportBadPacket( # CMsgCls, ""Protobuf parse failed."" ); \\ return; \\ } \\ } ///////////////////////////////////////////////////////////////////////////// // // CSteamNetworkListenSocketStandard - basic IPv4 packet handling // ///////////////////////////////////////////////////////////////////////////// void CSteamNetworkListenSocketStandard::ReceivedIPv4FromUnknownHost( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkListenSocketStandard *pSock ) { const uint8 *pPkt = static_cast( pvPkt ); SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); if ( cbPkt < 5 ) { ReportBadPacket( ""packet"", ""%d byte packet is too small"", cbPkt ); return; } if ( *pPkt & 0x80 ) { if ( *(uint32*)pPkt == 0xffffffff ) { // Source engine connectionless packet (LAN discovery, etc). // Just ignore it, and don't even spew. } else { // A stray data packet. Just ignore it. // // When clients are able to actually establish a connection, after that connection // is over we will use the FinWait state to close down the connection gracefully. // But since we don't have that connection in our table anymore, either this guy // never had a connection, or else we believe he knows that the connection was closed, // or the FinWait state has timed out. ReportBadPacket( ""Data"", ""Stray data packet from host with no connection. Ignoring."" ); } } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeRequest ) { ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ChallengeRequest, msg ) pSock->ReceivedIPv4_ChallengeRequest( msg, adrFrom, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectRequest ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectRequest, msg ) pSock->ReceivedIPv4_ConnectRequest( msg, adrFrom, cbPkt, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectionClosed ) { ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ConnectionClosed, msg ) pSock->ReceivedIPv4_ConnectionClosed( msg, adrFrom, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_NoConnection ) { // They don't think there's a connection on this address. // We agree -- connection ID doesn't matter. Nothing else to do. } else if ( *pPkt == k_ESteamNetworkingUDPMsg_Stats ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_Stats, msg ) pSock->ReceivedIPv4_Stats( msg, adrFrom, cbPkt, usecNow ); } else { // Any other lead byte is bogus // // Note in particular that these packet types should be ignored: // // k_ESteamNetworkingUDPMsg_ChallengeReply // k_ESteamNetworkingUDPMsg_ConnectOK // // We are not initiating connections, so we shouldn't ever get // those sorts of replies. ReportBadPacket( ""packet"", ""Invalid lead byte 0x%02x"", *pPkt ); } } uint64 CSteamNetworkListenSocketStandard::GenerateChallenge( uint16 nTime, uint32 nIP ) const { uint32 data[2] = { nTime, nIP }; uint64 nChallenge = siphash( (const uint8_t *)data, sizeof(data), m_argbChallengeSecret ); return ( nChallenge & 0xffffffffffff0000ull ) | nTime; } inline uint16 GetChallengeTime( SteamNetworkingMicroseconds usecNow ) { return uint16( usecNow >> 20 ); } void CSteamNetworkListenSocketStandard::ReceivedIPv4_ChallengeRequest( const CMsgSteamSockets_UDP_ChallengeRequest &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow ) { if ( msg.connection_id() == 0 ) { ReportBadPacket( ""ChallengeRequest"", ""Missing connection_id."" ); return; } //CSteamID steamIDClient( uint64( msg.client_steam_id() ) ); //if ( !steamIDClient.IsValid() ) //{ // ReportBadPacket( ""ChallengeRequest"", ""Missing/invalid SteamID."", cbPkt ); // return; //} // Get time value of challenge uint16 nTime = GetChallengeTime( usecNow ); // Generate a challenge uint64 nChallenge = GenerateChallenge( nTime, adrFrom.GetIP() ); // Send them a reply CMsgSteamSockets_UDP_ChallengeReply msgReply; msgReply.set_connection_id( msg.connection_id() ); msgReply.set_challenge( nChallenge ); msgReply.set_your_timestamp( msg.my_timestamp() ); msgReply.set_protocol_version( k_nCurrentProtocolVersion ); SendMsgIPv4( k_ESteamNetworkingUDPMsg_ChallengeReply, msgReply, adrFrom ); } void CSteamNetworkListenSocketStandard::ReceivedIPv4_ConnectRequest( const CMsgSteamSockets_UDP_ConnectRequest &msg, const netadr_t &adrFrom, int cbPkt, SteamNetworkingMicroseconds usecNow ) { // Make sure challenge was generated relatively recently uint16 nTimeThen = uint32( msg.challenge() ); uint16 nElapsed = GetChallengeTime( usecNow ) - nTimeThen; if ( nElapsed > GetChallengeTime( 4*k_nMillion ) ) { ReportBadPacket( ""ConnectRequest"", ""Challenge too old."" ); return; } // Assuming we sent them this time value, re-create the challenge we would have sent them. if ( GenerateChallenge( nTimeThen, adrFrom.GetIP() ) != msg.challenge() ) { ReportBadPacket( ""ConnectRequest"", ""Incorrect challenge. Could be spoofed."" ); return; } // Check that the Steam ID is valid. We'll authenticate this using their cert later CSteamID steamID( uint64( msg.client_steam_id() ) ); if ( !steamID.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 ) { ReportBadPacket( ""ConnectRequest"", ""Invalid SteamID %llu."", steamID.ConvertToUint64() ); return; } uint32 unClientConnectionID = msg.client_connection_id(); if ( unClientConnectionID == 0 ) { ReportBadPacket( ""ConnectRequest"", ""Missing connection ID"" ); return; } // Does this connection already exist? (At a different address?) int h = m_mapChildConnections.Find( ChildConnectionKey_t( steamID, unClientConnectionID ) ); if ( h != m_mapChildConnections.InvalidIndex() ) { CSteamNetworkConnectionBase *pOldConn = m_mapChildConnections[ h ]; Assert( pOldConn->m_steamIDRemote == steamID ); Assert( pOldConn->GetRemoteAddr() != adrFrom ); // or else why didn't we already map it directly to them! // NOTE: We cannot just destroy the object. The API semantics // are that all connections, once accepted and made visible // to the API, must be closed by the application. ReportBadPacket( ""ConnectRequest"", ""Rejecting connection request from %s at %s, connection ID %u. That steamID/ConnectionID pair already has a connection from %s\\n"", steamID.Render(), CUtlNetAdrRender( adrFrom ).String(), unClientConnectionID, CUtlNetAdrRender( pOldConn->GetRemoteAddr() ).String() ); CMsgSteamSockets_UDP_ConnectionClosed msgReply; msgReply.set_to_connection_id( unClientConnectionID ); msgReply.set_reason_code( k_ESteamNetConnectionEnd_Misc_Generic ); msgReply.set_debug( ""A connection with that ID already exists."" ); SendPaddedMsgIPv4( k_ESteamNetworkingUDPMsg_ConnectionClosed, msgReply, adrFrom ); } CSteamNetworkConnectionIPv4 *pConn = new CSteamNetworkConnectionIPv4( m_pSteamNetworkingSocketsInterface ); // OK, they have completed the handshake. Accept the connection. uint32 nPeerProtocolVersion = msg.has_protocol_version() ? msg.protocol_version() : 1; SteamDatagramErrMsg errMsg; if ( !pConn->BBeginAccept( this, adrFrom, m_pSockIPV4Connections, steamID, unClientConnectionID, nPeerProtocolVersion, msg.cert(), msg.crypt(), errMsg ) ) { SpewWarning( ""Failed to accept connection from %s. %s\\n"", CUtlNetAdrRender( adrFrom ).String(), errMsg ); pConn->Destroy(); return; } pConn->m_statsEndToEnd.TrackRecvPacket( cbPkt, usecNow ); // Did they send us a ping estimate? if ( msg.has_ping_est_ms() ) pConn->m_statsEndToEnd.m_ping.ReceivedPing( msg.ping_est_ms(), usecNow ); // Save of timestamp that we will use to reply to them when the application // decides to accept the connection if ( msg.has_my_timestamp() ) { pConn->m_ulHandshakeRemoteTimestamp = msg.my_timestamp(); pConn->m_usecWhenReceivedHandshakeRemoteTimestamp = usecNow; } } void CSteamNetworkListenSocketStandard::ReceivedIPv4_ConnectionClosed( const CMsgSteamSockets_UDP_ConnectionClosed &msg, const netadr_t &adrFrom, SteamNetworkingMicroseconds usecNow ) { // Send an ack. Note that we require the inbound message to be padded // to a minimum size, and this reply is tiny, so we are not at a risk of // being used for reflection, even though the source address could be spoofed. CMsgSteamSockets_UDP_NoConnection msgReply; if ( msg.from_connection_id() ) msgReply.set_to_connection_id( msg.from_connection_id() ); if ( msg.to_connection_id() ) msgReply.set_from_connection_id( msg.to_connection_id() ); SendMsgIPv4( k_ESteamNetworkingUDPMsg_NoConnection, msgReply, adrFrom ); } void CSteamNetworkListenSocketStandard::ReceivedIPv4_Stats( const CMsgSteamSockets_UDP_Stats &msg, const netadr_t &adrFrom, int cbPkt, SteamNetworkingMicroseconds usecNow ) { // Malformed? if ( msg.to_connection_id() == 0 ) return; // If their incoming message is a reasonable size, then there's no risk // of us being used for reflection attack, because the NoConnection // reply is tiny if ( cbPkt < 64 && !BCheckRateLimitReportBadPacket( usecNow ) ) return; // Just drop it // No connection! CMsgSteamSockets_UDP_NoConnection msgReply; if ( msg.from_connection_id() ) msgReply.set_to_connection_id( msg.from_connection_id() ); if ( msg.to_connection_id() ) msgReply.set_from_connection_id( msg.to_connection_id() ); SendMsgIPv4( k_ESteamNetworkingUDPMsg_NoConnection, msgReply, adrFrom ); } void CSteamNetworkListenSocketStandard::SendMsgIPv4( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t &adrTo ) { if ( !m_pSockIPV4Connections ) { Assert( false ); return; } uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ]; pkt[0] = nMsgID; int cbPkt = msg.ByteSize()+1; if ( cbPkt > sizeof(pkt) ) { AssertMsg3( false, ""Msg type %d is %d bytes, larger than MTU of %d bytes"", int( nMsgID ), cbPkt, (int)sizeof(pkt) ); return; } uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 ); Assert( cbPkt == pEnd - pkt ); // Send the reply m_pSockIPV4Connections->BSendRawPacket( pkt, cbPkt, adrTo ); } void CSteamNetworkListenSocketStandard::SendPaddedMsgIPv4( uint8 nMsgID, const google::protobuf::MessageLite &msg, const netadr_t adrTo ) { uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ]; memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire! UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt; int nMsgLength = msg.ByteSize(); hdr->m_nMsgID = nMsgID; hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) ); uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) ); int cbPkt = pEnd - pkt; Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) ); cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize ); m_pSockIPV4Connections->BSendRawPacket( pkt, cbPkt, adrTo ); } ///////////////////////////////////////////////////////////////////////////// // // IP connections // ///////////////////////////////////////////////////////////////////////////// CSteamNetworkConnectionIPv4::CSteamNetworkConnectionIPv4( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface ) : CSteamNetworkConnectionBase( pSteamNetworkingSocketsInterface ) { m_pSocket = nullptr; } CSteamNetworkConnectionIPv4::~CSteamNetworkConnectionIPv4() { AssertMsg( !m_pSocket, ""Connection not destroyed properly"" ); } void CSteamNetworkConnectionIPv4::FreeResources() { if ( m_pSocket ) { m_pSocket->Close(); m_pSocket = nullptr; } // Base class cleanup CSteamNetworkConnectionBase::FreeResources(); } int CSteamNetworkConnectionIPv4::SendDataChunk( const void *pChunk, int cbChunk, SteamNetworkingMicroseconds usecNow, uint16 *pOutSeqNum ) { if ( !m_pSocket ) { Assert( false ); return 0; } uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ]; UDPDataMsgHdr *hdr = (UDPDataMsgHdr *)pkt; hdr->m_unMsgFlags = 0x80; Assert( m_unConnectionIDRemote != 0 ); hdr->m_unToConnectionID = LittleDWord( m_unConnectionIDRemote ); hdr->m_unSeqNum = LittleWord( m_statsEndToEnd.GetNextSendSequenceNumber( usecNow ) ); byte *p = (byte*)( hdr + 1 ); // Check how much bigger we could grow the header // and still fit in a packet int cbHdrOutSpaceRemaining = pkt + sizeof(pkt) - p - cbChunk; if ( cbHdrOutSpaceRemaining < 0 ) { AssertMsg( false, ""MTU / header size problem!"" ); return 0; } // FIXME Check for putting acks in the header of the packet, instead of protobuf // Do we need to send tracer ping request or connection stats? // Make sure we aren't totally full already. (Is this even possible to fail right now?) if ( cbHdrOutSpaceRemaining >= 4 ) { // What sorts of ack should we request? uint32 nFlags = 0; if ( m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) ) { // Connection problem. Ping aggressively until we figure it out nFlags = CMsgSteamSockets_UDP_Stats::ACK_REQUEST_E2E | CMsgSteamSockets_UDP_Stats::ACK_REQUEST_IMMEDIATE; } else if ( m_statsEndToEnd.BReadyToSendTracerPing( usecNow ) || m_statsEndToEnd.BNeedToSendKeepalive( usecNow ) ) nFlags |= CMsgSteamSockets_UDP_Stats::ACK_REQUEST_E2E; // Check if we should send connection stats inline. bool bTrySendEndToEndStats = m_statsEndToEnd.BReadyToSendStats( usecNow ); // Do we actually want to send anything in the protobuf blob at all? // The goal is that we should only do this every couple of seconds or so. if ( bTrySendEndToEndStats || nFlags != 0 || m_statsEndToEnd.m_nPendingOutgoingAcks > 0 ) { // Populate a message with everything we'd like to send CMsgSteamSockets_UDP_Stats msgStatsOut; if ( bTrySendEndToEndStats ) m_statsEndToEnd.PopulateMessage( *msgStatsOut.mutable_stats(), usecNow ); // Acks // FIXME - Eventually we'd like to put a single ack in the header, since these will // be reasonably common PutEndToEndAcksIntoMessage( msgStatsOut, m_statsEndToEnd, usecNow ); // We'll try to fit what we can. If we try to serialize a message // and it won't fit, we'll remove some stuff and see if that fits. int cbStatsMsg, cbHdrSpaceNeeded; for (;;) { // Slam flags based on what we are actually going to send. Don't send flags // if they are implied by the stats we are sending. uint32 nImpliedFlags = 0; if ( msgStatsOut.has_stats() ) nImpliedFlags |= msgStatsOut.ACK_REQUEST_E2E; if ( nFlags != nImpliedFlags ) msgStatsOut.set_flags( nFlags ); else msgStatsOut.clear_flags(); // Cache size, check how big it would be cbStatsMsg = msgStatsOut.ByteSize(); // Include varint-encoded message size. // Note that if the size requires 3 bytes varint encoded, it won't fit in // a packet anyway, so we don't need to handle that case. But it is totally // possible that we might want to send more than 128 bytes of stats, and have // an opportunity to send it all in the same packet. cbHdrSpaceNeeded = cbStatsMsg + 1; if ( cbStatsMsg >= 0x80 ) ++cbHdrSpaceNeeded; // Will it fit inline with this data packet? if ( cbHdrSpaceNeeded <= cbHdrOutSpaceRemaining ) break; // Rats. We want to send some stuff, but it won't fit. // Strip off stuff, in no particular order. if ( msgStatsOut.has_stats() ) { Assert( bTrySendEndToEndStats ); if ( msgStatsOut.stats().has_instantaneous() && msgStatsOut.stats().has_lifetime() ) { // Trying to send both - clear instantaneous msgStatsOut.mutable_stats()->clear_instantaneous(); } else { // Trying to send just one or the other. Clear the whole container. msgStatsOut.clear_stats(); bTrySendEndToEndStats = false; } continue; } Assert( !bTrySendEndToEndStats ); // FIXME - we could try to send without acks. // Nothing left to clear!? We shouldn't get here! AssertMsg( false, ""Serialized stats message still won't fit, ever after clearing everything?"" ); cbStatsMsg = -1; break; } // Did we actually end up sending anything? if ( cbStatsMsg > 0 ) { // Serialize the stats size, var-int encoded byte *pStatsOut = SerializeVarInt( (byte*)p, uint32( cbStatsMsg ) ); // Serialize the actual message pStatsOut = msgStatsOut.SerializeWithCachedSizesToArray( pStatsOut ); // Make sure we wrote the number of bytes we expected if ( pStatsOut != p + cbHdrSpaceNeeded ) { // ABORT! AssertMsg( false, ""Size mismatch after serializing connection quality stats"" ); } else { // Update bookkeeping with the stuff we are actually sending TrackSentStats( msgStatsOut, true, usecNow ); // Mark header with the flag hdr->m_unMsgFlags |= hdr->kFlag_ProtobufBlob; // Advance pointer p = pStatsOut; } } } } // !FIXME! Time since previous, for jitter measurement? // Use gather-based send. This saves one memcpy of every payload iovec gather[2]; gather[0].iov_base = pkt; gather[0].iov_len = p - pkt; gather[1].iov_base = const_cast( pChunk ); gather[1].iov_len = cbChunk; int cbSend = gather[0].iov_len + gather[1].iov_len; Assert( cbSend <= sizeof(pkt) ); // Bug in the code above. We should never ""overflow"" the packet. (Ignoring the fact that we using a gather-based send. The data could be tiny with a large header for piggy-backed stats.) // !FIXME! Should we track data payload separately? Maybe we ought to track // *messages* instead of packets. // Return sequence number to caller, if requested if ( pOutSeqNum ) *pOutSeqNum = hdr->m_unSeqNum; // Send it SendPacketGather( 2, gather, cbSend ); return cbSend; } bool CSteamNetworkConnectionIPv4::BInitConnect( const netadr_t &netadrRemote, SteamDatagramErrMsg &errMsg ) { AssertMsg( !m_pSocket, ""Trying to connect when we already have a socket?"" ); // We're initiating a connection, not being accepted on a listen socket Assert( !m_pParentListenSocket ); // For now we're just assuming each connection will gets its own socket, // on an ephemeral port. Later we could add a setting to enable // sharing of the socket. m_pSocket = OpenUDPSocketBoundToHost( 0, 0, netadrRemote, CRecvPacketCallback( PacketReceived, this ), errMsg ); if ( !m_pSocket ) return false; // We use SteamID validity to denote when our connection has been accepted, // so it's important that it be cleared Assert( m_steamIDRemote.GetEAccountType() == k_EAccountTypeInvalid ); m_steamIDRemote.Clear(); // Let base class do some common initialization uint32 nPeerProtocolVersion = 0; // don't know yet SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); if ( !CSteamNetworkConnectionBase::BInitConnection( nPeerProtocolVersion, usecNow, errMsg ) ) { m_pSocket->Close(); m_pSocket = nullptr; return false; } // We should know our own identity, unless the app has said it's OK to go without this. if ( !m_steamIDLocal.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 ) { V_strcpy_safe( errMsg, ""Unable to determine local SteamID. Not logged into Steam?"" ); return false; } // Start the connection state machine, and send the first request packet. CheckConnectionStateAndSetNextThinkTime( usecNow ); return true; } bool CSteamNetworkConnectionIPv4::BCanSendEndToEndConnectRequest() const { return m_pSocket != nullptr; } bool CSteamNetworkConnectionIPv4::BCanSendEndToEndData() const { return m_pSocket != nullptr; } void CSteamNetworkConnectionIPv4::SendEndToEndConnectRequest( SteamNetworkingMicroseconds usecNow ) { Assert( !m_pParentListenSocket ); Assert( GetState() == k_ESteamNetworkingConnectionState_Connecting ); // Why else would we be doing this? Assert( m_unConnectionIDLocal ); CMsgSteamSockets_UDP_ChallengeRequest msg; msg.set_connection_id( m_unConnectionIDLocal ); //msg.set_client_steam_id( m_steamIDLocal.ConvertToUint64() ); msg.set_my_timestamp( usecNow ); msg.set_protocol_version( k_nCurrentProtocolVersion ); // Send it, with padding SendPaddedMsg( k_ESteamNetworkingUDPMsg_ChallengeRequest, msg ); // They are supposed to reply with a timestamps, from which we can estimate the ping. // So this counts as a ping request m_statsEndToEnd.TrackSentPingRequest( usecNow, false ); } void CSteamNetworkConnectionIPv4::SendEndToEndPing( bool bUrgent, SteamNetworkingMicroseconds usecNow ) { SendStatsMsg( bUrgent ? k_EStatsReplyRequest_Immediate : k_EStatsReplyRequest_DelayedOK, usecNow ); } void CSteamNetworkConnectionIPv4::ThinkConnection( SteamNetworkingMicroseconds usecNow ) { // Check if we have stats we need to flush out if ( BStateIsConnectedForWirePurposes() ) { // Do we need to send something immediately, for any reason? if ( m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow ) || m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) ) { SendStatsMsg( k_EStatsReplyRequest_None, usecNow ); // Make sure that took care of what we needed! Assert( !m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow ) ); Assert( !m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) ); } } } bool CSteamNetworkConnectionIPv4::BBeginAccept( CSteamNetworkListenSocketStandard *pParent, const netadr_t &adrFrom, CSharedSocket *pSharedSock, CSteamID steamID, uint32 unConnectionIDRemote, uint32 nPeerProtocolVersion, const CMsgSteamDatagramCertificateSigned &msgCert, const CMsgSteamDatagramSessionCryptInfoSigned &msgCryptSessionInfo, SteamDatagramErrMsg &errMsg ) { AssertMsg( !m_pSocket, ""Trying to accept when we already have a socket?"" ); // Get an interface just to talk just to this guy m_pSocket = pSharedSock->AddRemoteHost( adrFrom, CRecvPacketCallback( PacketReceived, this ) ); if ( !m_pSocket ) { V_strcpy_safe( errMsg, ""Unable to create a bound socket on the shared socket."" ); return false; } m_steamIDRemote = steamID; m_unConnectionIDRemote = unConnectionIDRemote; m_netAdrRemote = adrFrom; pParent->AddChildConnection( this ); // Let base class do some common initialization SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); if ( !CSteamNetworkConnectionBase::BInitConnection( nPeerProtocolVersion, usecNow, errMsg ) ) { m_pSocket->Close(); m_pSocket = nullptr; return false; } // Process crypto handshake now if ( !BRecvCryptoHandshake( msgCert, msgCryptSessionInfo, true ) ) { m_pSocket->Close(); m_pSocket = nullptr; return false; } // OK return true; } EResult CSteamNetworkConnectionIPv4::APIAcceptConnection() { SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); // Send the message SendConnectOK( usecNow ); // We are fully connected ConnectionState_Connected( usecNow ); // OK return k_EResultOK; } void CSteamNetworkConnectionIPv4::SendMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg ) { uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ]; pkt[0] = nMsgID; int cbPkt = msg.ByteSize()+1; if ( cbPkt > sizeof(pkt) ) { AssertMsg3( false, ""Msg type %d is %d bytes, larger than MTU of %d bytes"", int( nMsgID ), cbPkt, (int)sizeof(pkt) ); return; } uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt+1 ); Assert( cbPkt == pEnd - pkt ); SendPacket( pkt, cbPkt ); } void CSteamNetworkConnectionIPv4::SendPaddedMsg( uint8 nMsgID, const google::protobuf::MessageLite &msg ) { uint8 pkt[ k_cbSteamNetworkingSocketsMaxUDPMsgLen ]; V_memset( pkt, 0, sizeof(pkt) ); // don't send random bits from our process memory over the wire! UDPPaddedMessageHdr *hdr = (UDPPaddedMessageHdr *)pkt; int nMsgLength = msg.ByteSize(); if ( nMsgLength + sizeof(*hdr) > k_cbSteamNetworkingSocketsMaxUDPMsgLen ) { AssertMsg3( false, ""Msg type %d is %d bytes, larger than MTU of %d bytes"", int( nMsgID ), int( nMsgLength + sizeof(*hdr) ), (int)sizeof(pkt) ); return; } hdr->m_nMsgID = nMsgID; hdr->m_nMsgLength = LittleWord( uint16( nMsgLength ) ); uint8 *pEnd = msg.SerializeWithCachedSizesToArray( pkt + sizeof(*hdr) ); int cbPkt = pEnd - pkt; Assert( cbPkt == int( sizeof(*hdr) + nMsgLength ) ); cbPkt = MAX( cbPkt, k_cbSteamNetworkingMinPaddedPacketSize ); SendPacket( pkt, cbPkt ); } void CSteamNetworkConnectionIPv4::SendPacket( const void *pkt, int cbPkt ) { iovec temp; temp.iov_base = const_cast( pkt ); temp.iov_len = cbPkt; SendPacketGather( 1, &temp, cbPkt ); } void CSteamNetworkConnectionIPv4::SendPacketGather( int nChunks, const iovec *pChunks, int cbSendTotal ) { // Safety if ( !m_pSocket ) { AssertMsg( false, ""Attemt to send packet, but socket has been closed!"" ); return; } // Update stats m_statsEndToEnd.TrackSentPacket( cbSendTotal ); // Hand over to operating system m_pSocket->BSendRawPacketGather( nChunks, pChunks ); } void CSteamNetworkConnectionIPv4::ConnectionStateChanged( ESteamNetworkingConnectionState eOldState ) { CSteamNetworkConnectionBase::ConnectionStateChanged( eOldState ); switch ( GetState() ) { case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4 default: Assert( false ); case k_ESteamNetworkingConnectionState_None: case k_ESteamNetworkingConnectionState_Dead: return; case k_ESteamNetworkingConnectionState_FinWait: case k_ESteamNetworkingConnectionState_ProblemDetectedLocally: SendConnectionClosedOrNoConnection(); break; case k_ESteamNetworkingConnectionState_Linger: break; case k_ESteamNetworkingConnectionState_Connecting: case k_ESteamNetworkingConnectionState_Connected: case k_ESteamNetworkingConnectionState_ClosedByPeer: break; } } #define ReportBadPacketIPv4( pszMsgType, /* fmt */ ... ) \\ ReportBadPacketFrom( m_pSocket->GetRemoteHostAddr(), pszMsgType, __VA_ARGS__ ) void CSteamNetworkConnectionIPv4::PacketReceived( const void *pvPkt, int cbPkt, const netadr_t &adrFrom, CSteamNetworkConnectionIPv4 *pSelf ) { const uint8 *pPkt = static_cast( pvPkt ); SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); pSelf->m_statsEndToEnd.TrackRecvPacket( cbPkt, usecNow ); // FIXME - We really shouldn't do this until we know it is valid and hasn't been spoofed! if ( cbPkt < 5 ) { ReportBadPacket( ""packet"", ""%d byte packet is too small"", cbPkt ); return; } if ( *pPkt & 0x80 ) { pSelf->Received_Data( pPkt, cbPkt, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeReply ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ChallengeReply, msg ) pSelf->Received_ChallengeReply( msg, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectOK ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectOK, msg ); pSelf->Received_ConnectOK( msg, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectionClosed ) { ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ConnectionClosed, msg ) pSelf->Received_ConnectionClosed( msg, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_NoConnection ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_NoConnection, msg ) pSelf->Received_NoConnection( msg, usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ChallengeRequest ) { ParsePaddedPacket( pvPkt, cbPkt, CMsgSteamSockets_UDP_ChallengeRequest, msg ) pSelf->Received_ChallengeOrConnectRequest( ""ChallengeRequest"", msg.connection_id(), usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_ConnectRequest ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_ConnectRequest, msg ) pSelf->Received_ChallengeOrConnectRequest( ""ConnectRequest"", msg.client_connection_id(), usecNow ); } else if ( *pPkt == k_ESteamNetworkingUDPMsg_Stats ) { ParseProtobufBody( pPkt+1, cbPkt-1, CMsgSteamSockets_UDP_Stats, msg ) pSelf->Received_Stats( msg, usecNow ); } else { ReportBadPacket( ""packet"", ""Lead byte 0x%02x not a known message ID"", *pPkt ); } } std::string DescribeStatsContents( const CMsgSteamSockets_UDP_Stats &msg ) { std::string sWhat; if ( msg.flags() & msg.ACK_REQUEST_E2E ) sWhat += "" request_ack""; if ( msg.flags() & msg.ACK_REQUEST_IMMEDIATE ) sWhat += "" request_ack_immediate""; if ( msg.stats().has_lifetime() ) sWhat += "" stats.life""; if ( msg.stats().has_instantaneous() ) sWhat += "" stats.rate""; if ( msg.ack_e2e_size() > 0 ) sWhat += "" ack""; return sWhat; } void CSteamNetworkConnectionIPv4::RecvStats( const CMsgSteamSockets_UDP_Stats &msgStatsIn, bool bInline, SteamNetworkingMicroseconds usecNow ) { // Connection quality stats? if ( msgStatsIn.has_stats() ) m_statsEndToEnd.ProcessMessage( msgStatsIn.stats(), usecNow ); // Receive acks, if any m_statsEndToEnd.RecvPackedAcks( msgStatsIn.ack_e2e(), usecNow ); // Spew appropriately if ( g_eSteamDatagramDebugOutputDetailLevel >= k_ESteamNetworkingSocketsDebugOutputType_Verbose ) { std::string sWhat = DescribeStatsContents( msgStatsIn ); SpewVerbose( ""Recvd %s stats from %s @ %s:%s\\n"", bInline ? ""inline"" : ""standalone"", m_steamIDRemote.Render(), CUtlNetAdrRender( m_pSocket->GetRemoteHostAddr() ).String(), sWhat.c_str() ); } // Check if we need to reply, either now or later if ( BStateIsConnectedForWirePurposes() ) { // Check for queuing outgoing acks bool bImmediate = ( msgStatsIn.flags() & msgStatsIn.ACK_REQUEST_IMMEDIATE ) != 0; if ( ( msgStatsIn.flags() & msgStatsIn.ACK_REQUEST_E2E ) || msgStatsIn.has_stats() ) { m_statsEndToEnd.QueueOutgoingAck( msgStatsIn.seq_num(), bImmediate, usecNow ); } // Do we need to send an immediate reply? if ( m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) || m_statsEndToEnd.BNeedToSendStatsOrAcks( usecNow ) ) { // Send a stats message SendStatsMsg( k_EStatsReplyRequest_None, usecNow ); } } } void CSteamNetworkConnectionIPv4::TrackSentStats( const CMsgSteamSockets_UDP_Stats &msgStatsOut, bool bInline, SteamNetworkingMicroseconds usecNow ) { // What effective flags will be received? uint32 nSentFlags = msgStatsOut.flags(); if ( msgStatsOut.has_stats() ) nSentFlags |= msgStatsOut.ACK_REQUEST_E2E; if ( nSentFlags & msgStatsOut.ACK_REQUEST_E2E ) { bool bAllowDelayedReply = ( nSentFlags & msgStatsOut.ACK_REQUEST_IMMEDIATE ) == 0; // Record that we sent stats and are waiting for peer to ack if ( msgStatsOut.has_stats() ) { m_statsEndToEnd.TrackSentStats( msgStatsOut.stats(), usecNow, bAllowDelayedReply ); } else if ( ( nSentFlags & msgStatsOut.ACK_REQUEST_E2E ) ) { m_statsEndToEnd.TrackSentMessageExpectingSeqNumAck( usecNow, bAllowDelayedReply ); } } // Did we send any acks? m_statsEndToEnd.TrackSentPackedAcks( msgStatsOut.ack_e2e() ); // Spew appropriately if ( g_eSteamDatagramDebugOutputDetailLevel >= k_ESteamNetworkingSocketsDebugOutputType_Verbose ) { std::string sWhat = DescribeStatsContents( msgStatsOut ); SpewVerbose( ""Sent %s stats to %s @ %s:%s\\n"", bInline ? ""inline"" : ""standalone"", m_steamIDRemote.Render(), CUtlNetAdrRender( m_pSocket->GetRemoteHostAddr() ).String(), sWhat.c_str() ); } } void CSteamNetworkConnectionIPv4::SendStatsMsg( EStatsReplyRequest eReplyRequested, SteamNetworkingMicroseconds usecNow ) { CMsgSteamSockets_UDP_Stats msg; if ( m_unConnectionIDRemote ) msg.set_to_connection_id( m_unConnectionIDRemote ); msg.set_from_connection_id( m_unConnectionIDLocal ); msg.set_seq_num( m_statsEndToEnd.GetNextSendSequenceNumber( usecNow ) ); // What flags should we set? uint32 nFlags = 0; if ( eReplyRequested == k_EStatsReplyRequest_Immediate || m_statsEndToEnd.BNeedToSendPingImmediate( usecNow ) ) nFlags |= msg.ACK_REQUEST_E2E | msg.ACK_REQUEST_IMMEDIATE; else if ( eReplyRequested == k_EStatsReplyRequest_DelayedOK || m_statsEndToEnd.BNeedToSendKeepalive( usecNow ) || m_statsEndToEnd.BReadyToSendTracerPing( usecNow ) ) nFlags |= msg.ACK_REQUEST_E2E; // Need to send any connection stats stats? if ( m_statsEndToEnd.BReadyToSendStats( usecNow ) ) m_statsEndToEnd.PopulateMessage( *msg.mutable_stats(), usecNow ); // Any pending acks? PutEndToEndAcksIntoMessage( msg, m_statsEndToEnd, usecNow ); // Always set flags into message, even if they can be implied by the presence of stats msg.set_flags( nFlags ); // Send it SendMsg( k_ESteamNetworkingUDPMsg_Stats, msg ); // Track that we sent stats TrackSentStats( msg, false, usecNow ); } void CSteamNetworkConnectionIPv4::Received_Data( const uint8 *pPkt, int cbPkt, SteamNetworkingMicroseconds usecNow ) { if ( cbPkt < sizeof(UDPDataMsgHdr) ) { ReportBadPacketIPv4( ""DataPacket"", ""Packet of size %d is too small."", cbPkt ); return; } // Check cookie const UDPDataMsgHdr *hdr = (const UDPDataMsgHdr *)pPkt; if ( LittleDWord( hdr->m_unToConnectionID ) != m_unConnectionIDLocal ) { // Wrong session. It could be an old session, or it could be spoofed. ReportBadPacketIPv4( ""DataPacket"", ""Incorrect connection ID"" ); if ( BCheckGlobalSpamReplyRateLimit( usecNow ) ) { SendNoConnection( LittleDWord( hdr->m_unToConnectionID ), 0 ); } return; } uint16 nWirePktNumber = LittleWord( hdr->m_unSeqNum ); m_statsEndToEnd.TrackRecvSequencedPacket( nWirePktNumber, usecNow, 0 ); // Check state switch ( GetState() ) { case k_ESteamNetworkingConnectionState_Dead: case k_ESteamNetworkingConnectionState_None: case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4 default: Assert( false ); return; case k_ESteamNetworkingConnectionState_ClosedByPeer: case k_ESteamNetworkingConnectionState_FinWait: case k_ESteamNetworkingConnectionState_ProblemDetectedLocally: SendConnectionClosedOrNoConnection(); return; case k_ESteamNetworkingConnectionState_Linger: // FIXME: What should we do here? We are half-closed here, so this // data is definitely going to be ignored. Do we need to communicate // that state to the remote host somehow? return; case k_ESteamNetworkingConnectionState_Connecting: // Ignore it. We don't have the SteamID of whoever is on the other end yet, // their encryption keys, etc. The most likely cause is that a server sent // a ConnectOK, which dropped. So they think we're connected but we don't // have everything yet. return; case k_ESteamNetworkingConnectionState_Connected: // We'll process the chunk break; } const uint8 *pIn = pPkt + sizeof(*hdr); const uint8 *pPktEnd = pPkt + cbPkt; // Inline stats? uint32 cbStatsMsgIn = 0; if ( hdr->m_unMsgFlags & hdr->kFlag_ProtobufBlob ) { //Msg_Verbose( ""Received inline stats from %s"", server.m_szName ); pIn = DeserializeVarInt( pIn, pPktEnd, cbStatsMsgIn ); if ( pIn == NULL ) { ReportBadPacketIPv4( ""DataPacket"", ""Failed to varint decode size of stats blob"" ); return; } if ( pIn + cbStatsMsgIn > pPktEnd ) { ReportBadPacketIPv4( ""DataPacket"", ""stats message size doesn't make sense. Stats message size %d, packet size %d"", cbStatsMsgIn, cbPkt ); return; } CMsgSteamSockets_UDP_Stats msgStatsIn; if ( !msgStatsIn.ParseFromArray( pIn, cbStatsMsgIn ) ) { ReportBadPacketIPv4( ""DataPacket"", ""protobuf failed to parse inline stats message"" ); return; } // Shove sequence number so we know what acks to pend, etc msgStatsIn.set_seq_num( nWirePktNumber ); // Process the stats RecvStats( msgStatsIn, true, usecNow ); // Advance pointer pIn += cbStatsMsgIn; } RecvDataChunk( nWirePktNumber, pIn, pPktEnd - pIn, cbPkt, usecNow ); } void CSteamNetworkConnectionIPv4::Received_ChallengeReply( const CMsgSteamSockets_UDP_ChallengeReply &msg, SteamNetworkingMicroseconds usecNow ) { // We should only be getting this if we are the ""client"" if ( m_pParentListenSocket ) { ReportBadPacketIPv4( ""ChallengeReply"", ""Shouldn't be receiving this unless on accepted connections, only connections initiated locally."" ); return; } // Ignore if we're not trying to connect if ( GetState() != k_ESteamNetworkingConnectionState_Connecting ) return; // Check session ID to make sure they aren't spoofing. if ( msg.connection_id() != m_unConnectionIDLocal ) { ReportBadPacketIPv4( ""ChallengeReply"", ""Incorrect connection ID. Message is stale or could be spoofed, ignoring."" ); return; } if ( msg.protocol_version() < k_nMinRequiredProtocolVersion ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_Generic, ""Peer is running old software and needs to be udpated"" ); return; } // Update ping, if they replied with the timestamp if ( msg.has_your_timestamp() ) { SteamNetworkingMicroseconds usecElapsed = usecNow - (SteamNetworkingMicroseconds)msg.your_timestamp(); if ( usecElapsed < 0 || usecElapsed > 2*k_nMillion ) { SpewWarning( ""Ignoring weird timestamp %llu in ChallengeReply, current time is %llu.\\n"", (unsigned long long)msg.your_timestamp(), usecNow ); } else { int nPing = (usecElapsed + 500 ) / 1000; m_statsEndToEnd.m_ping.ReceivedPing( nPing, usecNow ); } } // Make sure we have the crypt info that we need if ( !m_msgSignedCertLocal.has_cert() || !m_msgSignedCryptLocal.has_info() ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_InternalError, ""Tried to connect request, but crypt not ready"" ); return; } // Remember protocol version. They should send it again in the connect OK, but we have a valid value now, // so we might as well save it m_statsEndToEnd.m_nPeerProtocolVersion = msg.protocol_version(); // Reply with the challenge data and our SteamID CMsgSteamSockets_UDP_ConnectRequest msgConnectRequest; msgConnectRequest.set_client_connection_id( m_unConnectionIDLocal ); msgConnectRequest.set_challenge( msg.challenge() ); msgConnectRequest.set_client_steam_id( m_steamIDLocal.ConvertToUint64() ); msgConnectRequest.set_my_timestamp( usecNow ); if ( m_statsEndToEnd.m_ping.m_nSmoothedPing >= 0 ) msgConnectRequest.set_ping_est_ms( m_statsEndToEnd.m_ping.m_nSmoothedPing ); *msgConnectRequest.mutable_cert() = m_msgSignedCertLocal; *msgConnectRequest.mutable_crypt() = m_msgSignedCryptLocal; msgConnectRequest.set_protocol_version( k_nCurrentProtocolVersion ); SendMsg( k_ESteamNetworkingUDPMsg_ConnectRequest, msgConnectRequest ); // Reset timeout/retry for this reply. But if it fails, we'll start // the whole handshake over again. It keeps the code simpler, and the // challenge value has a relatively short expiry anyway. m_usecWhenSentConnectRequest = usecNow; EnsureMinThinkTime( usecNow + k_usecConnectRetryInterval ); // They are supposed to reply with a timestamps, from which we can estimate the ping. // So this counts as a ping request m_statsEndToEnd.TrackSentPingRequest( usecNow, false ); } void CSteamNetworkConnectionIPv4::Received_ConnectOK( const CMsgSteamSockets_UDP_ConnectOK &msg, SteamNetworkingMicroseconds usecNow ) { // We should only be getting this if we are the ""client"" if ( m_pParentListenSocket ) { ReportBadPacketIPv4( ""ConnectOK"", ""Shouldn't be receiving this unless on accepted connections, only connections initiated locally."" ); return; } // Check connection ID to make sure they aren't spoofing and it's the same connection we think it is if ( msg.client_connection_id() != m_unConnectionIDLocal ) { ReportBadPacketIPv4( ""ConnectOK"", ""Incorrect connection ID. Message is stale or could be spoofed, ignoring."" ); return; } // Who are they? We'll authenticate their cert below CSteamID steamIDRemote( uint64( msg.server_steam_id() ) ); if ( !steamIDRemote.IsValid() && steamdatagram_ip_allow_connections_without_auth == 0 ) { ReportBadPacketIPv4( ""ConnectOK"", ""Invalid server_steam_id."" ); return; } // Make sure they are still who we think they are if ( m_steamIDRemote.IsValid() && m_steamIDRemote != steamIDRemote ) { ReportBadPacketIPv4( ""ConnectOK"", ""server_steam_id doesn't match who we expect to be connecting to!"" ); return; } // Update ping, if they replied a timestamp if ( msg.has_your_timestamp() ) { SteamNetworkingMicroseconds usecElapsed = usecNow - (SteamNetworkingMicroseconds)msg.your_timestamp() - msg.delay_time_usec(); if ( usecElapsed < 0 || usecElapsed > 2*k_nMillion ) { SpewWarning( ""Ignoring weird timestamp %llu in ConnectOK, current time is %llu, remote delay was %lld.\\n"", (unsigned long long)msg.your_timestamp(), usecNow, (long long)msg.delay_time_usec() ); } else { int nPing = (usecElapsed + 500 ) / 1000; m_statsEndToEnd.m_ping.ReceivedPing( nPing, usecNow ); } } // Check state switch ( GetState() ) { case k_ESteamNetworkingConnectionState_Dead: case k_ESteamNetworkingConnectionState_None: case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4 default: Assert( false ); return; case k_ESteamNetworkingConnectionState_ClosedByPeer: case k_ESteamNetworkingConnectionState_FinWait: case k_ESteamNetworkingConnectionState_ProblemDetectedLocally: SendConnectionClosedOrNoConnection(); return; case k_ESteamNetworkingConnectionState_Linger: case k_ESteamNetworkingConnectionState_Connected: // We already know we were able to establish the connection. // Just ignore this packet return; case k_ESteamNetworkingConnectionState_Connecting: break; } if ( msg.protocol_version() < k_nMinRequiredProtocolVersion ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Misc_Generic, ""Peer is running old software and needs to be udpated"" ); return; } m_statsEndToEnd.m_nPeerProtocolVersion = msg.protocol_version(); // New peers should send us their connection ID m_unConnectionIDRemote = msg.server_connection_id(); if ( ( m_unConnectionIDRemote & 0xffff ) == 0 ) { ConnectionState_ProblemDetectedLocally( k_ESteamNetConnectionEnd_Remote_BadCrypt, ""Didn't send valid connection ID"" ); return; } m_steamIDRemote = steamIDRemote; // Check the certs, save keys, etc if ( !BRecvCryptoHandshake( msg.cert(), msg.crypt(), false ) ) { Assert( GetState() == k_ESteamNetworkingConnectionState_ProblemDetectedLocally ); ReportBadPacketIPv4( ""ConnectOK"", ""Failed crypto init. %s"", m_szEndDebug ); return; } // Generic connection code will take it from here. ConnectionState_Connected( usecNow ); } void CSteamNetworkConnectionIPv4::Received_ConnectionClosed( const CMsgSteamSockets_UDP_ConnectionClosed &msg, SteamNetworkingMicroseconds usecNow ) { // Give them a reply to let them know we heard from them. If it's the right connection ID, // then they probably aren't spoofing and it's critical that we give them an ack! // // If the wrong connection ID, then it could be an old connection so we'd like to send a reply // to let them know that they can stop telling us the connection is closed. // However, it could just be random garbage, so we need to protect ourselves from abuse, // so limit how many of these we send. bool bConnectionIDMatch = msg.to_connection_id() == m_unConnectionIDLocal || ( msg.to_connection_id() == 0 && msg.from_connection_id() && msg.from_connection_id() == m_unConnectionIDRemote ); // they might not know our ID yet, if they are a client aborting the connection really early. if ( bConnectionIDMatch || BCheckGlobalSpamReplyRateLimit( usecNow ) ) { // Send a reply, echoing exactly what they sent to us CMsgSteamSockets_UDP_NoConnection msgReply; if ( msg.to_connection_id() ) msgReply.set_from_connection_id( msg.to_connection_id() ); if ( msg.from_connection_id() ) msgReply.set_to_connection_id( msg.from_connection_id() ); SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msgReply ); } // If incorrect connection ID, then that's all we'll do, since this packet actually // has nothing to do with current connection at all. if ( !bConnectionIDMatch ) return; // Generic connection code will take it from here. ConnectionState_ClosedByPeer( msg.reason_code(), msg.debug().c_str() ); } void CSteamNetworkConnectionIPv4::Received_NoConnection( const CMsgSteamSockets_UDP_NoConnection &msg, SteamNetworkingMicroseconds usecNow ) { // Make sure it's an ack of something we would have sent if ( msg.to_connection_id() != m_unConnectionIDLocal || msg.from_connection_id() != m_unConnectionIDRemote ) { ReportBadPacketIPv4( ""NoConnection"", ""Old/incorrect connection ID. Message is for a stale connection, or is spoofed. Ignoring."" ); return; } // Generic connection code will take it from here. ConnectionState_ClosedByPeer( 0, nullptr ); } void CSteamNetworkConnectionIPv4::Received_Stats( const CMsgSteamSockets_UDP_Stats &msg, SteamNetworkingMicroseconds usecNow ) { if ( msg.to_connection_id() == 0 ) { ReportBadPacketIPv4( ""Stats"", ""Missing connection ID."" ); return; } // Check connection ID to make sure they aren't spoofing and it's the same connection we think it is bool bConnectionIDMatch = msg.to_connection_id() == m_unConnectionIDLocal || ( msg.to_connection_id() == 0 && msg.from_connection_id() && msg.from_connection_id() == m_unConnectionIDRemote ); // they might not know our ID yet, if they are a client aborting the connection really early. if ( !bConnectionIDMatch ) { if ( BCheckGlobalSpamReplyRateLimit( usecNow ) ) { CMsgSteamSockets_UDP_NoConnection msgReply; if ( msg.to_connection_id() ) msgReply.set_from_connection_id( msg.to_connection_id() ); if ( msg.from_connection_id() ) msgReply.set_to_connection_id( msg.from_connection_id() ); SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msgReply ); } ReportBadPacketIPv4( ""Stats"", ""Old/incorrect connection ID. Message is for a stale connection, or is spoofed. Ignoring."" ); return; } // Update bookkeeping, we received a sequence number RecvNonDataSequencedPacket( msg.seq_num(), usecNow ); // Process the incoming stats, and if it warrants an immediate reply, go ahead and send it now RecvStats( msg, false, usecNow ); } void CSteamNetworkConnectionIPv4::Received_ChallengeOrConnectRequest( const char *pszDebugPacketType, uint32 unPacketConnectionID, SteamNetworkingMicroseconds usecNow ) { // If wrong connection ID, then check for sending a generic reply and bail if ( unPacketConnectionID != m_unConnectionIDRemote ) { ReportBadPacketIPv4( pszDebugPacketType, ""Incorrect connection ID, when we do have a connection for this address. Could be spoofed, ignoring."" ); // Let's not send a reply in this case //if ( BCheckGlobalSpamReplyRateLimit( usecNow ) ) // SendNoConnection( unPacketConnectionID ); return; } // Check state switch ( GetState() ) { case k_ESteamNetworkingConnectionState_Dead: case k_ESteamNetworkingConnectionState_None: case k_ESteamNetworkingConnectionState_FindingRoute: // not used for IPv4 default: Assert( false ); return; case k_ESteamNetworkingConnectionState_ClosedByPeer: case k_ESteamNetworkingConnectionState_FinWait: case k_ESteamNetworkingConnectionState_ProblemDetectedLocally: SendConnectionClosedOrNoConnection(); return; case k_ESteamNetworkingConnectionState_Connecting: // We're waiting on the application. So we'll just have to ignore. break; case k_ESteamNetworkingConnectionState_Linger: case k_ESteamNetworkingConnectionState_Connected: if ( !m_pParentListenSocket ) { // WAT? We initiated this connection, so why are they requesting to connect? ReportBadPacketIPv4( pszDebugPacketType, ""We are the 'client' who initiated the connection, so 'server' shouldn't be sending us this!"" ); return; } // This is totally legit and possible. Our earlier reply might have dropped, and they are re-sending SendConnectOK( usecNow ); return; } } void CSteamNetworkConnectionIPv4::SendConnectionClosedOrNoConnection() { if ( GetState() == k_ESteamNetworkingConnectionState_ClosedByPeer ) { SendNoConnection( m_unConnectionIDLocal, m_unConnectionIDRemote ); } else { CMsgSteamSockets_UDP_ConnectionClosed msg; msg.set_from_connection_id( m_unConnectionIDLocal ); if ( m_unConnectionIDRemote ) msg.set_to_connection_id( m_unConnectionIDRemote ); msg.set_reason_code( m_eEndReason ); if ( m_szEndDebug[0] ) msg.set_debug( m_szEndDebug ); SendPaddedMsg( k_ESteamNetworkingUDPMsg_ConnectionClosed, msg ); } } void CSteamNetworkConnectionIPv4::SendNoConnection( uint32 unFromConnectionID, uint32 unToConnectionID ) { CMsgSteamSockets_UDP_NoConnection msg; if ( unFromConnectionID == 0 && unToConnectionID == 0 ) { AssertMsg( false, ""Can't send NoConnection, we need at least one of from/to connection ID!"" ); return; } if ( unFromConnectionID ) msg.set_from_connection_id( unFromConnectionID ); if ( unToConnectionID ) msg.set_to_connection_id( unToConnectionID ); SendMsg( k_ESteamNetworkingUDPMsg_NoConnection, msg ); } void CSteamNetworkConnectionIPv4::SendConnectOK( SteamNetworkingMicroseconds usecNow ) { Assert( m_unConnectionIDLocal ); Assert( m_unConnectionIDRemote ); Assert( m_pParentListenSocket ); Assert( m_msgSignedCertLocal.has_cert() ); Assert( m_msgSignedCryptLocal.has_info() ); CMsgSteamSockets_UDP_ConnectOK msg; msg.set_client_connection_id( m_unConnectionIDRemote ); msg.set_server_connection_id( m_unConnectionIDLocal ); msg.set_server_steam_id( m_steamIDLocal.ConvertToUint64() ); *msg.mutable_cert() = m_msgSignedCertLocal; *msg.mutable_crypt() = m_msgSignedCryptLocal; msg.set_protocol_version( k_nCurrentProtocolVersion ); // Do we have a timestamp? if ( m_usecWhenReceivedHandshakeRemoteTimestamp ) { SteamNetworkingMicroseconds usecElapsed = usecNow - m_usecWhenReceivedHandshakeRemoteTimestamp; Assert( usecElapsed >= 0 ); if ( usecElapsed < 4*k_nMillion ) { msg.set_your_timestamp( m_ulHandshakeRemoteTimestamp ); msg.set_delay_time_usec( usecElapsed ); } else { SpewWarning( ""Discarding handshake timestamp that's %lldms old, not sending in ConnectOK\\n"", usecElapsed/1000 ); m_usecWhenReceivedHandshakeRemoteTimestamp = 0; } } // Send it, with padding SendMsg( k_ESteamNetworkingUDPMsg_ConnectOK, msg ); } ///////////////////////////////////////////////////////////////////////////// // // Loopback connections // ///////////////////////////////////////////////////////////////////////////// CSteamNetworkConnectionlocalhostLoopback::CSteamNetworkConnectionlocalhostLoopback( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface ) : CSteamNetworkConnectionIPv4( pSteamNetworkingSocketsInterface ) { } bool CSteamNetworkConnectionlocalhostLoopback::BAllowRemoteUnsignedCert() { return true; } void CSteamNetworkConnectionlocalhostLoopback::InitConnectionCrypto( SteamNetworkingMicroseconds usecNow ) { InitLocalCryptoWithUnsignedCert(); } void CSteamNetworkConnectionlocalhostLoopback::PostConnectionStateChangedCallback( ESteamNetworkingConnectionState eOldAPIState, ESteamNetworkingConnectionState eNewAPIState ) { // Don't post any callbacks for the initial transitions. if ( eNewAPIState == k_ESteamNetworkingConnectionState_Connected || eNewAPIState == k_ESteamNetworkingConnectionState_Connected ) return; // But post callbacks for these guys CSteamNetworkConnectionIPv4::PostConnectionStateChangedCallback( eOldAPIState, eNewAPIState ); } bool CSteamNetworkConnectionlocalhostLoopback::APICreateSocketPair( CSteamNetworkingSockets *pSteamNetworkingSocketsInterface, CSteamNetworkConnectionlocalhostLoopback *pConn[2] ) { SteamDatagramErrMsg errMsg; pConn[1] = new CSteamNetworkConnectionlocalhostLoopback( pSteamNetworkingSocketsInterface ); pConn[0] = new CSteamNetworkConnectionlocalhostLoopback( pSteamNetworkingSocketsInterface ); if ( !pConn[0] || !pConn[1] ) { failed: delete pConn[0]; pConn[0] = nullptr; delete pConn[1]; pConn[1] = nullptr; return false; } IBoundUDPSocket *sock[2]; if ( !CreateBoundSocketPair( CRecvPacketCallback( CSteamNetworkConnectionIPv4::PacketReceived, (CSteamNetworkConnectionIPv4*)pConn[0] ), CRecvPacketCallback( CSteamNetworkConnectionIPv4::PacketReceived, (CSteamNetworkConnectionIPv4*)pConn[1] ), sock, errMsg ) ) { // Use assert here, because this really should only fail if we have some sort of bug AssertMsg1( false, ""Failed to create UDP socekt pair. %s"", errMsg ); goto failed; } SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); // Initialize both connections for ( int i = 0 ; i < 2 ; ++i ) { pConn[i]->m_pSocket = sock[i]; if ( !pConn[i]->BInitConnection( k_nCurrentProtocolVersion, usecNow, errMsg ) ) goto failed; } // Tie the connections to each other, and mark them as connected for ( int i = 0 ; i < 2 ; ++i ) { CSteamNetworkConnectionlocalhostLoopback *p = pConn[i]; CSteamNetworkConnectionlocalhostLoopback *q = pConn[1-i]; p->m_steamIDRemote = q->m_steamIDLocal; p->m_unConnectionIDRemote = q->m_unConnectionIDLocal; p->m_statsEndToEnd.m_usecTimeLastRecv = usecNow; // Act like we just now received something if ( !p->BRecvCryptoHandshake( q->m_msgSignedCertLocal, q->m_msgSignedCryptLocal, i==0 ) ) { AssertMsg( false, ""BRecvCryptoHandshake failed creating localhost socket pair"" ); goto failed; } p->ConnectionState_Connected( usecNow ); } return true; } void UpdateSNPDebugWindow() { #if defined( WIN32 ) static bool s_bDebugWindowActive = false; static SteamNetworkingMicroseconds usec_debugWindowLastUpdate = 0; static SteamNetworkingMicroseconds usec_debugWindowUpdateTime = k_nMillion / 10; // do we need to enable the window if ( !s_bDebugWindowActive && steamdatagram_snp_debug_window ) { s_bDebugWindowActive = true; InitSNPDebugWindow(); } // or turn it off? if ( s_bDebugWindowActive && !steamdatagram_snp_debug_window ) { s_bDebugWindowActive = false; ShutdownSNPDebugWindow(); return; } SteamNetworkingMicroseconds usecNow = SteamNetworkingSockets_GetLocalTimestamp(); if ( s_bDebugWindowActive && usecNow - usec_debugWindowLastUpdate >= usec_debugWindowUpdateTime ) { usec_debugWindowLastUpdate = usecNow; int numConnections = g_listConnections.Count(); const char **ppText = (const char **)stackalloc( sizeof( char * ) * numConnections ); int n = 0; for ( int i = g_listConnections.CUtlLinkedListHead(); i != (int)g_listConnections.InvalidIndex(); i = g_listConnections.Next( i ) ) { CSteamNetworkConnectionBase *pConn = g_listConnections[ i ]; char *p = new char[4096]; pConn->GetDebugText( p, 4096 ); ppText[ n++ ] = p; } SetSNPDebugText( numConnections, ppText ); for ( int i = 0; i < numConnections; ++i ) { delete [] ppText[ i ]; } RunFrameSNPDebugWindow(); } #endif //defined( WIN32 ) } } // namespace SteamNetworkingSocketsLib ",16241,True,3436.4325508515535,median