text
stringlengths
5
1.04M
// Copyright (c) 2003, 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 "glog-config.h" #ifdef HAVE_USING_OPERATOR #include <iostream> #include <map> #include <ostream> #include <string> #include <vector> #ifdef __GNUC__ // C++0x isn't enabled by default in GCC and libc++ does not have // non-standard ext/* and tr1/unordered_*. # if defined(_LIBCPP_VERSION) # define GLOG_STL_LOGGING_FOR_UNORDERED # else # define GLOG_STL_LOGGING_FOR_EXT_HASH # define GLOG_STL_LOGGING_FOR_EXT_SLIST # define GLOG_STL_LOGGING_FOR_TR1_UNORDERED # endif #endif #include "glog/logging.h" #include "glog/stl_logging.h" #include "googletest.h" using namespace std; #ifdef GLOG_STL_LOGGING_FOR_EXT_HASH using namespace __gnu_cxx; #endif struct user_hash { size_t operator()(int x) const { return x; } }; void TestSTLLogging() { { // Test a sequence. vector<int> v; v.push_back(10); v.push_back(20); v.push_back(30); ostringstream ss; ss << v; EXPECT_EQ(ss.str(), "10 20 30"); vector<int> copied_v(v); CHECK_EQ(v, copied_v); // This must compile. } { // Test a sorted pair associative container. map< int, string > m; m[20] = "twenty"; m[10] = "ten"; m[30] = "thirty"; ostringstream ss; ss << m; EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); map< int, string > copied_m(m); CHECK_EQ(m, copied_m); // This must compile. } #ifdef GLOG_STL_LOGGING_FOR_EXT_HASH { // Test a hashed simple associative container. hash_set<int> hs; hs.insert(10); hs.insert(20); hs.insert(30); ostringstream ss; ss << hs; EXPECT_EQ(ss.str(), "10 20 30"); hash_set<int> copied_hs(hs); CHECK_EQ(hs, copied_hs); // This must compile. } #endif #ifdef GLOG_STL_LOGGING_FOR_EXT_HASH { // Test a hashed pair associative container. hash_map<int, string> hm; hm[10] = "ten"; hm[20] = "twenty"; hm[30] = "thirty"; ostringstream ss; ss << hm; EXPECT_EQ(ss.str(), "(10, ten) (20, twenty) (30, thirty)"); hash_map<int, string> copied_hm(hm); CHECK_EQ(hm, copied_hm); // this must compile } #endif { // Test a long sequence. vector<int> v; string expected; for (int i = 0; i < 100; i++) { v.push_back(i); if (i > 0) expected += ' '; char buf[256]; sprintf(buf, "%d", i); expected += buf; } v.push_back(100); expected += " ..."; ostringstream ss; ss << v; CHECK_EQ(ss.str(), expected.c_str()); } { // Test a sorted pair associative container. // Use a non-default comparison functor. map< int, string, greater<int> > m; m[20] = "twenty"; m[10] = "ten"; m[30] = "thirty"; ostringstream ss; ss << m; EXPECT_EQ(ss.str(), "(30, thirty) (20, twenty) (10, ten)"); map< int, string, greater<int> > copied_m(m); CHECK_EQ(m, copied_m); // This must compile. } #ifdef GLOG_STL_LOGGING_FOR_EXT_HASH { // Test a hashed simple associative container. // Use a user defined hash function. hash_set<int, user_hash> hs; hs.insert(10); hs.insert(20); hs.insert(30); ostringstream ss; ss << hs; EXPECT_EQ(ss.str(), "10 20 30"); hash_set<int, user_hash> copied_hs(hs); CHECK_EQ(hs, copied_hs); // This must compile. } #endif } int main(int, char**) { TestSTLLogging(); std::cout << "PASS\n"; return 0; } #else #include <iostream> int main(int, char**) { std::cout << "We don't support stl_logging for this compiler.\n" << "(we need compiler support of 'using ::operator<<' " << "for this feature.)\n"; return 0; } #endif // HAVE_USING_OPERATOR
// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #define TAO_PEGTL_INTERNAL_FILE_MAPPER_POSIX_HPP #include <sys/mman.h> #include <unistd.h> #include "../config.hpp" #include "file_opener.hpp" #include "../input_error.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { class file_mapper { public: explicit file_mapper( const char* filename ) : file_mapper( file_opener( filename ) ) { } explicit file_mapper( const file_opener& reader ) : m_size( reader.size() ), m_data( static_cast< const char* >( ::mmap( nullptr, m_size, PROT_READ, MAP_PRIVATE, reader.m_fd, 0 ) ) ) { if( ( m_size != 0 ) && ( intptr_t( m_data ) == -1 ) ) { TAO_PEGTL_THROW_INPUT_ERROR( "unable to mmap() file " << reader.m_source << " descriptor " << reader.m_fd ); } } file_mapper( const file_mapper& ) = delete; file_mapper( file_mapper&& ) = delete; ~file_mapper() noexcept { // Legacy C interface requires pointer-to-mutable but does not write through the pointer. ::munmap( const_cast< char* >( m_data ), m_size ); // NOLINT } void operator=( const file_mapper& ) = delete; void operator=( file_mapper&& ) = delete; bool empty() const noexcept { return m_size == 0; } std::size_t size() const noexcept { return m_size; } using iterator = const char*; using const_iterator = const char*; iterator data() const noexcept { return m_data; } iterator begin() const noexcept { return m_data; } iterator end() const noexcept { return m_data + m_size; } std::string string() const { return std::string( m_data, m_size ); } private: const std::size_t m_size; const char* const m_data; }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
/* Nº GRUPO: D25 NOMBRES Y APELLIDOS DE LAS PERSONAS QUE HAN REALIZADO EL CONTROL: JAVIER GÓMEZ MORALEDA MARIO ALCOLEA ALCOLEA */ #include "ParqueDeAtracciones.h" ParqueDeAtracciones::ParqueDeAtracciones() {} /* Función que añade una atraccion al Diccionario de atracciones. Para ello hace uso de iteradores. */ void ParqueDeAtracciones::an_atraccion(const string& nombre_atraccion) { //Iterador que busca en el diccionario de atracciones el valor nombre_atraccion Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccion = _atracciones.busca(nombre_atraccion); Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccionFin = _atracciones.end(); //Compruebo si la atracción NO existe para añadirla if(iAtraccion == iAtraccionFin){ Cola<tNinio> c; _atracciones.inserta(nombre_atraccion, c); } else { throw EAtraccionYaExiste(); } } /* Función que añade un niño al Diccionario de niño. Para ello hace uso de iteradores. */ void ParqueDeAtracciones::an_ninio(const string& nombre_ninio) { //Iterador que busca en el diccionario de niños el valor nombre_ninio Diccionario<tNinio, Diccionario<tAtraccion, int>> ::Iterator iNinio = _ninios.busca(nombre_ninio); Diccionario<tNinio, Diccionario<tAtraccion, int>> ::Iterator iNinioFin = _ninios.end(); //Compruebo si el niño NO existe para añadirlo if (iNinio == iNinioFin) { Diccionario<tAtraccion, int> d; _ninios.inserta(nombre_ninio, d); } else { throw ENinioYaRegistrado(); } } /* Función que añade un niño a la fila de una atracción */ void ParqueDeAtracciones::poner_en_fila(const string& nombre_ninio, const string& nombre_atraccion) { //Iterador que busca en el diccionario de niños el valor nombre_ninio Diccionario<tNinio, Diccionario<tAtraccion, int>> ::Iterator iNinio = _ninios.busca(nombre_ninio); Diccionario<tNinio, Diccionario<tAtraccion, int>> ::Iterator iNinioFin = _ninios.end(); //Iterador que busca en el diccionario de atracciones el valor nombre_atraccion Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccion = _atracciones.busca(nombre_atraccion); Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccionFin = _atracciones.end(); //Si tanto el niño como la atracción existe if (iNinio != iNinioFin && iAtraccion != iAtraccionFin) { //Iterador para el diccionario hash en el que busco si el niño está ya esperando DiccionarioHash<tNinio, tAtraccion> ::ConstIterator iNinioEsperando = _esperando.cbusca(nombre_ninio); DiccionarioHash<tNinio, tAtraccion> ::ConstIterator iNinioEsperandoFin = _esperando.cend(); //Si son iguales, es decir, el niño no está esperando, lo añado al diccionario hash y a la cola del diccionario de atracciones if (iNinioEsperando == iNinioEsperandoFin) { iAtraccion.valor().pon(nombre_ninio); _esperando.inserta(nombre_ninio, nombre_atraccion); } else { throw EAccesoAtraccion(); } } else { throw EAccesoAtraccion(); } } /* Función que avanza una atracción */ void ParqueDeAtracciones::avanzar(const string& nombre_atraccion) { //Iterador que busca en el diccionario de atracciones el valor nombre_atraccion Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccion = _atracciones.busca(nombre_atraccion); Diccionario<tAtraccion, Cola<tNinio>> ::Iterator iAtraccionFin = _atracciones.end(); //Si eiste la atracción if (iAtraccion != iAtraccionFin) { //Compruebo que la cola no esté vacía if (!iAtraccion.valor().esVacia()) { tNinio ninio = iAtraccion.valor().primero(); //Elimino al niño de la tabla hash _esperando.borra(ninio); //Iterador que busca al niño (asumo que existe, de otra forma no podría haberlo encolado) Diccionario<tNinio, Diccionario<tAtraccion, int>> ::Iterator iNinio = _ninios.busca(ninio); //Si el niño ya ha subido en la atracción, aumento el valor de dicha atracción en 1 if (iNinio.valor().contiene(iAtraccion.clave())) { iNinio.valor().inserta(iAtraccion.clave(), iNinio.valor().valorPara(iAtraccion.clave()) + 1); } //En otro caso, la inicializo a 1 else { iNinio.valor().inserta(iAtraccion.clave(), 1); } //Quito al niño de la cola de la atracción iAtraccion.valor().quita(); } } else { throw EAtraccionNoExiste(); } } /* Función que muestra las atraccíones visitadas por un niño */ Lista<string> ParqueDeAtracciones::atracciones_visitadas(const string& nombre_ninio) const { Lista<string> listado; Lista<string> ::Iterator it = listado.begin(); //Iterador que busca en el diccionario de niños el valor nombre_ninio Diccionario<tNinio, Diccionario<tAtraccion, int>> ::ConstIterator iNinio = _ninios.cbusca(nombre_ninio); Diccionario<tNinio, Diccionario<tAtraccion, int>> ::ConstIterator iNinioFin = _ninios.cend(); //Si existe el niño if (iNinio != iNinioFin) { //Iterador para recorrer las atracciones visitadas por el niño Diccionario<tAtraccion, int> ::ConstIterator iAtracciones = iNinio.valor().cbegin(); Diccionario<tAtraccion, int> ::ConstIterator iAtraccionesFin = iNinio.valor().cend(); //Inserto las atracciones en la lista while (iAtracciones != iAtraccionesFin) { listado.insertar(iAtracciones.clave(), it); iAtracciones.next(); } } else { throw ENinioNoRegistrado(); } return listado; } /* Función que muestra el número de visitas de un niño en una atracción */ int ParqueDeAtracciones::numero_visitas(const string& nombre_ninio, const string& nombre_atraccion) const { int contador = 0; //Iterador que busca en el diccionario de niños el valor nombre_ninio Diccionario<tNinio, Diccionario<tAtraccion, int>> ::ConstIterator iNinio = _ninios.cbusca(nombre_ninio); Diccionario<tNinio, Diccionario<tAtraccion, int>> ::ConstIterator iNinioFin = _ninios.cend(); //Iterador que busca en el diccionario de atracciones el valor nombre_atraccion Diccionario<tAtraccion, Cola<tNinio>> ::ConstIterator iAtraccion = _atracciones.cbusca(nombre_atraccion); Diccionario<tAtraccion, Cola<tNinio>> ::ConstIterator iAtraccionFin = _atracciones.cend(); //Si tanto el niño como la atracción existen if (iNinio != iNinioFin && iAtraccion != iAtraccionFin) { //Iterador que busca la atracción en el diccionario de atracciones de un niño Diccionario<tAtraccion, int> ::ConstIterator iAtracciones = iNinio.valor().cbusca(nombre_atraccion); Diccionario<tAtraccion, int> ::ConstIterator iAtraccionesFin = iNinio.valor().cend(); //Si el niño ha visitado esa atracción, guardo su valor en el contador if (iAtracciones != iAtraccionesFin) { contador = iAtracciones.valor(); } } else { throw EConsultaNumViajes(); } return contador; }
#include "pch.h" #include <ang/graphics/angraph.hpp> #include "ang_inlines.h" #include "vector_specialization.inl" #if defined _DEBUG #define new new(__FILE__, __LINE__) #endif using namespace ang; using namespace ang::graphics; using namespace ang::graphics::reflect; ANG_IMPLEMENT_ENUM(ang::graphics::reflect, var_type, uint, var_type::none); ANG_IMPLEMENT_ENUM(ang::graphics::reflect, var_class, uint, var_class::none); ANG_IMPLEMENT_ENUM(ang::graphics::reflect, var_semantic, uint, var_semantic::none); #define MY_ALLOCATOR ang::memory::default_allocator #define MY_TYPE ang::graphics::reflect::variable_desc_t #include <ang/collections/inline/vector_object_specialization.inl> #undef MY_TYPE #define MY_TYPE ang::graphics::reflect::attribute_desc_t #include <ang/collections/inline/vector_object_specialization.inl> #undef MY_TYPE #undef MY_ALLOCATOR static ang_pair<graphics::reflect::var_type, cstr_t> to_string_var_type_map[] = { { var_type::none, "none" }, { var_type::s8, "s8," }, { var_type::u8, "u8" }, { var_type::s16, "s16" }, { var_type::u16, "u16" }, { var_type::s32, "s32" }, { var_type::u32, "u32" }, { var_type::f32, "f32" }, { var_type::tex1D, "tex1D" }, { var_type::tex2D, "tex2D" }, { var_type::tex3D, "tex3D" }, { var_type::texCube, "texCube" }, { var_type::buffer, "buffer" }, { var_type::block, "structure" } }; static ang_pair<cstr_t, graphics::reflect::var_type> _parse_var_type_map[] = { { "block", var_type::block }, { "buffer", var_type::buffer }, { "f32", var_type::f32 }, { "none", var_type::none }, { "s16", var_type::s16 }, { "s32", var_type::s32 }, { "s8", var_type::s8 }, { "tex1D", var_type::tex1D }, { "tex2D", var_type::tex2D }, { "tex3D", var_type::tex3D }, { "texCube", var_type::texCube }, { "u16", var_type::u16 }, { "u32", var_type::u32 }, { "u8", var_type::u8 } }; var_type_t graphics::reflect::var_type_t::parse(cstr_t cstr) { wsize idx = ang_binary_search<cstr_t>(cstr, _parse_var_type_map); if (idx > array_size(_parse_var_type_map)) return var_type::none; else return _parse_var_type_map[idx].value; } var_type_t graphics::reflect::var_type_t::parse(cwstr_t cstr) { wsize idx = ang_binary_search<cwstr_t>(cstr, _parse_var_type_map); if (idx > array_size(_parse_var_type_map)) return var_type::none; else return _parse_var_type_map[idx].value; } cstr_t graphics::reflect::var_type_t::to_string()const { wsize idx = ang_binary_search(_value, to_string_var_type_map); if (idx > array_size(to_string_var_type_map)) return "none"_s; else return to_string_var_type_map[idx].value; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// static ang_pair<graphics::reflect::var_class, cstr_t> to_string_var_class_map[] = { { var_class::none, "none" }, { var_class::scalar, "scalar" }, { var_class::vec2, "vec2" }, { var_class::vec3, "vec3" }, { var_class::vec4, "vec4" }, { var_class::mat3, "mat3" }, { var_class::mat4, "mat4" } }; static ang_pair<cstr_t, graphics::reflect::var_class> _parse_var_class_map[] = { { "mat2", var_class::mat2 }, { "mat3", var_class::mat3 }, { "mat4", var_class::mat4 }, { "none", var_class::none }, { "scalar", var_class::scalar }, { "vec2", var_class::vec2 }, { "vec3", var_class::vec3 }, { "vec4", var_class::vec4 } }; var_class_t graphics::reflect::var_class_t::parse(cstr_t cstr) { wsize idx = ang_binary_search<cstr_t>(cstr, _parse_var_class_map); if (idx > array_size(_parse_var_class_map)) return var_class::none; else return _parse_var_class_map[idx].value; } var_class_t graphics::reflect::var_class_t::parse(cwstr_t cstr) { wsize idx = ang_binary_search<cwstr_t>(cstr, _parse_var_class_map); if (idx > array_size(_parse_var_class_map)) return var_class::none; else return _parse_var_class_map[idx].value; } cstr_t graphics::reflect::var_class_t::to_string()const { wsize idx = ang_binary_search(_value, to_string_var_class_map); if (idx > array_size(to_string_var_class_map)) return "none"_s; else return to_string_var_class_map[idx].value; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// static ang_pair<graphics::reflect::var_semantic, cstr_t> to_string_var_semantic_map[] = { { var_semantic::none, "UNKNOWN" }, { var_semantic::position, "POSITION" }, { var_semantic::color, "COLOR" }, { var_semantic::tex_coord, "TEXCOORD" }, { var_semantic::normal, "NORMAL" }, { var_semantic::binormal, "BINORMAL" }, { var_semantic::tangent, "TANGENT" }, { var_semantic::fog, "FOG" } }; static ang_pair<cstr_t, graphics::reflect::var_semantic> _parse_var_semantic_map[] = { { "BINORMAL" , var_semantic::binormal }, { "COLOR" , var_semantic::color }, { "FOG" , var_semantic::fog }, { "NORMAL" , var_semantic::normal }, { "POSITION" , var_semantic::position }, { "TANGENT" , var_semantic::tangent }, { "TEXCOORD" , var_semantic::tex_coord }, { "UNKNOWN" , var_semantic::none } }; var_semantic_t graphics::reflect::var_semantic_t::parse(cstr_t cstr) { wsize idx = ang_binary_search<cstr_t>(cstr, _parse_var_semantic_map); if (idx > array_size(_parse_var_semantic_map)) return var_semantic::none; else return _parse_var_semantic_map[idx].value; } var_semantic_t graphics::reflect::var_semantic_t::parse(cwstr_t cstr) { wsize idx = ang_binary_search<cwstr_t>(cstr, _parse_var_semantic_map); if (idx > array_size(_parse_var_semantic_map)) return var_semantic::none; else return _parse_var_semantic_map[idx].value; } cstr_t graphics::reflect::var_semantic_t::to_string()const { wsize idx = ang_binary_search(_value, to_string_var_semantic_map); if (idx > array_size(to_string_var_semantic_map)) return "UNKNOWN"_s; else return to_string_var_semantic_map[idx].value; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// variable_desc::variable_desc(var_type_t _type, var_class_t _class , string name, uint _array, uint aligment) { _var_type = _type; _var_class = _class; _var_name = name.get(); _aligment = aligment; _position = 0U; _array_count = max(_array, 1U); } variable_desc::variable_desc(string name, collections::vector<variable_desc> vars, uint _array, uint aligment) { _var_name = name.get(); _aligment = aligment; _position = 0U; _array_count = max(_array, 1U); _fields = ang::move(vars); _var_type = var_type::block; _var_class = var_class::scalar; calculate_positions(true); } variable_desc::variable_desc(variable_desc&& value) { _var_name = ang::move(value._var_name); _aligment = ang::move(value._aligment); _position = ang::move(value._position); _array_count = ang::move(value._array_count); _fields = ang::move(value._fields); _var_type = ang::move(value._var_type); _var_class = ang::move(value._var_class); } variable_desc::variable_desc(const variable_desc& value) { _var_name = value._var_name; _aligment = value._aligment; _position = value._position; _array_count = value._array_count; if(!value._fields.is_empty()) _fields = static_cast<collections::ienum<variable_desc> const*>(value._fields.get()); _var_type = value._var_type; _var_class = value._var_class; } variable_desc::~variable_desc() { _fields.clean(); } bool variable_desc::load(xml::ixml_node_t input, uint aligment) { if (input.is_empty()) return false; auto atts = input->xml_attributes(); if (input->xml_has_children()) { for(xml::ixml_node_t att : atts) { //xml::xml_attribute_t att = node->xml_as<xml::xml_attribute>(); auto name = att->xml_name()->xml_as<cwstr_t>(); if (name == "name"_s) _var_name = (cwstr_t)att->xml_value(); else if (name == "array"_s) _array_count = att->xml_value()->xml_as<uint>(); else if (name == "aligment"_s) _aligment = att->xml_value()->xml_as<uint>(); } _aligment = (aligment != invalid_index) ? aligment : max(_aligment, 1u); _array_count = max(_array_count, 1u); _position = 0; _var_type = var_type::block; _var_class = var_class::scalar; _fields = null; wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; for(xml::ixml_node_t field : input->xml_children()) { variable_desc desc; auto name = field->xml_name(); if (((cwstr_t)name == L"var"_s || (cwstr_t)name == L"block"_s) && desc.load(field, _aligment)) { size = desc.get_size_in_bytes(); temp = total % _aligment; res = _aligment - temp; if (res < _aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if (res < size) total += res; } desc._position = total; total += size; _fields += ang::move(desc); } } return true; } else if (!atts.is_empty()) { for(xml::ixml_node_t att : atts) { auto name = att->xml_name()->xml_as<cwstr_t>(); if (name == "name"_s) _var_name = (cwstr_t)att->xml_value(); else if (name == "type"_s) _var_type = att->xml_value()->xml_as<var_type_t>(); else if (name == "class"_s) _var_class = att->xml_value()->xml_as<var_class_t>(); else if (name == "array"_s) _array_count = att->xml_value()->xml_as<uint>(); else if (name == "aligment"_s) _aligment = att->xml_value()->xml_as<uint>(); } _position = 0; _aligment = (aligment != invalid_index) ? aligment : max(_aligment, 1u); _array_count = max(_array_count, 1u); _fields = null; return true; } return false; } bool variable_desc::save(xml::xml_document_t)const { return false; } var_type_t variable_desc::var_type()const { return _var_type; } var_class_t variable_desc::var_class()const { return _var_class; } string const& variable_desc::var_name()const { return _var_name; } uint variable_desc::array_count()const { return _array_count; } uint variable_desc::aligment()const { return _aligment; } uint variable_desc::position()const { return _position; } //uniform_fields_t& variable_desc::fields() { return _fields; } uniform_fields_t const& variable_desc::fields()const { return _fields; } void variable_desc::var_type(var_type_t value) { if (_var_type.get() == value.get())return; if (_var_type.get() == var_type::block) _var_class = var_class::scalar; _var_type = value; _fields = nullptr; } void variable_desc::var_class(var_class_t value) { if (_var_type.get() == var_type::block) return; //_var_class must be var_class::scalar _var_class = value; } void variable_desc::var_name(string value) { _var_name = value; } void variable_desc::array_count(uint value) { _array_count = value; } void variable_desc::aligment(uint value) { if (_aligment == value) return; _aligment = value; calculate_positions(true); } void variable_desc::position(uint value) { _position = value; } void variable_desc::fields(uniform_fields_t value) { if (value.is_empty()) return; _var_type = var_type::block; _var_class = var_class::scalar; _fields = ang::move(value); calculate_positions(true); } wsize variable_desc::calculate_positions(bool recursive) { if (_var_type != var_type::block) return get_size_in_bytes(); if (recursive) { wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; for(variable_desc& desc : _fields) { desc._aligment = _aligment; size = desc.calculate_positions(true); if (size == 0) { desc._position = invalid_index; continue;//next item } temp = (total % _aligment); res = _aligment - temp; if (res < _aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if(res < size) total += res; } desc._position = total; total += size; } return (_array_count == 1) ? total : get_memory_size_aligned(total, _aligment)*_array_count; } else { wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; for(variable_desc& desc : _fields) { size = desc.get_size_in_bytes(); if (size == 0) { desc._position = invalid_index; continue;//next item } temp = (total % _aligment); res = _aligment - temp; if (res < _aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if (res < size) total += res; } desc._position = total; total += size; } return (_array_count == 1) ? total : get_memory_size_aligned(total, _aligment)*_array_count; } } wsize variable_desc::get_size_in_bytes()const { if (_array_count == 0) return 0; switch (_var_type.get()) { case var_type::s8: case var_type::u8: return (uint)_var_class.get()* _array_count; case var_type::s16: case var_type::u16: return 2U * (uint)_var_class.get()* _array_count; case var_type::s32: case var_type::u32: case var_type::f32: return 4U * (uint)_var_class.get()* _array_count; case var_type::buffer: return get_memory_size_aligned(_array_count, _aligment); case var_type::block: { wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; if (_fields.is_empty()) return 0; variable_desc const& desc = *_fields->last(); total = desc._position; //get last position for optimization, warning it can be wrong size = desc.get_size_in_bytes(); if (size != 0) { temp = (total % _aligment); res = _aligment - temp; if (res < _aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if (res < size) total += res; } total += size; } return (_array_count == 1) ? total : get_memory_size_aligned(total, _aligment)*_array_count; } default:return 0u; } } wsize variable_desc::get_size_in_bytes(uint aligment)const { if (_array_count == 0) return 0; switch (_var_type.get()) { case var_type::s8: case var_type::u8: return (uint)_var_class.get()* _array_count; case var_type::s16: case var_type::u16: return 2U * (uint)_var_class.get()* _array_count; case var_type::s32: case var_type::u32: case var_type::f32: return 4U * (uint)_var_class.get()* _array_count; case var_type::buffer: return get_memory_size_aligned(_array_count, aligment); case var_type::block: { wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; for(variable_desc const& desc : _fields) { size = desc.get_size_in_bytes(aligment); if (size == 0)continue;//next item temp = (total % aligment); res = aligment - temp; if (res < aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if(res < size) total += res; } total += size; } return (_array_count == 1) ? total : get_memory_size_aligned(total, aligment)*_array_count; } default:return 0u; } } variable_desc& variable_desc::operator = (variable_desc&& value) { _var_name = ang::move(value._var_name); _aligment = ang::move(value._aligment); _position = ang::move(value._position); _array_count = ang::move(value._array_count); _array_count = max(_array_count, 1u); _fields = ang::move(value._fields); _var_type = ang::move(value._var_type); _var_class = ang::move(value._var_class); return*this; } variable_desc& variable_desc::operator = (const variable_desc& value) { _var_name = value._var_name; _aligment = value._aligment; _position = value._position; _array_count = value._array_count; _fields = static_cast<collections::ienum<variable_desc> const*>(value._fields.get()); _var_type = value._var_type; _var_class = value._var_class; return*this; } bool variable_desc::operator == (const variable_desc& value)const { return _var_name == value._var_name || _array_count == value._array_count || _fields == value._fields || _var_type == value._var_type || _var_class == value._var_class; } bool variable_desc::operator != (const variable_desc& value)const { return _var_name != value._var_name && _array_count != value._array_count && _fields != value._fields && _var_type != value._var_type && _var_class != value._var_class; } //////////////////////////////////////////////////////////////// wsize attribute_desc::calculate_positions(array_view<attribute_desc>& attributes) { static const wsize aligment = 16U; wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; for(attribute_desc& desc : attributes) { size = desc.get_size_in_bytes(); if (size == 0)continue;//next item temp = (total % aligment); res = aligment - temp; if (res < aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if (res < size) total += res; } desc.position(total); total += size; } return get_memory_size_aligned(total, aligment); } wsize attribute_desc::get_size_in_bytes(array_view<attribute_desc> attributes, wsize aligment, uint from, uint to) { if (attributes.size() <= from || from >= to) return 0; wsize total = 0; wsize size = 0; wsize temp = 0; wsize res = 0; to = min(attributes.size(), to); for (index i = from; i < to; ++i) { attribute_desc const& desc = attributes[i]; size = desc.get_size_in_bytes(); if (size == 0)continue;//next item temp = (total % aligment); res = aligment - temp; if (res < aligment) { if (res > size) total += get_memory_size_aligned(temp, size) - temp; else if (res < size) total += res; } total += size; }; return get_memory_size_aligned(total, aligment); } bool attribute_desc::load(xml::ixml_node_t inputs, collections::vector<attribute_desc>& out) { if (inputs.is_empty() || !inputs->xml_has_children()) return false; if (out.is_empty()) out = new collections::vector_buffer<attribute_desc>(); else out->clean(); attribute_desc_t desc; for(xml::ixml_node_t input : inputs->xml_children()) { if(desc.load(input)) out += desc; } return true; } attribute_desc::attribute_desc(var_type_t _type, var_class_t _class, string name, var_semantic_t sem, index idx, uint pos) { _var_type = _type; _var_class = _class; _var_name = name.get(); _semantic = sem; _semantic_index = idx; _position = pos; } attribute_desc::attribute_desc(const attribute_desc& value) { _var_name = value._var_name; _var_type = value._var_type; _var_class = value._var_class; _semantic = value._semantic; _semantic_index = value._semantic_index; } bool attribute_desc::load(xml::ixml_node_t input) { if (input.is_empty() || !input->xml_has_attributes()) return false; auto att = input->xml_attributes(); _var_name = (cwstr_t)att["name"_s]; _var_type = att["type"_s]->xml_as<var_type_t>(); _var_class = att["class"_s]->xml_as<var_class_t>(); _semantic = att["semantic"_s]->xml_as<var_semantic_t>(); _semantic_index = att["semantic_idx"_s]->xml_as<uint>(); return true; } bool attribute_desc::save(xml::xml_document_t)const { return false; } var_type_t attribute_desc::var_type()const { return _var_type.get(); } var_class_t attribute_desc::var_class()const { return _var_class.get(); } string const& attribute_desc::var_name()const { return _var_name; } var_semantic_t attribute_desc::semantic()const { return _semantic.get(); } index attribute_desc::semantic_index()const { return _semantic_index; } uint attribute_desc::position()const { return _position; } void attribute_desc::var_type(var_type_t value) { _var_type = value; } void attribute_desc::var_class(var_class_t value){ _var_class = value; } void attribute_desc::var_name(string value){ _var_name = value; } void attribute_desc::semantic(var_semantic_t value) { _semantic = value; } void attribute_desc::semantic_index(index value) { _semantic_index = value; } void attribute_desc::position(uint value) { _position = value; } wsize attribute_desc::get_size_in_bytes()const { switch (_var_type.get()) { case var_type::s16: case var_type::u16: return 2u * (uint)_var_class.get(); case var_type::s32: case var_type::u32: case var_type::f32: return 4u * (uint)_var_class.get(); default:return 0u; } } attribute_desc& attribute_desc::operator = (const attribute_desc& value) { _var_name = value._var_name; _var_type = value._var_type; _var_class = value._var_class; _semantic = value._semantic; _semantic_index = value._semantic_index; return*this; } bool attribute_desc::operator == (const attribute_desc& value)const { return _var_name == value._var_name || _semantic == value._semantic || _semantic_index == value._semantic_index || _var_type == value._var_type || _var_class == value._var_class; } bool attribute_desc::operator != (const attribute_desc& value)const { return _var_name != value._var_name && _semantic != value._semantic && _semantic_index != value._semantic_index && _var_type != value._var_type && _var_class != value._var_class; }
#include "syscalls32.gen.hpp" #define FDP_MODULE "syscalls32" #include "log.hpp" #include "os.hpp" #include <map> namespace { constexpr bool g_debug = false; static const tracer::callcfg_t g_callcfgs[] = { {"_NtAcceptConnectPort@24", 6, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"PVOID", "PortContext", sizeof(wow64::PVOID)}, {"PPORT_MESSAGE", "ConnectionRequest", sizeof(wow64::PPORT_MESSAGE)}, {"BOOLEAN", "AcceptConnection", sizeof(wow64::BOOLEAN)}, {"PPORT_VIEW", "ServerView", sizeof(wow64::PPORT_VIEW)}, {"PREMOTE_PORT_VIEW", "ClientView", sizeof(wow64::PREMOTE_PORT_VIEW)}}}, {"_ZwAccessCheckAndAuditAlarm@44", 11, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"PUNICODE_STRING", "ObjectTypeName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ObjectName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"BOOLEAN", "ObjectCreation", sizeof(wow64::BOOLEAN)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}, {"PBOOLEAN", "GenerateOnClose", sizeof(wow64::PBOOLEAN)}}}, {"_NtAccessCheckByTypeAndAuditAlarm@64", 16, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"PUNICODE_STRING", "ObjectTypeName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ObjectName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"PSID", "PrincipalSelfSid", sizeof(wow64::PSID)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"AUDIT_EVENT_TYPE", "AuditType", sizeof(wow64::AUDIT_EVENT_TYPE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"POBJECT_TYPE_LIST", "ObjectTypeList", sizeof(wow64::POBJECT_TYPE_LIST)}, {"ULONG", "ObjectTypeListLength", sizeof(wow64::ULONG)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"BOOLEAN", "ObjectCreation", sizeof(wow64::BOOLEAN)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}, {"PBOOLEAN", "GenerateOnClose", sizeof(wow64::PBOOLEAN)}}}, {"_NtAccessCheckByType@44", 11, {{"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"PSID", "PrincipalSelfSid", sizeof(wow64::PSID)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_TYPE_LIST", "ObjectTypeList", sizeof(wow64::POBJECT_TYPE_LIST)}, {"ULONG", "ObjectTypeListLength", sizeof(wow64::ULONG)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"PPRIVILEGE_SET", "PrivilegeSet", sizeof(wow64::PPRIVILEGE_SET)}, {"PULONG", "PrivilegeSetLength", sizeof(wow64::PULONG)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}}}, {"_ZwAccessCheckByTypeResultListAndAuditAlarmByHandle@68", 17, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "ObjectTypeName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ObjectName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"PSID", "PrincipalSelfSid", sizeof(wow64::PSID)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"AUDIT_EVENT_TYPE", "AuditType", sizeof(wow64::AUDIT_EVENT_TYPE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"POBJECT_TYPE_LIST", "ObjectTypeList", sizeof(wow64::POBJECT_TYPE_LIST)}, {"ULONG", "ObjectTypeListLength", sizeof(wow64::ULONG)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"BOOLEAN", "ObjectCreation", sizeof(wow64::BOOLEAN)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}, {"PBOOLEAN", "GenerateOnClose", sizeof(wow64::PBOOLEAN)}}}, {"_NtAccessCheckByTypeResultListAndAuditAlarm@64", 16, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"PUNICODE_STRING", "ObjectTypeName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ObjectName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"PSID", "PrincipalSelfSid", sizeof(wow64::PSID)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"AUDIT_EVENT_TYPE", "AuditType", sizeof(wow64::AUDIT_EVENT_TYPE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"POBJECT_TYPE_LIST", "ObjectTypeList", sizeof(wow64::POBJECT_TYPE_LIST)}, {"ULONG", "ObjectTypeListLength", sizeof(wow64::ULONG)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"BOOLEAN", "ObjectCreation", sizeof(wow64::BOOLEAN)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}, {"PBOOLEAN", "GenerateOnClose", sizeof(wow64::PBOOLEAN)}}}, {"_NtAccessCheckByTypeResultList@44", 11, {{"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"PSID", "PrincipalSelfSid", sizeof(wow64::PSID)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_TYPE_LIST", "ObjectTypeList", sizeof(wow64::POBJECT_TYPE_LIST)}, {"ULONG", "ObjectTypeListLength", sizeof(wow64::ULONG)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"PPRIVILEGE_SET", "PrivilegeSet", sizeof(wow64::PPRIVILEGE_SET)}, {"PULONG", "PrivilegeSetLength", sizeof(wow64::PULONG)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}}}, {"_NtAccessCheck@32", 8, {{"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"PGENERIC_MAPPING", "GenericMapping", sizeof(wow64::PGENERIC_MAPPING)}, {"PPRIVILEGE_SET", "PrivilegeSet", sizeof(wow64::PPRIVILEGE_SET)}, {"PULONG", "PrivilegeSetLength", sizeof(wow64::PULONG)}, {"PACCESS_MASK", "GrantedAccess", sizeof(wow64::PACCESS_MASK)}, {"PNTSTATUS", "AccessStatus", sizeof(wow64::PNTSTATUS)}}}, {"_NtAddAtom@12", 3, {{"PWSTR", "AtomName", sizeof(wow64::PWSTR)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PRTL_ATOM", "Atom", sizeof(wow64::PRTL_ATOM)}}}, {"_ZwAddBootEntry@8", 2, {{"PBOOT_ENTRY", "BootEntry", sizeof(wow64::PBOOT_ENTRY)}, {"PULONG", "Id", sizeof(wow64::PULONG)}}}, {"_NtAddDriverEntry@8", 2, {{"PEFI_DRIVER_ENTRY", "DriverEntry", sizeof(wow64::PEFI_DRIVER_ENTRY)}, {"PULONG", "Id", sizeof(wow64::PULONG)}}}, {"_ZwAdjustGroupsToken@24", 6, {{"HANDLE", "TokenHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "ResetToDefault", sizeof(wow64::BOOLEAN)}, {"PTOKEN_GROUPS", "NewState", sizeof(wow64::PTOKEN_GROUPS)}, {"ULONG", "BufferLength", sizeof(wow64::ULONG)}, {"PTOKEN_GROUPS", "PreviousState", sizeof(wow64::PTOKEN_GROUPS)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwAdjustPrivilegesToken@24", 6, {{"HANDLE", "TokenHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "DisableAllPrivileges", sizeof(wow64::BOOLEAN)}, {"PTOKEN_PRIVILEGES", "NewState", sizeof(wow64::PTOKEN_PRIVILEGES)}, {"ULONG", "BufferLength", sizeof(wow64::ULONG)}, {"PTOKEN_PRIVILEGES", "PreviousState", sizeof(wow64::PTOKEN_PRIVILEGES)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtAlertResumeThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PULONG", "PreviousSuspendCount", sizeof(wow64::PULONG)}}}, {"_NtAlertThread@4", 1, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}}}, {"_ZwAllocateLocallyUniqueId@4", 1, {{"PLUID", "Luid", sizeof(wow64::PLUID)}}}, {"_NtAllocateReserveObject@12", 3, {{"PHANDLE", "MemoryReserveHandle", sizeof(wow64::PHANDLE)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"MEMORY_RESERVE_TYPE", "Type", sizeof(wow64::MEMORY_RESERVE_TYPE)}}}, {"_NtAllocateUserPhysicalPages@12", 3, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PULONG_PTR", "NumberOfPages", sizeof(wow64::PULONG_PTR)}, {"PULONG_PTR", "UserPfnArra", sizeof(wow64::PULONG_PTR)}}}, {"_NtAllocateUuids@16", 4, {{"PULARGE_INTEGER", "Time", sizeof(wow64::PULARGE_INTEGER)}, {"PULONG", "Range", sizeof(wow64::PULONG)}, {"PULONG", "Sequence", sizeof(wow64::PULONG)}, {"PCHAR", "Seed", sizeof(wow64::PCHAR)}}}, {"_NtAllocateVirtualMemory@24", 6, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"ULONG_PTR", "ZeroBits", sizeof(wow64::ULONG_PTR)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"ULONG", "AllocationType", sizeof(wow64::ULONG)}, {"ULONG", "Protect", sizeof(wow64::ULONG)}}}, {"_NtAlpcAcceptConnectPort@36", 9, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"HANDLE", "ConnectionPortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PALPC_PORT_ATTRIBUTES", "PortAttributes", sizeof(wow64::PALPC_PORT_ATTRIBUTES)}, {"PVOID", "PortContext", sizeof(wow64::PVOID)}, {"PPORT_MESSAGE", "ConnectionRequest", sizeof(wow64::PPORT_MESSAGE)}, {"PALPC_MESSAGE_ATTRIBUTES", "ConnectionMessageAttributes", sizeof(wow64::PALPC_MESSAGE_ATTRIBUTES)}, {"BOOLEAN", "AcceptConnection", sizeof(wow64::BOOLEAN)}}}, {"_ZwAlpcCancelMessage@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PALPC_CONTEXT_ATTR", "MessageContext", sizeof(wow64::PALPC_CONTEXT_ATTR)}}}, {"_ZwAlpcConnectPort@44", 11, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"PUNICODE_STRING", "PortName", sizeof(wow64::PUNICODE_STRING)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PALPC_PORT_ATTRIBUTES", "PortAttributes", sizeof(wow64::PALPC_PORT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PSID", "RequiredServerSid", sizeof(wow64::PSID)}, {"PPORT_MESSAGE", "ConnectionMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}, {"PALPC_MESSAGE_ATTRIBUTES", "OutMessageAttributes", sizeof(wow64::PALPC_MESSAGE_ATTRIBUTES)}, {"PALPC_MESSAGE_ATTRIBUTES", "InMessageAttributes", sizeof(wow64::PALPC_MESSAGE_ATTRIBUTES)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwAlpcCreatePort@12", 3, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PALPC_PORT_ATTRIBUTES", "PortAttributes", sizeof(wow64::PALPC_PORT_ATTRIBUTES)}}}, {"_NtAlpcCreatePortSection@24", 6, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"SIZE_T", "SectionSize", sizeof(wow64::SIZE_T)}, {"PALPC_HANDLE", "AlpcSectionHandle", sizeof(wow64::PALPC_HANDLE)}, {"PSIZE_T", "ActualSectionSize", sizeof(wow64::PSIZE_T)}}}, {"_ZwAlpcCreateResourceReserve@16", 4, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"SIZE_T", "MessageSize", sizeof(wow64::SIZE_T)}, {"PALPC_HANDLE", "ResourceId", sizeof(wow64::PALPC_HANDLE)}}}, {"_ZwAlpcCreateSectionView@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PALPC_DATA_VIEW_ATTR", "ViewAttributes", sizeof(wow64::PALPC_DATA_VIEW_ATTR)}}}, {"_ZwAlpcCreateSecurityContext@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PALPC_SECURITY_ATTR", "SecurityAttribute", sizeof(wow64::PALPC_SECURITY_ATTR)}}}, {"_ZwAlpcDeletePortSection@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ALPC_HANDLE", "SectionHandle", sizeof(wow64::ALPC_HANDLE)}}}, {"_NtAlpcDeleteResourceReserve@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ALPC_HANDLE", "ResourceId", sizeof(wow64::ALPC_HANDLE)}}}, {"_NtAlpcDeleteSectionView@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PVOID", "ViewBase", sizeof(wow64::PVOID)}}}, {"_NtAlpcDeleteSecurityContext@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ALPC_HANDLE", "ContextHandle", sizeof(wow64::ALPC_HANDLE)}}}, {"_NtAlpcDisconnectPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwAlpcImpersonateClientOfPort@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "PortMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PVOID", "Reserved", sizeof(wow64::PVOID)}}}, {"_ZwAlpcOpenSenderProcess@24", 6, {{"PHANDLE", "ProcessHandle", sizeof(wow64::PHANDLE)}, {"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "PortMessage", sizeof(wow64::PPORT_MESSAGE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwAlpcOpenSenderThread@24", 6, {{"PHANDLE", "ThreadHandle", sizeof(wow64::PHANDLE)}, {"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "PortMessage", sizeof(wow64::PPORT_MESSAGE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwAlpcQueryInformation@20", 5, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ALPC_PORT_INFORMATION_CLASS", "PortInformationClass", sizeof(wow64::ALPC_PORT_INFORMATION_CLASS)}, {"PVOID", "PortInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwAlpcQueryInformationMessage@24", 6, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "PortMessage", sizeof(wow64::PPORT_MESSAGE)}, {"ALPC_MESSAGE_INFORMATION_CLASS", "MessageInformationClass", sizeof(wow64::ALPC_MESSAGE_INFORMATION_CLASS)}, {"PVOID", "MessageInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtAlpcRevokeSecurityContext@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ALPC_HANDLE", "ContextHandle", sizeof(wow64::ALPC_HANDLE)}}}, {"_NtAlpcSendWaitReceivePort@32", 8, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PPORT_MESSAGE", "SendMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PALPC_MESSAGE_ATTRIBUTES", "SendMessageAttributes", sizeof(wow64::PALPC_MESSAGE_ATTRIBUTES)}, {"PPORT_MESSAGE", "ReceiveMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}, {"PALPC_MESSAGE_ATTRIBUTES", "ReceiveMessageAttributes", sizeof(wow64::PALPC_MESSAGE_ATTRIBUTES)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtAlpcSetInformation@16", 4, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"ALPC_PORT_INFORMATION_CLASS", "PortInformationClass", sizeof(wow64::ALPC_PORT_INFORMATION_CLASS)}, {"PVOID", "PortInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}}}, {"_NtApphelpCacheControl@8", 2, {{"APPHELPCOMMAND", "type", sizeof(wow64::APPHELPCOMMAND)}, {"PVOID", "buf", sizeof(wow64::PVOID)}}}, {"_ZwAreMappedFilesTheSame@8", 2, {{"PVOID", "File1MappedAsAnImage", sizeof(wow64::PVOID)}, {"PVOID", "File2MappedAsFile", sizeof(wow64::PVOID)}}}, {"_ZwAssignProcessToJobObject@8", 2, {{"HANDLE", "JobHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}}}, {"_NtCancelIoFileEx@12", 3, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoRequestToCancel", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}}}, {"_ZwCancelIoFile@8", 2, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}}}, {"_NtCancelSynchronousIoFile@12", 3, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoRequestToCancel", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}}}, {"_ZwCancelTimer@8", 2, {{"HANDLE", "TimerHandle", sizeof(wow64::HANDLE)}, {"PBOOLEAN", "CurrentState", sizeof(wow64::PBOOLEAN)}}}, {"_NtClearEvent@4", 1, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}}}, {"_NtClose@4", 1, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}}}, {"_ZwCloseObjectAuditAlarm@12", 3, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"BOOLEAN", "GenerateOnClose", sizeof(wow64::BOOLEAN)}}}, {"_ZwCommitComplete@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtCommitEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtCommitTransaction@8", 2, {{"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "Wait", sizeof(wow64::BOOLEAN)}}}, {"_NtCompactKeys@8", 2, {{"ULONG", "Count", sizeof(wow64::ULONG)}, {"HANDLE", "KeyArray", sizeof(wow64::HANDLE)}}}, {"_ZwCompareTokens@12", 3, {{"HANDLE", "FirstTokenHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "SecondTokenHandle", sizeof(wow64::HANDLE)}, {"PBOOLEAN", "Equal", sizeof(wow64::PBOOLEAN)}}}, {"_NtCompleteConnectPort@4", 1, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}}}, {"_ZwCompressKey@4", 1, {{"HANDLE", "Key", sizeof(wow64::HANDLE)}}}, {"_NtConnectPort@32", 8, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"PUNICODE_STRING", "PortName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_QUALITY_OF_SERVICE", "SecurityQos", sizeof(wow64::PSECURITY_QUALITY_OF_SERVICE)}, {"PPORT_VIEW", "ClientView", sizeof(wow64::PPORT_VIEW)}, {"PREMOTE_PORT_VIEW", "ServerView", sizeof(wow64::PREMOTE_PORT_VIEW)}, {"PULONG", "MaxMessageLength", sizeof(wow64::PULONG)}, {"PVOID", "ConnectionInformation", sizeof(wow64::PVOID)}, {"PULONG", "ConnectionInformationLength", sizeof(wow64::PULONG)}}}, {"_ZwContinue@8", 2, {{"PCONTEXT", "ContextRecord", sizeof(wow64::PCONTEXT)}, {"BOOLEAN", "TestAlert", sizeof(wow64::BOOLEAN)}}}, {"_ZwCreateDebugObject@16", 4, {{"PHANDLE", "DebugObjectHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwCreateDirectoryObject@12", 3, {{"PHANDLE", "DirectoryHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwCreateEnlistment@32", 8, {{"PHANDLE", "EnlistmentHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"NOTIFICATION_MASK", "NotificationMask", sizeof(wow64::NOTIFICATION_MASK)}, {"PVOID", "EnlistmentKey", sizeof(wow64::PVOID)}}}, {"_NtCreateEvent@20", 5, {{"PHANDLE", "EventHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"EVENT_TYPE", "EventType", sizeof(wow64::EVENT_TYPE)}, {"BOOLEAN", "InitialState", sizeof(wow64::BOOLEAN)}}}, {"_NtCreateEventPair@12", 3, {{"PHANDLE", "EventPairHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtCreateFile@44", 11, {{"PHANDLE", "FileHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PLARGE_INTEGER", "AllocationSize", sizeof(wow64::PLARGE_INTEGER)}, {"ULONG", "FileAttributes", sizeof(wow64::ULONG)}, {"ULONG", "ShareAccess", sizeof(wow64::ULONG)}, {"ULONG", "CreateDisposition", sizeof(wow64::ULONG)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"PVOID", "EaBuffer", sizeof(wow64::PVOID)}, {"ULONG", "EaLength", sizeof(wow64::ULONG)}}}, {"_NtCreateIoCompletion@16", 4, {{"PHANDLE", "IoCompletionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Count", sizeof(wow64::ULONG)}}}, {"_ZwCreateJobObject@12", 3, {{"PHANDLE", "JobHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtCreateJobSet@12", 3, {{"ULONG", "NumJob", sizeof(wow64::ULONG)}, {"PJOB_SET_ARRAY", "UserJobSet", sizeof(wow64::PJOB_SET_ARRAY)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwCreateKeyedEvent@16", 4, {{"PHANDLE", "KeyedEventHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwCreateKey@28", 7, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "TitleIndex", sizeof(wow64::ULONG)}, {"PUNICODE_STRING", "Class", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"PULONG", "Disposition", sizeof(wow64::PULONG)}}}, {"_NtCreateKeyTransacted@32", 8, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "TitleIndex", sizeof(wow64::ULONG)}, {"PUNICODE_STRING", "Class", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"PULONG", "Disposition", sizeof(wow64::PULONG)}}}, {"_ZwCreateMailslotFile@32", 8, {{"PHANDLE", "FileHandle", sizeof(wow64::PHANDLE)}, {"ULONG", "DesiredAccess", sizeof(wow64::ULONG)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"ULONG", "MailslotQuota", sizeof(wow64::ULONG)}, {"ULONG", "MaximumMessageSize", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "ReadTimeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwCreateMutant@16", 4, {{"PHANDLE", "MutantHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"BOOLEAN", "InitialOwner", sizeof(wow64::BOOLEAN)}}}, {"_ZwCreateNamedPipeFile@56", 14, {{"PHANDLE", "FileHandle", sizeof(wow64::PHANDLE)}, {"ULONG", "DesiredAccess", sizeof(wow64::ULONG)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "ShareAccess", sizeof(wow64::ULONG)}, {"ULONG", "CreateDisposition", sizeof(wow64::ULONG)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"ULONG", "NamedPipeType", sizeof(wow64::ULONG)}, {"ULONG", "ReadMode", sizeof(wow64::ULONG)}, {"ULONG", "CompletionMode", sizeof(wow64::ULONG)}, {"ULONG", "MaximumInstances", sizeof(wow64::ULONG)}, {"ULONG", "InboundQuota", sizeof(wow64::ULONG)}, {"ULONG", "OutboundQuota", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "DefaultTimeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtCreatePagingFile@16", 4, {{"PUNICODE_STRING", "PageFileName", sizeof(wow64::PUNICODE_STRING)}, {"PLARGE_INTEGER", "MinimumSize", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "MaximumSize", sizeof(wow64::PLARGE_INTEGER)}, {"ULONG", "Priority", sizeof(wow64::ULONG)}}}, {"_ZwCreatePort@20", 5, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "MaxConnectionInfoLength", sizeof(wow64::ULONG)}, {"ULONG", "MaxMessageLength", sizeof(wow64::ULONG)}, {"ULONG", "MaxPoolUsage", sizeof(wow64::ULONG)}}}, {"_NtCreatePrivateNamespace@16", 4, {{"PHANDLE", "NamespaceHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PVOID", "BoundaryDescriptor", sizeof(wow64::PVOID)}}}, {"_ZwCreateProcessEx@36", 9, {{"PHANDLE", "ProcessHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "ParentProcess", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "DebugPort", sizeof(wow64::HANDLE)}, {"HANDLE", "ExceptionPort", sizeof(wow64::HANDLE)}, {"ULONG", "JobMemberLevel", sizeof(wow64::ULONG)}}}, {"_ZwCreateProcess@32", 8, {{"PHANDLE", "ProcessHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "ParentProcess", sizeof(wow64::HANDLE)}, {"BOOLEAN", "InheritObjectTable", sizeof(wow64::BOOLEAN)}, {"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "DebugPort", sizeof(wow64::HANDLE)}, {"HANDLE", "ExceptionPort", sizeof(wow64::HANDLE)}}}, {"_NtCreateProfileEx@40", 10, {{"PHANDLE", "ProfileHandle", sizeof(wow64::PHANDLE)}, {"HANDLE", "Process", sizeof(wow64::HANDLE)}, {"PVOID", "ProfileBase", sizeof(wow64::PVOID)}, {"SIZE_T", "ProfileSize", sizeof(wow64::SIZE_T)}, {"ULONG", "BucketSize", sizeof(wow64::ULONG)}, {"PULONG", "Buffer", sizeof(wow64::PULONG)}, {"ULONG", "BufferSize", sizeof(wow64::ULONG)}, {"KPROFILE_SOURCE", "ProfileSource", sizeof(wow64::KPROFILE_SOURCE)}, {"ULONG", "GroupAffinityCount", sizeof(wow64::ULONG)}, {"PGROUP_AFFINITY", "GroupAffinity", sizeof(wow64::PGROUP_AFFINITY)}}}, {"_ZwCreateProfile@36", 9, {{"PHANDLE", "ProfileHandle", sizeof(wow64::PHANDLE)}, {"HANDLE", "Process", sizeof(wow64::HANDLE)}, {"PVOID", "RangeBase", sizeof(wow64::PVOID)}, {"SIZE_T", "RangeSize", sizeof(wow64::SIZE_T)}, {"ULONG", "BucketSize", sizeof(wow64::ULONG)}, {"PULONG", "Buffer", sizeof(wow64::PULONG)}, {"ULONG", "BufferSize", sizeof(wow64::ULONG)}, {"KPROFILE_SOURCE", "ProfileSource", sizeof(wow64::KPROFILE_SOURCE)}, {"KAFFINITY", "Affinity", sizeof(wow64::KAFFINITY)}}}, {"_ZwCreateResourceManager@28", 7, {{"PHANDLE", "ResourceManagerHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"HANDLE", "TmHandle", sizeof(wow64::HANDLE)}, {"LPGUID", "RmGuid", sizeof(wow64::LPGUID)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"PUNICODE_STRING", "Description", sizeof(wow64::PUNICODE_STRING)}}}, {"_NtCreateSection@28", 7, {{"PHANDLE", "SectionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PLARGE_INTEGER", "MaximumSize", sizeof(wow64::PLARGE_INTEGER)}, {"ULONG", "SectionPageProtection", sizeof(wow64::ULONG)}, {"ULONG", "AllocationAttributes", sizeof(wow64::ULONG)}, {"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}}}, {"_NtCreateSemaphore@20", 5, {{"PHANDLE", "SemaphoreHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"LONG", "InitialCount", sizeof(wow64::LONG)}, {"LONG", "MaximumCount", sizeof(wow64::LONG)}}}, {"_ZwCreateSymbolicLinkObject@16", 4, {{"PHANDLE", "LinkHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PUNICODE_STRING", "LinkTarget", sizeof(wow64::PUNICODE_STRING)}}}, {"_NtCreateThreadEx@44", 11, {{"PHANDLE", "ThreadHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "StartRoutine", sizeof(wow64::PVOID)}, {"PVOID", "Argument", sizeof(wow64::PVOID)}, {"ULONG", "CreateFlags", sizeof(wow64::ULONG)}, {"ULONG_PTR", "ZeroBits", sizeof(wow64::ULONG_PTR)}, {"SIZE_T", "StackSize", sizeof(wow64::SIZE_T)}, {"SIZE_T", "MaximumStackSize", sizeof(wow64::SIZE_T)}, {"PPS_ATTRIBUTE_LIST", "AttributeList", sizeof(wow64::PPS_ATTRIBUTE_LIST)}}}, {"_NtCreateThread@32", 8, {{"PHANDLE", "ThreadHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PCLIENT_ID", "ClientId", sizeof(wow64::PCLIENT_ID)}, {"PCONTEXT", "ThreadContext", sizeof(wow64::PCONTEXT)}, {"PINITIAL_TEB", "InitialTeb", sizeof(wow64::PINITIAL_TEB)}, {"BOOLEAN", "CreateSuspended", sizeof(wow64::BOOLEAN)}}}, {"_ZwCreateTimer@16", 4, {{"PHANDLE", "TimerHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"TIMER_TYPE", "TimerType", sizeof(wow64::TIMER_TYPE)}}}, {"_NtCreateToken@52", 13, {{"PHANDLE", "TokenHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"TOKEN_TYPE", "TokenType", sizeof(wow64::TOKEN_TYPE)}, {"PLUID", "AuthenticationId", sizeof(wow64::PLUID)}, {"PLARGE_INTEGER", "ExpirationTime", sizeof(wow64::PLARGE_INTEGER)}, {"PTOKEN_USER", "User", sizeof(wow64::PTOKEN_USER)}, {"PTOKEN_GROUPS", "Groups", sizeof(wow64::PTOKEN_GROUPS)}, {"PTOKEN_PRIVILEGES", "Privileges", sizeof(wow64::PTOKEN_PRIVILEGES)}, {"PTOKEN_OWNER", "Owner", sizeof(wow64::PTOKEN_OWNER)}, {"PTOKEN_PRIMARY_GROUP", "PrimaryGroup", sizeof(wow64::PTOKEN_PRIMARY_GROUP)}, {"PTOKEN_DEFAULT_DACL", "DefaultDacl", sizeof(wow64::PTOKEN_DEFAULT_DACL)}, {"PTOKEN_SOURCE", "TokenSource", sizeof(wow64::PTOKEN_SOURCE)}}}, {"_ZwCreateTransactionManager@24", 6, {{"PHANDLE", "TmHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PUNICODE_STRING", "LogFileName", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"ULONG", "CommitStrength", sizeof(wow64::ULONG)}}}, {"_NtCreateTransaction@40", 10, {{"PHANDLE", "TransactionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"LPGUID", "Uow", sizeof(wow64::LPGUID)}, {"HANDLE", "TmHandle", sizeof(wow64::HANDLE)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}, {"ULONG", "IsolationLevel", sizeof(wow64::ULONG)}, {"ULONG", "IsolationFlags", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}, {"PUNICODE_STRING", "Description", sizeof(wow64::PUNICODE_STRING)}}}, {"_NtCreateUserProcess@44", 11, {{"PHANDLE", "ProcessHandle", sizeof(wow64::PHANDLE)}, {"PHANDLE", "ThreadHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "ProcessDesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ACCESS_MASK", "ThreadDesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ProcessObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"POBJECT_ATTRIBUTES", "ThreadObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "ProcessFlags", sizeof(wow64::ULONG)}, {"ULONG", "ThreadFlags", sizeof(wow64::ULONG)}, {"PRTL_USER_PROCESS_PARAMETERS", "ProcessParameters", sizeof(wow64::PRTL_USER_PROCESS_PARAMETERS)}, {"PPROCESS_CREATE_INFO", "CreateInfo", sizeof(wow64::PPROCESS_CREATE_INFO)}, {"PPROCESS_ATTRIBUTE_LIST", "AttributeList", sizeof(wow64::PPROCESS_ATTRIBUTE_LIST)}}}, {"_ZwCreateWaitablePort@20", 5, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "MaxConnectionInfoLength", sizeof(wow64::ULONG)}, {"ULONG", "MaxMessageLength", sizeof(wow64::ULONG)}, {"ULONG", "MaxPoolUsage", sizeof(wow64::ULONG)}}}, {"_NtCreateWorkerFactory@40", 10, {{"PHANDLE", "WorkerFactoryHandleReturn", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "CompletionPortHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "WorkerProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "StartRoutine", sizeof(wow64::PVOID)}, {"PVOID", "StartParameter", sizeof(wow64::PVOID)}, {"ULONG", "MaxThreadCount", sizeof(wow64::ULONG)}, {"SIZE_T", "StackReserve", sizeof(wow64::SIZE_T)}, {"SIZE_T", "StackCommit", sizeof(wow64::SIZE_T)}}}, {"_NtDebugActiveProcess@8", 2, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "DebugObjectHandle", sizeof(wow64::HANDLE)}}}, {"_ZwDebugContinue@12", 3, {{"HANDLE", "DebugObjectHandle", sizeof(wow64::HANDLE)}, {"PCLIENT_ID", "ClientId", sizeof(wow64::PCLIENT_ID)}, {"NTSTATUS", "ContinueStatus", sizeof(wow64::NTSTATUS)}}}, {"_ZwDelayExecution@8", 2, {{"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "DelayInterval", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwDeleteAtom@4", 1, {{"RTL_ATOM", "Atom", sizeof(wow64::RTL_ATOM)}}}, {"_NtDeleteBootEntry@4", 1, {{"ULONG", "Id", sizeof(wow64::ULONG)}}}, {"_ZwDeleteDriverEntry@4", 1, {{"ULONG", "Id", sizeof(wow64::ULONG)}}}, {"_NtDeleteFile@4", 1, {{"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwDeleteKey@4", 1, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}}}, {"_NtDeleteObjectAuditAlarm@12", 3, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"BOOLEAN", "GenerateOnClose", sizeof(wow64::BOOLEAN)}}}, {"_NtDeletePrivateNamespace@4", 1, {{"HANDLE", "NamespaceHandle", sizeof(wow64::HANDLE)}}}, {"_NtDeleteValueKey@8", 2, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "ValueName", sizeof(wow64::PUNICODE_STRING)}}}, {"_ZwDeviceIoControlFile@40", 10, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "IoControlCode", sizeof(wow64::ULONG)}, {"PVOID", "InputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "InputBufferLength", sizeof(wow64::ULONG)}, {"PVOID", "OutputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "OutputBufferLength", sizeof(wow64::ULONG)}}}, {"_NtDisplayString@4", 1, {{"PUNICODE_STRING", "String", sizeof(wow64::PUNICODE_STRING)}}}, {"_ZwDrawText@4", 1, {{"PUNICODE_STRING", "Text", sizeof(wow64::PUNICODE_STRING)}}}, {"_ZwDuplicateObject@28", 7, {{"HANDLE", "SourceProcessHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "SourceHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "TargetProcessHandle", sizeof(wow64::HANDLE)}, {"PHANDLE", "TargetHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ULONG", "HandleAttributes", sizeof(wow64::ULONG)}, {"ULONG", "Options", sizeof(wow64::ULONG)}}}, {"_NtDuplicateToken@24", 6, {{"HANDLE", "ExistingTokenHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"BOOLEAN", "EffectiveOnly", sizeof(wow64::BOOLEAN)}, {"TOKEN_TYPE", "TokenType", sizeof(wow64::TOKEN_TYPE)}, {"PHANDLE", "NewTokenHandle", sizeof(wow64::PHANDLE)}}}, {"_ZwEnumerateBootEntries@8", 2, {{"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}}}, {"_NtEnumerateDriverEntries@8", 2, {{"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}}}, {"_ZwEnumerateKey@24", 6, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Index", sizeof(wow64::ULONG)}, {"KEY_INFORMATION_CLASS", "KeyInformationClass", sizeof(wow64::KEY_INFORMATION_CLASS)}, {"PVOID", "KeyInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ResultLength", sizeof(wow64::PULONG)}}}, {"_ZwEnumerateSystemEnvironmentValuesEx@12", 3, {{"ULONG", "InformationClass", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}}}, {"_ZwEnumerateTransactionObject@20", 5, {{"HANDLE", "RootObjectHandle", sizeof(wow64::HANDLE)}, {"KTMOBJECT_TYPE", "QueryType", sizeof(wow64::KTMOBJECT_TYPE)}, {"PKTMOBJECT_CURSOR", "ObjectCursor", sizeof(wow64::PKTMOBJECT_CURSOR)}, {"ULONG", "ObjectCursorLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtEnumerateValueKey@24", 6, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Index", sizeof(wow64::ULONG)}, {"KEY_VALUE_INFORMATION_CLASS", "KeyValueInformationClass", sizeof(wow64::KEY_VALUE_INFORMATION_CLASS)}, {"PVOID", "KeyValueInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ResultLength", sizeof(wow64::PULONG)}}}, {"_ZwExtendSection@8", 2, {{"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "NewSectionSize", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtFilterToken@24", 6, {{"HANDLE", "ExistingTokenHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PTOKEN_GROUPS", "SidsToDisable", sizeof(wow64::PTOKEN_GROUPS)}, {"PTOKEN_PRIVILEGES", "PrivilegesToDelete", sizeof(wow64::PTOKEN_PRIVILEGES)}, {"PTOKEN_GROUPS", "RestrictedSids", sizeof(wow64::PTOKEN_GROUPS)}, {"PHANDLE", "NewTokenHandle", sizeof(wow64::PHANDLE)}}}, {"_NtFindAtom@12", 3, {{"PWSTR", "AtomName", sizeof(wow64::PWSTR)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PRTL_ATOM", "Atom", sizeof(wow64::PRTL_ATOM)}}}, {"_ZwFlushBuffersFile@8", 2, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}}}, {"_ZwFlushInstallUILanguage@8", 2, {{"LANGID", "InstallUILanguage", sizeof(wow64::LANGID)}, {"ULONG", "SetComittedFlag", sizeof(wow64::ULONG)}}}, {"_ZwFlushInstructionCache@12", 3, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"SIZE_T", "Length", sizeof(wow64::SIZE_T)}}}, {"_NtFlushKey@4", 1, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}}}, {"_ZwFlushVirtualMemory@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"PIO_STATUS_BLOCK", "IoStatus", sizeof(wow64::PIO_STATUS_BLOCK)}}}, {"_NtFreeUserPhysicalPages@12", 3, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PULONG_PTR", "NumberOfPages", sizeof(wow64::PULONG_PTR)}, {"PULONG_PTR", "UserPfnArra", sizeof(wow64::PULONG_PTR)}}}, {"_NtFreeVirtualMemory@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"ULONG", "FreeType", sizeof(wow64::ULONG)}}}, {"_NtFreezeRegistry@4", 1, {{"ULONG", "TimeOutInSeconds", sizeof(wow64::ULONG)}}}, {"_ZwFreezeTransactions@8", 2, {{"PLARGE_INTEGER", "FreezeTimeout", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "ThawTimeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtFsControlFile@40", 10, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "IoControlCode", sizeof(wow64::ULONG)}, {"PVOID", "InputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "InputBufferLength", sizeof(wow64::ULONG)}, {"PVOID", "OutputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "OutputBufferLength", sizeof(wow64::ULONG)}}}, {"_NtGetContextThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PCONTEXT", "ThreadContext", sizeof(wow64::PCONTEXT)}}}, {"_NtGetDevicePowerState@8", 2, {{"HANDLE", "Device", sizeof(wow64::HANDLE)}, {"DEVICE_POWER_STATE", "STARState", sizeof(wow64::DEVICE_POWER_STATE)}}}, {"_NtGetMUIRegistryInfo@12", 3, {{"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PULONG", "DataSize", sizeof(wow64::PULONG)}, {"PVOID", "Data", sizeof(wow64::PVOID)}}}, {"_ZwGetNextProcess@20", 5, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ULONG", "HandleAttributes", sizeof(wow64::ULONG)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PHANDLE", "NewProcessHandle", sizeof(wow64::PHANDLE)}}}, {"_ZwGetNextThread@24", 6, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ULONG", "HandleAttributes", sizeof(wow64::ULONG)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PHANDLE", "NewThreadHandle", sizeof(wow64::PHANDLE)}}}, {"_NtGetNlsSectionPtr@20", 5, {{"ULONG", "SectionType", sizeof(wow64::ULONG)}, {"ULONG", "SectionData", sizeof(wow64::ULONG)}, {"PVOID", "ContextData", sizeof(wow64::PVOID)}, {"PVOID", "STARSectionPointer", sizeof(wow64::PVOID)}, {"PULONG", "SectionSize", sizeof(wow64::PULONG)}}}, {"_ZwGetNotificationResourceManager@28", 7, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"PTRANSACTION_NOTIFICATION", "TransactionNotification", sizeof(wow64::PTRANSACTION_NOTIFICATION)}, {"ULONG", "NotificationLength", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}, {"ULONG", "Asynchronous", sizeof(wow64::ULONG)}, {"ULONG_PTR", "AsynchronousContext", sizeof(wow64::ULONG_PTR)}}}, {"_NtGetWriteWatch@28", 7, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"SIZE_T", "RegionSize", sizeof(wow64::SIZE_T)}, {"PVOID", "STARUserAddressArray", sizeof(wow64::PVOID)}, {"PULONG_PTR", "EntriesInUserAddressArray", sizeof(wow64::PULONG_PTR)}, {"PULONG", "Granularity", sizeof(wow64::PULONG)}}}, {"_NtImpersonateAnonymousToken@4", 1, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}}}, {"_ZwImpersonateClientOfPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "Message", sizeof(wow64::PPORT_MESSAGE)}}}, {"_ZwImpersonateThread@12", 3, {{"HANDLE", "ServerThreadHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "ClientThreadHandle", sizeof(wow64::HANDLE)}, {"PSECURITY_QUALITY_OF_SERVICE", "SecurityQos", sizeof(wow64::PSECURITY_QUALITY_OF_SERVICE)}}}, {"_NtInitializeNlsFiles@12", 3, {{"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PLCID", "DefaultLocaleId", sizeof(wow64::PLCID)}, {"PLARGE_INTEGER", "DefaultCasingTableSize", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwInitializeRegistry@4", 1, {{"USHORT", "BootCondition", sizeof(wow64::USHORT)}}}, {"_NtInitiatePowerAction@16", 4, {{"POWER_ACTION", "SystemAction", sizeof(wow64::POWER_ACTION)}, {"SYSTEM_POWER_STATE", "MinSystemState", sizeof(wow64::SYSTEM_POWER_STATE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"BOOLEAN", "Asynchronous", sizeof(wow64::BOOLEAN)}}}, {"_ZwIsProcessInJob@8", 2, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "JobHandle", sizeof(wow64::HANDLE)}}}, {"_ZwListenPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "ConnectionRequest", sizeof(wow64::PPORT_MESSAGE)}}}, {"_NtLoadDriver@4", 1, {{"PUNICODE_STRING", "DriverServiceName", sizeof(wow64::PUNICODE_STRING)}}}, {"_NtLoadKey2@12", 3, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"POBJECT_ATTRIBUTES", "SourceFile", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_NtLoadKeyEx@32", 8, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"POBJECT_ATTRIBUTES", "SourceFile", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"HANDLE", "TrustClassKey", sizeof(wow64::HANDLE)}, {"PVOID", "Reserved", sizeof(wow64::PVOID)}, {"PVOID", "ObjectContext", sizeof(wow64::PVOID)}, {"PVOID", "CallbackReserverd", sizeof(wow64::PVOID)}, {"PVOID", "IoStatusBlock", sizeof(wow64::PVOID)}}}, {"_NtLoadKey@8", 2, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"POBJECT_ATTRIBUTES", "SourceFile", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtLockFile@40", 10, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "Length", sizeof(wow64::PLARGE_INTEGER)}, {"ULONG", "Key", sizeof(wow64::ULONG)}, {"BOOLEAN", "FailImmediately", sizeof(wow64::BOOLEAN)}, {"BOOLEAN", "ExclusiveLock", sizeof(wow64::BOOLEAN)}}}, {"_ZwLockProductActivationKeys@8", 2, {{"ULONG", "STARpPrivateVer", sizeof(wow64::ULONG)}, {"ULONG", "STARpSafeMode", sizeof(wow64::ULONG)}}}, {"_NtLockRegistryKey@4", 1, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}}}, {"_ZwLockVirtualMemory@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"ULONG", "MapType", sizeof(wow64::ULONG)}}}, {"_ZwMakePermanentObject@4", 1, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}}}, {"_NtMakeTemporaryObject@4", 1, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}}}, {"_ZwMapCMFModule@24", 6, {{"ULONG", "What", sizeof(wow64::ULONG)}, {"ULONG", "Index", sizeof(wow64::ULONG)}, {"PULONG", "CacheIndexOut", sizeof(wow64::PULONG)}, {"PULONG", "CacheFlagsOut", sizeof(wow64::PULONG)}, {"PULONG", "ViewSizeOut", sizeof(wow64::PULONG)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}}}, {"_NtMapUserPhysicalPages@12", 3, {{"PVOID", "VirtualAddress", sizeof(wow64::PVOID)}, {"ULONG_PTR", "NumberOfPages", sizeof(wow64::ULONG_PTR)}, {"PULONG_PTR", "UserPfnArra", sizeof(wow64::PULONG_PTR)}}}, {"_ZwMapUserPhysicalPagesScatter@12", 3, {{"PVOID", "STARVirtualAddresses", sizeof(wow64::PVOID)}, {"ULONG_PTR", "NumberOfPages", sizeof(wow64::ULONG_PTR)}, {"PULONG_PTR", "UserPfnArray", sizeof(wow64::PULONG_PTR)}}}, {"_ZwMapViewOfSection@40", 10, {{"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"ULONG_PTR", "ZeroBits", sizeof(wow64::ULONG_PTR)}, {"SIZE_T", "CommitSize", sizeof(wow64::SIZE_T)}, {"PLARGE_INTEGER", "SectionOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PSIZE_T", "ViewSize", sizeof(wow64::PSIZE_T)}, {"SECTION_INHERIT", "InheritDisposition", sizeof(wow64::SECTION_INHERIT)}, {"ULONG", "AllocationType", sizeof(wow64::ULONG)}, {"WIN32_PROTECTION_MASK", "Win32Protect", sizeof(wow64::WIN32_PROTECTION_MASK)}}}, {"_NtModifyBootEntry@4", 1, {{"PBOOT_ENTRY", "BootEntry", sizeof(wow64::PBOOT_ENTRY)}}}, {"_ZwModifyDriverEntry@4", 1, {{"PEFI_DRIVER_ENTRY", "DriverEntry", sizeof(wow64::PEFI_DRIVER_ENTRY)}}}, {"_NtNotifyChangeDirectoryFile@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"ULONG", "CompletionFilter", sizeof(wow64::ULONG)}, {"BOOLEAN", "WatchTree", sizeof(wow64::BOOLEAN)}}}, {"_NtNotifyChangeKey@40", 10, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "CompletionFilter", sizeof(wow64::ULONG)}, {"BOOLEAN", "WatchTree", sizeof(wow64::BOOLEAN)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "BufferSize", sizeof(wow64::ULONG)}, {"BOOLEAN", "Asynchronous", sizeof(wow64::BOOLEAN)}}}, {"_NtNotifyChangeMultipleKeys@48", 12, {{"HANDLE", "MasterKeyHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Count", sizeof(wow64::ULONG)}, {"POBJECT_ATTRIBUTES", "SlaveObjects", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "CompletionFilter", sizeof(wow64::ULONG)}, {"BOOLEAN", "WatchTree", sizeof(wow64::BOOLEAN)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "BufferSize", sizeof(wow64::ULONG)}, {"BOOLEAN", "Asynchronous", sizeof(wow64::BOOLEAN)}}}, {"_NtNotifyChangeSession@32", 8, {{"HANDLE", "Session", sizeof(wow64::HANDLE)}, {"ULONG", "IoStateSequence", sizeof(wow64::ULONG)}, {"PVOID", "Reserved", sizeof(wow64::PVOID)}, {"ULONG", "Action", sizeof(wow64::ULONG)}, {"IO_SESSION_STATE", "IoState", sizeof(wow64::IO_SESSION_STATE)}, {"IO_SESSION_STATE", "IoState2", sizeof(wow64::IO_SESSION_STATE)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "BufferSize", sizeof(wow64::ULONG)}}}, {"_ZwOpenDirectoryObject@12", 3, {{"PHANDLE", "DirectoryHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenEnlistment@20", 5, {{"PHANDLE", "EnlistmentHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"LPGUID", "EnlistmentGuid", sizeof(wow64::LPGUID)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenEvent@12", 3, {{"PHANDLE", "EventHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenEventPair@12", 3, {{"PHANDLE", "EventPairHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenFile@24", 6, {{"PHANDLE", "FileHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"ULONG", "ShareAccess", sizeof(wow64::ULONG)}, {"ULONG", "OpenOptions", sizeof(wow64::ULONG)}}}, {"_ZwOpenIoCompletion@12", 3, {{"PHANDLE", "IoCompletionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenJobObject@12", 3, {{"PHANDLE", "JobHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenKeyedEvent@12", 3, {{"PHANDLE", "KeyedEventHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenKeyEx@16", 4, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "OpenOptions", sizeof(wow64::ULONG)}}}, {"_ZwOpenKey@12", 3, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenKeyTransactedEx@20", 5, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "OpenOptions", sizeof(wow64::ULONG)}, {"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}}}, {"_NtOpenKeyTransacted@16", 4, {{"PHANDLE", "KeyHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}}}, {"_NtOpenMutant@12", 3, {{"PHANDLE", "MutantHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenObjectAuditAlarm@48", 12, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"PUNICODE_STRING", "ObjectTypeName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ObjectName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ACCESS_MASK", "GrantedAccess", sizeof(wow64::ACCESS_MASK)}, {"PPRIVILEGE_SET", "Privileges", sizeof(wow64::PPRIVILEGE_SET)}, {"BOOLEAN", "ObjectCreation", sizeof(wow64::BOOLEAN)}, {"BOOLEAN", "AccessGranted", sizeof(wow64::BOOLEAN)}, {"PBOOLEAN", "GenerateOnClose", sizeof(wow64::PBOOLEAN)}}}, {"_NtOpenPrivateNamespace@16", 4, {{"PHANDLE", "NamespaceHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PVOID", "BoundaryDescriptor", sizeof(wow64::PVOID)}}}, {"_ZwOpenProcess@16", 4, {{"PHANDLE", "ProcessHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PCLIENT_ID", "ClientId", sizeof(wow64::PCLIENT_ID)}}}, {"_ZwOpenProcessTokenEx@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"ULONG", "HandleAttributes", sizeof(wow64::ULONG)}, {"PHANDLE", "TokenHandle", sizeof(wow64::PHANDLE)}}}, {"_ZwOpenProcessToken@12", 3, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"PHANDLE", "TokenHandle", sizeof(wow64::PHANDLE)}}}, {"_ZwOpenResourceManager@20", 5, {{"PHANDLE", "ResourceManagerHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"HANDLE", "TmHandle", sizeof(wow64::HANDLE)}, {"LPGUID", "ResourceManagerGuid", sizeof(wow64::LPGUID)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenSection@12", 3, {{"PHANDLE", "SectionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenSemaphore@12", 3, {{"PHANDLE", "SemaphoreHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenSession@12", 3, {{"PHANDLE", "SessionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtOpenSymbolicLinkObject@12", 3, {{"PHANDLE", "LinkHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenThread@16", 4, {{"PHANDLE", "ThreadHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PCLIENT_ID", "ClientId", sizeof(wow64::PCLIENT_ID)}}}, {"_NtOpenThreadTokenEx@20", 5, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"BOOLEAN", "OpenAsSelf", sizeof(wow64::BOOLEAN)}, {"ULONG", "HandleAttributes", sizeof(wow64::ULONG)}, {"PHANDLE", "TokenHandle", sizeof(wow64::PHANDLE)}}}, {"_NtOpenThreadToken@16", 4, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"BOOLEAN", "OpenAsSelf", sizeof(wow64::BOOLEAN)}, {"PHANDLE", "TokenHandle", sizeof(wow64::PHANDLE)}}}, {"_ZwOpenTimer@12", 3, {{"PHANDLE", "TimerHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwOpenTransactionManager@24", 6, {{"PHANDLE", "TmHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PUNICODE_STRING", "LogFileName", sizeof(wow64::PUNICODE_STRING)}, {"LPGUID", "TmIdentity", sizeof(wow64::LPGUID)}, {"ULONG", "OpenOptions", sizeof(wow64::ULONG)}}}, {"_ZwOpenTransaction@20", 5, {{"PHANDLE", "TransactionHandle", sizeof(wow64::PHANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"LPGUID", "Uow", sizeof(wow64::LPGUID)}, {"HANDLE", "TmHandle", sizeof(wow64::HANDLE)}}}, {"_NtPlugPlayControl@12", 3, {{"PLUGPLAY_CONTROL_CLASS", "PnPControlClass", sizeof(wow64::PLUGPLAY_CONTROL_CLASS)}, {"PVOID", "PnPControlData", sizeof(wow64::PVOID)}, {"ULONG", "PnPControlDataLength", sizeof(wow64::ULONG)}}}, {"_ZwPowerInformation@20", 5, {{"POWER_INFORMATION_LEVEL", "InformationLevel", sizeof(wow64::POWER_INFORMATION_LEVEL)}, {"PVOID", "InputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "InputBufferLength", sizeof(wow64::ULONG)}, {"PVOID", "OutputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "OutputBufferLength", sizeof(wow64::ULONG)}}}, {"_NtPrepareComplete@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwPrepareEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwPrePrepareComplete@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtPrePrepareEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwPrivilegeCheck@12", 3, {{"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"PPRIVILEGE_SET", "RequiredPrivileges", sizeof(wow64::PPRIVILEGE_SET)}, {"PBOOLEAN", "Result", sizeof(wow64::PBOOLEAN)}}}, {"_NtPrivilegedServiceAuditAlarm@20", 5, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "ServiceName", sizeof(wow64::PUNICODE_STRING)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"PPRIVILEGE_SET", "Privileges", sizeof(wow64::PPRIVILEGE_SET)}, {"BOOLEAN", "AccessGranted", sizeof(wow64::BOOLEAN)}}}, {"_ZwPrivilegeObjectAuditAlarm@24", 6, {{"PUNICODE_STRING", "SubsystemName", sizeof(wow64::PUNICODE_STRING)}, {"PVOID", "HandleId", sizeof(wow64::PVOID)}, {"HANDLE", "ClientToken", sizeof(wow64::HANDLE)}, {"ACCESS_MASK", "DesiredAccess", sizeof(wow64::ACCESS_MASK)}, {"PPRIVILEGE_SET", "Privileges", sizeof(wow64::PPRIVILEGE_SET)}, {"BOOLEAN", "AccessGranted", sizeof(wow64::BOOLEAN)}}}, {"_NtPropagationComplete@16", 4, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"ULONG", "RequestCookie", sizeof(wow64::ULONG)}, {"ULONG", "BufferLength", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}}}, {"_ZwPropagationFailed@12", 3, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"ULONG", "RequestCookie", sizeof(wow64::ULONG)}, {"NTSTATUS", "PropStatus", sizeof(wow64::NTSTATUS)}}}, {"_ZwProtectVirtualMemory@20", 5, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"WIN32_PROTECTION_MASK", "NewProtectWin32", sizeof(wow64::WIN32_PROTECTION_MASK)}, {"PULONG", "OldProtect", sizeof(wow64::PULONG)}}}, {"_ZwPulseEvent@8", 2, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}, {"PLONG", "PreviousState", sizeof(wow64::PLONG)}}}, {"_ZwQueryAttributesFile@8", 2, {{"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PFILE_BASIC_INFORMATION", "FileInformation", sizeof(wow64::PFILE_BASIC_INFORMATION)}}}, {"_ZwQueryBootEntryOrder@8", 2, {{"PULONG", "Ids", sizeof(wow64::PULONG)}, {"PULONG", "Count", sizeof(wow64::PULONG)}}}, {"_ZwQueryBootOptions@8", 2, {{"PBOOT_OPTIONS", "BootOptions", sizeof(wow64::PBOOT_OPTIONS)}, {"PULONG", "BootOptionsLength", sizeof(wow64::PULONG)}}}, {"_NtQueryDebugFilterState@8", 2, {{"ULONG", "ComponentId", sizeof(wow64::ULONG)}, {"ULONG", "Level", sizeof(wow64::ULONG)}}}, {"_NtQueryDefaultLocale@8", 2, {{"BOOLEAN", "UserProfile", sizeof(wow64::BOOLEAN)}, {"PLCID", "DefaultLocaleId", sizeof(wow64::PLCID)}}}, {"_ZwQueryDefaultUILanguage@4", 1, {{"LANGID", "STARDefaultUILanguageId", sizeof(wow64::LANGID)}}}, {"_ZwQueryDirectoryFile@44", 11, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "FileInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"FILE_INFORMATION_CLASS", "FileInformationClass", sizeof(wow64::FILE_INFORMATION_CLASS)}, {"BOOLEAN", "ReturnSingleEntry", sizeof(wow64::BOOLEAN)}, {"PUNICODE_STRING", "FileName", sizeof(wow64::PUNICODE_STRING)}, {"BOOLEAN", "RestartScan", sizeof(wow64::BOOLEAN)}}}, {"_ZwQueryDirectoryObject@28", 7, {{"HANDLE", "DirectoryHandle", sizeof(wow64::HANDLE)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"BOOLEAN", "ReturnSingleEntry", sizeof(wow64::BOOLEAN)}, {"BOOLEAN", "RestartScan", sizeof(wow64::BOOLEAN)}, {"PULONG", "Context", sizeof(wow64::PULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryDriverEntryOrder@8", 2, {{"PULONG", "Ids", sizeof(wow64::PULONG)}, {"PULONG", "Count", sizeof(wow64::PULONG)}}}, {"_ZwQueryEaFile@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"BOOLEAN", "ReturnSingleEntry", sizeof(wow64::BOOLEAN)}, {"PVOID", "EaList", sizeof(wow64::PVOID)}, {"ULONG", "EaListLength", sizeof(wow64::ULONG)}, {"PULONG", "EaIndex", sizeof(wow64::PULONG)}, {"BOOLEAN", "RestartScan", sizeof(wow64::BOOLEAN)}}}, {"_NtQueryEvent@20", 5, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}, {"EVENT_INFORMATION_CLASS", "EventInformationClass", sizeof(wow64::EVENT_INFORMATION_CLASS)}, {"PVOID", "EventInformation", sizeof(wow64::PVOID)}, {"ULONG", "EventInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryFullAttributesFile@8", 2, {{"POBJECT_ATTRIBUTES", "ObjectAttributes", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PFILE_NETWORK_OPEN_INFORMATION", "FileInformation", sizeof(wow64::PFILE_NETWORK_OPEN_INFORMATION)}}}, {"_NtQueryInformationAtom@20", 5, {{"RTL_ATOM", "Atom", sizeof(wow64::RTL_ATOM)}, {"ATOM_INFORMATION_CLASS", "InformationClass", sizeof(wow64::ATOM_INFORMATION_CLASS)}, {"PVOID", "AtomInformation", sizeof(wow64::PVOID)}, {"ULONG", "AtomInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationEnlistment@20", 5, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"ENLISTMENT_INFORMATION_CLASS", "EnlistmentInformationClass", sizeof(wow64::ENLISTMENT_INFORMATION_CLASS)}, {"PVOID", "EnlistmentInformation", sizeof(wow64::PVOID)}, {"ULONG", "EnlistmentInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationFile@20", 5, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "FileInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"FILE_INFORMATION_CLASS", "FileInformationClass", sizeof(wow64::FILE_INFORMATION_CLASS)}}}, {"_ZwQueryInformationJobObject@20", 5, {{"HANDLE", "JobHandle", sizeof(wow64::HANDLE)}, {"JOBOBJECTINFOCLASS", "JobObjectInformationClass", sizeof(wow64::JOBOBJECTINFOCLASS)}, {"PVOID", "JobObjectInformation", sizeof(wow64::PVOID)}, {"ULONG", "JobObjectInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationPort@20", 5, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PORT_INFORMATION_CLASS", "PortInformationClass", sizeof(wow64::PORT_INFORMATION_CLASS)}, {"PVOID", "PortInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationProcess@20", 5, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PROCESSINFOCLASS", "ProcessInformationClass", sizeof(wow64::PROCESSINFOCLASS)}, {"PVOID", "ProcessInformation", sizeof(wow64::PVOID)}, {"ULONG", "ProcessInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationResourceManager@20", 5, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"RESOURCEMANAGER_INFORMATION_CLASS", "ResourceManagerInformationClass", sizeof(wow64::RESOURCEMANAGER_INFORMATION_CLASS)}, {"PVOID", "ResourceManagerInformation", sizeof(wow64::PVOID)}, {"ULONG", "ResourceManagerInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryInformationThread@20", 5, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"THREADINFOCLASS", "ThreadInformationClass", sizeof(wow64::THREADINFOCLASS)}, {"PVOID", "ThreadInformation", sizeof(wow64::PVOID)}, {"ULONG", "ThreadInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationToken@20", 5, {{"HANDLE", "TokenHandle", sizeof(wow64::HANDLE)}, {"TOKEN_INFORMATION_CLASS", "TokenInformationClass", sizeof(wow64::TOKEN_INFORMATION_CLASS)}, {"PVOID", "TokenInformation", sizeof(wow64::PVOID)}, {"ULONG", "TokenInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationTransaction@20", 5, {{"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"TRANSACTION_INFORMATION_CLASS", "TransactionInformationClass", sizeof(wow64::TRANSACTION_INFORMATION_CLASS)}, {"PVOID", "TransactionInformation", sizeof(wow64::PVOID)}, {"ULONG", "TransactionInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryInformationTransactionManager@20", 5, {{"HANDLE", "TransactionManagerHandle", sizeof(wow64::HANDLE)}, {"TRANSACTIONMANAGER_INFORMATION_CLASS", "TransactionManagerInformationClass", sizeof(wow64::TRANSACTIONMANAGER_INFORMATION_CLASS)}, {"PVOID", "TransactionManagerInformation", sizeof(wow64::PVOID)}, {"ULONG", "TransactionManagerInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryInformationWorkerFactory@20", 5, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}, {"WORKERFACTORYINFOCLASS", "WorkerFactoryInformationClass", sizeof(wow64::WORKERFACTORYINFOCLASS)}, {"PVOID", "WorkerFactoryInformation", sizeof(wow64::PVOID)}, {"ULONG", "WorkerFactoryInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryInstallUILanguage@4", 1, {{"LANGID", "STARInstallUILanguageId", sizeof(wow64::LANGID)}}}, {"_NtQueryIntervalProfile@8", 2, {{"KPROFILE_SOURCE", "ProfileSource", sizeof(wow64::KPROFILE_SOURCE)}, {"PULONG", "Interval", sizeof(wow64::PULONG)}}}, {"_NtQueryIoCompletion@20", 5, {{"HANDLE", "IoCompletionHandle", sizeof(wow64::HANDLE)}, {"IO_COMPLETION_INFORMATION_CLASS", "IoCompletionInformationClass", sizeof(wow64::IO_COMPLETION_INFORMATION_CLASS)}, {"PVOID", "IoCompletionInformation", sizeof(wow64::PVOID)}, {"ULONG", "IoCompletionInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQueryKey@20", 5, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"KEY_INFORMATION_CLASS", "KeyInformationClass", sizeof(wow64::KEY_INFORMATION_CLASS)}, {"PVOID", "KeyInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ResultLength", sizeof(wow64::PULONG)}}}, {"_NtQueryLicenseValue@20", 5, {{"PUNICODE_STRING", "Name", sizeof(wow64::PUNICODE_STRING)}, {"PULONG", "Type", sizeof(wow64::PULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ReturnedLength", sizeof(wow64::PULONG)}}}, {"_NtQueryMultipleValueKey@24", 6, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"PKEY_VALUE_ENTRY", "ValueEntries", sizeof(wow64::PKEY_VALUE_ENTRY)}, {"ULONG", "EntryCount", sizeof(wow64::ULONG)}, {"PVOID", "ValueBuffer", sizeof(wow64::PVOID)}, {"PULONG", "BufferLength", sizeof(wow64::PULONG)}, {"PULONG", "RequiredBufferLength", sizeof(wow64::PULONG)}}}, {"_NtQueryMutant@20", 5, {{"HANDLE", "MutantHandle", sizeof(wow64::HANDLE)}, {"MUTANT_INFORMATION_CLASS", "MutantInformationClass", sizeof(wow64::MUTANT_INFORMATION_CLASS)}, {"PVOID", "MutantInformation", sizeof(wow64::PVOID)}, {"ULONG", "MutantInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryObject@20", 5, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}, {"OBJECT_INFORMATION_CLASS", "ObjectInformationClass", sizeof(wow64::OBJECT_INFORMATION_CLASS)}, {"PVOID", "ObjectInformation", sizeof(wow64::PVOID)}, {"ULONG", "ObjectInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryOpenSubKeysEx@16", 4, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "BufferLength", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"PULONG", "RequiredSize", sizeof(wow64::PULONG)}}}, {"_NtQueryOpenSubKeys@8", 2, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"PULONG", "HandleCount", sizeof(wow64::PULONG)}}}, {"_NtQueryPerformanceCounter@8", 2, {{"PLARGE_INTEGER", "PerformanceCounter", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "PerformanceFrequency", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwQueryQuotaInformationFile@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"BOOLEAN", "ReturnSingleEntry", sizeof(wow64::BOOLEAN)}, {"PVOID", "SidList", sizeof(wow64::PVOID)}, {"ULONG", "SidListLength", sizeof(wow64::ULONG)}, {"PULONG", "StartSid", sizeof(wow64::PULONG)}, {"BOOLEAN", "RestartScan", sizeof(wow64::BOOLEAN)}}}, {"_ZwQuerySection@20", 5, {{"HANDLE", "SectionHandle", sizeof(wow64::HANDLE)}, {"SECTION_INFORMATION_CLASS", "SectionInformationClass", sizeof(wow64::SECTION_INFORMATION_CLASS)}, {"PVOID", "SectionInformation", sizeof(wow64::PVOID)}, {"SIZE_T", "SectionInformationLength", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "ReturnLength", sizeof(wow64::PSIZE_T)}}}, {"_ZwQuerySecurityAttributesToken@24", 6, {{"HANDLE", "TokenHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "Attributes", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "NumberOfAttributes", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQuerySecurityObject@20", 5, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}, {"SECURITY_INFORMATION", "SecurityInformation", sizeof(wow64::SECURITY_INFORMATION)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "LengthNeeded", sizeof(wow64::PULONG)}}}, {"_ZwQuerySemaphore@20", 5, {{"HANDLE", "SemaphoreHandle", sizeof(wow64::HANDLE)}, {"SEMAPHORE_INFORMATION_CLASS", "SemaphoreInformationClass", sizeof(wow64::SEMAPHORE_INFORMATION_CLASS)}, {"PVOID", "SemaphoreInformation", sizeof(wow64::PVOID)}, {"ULONG", "SemaphoreInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwQuerySymbolicLinkObject@12", 3, {{"HANDLE", "LinkHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "LinkTarget", sizeof(wow64::PUNICODE_STRING)}, {"PULONG", "ReturnedLength", sizeof(wow64::PULONG)}}}, {"_ZwQuerySystemEnvironmentValueEx@20", 5, {{"PUNICODE_STRING", "VariableName", sizeof(wow64::PUNICODE_STRING)}, {"LPGUID", "VendorGuid", sizeof(wow64::LPGUID)}, {"PVOID", "Value", sizeof(wow64::PVOID)}, {"PULONG", "ValueLength", sizeof(wow64::PULONG)}, {"PULONG", "Attributes", sizeof(wow64::PULONG)}}}, {"_ZwQuerySystemEnvironmentValue@16", 4, {{"PUNICODE_STRING", "VariableName", sizeof(wow64::PUNICODE_STRING)}, {"PWSTR", "VariableValue", sizeof(wow64::PWSTR)}, {"USHORT", "ValueLength", sizeof(wow64::USHORT)}, {"PUSHORT", "ReturnLength", sizeof(wow64::PUSHORT)}}}, {"_ZwQuerySystemInformationEx@24", 6, {{"SYSTEM_INFORMATION_CLASS", "SystemInformationClass", sizeof(wow64::SYSTEM_INFORMATION_CLASS)}, {"PVOID", "QueryInformation", sizeof(wow64::PVOID)}, {"ULONG", "QueryInformationLength", sizeof(wow64::ULONG)}, {"PVOID", "SystemInformation", sizeof(wow64::PVOID)}, {"ULONG", "SystemInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQuerySystemInformation@16", 4, {{"SYSTEM_INFORMATION_CLASS", "SystemInformationClass", sizeof(wow64::SYSTEM_INFORMATION_CLASS)}, {"PVOID", "SystemInformation", sizeof(wow64::PVOID)}, {"ULONG", "SystemInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQuerySystemTime@4", 1, {{"PLARGE_INTEGER", "SystemTime", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwQueryTimer@20", 5, {{"HANDLE", "TimerHandle", sizeof(wow64::HANDLE)}, {"TIMER_INFORMATION_CLASS", "TimerInformationClass", sizeof(wow64::TIMER_INFORMATION_CLASS)}, {"PVOID", "TimerInformation", sizeof(wow64::PVOID)}, {"ULONG", "TimerInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtQueryTimerResolution@12", 3, {{"PULONG", "MaximumTime", sizeof(wow64::PULONG)}, {"PULONG", "MinimumTime", sizeof(wow64::PULONG)}, {"PULONG", "CurrentTime", sizeof(wow64::PULONG)}}}, {"_ZwQueryValueKey@24", 6, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "ValueName", sizeof(wow64::PUNICODE_STRING)}, {"KEY_VALUE_INFORMATION_CLASS", "KeyValueInformationClass", sizeof(wow64::KEY_VALUE_INFORMATION_CLASS)}, {"PVOID", "KeyValueInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PULONG", "ResultLength", sizeof(wow64::PULONG)}}}, {"_NtQueryVirtualMemory@24", 6, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"MEMORY_INFORMATION_CLASS", "MemoryInformationClass", sizeof(wow64::MEMORY_INFORMATION_CLASS)}, {"PVOID", "MemoryInformation", sizeof(wow64::PVOID)}, {"SIZE_T", "MemoryInformationLength", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "ReturnLength", sizeof(wow64::PSIZE_T)}}}, {"_NtQueryVolumeInformationFile@20", 5, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "FsInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"FS_INFORMATION_CLASS", "FsInformationClass", sizeof(wow64::FS_INFORMATION_CLASS)}}}, {"_NtQueueApcThreadEx@24", 6, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "UserApcReserveHandle", sizeof(wow64::HANDLE)}, {"PPS_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PPS_APC_ROUTINE)}, {"PVOID", "ApcArgument1", sizeof(wow64::PVOID)}, {"PVOID", "ApcArgument2", sizeof(wow64::PVOID)}, {"PVOID", "ApcArgument3", sizeof(wow64::PVOID)}}}, {"_NtQueueApcThread@20", 5, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PPS_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PPS_APC_ROUTINE)}, {"PVOID", "ApcArgument1", sizeof(wow64::PVOID)}, {"PVOID", "ApcArgument2", sizeof(wow64::PVOID)}, {"PVOID", "ApcArgument3", sizeof(wow64::PVOID)}}}, {"_ZwRaiseException@12", 3, {{"PEXCEPTION_RECORD", "ExceptionRecord", sizeof(wow64::PEXCEPTION_RECORD)}, {"PCONTEXT", "ContextRecord", sizeof(wow64::PCONTEXT)}, {"BOOLEAN", "FirstChance", sizeof(wow64::BOOLEAN)}}}, {"_ZwRaiseHardError@24", 6, {{"NTSTATUS", "ErrorStatus", sizeof(wow64::NTSTATUS)}, {"ULONG", "NumberOfParameters", sizeof(wow64::ULONG)}, {"ULONG", "UnicodeStringParameterMask", sizeof(wow64::ULONG)}, {"PULONG_PTR", "Parameters", sizeof(wow64::PULONG_PTR)}, {"ULONG", "ValidResponseOptions", sizeof(wow64::ULONG)}, {"PULONG", "Response", sizeof(wow64::PULONG)}}}, {"_NtReadFile@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PULONG", "Key", sizeof(wow64::PULONG)}}}, {"_NtReadFileScatter@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PFILE_SEGMENT_ELEMENT", "SegmentArray", sizeof(wow64::PFILE_SEGMENT_ELEMENT)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PULONG", "Key", sizeof(wow64::PULONG)}}}, {"_ZwReadOnlyEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwReadRequestData@24", 6, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "Message", sizeof(wow64::PPORT_MESSAGE)}, {"ULONG", "DataEntryIndex", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"SIZE_T", "BufferSize", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "NumberOfBytesRead", sizeof(wow64::PSIZE_T)}}}, {"_NtReadVirtualMemory@20", 5, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"SIZE_T", "BufferSize", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "NumberOfBytesRead", sizeof(wow64::PSIZE_T)}}}, {"_NtRecoverEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PVOID", "EnlistmentKey", sizeof(wow64::PVOID)}}}, {"_NtRecoverResourceManager@4", 1, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}}}, {"_ZwRecoverTransactionManager@4", 1, {{"HANDLE", "TransactionManagerHandle", sizeof(wow64::HANDLE)}}}, {"_ZwRegisterProtocolAddressInformation@20", 5, {{"HANDLE", "ResourceManager", sizeof(wow64::HANDLE)}, {"PCRM_PROTOCOL_ID", "ProtocolId", sizeof(wow64::PCRM_PROTOCOL_ID)}, {"ULONG", "ProtocolInformationSize", sizeof(wow64::ULONG)}, {"PVOID", "ProtocolInformation", sizeof(wow64::PVOID)}, {"ULONG", "CreateOptions", sizeof(wow64::ULONG)}}}, {"_ZwRegisterThreadTerminatePort@4", 1, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}}}, {"_NtReleaseKeyedEvent@16", 4, {{"HANDLE", "KeyedEventHandle", sizeof(wow64::HANDLE)}, {"PVOID", "KeyValue", sizeof(wow64::PVOID)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwReleaseMutant@8", 2, {{"HANDLE", "MutantHandle", sizeof(wow64::HANDLE)}, {"PLONG", "PreviousCount", sizeof(wow64::PLONG)}}}, {"_NtReleaseSemaphore@12", 3, {{"HANDLE", "SemaphoreHandle", sizeof(wow64::HANDLE)}, {"LONG", "ReleaseCount", sizeof(wow64::LONG)}, {"PLONG", "PreviousCount", sizeof(wow64::PLONG)}}}, {"_ZwReleaseWorkerFactoryWorker@4", 1, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}}}, {"_ZwRemoveIoCompletionEx@24", 6, {{"HANDLE", "IoCompletionHandle", sizeof(wow64::HANDLE)}, {"PFILE_IO_COMPLETION_INFORMATION", "IoCompletionInformation", sizeof(wow64::PFILE_IO_COMPLETION_INFORMATION)}, {"ULONG", "Count", sizeof(wow64::ULONG)}, {"PULONG", "NumEntriesRemoved", sizeof(wow64::PULONG)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}}}, {"_ZwRemoveIoCompletion@20", 5, {{"HANDLE", "IoCompletionHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARKeyContext", sizeof(wow64::PVOID)}, {"PVOID", "STARApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwRemoveProcessDebug@8", 2, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "DebugObjectHandle", sizeof(wow64::HANDLE)}}}, {"_ZwRenameKey@8", 2, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "NewName", sizeof(wow64::PUNICODE_STRING)}}}, {"_NtRenameTransactionManager@8", 2, {{"PUNICODE_STRING", "LogFileName", sizeof(wow64::PUNICODE_STRING)}, {"LPGUID", "ExistingTransactionManagerGuid", sizeof(wow64::LPGUID)}}}, {"_ZwReplaceKey@12", 3, {{"POBJECT_ATTRIBUTES", "NewFile", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "TargetHandle", sizeof(wow64::HANDLE)}, {"POBJECT_ATTRIBUTES", "OldFile", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_NtReplacePartitionUnit@12", 3, {{"PUNICODE_STRING", "TargetInstancePath", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "SpareInstancePath", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwReplyPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "ReplyMessage", sizeof(wow64::PPORT_MESSAGE)}}}, {"_NtReplyWaitReceivePortEx@20", 5, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARPortContext", sizeof(wow64::PVOID)}, {"PPORT_MESSAGE", "ReplyMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PPORT_MESSAGE", "ReceiveMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtReplyWaitReceivePort@16", 4, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARPortContext", sizeof(wow64::PVOID)}, {"PPORT_MESSAGE", "ReplyMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PPORT_MESSAGE", "ReceiveMessage", sizeof(wow64::PPORT_MESSAGE)}}}, {"_NtReplyWaitReplyPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "ReplyMessage", sizeof(wow64::PPORT_MESSAGE)}}}, {"_ZwRequestPort@8", 2, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "RequestMessage", sizeof(wow64::PPORT_MESSAGE)}}}, {"_NtRequestWaitReplyPort@12", 3, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "RequestMessage", sizeof(wow64::PPORT_MESSAGE)}, {"PPORT_MESSAGE", "ReplyMessage", sizeof(wow64::PPORT_MESSAGE)}}}, {"_NtResetEvent@8", 2, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}, {"PLONG", "PreviousState", sizeof(wow64::PLONG)}}}, {"_ZwResetWriteWatch@12", 3, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"SIZE_T", "RegionSize", sizeof(wow64::SIZE_T)}}}, {"_NtRestoreKey@12", 3, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwResumeProcess@4", 1, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}}}, {"_ZwResumeThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PULONG", "PreviousSuspendCount", sizeof(wow64::PULONG)}}}, {"_ZwRollbackComplete@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtRollbackEnlistment@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtRollbackTransaction@8", 2, {{"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "Wait", sizeof(wow64::BOOLEAN)}}}, {"_NtRollforwardTransactionManager@8", 2, {{"HANDLE", "TransactionManagerHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtSaveKeyEx@12", 3, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Format", sizeof(wow64::ULONG)}}}, {"_NtSaveKey@8", 2, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}}}, {"_NtSaveMergedKeys@12", 3, {{"HANDLE", "HighPrecedenceKeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "LowPrecedenceKeyHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}}}, {"_NtSecureConnectPort@36", 9, {{"PHANDLE", "PortHandle", sizeof(wow64::PHANDLE)}, {"PUNICODE_STRING", "PortName", sizeof(wow64::PUNICODE_STRING)}, {"PSECURITY_QUALITY_OF_SERVICE", "SecurityQos", sizeof(wow64::PSECURITY_QUALITY_OF_SERVICE)}, {"PPORT_VIEW", "ClientView", sizeof(wow64::PPORT_VIEW)}, {"PSID", "RequiredServerSid", sizeof(wow64::PSID)}, {"PREMOTE_PORT_VIEW", "ServerView", sizeof(wow64::PREMOTE_PORT_VIEW)}, {"PULONG", "MaxMessageLength", sizeof(wow64::PULONG)}, {"PVOID", "ConnectionInformation", sizeof(wow64::PVOID)}, {"PULONG", "ConnectionInformationLength", sizeof(wow64::PULONG)}}}, {"_ZwSetBootEntryOrder@8", 2, {{"PULONG", "Ids", sizeof(wow64::PULONG)}, {"ULONG", "Count", sizeof(wow64::ULONG)}}}, {"_ZwSetBootOptions@8", 2, {{"PBOOT_OPTIONS", "BootOptions", sizeof(wow64::PBOOT_OPTIONS)}, {"ULONG", "FieldsToChange", sizeof(wow64::ULONG)}}}, {"_ZwSetContextThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PCONTEXT", "ThreadContext", sizeof(wow64::PCONTEXT)}}}, {"_NtSetDebugFilterState@12", 3, {{"ULONG", "ComponentId", sizeof(wow64::ULONG)}, {"ULONG", "Level", sizeof(wow64::ULONG)}, {"BOOLEAN", "State", sizeof(wow64::BOOLEAN)}}}, {"_NtSetDefaultHardErrorPort@4", 1, {{"HANDLE", "DefaultHardErrorPort", sizeof(wow64::HANDLE)}}}, {"_NtSetDefaultLocale@8", 2, {{"BOOLEAN", "UserProfile", sizeof(wow64::BOOLEAN)}, {"LCID", "DefaultLocaleId", sizeof(wow64::LCID)}}}, {"_ZwSetDefaultUILanguage@4", 1, {{"LANGID", "DefaultUILanguageId", sizeof(wow64::LANGID)}}}, {"_NtSetDriverEntryOrder@8", 2, {{"PULONG", "Ids", sizeof(wow64::PULONG)}, {"ULONG", "Count", sizeof(wow64::ULONG)}}}, {"_ZwSetEaFile@16", 4, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}}}, {"_NtSetEventBoostPriority@4", 1, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}}}, {"_NtSetEvent@8", 2, {{"HANDLE", "EventHandle", sizeof(wow64::HANDLE)}, {"PLONG", "PreviousState", sizeof(wow64::PLONG)}}}, {"_NtSetHighEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_NtSetHighWaitLowEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_ZwSetInformationDebugObject@20", 5, {{"HANDLE", "DebugObjectHandle", sizeof(wow64::HANDLE)}, {"DEBUGOBJECTINFOCLASS", "DebugObjectInformationClass", sizeof(wow64::DEBUGOBJECTINFOCLASS)}, {"PVOID", "DebugInformation", sizeof(wow64::PVOID)}, {"ULONG", "DebugInformationLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtSetInformationEnlistment@16", 4, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"ENLISTMENT_INFORMATION_CLASS", "EnlistmentInformationClass", sizeof(wow64::ENLISTMENT_INFORMATION_CLASS)}, {"PVOID", "EnlistmentInformation", sizeof(wow64::PVOID)}, {"ULONG", "EnlistmentInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationFile@20", 5, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "FileInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"FILE_INFORMATION_CLASS", "FileInformationClass", sizeof(wow64::FILE_INFORMATION_CLASS)}}}, {"_ZwSetInformationJobObject@16", 4, {{"HANDLE", "JobHandle", sizeof(wow64::HANDLE)}, {"JOBOBJECTINFOCLASS", "JobObjectInformationClass", sizeof(wow64::JOBOBJECTINFOCLASS)}, {"PVOID", "JobObjectInformation", sizeof(wow64::PVOID)}, {"ULONG", "JobObjectInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationKey@16", 4, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"KEY_SET_INFORMATION_CLASS", "KeySetInformationClass", sizeof(wow64::KEY_SET_INFORMATION_CLASS)}, {"PVOID", "KeySetInformation", sizeof(wow64::PVOID)}, {"ULONG", "KeySetInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationObject@16", 4, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}, {"OBJECT_INFORMATION_CLASS", "ObjectInformationClass", sizeof(wow64::OBJECT_INFORMATION_CLASS)}, {"PVOID", "ObjectInformation", sizeof(wow64::PVOID)}, {"ULONG", "ObjectInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationProcess@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PROCESSINFOCLASS", "ProcessInformationClass", sizeof(wow64::PROCESSINFOCLASS)}, {"PVOID", "ProcessInformation", sizeof(wow64::PVOID)}, {"ULONG", "ProcessInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationResourceManager@16", 4, {{"HANDLE", "ResourceManagerHandle", sizeof(wow64::HANDLE)}, {"RESOURCEMANAGER_INFORMATION_CLASS", "ResourceManagerInformationClass", sizeof(wow64::RESOURCEMANAGER_INFORMATION_CLASS)}, {"PVOID", "ResourceManagerInformation", sizeof(wow64::PVOID)}, {"ULONG", "ResourceManagerInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationThread@16", 4, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"THREADINFOCLASS", "ThreadInformationClass", sizeof(wow64::THREADINFOCLASS)}, {"PVOID", "ThreadInformation", sizeof(wow64::PVOID)}, {"ULONG", "ThreadInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationToken@16", 4, {{"HANDLE", "TokenHandle", sizeof(wow64::HANDLE)}, {"TOKEN_INFORMATION_CLASS", "TokenInformationClass", sizeof(wow64::TOKEN_INFORMATION_CLASS)}, {"PVOID", "TokenInformation", sizeof(wow64::PVOID)}, {"ULONG", "TokenInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationTransaction@16", 4, {{"HANDLE", "TransactionHandle", sizeof(wow64::HANDLE)}, {"TRANSACTION_INFORMATION_CLASS", "TransactionInformationClass", sizeof(wow64::TRANSACTION_INFORMATION_CLASS)}, {"PVOID", "TransactionInformation", sizeof(wow64::PVOID)}, {"ULONG", "TransactionInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationTransactionManager@16", 4, {{"HANDLE", "TmHandle", sizeof(wow64::HANDLE)}, {"TRANSACTIONMANAGER_INFORMATION_CLASS", "TransactionManagerInformationClass", sizeof(wow64::TRANSACTIONMANAGER_INFORMATION_CLASS)}, {"PVOID", "TransactionManagerInformation", sizeof(wow64::PVOID)}, {"ULONG", "TransactionManagerInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetInformationWorkerFactory@16", 4, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}, {"WORKERFACTORYINFOCLASS", "WorkerFactoryInformationClass", sizeof(wow64::WORKERFACTORYINFOCLASS)}, {"PVOID", "WorkerFactoryInformation", sizeof(wow64::PVOID)}, {"ULONG", "WorkerFactoryInformationLength", sizeof(wow64::ULONG)}}}, {"_NtSetIntervalProfile@8", 2, {{"ULONG", "Interval", sizeof(wow64::ULONG)}, {"KPROFILE_SOURCE", "Source", sizeof(wow64::KPROFILE_SOURCE)}}}, {"_NtSetIoCompletionEx@24", 6, {{"HANDLE", "IoCompletionHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "IoCompletionReserveHandle", sizeof(wow64::HANDLE)}, {"PVOID", "KeyContext", sizeof(wow64::PVOID)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"NTSTATUS", "IoStatus", sizeof(wow64::NTSTATUS)}, {"ULONG_PTR", "IoStatusInformation", sizeof(wow64::ULONG_PTR)}}}, {"_NtSetIoCompletion@20", 5, {{"HANDLE", "IoCompletionHandle", sizeof(wow64::HANDLE)}, {"PVOID", "KeyContext", sizeof(wow64::PVOID)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"NTSTATUS", "IoStatus", sizeof(wow64::NTSTATUS)}, {"ULONG_PTR", "IoStatusInformation", sizeof(wow64::ULONG_PTR)}}}, {"_ZwSetLdtEntries@24", 6, {{"ULONG", "Selector0", sizeof(wow64::ULONG)}, {"ULONG", "Entry0Low", sizeof(wow64::ULONG)}, {"ULONG", "Entry0Hi", sizeof(wow64::ULONG)}, {"ULONG", "Selector1", sizeof(wow64::ULONG)}, {"ULONG", "Entry1Low", sizeof(wow64::ULONG)}, {"ULONG", "Entry1Hi", sizeof(wow64::ULONG)}}}, {"_ZwSetLowEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_ZwSetLowWaitHighEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_ZwSetQuotaInformationFile@16", 4, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}}}, {"_NtSetSecurityObject@12", 3, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}, {"SECURITY_INFORMATION", "SecurityInformation", sizeof(wow64::SECURITY_INFORMATION)}, {"PSECURITY_DESCRIPTOR", "SecurityDescriptor", sizeof(wow64::PSECURITY_DESCRIPTOR)}}}, {"_ZwSetSystemEnvironmentValueEx@20", 5, {{"PUNICODE_STRING", "VariableName", sizeof(wow64::PUNICODE_STRING)}, {"LPGUID", "VendorGuid", sizeof(wow64::LPGUID)}, {"PVOID", "Value", sizeof(wow64::PVOID)}, {"ULONG", "ValueLength", sizeof(wow64::ULONG)}, {"ULONG", "Attributes", sizeof(wow64::ULONG)}}}, {"_ZwSetSystemEnvironmentValue@8", 2, {{"PUNICODE_STRING", "VariableName", sizeof(wow64::PUNICODE_STRING)}, {"PUNICODE_STRING", "VariableValue", sizeof(wow64::PUNICODE_STRING)}}}, {"_ZwSetSystemInformation@12", 3, {{"SYSTEM_INFORMATION_CLASS", "SystemInformationClass", sizeof(wow64::SYSTEM_INFORMATION_CLASS)}, {"PVOID", "SystemInformation", sizeof(wow64::PVOID)}, {"ULONG", "SystemInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetSystemPowerState@12", 3, {{"POWER_ACTION", "SystemAction", sizeof(wow64::POWER_ACTION)}, {"SYSTEM_POWER_STATE", "MinSystemState", sizeof(wow64::SYSTEM_POWER_STATE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwSetSystemTime@8", 2, {{"PLARGE_INTEGER", "SystemTime", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "PreviousTime", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwSetThreadExecutionState@8", 2, {{"EXECUTION_STATE", "esFlags", sizeof(wow64::EXECUTION_STATE)}, {"EXECUTION_STATE", "STARPreviousFlags", sizeof(wow64::EXECUTION_STATE)}}}, {"_ZwSetTimerEx@16", 4, {{"HANDLE", "TimerHandle", sizeof(wow64::HANDLE)}, {"TIMER_SET_INFORMATION_CLASS", "TimerSetInformationClass", sizeof(wow64::TIMER_SET_INFORMATION_CLASS)}, {"PVOID", "TimerSetInformation", sizeof(wow64::PVOID)}, {"ULONG", "TimerSetInformationLength", sizeof(wow64::ULONG)}}}, {"_ZwSetTimer@28", 7, {{"HANDLE", "TimerHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "DueTime", sizeof(wow64::PLARGE_INTEGER)}, {"PTIMER_APC_ROUTINE", "TimerApcRoutine", sizeof(wow64::PTIMER_APC_ROUTINE)}, {"PVOID", "TimerContext", sizeof(wow64::PVOID)}, {"BOOLEAN", "WakeTimer", sizeof(wow64::BOOLEAN)}, {"LONG", "Period", sizeof(wow64::LONG)}, {"PBOOLEAN", "PreviousState", sizeof(wow64::PBOOLEAN)}}}, {"_NtSetTimerResolution@12", 3, {{"ULONG", "DesiredTime", sizeof(wow64::ULONG)}, {"BOOLEAN", "SetResolution", sizeof(wow64::BOOLEAN)}, {"PULONG", "ActualTime", sizeof(wow64::PULONG)}}}, {"_ZwSetUuidSeed@4", 1, {{"PCHAR", "Seed", sizeof(wow64::PCHAR)}}}, {"_ZwSetValueKey@24", 6, {{"HANDLE", "KeyHandle", sizeof(wow64::HANDLE)}, {"PUNICODE_STRING", "ValueName", sizeof(wow64::PUNICODE_STRING)}, {"ULONG", "TitleIndex", sizeof(wow64::ULONG)}, {"ULONG", "Type", sizeof(wow64::ULONG)}, {"PVOID", "Data", sizeof(wow64::PVOID)}, {"ULONG", "DataSize", sizeof(wow64::ULONG)}}}, {"_NtSetVolumeInformationFile@20", 5, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "FsInformation", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"FS_INFORMATION_CLASS", "FsInformationClass", sizeof(wow64::FS_INFORMATION_CLASS)}}}, {"_ZwShutdownSystem@4", 1, {{"SHUTDOWN_ACTION", "Action", sizeof(wow64::SHUTDOWN_ACTION)}}}, {"_NtShutdownWorkerFactory@8", 2, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}, {"LONG", "STARPendingWorkerCount", sizeof(wow64::LONG)}}}, {"_ZwSignalAndWaitForSingleObject@16", 4, {{"HANDLE", "SignalHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "WaitHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwSinglePhaseReject@8", 2, {{"HANDLE", "EnlistmentHandle", sizeof(wow64::HANDLE)}, {"PLARGE_INTEGER", "TmVirtualClock", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtStartProfile@4", 1, {{"HANDLE", "ProfileHandle", sizeof(wow64::HANDLE)}}}, {"_ZwStopProfile@4", 1, {{"HANDLE", "ProfileHandle", sizeof(wow64::HANDLE)}}}, {"_ZwSuspendProcess@4", 1, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}}}, {"_ZwSuspendThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"PULONG", "PreviousSuspendCount", sizeof(wow64::PULONG)}}}, {"_NtSystemDebugControl@24", 6, {{"SYSDBG_COMMAND", "Command", sizeof(wow64::SYSDBG_COMMAND)}, {"PVOID", "InputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "InputBufferLength", sizeof(wow64::ULONG)}, {"PVOID", "OutputBuffer", sizeof(wow64::PVOID)}, {"ULONG", "OutputBufferLength", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_ZwTerminateJobObject@8", 2, {{"HANDLE", "JobHandle", sizeof(wow64::HANDLE)}, {"NTSTATUS", "ExitStatus", sizeof(wow64::NTSTATUS)}}}, {"_ZwTerminateProcess@8", 2, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"NTSTATUS", "ExitStatus", sizeof(wow64::NTSTATUS)}}}, {"_ZwTerminateThread@8", 2, {{"HANDLE", "ThreadHandle", sizeof(wow64::HANDLE)}, {"NTSTATUS", "ExitStatus", sizeof(wow64::NTSTATUS)}}}, {"_ZwTraceControl@24", 6, {{"ULONG", "FunctionCode", sizeof(wow64::ULONG)}, {"PVOID", "InBuffer", sizeof(wow64::PVOID)}, {"ULONG", "InBufferLen", sizeof(wow64::ULONG)}, {"PVOID", "OutBuffer", sizeof(wow64::PVOID)}, {"ULONG", "OutBufferLen", sizeof(wow64::ULONG)}, {"PULONG", "ReturnLength", sizeof(wow64::PULONG)}}}, {"_NtTraceEvent@16", 4, {{"HANDLE", "TraceHandle", sizeof(wow64::HANDLE)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}, {"ULONG", "FieldSize", sizeof(wow64::ULONG)}, {"PVOID", "Fields", sizeof(wow64::PVOID)}}}, {"_NtTranslateFilePath@16", 4, {{"PFILE_PATH", "InputFilePath", sizeof(wow64::PFILE_PATH)}, {"ULONG", "OutputType", sizeof(wow64::ULONG)}, {"PFILE_PATH", "OutputFilePath", sizeof(wow64::PFILE_PATH)}, {"PULONG", "OutputFilePathLength", sizeof(wow64::PULONG)}}}, {"_ZwUnloadDriver@4", 1, {{"PUNICODE_STRING", "DriverServiceName", sizeof(wow64::PUNICODE_STRING)}}}, {"_ZwUnloadKey2@8", 2, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"ULONG", "Flags", sizeof(wow64::ULONG)}}}, {"_ZwUnloadKeyEx@8", 2, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}}}, {"_NtUnloadKey@4", 1, {{"POBJECT_ATTRIBUTES", "TargetKey", sizeof(wow64::POBJECT_ATTRIBUTES)}}}, {"_ZwUnlockFile@20", 5, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PLARGE_INTEGER", "Length", sizeof(wow64::PLARGE_INTEGER)}, {"ULONG", "Key", sizeof(wow64::ULONG)}}}, {"_NtUnlockVirtualMemory@16", 4, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "STARBaseAddress", sizeof(wow64::PVOID)}, {"PSIZE_T", "RegionSize", sizeof(wow64::PSIZE_T)}, {"ULONG", "MapType", sizeof(wow64::ULONG)}}}, {"_NtUnmapViewOfSection@8", 2, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}}}, {"_NtVdmControl@8", 2, {{"VDMSERVICECLASS", "Service", sizeof(wow64::VDMSERVICECLASS)}, {"PVOID", "ServiceData", sizeof(wow64::PVOID)}}}, {"_NtWaitForDebugEvent@16", 4, {{"HANDLE", "DebugObjectHandle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}, {"PDBGUI_WAIT_STATE_CHANGE", "WaitStateChange", sizeof(wow64::PDBGUI_WAIT_STATE_CHANGE)}}}, {"_NtWaitForKeyedEvent@16", 4, {{"HANDLE", "KeyedEventHandle", sizeof(wow64::HANDLE)}, {"PVOID", "KeyValue", sizeof(wow64::PVOID)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtWaitForMultipleObjects32@20", 5, {{"ULONG", "Count", sizeof(wow64::ULONG)}, {"LONG", "Handles", sizeof(wow64::LONG)}, {"WAIT_TYPE", "WaitType", sizeof(wow64::WAIT_TYPE)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtWaitForMultipleObjects@20", 5, {{"ULONG", "Count", sizeof(wow64::ULONG)}, {"HANDLE", "Handles", sizeof(wow64::HANDLE)}, {"WAIT_TYPE", "WaitType", sizeof(wow64::WAIT_TYPE)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_ZwWaitForSingleObject@12", 3, {{"HANDLE", "Handle", sizeof(wow64::HANDLE)}, {"BOOLEAN", "Alertable", sizeof(wow64::BOOLEAN)}, {"PLARGE_INTEGER", "Timeout", sizeof(wow64::PLARGE_INTEGER)}}}, {"_NtWaitForWorkViaWorkerFactory@20", 5, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}, {"PFILE_IO_COMPLETION_INFORMATION", "MiniPacket", sizeof(wow64::PFILE_IO_COMPLETION_INFORMATION)}, {"PVOID", "Arg2", sizeof(wow64::PVOID)}, {"PVOID", "Arg3", sizeof(wow64::PVOID)}, {"PVOID", "Arg4", sizeof(wow64::PVOID)}}}, {"_ZwWaitHighEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_NtWaitLowEventPair@4", 1, {{"HANDLE", "EventPairHandle", sizeof(wow64::HANDLE)}}}, {"_NtWorkerFactoryWorkerReady@4", 1, {{"HANDLE", "WorkerFactoryHandle", sizeof(wow64::HANDLE)}}}, {"_NtWriteFileGather@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PFILE_SEGMENT_ELEMENT", "SegmentArray", sizeof(wow64::PFILE_SEGMENT_ELEMENT)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PULONG", "Key", sizeof(wow64::PULONG)}}}, {"_NtWriteFile@36", 9, {{"HANDLE", "FileHandle", sizeof(wow64::HANDLE)}, {"HANDLE", "Event", sizeof(wow64::HANDLE)}, {"PIO_APC_ROUTINE", "ApcRoutine", sizeof(wow64::PIO_APC_ROUTINE)}, {"PVOID", "ApcContext", sizeof(wow64::PVOID)}, {"PIO_STATUS_BLOCK", "IoStatusBlock", sizeof(wow64::PIO_STATUS_BLOCK)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"ULONG", "Length", sizeof(wow64::ULONG)}, {"PLARGE_INTEGER", "ByteOffset", sizeof(wow64::PLARGE_INTEGER)}, {"PULONG", "Key", sizeof(wow64::PULONG)}}}, {"_NtWriteRequestData@24", 6, {{"HANDLE", "PortHandle", sizeof(wow64::HANDLE)}, {"PPORT_MESSAGE", "Message", sizeof(wow64::PPORT_MESSAGE)}, {"ULONG", "DataEntryIndex", sizeof(wow64::ULONG)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"SIZE_T", "BufferSize", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "NumberOfBytesWritten", sizeof(wow64::PSIZE_T)}}}, {"_NtWriteVirtualMemory@20", 5, {{"HANDLE", "ProcessHandle", sizeof(wow64::HANDLE)}, {"PVOID", "BaseAddress", sizeof(wow64::PVOID)}, {"PVOID", "Buffer", sizeof(wow64::PVOID)}, {"SIZE_T", "BufferSize", sizeof(wow64::SIZE_T)}, {"PSIZE_T", "NumberOfBytesWritten", sizeof(wow64::PSIZE_T)}}}, {"_NtDisableLastKnownGood@0", 0, {}}, {"_NtEnableLastKnownGood@0", 0, {}}, {"_ZwFlushProcessWriteBuffers@0", 0, {}}, {"_NtFlushWriteBuffer@0", 0, {}}, {"_NtGetCurrentProcessorNumber@0", 0, {}}, {"_NtIsSystemResumeAutomatic@0", 0, {}}, {"_ZwIsUILanguageComitted@0", 0, {}}, {"_ZwQueryPortInformationProcess@0", 0, {}}, {"_NtSerializeBoot@0", 0, {}}, {"_NtTestAlert@0", 0, {}}, {"_ZwThawRegistry@0", 0, {}}, {"_NtThawTransactions@0", 0, {}}, {"_ZwUmsThreadYield@4", 1, {{"PVOID", "SchedulerParam", sizeof(wow64::PVOID)}}}, {"_ZwYieldExecution@0", 0, {}}, }; using bpid_t = wow64::syscalls32::bpid_t; using Listeners = std::multimap<bpid_t, core::Breakpoint>; } struct wow64::syscalls32::Data { Data(core::Core& core, sym::Symbols& syms, std::string_view module); core::Core& core; sym::Symbols& syms; std::string module; Listeners listeners; bpid_t last_id; }; wow64::syscalls32::Data::Data(core::Core& core, sym::Symbols& syms, std::string_view module) : core(core) , syms(syms) , module(module) , last_id(0) { } wow64::syscalls32::syscalls32(core::Core& core, sym::Symbols& syms, std::string_view module) : d_(std::make_unique<Data>(core, syms, module)) { } wow64::syscalls32::~syscalls32() = default; namespace { static opt<bpid_t> register_callback(wow64::syscalls32::Data& d, bpid_t id, proc_t proc, const char* name, const core::Task& on_call) { const auto addr = d.syms.symbol(d.module, name); if(!addr) return FAIL(ext::nullopt, "unable to find symbole {}!{}", d.module, name); const auto bp = d.core.state.set_breakpoint(name, *addr, proc, on_call); if(!bp) return FAIL(ext::nullopt, "unable to set breakpoint"); d.listeners.emplace(id, bp); return id; } template <typename T> static T arg(core::Core& core, size_t i) { const auto arg = core.os->read_arg(i); if(!arg) return {}; T value = {}; static_assert(sizeof value <= sizeof arg->val, "invalid size"); memcpy(&value, &arg->val, sizeof value); return value; } } opt<bpid_t> wow64::syscalls32::register_NtAcceptConnectPort(proc_t proc, const on_NtAcceptConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAcceptConnectPort@24", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto PortContext = arg<wow64::PVOID>(core, 1); const auto ConnectionRequest = arg<wow64::PPORT_MESSAGE>(core, 2); const auto AcceptConnection = arg<wow64::BOOLEAN>(core, 3); const auto ServerView = arg<wow64::PPORT_VIEW>(core, 4); const auto ClientView = arg<wow64::PREMOTE_PORT_VIEW>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[0]); on_func(PortHandle, PortContext, ConnectionRequest, AcceptConnection, ServerView, ClientView); }); } opt<bpid_t> wow64::syscalls32::register_ZwAccessCheckAndAuditAlarm(proc_t proc, const on_ZwAccessCheckAndAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAccessCheckAndAuditAlarm@44", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ObjectTypeName = arg<wow64::PUNICODE_STRING>(core, 2); const auto ObjectName = arg<wow64::PUNICODE_STRING>(core, 3); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 4); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 5); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 6); const auto ObjectCreation = arg<wow64::BOOLEAN>(core, 7); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 8); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 9); const auto GenerateOnClose = arg<wow64::PBOOLEAN>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[1]); on_func(SubsystemName, HandleId, ObjectTypeName, ObjectName, SecurityDescriptor, DesiredAccess, GenericMapping, ObjectCreation, GrantedAccess, AccessStatus, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtAccessCheckByTypeAndAuditAlarm(proc_t proc, const on_NtAccessCheckByTypeAndAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAccessCheckByTypeAndAuditAlarm@64", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ObjectTypeName = arg<wow64::PUNICODE_STRING>(core, 2); const auto ObjectName = arg<wow64::PUNICODE_STRING>(core, 3); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 4); const auto PrincipalSelfSid = arg<wow64::PSID>(core, 5); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 6); const auto AuditType = arg<wow64::AUDIT_EVENT_TYPE>(core, 7); const auto Flags = arg<wow64::ULONG>(core, 8); const auto ObjectTypeList = arg<wow64::POBJECT_TYPE_LIST>(core, 9); const auto ObjectTypeListLength = arg<wow64::ULONG>(core, 10); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 11); const auto ObjectCreation = arg<wow64::BOOLEAN>(core, 12); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 13); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 14); const auto GenerateOnClose = arg<wow64::PBOOLEAN>(core, 15); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[2]); on_func(SubsystemName, HandleId, ObjectTypeName, ObjectName, SecurityDescriptor, PrincipalSelfSid, DesiredAccess, AuditType, Flags, ObjectTypeList, ObjectTypeListLength, GenericMapping, ObjectCreation, GrantedAccess, AccessStatus, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtAccessCheckByType(proc_t proc, const on_NtAccessCheckByType_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAccessCheckByType@44", [=] { auto& core = d_->core; const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 0); const auto PrincipalSelfSid = arg<wow64::PSID>(core, 1); const auto ClientToken = arg<wow64::HANDLE>(core, 2); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 3); const auto ObjectTypeList = arg<wow64::POBJECT_TYPE_LIST>(core, 4); const auto ObjectTypeListLength = arg<wow64::ULONG>(core, 5); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 6); const auto PrivilegeSet = arg<wow64::PPRIVILEGE_SET>(core, 7); const auto PrivilegeSetLength = arg<wow64::PULONG>(core, 8); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 9); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[3]); on_func(SecurityDescriptor, PrincipalSelfSid, ClientToken, DesiredAccess, ObjectTypeList, ObjectTypeListLength, GenericMapping, PrivilegeSet, PrivilegeSetLength, GrantedAccess, AccessStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwAccessCheckByTypeResultListAndAuditAlarmByHandle(proc_t proc, const on_ZwAccessCheckByTypeResultListAndAuditAlarmByHandle_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAccessCheckByTypeResultListAndAuditAlarmByHandle@68", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ClientToken = arg<wow64::HANDLE>(core, 2); const auto ObjectTypeName = arg<wow64::PUNICODE_STRING>(core, 3); const auto ObjectName = arg<wow64::PUNICODE_STRING>(core, 4); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 5); const auto PrincipalSelfSid = arg<wow64::PSID>(core, 6); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 7); const auto AuditType = arg<wow64::AUDIT_EVENT_TYPE>(core, 8); const auto Flags = arg<wow64::ULONG>(core, 9); const auto ObjectTypeList = arg<wow64::POBJECT_TYPE_LIST>(core, 10); const auto ObjectTypeListLength = arg<wow64::ULONG>(core, 11); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 12); const auto ObjectCreation = arg<wow64::BOOLEAN>(core, 13); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 14); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 15); const auto GenerateOnClose = arg<wow64::PBOOLEAN>(core, 16); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[4]); on_func(SubsystemName, HandleId, ClientToken, ObjectTypeName, ObjectName, SecurityDescriptor, PrincipalSelfSid, DesiredAccess, AuditType, Flags, ObjectTypeList, ObjectTypeListLength, GenericMapping, ObjectCreation, GrantedAccess, AccessStatus, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtAccessCheckByTypeResultListAndAuditAlarm(proc_t proc, const on_NtAccessCheckByTypeResultListAndAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAccessCheckByTypeResultListAndAuditAlarm@64", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ObjectTypeName = arg<wow64::PUNICODE_STRING>(core, 2); const auto ObjectName = arg<wow64::PUNICODE_STRING>(core, 3); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 4); const auto PrincipalSelfSid = arg<wow64::PSID>(core, 5); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 6); const auto AuditType = arg<wow64::AUDIT_EVENT_TYPE>(core, 7); const auto Flags = arg<wow64::ULONG>(core, 8); const auto ObjectTypeList = arg<wow64::POBJECT_TYPE_LIST>(core, 9); const auto ObjectTypeListLength = arg<wow64::ULONG>(core, 10); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 11); const auto ObjectCreation = arg<wow64::BOOLEAN>(core, 12); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 13); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 14); const auto GenerateOnClose = arg<wow64::PBOOLEAN>(core, 15); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[5]); on_func(SubsystemName, HandleId, ObjectTypeName, ObjectName, SecurityDescriptor, PrincipalSelfSid, DesiredAccess, AuditType, Flags, ObjectTypeList, ObjectTypeListLength, GenericMapping, ObjectCreation, GrantedAccess, AccessStatus, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtAccessCheckByTypeResultList(proc_t proc, const on_NtAccessCheckByTypeResultList_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAccessCheckByTypeResultList@44", [=] { auto& core = d_->core; const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 0); const auto PrincipalSelfSid = arg<wow64::PSID>(core, 1); const auto ClientToken = arg<wow64::HANDLE>(core, 2); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 3); const auto ObjectTypeList = arg<wow64::POBJECT_TYPE_LIST>(core, 4); const auto ObjectTypeListLength = arg<wow64::ULONG>(core, 5); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 6); const auto PrivilegeSet = arg<wow64::PPRIVILEGE_SET>(core, 7); const auto PrivilegeSetLength = arg<wow64::PULONG>(core, 8); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 9); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[6]); on_func(SecurityDescriptor, PrincipalSelfSid, ClientToken, DesiredAccess, ObjectTypeList, ObjectTypeListLength, GenericMapping, PrivilegeSet, PrivilegeSetLength, GrantedAccess, AccessStatus); }); } opt<bpid_t> wow64::syscalls32::register_NtAccessCheck(proc_t proc, const on_NtAccessCheck_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAccessCheck@32", [=] { auto& core = d_->core; const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 0); const auto ClientToken = arg<wow64::HANDLE>(core, 1); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 2); const auto GenericMapping = arg<wow64::PGENERIC_MAPPING>(core, 3); const auto PrivilegeSet = arg<wow64::PPRIVILEGE_SET>(core, 4); const auto PrivilegeSetLength = arg<wow64::PULONG>(core, 5); const auto GrantedAccess = arg<wow64::PACCESS_MASK>(core, 6); const auto AccessStatus = arg<wow64::PNTSTATUS>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[7]); on_func(SecurityDescriptor, ClientToken, DesiredAccess, GenericMapping, PrivilegeSet, PrivilegeSetLength, GrantedAccess, AccessStatus); }); } opt<bpid_t> wow64::syscalls32::register_NtAddAtom(proc_t proc, const on_NtAddAtom_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAddAtom@12", [=] { auto& core = d_->core; const auto AtomName = arg<wow64::PWSTR>(core, 0); const auto Length = arg<wow64::ULONG>(core, 1); const auto Atom = arg<wow64::PRTL_ATOM>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[8]); on_func(AtomName, Length, Atom); }); } opt<bpid_t> wow64::syscalls32::register_ZwAddBootEntry(proc_t proc, const on_ZwAddBootEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAddBootEntry@8", [=] { auto& core = d_->core; const auto BootEntry = arg<wow64::PBOOT_ENTRY>(core, 0); const auto Id = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[9]); on_func(BootEntry, Id); }); } opt<bpid_t> wow64::syscalls32::register_NtAddDriverEntry(proc_t proc, const on_NtAddDriverEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAddDriverEntry@8", [=] { auto& core = d_->core; const auto DriverEntry = arg<wow64::PEFI_DRIVER_ENTRY>(core, 0); const auto Id = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[10]); on_func(DriverEntry, Id); }); } opt<bpid_t> wow64::syscalls32::register_ZwAdjustGroupsToken(proc_t proc, const on_ZwAdjustGroupsToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAdjustGroupsToken@24", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::HANDLE>(core, 0); const auto ResetToDefault = arg<wow64::BOOLEAN>(core, 1); const auto NewState = arg<wow64::PTOKEN_GROUPS>(core, 2); const auto BufferLength = arg<wow64::ULONG>(core, 3); const auto PreviousState = arg<wow64::PTOKEN_GROUPS>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[11]); on_func(TokenHandle, ResetToDefault, NewState, BufferLength, PreviousState, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwAdjustPrivilegesToken(proc_t proc, const on_ZwAdjustPrivilegesToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAdjustPrivilegesToken@24", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::HANDLE>(core, 0); const auto DisableAllPrivileges = arg<wow64::BOOLEAN>(core, 1); const auto NewState = arg<wow64::PTOKEN_PRIVILEGES>(core, 2); const auto BufferLength = arg<wow64::ULONG>(core, 3); const auto PreviousState = arg<wow64::PTOKEN_PRIVILEGES>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[12]); on_func(TokenHandle, DisableAllPrivileges, NewState, BufferLength, PreviousState, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtAlertResumeThread(proc_t proc, const on_NtAlertResumeThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlertResumeThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousSuspendCount = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[13]); on_func(ThreadHandle, PreviousSuspendCount); }); } opt<bpid_t> wow64::syscalls32::register_NtAlertThread(proc_t proc, const on_NtAlertThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlertThread@4", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[14]); on_func(ThreadHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwAllocateLocallyUniqueId(proc_t proc, const on_ZwAllocateLocallyUniqueId_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAllocateLocallyUniqueId@4", [=] { auto& core = d_->core; const auto Luid = arg<wow64::PLUID>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[15]); on_func(Luid); }); } opt<bpid_t> wow64::syscalls32::register_NtAllocateReserveObject(proc_t proc, const on_NtAllocateReserveObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAllocateReserveObject@12", [=] { auto& core = d_->core; const auto MemoryReserveHandle = arg<wow64::PHANDLE>(core, 0); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto Type = arg<wow64::MEMORY_RESERVE_TYPE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[16]); on_func(MemoryReserveHandle, ObjectAttributes, Type); }); } opt<bpid_t> wow64::syscalls32::register_NtAllocateUserPhysicalPages(proc_t proc, const on_NtAllocateUserPhysicalPages_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAllocateUserPhysicalPages@12", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto NumberOfPages = arg<wow64::PULONG_PTR>(core, 1); const auto UserPfnArra = arg<wow64::PULONG_PTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[17]); on_func(ProcessHandle, NumberOfPages, UserPfnArra); }); } opt<bpid_t> wow64::syscalls32::register_NtAllocateUuids(proc_t proc, const on_NtAllocateUuids_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAllocateUuids@16", [=] { auto& core = d_->core; const auto Time = arg<wow64::PULARGE_INTEGER>(core, 0); const auto Range = arg<wow64::PULONG>(core, 1); const auto Sequence = arg<wow64::PULONG>(core, 2); const auto Seed = arg<wow64::PCHAR>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[18]); on_func(Time, Range, Sequence, Seed); }); } opt<bpid_t> wow64::syscalls32::register_NtAllocateVirtualMemory(proc_t proc, const on_NtAllocateVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAllocateVirtualMemory@24", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto ZeroBits = arg<wow64::ULONG_PTR>(core, 2); const auto RegionSize = arg<wow64::PSIZE_T>(core, 3); const auto AllocationType = arg<wow64::ULONG>(core, 4); const auto Protect = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[19]); on_func(ProcessHandle, STARBaseAddress, ZeroBits, RegionSize, AllocationType, Protect); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcAcceptConnectPort(proc_t proc, const on_NtAlpcAcceptConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcAcceptConnectPort@36", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto ConnectionPortHandle = arg<wow64::HANDLE>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 3); const auto PortAttributes = arg<wow64::PALPC_PORT_ATTRIBUTES>(core, 4); const auto PortContext = arg<wow64::PVOID>(core, 5); const auto ConnectionRequest = arg<wow64::PPORT_MESSAGE>(core, 6); const auto ConnectionMessageAttributes = arg<wow64::PALPC_MESSAGE_ATTRIBUTES>(core, 7); const auto AcceptConnection = arg<wow64::BOOLEAN>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[20]); on_func(PortHandle, ConnectionPortHandle, Flags, ObjectAttributes, PortAttributes, PortContext, ConnectionRequest, ConnectionMessageAttributes, AcceptConnection); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcCancelMessage(proc_t proc, const on_ZwAlpcCancelMessage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcCancelMessage@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto MessageContext = arg<wow64::PALPC_CONTEXT_ATTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[21]); on_func(PortHandle, Flags, MessageContext); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcConnectPort(proc_t proc, const on_ZwAlpcConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcConnectPort@44", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto PortName = arg<wow64::PUNICODE_STRING>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto PortAttributes = arg<wow64::PALPC_PORT_ATTRIBUTES>(core, 3); const auto Flags = arg<wow64::ULONG>(core, 4); const auto RequiredServerSid = arg<wow64::PSID>(core, 5); const auto ConnectionMessage = arg<wow64::PPORT_MESSAGE>(core, 6); const auto BufferLength = arg<wow64::PULONG>(core, 7); const auto OutMessageAttributes = arg<wow64::PALPC_MESSAGE_ATTRIBUTES>(core, 8); const auto InMessageAttributes = arg<wow64::PALPC_MESSAGE_ATTRIBUTES>(core, 9); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[22]); on_func(PortHandle, PortName, ObjectAttributes, PortAttributes, Flags, RequiredServerSid, ConnectionMessage, BufferLength, OutMessageAttributes, InMessageAttributes, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcCreatePort(proc_t proc, const on_ZwAlpcCreatePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcCreatePort@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto PortAttributes = arg<wow64::PALPC_PORT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[23]); on_func(PortHandle, ObjectAttributes, PortAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcCreatePortSection(proc_t proc, const on_NtAlpcCreatePortSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcCreatePortSection@24", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto SectionHandle = arg<wow64::HANDLE>(core, 2); const auto SectionSize = arg<wow64::SIZE_T>(core, 3); const auto AlpcSectionHandle = arg<wow64::PALPC_HANDLE>(core, 4); const auto ActualSectionSize = arg<wow64::PSIZE_T>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[24]); on_func(PortHandle, Flags, SectionHandle, SectionSize, AlpcSectionHandle, ActualSectionSize); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcCreateResourceReserve(proc_t proc, const on_ZwAlpcCreateResourceReserve_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcCreateResourceReserve@16", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto MessageSize = arg<wow64::SIZE_T>(core, 2); const auto ResourceId = arg<wow64::PALPC_HANDLE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[25]); on_func(PortHandle, Flags, MessageSize, ResourceId); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcCreateSectionView(proc_t proc, const on_ZwAlpcCreateSectionView_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcCreateSectionView@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto ViewAttributes = arg<wow64::PALPC_DATA_VIEW_ATTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[26]); on_func(PortHandle, Flags, ViewAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcCreateSecurityContext(proc_t proc, const on_ZwAlpcCreateSecurityContext_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcCreateSecurityContext@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto SecurityAttribute = arg<wow64::PALPC_SECURITY_ATTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[27]); on_func(PortHandle, Flags, SecurityAttribute); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcDeletePortSection(proc_t proc, const on_ZwAlpcDeletePortSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcDeletePortSection@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto SectionHandle = arg<wow64::ALPC_HANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[28]); on_func(PortHandle, Flags, SectionHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcDeleteResourceReserve(proc_t proc, const on_NtAlpcDeleteResourceReserve_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcDeleteResourceReserve@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto ResourceId = arg<wow64::ALPC_HANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[29]); on_func(PortHandle, Flags, ResourceId); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcDeleteSectionView(proc_t proc, const on_NtAlpcDeleteSectionView_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcDeleteSectionView@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto ViewBase = arg<wow64::PVOID>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[30]); on_func(PortHandle, Flags, ViewBase); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcDeleteSecurityContext(proc_t proc, const on_NtAlpcDeleteSecurityContext_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcDeleteSecurityContext@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto ContextHandle = arg<wow64::ALPC_HANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[31]); on_func(PortHandle, Flags, ContextHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcDisconnectPort(proc_t proc, const on_NtAlpcDisconnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcDisconnectPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[32]); on_func(PortHandle, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcImpersonateClientOfPort(proc_t proc, const on_ZwAlpcImpersonateClientOfPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcImpersonateClientOfPort@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto PortMessage = arg<wow64::PPORT_MESSAGE>(core, 1); const auto Reserved = arg<wow64::PVOID>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[33]); on_func(PortHandle, PortMessage, Reserved); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcOpenSenderProcess(proc_t proc, const on_ZwAlpcOpenSenderProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcOpenSenderProcess@24", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::PHANDLE>(core, 0); const auto PortHandle = arg<wow64::HANDLE>(core, 1); const auto PortMessage = arg<wow64::PPORT_MESSAGE>(core, 2); const auto Flags = arg<wow64::ULONG>(core, 3); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 4); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[34]); on_func(ProcessHandle, PortHandle, PortMessage, Flags, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcOpenSenderThread(proc_t proc, const on_ZwAlpcOpenSenderThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcOpenSenderThread@24", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::PHANDLE>(core, 0); const auto PortHandle = arg<wow64::HANDLE>(core, 1); const auto PortMessage = arg<wow64::PPORT_MESSAGE>(core, 2); const auto Flags = arg<wow64::ULONG>(core, 3); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 4); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[35]); on_func(ThreadHandle, PortHandle, PortMessage, Flags, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcQueryInformation(proc_t proc, const on_ZwAlpcQueryInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcQueryInformation@20", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto PortInformationClass = arg<wow64::ALPC_PORT_INFORMATION_CLASS>(core, 1); const auto PortInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[36]); on_func(PortHandle, PortInformationClass, PortInformation, Length, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwAlpcQueryInformationMessage(proc_t proc, const on_ZwAlpcQueryInformationMessage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAlpcQueryInformationMessage@24", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto PortMessage = arg<wow64::PPORT_MESSAGE>(core, 1); const auto MessageInformationClass = arg<wow64::ALPC_MESSAGE_INFORMATION_CLASS>(core, 2); const auto MessageInformation = arg<wow64::PVOID>(core, 3); const auto Length = arg<wow64::ULONG>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[37]); on_func(PortHandle, PortMessage, MessageInformationClass, MessageInformation, Length, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcRevokeSecurityContext(proc_t proc, const on_NtAlpcRevokeSecurityContext_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcRevokeSecurityContext@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto ContextHandle = arg<wow64::ALPC_HANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[38]); on_func(PortHandle, Flags, ContextHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcSendWaitReceivePort(proc_t proc, const on_NtAlpcSendWaitReceivePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcSendWaitReceivePort@32", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto SendMessage = arg<wow64::PPORT_MESSAGE>(core, 2); const auto SendMessageAttributes = arg<wow64::PALPC_MESSAGE_ATTRIBUTES>(core, 3); const auto ReceiveMessage = arg<wow64::PPORT_MESSAGE>(core, 4); const auto BufferLength = arg<wow64::PULONG>(core, 5); const auto ReceiveMessageAttributes = arg<wow64::PALPC_MESSAGE_ATTRIBUTES>(core, 6); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[39]); on_func(PortHandle, Flags, SendMessage, SendMessageAttributes, ReceiveMessage, BufferLength, ReceiveMessageAttributes, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_NtAlpcSetInformation(proc_t proc, const on_NtAlpcSetInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtAlpcSetInformation@16", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto PortInformationClass = arg<wow64::ALPC_PORT_INFORMATION_CLASS>(core, 1); const auto PortInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[40]); on_func(PortHandle, PortInformationClass, PortInformation, Length); }); } opt<bpid_t> wow64::syscalls32::register_NtApphelpCacheControl(proc_t proc, const on_NtApphelpCacheControl_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtApphelpCacheControl@8", [=] { auto& core = d_->core; const auto type = arg<wow64::APPHELPCOMMAND>(core, 0); const auto buf = arg<wow64::PVOID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[41]); on_func(type, buf); }); } opt<bpid_t> wow64::syscalls32::register_ZwAreMappedFilesTheSame(proc_t proc, const on_ZwAreMappedFilesTheSame_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAreMappedFilesTheSame@8", [=] { auto& core = d_->core; const auto File1MappedAsAnImage = arg<wow64::PVOID>(core, 0); const auto File2MappedAsFile = arg<wow64::PVOID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[42]); on_func(File1MappedAsAnImage, File2MappedAsFile); }); } opt<bpid_t> wow64::syscalls32::register_ZwAssignProcessToJobObject(proc_t proc, const on_ZwAssignProcessToJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwAssignProcessToJobObject@8", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::HANDLE>(core, 0); const auto ProcessHandle = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[43]); on_func(JobHandle, ProcessHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtCancelIoFileEx(proc_t proc, const on_NtCancelIoFileEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCancelIoFileEx@12", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoRequestToCancel = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[44]); on_func(FileHandle, IoRequestToCancel, IoStatusBlock); }); } opt<bpid_t> wow64::syscalls32::register_ZwCancelIoFile(proc_t proc, const on_ZwCancelIoFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCancelIoFile@8", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[45]); on_func(FileHandle, IoStatusBlock); }); } opt<bpid_t> wow64::syscalls32::register_NtCancelSynchronousIoFile(proc_t proc, const on_NtCancelSynchronousIoFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCancelSynchronousIoFile@12", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto IoRequestToCancel = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[46]); on_func(ThreadHandle, IoRequestToCancel, IoStatusBlock); }); } opt<bpid_t> wow64::syscalls32::register_ZwCancelTimer(proc_t proc, const on_ZwCancelTimer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCancelTimer@8", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::HANDLE>(core, 0); const auto CurrentState = arg<wow64::PBOOLEAN>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[47]); on_func(TimerHandle, CurrentState); }); } opt<bpid_t> wow64::syscalls32::register_NtClearEvent(proc_t proc, const on_NtClearEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtClearEvent@4", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[48]); on_func(EventHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtClose(proc_t proc, const on_NtClose_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtClose@4", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[49]); on_func(Handle); }); } opt<bpid_t> wow64::syscalls32::register_ZwCloseObjectAuditAlarm(proc_t proc, const on_ZwCloseObjectAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCloseObjectAuditAlarm@12", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto GenerateOnClose = arg<wow64::BOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[50]); on_func(SubsystemName, HandleId, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_ZwCommitComplete(proc_t proc, const on_ZwCommitComplete_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCommitComplete@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[51]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtCommitEnlistment(proc_t proc, const on_NtCommitEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCommitEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[52]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtCommitTransaction(proc_t proc, const on_NtCommitTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCommitTransaction@8", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::HANDLE>(core, 0); const auto Wait = arg<wow64::BOOLEAN>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[53]); on_func(TransactionHandle, Wait); }); } opt<bpid_t> wow64::syscalls32::register_NtCompactKeys(proc_t proc, const on_NtCompactKeys_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCompactKeys@8", [=] { auto& core = d_->core; const auto Count = arg<wow64::ULONG>(core, 0); const auto KeyArray = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[54]); on_func(Count, KeyArray); }); } opt<bpid_t> wow64::syscalls32::register_ZwCompareTokens(proc_t proc, const on_ZwCompareTokens_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCompareTokens@12", [=] { auto& core = d_->core; const auto FirstTokenHandle = arg<wow64::HANDLE>(core, 0); const auto SecondTokenHandle = arg<wow64::HANDLE>(core, 1); const auto Equal = arg<wow64::PBOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[55]); on_func(FirstTokenHandle, SecondTokenHandle, Equal); }); } opt<bpid_t> wow64::syscalls32::register_NtCompleteConnectPort(proc_t proc, const on_NtCompleteConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCompleteConnectPort@4", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[56]); on_func(PortHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwCompressKey(proc_t proc, const on_ZwCompressKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCompressKey@4", [=] { auto& core = d_->core; const auto Key = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[57]); on_func(Key); }); } opt<bpid_t> wow64::syscalls32::register_NtConnectPort(proc_t proc, const on_NtConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtConnectPort@32", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto PortName = arg<wow64::PUNICODE_STRING>(core, 1); const auto SecurityQos = arg<wow64::PSECURITY_QUALITY_OF_SERVICE>(core, 2); const auto ClientView = arg<wow64::PPORT_VIEW>(core, 3); const auto ServerView = arg<wow64::PREMOTE_PORT_VIEW>(core, 4); const auto MaxMessageLength = arg<wow64::PULONG>(core, 5); const auto ConnectionInformation = arg<wow64::PVOID>(core, 6); const auto ConnectionInformationLength = arg<wow64::PULONG>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[58]); on_func(PortHandle, PortName, SecurityQos, ClientView, ServerView, MaxMessageLength, ConnectionInformation, ConnectionInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwContinue(proc_t proc, const on_ZwContinue_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwContinue@8", [=] { auto& core = d_->core; const auto ContextRecord = arg<wow64::PCONTEXT>(core, 0); const auto TestAlert = arg<wow64::BOOLEAN>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[59]); on_func(ContextRecord, TestAlert); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateDebugObject(proc_t proc, const on_ZwCreateDebugObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateDebugObject@16", [=] { auto& core = d_->core; const auto DebugObjectHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Flags = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[60]); on_func(DebugObjectHandle, DesiredAccess, ObjectAttributes, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateDirectoryObject(proc_t proc, const on_ZwCreateDirectoryObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateDirectoryObject@12", [=] { auto& core = d_->core; const auto DirectoryHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[61]); on_func(DirectoryHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateEnlistment(proc_t proc, const on_ZwCreateEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateEnlistment@32", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 2); const auto TransactionHandle = arg<wow64::HANDLE>(core, 3); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 4); const auto CreateOptions = arg<wow64::ULONG>(core, 5); const auto NotificationMask = arg<wow64::NOTIFICATION_MASK>(core, 6); const auto EnlistmentKey = arg<wow64::PVOID>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[62]); on_func(EnlistmentHandle, DesiredAccess, ResourceManagerHandle, TransactionHandle, ObjectAttributes, CreateOptions, NotificationMask, EnlistmentKey); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateEvent(proc_t proc, const on_NtCreateEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateEvent@20", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto EventType = arg<wow64::EVENT_TYPE>(core, 3); const auto InitialState = arg<wow64::BOOLEAN>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[63]); on_func(EventHandle, DesiredAccess, ObjectAttributes, EventType, InitialState); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateEventPair(proc_t proc, const on_NtCreateEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateEventPair@12", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[64]); on_func(EventPairHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateFile(proc_t proc, const on_NtCreateFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateFile@44", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 3); const auto AllocationSize = arg<wow64::PLARGE_INTEGER>(core, 4); const auto FileAttributes = arg<wow64::ULONG>(core, 5); const auto ShareAccess = arg<wow64::ULONG>(core, 6); const auto CreateDisposition = arg<wow64::ULONG>(core, 7); const auto CreateOptions = arg<wow64::ULONG>(core, 8); const auto EaBuffer = arg<wow64::PVOID>(core, 9); const auto EaLength = arg<wow64::ULONG>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[65]); on_func(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, AllocationSize, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, EaBuffer, EaLength); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateIoCompletion(proc_t proc, const on_NtCreateIoCompletion_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateIoCompletion@16", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Count = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[66]); on_func(IoCompletionHandle, DesiredAccess, ObjectAttributes, Count); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateJobObject(proc_t proc, const on_ZwCreateJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateJobObject@12", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[67]); on_func(JobHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateJobSet(proc_t proc, const on_NtCreateJobSet_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateJobSet@12", [=] { auto& core = d_->core; const auto NumJob = arg<wow64::ULONG>(core, 0); const auto UserJobSet = arg<wow64::PJOB_SET_ARRAY>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[68]); on_func(NumJob, UserJobSet, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateKeyedEvent(proc_t proc, const on_ZwCreateKeyedEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateKeyedEvent@16", [=] { auto& core = d_->core; const auto KeyedEventHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Flags = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[69]); on_func(KeyedEventHandle, DesiredAccess, ObjectAttributes, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateKey(proc_t proc, const on_ZwCreateKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateKey@28", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto TitleIndex = arg<wow64::ULONG>(core, 3); const auto Class = arg<wow64::PUNICODE_STRING>(core, 4); const auto CreateOptions = arg<wow64::ULONG>(core, 5); const auto Disposition = arg<wow64::PULONG>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[70]); on_func(KeyHandle, DesiredAccess, ObjectAttributes, TitleIndex, Class, CreateOptions, Disposition); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateKeyTransacted(proc_t proc, const on_NtCreateKeyTransacted_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateKeyTransacted@32", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto TitleIndex = arg<wow64::ULONG>(core, 3); const auto Class = arg<wow64::PUNICODE_STRING>(core, 4); const auto CreateOptions = arg<wow64::ULONG>(core, 5); const auto TransactionHandle = arg<wow64::HANDLE>(core, 6); const auto Disposition = arg<wow64::PULONG>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[71]); on_func(KeyHandle, DesiredAccess, ObjectAttributes, TitleIndex, Class, CreateOptions, TransactionHandle, Disposition); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateMailslotFile(proc_t proc, const on_ZwCreateMailslotFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateMailslotFile@32", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ULONG>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 3); const auto CreateOptions = arg<wow64::ULONG>(core, 4); const auto MailslotQuota = arg<wow64::ULONG>(core, 5); const auto MaximumMessageSize = arg<wow64::ULONG>(core, 6); const auto ReadTimeout = arg<wow64::PLARGE_INTEGER>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[72]); on_func(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, CreateOptions, MailslotQuota, MaximumMessageSize, ReadTimeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateMutant(proc_t proc, const on_ZwCreateMutant_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateMutant@16", [=] { auto& core = d_->core; const auto MutantHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto InitialOwner = arg<wow64::BOOLEAN>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[73]); on_func(MutantHandle, DesiredAccess, ObjectAttributes, InitialOwner); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateNamedPipeFile(proc_t proc, const on_ZwCreateNamedPipeFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateNamedPipeFile@56", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ULONG>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 3); const auto ShareAccess = arg<wow64::ULONG>(core, 4); const auto CreateDisposition = arg<wow64::ULONG>(core, 5); const auto CreateOptions = arg<wow64::ULONG>(core, 6); const auto NamedPipeType = arg<wow64::ULONG>(core, 7); const auto ReadMode = arg<wow64::ULONG>(core, 8); const auto CompletionMode = arg<wow64::ULONG>(core, 9); const auto MaximumInstances = arg<wow64::ULONG>(core, 10); const auto InboundQuota = arg<wow64::ULONG>(core, 11); const auto OutboundQuota = arg<wow64::ULONG>(core, 12); const auto DefaultTimeout = arg<wow64::PLARGE_INTEGER>(core, 13); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[74]); on_func(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, CreateDisposition, CreateOptions, NamedPipeType, ReadMode, CompletionMode, MaximumInstances, InboundQuota, OutboundQuota, DefaultTimeout); }); } opt<bpid_t> wow64::syscalls32::register_NtCreatePagingFile(proc_t proc, const on_NtCreatePagingFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreatePagingFile@16", [=] { auto& core = d_->core; const auto PageFileName = arg<wow64::PUNICODE_STRING>(core, 0); const auto MinimumSize = arg<wow64::PLARGE_INTEGER>(core, 1); const auto MaximumSize = arg<wow64::PLARGE_INTEGER>(core, 2); const auto Priority = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[75]); on_func(PageFileName, MinimumSize, MaximumSize, Priority); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreatePort(proc_t proc, const on_ZwCreatePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreatePort@20", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto MaxConnectionInfoLength = arg<wow64::ULONG>(core, 2); const auto MaxMessageLength = arg<wow64::ULONG>(core, 3); const auto MaxPoolUsage = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[76]); on_func(PortHandle, ObjectAttributes, MaxConnectionInfoLength, MaxMessageLength, MaxPoolUsage); }); } opt<bpid_t> wow64::syscalls32::register_NtCreatePrivateNamespace(proc_t proc, const on_NtCreatePrivateNamespace_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreatePrivateNamespace@16", [=] { auto& core = d_->core; const auto NamespaceHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto BoundaryDescriptor = arg<wow64::PVOID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[77]); on_func(NamespaceHandle, DesiredAccess, ObjectAttributes, BoundaryDescriptor); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateProcessEx(proc_t proc, const on_ZwCreateProcessEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateProcessEx@36", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ParentProcess = arg<wow64::HANDLE>(core, 3); const auto Flags = arg<wow64::ULONG>(core, 4); const auto SectionHandle = arg<wow64::HANDLE>(core, 5); const auto DebugPort = arg<wow64::HANDLE>(core, 6); const auto ExceptionPort = arg<wow64::HANDLE>(core, 7); const auto JobMemberLevel = arg<wow64::ULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[78]); on_func(ProcessHandle, DesiredAccess, ObjectAttributes, ParentProcess, Flags, SectionHandle, DebugPort, ExceptionPort, JobMemberLevel); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateProcess(proc_t proc, const on_ZwCreateProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateProcess@32", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ParentProcess = arg<wow64::HANDLE>(core, 3); const auto InheritObjectTable = arg<wow64::BOOLEAN>(core, 4); const auto SectionHandle = arg<wow64::HANDLE>(core, 5); const auto DebugPort = arg<wow64::HANDLE>(core, 6); const auto ExceptionPort = arg<wow64::HANDLE>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[79]); on_func(ProcessHandle, DesiredAccess, ObjectAttributes, ParentProcess, InheritObjectTable, SectionHandle, DebugPort, ExceptionPort); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateProfileEx(proc_t proc, const on_NtCreateProfileEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateProfileEx@40", [=] { auto& core = d_->core; const auto ProfileHandle = arg<wow64::PHANDLE>(core, 0); const auto Process = arg<wow64::HANDLE>(core, 1); const auto ProfileBase = arg<wow64::PVOID>(core, 2); const auto ProfileSize = arg<wow64::SIZE_T>(core, 3); const auto BucketSize = arg<wow64::ULONG>(core, 4); const auto Buffer = arg<wow64::PULONG>(core, 5); const auto BufferSize = arg<wow64::ULONG>(core, 6); const auto ProfileSource = arg<wow64::KPROFILE_SOURCE>(core, 7); const auto GroupAffinityCount = arg<wow64::ULONG>(core, 8); const auto GroupAffinity = arg<wow64::PGROUP_AFFINITY>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[80]); on_func(ProfileHandle, Process, ProfileBase, ProfileSize, BucketSize, Buffer, BufferSize, ProfileSource, GroupAffinityCount, GroupAffinity); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateProfile(proc_t proc, const on_ZwCreateProfile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateProfile@36", [=] { auto& core = d_->core; const auto ProfileHandle = arg<wow64::PHANDLE>(core, 0); const auto Process = arg<wow64::HANDLE>(core, 1); const auto RangeBase = arg<wow64::PVOID>(core, 2); const auto RangeSize = arg<wow64::SIZE_T>(core, 3); const auto BucketSize = arg<wow64::ULONG>(core, 4); const auto Buffer = arg<wow64::PULONG>(core, 5); const auto BufferSize = arg<wow64::ULONG>(core, 6); const auto ProfileSource = arg<wow64::KPROFILE_SOURCE>(core, 7); const auto Affinity = arg<wow64::KAFFINITY>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[81]); on_func(ProfileHandle, Process, RangeBase, RangeSize, BucketSize, Buffer, BufferSize, ProfileSource, Affinity); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateResourceManager(proc_t proc, const on_ZwCreateResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateResourceManager@28", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto TmHandle = arg<wow64::HANDLE>(core, 2); const auto RmGuid = arg<wow64::LPGUID>(core, 3); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 4); const auto CreateOptions = arg<wow64::ULONG>(core, 5); const auto Description = arg<wow64::PUNICODE_STRING>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[82]); on_func(ResourceManagerHandle, DesiredAccess, TmHandle, RmGuid, ObjectAttributes, CreateOptions, Description); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateSection(proc_t proc, const on_NtCreateSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateSection@28", [=] { auto& core = d_->core; const auto SectionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto MaximumSize = arg<wow64::PLARGE_INTEGER>(core, 3); const auto SectionPageProtection = arg<wow64::ULONG>(core, 4); const auto AllocationAttributes = arg<wow64::ULONG>(core, 5); const auto FileHandle = arg<wow64::HANDLE>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[83]); on_func(SectionHandle, DesiredAccess, ObjectAttributes, MaximumSize, SectionPageProtection, AllocationAttributes, FileHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateSemaphore(proc_t proc, const on_NtCreateSemaphore_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateSemaphore@20", [=] { auto& core = d_->core; const auto SemaphoreHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto InitialCount = arg<wow64::LONG>(core, 3); const auto MaximumCount = arg<wow64::LONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[84]); on_func(SemaphoreHandle, DesiredAccess, ObjectAttributes, InitialCount, MaximumCount); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateSymbolicLinkObject(proc_t proc, const on_ZwCreateSymbolicLinkObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateSymbolicLinkObject@16", [=] { auto& core = d_->core; const auto LinkHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto LinkTarget = arg<wow64::PUNICODE_STRING>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[85]); on_func(LinkHandle, DesiredAccess, ObjectAttributes, LinkTarget); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateThreadEx(proc_t proc, const on_NtCreateThreadEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateThreadEx@44", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ProcessHandle = arg<wow64::HANDLE>(core, 3); const auto StartRoutine = arg<wow64::PVOID>(core, 4); const auto Argument = arg<wow64::PVOID>(core, 5); const auto CreateFlags = arg<wow64::ULONG>(core, 6); const auto ZeroBits = arg<wow64::ULONG_PTR>(core, 7); const auto StackSize = arg<wow64::SIZE_T>(core, 8); const auto MaximumStackSize = arg<wow64::SIZE_T>(core, 9); const auto AttributeList = arg<wow64::PPS_ATTRIBUTE_LIST>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[86]); on_func(ThreadHandle, DesiredAccess, ObjectAttributes, ProcessHandle, StartRoutine, Argument, CreateFlags, ZeroBits, StackSize, MaximumStackSize, AttributeList); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateThread(proc_t proc, const on_NtCreateThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateThread@32", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ProcessHandle = arg<wow64::HANDLE>(core, 3); const auto ClientId = arg<wow64::PCLIENT_ID>(core, 4); const auto ThreadContext = arg<wow64::PCONTEXT>(core, 5); const auto InitialTeb = arg<wow64::PINITIAL_TEB>(core, 6); const auto CreateSuspended = arg<wow64::BOOLEAN>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[87]); on_func(ThreadHandle, DesiredAccess, ObjectAttributes, ProcessHandle, ClientId, ThreadContext, InitialTeb, CreateSuspended); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateTimer(proc_t proc, const on_ZwCreateTimer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateTimer@16", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto TimerType = arg<wow64::TIMER_TYPE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[88]); on_func(TimerHandle, DesiredAccess, ObjectAttributes, TimerType); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateToken(proc_t proc, const on_NtCreateToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateToken@52", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto TokenType = arg<wow64::TOKEN_TYPE>(core, 3); const auto AuthenticationId = arg<wow64::PLUID>(core, 4); const auto ExpirationTime = arg<wow64::PLARGE_INTEGER>(core, 5); const auto User = arg<wow64::PTOKEN_USER>(core, 6); const auto Groups = arg<wow64::PTOKEN_GROUPS>(core, 7); const auto Privileges = arg<wow64::PTOKEN_PRIVILEGES>(core, 8); const auto Owner = arg<wow64::PTOKEN_OWNER>(core, 9); const auto PrimaryGroup = arg<wow64::PTOKEN_PRIMARY_GROUP>(core, 10); const auto DefaultDacl = arg<wow64::PTOKEN_DEFAULT_DACL>(core, 11); const auto TokenSource = arg<wow64::PTOKEN_SOURCE>(core, 12); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[89]); on_func(TokenHandle, DesiredAccess, ObjectAttributes, TokenType, AuthenticationId, ExpirationTime, User, Groups, Privileges, Owner, PrimaryGroup, DefaultDacl, TokenSource); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateTransactionManager(proc_t proc, const on_ZwCreateTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateTransactionManager@24", [=] { auto& core = d_->core; const auto TmHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto LogFileName = arg<wow64::PUNICODE_STRING>(core, 3); const auto CreateOptions = arg<wow64::ULONG>(core, 4); const auto CommitStrength = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[90]); on_func(TmHandle, DesiredAccess, ObjectAttributes, LogFileName, CreateOptions, CommitStrength); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateTransaction(proc_t proc, const on_NtCreateTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateTransaction@40", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Uow = arg<wow64::LPGUID>(core, 3); const auto TmHandle = arg<wow64::HANDLE>(core, 4); const auto CreateOptions = arg<wow64::ULONG>(core, 5); const auto IsolationLevel = arg<wow64::ULONG>(core, 6); const auto IsolationFlags = arg<wow64::ULONG>(core, 7); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 8); const auto Description = arg<wow64::PUNICODE_STRING>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[91]); on_func(TransactionHandle, DesiredAccess, ObjectAttributes, Uow, TmHandle, CreateOptions, IsolationLevel, IsolationFlags, Timeout, Description); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateUserProcess(proc_t proc, const on_NtCreateUserProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateUserProcess@44", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::PHANDLE>(core, 0); const auto ThreadHandle = arg<wow64::PHANDLE>(core, 1); const auto ProcessDesiredAccess = arg<wow64::ACCESS_MASK>(core, 2); const auto ThreadDesiredAccess = arg<wow64::ACCESS_MASK>(core, 3); const auto ProcessObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 4); const auto ThreadObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 5); const auto ProcessFlags = arg<wow64::ULONG>(core, 6); const auto ThreadFlags = arg<wow64::ULONG>(core, 7); const auto ProcessParameters = arg<wow64::PRTL_USER_PROCESS_PARAMETERS>(core, 8); const auto CreateInfo = arg<wow64::PPROCESS_CREATE_INFO>(core, 9); const auto AttributeList = arg<wow64::PPROCESS_ATTRIBUTE_LIST>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[92]); on_func(ProcessHandle, ThreadHandle, ProcessDesiredAccess, ThreadDesiredAccess, ProcessObjectAttributes, ThreadObjectAttributes, ProcessFlags, ThreadFlags, ProcessParameters, CreateInfo, AttributeList); }); } opt<bpid_t> wow64::syscalls32::register_ZwCreateWaitablePort(proc_t proc, const on_ZwCreateWaitablePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwCreateWaitablePort@20", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto MaxConnectionInfoLength = arg<wow64::ULONG>(core, 2); const auto MaxMessageLength = arg<wow64::ULONG>(core, 3); const auto MaxPoolUsage = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[93]); on_func(PortHandle, ObjectAttributes, MaxConnectionInfoLength, MaxMessageLength, MaxPoolUsage); }); } opt<bpid_t> wow64::syscalls32::register_NtCreateWorkerFactory(proc_t proc, const on_NtCreateWorkerFactory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtCreateWorkerFactory@40", [=] { auto& core = d_->core; const auto WorkerFactoryHandleReturn = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto CompletionPortHandle = arg<wow64::HANDLE>(core, 3); const auto WorkerProcessHandle = arg<wow64::HANDLE>(core, 4); const auto StartRoutine = arg<wow64::PVOID>(core, 5); const auto StartParameter = arg<wow64::PVOID>(core, 6); const auto MaxThreadCount = arg<wow64::ULONG>(core, 7); const auto StackReserve = arg<wow64::SIZE_T>(core, 8); const auto StackCommit = arg<wow64::SIZE_T>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[94]); on_func(WorkerFactoryHandleReturn, DesiredAccess, ObjectAttributes, CompletionPortHandle, WorkerProcessHandle, StartRoutine, StartParameter, MaxThreadCount, StackReserve, StackCommit); }); } opt<bpid_t> wow64::syscalls32::register_NtDebugActiveProcess(proc_t proc, const on_NtDebugActiveProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDebugActiveProcess@8", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto DebugObjectHandle = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[95]); on_func(ProcessHandle, DebugObjectHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwDebugContinue(proc_t proc, const on_ZwDebugContinue_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDebugContinue@12", [=] { auto& core = d_->core; const auto DebugObjectHandle = arg<wow64::HANDLE>(core, 0); const auto ClientId = arg<wow64::PCLIENT_ID>(core, 1); const auto ContinueStatus = arg<wow64::NTSTATUS>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[96]); on_func(DebugObjectHandle, ClientId, ContinueStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwDelayExecution(proc_t proc, const on_ZwDelayExecution_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDelayExecution@8", [=] { auto& core = d_->core; const auto Alertable = arg<wow64::BOOLEAN>(core, 0); const auto DelayInterval = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[97]); on_func(Alertable, DelayInterval); }); } opt<bpid_t> wow64::syscalls32::register_ZwDeleteAtom(proc_t proc, const on_ZwDeleteAtom_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDeleteAtom@4", [=] { auto& core = d_->core; const auto Atom = arg<wow64::RTL_ATOM>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[98]); on_func(Atom); }); } opt<bpid_t> wow64::syscalls32::register_NtDeleteBootEntry(proc_t proc, const on_NtDeleteBootEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDeleteBootEntry@4", [=] { auto& core = d_->core; const auto Id = arg<wow64::ULONG>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[99]); on_func(Id); }); } opt<bpid_t> wow64::syscalls32::register_ZwDeleteDriverEntry(proc_t proc, const on_ZwDeleteDriverEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDeleteDriverEntry@4", [=] { auto& core = d_->core; const auto Id = arg<wow64::ULONG>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[100]); on_func(Id); }); } opt<bpid_t> wow64::syscalls32::register_NtDeleteFile(proc_t proc, const on_NtDeleteFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDeleteFile@4", [=] { auto& core = d_->core; const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[101]); on_func(ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwDeleteKey(proc_t proc, const on_ZwDeleteKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDeleteKey@4", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[102]); on_func(KeyHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtDeleteObjectAuditAlarm(proc_t proc, const on_NtDeleteObjectAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDeleteObjectAuditAlarm@12", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto GenerateOnClose = arg<wow64::BOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[103]); on_func(SubsystemName, HandleId, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtDeletePrivateNamespace(proc_t proc, const on_NtDeletePrivateNamespace_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDeletePrivateNamespace@4", [=] { auto& core = d_->core; const auto NamespaceHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[104]); on_func(NamespaceHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtDeleteValueKey(proc_t proc, const on_NtDeleteValueKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDeleteValueKey@8", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto ValueName = arg<wow64::PUNICODE_STRING>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[105]); on_func(KeyHandle, ValueName); }); } opt<bpid_t> wow64::syscalls32::register_ZwDeviceIoControlFile(proc_t proc, const on_ZwDeviceIoControlFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDeviceIoControlFile@40", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto IoControlCode = arg<wow64::ULONG>(core, 5); const auto InputBuffer = arg<wow64::PVOID>(core, 6); const auto InputBufferLength = arg<wow64::ULONG>(core, 7); const auto OutputBuffer = arg<wow64::PVOID>(core, 8); const auto OutputBufferLength = arg<wow64::ULONG>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[106]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, IoControlCode, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength); }); } opt<bpid_t> wow64::syscalls32::register_NtDisplayString(proc_t proc, const on_NtDisplayString_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDisplayString@4", [=] { auto& core = d_->core; const auto String = arg<wow64::PUNICODE_STRING>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[107]); on_func(String); }); } opt<bpid_t> wow64::syscalls32::register_ZwDrawText(proc_t proc, const on_ZwDrawText_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDrawText@4", [=] { auto& core = d_->core; const auto Text = arg<wow64::PUNICODE_STRING>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[108]); on_func(Text); }); } opt<bpid_t> wow64::syscalls32::register_ZwDuplicateObject(proc_t proc, const on_ZwDuplicateObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwDuplicateObject@28", [=] { auto& core = d_->core; const auto SourceProcessHandle = arg<wow64::HANDLE>(core, 0); const auto SourceHandle = arg<wow64::HANDLE>(core, 1); const auto TargetProcessHandle = arg<wow64::HANDLE>(core, 2); const auto TargetHandle = arg<wow64::PHANDLE>(core, 3); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 4); const auto HandleAttributes = arg<wow64::ULONG>(core, 5); const auto Options = arg<wow64::ULONG>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[109]); on_func(SourceProcessHandle, SourceHandle, TargetProcessHandle, TargetHandle, DesiredAccess, HandleAttributes, Options); }); } opt<bpid_t> wow64::syscalls32::register_NtDuplicateToken(proc_t proc, const on_NtDuplicateToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDuplicateToken@24", [=] { auto& core = d_->core; const auto ExistingTokenHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto EffectiveOnly = arg<wow64::BOOLEAN>(core, 3); const auto TokenType = arg<wow64::TOKEN_TYPE>(core, 4); const auto NewTokenHandle = arg<wow64::PHANDLE>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[110]); on_func(ExistingTokenHandle, DesiredAccess, ObjectAttributes, EffectiveOnly, TokenType, NewTokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwEnumerateBootEntries(proc_t proc, const on_ZwEnumerateBootEntries_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwEnumerateBootEntries@8", [=] { auto& core = d_->core; const auto Buffer = arg<wow64::PVOID>(core, 0); const auto BufferLength = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[111]); on_func(Buffer, BufferLength); }); } opt<bpid_t> wow64::syscalls32::register_NtEnumerateDriverEntries(proc_t proc, const on_NtEnumerateDriverEntries_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtEnumerateDriverEntries@8", [=] { auto& core = d_->core; const auto Buffer = arg<wow64::PVOID>(core, 0); const auto BufferLength = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[112]); on_func(Buffer, BufferLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwEnumerateKey(proc_t proc, const on_ZwEnumerateKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwEnumerateKey@24", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto Index = arg<wow64::ULONG>(core, 1); const auto KeyInformationClass = arg<wow64::KEY_INFORMATION_CLASS>(core, 2); const auto KeyInformation = arg<wow64::PVOID>(core, 3); const auto Length = arg<wow64::ULONG>(core, 4); const auto ResultLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[113]); on_func(KeyHandle, Index, KeyInformationClass, KeyInformation, Length, ResultLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwEnumerateSystemEnvironmentValuesEx(proc_t proc, const on_ZwEnumerateSystemEnvironmentValuesEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwEnumerateSystemEnvironmentValuesEx@12", [=] { auto& core = d_->core; const auto InformationClass = arg<wow64::ULONG>(core, 0); const auto Buffer = arg<wow64::PVOID>(core, 1); const auto BufferLength = arg<wow64::PULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[114]); on_func(InformationClass, Buffer, BufferLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwEnumerateTransactionObject(proc_t proc, const on_ZwEnumerateTransactionObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwEnumerateTransactionObject@20", [=] { auto& core = d_->core; const auto RootObjectHandle = arg<wow64::HANDLE>(core, 0); const auto QueryType = arg<wow64::KTMOBJECT_TYPE>(core, 1); const auto ObjectCursor = arg<wow64::PKTMOBJECT_CURSOR>(core, 2); const auto ObjectCursorLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[115]); on_func(RootObjectHandle, QueryType, ObjectCursor, ObjectCursorLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtEnumerateValueKey(proc_t proc, const on_NtEnumerateValueKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtEnumerateValueKey@24", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto Index = arg<wow64::ULONG>(core, 1); const auto KeyValueInformationClass = arg<wow64::KEY_VALUE_INFORMATION_CLASS>(core, 2); const auto KeyValueInformation = arg<wow64::PVOID>(core, 3); const auto Length = arg<wow64::ULONG>(core, 4); const auto ResultLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[116]); on_func(KeyHandle, Index, KeyValueInformationClass, KeyValueInformation, Length, ResultLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwExtendSection(proc_t proc, const on_ZwExtendSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwExtendSection@8", [=] { auto& core = d_->core; const auto SectionHandle = arg<wow64::HANDLE>(core, 0); const auto NewSectionSize = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[117]); on_func(SectionHandle, NewSectionSize); }); } opt<bpid_t> wow64::syscalls32::register_NtFilterToken(proc_t proc, const on_NtFilterToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFilterToken@24", [=] { auto& core = d_->core; const auto ExistingTokenHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto SidsToDisable = arg<wow64::PTOKEN_GROUPS>(core, 2); const auto PrivilegesToDelete = arg<wow64::PTOKEN_PRIVILEGES>(core, 3); const auto RestrictedSids = arg<wow64::PTOKEN_GROUPS>(core, 4); const auto NewTokenHandle = arg<wow64::PHANDLE>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[118]); on_func(ExistingTokenHandle, Flags, SidsToDisable, PrivilegesToDelete, RestrictedSids, NewTokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtFindAtom(proc_t proc, const on_NtFindAtom_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFindAtom@12", [=] { auto& core = d_->core; const auto AtomName = arg<wow64::PWSTR>(core, 0); const auto Length = arg<wow64::ULONG>(core, 1); const auto Atom = arg<wow64::PRTL_ATOM>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[119]); on_func(AtomName, Length, Atom); }); } opt<bpid_t> wow64::syscalls32::register_ZwFlushBuffersFile(proc_t proc, const on_ZwFlushBuffersFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFlushBuffersFile@8", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[120]); on_func(FileHandle, IoStatusBlock); }); } opt<bpid_t> wow64::syscalls32::register_ZwFlushInstallUILanguage(proc_t proc, const on_ZwFlushInstallUILanguage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFlushInstallUILanguage@8", [=] { auto& core = d_->core; const auto InstallUILanguage = arg<wow64::LANGID>(core, 0); const auto SetComittedFlag = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[121]); on_func(InstallUILanguage, SetComittedFlag); }); } opt<bpid_t> wow64::syscalls32::register_ZwFlushInstructionCache(proc_t proc, const on_ZwFlushInstructionCache_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFlushInstructionCache@12", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); const auto Length = arg<wow64::SIZE_T>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[122]); on_func(ProcessHandle, BaseAddress, Length); }); } opt<bpid_t> wow64::syscalls32::register_NtFlushKey(proc_t proc, const on_NtFlushKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFlushKey@4", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[123]); on_func(KeyHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwFlushVirtualMemory(proc_t proc, const on_ZwFlushVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFlushVirtualMemory@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::PSIZE_T>(core, 2); const auto IoStatus = arg<wow64::PIO_STATUS_BLOCK>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[124]); on_func(ProcessHandle, STARBaseAddress, RegionSize, IoStatus); }); } opt<bpid_t> wow64::syscalls32::register_NtFreeUserPhysicalPages(proc_t proc, const on_NtFreeUserPhysicalPages_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFreeUserPhysicalPages@12", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto NumberOfPages = arg<wow64::PULONG_PTR>(core, 1); const auto UserPfnArra = arg<wow64::PULONG_PTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[125]); on_func(ProcessHandle, NumberOfPages, UserPfnArra); }); } opt<bpid_t> wow64::syscalls32::register_NtFreeVirtualMemory(proc_t proc, const on_NtFreeVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFreeVirtualMemory@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::PSIZE_T>(core, 2); const auto FreeType = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[126]); on_func(ProcessHandle, STARBaseAddress, RegionSize, FreeType); }); } opt<bpid_t> wow64::syscalls32::register_NtFreezeRegistry(proc_t proc, const on_NtFreezeRegistry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFreezeRegistry@4", [=] { auto& core = d_->core; const auto TimeOutInSeconds = arg<wow64::ULONG>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[127]); on_func(TimeOutInSeconds); }); } opt<bpid_t> wow64::syscalls32::register_ZwFreezeTransactions(proc_t proc, const on_ZwFreezeTransactions_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFreezeTransactions@8", [=] { auto& core = d_->core; const auto FreezeTimeout = arg<wow64::PLARGE_INTEGER>(core, 0); const auto ThawTimeout = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[128]); on_func(FreezeTimeout, ThawTimeout); }); } opt<bpid_t> wow64::syscalls32::register_NtFsControlFile(proc_t proc, const on_NtFsControlFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFsControlFile@40", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto IoControlCode = arg<wow64::ULONG>(core, 5); const auto InputBuffer = arg<wow64::PVOID>(core, 6); const auto InputBufferLength = arg<wow64::ULONG>(core, 7); const auto OutputBuffer = arg<wow64::PVOID>(core, 8); const auto OutputBufferLength = arg<wow64::ULONG>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[129]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, IoControlCode, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength); }); } opt<bpid_t> wow64::syscalls32::register_NtGetContextThread(proc_t proc, const on_NtGetContextThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetContextThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ThreadContext = arg<wow64::PCONTEXT>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[130]); on_func(ThreadHandle, ThreadContext); }); } opt<bpid_t> wow64::syscalls32::register_NtGetDevicePowerState(proc_t proc, const on_NtGetDevicePowerState_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetDevicePowerState@8", [=] { auto& core = d_->core; const auto Device = arg<wow64::HANDLE>(core, 0); const auto STARState = arg<wow64::DEVICE_POWER_STATE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[131]); on_func(Device, STARState); }); } opt<bpid_t> wow64::syscalls32::register_NtGetMUIRegistryInfo(proc_t proc, const on_NtGetMUIRegistryInfo_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetMUIRegistryInfo@12", [=] { auto& core = d_->core; const auto Flags = arg<wow64::ULONG>(core, 0); const auto DataSize = arg<wow64::PULONG>(core, 1); const auto Data = arg<wow64::PVOID>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[132]); on_func(Flags, DataSize, Data); }); } opt<bpid_t> wow64::syscalls32::register_ZwGetNextProcess(proc_t proc, const on_ZwGetNextProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwGetNextProcess@20", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto HandleAttributes = arg<wow64::ULONG>(core, 2); const auto Flags = arg<wow64::ULONG>(core, 3); const auto NewProcessHandle = arg<wow64::PHANDLE>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[133]); on_func(ProcessHandle, DesiredAccess, HandleAttributes, Flags, NewProcessHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwGetNextThread(proc_t proc, const on_ZwGetNextThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwGetNextThread@24", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto ThreadHandle = arg<wow64::HANDLE>(core, 1); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 2); const auto HandleAttributes = arg<wow64::ULONG>(core, 3); const auto Flags = arg<wow64::ULONG>(core, 4); const auto NewThreadHandle = arg<wow64::PHANDLE>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[134]); on_func(ProcessHandle, ThreadHandle, DesiredAccess, HandleAttributes, Flags, NewThreadHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtGetNlsSectionPtr(proc_t proc, const on_NtGetNlsSectionPtr_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetNlsSectionPtr@20", [=] { auto& core = d_->core; const auto SectionType = arg<wow64::ULONG>(core, 0); const auto SectionData = arg<wow64::ULONG>(core, 1); const auto ContextData = arg<wow64::PVOID>(core, 2); const auto STARSectionPointer = arg<wow64::PVOID>(core, 3); const auto SectionSize = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[135]); on_func(SectionType, SectionData, ContextData, STARSectionPointer, SectionSize); }); } opt<bpid_t> wow64::syscalls32::register_ZwGetNotificationResourceManager(proc_t proc, const on_ZwGetNotificationResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwGetNotificationResourceManager@28", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); const auto TransactionNotification = arg<wow64::PTRANSACTION_NOTIFICATION>(core, 1); const auto NotificationLength = arg<wow64::ULONG>(core, 2); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); const auto Asynchronous = arg<wow64::ULONG>(core, 5); const auto AsynchronousContext = arg<wow64::ULONG_PTR>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[136]); on_func(ResourceManagerHandle, TransactionNotification, NotificationLength, Timeout, ReturnLength, Asynchronous, AsynchronousContext); }); } opt<bpid_t> wow64::syscalls32::register_NtGetWriteWatch(proc_t proc, const on_NtGetWriteWatch_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetWriteWatch@28", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto BaseAddress = arg<wow64::PVOID>(core, 2); const auto RegionSize = arg<wow64::SIZE_T>(core, 3); const auto STARUserAddressArray = arg<wow64::PVOID>(core, 4); const auto EntriesInUserAddressArray = arg<wow64::PULONG_PTR>(core, 5); const auto Granularity = arg<wow64::PULONG>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[137]); on_func(ProcessHandle, Flags, BaseAddress, RegionSize, STARUserAddressArray, EntriesInUserAddressArray, Granularity); }); } opt<bpid_t> wow64::syscalls32::register_NtImpersonateAnonymousToken(proc_t proc, const on_NtImpersonateAnonymousToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtImpersonateAnonymousToken@4", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[138]); on_func(ThreadHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwImpersonateClientOfPort(proc_t proc, const on_ZwImpersonateClientOfPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwImpersonateClientOfPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Message = arg<wow64::PPORT_MESSAGE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[139]); on_func(PortHandle, Message); }); } opt<bpid_t> wow64::syscalls32::register_ZwImpersonateThread(proc_t proc, const on_ZwImpersonateThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwImpersonateThread@12", [=] { auto& core = d_->core; const auto ServerThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ClientThreadHandle = arg<wow64::HANDLE>(core, 1); const auto SecurityQos = arg<wow64::PSECURITY_QUALITY_OF_SERVICE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[140]); on_func(ServerThreadHandle, ClientThreadHandle, SecurityQos); }); } opt<bpid_t> wow64::syscalls32::register_NtInitializeNlsFiles(proc_t proc, const on_NtInitializeNlsFiles_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtInitializeNlsFiles@12", [=] { auto& core = d_->core; const auto STARBaseAddress = arg<wow64::PVOID>(core, 0); const auto DefaultLocaleId = arg<wow64::PLCID>(core, 1); const auto DefaultCasingTableSize = arg<wow64::PLARGE_INTEGER>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[141]); on_func(STARBaseAddress, DefaultLocaleId, DefaultCasingTableSize); }); } opt<bpid_t> wow64::syscalls32::register_ZwInitializeRegistry(proc_t proc, const on_ZwInitializeRegistry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwInitializeRegistry@4", [=] { auto& core = d_->core; const auto BootCondition = arg<wow64::USHORT>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[142]); on_func(BootCondition); }); } opt<bpid_t> wow64::syscalls32::register_NtInitiatePowerAction(proc_t proc, const on_NtInitiatePowerAction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtInitiatePowerAction@16", [=] { auto& core = d_->core; const auto SystemAction = arg<wow64::POWER_ACTION>(core, 0); const auto MinSystemState = arg<wow64::SYSTEM_POWER_STATE>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); const auto Asynchronous = arg<wow64::BOOLEAN>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[143]); on_func(SystemAction, MinSystemState, Flags, Asynchronous); }); } opt<bpid_t> wow64::syscalls32::register_ZwIsProcessInJob(proc_t proc, const on_ZwIsProcessInJob_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwIsProcessInJob@8", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto JobHandle = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[144]); on_func(ProcessHandle, JobHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwListenPort(proc_t proc, const on_ZwListenPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwListenPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto ConnectionRequest = arg<wow64::PPORT_MESSAGE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[145]); on_func(PortHandle, ConnectionRequest); }); } opt<bpid_t> wow64::syscalls32::register_NtLoadDriver(proc_t proc, const on_NtLoadDriver_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLoadDriver@4", [=] { auto& core = d_->core; const auto DriverServiceName = arg<wow64::PUNICODE_STRING>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[146]); on_func(DriverServiceName); }); } opt<bpid_t> wow64::syscalls32::register_NtLoadKey2(proc_t proc, const on_NtLoadKey2_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLoadKey2@12", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto SourceFile = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[147]); on_func(TargetKey, SourceFile, Flags); }); } opt<bpid_t> wow64::syscalls32::register_NtLoadKeyEx(proc_t proc, const on_NtLoadKeyEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLoadKeyEx@32", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto SourceFile = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); const auto TrustClassKey = arg<wow64::HANDLE>(core, 3); const auto Reserved = arg<wow64::PVOID>(core, 4); const auto ObjectContext = arg<wow64::PVOID>(core, 5); const auto CallbackReserverd = arg<wow64::PVOID>(core, 6); const auto IoStatusBlock = arg<wow64::PVOID>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[148]); on_func(TargetKey, SourceFile, Flags, TrustClassKey, Reserved, ObjectContext, CallbackReserverd, IoStatusBlock); }); } opt<bpid_t> wow64::syscalls32::register_NtLoadKey(proc_t proc, const on_NtLoadKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLoadKey@8", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto SourceFile = arg<wow64::POBJECT_ATTRIBUTES>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[149]); on_func(TargetKey, SourceFile); }); } opt<bpid_t> wow64::syscalls32::register_NtLockFile(proc_t proc, const on_NtLockFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLockFile@40", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 5); const auto Length = arg<wow64::PLARGE_INTEGER>(core, 6); const auto Key = arg<wow64::ULONG>(core, 7); const auto FailImmediately = arg<wow64::BOOLEAN>(core, 8); const auto ExclusiveLock = arg<wow64::BOOLEAN>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[150]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, ByteOffset, Length, Key, FailImmediately, ExclusiveLock); }); } opt<bpid_t> wow64::syscalls32::register_ZwLockProductActivationKeys(proc_t proc, const on_ZwLockProductActivationKeys_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwLockProductActivationKeys@8", [=] { auto& core = d_->core; const auto STARpPrivateVer = arg<wow64::ULONG>(core, 0); const auto STARpSafeMode = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[151]); on_func(STARpPrivateVer, STARpSafeMode); }); } opt<bpid_t> wow64::syscalls32::register_NtLockRegistryKey(proc_t proc, const on_NtLockRegistryKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtLockRegistryKey@4", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[152]); on_func(KeyHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwLockVirtualMemory(proc_t proc, const on_ZwLockVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwLockVirtualMemory@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::PSIZE_T>(core, 2); const auto MapType = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[153]); on_func(ProcessHandle, STARBaseAddress, RegionSize, MapType); }); } opt<bpid_t> wow64::syscalls32::register_ZwMakePermanentObject(proc_t proc, const on_ZwMakePermanentObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwMakePermanentObject@4", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[154]); on_func(Handle); }); } opt<bpid_t> wow64::syscalls32::register_NtMakeTemporaryObject(proc_t proc, const on_NtMakeTemporaryObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtMakeTemporaryObject@4", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[155]); on_func(Handle); }); } opt<bpid_t> wow64::syscalls32::register_ZwMapCMFModule(proc_t proc, const on_ZwMapCMFModule_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwMapCMFModule@24", [=] { auto& core = d_->core; const auto What = arg<wow64::ULONG>(core, 0); const auto Index = arg<wow64::ULONG>(core, 1); const auto CacheIndexOut = arg<wow64::PULONG>(core, 2); const auto CacheFlagsOut = arg<wow64::PULONG>(core, 3); const auto ViewSizeOut = arg<wow64::PULONG>(core, 4); const auto STARBaseAddress = arg<wow64::PVOID>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[156]); on_func(What, Index, CacheIndexOut, CacheFlagsOut, ViewSizeOut, STARBaseAddress); }); } opt<bpid_t> wow64::syscalls32::register_NtMapUserPhysicalPages(proc_t proc, const on_NtMapUserPhysicalPages_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtMapUserPhysicalPages@12", [=] { auto& core = d_->core; const auto VirtualAddress = arg<wow64::PVOID>(core, 0); const auto NumberOfPages = arg<wow64::ULONG_PTR>(core, 1); const auto UserPfnArra = arg<wow64::PULONG_PTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[157]); on_func(VirtualAddress, NumberOfPages, UserPfnArra); }); } opt<bpid_t> wow64::syscalls32::register_ZwMapUserPhysicalPagesScatter(proc_t proc, const on_ZwMapUserPhysicalPagesScatter_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwMapUserPhysicalPagesScatter@12", [=] { auto& core = d_->core; const auto STARVirtualAddresses = arg<wow64::PVOID>(core, 0); const auto NumberOfPages = arg<wow64::ULONG_PTR>(core, 1); const auto UserPfnArray = arg<wow64::PULONG_PTR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[158]); on_func(STARVirtualAddresses, NumberOfPages, UserPfnArray); }); } opt<bpid_t> wow64::syscalls32::register_ZwMapViewOfSection(proc_t proc, const on_ZwMapViewOfSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwMapViewOfSection@40", [=] { auto& core = d_->core; const auto SectionHandle = arg<wow64::HANDLE>(core, 0); const auto ProcessHandle = arg<wow64::HANDLE>(core, 1); const auto STARBaseAddress = arg<wow64::PVOID>(core, 2); const auto ZeroBits = arg<wow64::ULONG_PTR>(core, 3); const auto CommitSize = arg<wow64::SIZE_T>(core, 4); const auto SectionOffset = arg<wow64::PLARGE_INTEGER>(core, 5); const auto ViewSize = arg<wow64::PSIZE_T>(core, 6); const auto InheritDisposition = arg<wow64::SECTION_INHERIT>(core, 7); const auto AllocationType = arg<wow64::ULONG>(core, 8); const auto Win32Protect = arg<wow64::WIN32_PROTECTION_MASK>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[159]); on_func(SectionHandle, ProcessHandle, STARBaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, InheritDisposition, AllocationType, Win32Protect); }); } opt<bpid_t> wow64::syscalls32::register_NtModifyBootEntry(proc_t proc, const on_NtModifyBootEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtModifyBootEntry@4", [=] { auto& core = d_->core; const auto BootEntry = arg<wow64::PBOOT_ENTRY>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[160]); on_func(BootEntry); }); } opt<bpid_t> wow64::syscalls32::register_ZwModifyDriverEntry(proc_t proc, const on_ZwModifyDriverEntry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwModifyDriverEntry@4", [=] { auto& core = d_->core; const auto DriverEntry = arg<wow64::PEFI_DRIVER_ENTRY>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[161]); on_func(DriverEntry); }); } opt<bpid_t> wow64::syscalls32::register_NtNotifyChangeDirectoryFile(proc_t proc, const on_NtNotifyChangeDirectoryFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtNotifyChangeDirectoryFile@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto Buffer = arg<wow64::PVOID>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto CompletionFilter = arg<wow64::ULONG>(core, 7); const auto WatchTree = arg<wow64::BOOLEAN>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[162]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, Buffer, Length, CompletionFilter, WatchTree); }); } opt<bpid_t> wow64::syscalls32::register_NtNotifyChangeKey(proc_t proc, const on_NtNotifyChangeKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtNotifyChangeKey@40", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto CompletionFilter = arg<wow64::ULONG>(core, 5); const auto WatchTree = arg<wow64::BOOLEAN>(core, 6); const auto Buffer = arg<wow64::PVOID>(core, 7); const auto BufferSize = arg<wow64::ULONG>(core, 8); const auto Asynchronous = arg<wow64::BOOLEAN>(core, 9); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[163]); on_func(KeyHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, CompletionFilter, WatchTree, Buffer, BufferSize, Asynchronous); }); } opt<bpid_t> wow64::syscalls32::register_NtNotifyChangeMultipleKeys(proc_t proc, const on_NtNotifyChangeMultipleKeys_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtNotifyChangeMultipleKeys@48", [=] { auto& core = d_->core; const auto MasterKeyHandle = arg<wow64::HANDLE>(core, 0); const auto Count = arg<wow64::ULONG>(core, 1); const auto SlaveObjects = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Event = arg<wow64::HANDLE>(core, 3); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 4); const auto ApcContext = arg<wow64::PVOID>(core, 5); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 6); const auto CompletionFilter = arg<wow64::ULONG>(core, 7); const auto WatchTree = arg<wow64::BOOLEAN>(core, 8); const auto Buffer = arg<wow64::PVOID>(core, 9); const auto BufferSize = arg<wow64::ULONG>(core, 10); const auto Asynchronous = arg<wow64::BOOLEAN>(core, 11); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[164]); on_func(MasterKeyHandle, Count, SlaveObjects, Event, ApcRoutine, ApcContext, IoStatusBlock, CompletionFilter, WatchTree, Buffer, BufferSize, Asynchronous); }); } opt<bpid_t> wow64::syscalls32::register_NtNotifyChangeSession(proc_t proc, const on_NtNotifyChangeSession_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtNotifyChangeSession@32", [=] { auto& core = d_->core; const auto Session = arg<wow64::HANDLE>(core, 0); const auto IoStateSequence = arg<wow64::ULONG>(core, 1); const auto Reserved = arg<wow64::PVOID>(core, 2); const auto Action = arg<wow64::ULONG>(core, 3); const auto IoState = arg<wow64::IO_SESSION_STATE>(core, 4); const auto IoState2 = arg<wow64::IO_SESSION_STATE>(core, 5); const auto Buffer = arg<wow64::PVOID>(core, 6); const auto BufferSize = arg<wow64::ULONG>(core, 7); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[165]); on_func(Session, IoStateSequence, Reserved, Action, IoState, IoState2, Buffer, BufferSize); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenDirectoryObject(proc_t proc, const on_ZwOpenDirectoryObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenDirectoryObject@12", [=] { auto& core = d_->core; const auto DirectoryHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[166]); on_func(DirectoryHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenEnlistment(proc_t proc, const on_ZwOpenEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenEnlistment@20", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 2); const auto EnlistmentGuid = arg<wow64::LPGUID>(core, 3); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[167]); on_func(EnlistmentHandle, DesiredAccess, ResourceManagerHandle, EnlistmentGuid, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenEvent(proc_t proc, const on_NtOpenEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenEvent@12", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[168]); on_func(EventHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenEventPair(proc_t proc, const on_NtOpenEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenEventPair@12", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[169]); on_func(EventPairHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenFile(proc_t proc, const on_NtOpenFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenFile@24", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 3); const auto ShareAccess = arg<wow64::ULONG>(core, 4); const auto OpenOptions = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[170]); on_func(FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, ShareAccess, OpenOptions); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenIoCompletion(proc_t proc, const on_ZwOpenIoCompletion_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenIoCompletion@12", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[171]); on_func(IoCompletionHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenJobObject(proc_t proc, const on_ZwOpenJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenJobObject@12", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[172]); on_func(JobHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenKeyedEvent(proc_t proc, const on_NtOpenKeyedEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenKeyedEvent@12", [=] { auto& core = d_->core; const auto KeyedEventHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[173]); on_func(KeyedEventHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenKeyEx(proc_t proc, const on_ZwOpenKeyEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenKeyEx@16", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto OpenOptions = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[174]); on_func(KeyHandle, DesiredAccess, ObjectAttributes, OpenOptions); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenKey(proc_t proc, const on_ZwOpenKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenKey@12", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[175]); on_func(KeyHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenKeyTransactedEx(proc_t proc, const on_NtOpenKeyTransactedEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenKeyTransactedEx@20", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto OpenOptions = arg<wow64::ULONG>(core, 3); const auto TransactionHandle = arg<wow64::HANDLE>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[176]); on_func(KeyHandle, DesiredAccess, ObjectAttributes, OpenOptions, TransactionHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenKeyTransacted(proc_t proc, const on_NtOpenKeyTransacted_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenKeyTransacted@16", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto TransactionHandle = arg<wow64::HANDLE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[177]); on_func(KeyHandle, DesiredAccess, ObjectAttributes, TransactionHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenMutant(proc_t proc, const on_NtOpenMutant_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenMutant@12", [=] { auto& core = d_->core; const auto MutantHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[178]); on_func(MutantHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenObjectAuditAlarm(proc_t proc, const on_ZwOpenObjectAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenObjectAuditAlarm@48", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ObjectTypeName = arg<wow64::PUNICODE_STRING>(core, 2); const auto ObjectName = arg<wow64::PUNICODE_STRING>(core, 3); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 4); const auto ClientToken = arg<wow64::HANDLE>(core, 5); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 6); const auto GrantedAccess = arg<wow64::ACCESS_MASK>(core, 7); const auto Privileges = arg<wow64::PPRIVILEGE_SET>(core, 8); const auto ObjectCreation = arg<wow64::BOOLEAN>(core, 9); const auto AccessGranted = arg<wow64::BOOLEAN>(core, 10); const auto GenerateOnClose = arg<wow64::PBOOLEAN>(core, 11); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[179]); on_func(SubsystemName, HandleId, ObjectTypeName, ObjectName, SecurityDescriptor, ClientToken, DesiredAccess, GrantedAccess, Privileges, ObjectCreation, AccessGranted, GenerateOnClose); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenPrivateNamespace(proc_t proc, const on_NtOpenPrivateNamespace_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenPrivateNamespace@16", [=] { auto& core = d_->core; const auto NamespaceHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto BoundaryDescriptor = arg<wow64::PVOID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[180]); on_func(NamespaceHandle, DesiredAccess, ObjectAttributes, BoundaryDescriptor); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenProcess(proc_t proc, const on_ZwOpenProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenProcess@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ClientId = arg<wow64::PCLIENT_ID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[181]); on_func(ProcessHandle, DesiredAccess, ObjectAttributes, ClientId); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenProcessTokenEx(proc_t proc, const on_ZwOpenProcessTokenEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenProcessTokenEx@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto HandleAttributes = arg<wow64::ULONG>(core, 2); const auto TokenHandle = arg<wow64::PHANDLE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[182]); on_func(ProcessHandle, DesiredAccess, HandleAttributes, TokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenProcessToken(proc_t proc, const on_ZwOpenProcessToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenProcessToken@12", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto TokenHandle = arg<wow64::PHANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[183]); on_func(ProcessHandle, DesiredAccess, TokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenResourceManager(proc_t proc, const on_ZwOpenResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenResourceManager@20", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto TmHandle = arg<wow64::HANDLE>(core, 2); const auto ResourceManagerGuid = arg<wow64::LPGUID>(core, 3); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[184]); on_func(ResourceManagerHandle, DesiredAccess, TmHandle, ResourceManagerGuid, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenSection(proc_t proc, const on_NtOpenSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenSection@12", [=] { auto& core = d_->core; const auto SectionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[185]); on_func(SectionHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenSemaphore(proc_t proc, const on_NtOpenSemaphore_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenSemaphore@12", [=] { auto& core = d_->core; const auto SemaphoreHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[186]); on_func(SemaphoreHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenSession(proc_t proc, const on_NtOpenSession_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenSession@12", [=] { auto& core = d_->core; const auto SessionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[187]); on_func(SessionHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenSymbolicLinkObject(proc_t proc, const on_NtOpenSymbolicLinkObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenSymbolicLinkObject@12", [=] { auto& core = d_->core; const auto LinkHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[188]); on_func(LinkHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenThread(proc_t proc, const on_ZwOpenThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenThread@16", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto ClientId = arg<wow64::PCLIENT_ID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[189]); on_func(ThreadHandle, DesiredAccess, ObjectAttributes, ClientId); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenThreadTokenEx(proc_t proc, const on_NtOpenThreadTokenEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenThreadTokenEx@20", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto OpenAsSelf = arg<wow64::BOOLEAN>(core, 2); const auto HandleAttributes = arg<wow64::ULONG>(core, 3); const auto TokenHandle = arg<wow64::PHANDLE>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[190]); on_func(ThreadHandle, DesiredAccess, OpenAsSelf, HandleAttributes, TokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtOpenThreadToken(proc_t proc, const on_NtOpenThreadToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtOpenThreadToken@16", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto OpenAsSelf = arg<wow64::BOOLEAN>(core, 2); const auto TokenHandle = arg<wow64::PHANDLE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[191]); on_func(ThreadHandle, DesiredAccess, OpenAsSelf, TokenHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenTimer(proc_t proc, const on_ZwOpenTimer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenTimer@12", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[192]); on_func(TimerHandle, DesiredAccess, ObjectAttributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenTransactionManager(proc_t proc, const on_ZwOpenTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenTransactionManager@24", [=] { auto& core = d_->core; const auto TmHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto LogFileName = arg<wow64::PUNICODE_STRING>(core, 3); const auto TmIdentity = arg<wow64::LPGUID>(core, 4); const auto OpenOptions = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[193]); on_func(TmHandle, DesiredAccess, ObjectAttributes, LogFileName, TmIdentity, OpenOptions); }); } opt<bpid_t> wow64::syscalls32::register_ZwOpenTransaction(proc_t proc, const on_ZwOpenTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwOpenTransaction@20", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::PHANDLE>(core, 0); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 1); const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); const auto Uow = arg<wow64::LPGUID>(core, 3); const auto TmHandle = arg<wow64::HANDLE>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[194]); on_func(TransactionHandle, DesiredAccess, ObjectAttributes, Uow, TmHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtPlugPlayControl(proc_t proc, const on_NtPlugPlayControl_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtPlugPlayControl@12", [=] { auto& core = d_->core; const auto PnPControlClass = arg<wow64::PLUGPLAY_CONTROL_CLASS>(core, 0); const auto PnPControlData = arg<wow64::PVOID>(core, 1); const auto PnPControlDataLength = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[195]); on_func(PnPControlClass, PnPControlData, PnPControlDataLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwPowerInformation(proc_t proc, const on_ZwPowerInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPowerInformation@20", [=] { auto& core = d_->core; const auto InformationLevel = arg<wow64::POWER_INFORMATION_LEVEL>(core, 0); const auto InputBuffer = arg<wow64::PVOID>(core, 1); const auto InputBufferLength = arg<wow64::ULONG>(core, 2); const auto OutputBuffer = arg<wow64::PVOID>(core, 3); const auto OutputBufferLength = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[196]); on_func(InformationLevel, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength); }); } opt<bpid_t> wow64::syscalls32::register_NtPrepareComplete(proc_t proc, const on_NtPrepareComplete_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtPrepareComplete@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[197]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_ZwPrepareEnlistment(proc_t proc, const on_ZwPrepareEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPrepareEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[198]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_ZwPrePrepareComplete(proc_t proc, const on_ZwPrePrepareComplete_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPrePrepareComplete@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[199]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtPrePrepareEnlistment(proc_t proc, const on_NtPrePrepareEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtPrePrepareEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[200]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_ZwPrivilegeCheck(proc_t proc, const on_ZwPrivilegeCheck_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPrivilegeCheck@12", [=] { auto& core = d_->core; const auto ClientToken = arg<wow64::HANDLE>(core, 0); const auto RequiredPrivileges = arg<wow64::PPRIVILEGE_SET>(core, 1); const auto Result = arg<wow64::PBOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[201]); on_func(ClientToken, RequiredPrivileges, Result); }); } opt<bpid_t> wow64::syscalls32::register_NtPrivilegedServiceAuditAlarm(proc_t proc, const on_NtPrivilegedServiceAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtPrivilegedServiceAuditAlarm@20", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto ServiceName = arg<wow64::PUNICODE_STRING>(core, 1); const auto ClientToken = arg<wow64::HANDLE>(core, 2); const auto Privileges = arg<wow64::PPRIVILEGE_SET>(core, 3); const auto AccessGranted = arg<wow64::BOOLEAN>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[202]); on_func(SubsystemName, ServiceName, ClientToken, Privileges, AccessGranted); }); } opt<bpid_t> wow64::syscalls32::register_ZwPrivilegeObjectAuditAlarm(proc_t proc, const on_ZwPrivilegeObjectAuditAlarm_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPrivilegeObjectAuditAlarm@24", [=] { auto& core = d_->core; const auto SubsystemName = arg<wow64::PUNICODE_STRING>(core, 0); const auto HandleId = arg<wow64::PVOID>(core, 1); const auto ClientToken = arg<wow64::HANDLE>(core, 2); const auto DesiredAccess = arg<wow64::ACCESS_MASK>(core, 3); const auto Privileges = arg<wow64::PPRIVILEGE_SET>(core, 4); const auto AccessGranted = arg<wow64::BOOLEAN>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[203]); on_func(SubsystemName, HandleId, ClientToken, DesiredAccess, Privileges, AccessGranted); }); } opt<bpid_t> wow64::syscalls32::register_NtPropagationComplete(proc_t proc, const on_NtPropagationComplete_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtPropagationComplete@16", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); const auto RequestCookie = arg<wow64::ULONG>(core, 1); const auto BufferLength = arg<wow64::ULONG>(core, 2); const auto Buffer = arg<wow64::PVOID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[204]); on_func(ResourceManagerHandle, RequestCookie, BufferLength, Buffer); }); } opt<bpid_t> wow64::syscalls32::register_ZwPropagationFailed(proc_t proc, const on_ZwPropagationFailed_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPropagationFailed@12", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); const auto RequestCookie = arg<wow64::ULONG>(core, 1); const auto PropStatus = arg<wow64::NTSTATUS>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[205]); on_func(ResourceManagerHandle, RequestCookie, PropStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwProtectVirtualMemory(proc_t proc, const on_ZwProtectVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwProtectVirtualMemory@20", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::PSIZE_T>(core, 2); const auto NewProtectWin32 = arg<wow64::WIN32_PROTECTION_MASK>(core, 3); const auto OldProtect = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[206]); on_func(ProcessHandle, STARBaseAddress, RegionSize, NewProtectWin32, OldProtect); }); } opt<bpid_t> wow64::syscalls32::register_ZwPulseEvent(proc_t proc, const on_ZwPulseEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwPulseEvent@8", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousState = arg<wow64::PLONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[207]); on_func(EventHandle, PreviousState); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryAttributesFile(proc_t proc, const on_ZwQueryAttributesFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryAttributesFile@8", [=] { auto& core = d_->core; const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto FileInformation = arg<wow64::PFILE_BASIC_INFORMATION>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[208]); on_func(ObjectAttributes, FileInformation); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryBootEntryOrder(proc_t proc, const on_ZwQueryBootEntryOrder_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryBootEntryOrder@8", [=] { auto& core = d_->core; const auto Ids = arg<wow64::PULONG>(core, 0); const auto Count = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[209]); on_func(Ids, Count); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryBootOptions(proc_t proc, const on_ZwQueryBootOptions_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryBootOptions@8", [=] { auto& core = d_->core; const auto BootOptions = arg<wow64::PBOOT_OPTIONS>(core, 0); const auto BootOptionsLength = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[210]); on_func(BootOptions, BootOptionsLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryDebugFilterState(proc_t proc, const on_NtQueryDebugFilterState_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryDebugFilterState@8", [=] { auto& core = d_->core; const auto ComponentId = arg<wow64::ULONG>(core, 0); const auto Level = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[211]); on_func(ComponentId, Level); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryDefaultLocale(proc_t proc, const on_NtQueryDefaultLocale_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryDefaultLocale@8", [=] { auto& core = d_->core; const auto UserProfile = arg<wow64::BOOLEAN>(core, 0); const auto DefaultLocaleId = arg<wow64::PLCID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[212]); on_func(UserProfile, DefaultLocaleId); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryDefaultUILanguage(proc_t proc, const on_ZwQueryDefaultUILanguage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryDefaultUILanguage@4", [=] { auto& core = d_->core; const auto STARDefaultUILanguageId = arg<wow64::LANGID>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[213]); on_func(STARDefaultUILanguageId); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryDirectoryFile(proc_t proc, const on_ZwQueryDirectoryFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryDirectoryFile@44", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto FileInformation = arg<wow64::PVOID>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto FileInformationClass = arg<wow64::FILE_INFORMATION_CLASS>(core, 7); const auto ReturnSingleEntry = arg<wow64::BOOLEAN>(core, 8); const auto FileName = arg<wow64::PUNICODE_STRING>(core, 9); const auto RestartScan = arg<wow64::BOOLEAN>(core, 10); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[214]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, FileInformation, Length, FileInformationClass, ReturnSingleEntry, FileName, RestartScan); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryDirectoryObject(proc_t proc, const on_ZwQueryDirectoryObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryDirectoryObject@28", [=] { auto& core = d_->core; const auto DirectoryHandle = arg<wow64::HANDLE>(core, 0); const auto Buffer = arg<wow64::PVOID>(core, 1); const auto Length = arg<wow64::ULONG>(core, 2); const auto ReturnSingleEntry = arg<wow64::BOOLEAN>(core, 3); const auto RestartScan = arg<wow64::BOOLEAN>(core, 4); const auto Context = arg<wow64::PULONG>(core, 5); const auto ReturnLength = arg<wow64::PULONG>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[215]); on_func(DirectoryHandle, Buffer, Length, ReturnSingleEntry, RestartScan, Context, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryDriverEntryOrder(proc_t proc, const on_NtQueryDriverEntryOrder_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryDriverEntryOrder@8", [=] { auto& core = d_->core; const auto Ids = arg<wow64::PULONG>(core, 0); const auto Count = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[216]); on_func(Ids, Count); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryEaFile(proc_t proc, const on_ZwQueryEaFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryEaFile@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ReturnSingleEntry = arg<wow64::BOOLEAN>(core, 4); const auto EaList = arg<wow64::PVOID>(core, 5); const auto EaListLength = arg<wow64::ULONG>(core, 6); const auto EaIndex = arg<wow64::PULONG>(core, 7); const auto RestartScan = arg<wow64::BOOLEAN>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[217]); on_func(FileHandle, IoStatusBlock, Buffer, Length, ReturnSingleEntry, EaList, EaListLength, EaIndex, RestartScan); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryEvent(proc_t proc, const on_NtQueryEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryEvent@20", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); const auto EventInformationClass = arg<wow64::EVENT_INFORMATION_CLASS>(core, 1); const auto EventInformation = arg<wow64::PVOID>(core, 2); const auto EventInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[218]); on_func(EventHandle, EventInformationClass, EventInformation, EventInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryFullAttributesFile(proc_t proc, const on_ZwQueryFullAttributesFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryFullAttributesFile@8", [=] { auto& core = d_->core; const auto ObjectAttributes = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto FileInformation = arg<wow64::PFILE_NETWORK_OPEN_INFORMATION>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[219]); on_func(ObjectAttributes, FileInformation); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryInformationAtom(proc_t proc, const on_NtQueryInformationAtom_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryInformationAtom@20", [=] { auto& core = d_->core; const auto Atom = arg<wow64::RTL_ATOM>(core, 0); const auto InformationClass = arg<wow64::ATOM_INFORMATION_CLASS>(core, 1); const auto AtomInformation = arg<wow64::PVOID>(core, 2); const auto AtomInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[220]); on_func(Atom, InformationClass, AtomInformation, AtomInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationEnlistment(proc_t proc, const on_ZwQueryInformationEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationEnlistment@20", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto EnlistmentInformationClass = arg<wow64::ENLISTMENT_INFORMATION_CLASS>(core, 1); const auto EnlistmentInformation = arg<wow64::PVOID>(core, 2); const auto EnlistmentInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[221]); on_func(EnlistmentHandle, EnlistmentInformationClass, EnlistmentInformation, EnlistmentInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationFile(proc_t proc, const on_ZwQueryInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationFile@20", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto FileInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto FileInformationClass = arg<wow64::FILE_INFORMATION_CLASS>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[222]); on_func(FileHandle, IoStatusBlock, FileInformation, Length, FileInformationClass); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationJobObject(proc_t proc, const on_ZwQueryInformationJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationJobObject@20", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::HANDLE>(core, 0); const auto JobObjectInformationClass = arg<wow64::JOBOBJECTINFOCLASS>(core, 1); const auto JobObjectInformation = arg<wow64::PVOID>(core, 2); const auto JobObjectInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[223]); on_func(JobHandle, JobObjectInformationClass, JobObjectInformation, JobObjectInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationPort(proc_t proc, const on_ZwQueryInformationPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationPort@20", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto PortInformationClass = arg<wow64::PORT_INFORMATION_CLASS>(core, 1); const auto PortInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[224]); on_func(PortHandle, PortInformationClass, PortInformation, Length, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationProcess(proc_t proc, const on_ZwQueryInformationProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationProcess@20", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto ProcessInformationClass = arg<wow64::PROCESSINFOCLASS>(core, 1); const auto ProcessInformation = arg<wow64::PVOID>(core, 2); const auto ProcessInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[225]); on_func(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationResourceManager(proc_t proc, const on_ZwQueryInformationResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationResourceManager@20", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); const auto ResourceManagerInformationClass = arg<wow64::RESOURCEMANAGER_INFORMATION_CLASS>(core, 1); const auto ResourceManagerInformation = arg<wow64::PVOID>(core, 2); const auto ResourceManagerInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[226]); on_func(ResourceManagerHandle, ResourceManagerInformationClass, ResourceManagerInformation, ResourceManagerInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryInformationThread(proc_t proc, const on_NtQueryInformationThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryInformationThread@20", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ThreadInformationClass = arg<wow64::THREADINFOCLASS>(core, 1); const auto ThreadInformation = arg<wow64::PVOID>(core, 2); const auto ThreadInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[227]); on_func(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationToken(proc_t proc, const on_ZwQueryInformationToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationToken@20", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::HANDLE>(core, 0); const auto TokenInformationClass = arg<wow64::TOKEN_INFORMATION_CLASS>(core, 1); const auto TokenInformation = arg<wow64::PVOID>(core, 2); const auto TokenInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[228]); on_func(TokenHandle, TokenInformationClass, TokenInformation, TokenInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationTransaction(proc_t proc, const on_ZwQueryInformationTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationTransaction@20", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::HANDLE>(core, 0); const auto TransactionInformationClass = arg<wow64::TRANSACTION_INFORMATION_CLASS>(core, 1); const auto TransactionInformation = arg<wow64::PVOID>(core, 2); const auto TransactionInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[229]); on_func(TransactionHandle, TransactionInformationClass, TransactionInformation, TransactionInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryInformationTransactionManager(proc_t proc, const on_NtQueryInformationTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryInformationTransactionManager@20", [=] { auto& core = d_->core; const auto TransactionManagerHandle = arg<wow64::HANDLE>(core, 0); const auto TransactionManagerInformationClass = arg<wow64::TRANSACTIONMANAGER_INFORMATION_CLASS>(core, 1); const auto TransactionManagerInformation = arg<wow64::PVOID>(core, 2); const auto TransactionManagerInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[230]); on_func(TransactionManagerHandle, TransactionManagerInformationClass, TransactionManagerInformation, TransactionManagerInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryInformationWorkerFactory(proc_t proc, const on_ZwQueryInformationWorkerFactory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryInformationWorkerFactory@20", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); const auto WorkerFactoryInformationClass = arg<wow64::WORKERFACTORYINFOCLASS>(core, 1); const auto WorkerFactoryInformation = arg<wow64::PVOID>(core, 2); const auto WorkerFactoryInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[231]); on_func(WorkerFactoryHandle, WorkerFactoryInformationClass, WorkerFactoryInformation, WorkerFactoryInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryInstallUILanguage(proc_t proc, const on_NtQueryInstallUILanguage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryInstallUILanguage@4", [=] { auto& core = d_->core; const auto STARInstallUILanguageId = arg<wow64::LANGID>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[232]); on_func(STARInstallUILanguageId); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryIntervalProfile(proc_t proc, const on_NtQueryIntervalProfile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryIntervalProfile@8", [=] { auto& core = d_->core; const auto ProfileSource = arg<wow64::KPROFILE_SOURCE>(core, 0); const auto Interval = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[233]); on_func(ProfileSource, Interval); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryIoCompletion(proc_t proc, const on_NtQueryIoCompletion_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryIoCompletion@20", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::HANDLE>(core, 0); const auto IoCompletionInformationClass = arg<wow64::IO_COMPLETION_INFORMATION_CLASS>(core, 1); const auto IoCompletionInformation = arg<wow64::PVOID>(core, 2); const auto IoCompletionInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[234]); on_func(IoCompletionHandle, IoCompletionInformationClass, IoCompletionInformation, IoCompletionInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryKey(proc_t proc, const on_ZwQueryKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryKey@20", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto KeyInformationClass = arg<wow64::KEY_INFORMATION_CLASS>(core, 1); const auto KeyInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ResultLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[235]); on_func(KeyHandle, KeyInformationClass, KeyInformation, Length, ResultLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryLicenseValue(proc_t proc, const on_NtQueryLicenseValue_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryLicenseValue@20", [=] { auto& core = d_->core; const auto Name = arg<wow64::PUNICODE_STRING>(core, 0); const auto Type = arg<wow64::PULONG>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ReturnedLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[236]); on_func(Name, Type, Buffer, Length, ReturnedLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryMultipleValueKey(proc_t proc, const on_NtQueryMultipleValueKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryMultipleValueKey@24", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto ValueEntries = arg<wow64::PKEY_VALUE_ENTRY>(core, 1); const auto EntryCount = arg<wow64::ULONG>(core, 2); const auto ValueBuffer = arg<wow64::PVOID>(core, 3); const auto BufferLength = arg<wow64::PULONG>(core, 4); const auto RequiredBufferLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[237]); on_func(KeyHandle, ValueEntries, EntryCount, ValueBuffer, BufferLength, RequiredBufferLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryMutant(proc_t proc, const on_NtQueryMutant_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryMutant@20", [=] { auto& core = d_->core; const auto MutantHandle = arg<wow64::HANDLE>(core, 0); const auto MutantInformationClass = arg<wow64::MUTANT_INFORMATION_CLASS>(core, 1); const auto MutantInformation = arg<wow64::PVOID>(core, 2); const auto MutantInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[238]); on_func(MutantHandle, MutantInformationClass, MutantInformation, MutantInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryObject(proc_t proc, const on_NtQueryObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryObject@20", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); const auto ObjectInformationClass = arg<wow64::OBJECT_INFORMATION_CLASS>(core, 1); const auto ObjectInformation = arg<wow64::PVOID>(core, 2); const auto ObjectInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[239]); on_func(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryOpenSubKeysEx(proc_t proc, const on_NtQueryOpenSubKeysEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryOpenSubKeysEx@16", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto BufferLength = arg<wow64::ULONG>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto RequiredSize = arg<wow64::PULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[240]); on_func(TargetKey, BufferLength, Buffer, RequiredSize); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryOpenSubKeys(proc_t proc, const on_NtQueryOpenSubKeys_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryOpenSubKeys@8", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto HandleCount = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[241]); on_func(TargetKey, HandleCount); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryPerformanceCounter(proc_t proc, const on_NtQueryPerformanceCounter_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryPerformanceCounter@8", [=] { auto& core = d_->core; const auto PerformanceCounter = arg<wow64::PLARGE_INTEGER>(core, 0); const auto PerformanceFrequency = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[242]); on_func(PerformanceCounter, PerformanceFrequency); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryQuotaInformationFile(proc_t proc, const on_ZwQueryQuotaInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryQuotaInformationFile@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto ReturnSingleEntry = arg<wow64::BOOLEAN>(core, 4); const auto SidList = arg<wow64::PVOID>(core, 5); const auto SidListLength = arg<wow64::ULONG>(core, 6); const auto StartSid = arg<wow64::PULONG>(core, 7); const auto RestartScan = arg<wow64::BOOLEAN>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[243]); on_func(FileHandle, IoStatusBlock, Buffer, Length, ReturnSingleEntry, SidList, SidListLength, StartSid, RestartScan); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySection(proc_t proc, const on_ZwQuerySection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySection@20", [=] { auto& core = d_->core; const auto SectionHandle = arg<wow64::HANDLE>(core, 0); const auto SectionInformationClass = arg<wow64::SECTION_INFORMATION_CLASS>(core, 1); const auto SectionInformation = arg<wow64::PVOID>(core, 2); const auto SectionInformationLength = arg<wow64::SIZE_T>(core, 3); const auto ReturnLength = arg<wow64::PSIZE_T>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[244]); on_func(SectionHandle, SectionInformationClass, SectionInformation, SectionInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySecurityAttributesToken(proc_t proc, const on_ZwQuerySecurityAttributesToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySecurityAttributesToken@24", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::HANDLE>(core, 0); const auto Attributes = arg<wow64::PUNICODE_STRING>(core, 1); const auto NumberOfAttributes = arg<wow64::ULONG>(core, 2); const auto Buffer = arg<wow64::PVOID>(core, 3); const auto Length = arg<wow64::ULONG>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[245]); on_func(TokenHandle, Attributes, NumberOfAttributes, Buffer, Length, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQuerySecurityObject(proc_t proc, const on_NtQuerySecurityObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQuerySecurityObject@20", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); const auto SecurityInformation = arg<wow64::SECURITY_INFORMATION>(core, 1); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto LengthNeeded = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[246]); on_func(Handle, SecurityInformation, SecurityDescriptor, Length, LengthNeeded); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySemaphore(proc_t proc, const on_ZwQuerySemaphore_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySemaphore@20", [=] { auto& core = d_->core; const auto SemaphoreHandle = arg<wow64::HANDLE>(core, 0); const auto SemaphoreInformationClass = arg<wow64::SEMAPHORE_INFORMATION_CLASS>(core, 1); const auto SemaphoreInformation = arg<wow64::PVOID>(core, 2); const auto SemaphoreInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[247]); on_func(SemaphoreHandle, SemaphoreInformationClass, SemaphoreInformation, SemaphoreInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySymbolicLinkObject(proc_t proc, const on_ZwQuerySymbolicLinkObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySymbolicLinkObject@12", [=] { auto& core = d_->core; const auto LinkHandle = arg<wow64::HANDLE>(core, 0); const auto LinkTarget = arg<wow64::PUNICODE_STRING>(core, 1); const auto ReturnedLength = arg<wow64::PULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[248]); on_func(LinkHandle, LinkTarget, ReturnedLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySystemEnvironmentValueEx(proc_t proc, const on_ZwQuerySystemEnvironmentValueEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySystemEnvironmentValueEx@20", [=] { auto& core = d_->core; const auto VariableName = arg<wow64::PUNICODE_STRING>(core, 0); const auto VendorGuid = arg<wow64::LPGUID>(core, 1); const auto Value = arg<wow64::PVOID>(core, 2); const auto ValueLength = arg<wow64::PULONG>(core, 3); const auto Attributes = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[249]); on_func(VariableName, VendorGuid, Value, ValueLength, Attributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySystemEnvironmentValue(proc_t proc, const on_ZwQuerySystemEnvironmentValue_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySystemEnvironmentValue@16", [=] { auto& core = d_->core; const auto VariableName = arg<wow64::PUNICODE_STRING>(core, 0); const auto VariableValue = arg<wow64::PWSTR>(core, 1); const auto ValueLength = arg<wow64::USHORT>(core, 2); const auto ReturnLength = arg<wow64::PUSHORT>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[250]); on_func(VariableName, VariableValue, ValueLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwQuerySystemInformationEx(proc_t proc, const on_ZwQuerySystemInformationEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQuerySystemInformationEx@24", [=] { auto& core = d_->core; const auto SystemInformationClass = arg<wow64::SYSTEM_INFORMATION_CLASS>(core, 0); const auto QueryInformation = arg<wow64::PVOID>(core, 1); const auto QueryInformationLength = arg<wow64::ULONG>(core, 2); const auto SystemInformation = arg<wow64::PVOID>(core, 3); const auto SystemInformationLength = arg<wow64::ULONG>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[251]); on_func(SystemInformationClass, QueryInformation, QueryInformationLength, SystemInformation, SystemInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQuerySystemInformation(proc_t proc, const on_NtQuerySystemInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQuerySystemInformation@16", [=] { auto& core = d_->core; const auto SystemInformationClass = arg<wow64::SYSTEM_INFORMATION_CLASS>(core, 0); const auto SystemInformation = arg<wow64::PVOID>(core, 1); const auto SystemInformationLength = arg<wow64::ULONG>(core, 2); const auto ReturnLength = arg<wow64::PULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[252]); on_func(SystemInformationClass, SystemInformation, SystemInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQuerySystemTime(proc_t proc, const on_NtQuerySystemTime_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQuerySystemTime@4", [=] { auto& core = d_->core; const auto SystemTime = arg<wow64::PLARGE_INTEGER>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[253]); on_func(SystemTime); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryTimer(proc_t proc, const on_ZwQueryTimer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryTimer@20", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::HANDLE>(core, 0); const auto TimerInformationClass = arg<wow64::TIMER_INFORMATION_CLASS>(core, 1); const auto TimerInformation = arg<wow64::PVOID>(core, 2); const auto TimerInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[254]); on_func(TimerHandle, TimerInformationClass, TimerInformation, TimerInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryTimerResolution(proc_t proc, const on_NtQueryTimerResolution_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryTimerResolution@12", [=] { auto& core = d_->core; const auto MaximumTime = arg<wow64::PULONG>(core, 0); const auto MinimumTime = arg<wow64::PULONG>(core, 1); const auto CurrentTime = arg<wow64::PULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[255]); on_func(MaximumTime, MinimumTime, CurrentTime); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryValueKey(proc_t proc, const on_ZwQueryValueKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryValueKey@24", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto ValueName = arg<wow64::PUNICODE_STRING>(core, 1); const auto KeyValueInformationClass = arg<wow64::KEY_VALUE_INFORMATION_CLASS>(core, 2); const auto KeyValueInformation = arg<wow64::PVOID>(core, 3); const auto Length = arg<wow64::ULONG>(core, 4); const auto ResultLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[256]); on_func(KeyHandle, ValueName, KeyValueInformationClass, KeyValueInformation, Length, ResultLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryVirtualMemory(proc_t proc, const on_NtQueryVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryVirtualMemory@24", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); const auto MemoryInformationClass = arg<wow64::MEMORY_INFORMATION_CLASS>(core, 2); const auto MemoryInformation = arg<wow64::PVOID>(core, 3); const auto MemoryInformationLength = arg<wow64::SIZE_T>(core, 4); const auto ReturnLength = arg<wow64::PSIZE_T>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[257]); on_func(ProcessHandle, BaseAddress, MemoryInformationClass, MemoryInformation, MemoryInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtQueryVolumeInformationFile(proc_t proc, const on_NtQueryVolumeInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueryVolumeInformationFile@20", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto FsInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto FsInformationClass = arg<wow64::FS_INFORMATION_CLASS>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[258]); on_func(FileHandle, IoStatusBlock, FsInformation, Length, FsInformationClass); }); } opt<bpid_t> wow64::syscalls32::register_NtQueueApcThreadEx(proc_t proc, const on_NtQueueApcThreadEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueueApcThreadEx@24", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto UserApcReserveHandle = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PPS_APC_ROUTINE>(core, 2); const auto ApcArgument1 = arg<wow64::PVOID>(core, 3); const auto ApcArgument2 = arg<wow64::PVOID>(core, 4); const auto ApcArgument3 = arg<wow64::PVOID>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[259]); on_func(ThreadHandle, UserApcReserveHandle, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3); }); } opt<bpid_t> wow64::syscalls32::register_NtQueueApcThread(proc_t proc, const on_NtQueueApcThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtQueueApcThread@20", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ApcRoutine = arg<wow64::PPS_APC_ROUTINE>(core, 1); const auto ApcArgument1 = arg<wow64::PVOID>(core, 2); const auto ApcArgument2 = arg<wow64::PVOID>(core, 3); const auto ApcArgument3 = arg<wow64::PVOID>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[260]); on_func(ThreadHandle, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3); }); } opt<bpid_t> wow64::syscalls32::register_ZwRaiseException(proc_t proc, const on_ZwRaiseException_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRaiseException@12", [=] { auto& core = d_->core; const auto ExceptionRecord = arg<wow64::PEXCEPTION_RECORD>(core, 0); const auto ContextRecord = arg<wow64::PCONTEXT>(core, 1); const auto FirstChance = arg<wow64::BOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[261]); on_func(ExceptionRecord, ContextRecord, FirstChance); }); } opt<bpid_t> wow64::syscalls32::register_ZwRaiseHardError(proc_t proc, const on_ZwRaiseHardError_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRaiseHardError@24", [=] { auto& core = d_->core; const auto ErrorStatus = arg<wow64::NTSTATUS>(core, 0); const auto NumberOfParameters = arg<wow64::ULONG>(core, 1); const auto UnicodeStringParameterMask = arg<wow64::ULONG>(core, 2); const auto Parameters = arg<wow64::PULONG_PTR>(core, 3); const auto ValidResponseOptions = arg<wow64::ULONG>(core, 4); const auto Response = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[262]); on_func(ErrorStatus, NumberOfParameters, UnicodeStringParameterMask, Parameters, ValidResponseOptions, Response); }); } opt<bpid_t> wow64::syscalls32::register_NtReadFile(proc_t proc, const on_NtReadFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReadFile@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto Buffer = arg<wow64::PVOID>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 7); const auto Key = arg<wow64::PULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[263]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, Buffer, Length, ByteOffset, Key); }); } opt<bpid_t> wow64::syscalls32::register_NtReadFileScatter(proc_t proc, const on_NtReadFileScatter_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReadFileScatter@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto SegmentArray = arg<wow64::PFILE_SEGMENT_ELEMENT>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 7); const auto Key = arg<wow64::PULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[264]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, SegmentArray, Length, ByteOffset, Key); }); } opt<bpid_t> wow64::syscalls32::register_ZwReadOnlyEnlistment(proc_t proc, const on_ZwReadOnlyEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReadOnlyEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[265]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_ZwReadRequestData(proc_t proc, const on_ZwReadRequestData_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReadRequestData@24", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Message = arg<wow64::PPORT_MESSAGE>(core, 1); const auto DataEntryIndex = arg<wow64::ULONG>(core, 2); const auto Buffer = arg<wow64::PVOID>(core, 3); const auto BufferSize = arg<wow64::SIZE_T>(core, 4); const auto NumberOfBytesRead = arg<wow64::PSIZE_T>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[266]); on_func(PortHandle, Message, DataEntryIndex, Buffer, BufferSize, NumberOfBytesRead); }); } opt<bpid_t> wow64::syscalls32::register_NtReadVirtualMemory(proc_t proc, const on_NtReadVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReadVirtualMemory@20", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto BufferSize = arg<wow64::SIZE_T>(core, 3); const auto NumberOfBytesRead = arg<wow64::PSIZE_T>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[267]); on_func(ProcessHandle, BaseAddress, Buffer, BufferSize, NumberOfBytesRead); }); } opt<bpid_t> wow64::syscalls32::register_NtRecoverEnlistment(proc_t proc, const on_NtRecoverEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRecoverEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto EnlistmentKey = arg<wow64::PVOID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[268]); on_func(EnlistmentHandle, EnlistmentKey); }); } opt<bpid_t> wow64::syscalls32::register_NtRecoverResourceManager(proc_t proc, const on_NtRecoverResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRecoverResourceManager@4", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[269]); on_func(ResourceManagerHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwRecoverTransactionManager(proc_t proc, const on_ZwRecoverTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRecoverTransactionManager@4", [=] { auto& core = d_->core; const auto TransactionManagerHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[270]); on_func(TransactionManagerHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwRegisterProtocolAddressInformation(proc_t proc, const on_ZwRegisterProtocolAddressInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRegisterProtocolAddressInformation@20", [=] { auto& core = d_->core; const auto ResourceManager = arg<wow64::HANDLE>(core, 0); const auto ProtocolId = arg<wow64::PCRM_PROTOCOL_ID>(core, 1); const auto ProtocolInformationSize = arg<wow64::ULONG>(core, 2); const auto ProtocolInformation = arg<wow64::PVOID>(core, 3); const auto CreateOptions = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[271]); on_func(ResourceManager, ProtocolId, ProtocolInformationSize, ProtocolInformation, CreateOptions); }); } opt<bpid_t> wow64::syscalls32::register_ZwRegisterThreadTerminatePort(proc_t proc, const on_ZwRegisterThreadTerminatePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRegisterThreadTerminatePort@4", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[272]); on_func(PortHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtReleaseKeyedEvent(proc_t proc, const on_NtReleaseKeyedEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReleaseKeyedEvent@16", [=] { auto& core = d_->core; const auto KeyedEventHandle = arg<wow64::HANDLE>(core, 0); const auto KeyValue = arg<wow64::PVOID>(core, 1); const auto Alertable = arg<wow64::BOOLEAN>(core, 2); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[273]); on_func(KeyedEventHandle, KeyValue, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwReleaseMutant(proc_t proc, const on_ZwReleaseMutant_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReleaseMutant@8", [=] { auto& core = d_->core; const auto MutantHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousCount = arg<wow64::PLONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[274]); on_func(MutantHandle, PreviousCount); }); } opt<bpid_t> wow64::syscalls32::register_NtReleaseSemaphore(proc_t proc, const on_NtReleaseSemaphore_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReleaseSemaphore@12", [=] { auto& core = d_->core; const auto SemaphoreHandle = arg<wow64::HANDLE>(core, 0); const auto ReleaseCount = arg<wow64::LONG>(core, 1); const auto PreviousCount = arg<wow64::PLONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[275]); on_func(SemaphoreHandle, ReleaseCount, PreviousCount); }); } opt<bpid_t> wow64::syscalls32::register_ZwReleaseWorkerFactoryWorker(proc_t proc, const on_ZwReleaseWorkerFactoryWorker_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReleaseWorkerFactoryWorker@4", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[276]); on_func(WorkerFactoryHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwRemoveIoCompletionEx(proc_t proc, const on_ZwRemoveIoCompletionEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRemoveIoCompletionEx@24", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::HANDLE>(core, 0); const auto IoCompletionInformation = arg<wow64::PFILE_IO_COMPLETION_INFORMATION>(core, 1); const auto Count = arg<wow64::ULONG>(core, 2); const auto NumEntriesRemoved = arg<wow64::PULONG>(core, 3); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 4); const auto Alertable = arg<wow64::BOOLEAN>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[277]); on_func(IoCompletionHandle, IoCompletionInformation, Count, NumEntriesRemoved, Timeout, Alertable); }); } opt<bpid_t> wow64::syscalls32::register_ZwRemoveIoCompletion(proc_t proc, const on_ZwRemoveIoCompletion_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRemoveIoCompletion@20", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::HANDLE>(core, 0); const auto STARKeyContext = arg<wow64::PVOID>(core, 1); const auto STARApcContext = arg<wow64::PVOID>(core, 2); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 3); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[278]); on_func(IoCompletionHandle, STARKeyContext, STARApcContext, IoStatusBlock, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwRemoveProcessDebug(proc_t proc, const on_ZwRemoveProcessDebug_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRemoveProcessDebug@8", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto DebugObjectHandle = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[279]); on_func(ProcessHandle, DebugObjectHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwRenameKey(proc_t proc, const on_ZwRenameKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRenameKey@8", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto NewName = arg<wow64::PUNICODE_STRING>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[280]); on_func(KeyHandle, NewName); }); } opt<bpid_t> wow64::syscalls32::register_NtRenameTransactionManager(proc_t proc, const on_NtRenameTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRenameTransactionManager@8", [=] { auto& core = d_->core; const auto LogFileName = arg<wow64::PUNICODE_STRING>(core, 0); const auto ExistingTransactionManagerGuid = arg<wow64::LPGUID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[281]); on_func(LogFileName, ExistingTransactionManagerGuid); }); } opt<bpid_t> wow64::syscalls32::register_ZwReplaceKey(proc_t proc, const on_ZwReplaceKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReplaceKey@12", [=] { auto& core = d_->core; const auto NewFile = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto TargetHandle = arg<wow64::HANDLE>(core, 1); const auto OldFile = arg<wow64::POBJECT_ATTRIBUTES>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[282]); on_func(NewFile, TargetHandle, OldFile); }); } opt<bpid_t> wow64::syscalls32::register_NtReplacePartitionUnit(proc_t proc, const on_NtReplacePartitionUnit_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReplacePartitionUnit@12", [=] { auto& core = d_->core; const auto TargetInstancePath = arg<wow64::PUNICODE_STRING>(core, 0); const auto SpareInstancePath = arg<wow64::PUNICODE_STRING>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[283]); on_func(TargetInstancePath, SpareInstancePath, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwReplyPort(proc_t proc, const on_ZwReplyPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwReplyPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto ReplyMessage = arg<wow64::PPORT_MESSAGE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[284]); on_func(PortHandle, ReplyMessage); }); } opt<bpid_t> wow64::syscalls32::register_NtReplyWaitReceivePortEx(proc_t proc, const on_NtReplyWaitReceivePortEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReplyWaitReceivePortEx@20", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto STARPortContext = arg<wow64::PVOID>(core, 1); const auto ReplyMessage = arg<wow64::PPORT_MESSAGE>(core, 2); const auto ReceiveMessage = arg<wow64::PPORT_MESSAGE>(core, 3); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[285]); on_func(PortHandle, STARPortContext, ReplyMessage, ReceiveMessage, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_NtReplyWaitReceivePort(proc_t proc, const on_NtReplyWaitReceivePort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReplyWaitReceivePort@16", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto STARPortContext = arg<wow64::PVOID>(core, 1); const auto ReplyMessage = arg<wow64::PPORT_MESSAGE>(core, 2); const auto ReceiveMessage = arg<wow64::PPORT_MESSAGE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[286]); on_func(PortHandle, STARPortContext, ReplyMessage, ReceiveMessage); }); } opt<bpid_t> wow64::syscalls32::register_NtReplyWaitReplyPort(proc_t proc, const on_NtReplyWaitReplyPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtReplyWaitReplyPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto ReplyMessage = arg<wow64::PPORT_MESSAGE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[287]); on_func(PortHandle, ReplyMessage); }); } opt<bpid_t> wow64::syscalls32::register_ZwRequestPort(proc_t proc, const on_ZwRequestPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRequestPort@8", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto RequestMessage = arg<wow64::PPORT_MESSAGE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[288]); on_func(PortHandle, RequestMessage); }); } opt<bpid_t> wow64::syscalls32::register_NtRequestWaitReplyPort(proc_t proc, const on_NtRequestWaitReplyPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRequestWaitReplyPort@12", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto RequestMessage = arg<wow64::PPORT_MESSAGE>(core, 1); const auto ReplyMessage = arg<wow64::PPORT_MESSAGE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[289]); on_func(PortHandle, RequestMessage, ReplyMessage); }); } opt<bpid_t> wow64::syscalls32::register_NtResetEvent(proc_t proc, const on_NtResetEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtResetEvent@8", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousState = arg<wow64::PLONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[290]); on_func(EventHandle, PreviousState); }); } opt<bpid_t> wow64::syscalls32::register_ZwResetWriteWatch(proc_t proc, const on_ZwResetWriteWatch_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwResetWriteWatch@12", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::SIZE_T>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[291]); on_func(ProcessHandle, BaseAddress, RegionSize); }); } opt<bpid_t> wow64::syscalls32::register_NtRestoreKey(proc_t proc, const on_NtRestoreKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRestoreKey@12", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto FileHandle = arg<wow64::HANDLE>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[292]); on_func(KeyHandle, FileHandle, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwResumeProcess(proc_t proc, const on_ZwResumeProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwResumeProcess@4", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[293]); on_func(ProcessHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwResumeThread(proc_t proc, const on_ZwResumeThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwResumeThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousSuspendCount = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[294]); on_func(ThreadHandle, PreviousSuspendCount); }); } opt<bpid_t> wow64::syscalls32::register_ZwRollbackComplete(proc_t proc, const on_ZwRollbackComplete_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwRollbackComplete@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[295]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtRollbackEnlistment(proc_t proc, const on_NtRollbackEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRollbackEnlistment@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[296]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtRollbackTransaction(proc_t proc, const on_NtRollbackTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRollbackTransaction@8", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::HANDLE>(core, 0); const auto Wait = arg<wow64::BOOLEAN>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[297]); on_func(TransactionHandle, Wait); }); } opt<bpid_t> wow64::syscalls32::register_NtRollforwardTransactionManager(proc_t proc, const on_NtRollforwardTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtRollforwardTransactionManager@8", [=] { auto& core = d_->core; const auto TransactionManagerHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[298]); on_func(TransactionManagerHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtSaveKeyEx(proc_t proc, const on_NtSaveKeyEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSaveKeyEx@12", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto FileHandle = arg<wow64::HANDLE>(core, 1); const auto Format = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[299]); on_func(KeyHandle, FileHandle, Format); }); } opt<bpid_t> wow64::syscalls32::register_NtSaveKey(proc_t proc, const on_NtSaveKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSaveKey@8", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto FileHandle = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[300]); on_func(KeyHandle, FileHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtSaveMergedKeys(proc_t proc, const on_NtSaveMergedKeys_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSaveMergedKeys@12", [=] { auto& core = d_->core; const auto HighPrecedenceKeyHandle = arg<wow64::HANDLE>(core, 0); const auto LowPrecedenceKeyHandle = arg<wow64::HANDLE>(core, 1); const auto FileHandle = arg<wow64::HANDLE>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[301]); on_func(HighPrecedenceKeyHandle, LowPrecedenceKeyHandle, FileHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtSecureConnectPort(proc_t proc, const on_NtSecureConnectPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSecureConnectPort@36", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::PHANDLE>(core, 0); const auto PortName = arg<wow64::PUNICODE_STRING>(core, 1); const auto SecurityQos = arg<wow64::PSECURITY_QUALITY_OF_SERVICE>(core, 2); const auto ClientView = arg<wow64::PPORT_VIEW>(core, 3); const auto RequiredServerSid = arg<wow64::PSID>(core, 4); const auto ServerView = arg<wow64::PREMOTE_PORT_VIEW>(core, 5); const auto MaxMessageLength = arg<wow64::PULONG>(core, 6); const auto ConnectionInformation = arg<wow64::PVOID>(core, 7); const auto ConnectionInformationLength = arg<wow64::PULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[302]); on_func(PortHandle, PortName, SecurityQos, ClientView, RequiredServerSid, ServerView, MaxMessageLength, ConnectionInformation, ConnectionInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetBootEntryOrder(proc_t proc, const on_ZwSetBootEntryOrder_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetBootEntryOrder@8", [=] { auto& core = d_->core; const auto Ids = arg<wow64::PULONG>(core, 0); const auto Count = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[303]); on_func(Ids, Count); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetBootOptions(proc_t proc, const on_ZwSetBootOptions_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetBootOptions@8", [=] { auto& core = d_->core; const auto BootOptions = arg<wow64::PBOOT_OPTIONS>(core, 0); const auto FieldsToChange = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[304]); on_func(BootOptions, FieldsToChange); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetContextThread(proc_t proc, const on_ZwSetContextThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetContextThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ThreadContext = arg<wow64::PCONTEXT>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[305]); on_func(ThreadHandle, ThreadContext); }); } opt<bpid_t> wow64::syscalls32::register_NtSetDebugFilterState(proc_t proc, const on_NtSetDebugFilterState_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetDebugFilterState@12", [=] { auto& core = d_->core; const auto ComponentId = arg<wow64::ULONG>(core, 0); const auto Level = arg<wow64::ULONG>(core, 1); const auto State = arg<wow64::BOOLEAN>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[306]); on_func(ComponentId, Level, State); }); } opt<bpid_t> wow64::syscalls32::register_NtSetDefaultHardErrorPort(proc_t proc, const on_NtSetDefaultHardErrorPort_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetDefaultHardErrorPort@4", [=] { auto& core = d_->core; const auto DefaultHardErrorPort = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[307]); on_func(DefaultHardErrorPort); }); } opt<bpid_t> wow64::syscalls32::register_NtSetDefaultLocale(proc_t proc, const on_NtSetDefaultLocale_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetDefaultLocale@8", [=] { auto& core = d_->core; const auto UserProfile = arg<wow64::BOOLEAN>(core, 0); const auto DefaultLocaleId = arg<wow64::LCID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[308]); on_func(UserProfile, DefaultLocaleId); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetDefaultUILanguage(proc_t proc, const on_ZwSetDefaultUILanguage_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetDefaultUILanguage@4", [=] { auto& core = d_->core; const auto DefaultUILanguageId = arg<wow64::LANGID>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[309]); on_func(DefaultUILanguageId); }); } opt<bpid_t> wow64::syscalls32::register_NtSetDriverEntryOrder(proc_t proc, const on_NtSetDriverEntryOrder_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetDriverEntryOrder@8", [=] { auto& core = d_->core; const auto Ids = arg<wow64::PULONG>(core, 0); const auto Count = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[310]); on_func(Ids, Count); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetEaFile(proc_t proc, const on_ZwSetEaFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetEaFile@16", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[311]); on_func(FileHandle, IoStatusBlock, Buffer, Length); }); } opt<bpid_t> wow64::syscalls32::register_NtSetEventBoostPriority(proc_t proc, const on_NtSetEventBoostPriority_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetEventBoostPriority@4", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[312]); on_func(EventHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtSetEvent(proc_t proc, const on_NtSetEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetEvent@8", [=] { auto& core = d_->core; const auto EventHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousState = arg<wow64::PLONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[313]); on_func(EventHandle, PreviousState); }); } opt<bpid_t> wow64::syscalls32::register_NtSetHighEventPair(proc_t proc, const on_NtSetHighEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetHighEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[314]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtSetHighWaitLowEventPair(proc_t proc, const on_NtSetHighWaitLowEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetHighWaitLowEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[315]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationDebugObject(proc_t proc, const on_ZwSetInformationDebugObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationDebugObject@20", [=] { auto& core = d_->core; const auto DebugObjectHandle = arg<wow64::HANDLE>(core, 0); const auto DebugObjectInformationClass = arg<wow64::DEBUGOBJECTINFOCLASS>(core, 1); const auto DebugInformation = arg<wow64::PVOID>(core, 2); const auto DebugInformationLength = arg<wow64::ULONG>(core, 3); const auto ReturnLength = arg<wow64::PULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[316]); on_func(DebugObjectHandle, DebugObjectInformationClass, DebugInformation, DebugInformationLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtSetInformationEnlistment(proc_t proc, const on_NtSetInformationEnlistment_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetInformationEnlistment@16", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto EnlistmentInformationClass = arg<wow64::ENLISTMENT_INFORMATION_CLASS>(core, 1); const auto EnlistmentInformation = arg<wow64::PVOID>(core, 2); const auto EnlistmentInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[317]); on_func(EnlistmentHandle, EnlistmentInformationClass, EnlistmentInformation, EnlistmentInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationFile(proc_t proc, const on_ZwSetInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationFile@20", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto FileInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto FileInformationClass = arg<wow64::FILE_INFORMATION_CLASS>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[318]); on_func(FileHandle, IoStatusBlock, FileInformation, Length, FileInformationClass); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationJobObject(proc_t proc, const on_ZwSetInformationJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationJobObject@16", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::HANDLE>(core, 0); const auto JobObjectInformationClass = arg<wow64::JOBOBJECTINFOCLASS>(core, 1); const auto JobObjectInformation = arg<wow64::PVOID>(core, 2); const auto JobObjectInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[319]); on_func(JobHandle, JobObjectInformationClass, JobObjectInformation, JobObjectInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationKey(proc_t proc, const on_ZwSetInformationKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationKey@16", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto KeySetInformationClass = arg<wow64::KEY_SET_INFORMATION_CLASS>(core, 1); const auto KeySetInformation = arg<wow64::PVOID>(core, 2); const auto KeySetInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[320]); on_func(KeyHandle, KeySetInformationClass, KeySetInformation, KeySetInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationObject(proc_t proc, const on_ZwSetInformationObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationObject@16", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); const auto ObjectInformationClass = arg<wow64::OBJECT_INFORMATION_CLASS>(core, 1); const auto ObjectInformation = arg<wow64::PVOID>(core, 2); const auto ObjectInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[321]); on_func(Handle, ObjectInformationClass, ObjectInformation, ObjectInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationProcess(proc_t proc, const on_ZwSetInformationProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationProcess@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto ProcessInformationClass = arg<wow64::PROCESSINFOCLASS>(core, 1); const auto ProcessInformation = arg<wow64::PVOID>(core, 2); const auto ProcessInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[322]); on_func(ProcessHandle, ProcessInformationClass, ProcessInformation, ProcessInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationResourceManager(proc_t proc, const on_ZwSetInformationResourceManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationResourceManager@16", [=] { auto& core = d_->core; const auto ResourceManagerHandle = arg<wow64::HANDLE>(core, 0); const auto ResourceManagerInformationClass = arg<wow64::RESOURCEMANAGER_INFORMATION_CLASS>(core, 1); const auto ResourceManagerInformation = arg<wow64::PVOID>(core, 2); const auto ResourceManagerInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[323]); on_func(ResourceManagerHandle, ResourceManagerInformationClass, ResourceManagerInformation, ResourceManagerInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationThread(proc_t proc, const on_ZwSetInformationThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationThread@16", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ThreadInformationClass = arg<wow64::THREADINFOCLASS>(core, 1); const auto ThreadInformation = arg<wow64::PVOID>(core, 2); const auto ThreadInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[324]); on_func(ThreadHandle, ThreadInformationClass, ThreadInformation, ThreadInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationToken(proc_t proc, const on_ZwSetInformationToken_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationToken@16", [=] { auto& core = d_->core; const auto TokenHandle = arg<wow64::HANDLE>(core, 0); const auto TokenInformationClass = arg<wow64::TOKEN_INFORMATION_CLASS>(core, 1); const auto TokenInformation = arg<wow64::PVOID>(core, 2); const auto TokenInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[325]); on_func(TokenHandle, TokenInformationClass, TokenInformation, TokenInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationTransaction(proc_t proc, const on_ZwSetInformationTransaction_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationTransaction@16", [=] { auto& core = d_->core; const auto TransactionHandle = arg<wow64::HANDLE>(core, 0); const auto TransactionInformationClass = arg<wow64::TRANSACTION_INFORMATION_CLASS>(core, 1); const auto TransactionInformation = arg<wow64::PVOID>(core, 2); const auto TransactionInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[326]); on_func(TransactionHandle, TransactionInformationClass, TransactionInformation, TransactionInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationTransactionManager(proc_t proc, const on_ZwSetInformationTransactionManager_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationTransactionManager@16", [=] { auto& core = d_->core; const auto TmHandle = arg<wow64::HANDLE>(core, 0); const auto TransactionManagerInformationClass = arg<wow64::TRANSACTIONMANAGER_INFORMATION_CLASS>(core, 1); const auto TransactionManagerInformation = arg<wow64::PVOID>(core, 2); const auto TransactionManagerInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[327]); on_func(TmHandle, TransactionManagerInformationClass, TransactionManagerInformation, TransactionManagerInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetInformationWorkerFactory(proc_t proc, const on_ZwSetInformationWorkerFactory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetInformationWorkerFactory@16", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); const auto WorkerFactoryInformationClass = arg<wow64::WORKERFACTORYINFOCLASS>(core, 1); const auto WorkerFactoryInformation = arg<wow64::PVOID>(core, 2); const auto WorkerFactoryInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[328]); on_func(WorkerFactoryHandle, WorkerFactoryInformationClass, WorkerFactoryInformation, WorkerFactoryInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_NtSetIntervalProfile(proc_t proc, const on_NtSetIntervalProfile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetIntervalProfile@8", [=] { auto& core = d_->core; const auto Interval = arg<wow64::ULONG>(core, 0); const auto Source = arg<wow64::KPROFILE_SOURCE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[329]); on_func(Interval, Source); }); } opt<bpid_t> wow64::syscalls32::register_NtSetIoCompletionEx(proc_t proc, const on_NtSetIoCompletionEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetIoCompletionEx@24", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::HANDLE>(core, 0); const auto IoCompletionReserveHandle = arg<wow64::HANDLE>(core, 1); const auto KeyContext = arg<wow64::PVOID>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatus = arg<wow64::NTSTATUS>(core, 4); const auto IoStatusInformation = arg<wow64::ULONG_PTR>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[330]); on_func(IoCompletionHandle, IoCompletionReserveHandle, KeyContext, ApcContext, IoStatus, IoStatusInformation); }); } opt<bpid_t> wow64::syscalls32::register_NtSetIoCompletion(proc_t proc, const on_NtSetIoCompletion_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetIoCompletion@20", [=] { auto& core = d_->core; const auto IoCompletionHandle = arg<wow64::HANDLE>(core, 0); const auto KeyContext = arg<wow64::PVOID>(core, 1); const auto ApcContext = arg<wow64::PVOID>(core, 2); const auto IoStatus = arg<wow64::NTSTATUS>(core, 3); const auto IoStatusInformation = arg<wow64::ULONG_PTR>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[331]); on_func(IoCompletionHandle, KeyContext, ApcContext, IoStatus, IoStatusInformation); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetLdtEntries(proc_t proc, const on_ZwSetLdtEntries_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetLdtEntries@24", [=] { auto& core = d_->core; const auto Selector0 = arg<wow64::ULONG>(core, 0); const auto Entry0Low = arg<wow64::ULONG>(core, 1); const auto Entry0Hi = arg<wow64::ULONG>(core, 2); const auto Selector1 = arg<wow64::ULONG>(core, 3); const auto Entry1Low = arg<wow64::ULONG>(core, 4); const auto Entry1Hi = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[332]); on_func(Selector0, Entry0Low, Entry0Hi, Selector1, Entry1Low, Entry1Hi); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetLowEventPair(proc_t proc, const on_ZwSetLowEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetLowEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[333]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetLowWaitHighEventPair(proc_t proc, const on_ZwSetLowWaitHighEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetLowWaitHighEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[334]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetQuotaInformationFile(proc_t proc, const on_ZwSetQuotaInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetQuotaInformationFile@16", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[335]); on_func(FileHandle, IoStatusBlock, Buffer, Length); }); } opt<bpid_t> wow64::syscalls32::register_NtSetSecurityObject(proc_t proc, const on_NtSetSecurityObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetSecurityObject@12", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); const auto SecurityInformation = arg<wow64::SECURITY_INFORMATION>(core, 1); const auto SecurityDescriptor = arg<wow64::PSECURITY_DESCRIPTOR>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[336]); on_func(Handle, SecurityInformation, SecurityDescriptor); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetSystemEnvironmentValueEx(proc_t proc, const on_ZwSetSystemEnvironmentValueEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetSystemEnvironmentValueEx@20", [=] { auto& core = d_->core; const auto VariableName = arg<wow64::PUNICODE_STRING>(core, 0); const auto VendorGuid = arg<wow64::LPGUID>(core, 1); const auto Value = arg<wow64::PVOID>(core, 2); const auto ValueLength = arg<wow64::ULONG>(core, 3); const auto Attributes = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[337]); on_func(VariableName, VendorGuid, Value, ValueLength, Attributes); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetSystemEnvironmentValue(proc_t proc, const on_ZwSetSystemEnvironmentValue_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetSystemEnvironmentValue@8", [=] { auto& core = d_->core; const auto VariableName = arg<wow64::PUNICODE_STRING>(core, 0); const auto VariableValue = arg<wow64::PUNICODE_STRING>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[338]); on_func(VariableName, VariableValue); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetSystemInformation(proc_t proc, const on_ZwSetSystemInformation_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetSystemInformation@12", [=] { auto& core = d_->core; const auto SystemInformationClass = arg<wow64::SYSTEM_INFORMATION_CLASS>(core, 0); const auto SystemInformation = arg<wow64::PVOID>(core, 1); const auto SystemInformationLength = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[339]); on_func(SystemInformationClass, SystemInformation, SystemInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetSystemPowerState(proc_t proc, const on_ZwSetSystemPowerState_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetSystemPowerState@12", [=] { auto& core = d_->core; const auto SystemAction = arg<wow64::POWER_ACTION>(core, 0); const auto MinSystemState = arg<wow64::SYSTEM_POWER_STATE>(core, 1); const auto Flags = arg<wow64::ULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[340]); on_func(SystemAction, MinSystemState, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetSystemTime(proc_t proc, const on_ZwSetSystemTime_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetSystemTime@8", [=] { auto& core = d_->core; const auto SystemTime = arg<wow64::PLARGE_INTEGER>(core, 0); const auto PreviousTime = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[341]); on_func(SystemTime, PreviousTime); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetThreadExecutionState(proc_t proc, const on_ZwSetThreadExecutionState_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetThreadExecutionState@8", [=] { auto& core = d_->core; const auto esFlags = arg<wow64::EXECUTION_STATE>(core, 0); const auto STARPreviousFlags = arg<wow64::EXECUTION_STATE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[342]); on_func(esFlags, STARPreviousFlags); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetTimerEx(proc_t proc, const on_ZwSetTimerEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetTimerEx@16", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::HANDLE>(core, 0); const auto TimerSetInformationClass = arg<wow64::TIMER_SET_INFORMATION_CLASS>(core, 1); const auto TimerSetInformation = arg<wow64::PVOID>(core, 2); const auto TimerSetInformationLength = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[343]); on_func(TimerHandle, TimerSetInformationClass, TimerSetInformation, TimerSetInformationLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetTimer(proc_t proc, const on_ZwSetTimer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetTimer@28", [=] { auto& core = d_->core; const auto TimerHandle = arg<wow64::HANDLE>(core, 0); const auto DueTime = arg<wow64::PLARGE_INTEGER>(core, 1); const auto TimerApcRoutine = arg<wow64::PTIMER_APC_ROUTINE>(core, 2); const auto TimerContext = arg<wow64::PVOID>(core, 3); const auto WakeTimer = arg<wow64::BOOLEAN>(core, 4); const auto Period = arg<wow64::LONG>(core, 5); const auto PreviousState = arg<wow64::PBOOLEAN>(core, 6); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[344]); on_func(TimerHandle, DueTime, TimerApcRoutine, TimerContext, WakeTimer, Period, PreviousState); }); } opt<bpid_t> wow64::syscalls32::register_NtSetTimerResolution(proc_t proc, const on_NtSetTimerResolution_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetTimerResolution@12", [=] { auto& core = d_->core; const auto DesiredTime = arg<wow64::ULONG>(core, 0); const auto SetResolution = arg<wow64::BOOLEAN>(core, 1); const auto ActualTime = arg<wow64::PULONG>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[345]); on_func(DesiredTime, SetResolution, ActualTime); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetUuidSeed(proc_t proc, const on_ZwSetUuidSeed_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetUuidSeed@4", [=] { auto& core = d_->core; const auto Seed = arg<wow64::PCHAR>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[346]); on_func(Seed); }); } opt<bpid_t> wow64::syscalls32::register_ZwSetValueKey(proc_t proc, const on_ZwSetValueKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSetValueKey@24", [=] { auto& core = d_->core; const auto KeyHandle = arg<wow64::HANDLE>(core, 0); const auto ValueName = arg<wow64::PUNICODE_STRING>(core, 1); const auto TitleIndex = arg<wow64::ULONG>(core, 2); const auto Type = arg<wow64::ULONG>(core, 3); const auto Data = arg<wow64::PVOID>(core, 4); const auto DataSize = arg<wow64::ULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[347]); on_func(KeyHandle, ValueName, TitleIndex, Type, Data, DataSize); }); } opt<bpid_t> wow64::syscalls32::register_NtSetVolumeInformationFile(proc_t proc, const on_NtSetVolumeInformationFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSetVolumeInformationFile@20", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto FsInformation = arg<wow64::PVOID>(core, 2); const auto Length = arg<wow64::ULONG>(core, 3); const auto FsInformationClass = arg<wow64::FS_INFORMATION_CLASS>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[348]); on_func(FileHandle, IoStatusBlock, FsInformation, Length, FsInformationClass); }); } opt<bpid_t> wow64::syscalls32::register_ZwShutdownSystem(proc_t proc, const on_ZwShutdownSystem_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwShutdownSystem@4", [=] { auto& core = d_->core; const auto Action = arg<wow64::SHUTDOWN_ACTION>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[349]); on_func(Action); }); } opt<bpid_t> wow64::syscalls32::register_NtShutdownWorkerFactory(proc_t proc, const on_NtShutdownWorkerFactory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtShutdownWorkerFactory@8", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); const auto STARPendingWorkerCount = arg<wow64::LONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[350]); on_func(WorkerFactoryHandle, STARPendingWorkerCount); }); } opt<bpid_t> wow64::syscalls32::register_ZwSignalAndWaitForSingleObject(proc_t proc, const on_ZwSignalAndWaitForSingleObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSignalAndWaitForSingleObject@16", [=] { auto& core = d_->core; const auto SignalHandle = arg<wow64::HANDLE>(core, 0); const auto WaitHandle = arg<wow64::HANDLE>(core, 1); const auto Alertable = arg<wow64::BOOLEAN>(core, 2); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[351]); on_func(SignalHandle, WaitHandle, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwSinglePhaseReject(proc_t proc, const on_ZwSinglePhaseReject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSinglePhaseReject@8", [=] { auto& core = d_->core; const auto EnlistmentHandle = arg<wow64::HANDLE>(core, 0); const auto TmVirtualClock = arg<wow64::PLARGE_INTEGER>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[352]); on_func(EnlistmentHandle, TmVirtualClock); }); } opt<bpid_t> wow64::syscalls32::register_NtStartProfile(proc_t proc, const on_NtStartProfile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtStartProfile@4", [=] { auto& core = d_->core; const auto ProfileHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[353]); on_func(ProfileHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwStopProfile(proc_t proc, const on_ZwStopProfile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwStopProfile@4", [=] { auto& core = d_->core; const auto ProfileHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[354]); on_func(ProfileHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwSuspendProcess(proc_t proc, const on_ZwSuspendProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSuspendProcess@4", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[355]); on_func(ProcessHandle); }); } opt<bpid_t> wow64::syscalls32::register_ZwSuspendThread(proc_t proc, const on_ZwSuspendThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwSuspendThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto PreviousSuspendCount = arg<wow64::PULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[356]); on_func(ThreadHandle, PreviousSuspendCount); }); } opt<bpid_t> wow64::syscalls32::register_NtSystemDebugControl(proc_t proc, const on_NtSystemDebugControl_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSystemDebugControl@24", [=] { auto& core = d_->core; const auto Command = arg<wow64::SYSDBG_COMMAND>(core, 0); const auto InputBuffer = arg<wow64::PVOID>(core, 1); const auto InputBufferLength = arg<wow64::ULONG>(core, 2); const auto OutputBuffer = arg<wow64::PVOID>(core, 3); const auto OutputBufferLength = arg<wow64::ULONG>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[357]); on_func(Command, InputBuffer, InputBufferLength, OutputBuffer, OutputBufferLength, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwTerminateJobObject(proc_t proc, const on_ZwTerminateJobObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwTerminateJobObject@8", [=] { auto& core = d_->core; const auto JobHandle = arg<wow64::HANDLE>(core, 0); const auto ExitStatus = arg<wow64::NTSTATUS>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[358]); on_func(JobHandle, ExitStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwTerminateProcess(proc_t proc, const on_ZwTerminateProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwTerminateProcess@8", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto ExitStatus = arg<wow64::NTSTATUS>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[359]); on_func(ProcessHandle, ExitStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwTerminateThread(proc_t proc, const on_ZwTerminateThread_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwTerminateThread@8", [=] { auto& core = d_->core; const auto ThreadHandle = arg<wow64::HANDLE>(core, 0); const auto ExitStatus = arg<wow64::NTSTATUS>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[360]); on_func(ThreadHandle, ExitStatus); }); } opt<bpid_t> wow64::syscalls32::register_ZwTraceControl(proc_t proc, const on_ZwTraceControl_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwTraceControl@24", [=] { auto& core = d_->core; const auto FunctionCode = arg<wow64::ULONG>(core, 0); const auto InBuffer = arg<wow64::PVOID>(core, 1); const auto InBufferLen = arg<wow64::ULONG>(core, 2); const auto OutBuffer = arg<wow64::PVOID>(core, 3); const auto OutBufferLen = arg<wow64::ULONG>(core, 4); const auto ReturnLength = arg<wow64::PULONG>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[361]); on_func(FunctionCode, InBuffer, InBufferLen, OutBuffer, OutBufferLen, ReturnLength); }); } opt<bpid_t> wow64::syscalls32::register_NtTraceEvent(proc_t proc, const on_NtTraceEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtTraceEvent@16", [=] { auto& core = d_->core; const auto TraceHandle = arg<wow64::HANDLE>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); const auto FieldSize = arg<wow64::ULONG>(core, 2); const auto Fields = arg<wow64::PVOID>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[362]); on_func(TraceHandle, Flags, FieldSize, Fields); }); } opt<bpid_t> wow64::syscalls32::register_NtTranslateFilePath(proc_t proc, const on_NtTranslateFilePath_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtTranslateFilePath@16", [=] { auto& core = d_->core; const auto InputFilePath = arg<wow64::PFILE_PATH>(core, 0); const auto OutputType = arg<wow64::ULONG>(core, 1); const auto OutputFilePath = arg<wow64::PFILE_PATH>(core, 2); const auto OutputFilePathLength = arg<wow64::PULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[363]); on_func(InputFilePath, OutputType, OutputFilePath, OutputFilePathLength); }); } opt<bpid_t> wow64::syscalls32::register_ZwUnloadDriver(proc_t proc, const on_ZwUnloadDriver_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwUnloadDriver@4", [=] { auto& core = d_->core; const auto DriverServiceName = arg<wow64::PUNICODE_STRING>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[364]); on_func(DriverServiceName); }); } opt<bpid_t> wow64::syscalls32::register_ZwUnloadKey2(proc_t proc, const on_ZwUnloadKey2_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwUnloadKey2@8", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto Flags = arg<wow64::ULONG>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[365]); on_func(TargetKey, Flags); }); } opt<bpid_t> wow64::syscalls32::register_ZwUnloadKeyEx(proc_t proc, const on_ZwUnloadKeyEx_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwUnloadKeyEx@8", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[366]); on_func(TargetKey, Event); }); } opt<bpid_t> wow64::syscalls32::register_NtUnloadKey(proc_t proc, const on_NtUnloadKey_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtUnloadKey@4", [=] { auto& core = d_->core; const auto TargetKey = arg<wow64::POBJECT_ATTRIBUTES>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[367]); on_func(TargetKey); }); } opt<bpid_t> wow64::syscalls32::register_ZwUnlockFile(proc_t proc, const on_ZwUnlockFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwUnlockFile@20", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 1); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 2); const auto Length = arg<wow64::PLARGE_INTEGER>(core, 3); const auto Key = arg<wow64::ULONG>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[368]); on_func(FileHandle, IoStatusBlock, ByteOffset, Length, Key); }); } opt<bpid_t> wow64::syscalls32::register_NtUnlockVirtualMemory(proc_t proc, const on_NtUnlockVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtUnlockVirtualMemory@16", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto STARBaseAddress = arg<wow64::PVOID>(core, 1); const auto RegionSize = arg<wow64::PSIZE_T>(core, 2); const auto MapType = arg<wow64::ULONG>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[369]); on_func(ProcessHandle, STARBaseAddress, RegionSize, MapType); }); } opt<bpid_t> wow64::syscalls32::register_NtUnmapViewOfSection(proc_t proc, const on_NtUnmapViewOfSection_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtUnmapViewOfSection@8", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[370]); on_func(ProcessHandle, BaseAddress); }); } opt<bpid_t> wow64::syscalls32::register_NtVdmControl(proc_t proc, const on_NtVdmControl_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtVdmControl@8", [=] { auto& core = d_->core; const auto Service = arg<wow64::VDMSERVICECLASS>(core, 0); const auto ServiceData = arg<wow64::PVOID>(core, 1); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[371]); on_func(Service, ServiceData); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitForDebugEvent(proc_t proc, const on_NtWaitForDebugEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitForDebugEvent@16", [=] { auto& core = d_->core; const auto DebugObjectHandle = arg<wow64::HANDLE>(core, 0); const auto Alertable = arg<wow64::BOOLEAN>(core, 1); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 2); const auto WaitStateChange = arg<wow64::PDBGUI_WAIT_STATE_CHANGE>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[372]); on_func(DebugObjectHandle, Alertable, Timeout, WaitStateChange); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitForKeyedEvent(proc_t proc, const on_NtWaitForKeyedEvent_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitForKeyedEvent@16", [=] { auto& core = d_->core; const auto KeyedEventHandle = arg<wow64::HANDLE>(core, 0); const auto KeyValue = arg<wow64::PVOID>(core, 1); const auto Alertable = arg<wow64::BOOLEAN>(core, 2); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 3); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[373]); on_func(KeyedEventHandle, KeyValue, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitForMultipleObjects32(proc_t proc, const on_NtWaitForMultipleObjects32_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitForMultipleObjects32@20", [=] { auto& core = d_->core; const auto Count = arg<wow64::ULONG>(core, 0); const auto Handles = arg<wow64::LONG>(core, 1); const auto WaitType = arg<wow64::WAIT_TYPE>(core, 2); const auto Alertable = arg<wow64::BOOLEAN>(core, 3); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[374]); on_func(Count, Handles, WaitType, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitForMultipleObjects(proc_t proc, const on_NtWaitForMultipleObjects_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitForMultipleObjects@20", [=] { auto& core = d_->core; const auto Count = arg<wow64::ULONG>(core, 0); const auto Handles = arg<wow64::HANDLE>(core, 1); const auto WaitType = arg<wow64::WAIT_TYPE>(core, 2); const auto Alertable = arg<wow64::BOOLEAN>(core, 3); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[375]); on_func(Count, Handles, WaitType, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_ZwWaitForSingleObject(proc_t proc, const on_ZwWaitForSingleObject_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwWaitForSingleObject@12", [=] { auto& core = d_->core; const auto Handle = arg<wow64::HANDLE>(core, 0); const auto Alertable = arg<wow64::BOOLEAN>(core, 1); const auto Timeout = arg<wow64::PLARGE_INTEGER>(core, 2); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[376]); on_func(Handle, Alertable, Timeout); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitForWorkViaWorkerFactory(proc_t proc, const on_NtWaitForWorkViaWorkerFactory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitForWorkViaWorkerFactory@20", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); const auto MiniPacket = arg<wow64::PFILE_IO_COMPLETION_INFORMATION>(core, 1); const auto Arg2 = arg<wow64::PVOID>(core, 2); const auto Arg3 = arg<wow64::PVOID>(core, 3); const auto Arg4 = arg<wow64::PVOID>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[377]); on_func(WorkerFactoryHandle, MiniPacket, Arg2, Arg3, Arg4); }); } opt<bpid_t> wow64::syscalls32::register_ZwWaitHighEventPair(proc_t proc, const on_ZwWaitHighEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwWaitHighEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[378]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtWaitLowEventPair(proc_t proc, const on_NtWaitLowEventPair_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWaitLowEventPair@4", [=] { auto& core = d_->core; const auto EventPairHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[379]); on_func(EventPairHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtWorkerFactoryWorkerReady(proc_t proc, const on_NtWorkerFactoryWorkerReady_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWorkerFactoryWorkerReady@4", [=] { auto& core = d_->core; const auto WorkerFactoryHandle = arg<wow64::HANDLE>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[380]); on_func(WorkerFactoryHandle); }); } opt<bpid_t> wow64::syscalls32::register_NtWriteFileGather(proc_t proc, const on_NtWriteFileGather_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWriteFileGather@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto SegmentArray = arg<wow64::PFILE_SEGMENT_ELEMENT>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 7); const auto Key = arg<wow64::PULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[381]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, SegmentArray, Length, ByteOffset, Key); }); } opt<bpid_t> wow64::syscalls32::register_NtWriteFile(proc_t proc, const on_NtWriteFile_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWriteFile@36", [=] { auto& core = d_->core; const auto FileHandle = arg<wow64::HANDLE>(core, 0); const auto Event = arg<wow64::HANDLE>(core, 1); const auto ApcRoutine = arg<wow64::PIO_APC_ROUTINE>(core, 2); const auto ApcContext = arg<wow64::PVOID>(core, 3); const auto IoStatusBlock = arg<wow64::PIO_STATUS_BLOCK>(core, 4); const auto Buffer = arg<wow64::PVOID>(core, 5); const auto Length = arg<wow64::ULONG>(core, 6); const auto ByteOffset = arg<wow64::PLARGE_INTEGER>(core, 7); const auto Key = arg<wow64::PULONG>(core, 8); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[382]); on_func(FileHandle, Event, ApcRoutine, ApcContext, IoStatusBlock, Buffer, Length, ByteOffset, Key); }); } opt<bpid_t> wow64::syscalls32::register_NtWriteRequestData(proc_t proc, const on_NtWriteRequestData_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWriteRequestData@24", [=] { auto& core = d_->core; const auto PortHandle = arg<wow64::HANDLE>(core, 0); const auto Message = arg<wow64::PPORT_MESSAGE>(core, 1); const auto DataEntryIndex = arg<wow64::ULONG>(core, 2); const auto Buffer = arg<wow64::PVOID>(core, 3); const auto BufferSize = arg<wow64::SIZE_T>(core, 4); const auto NumberOfBytesWritten = arg<wow64::PSIZE_T>(core, 5); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[383]); on_func(PortHandle, Message, DataEntryIndex, Buffer, BufferSize, NumberOfBytesWritten); }); } opt<bpid_t> wow64::syscalls32::register_NtWriteVirtualMemory(proc_t proc, const on_NtWriteVirtualMemory_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtWriteVirtualMemory@20", [=] { auto& core = d_->core; const auto ProcessHandle = arg<wow64::HANDLE>(core, 0); const auto BaseAddress = arg<wow64::PVOID>(core, 1); const auto Buffer = arg<wow64::PVOID>(core, 2); const auto BufferSize = arg<wow64::SIZE_T>(core, 3); const auto NumberOfBytesWritten = arg<wow64::PSIZE_T>(core, 4); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[384]); on_func(ProcessHandle, BaseAddress, Buffer, BufferSize, NumberOfBytesWritten); }); } opt<bpid_t> wow64::syscalls32::register_NtDisableLastKnownGood(proc_t proc, const on_NtDisableLastKnownGood_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtDisableLastKnownGood@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[385]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtEnableLastKnownGood(proc_t proc, const on_NtEnableLastKnownGood_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtEnableLastKnownGood@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[386]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_ZwFlushProcessWriteBuffers(proc_t proc, const on_ZwFlushProcessWriteBuffers_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwFlushProcessWriteBuffers@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[387]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtFlushWriteBuffer(proc_t proc, const on_NtFlushWriteBuffer_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtFlushWriteBuffer@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[388]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtGetCurrentProcessorNumber(proc_t proc, const on_NtGetCurrentProcessorNumber_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtGetCurrentProcessorNumber@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[389]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtIsSystemResumeAutomatic(proc_t proc, const on_NtIsSystemResumeAutomatic_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtIsSystemResumeAutomatic@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[390]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_ZwIsUILanguageComitted(proc_t proc, const on_ZwIsUILanguageComitted_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwIsUILanguageComitted@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[391]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_ZwQueryPortInformationProcess(proc_t proc, const on_ZwQueryPortInformationProcess_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwQueryPortInformationProcess@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[392]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtSerializeBoot(proc_t proc, const on_NtSerializeBoot_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtSerializeBoot@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[393]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtTestAlert(proc_t proc, const on_NtTestAlert_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtTestAlert@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[394]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_ZwThawRegistry(proc_t proc, const on_ZwThawRegistry_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwThawRegistry@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[395]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_NtThawTransactions(proc_t proc, const on_NtThawTransactions_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_NtThawTransactions@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[396]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_ZwUmsThreadYield(proc_t proc, const on_ZwUmsThreadYield_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwUmsThreadYield@4", [=] { auto& core = d_->core; const auto SchedulerParam = arg<wow64::PVOID>(core, 0); if constexpr(g_debug) tracer::log_call(core, g_callcfgs[397]); on_func(SchedulerParam); }); } opt<bpid_t> wow64::syscalls32::register_ZwYieldExecution(proc_t proc, const on_ZwYieldExecution_fn& on_func) { return register_callback(*d_, ++d_->last_id, proc, "_ZwYieldExecution@0", [=] { auto& core = d_->core; if constexpr(g_debug) tracer::log_call(core, g_callcfgs[398]); on_func(); }); } opt<bpid_t> wow64::syscalls32::register_all(proc_t proc, const wow64::syscalls32::on_call_fn& on_call) { const auto id = ++d_->last_id; const auto size = d_->listeners.size(); for(const auto cfg : g_callcfgs) register_callback(*d_, id, proc, cfg.name, [=]{ on_call(cfg); }); if(size == d_->listeners.size()) return {}; return id; } bool wow64::syscalls32::unregister(bpid_t id) { return d_->listeners.erase(id) > 0; }
// RUN: %clang_cc1 -verify -fopenmp %s -Wno-openmp-target -Wuninitialized // RUN: %clang_cc1 -verify -fopenmp-simd %s -Wno-openmp-target -Wuninitialized extern int omp_default_mem_alloc; void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} expected-note{{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2() : a(0) {} S2(const S2 &s2) : a(s2.a) {} static float S2s; static const float S2sc; }; const float S2::S2sc = 0; const S2 b; const S2 ba[5]; class S3 { int a; public: S3() : a(0) {} S3(const S3 &s3) : a(s3.a) {} }; const S3 c; const S3 ca[5]; extern const int f; class S4 { int a; S4(); S4(const S4 &s4); // expected-note {{implicitly declared private here}} public: S4(int v) : a(v) {} }; class S5 { int a; S5() : a(0) {} S5(const S5 &s5) : a(s5.a) {} // expected-note {{implicitly declared private here}} public: S5(int v) : a(v) {} }; S3 h; #pragma omp threadprivate(h) // expected-note {{defined as threadprivate or thread local}} namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace B { using A::x; } int main(int argc, char **argv) { const int d = 5; const int da[5] = {0}; S4 e(4); S5 g(5); int i, z; int &j = i; #pragma omp target #pragma omp teams firstprivate // expected-error {{expected '(' after 'firstprivate'}} foo(); #pragma omp target #pragma omp teams firstprivate( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} foo(); #pragma omp target #pragma omp teams firstprivate() // expected-error {{expected expression}} foo(); #pragma omp target #pragma omp teams firstprivate(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} foo(); #pragma omp target #pragma omp teams firstprivate(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} foo(); #pragma omp target #pragma omp teams firstprivate(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} foo(); #pragma omp target #pragma omp teams firstprivate(argc) allocate , allocate(, allocate(omp_default , allocate(omp_default_mem_alloc, allocate(omp_default_mem_alloc:, allocate(omp_default_mem_alloc: argc, allocate(omp_default_mem_alloc: argv), allocate(argv) // expected-error {{expected '(' after 'allocate'}} expected-error 2 {{expected expression}} expected-error 2 {{expected ')'}} expected-error {{use of undeclared identifier 'omp_default'}} expected-note 2 {{to match this '('}} foo(); #pragma omp target #pragma omp teams firstprivate(S1) // expected-error {{'S1' does not refer to a value}} foo(); #pragma omp target #pragma omp teams firstprivate(a, b, c, d, f) // expected-error {{incomplete type 'S1' where a complete type is required}} expected-error {{firstprivate variable with incomplete type 'S1'}} foo(); #pragma omp target #pragma omp teams firstprivate(argv[1]) // expected-error {{expected variable name}} foo(); #pragma omp target #pragma omp teams firstprivate(ba, z) foo(); #pragma omp target #pragma omp teams firstprivate(ca) foo(); #pragma omp target #pragma omp teams firstprivate(da) foo(); #pragma omp target #pragma omp teams firstprivate(S2::S2s) foo(); #pragma omp target #pragma omp teams firstprivate(S2::S2sc) foo(); #pragma omp target #pragma omp teams firstprivate(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}} foo(); #pragma omp target #pragma omp teams firstprivate(h, B::x) // expected-error 2 {{threadprivate or thread local variable cannot be firstprivate}} foo(); #pragma omp target #pragma omp teams private(i), firstprivate(i) // expected-error {{private variable cannot be firstprivate}} expected-note{{defined as private}} foo(); #pragma omp target #pragma omp teams shared(i) foo(); #pragma omp target #pragma omp teams firstprivate(i) foo(); #pragma omp target #pragma omp teams firstprivate(j) foo(); static int m; #pragma omp target #pragma omp teams firstprivate(m) // OK foo(); return 0; }
#include "StdAfx.h" #include "MyRecordSet.h" using namespace System; using namespace System::IO; using namespace System::Text; using namespace System::Data::OleDb; using namespace System::Data; using namespace System::Collections::Generic; MyRecordSet::MyRecordSet(void) { } void MyRecordSet::SetPath() { String^ connection_string = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="; // Datenbank Pfad auslesen String^ pfad = Environment::GetFolderPath(Environment::SpecialFolder::LocalApplicationData); pfad += "\\db_pfad.txt"; FileStream^ fs = File::OpenRead(pfad); array<Byte>^b = gcnew array<Byte>(1024); UTF8Encoding^ temp = gcnew UTF8Encoding(true); fs->Read(b, 0, b->Length); mdbPath= temp->GetString(b); path = connection_string+mdbPath; fs->Close(); /*OleDbConnection^ myConnection; myConnection = gcnew OleDbConnection(path); myConnection->Open();*/ //myConnection->Close(); } MyRecordSet::MyRecordSet(String^ input) { query_=input; // Verbindung herstellen Establish connection String^ mySelectQuery = input; OleDbConnection^ myConnection; myConnection = gcnew OleDbConnection(path); myConnection->Open(); OleDbCommand^ myCommand = gcnew OleDbCommand(mySelectQuery,myConnection); OleDbDataReader^ myReader = myCommand->ExecuteReader(); rows_=0; try { coloumns_ = myReader->FieldCount; // Namen und Typen erkennen //Recognize names and types for(int i=0;i<coloumns_;++i) { String^ data_name (myReader->GetName(i)); String^ data_type (myReader->GetDataTypeName(i)); namen_.Add(data_name); typen_.Add(data_type); List<String^>^ new_list = gcnew List<String^>; table_.Add(new_list); } // Werte konvertieren und Tabelle füllen //Convert values and fill the table while (myReader->Read()) { rows_++; for(int i=0;i<coloumns_;++i) { String^ data_name (myReader->GetName(i)); String^ data_type (myReader->GetDataTypeName(i)); if(typen_[i] == "DBTYPE_I4") table_[i]->Add( (myReader->GetInt32(i)).ToString()); if(typen_[i] == "DBTYPE_WVARCHAR") table_[i]->Add(myReader->GetString(i)); } } } __finally { myReader->Close(); myConnection->Close(); } } String^ MyRecordSet::get_Name(int index) { return namen_[index]; } String^ MyRecordSet::get_Type(int index) { return typen_[index]; } String^ MyRecordSet::get_val(int index_row, int index_clm) { List<String^> liste(table_[index_clm]); return liste[index_row]; } int MyRecordSet::get_clm() { return coloumns_; } int MyRecordSet::get_row() { return rows_; } int MyRecordSet::get_new_id() { List<String^> liste(table_[0]); for(int i=1;i<liste.Count+3;++i) if(!liste.Contains(i.ToString())) return i; return -1; } String^ MyRecordSet::QueryAllAnnualBudget(String^ city, String^ area, String^ program) { return "SELECT jahreshaushalt.* FROM jahreshaushalt inner join (Programme inner join (Gebiete inner join Staedte on Gebiete.Stadt_ID=Staedte.ID ) on Programme.Gebiet_ID=Gebiete.ID) on jahreshaushalt.programm_ID=Programme.ID WHERE Staedte.Stadt='" + city + "' and Gebiete.Gebiet='" + area + "' and Programme.Programm='" + program+"'"; } String^ MyRecordSet::GetProgramNr(String^ programName) { String^ query = "SELECT Programm_Nr FROM Programme WHERE Programm='" + programName + "'"; MyRecordSet RC(query); return RC.get_val(0, 0); } String^ MyRecordSet::GetAreaId(String^ city, String^ area) { String^ query = "SELECT Gebiete.ID FROM Gebiete inner join Staedte on Gebiete.Stadt_ID=Staedte.ID WHERE Staedte.Stadt='" + city + "' AND Gebiet='"+area+"'"; MyRecordSet RC(query); return RC.get_val(0, 0); } String^ MyRecordSet::QueryOneAnnualBudget(String^ city, String^ area, String^ program, String^ year) { return QueryAllAnnualBudget(city, area, program) + " and jahreshaushalt.jahr='" + year + "'"; }
// Copyright (c) 2005-2014 Code Synthesis Tools CC // // This program was generated by CodeSynthesis XSD, an XML Schema to // C++ data binding compiler. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // // In addition, as a special exception, Code Synthesis Tools CC gives // permission to link this program with the Xerces-C++ library (or with // modified versions of Xerces-C++ that use the same license as Xerces-C++), // and distribute linked combinations including the two. You must obey // the GNU General Public License version 2 in all respects for all of // the code used other than Xerces-C++. If you modify this copy of the // program, you may extend this exception to your version of the program, // but you are not obligated to do so. If you do not wish to do so, delete // this exception statement from your version. // // Furthermore, Code Synthesis Tools CC makes a special exception for // the Free/Libre and Open Source Software (FLOSS) which is described // in the accompanying FLOSSE file. // // Begin prologue. // // // End prologue. #include <xsd/cxx/pre.hxx> #include "SimTemplateNaturalVentilation_NaturalVentilation.hxx" namespace schema { namespace simxml { namespace ResourcesGeneral { // SimTemplateNaturalVentilation_NaturalVentilation // } } } #include <xsd/cxx/xml/dom/parsing-source.hxx> #include <xsd/cxx/tree/type-factory-map.hxx> namespace _xsd { static const ::xsd::cxx::tree::type_factory_plate< 0, char > type_factory_plate_init; } namespace schema { namespace simxml { namespace ResourcesGeneral { // SimTemplateNaturalVentilation_NaturalVentilation // SimTemplateNaturalVentilation_NaturalVentilation:: SimTemplateNaturalVentilation_NaturalVentilation () : ::schema::simxml::ResourcesGeneral::SimTemplateNaturalVentilation () { } SimTemplateNaturalVentilation_NaturalVentilation:: SimTemplateNaturalVentilation_NaturalVentilation (const RefId_type& RefId) : ::schema::simxml::ResourcesGeneral::SimTemplateNaturalVentilation (RefId) { } SimTemplateNaturalVentilation_NaturalVentilation:: SimTemplateNaturalVentilation_NaturalVentilation (const SimTemplateNaturalVentilation_NaturalVentilation& x, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimTemplateNaturalVentilation (x, f, c) { } SimTemplateNaturalVentilation_NaturalVentilation:: SimTemplateNaturalVentilation_NaturalVentilation (const ::xercesc::DOMElement& e, ::xml_schema::flags f, ::xml_schema::container* c) : ::schema::simxml::ResourcesGeneral::SimTemplateNaturalVentilation (e, f, c) { } SimTemplateNaturalVentilation_NaturalVentilation* SimTemplateNaturalVentilation_NaturalVentilation:: _clone (::xml_schema::flags f, ::xml_schema::container* c) const { return new class SimTemplateNaturalVentilation_NaturalVentilation (*this, f, c); } SimTemplateNaturalVentilation_NaturalVentilation:: ~SimTemplateNaturalVentilation_NaturalVentilation () { } } } } #include <istream> #include <xsd/cxx/xml/sax/std-input-source.hxx> #include <xsd/cxx/tree/error-handler.hxx> namespace schema { namespace simxml { namespace ResourcesGeneral { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue.
#include "main.h" #include <cage-core/math.h> #include <cage-core/variableSmoothingBuffer.h> void testVariableSmoothingBuffer() { CAGE_TESTCASE("VariableSmoothingBuffer"); { CAGE_TESTCASE("compilations"); VariableSmoothingBuffer<uint32> iUint32; VariableSmoothingBuffer<Real> iReal; VariableSmoothingBuffer<Rads> iRads; VariableSmoothingBuffer<Vec2> iVec2; VariableSmoothingBuffer<Vec3> iVec3; VariableSmoothingBuffer<Vec4> iVec4; VariableSmoothingBuffer<Quat> iQuat; } { CAGE_TESTCASE("smoothing with real"); VariableSmoothingBuffer<Real, 3> v; CAGE_TEST(v.current() == 0); v.seed(13); v.add(90); v.add(30); v.add(50); v.add(10); CAGE_TEST(v.current() == 10); CAGE_TEST(v.oldest() == 30); CAGE_TEST(v.smooth() == 30); CAGE_TEST(v.max() == 50); CAGE_TEST(v.min() == 10); } { CAGE_TESTCASE("smoothing with uint32"); VariableSmoothingBuffer<uint32, 4> v; CAGE_TEST(v.current() == 0); v.add(20); v.add(10); v.add(50); v.add(40); CAGE_TEST(v.current() == 40); CAGE_TEST(v.oldest() == 20); CAGE_TEST(v.smooth() == 30); CAGE_TEST(v.max() == 50); CAGE_TEST(v.min() == 10); } { CAGE_TESTCASE("smoothing with quat"); VariableSmoothingBuffer<Quat, 4> v; v.seed(Quat(Degs(50), Degs(), Degs())); v.add(Quat(Degs(20), Degs(), Degs())); v.add(Quat(Degs(10), Degs(), Degs())); CAGE_TEST(v.current() == Quat(Degs(10), Degs(), Degs())); CAGE_TEST(v.oldest() == Quat(Degs(50), Degs(), Degs())); v.smooth(); } }
/* Smooth - A C++ framework for embedded programming on top of Espressif's ESP-IDF Copyright 2019 Per Malmberg (https://gitbub.com/PerMalmberg) 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 "server_socket_test.h" #include <deque> #include "smooth/core/Task.h" #include "smooth/core/task_priorities.h" #include "smooth/core/Application.h" #include "smooth/core/logging/log.h" #include "smooth/core/network/IPv4.h" #include "smooth/core/network/ServerSocket.h" #include "smooth/core/network/SecureServerSocket.h" #include "wifi_creds.h" using namespace std::chrono; using namespace smooth::core; using namespace smooth::core::network; using namespace smooth::core::network::event; using namespace smooth::core::logging; namespace server_socket_test { App::App() : Application(smooth::core::APPLICATION_BASE_PRIO, std::chrono::milliseconds(1000)) { } void App::init() { Application::init(); Log::info("App::Init", "Starting wifi..."); network::Wifi& wifi = get_wifi(); wifi.set_host_name("Smooth-ESP"); wifi.set_auto_connect(true); wifi.set_ap_credentials(WIFI_SSID, WIFI_PASSWORD); wifi.connect_to_ap(); // The server creates StreamingClients which are self-sufficient and never seen by the main // application (unless the implementor adds such bindings). server = ServerSocket<StreamingClient, StreamingProtocol, void>::create(*this, 5, 5); server->start(std::make_shared<IPv4>("0.0.0.0", 8080)); // Point your browser to http://localhost:8080 and watch the output. // Or, if you're on linux, do "echo ` date` | nc localhost 8080 -w1" } }
/* * Copyright 2004-2009, Marcus Overhagen. All rights reserved. * Distributed under the terms of the MIT License. */ #include "util.h" #include <KernelExport.h> #include <OS.h> #include <vm/vm.h> #include <string.h> #define TRACE(a...) dprintf("ahci: " a) #define ERROR(a...) dprintf("ahci: " a) static inline uint32 round_to_pagesize(uint32 size) { return (size + B_PAGE_SIZE - 1) & ~(B_PAGE_SIZE - 1); } area_id alloc_mem(void **virt, phys_addr_t *phy, size_t size, uint32 protection, const char *name) { physical_entry pe; void * virtadr; area_id areaid; status_t rv; TRACE("allocating %ld bytes for %s\n", size, name); size = round_to_pagesize(size); areaid = create_area(name, &virtadr, B_ANY_KERNEL_ADDRESS, size, B_CONTIGUOUS, protection); if (areaid < B_OK) { ERROR("couldn't allocate area %s\n", name); return B_ERROR; } rv = get_memory_map(virtadr, size, &pe, 1); if (rv < B_OK) { delete_area(areaid); ERROR("couldn't get mapping for %s\n", name); return B_ERROR; } if (virt) *virt = virtadr; if (phy) *phy = pe.address; TRACE("area = %" B_PRId32 ", size = %ld, virt = %p, phy = %#" B_PRIxPHYSADDR "\n", areaid, size, virtadr, pe.address); return areaid; } area_id map_mem(void **virt, phys_addr_t phy, size_t size, uint32 protection, const char *name) { uint32 offset; phys_addr_t phyadr; void *mapadr; area_id area; TRACE("mapping physical address %#" B_PRIxPHYSADDR " with %" B_PRIuSIZE " bytes for %s\n", phy, size, name); offset = phy & (B_PAGE_SIZE - 1); phyadr = phy - offset; size = round_to_pagesize(size + offset); area = map_physical_memory(name, phyadr, size, B_ANY_KERNEL_BLOCK_ADDRESS, protection, &mapadr); if (area < B_OK) { ERROR("mapping '%s' failed, error 0x%" B_PRIx32 " (%s)\n", name, area, strerror(area)); return area; } *virt = (char *)mapadr + offset; TRACE("physical = %#" B_PRIxPHYSADDR ", virtual = %p, offset = %" B_PRId32 ", phyadr = %#" B_PRIxPHYSADDR ", mapadr = %p, size = %" B_PRIuSIZE ", area = 0x%08" B_PRIx32 "\n", phy, *virt, offset, phyadr, mapadr, size, area); return area; } status_t sg_memcpy(const physical_entry *sgTable, int sgCount, const void *data, size_t dataSize) { int i; for (i = 0; i < sgCount && dataSize > 0; i++) { size_t size = min_c(dataSize, sgTable[i].size); TRACE("sg_memcpy phyAddr %#" B_PRIxPHYSADDR ", size %lu\n", sgTable[i].address, size); vm_memcpy_to_physical(sgTable[i].address, data, size, false); data = (char *)data + size; dataSize -= size; } if (dataSize != 0) return B_ERROR; return B_OK; } void swap_words(void *data, size_t size) { uint16 *word = (uint16*)data; size_t count = size / 2; while (count--) { *word = (*word << 8) | (*word >> 8); word++; } } int fls(unsigned mask) { if (mask == 0) return 0; int pos = 1; while (mask != 1) { mask >>= 1; pos++; } return pos; }
#include <algorithm> #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" namespace caffe { template <typename Dtype> void SliceLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { LOG(INFO)<<"slice start reshape"; const SliceParameter& slice_param = this->layer_param_.slice_param(); slice_dim_ = slice_param.slice_dim(); CHECK_GE(slice_dim_, 0); CHECK_LE(slice_dim_, 1) << "Can only slice num and channels"; slice_point_.clear(); std::copy(slice_param.slice_point().begin(), slice_param.slice_point().end(), std::back_inserter(slice_point_)); Reshape(bottom,top); // this is tzeng test part 12/08/2014 //for (int i = 0; i < top->size(); ++i){ //(*top)[i]->Reshape(bottom[0]->num(), bottom[0]->channels(), // bottom[0]->height(), bottom[0]->width()); // CHECK_EQ(count_, (*top)[i]->count()); //} } template <typename Dtype> void SliceLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { count_ = 0; num_ = bottom[0]->num(); channels_ = bottom[0]->channels(); height_ = bottom[0]->height(); width_ = bottom[0]->width(); LOG(INFO)<<"slice start reshape"; if (slice_point_.size() != 0) { CHECK_EQ(slice_point_.size(), top->size() - 1); if (slice_dim_ == 0) { CHECK_LE(top->size(), num_); } else { CHECK_LE(top->size(), channels_); } int prev = 0; vector<int> slices; for (int i = 0; i < slice_point_.size(); ++i) { CHECK_GT(slice_point_[i], prev); slices.push_back(slice_point_[i] - prev); prev = slice_point_[i]; } if (slice_dim_ == 0) { slices.push_back(num_ - prev); for (int i = 0; i < top->size(); ++i) { (*top)[i]->Reshape(slices[i], channels_, height_, width_); count_ += (*top)[i]->count(); } } else { slices.push_back(channels_ - prev); for (int i = 0; i < top->size(); ++i) { (*top)[i]->Reshape(num_, slices[i], height_, width_); count_ += (*top)[i]->count(); } } } else { if (slice_dim_ == 0) { CHECK_EQ(num_ % top->size(), 0) << "Number of top blobs (" << top->size() << ") " << "should evenly divide input num ( " << num_ << ")"; num_ = num_ / top->size(); } else { CHECK_EQ(channels_ % top->size(), 0) << "Number of top blobs (" << top->size() << ") " << "should evenly divide input channels ( " << channels_ << ")"; channels_ = channels_ / top->size(); } for (int i = 0; i < top->size(); ++i) { (*top)[i]->Reshape(num_, channels_, height_, width_); count_ += (*top)[i]->count(); } } CHECK_EQ(count_, bottom[0]->count()); Blob<Dtype>* blob = (*top)[0]; LOG(INFO)<<"top(0) num =" <<blob->num() << "channels ="<<blob->channels(); } template <typename Dtype> Dtype SliceLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) { const Dtype* bottom_data = bottom[0]->mutable_cpu_data(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* blob = (*top)[i]; Dtype* top_data = blob->mutable_cpu_data(); caffe_copy(blob->count(), bottom_data + bottom[0]->offset(offset_num), top_data); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top->size(); ++i) { Blob<Dtype>* blob = (*top)[i]; Dtype* top_data = blob->mutable_cpu_data(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, bottom_data + bottom[0]->offset(n, offset_channel), top_data + blob->offset(n)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. return Dtype(0.); } template <typename Dtype> void SliceLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, vector<Blob<Dtype>*>* bottom) { if (!propagate_down[0]) { return; } Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff(); if (slice_dim_ == 0) { int offset_num = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); caffe_copy(blob->count(), top_diff, bottom_diff + (*bottom)[0]->offset(offset_num)); offset_num += blob->num(); } } else if (slice_dim_ == 1) { int offset_channel = 0; for (int i = 0; i < top.size(); ++i) { Blob<Dtype>* blob = top[i]; const Dtype* top_diff = blob->cpu_diff(); const int num_elem = blob->channels() * blob->height() * blob->width(); for (int n = 0; n < num_; ++n) { caffe_copy(num_elem, top_diff + blob->offset(n), bottom_diff + (*bottom)[0]->offset(n, offset_channel)); } offset_channel += blob->channels(); } } // slice_dim_ is guaranteed to be 0 or 1 by SetUp. } #ifdef CPU_ONLY STUB_GPU(SliceLayer); #endif INSTANTIATE_CLASS(SliceLayer); } // namespace caffe
#include "basis_function/lagrange.h" namespace BasisFunction { // linear template<> double LagrangeOfOrder<1>:: dphi_dxi(int i, double xi) { if (i==0) return -1; return 1; } template<> double LagrangeOfOrder<1>:: phi(int i, double xi) { if (i==0) return 1-xi; return xi; } // quadratic template<> double LagrangeOfOrder<2>:: dphi_dxi(int i, double xi) { if (i==0) return 4*xi - 3; else if (i==1) return -8*xi + 4; return 4*xi - 1; } template<> double LagrangeOfOrder<2>:: phi(int i, double xi) { // phi(xi) = a*xi^2 + b*xi + c // phi0(xi) = 2*xi^2 -3*xi + 1 // phi1(xi) = -4*xi^2 + 4*xi // phi2(xi) = 2*xi^2 - xi if (i==0) return (2*xi - 1) * (xi-1); // 2*xi*xi - 3*xi + 1 else if (i==1) return 4*(xi - xi*xi); return 2*xi*xi - xi; } } // namespace
/*************************************************************************/ /* texture.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "texture.h" #include "core/core_string_names.h" #include "core/io/image_loader.h" #include "core/method_bind_ext.gen.inc" #include "core/os/os.h" #include "scene/resources/bit_mask.h" Size2 Texture::get_size() const { return Size2(get_width(), get_height()); } bool Texture::is_pixel_opaque(int p_x, int p_y) const { return true; } void Texture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, get_size()), get_rid(), false, p_modulate, p_transpose, normal_rid); } void Texture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, get_rid(), p_tile, p_modulate, p_transpose, normal_rid); } void Texture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map, bool p_clip_uv) const { RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, get_rid(), p_src_rect, p_modulate, p_transpose, normal_rid, p_clip_uv); } bool Texture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const { r_rect = p_rect; r_src_rect = p_src_rect; return true; } void Texture::_bind_methods() { ClassDB::bind_method(D_METHOD("get_width"), &Texture::get_width); ClassDB::bind_method(D_METHOD("get_height"), &Texture::get_height); ClassDB::bind_method(D_METHOD("get_size"), &Texture::get_size); ClassDB::bind_method(D_METHOD("has_alpha"), &Texture::has_alpha); ClassDB::bind_method(D_METHOD("set_flags", "flags"), &Texture::set_flags); ClassDB::bind_method(D_METHOD("get_flags"), &Texture::get_flags); ClassDB::bind_method(D_METHOD("draw", "canvas_item", "position", "modulate", "transpose", "normal_map"), &Texture::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(false), DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("draw_rect", "canvas_item", "rect", "tile", "modulate", "transpose", "normal_map"), &Texture::draw_rect, DEFVAL(Color(1, 1, 1)), DEFVAL(false), DEFVAL(Variant())); ClassDB::bind_method(D_METHOD("draw_rect_region", "canvas_item", "rect", "src_rect", "modulate", "transpose", "normal_map", "clip_uv"), &Texture::draw_rect_region, DEFVAL(Color(1, 1, 1)), DEFVAL(false), DEFVAL(Variant()), DEFVAL(true)); ClassDB::bind_method(D_METHOD("get_data"), &Texture::get_data); ADD_GROUP("Flags", ""); ADD_PROPERTY(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter,Anisotropic Linear,Convert to Linear,Mirrored Repeat,Video Surface"), "set_flags", "get_flags"); ADD_GROUP("", ""); BIND_ENUM_CONSTANT(FLAGS_DEFAULT); BIND_ENUM_CONSTANT(FLAG_MIPMAPS); BIND_ENUM_CONSTANT(FLAG_REPEAT); BIND_ENUM_CONSTANT(FLAG_FILTER); BIND_ENUM_CONSTANT(FLAG_ANISOTROPIC_FILTER); BIND_ENUM_CONSTANT(FLAG_CONVERT_TO_LINEAR); BIND_ENUM_CONSTANT(FLAG_MIRRORED_REPEAT); BIND_ENUM_CONSTANT(FLAG_VIDEO_SURFACE); } Texture::Texture() { } ///////////////////// void ImageTexture::reload_from_file() { String path = ResourceLoader::path_remap(get_path()); if (!path.is_resource_file()) return; uint32_t flags = get_flags(); Ref<Image> img; img.instance(); Error err = ImageLoader::load_image(path, img); ERR_FAIL_COND(err != OK); create_from_image(img, flags); } bool ImageTexture::_set(const StringName &p_name, const Variant &p_value) { if (p_name == "image") create_from_image(p_value, flags); else if (p_name == "flags") if (w * h == 0) flags = p_value; else set_flags(p_value); else if (p_name == "size") { Size2 s = p_value; w = s.width; h = s.height; VisualServer::get_singleton()->texture_set_size_override(texture, w, h, 0); } else if (p_name == "_data") { _set_data(p_value); } else return false; return true; } bool ImageTexture::_get(const StringName &p_name, Variant &r_ret) const { if (p_name == "image_data") { } else if (p_name == "image") r_ret = get_data(); else if (p_name == "flags") r_ret = flags; else if (p_name == "size") r_ret = Size2(w, h); else return false; return true; } void ImageTexture::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter,Anisotropic,sRGB,Mirrored Repeat")); p_list->push_back(PropertyInfo(Variant::OBJECT, "image", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::VECTOR2, "size", PROPERTY_HINT_NONE, "")); } void ImageTexture::_reload_hook(const RID &p_hook) { String path = get_path(); if (!path.is_resource_file()) return; Ref<Image> img; img.instance(); Error err = ImageLoader::load_image(path, img); ERR_FAIL_COND(err != OK); VisualServer::get_singleton()->texture_set_data(texture, img); _change_notify(); } bool ImageTexture::keep_images_cached = false; void ImageTexture::set_keep_images_cached(bool p_enable) { keep_images_cached = p_enable; } void ImageTexture::create(int p_width, int p_height, Image::Format p_format, uint32_t p_flags) { flags = p_flags; VisualServer::get_singleton()->texture_allocate(texture, p_width, p_height, 0, p_format, VS::TEXTURE_TYPE_2D, p_flags); format = p_format; w = p_width; h = p_height; _change_notify(); } void ImageTexture::create_from_image(const Ref<Image> &p_image, uint32_t p_flags) { ERR_FAIL_COND(p_image.is_null()); flags = p_flags; w = p_image->get_width(); h = p_image->get_height(); format = p_image->get_format(); VisualServer::get_singleton()->texture_allocate(texture, p_image->get_width(), p_image->get_height(), 0, p_image->get_format(), VS::TEXTURE_TYPE_2D, p_flags); VisualServer::get_singleton()->texture_set_data(texture, p_image); _change_notify(); if (keep_images_cached) { image_cache = p_image; } } void ImageTexture::set_flags(uint32_t p_flags) { /* uint32_t cube = flags & FLAG_CUBEMAP; if (flags == p_flags&cube) return; flags=p_flags|cube; */ flags = p_flags; if (w == 0 || h == 0) { return; //uninitialized, do not set to texture } VisualServer::get_singleton()->texture_set_flags(texture, p_flags); _change_notify("flags"); } uint32_t ImageTexture::get_flags() const { return ImageTexture::flags; } Image::Format ImageTexture::get_format() const { return format; } #ifndef DISABLE_DEPRECATED Error ImageTexture::load(const String &p_path) { WARN_DEPRECATED Ref<Image> img; img.instance(); Error err = img->load(p_path); if (err == OK) { create_from_image(img); } return err; } #endif void ImageTexture::set_data(const Ref<Image> &p_image) { ERR_FAIL_COND(p_image.is_null()); VisualServer::get_singleton()->texture_set_data(texture, p_image); _change_notify(); alpha_cache.unref(); if (keep_images_cached) { image_cache = p_image; } } void ImageTexture::_resource_path_changed() { String path = get_path(); } Ref<Image> ImageTexture::get_data() const { if (image_cache.is_valid()) { return image_cache; } else { return VisualServer::get_singleton()->texture_get_data(texture); } } int ImageTexture::get_width() const { return w; } int ImageTexture::get_height() const { return h; } RID ImageTexture::get_rid() const { return texture; } bool ImageTexture::has_alpha() const { return (format == Image::FORMAT_LA8 || format == Image::FORMAT_RGBA8); } void ImageTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose, normal_rid); } void ImageTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose, normal_rid); } void ImageTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map, bool p_clip_uv) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose, normal_rid, p_clip_uv); } bool ImageTexture::is_pixel_opaque(int p_x, int p_y) const { if (!alpha_cache.is_valid()) { Ref<Image> img = get_data(); if (img.is_valid()) { if (img->is_compressed()) { //must decompress, if compressed Ref<Image> decom = img->duplicate(); decom->decompress(); img = decom; } alpha_cache.instance(); alpha_cache->create_from_image_alpha(img); } } if (alpha_cache.is_valid()) { int aw = int(alpha_cache->get_size().width); int ah = int(alpha_cache->get_size().height); if (aw == 0 || ah == 0) { return true; } int x = p_x * aw / w; int y = p_y * ah / h; x = CLAMP(x, 0, aw); y = CLAMP(y, 0, ah); return alpha_cache->get_bit(Point2(x, y)); } return true; } void ImageTexture::set_size_override(const Size2 &p_size) { Size2 s = p_size; if (s.x != 0) w = s.x; if (s.y != 0) h = s.y; VisualServer::get_singleton()->texture_set_size_override(texture, w, h, 0); } void ImageTexture::set_path(const String &p_path, bool p_take_over) { if (texture.is_valid()) { VisualServer::get_singleton()->texture_set_path(texture, p_path); } Resource::set_path(p_path, p_take_over); } void ImageTexture::set_storage(Storage p_storage) { storage = p_storage; } ImageTexture::Storage ImageTexture::get_storage() const { return storage; } void ImageTexture::set_lossy_storage_quality(float p_lossy_storage_quality) { lossy_storage_quality = p_lossy_storage_quality; } float ImageTexture::get_lossy_storage_quality() const { return lossy_storage_quality; } void ImageTexture::_set_data(Dictionary p_data) { Ref<Image> img = p_data["image"]; ERR_FAIL_COND(!img.is_valid()); uint32_t flags = p_data["flags"]; create_from_image(img, flags); set_storage(Storage(p_data["storage"].operator int())); set_lossy_storage_quality(p_data["lossy_quality"]); set_size_override(p_data["size"]); }; void ImageTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("create", "width", "height", "format", "flags"), &ImageTexture::create, DEFVAL(FLAGS_DEFAULT)); ClassDB::bind_method(D_METHOD("create_from_image", "image", "flags"), &ImageTexture::create_from_image, DEFVAL(FLAGS_DEFAULT)); ClassDB::bind_method(D_METHOD("get_format"), &ImageTexture::get_format); #ifndef DISABLE_DEPRECATED ClassDB::bind_method(D_METHOD("load", "path"), &ImageTexture::load); #endif ClassDB::bind_method(D_METHOD("set_data", "image"), &ImageTexture::set_data); ClassDB::bind_method(D_METHOD("set_storage", "mode"), &ImageTexture::set_storage); ClassDB::bind_method(D_METHOD("get_storage"), &ImageTexture::get_storage); ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &ImageTexture::set_lossy_storage_quality); ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &ImageTexture::get_lossy_storage_quality); ClassDB::bind_method(D_METHOD("set_size_override", "size"), &ImageTexture::set_size_override); ClassDB::bind_method(D_METHOD("_reload_hook", "rid"), &ImageTexture::_reload_hook); ADD_PROPERTY(PropertyInfo(Variant::INT, "storage", PROPERTY_HINT_ENUM, "Uncompressed,Compress Lossy,Compress Lossless"), "set_storage", "get_storage"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "lossy_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), "set_lossy_storage_quality", "get_lossy_storage_quality"); BIND_ENUM_CONSTANT(STORAGE_RAW); BIND_ENUM_CONSTANT(STORAGE_COMPRESS_LOSSY); BIND_ENUM_CONSTANT(STORAGE_COMPRESS_LOSSLESS); } ImageTexture::ImageTexture() { w = h = 0; flags = FLAGS_DEFAULT; texture = VisualServer::get_singleton()->texture_create(); storage = STORAGE_RAW; lossy_storage_quality = 0.7; } ImageTexture::~ImageTexture() { VisualServer::get_singleton()->free(texture); } ////////////////////////////////////////// void StreamTexture::set_path(const String &p_path, bool p_take_over) { if (texture.is_valid()) { VisualServer::get_singleton()->texture_set_path(texture, p_path); } Resource::set_path(p_path, p_take_over); } void StreamTexture::_requested_3d(void *p_ud) { StreamTexture *st = (StreamTexture *)p_ud; Ref<StreamTexture> stex(st); ERR_FAIL_COND(!request_3d_callback); request_3d_callback(stex); } void StreamTexture::_requested_srgb(void *p_ud) { StreamTexture *st = (StreamTexture *)p_ud; Ref<StreamTexture> stex(st); ERR_FAIL_COND(!request_srgb_callback); request_srgb_callback(stex); } void StreamTexture::_requested_normal(void *p_ud) { StreamTexture *st = (StreamTexture *)p_ud; Ref<StreamTexture> stex(st); ERR_FAIL_COND(!request_normal_callback); request_normal_callback(stex); } StreamTexture::TextureFormatRequestCallback StreamTexture::request_3d_callback = NULL; StreamTexture::TextureFormatRequestCallback StreamTexture::request_srgb_callback = NULL; StreamTexture::TextureFormatRequestCallback StreamTexture::request_normal_callback = NULL; uint32_t StreamTexture::get_flags() const { return flags; } Image::Format StreamTexture::get_format() const { return format; } Error StreamTexture::_load_data(const String &p_path, int &tw, int &th, int &flags, Ref<Image> &image, int p_size_limit) { alpha_cache.unref(); ERR_FAIL_COND_V(image.is_null(), ERR_INVALID_PARAMETER); FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V(!f, ERR_CANT_OPEN); uint8_t header[4]; f->get_buffer(header, 4); if (header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T') { memdelete(f); ERR_FAIL_COND_V(header[0] != 'G' || header[1] != 'D' || header[2] != 'S' || header[3] != 'T', ERR_FILE_CORRUPT); } tw = f->get_32(); th = f->get_32(); flags = f->get_32(); //texture flags! uint32_t df = f->get_32(); //data format /* print_line("width: " + itos(tw)); print_line("height: " + itos(th)); print_line("flags: " + itos(flags)); print_line("df: " + itos(df)); */ #ifdef TOOLS_ENABLED if (request_3d_callback && df & FORMAT_BIT_DETECT_3D) { //print_line("request detect 3D at " + p_path); VS::get_singleton()->texture_set_detect_3d_callback(texture, _requested_3d, this); } else { //print_line("not requesting detect 3D at " + p_path); VS::get_singleton()->texture_set_detect_3d_callback(texture, NULL, NULL); } if (request_srgb_callback && df & FORMAT_BIT_DETECT_SRGB) { //print_line("request detect srgb at " + p_path); VS::get_singleton()->texture_set_detect_srgb_callback(texture, _requested_srgb, this); } else { //print_line("not requesting detect srgb at " + p_path); VS::get_singleton()->texture_set_detect_srgb_callback(texture, NULL, NULL); } if (request_srgb_callback && df & FORMAT_BIT_DETECT_NORMAL) { //print_line("request detect srgb at " + p_path); VS::get_singleton()->texture_set_detect_normal_callback(texture, _requested_normal, this); } else { //print_line("not requesting detect normal at " + p_path); VS::get_singleton()->texture_set_detect_normal_callback(texture, NULL, NULL); } #endif if (!(df & FORMAT_BIT_STREAM)) { p_size_limit = 0; } if (df & FORMAT_BIT_LOSSLESS || df & FORMAT_BIT_LOSSY) { //look for a PNG or WEBP file inside int sw = tw; int sh = th; uint32_t mipmaps = f->get_32(); uint32_t size = f->get_32(); //print_line("mipmaps: " + itos(mipmaps)); while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) { f->seek(f->get_position() + size); mipmaps = f->get_32(); size = f->get_32(); sw = MAX(sw >> 1, 1); sh = MAX(sh >> 1, 1); mipmaps--; } //mipmaps need to be read independently, they will be later combined Vector<Ref<Image> > mipmap_images; int total_size = 0; for (uint32_t i = 0; i < mipmaps; i++) { if (i) { size = f->get_32(); } PoolVector<uint8_t> pv; pv.resize(size); { PoolVector<uint8_t>::Write w = pv.write(); f->get_buffer(w.ptr(), size); } Ref<Image> img; if (df & FORMAT_BIT_LOSSLESS) { img = Image::lossless_unpacker(pv); } else { img = Image::lossy_unpacker(pv); } if (img.is_null() || img->empty()) { memdelete(f); ERR_FAIL_COND_V(img.is_null() || img->empty(), ERR_FILE_CORRUPT); } total_size += img->get_data().size(); mipmap_images.push_back(img); } //print_line("mipmap read total: " + itos(mipmap_images.size())); memdelete(f); //no longer needed if (mipmap_images.size() == 1) { image = mipmap_images[0]; return OK; } else { PoolVector<uint8_t> img_data; img_data.resize(total_size); { PoolVector<uint8_t>::Write w = img_data.write(); int ofs = 0; for (int i = 0; i < mipmap_images.size(); i++) { PoolVector<uint8_t> id = mipmap_images[i]->get_data(); int len = id.size(); PoolVector<uint8_t>::Read r = id.read(); copymem(&w[ofs], r.ptr(), len); ofs += len; } } image->create(sw, sh, true, mipmap_images[0]->get_format(), img_data); return OK; } } else { //look for regular format Image::Format format = (Image::Format)(df & FORMAT_MASK_IMAGE_FORMAT); bool mipmaps = df & FORMAT_BIT_HAS_MIPMAPS; if (!mipmaps) { int size = Image::get_image_data_size(tw, th, format, 0); PoolVector<uint8_t> img_data; img_data.resize(size); { PoolVector<uint8_t>::Write w = img_data.write(); f->get_buffer(w.ptr(), size); } memdelete(f); image->create(tw, th, false, format, img_data); return OK; } else { int sw = tw; int sh = th; int mipmaps = Image::get_image_required_mipmaps(tw, th, format); int total_size = Image::get_image_data_size(tw, th, format, true); int idx = 0; int ofs = 0; while (mipmaps > 1 && p_size_limit > 0 && (sw > p_size_limit || sh > p_size_limit)) { sw = MAX(sw >> 1, 1); sh = MAX(sh >> 1, 1); mipmaps--; idx++; } if (idx > 0) { ofs = Image::get_image_data_size(tw, th, format, idx - 1); } if (total_size - ofs <= 0) { memdelete(f); ERR_FAIL_V(ERR_FILE_CORRUPT); } f->seek(f->get_position() + ofs); PoolVector<uint8_t> img_data; img_data.resize(total_size - ofs); { PoolVector<uint8_t>::Write w = img_data.write(); int bytes = f->get_buffer(w.ptr(), total_size - ofs); //print_line("requested read: " + itos(total_size - ofs) + " but got: " + itos(bytes)); memdelete(f); int expected = total_size - ofs; if (bytes < expected) { //this is a compatibility workaround for older format, which saved less mipmaps. It is still recommended the image is reimported. zeromem(w.ptr() + bytes, (expected - bytes)); } else if (bytes != expected) { ERR_FAIL_V(ERR_FILE_CORRUPT); } } image->create(sw, sh, true, format, img_data); return OK; } } return ERR_BUG; //unreachable } Error StreamTexture::load(const String &p_path) { int lw, lh, lflags; Ref<Image> image; image.instance(); Error err = _load_data(p_path, lw, lh, lflags, image); if (err) return err; VS::get_singleton()->texture_allocate(texture, image->get_width(), image->get_height(), 0, image->get_format(), VS::TEXTURE_TYPE_2D, lflags); VS::get_singleton()->texture_set_data(texture, image); w = lw; h = lh; flags = lflags; path_to_file = p_path; format = image->get_format(); _change_notify(); return OK; } String StreamTexture::get_load_path() const { return path_to_file; } int StreamTexture::get_width() const { return w; } int StreamTexture::get_height() const { return h; } RID StreamTexture::get_rid() const { return texture; } void StreamTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, Rect2(p_pos, Size2(w, h)), texture, false, p_modulate, p_transpose, normal_rid); } void StreamTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect(p_canvas_item, p_rect, texture, p_tile, p_modulate, p_transpose, normal_rid); } void StreamTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map, bool p_clip_uv) const { if ((w | h) == 0) return; RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, p_rect, texture, p_src_rect, p_modulate, p_transpose, normal_rid, p_clip_uv); } bool StreamTexture::has_alpha() const { return false; } Ref<Image> StreamTexture::get_data() const { return VS::get_singleton()->texture_get_data(texture); } bool StreamTexture::is_pixel_opaque(int p_x, int p_y) const { if (!alpha_cache.is_valid()) { Ref<Image> img = get_data(); if (img.is_valid()) { if (img->is_compressed()) { //must decompress, if compressed Ref<Image> decom = img->duplicate(); decom->decompress(); img = decom; } alpha_cache.instance(); alpha_cache->create_from_image_alpha(img); } } if (alpha_cache.is_valid()) { int aw = int(alpha_cache->get_size().width); int ah = int(alpha_cache->get_size().height); if (aw == 0 || ah == 0) { return true; } int x = p_x * aw / w; int y = p_y * ah / h; x = CLAMP(x, 0, aw); y = CLAMP(y, 0, ah); return alpha_cache->get_bit(Point2(x, y)); } return true; } void StreamTexture::set_flags(uint32_t p_flags) { flags = p_flags; VS::get_singleton()->texture_set_flags(texture, flags); _change_notify("flags"); } void StreamTexture::reload_from_file() { String path = get_path(); if (!path.is_resource_file()) return; path = ResourceLoader::path_remap(path); //remap for translation path = ResourceLoader::import_remap(path); //remap for import if (!path.is_resource_file()) return; load(path); } void StreamTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("load", "path"), &StreamTexture::load); ClassDB::bind_method(D_METHOD("get_load_path"), &StreamTexture::get_load_path); ADD_PROPERTY(PropertyInfo(Variant::STRING, "load_path", PROPERTY_HINT_FILE, "*.stex"), "load", "get_load_path"); } StreamTexture::StreamTexture() { format = Image::FORMAT_MAX; flags = 0; w = 0; h = 0; texture = VS::get_singleton()->texture_create(); } StreamTexture::~StreamTexture() { VS::get_singleton()->free(texture); } RES ResourceFormatLoaderStreamTexture::load(const String &p_path, const String &p_original_path, Error *r_error) { Ref<StreamTexture> st; st.instance(); Error err = st->load(p_path); if (r_error) *r_error = err; if (err != OK) return RES(); return st; } void ResourceFormatLoaderStreamTexture::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("stex"); } bool ResourceFormatLoaderStreamTexture::handles_type(const String &p_type) const { return p_type == "StreamTexture"; } String ResourceFormatLoaderStreamTexture::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower() == "stex") return "StreamTexture"; return ""; } ////////////////////////////////////////// int AtlasTexture::get_width() const { if (region.size.width == 0) { if (atlas.is_valid()) return atlas->get_width(); return 1; } else { return region.size.width + margin.size.width; } } int AtlasTexture::get_height() const { if (region.size.height == 0) { if (atlas.is_valid()) return atlas->get_height(); return 1; } else { return region.size.height + margin.size.height; } } RID AtlasTexture::get_rid() const { if (atlas.is_valid()) return atlas->get_rid(); return RID(); } bool AtlasTexture::has_alpha() const { if (atlas.is_valid()) return atlas->has_alpha(); return false; } void AtlasTexture::set_flags(uint32_t p_flags) { if (atlas.is_valid()) atlas->set_flags(p_flags); } uint32_t AtlasTexture::get_flags() const { if (atlas.is_valid()) return atlas->get_flags(); return 0; } void AtlasTexture::set_atlas(const Ref<Texture> &p_atlas) { ERR_FAIL_COND(p_atlas == this); if (atlas == p_atlas) return; atlas = p_atlas; emit_changed(); _change_notify("atlas"); } Ref<Texture> AtlasTexture::get_atlas() const { return atlas; } void AtlasTexture::set_region(const Rect2 &p_region) { if (region == p_region) return; region = p_region; emit_changed(); _change_notify("region"); } Rect2 AtlasTexture::get_region() const { return region; } void AtlasTexture::set_margin(const Rect2 &p_margin) { if (margin == p_margin) return; margin = p_margin; emit_changed(); _change_notify("margin"); } Rect2 AtlasTexture::get_margin() const { return margin; } void AtlasTexture::set_filter_clip(const bool p_enable) { filter_clip = p_enable; emit_changed(); _change_notify("filter_clip"); } bool AtlasTexture::has_filter_clip() const { return filter_clip; } void AtlasTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_atlas", "atlas"), &AtlasTexture::set_atlas); ClassDB::bind_method(D_METHOD("get_atlas"), &AtlasTexture::get_atlas); ClassDB::bind_method(D_METHOD("set_region", "region"), &AtlasTexture::set_region); ClassDB::bind_method(D_METHOD("get_region"), &AtlasTexture::get_region); ClassDB::bind_method(D_METHOD("set_margin", "margin"), &AtlasTexture::set_margin); ClassDB::bind_method(D_METHOD("get_margin"), &AtlasTexture::get_margin); ClassDB::bind_method(D_METHOD("set_filter_clip", "enable"), &AtlasTexture::set_filter_clip); ClassDB::bind_method(D_METHOD("has_filter_clip"), &AtlasTexture::has_filter_clip); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "atlas", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_atlas", "get_atlas"); ADD_PROPERTY(PropertyInfo(Variant::RECT2, "region"), "set_region", "get_region"); ADD_PROPERTY(PropertyInfo(Variant::RECT2, "margin"), "set_margin", "get_margin"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "filter_clip"), "set_filter_clip", "has_filter_clip"); } void AtlasTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if (!atlas.is_valid()) return; Rect2 rc = region; if (rc.size.width == 0) { rc.size.width = atlas->get_width(); } if (rc.size.height == 0) { rc.size.height = atlas->get_height(); } RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(p_pos + margin.position, rc.size), atlas->get_rid(), rc, p_modulate, p_transpose, normal_rid, filter_clip); } void AtlasTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { if (!atlas.is_valid()) return; Rect2 rc = region; if (rc.size.width == 0) { rc.size.width = atlas->get_width(); } if (rc.size.height == 0) { rc.size.height = atlas->get_height(); } Vector2 scale = p_rect.size / (region.size + margin.size); Rect2 dr(p_rect.position + margin.position * scale, rc.size * scale); RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), rc, p_modulate, p_transpose, normal_rid, filter_clip); } void AtlasTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map, bool p_clip_uv) const { //this might not necessarily work well if using a rect, needs to be fixed properly if (!atlas.is_valid()) return; Rect2 dr; Rect2 src_c; get_rect_region(p_rect, p_src_rect, dr, src_c); RID normal_rid = p_normal_map.is_valid() ? p_normal_map->get_rid() : RID(); VS::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, dr, atlas->get_rid(), src_c, p_modulate, p_transpose, normal_rid, filter_clip); } bool AtlasTexture::get_rect_region(const Rect2 &p_rect, const Rect2 &p_src_rect, Rect2 &r_rect, Rect2 &r_src_rect) const { if (!atlas.is_valid()) return false; Rect2 rc = region; Rect2 src = p_src_rect; if (src.size == Size2()) { src.size = rc.size; } Vector2 scale = p_rect.size / src.size; src.position += (rc.position - margin.position); Rect2 src_c = rc.clip(src); if (src_c.size == Size2()) return false; Vector2 ofs = (src_c.position - src.position); if (scale.x < 0) { float mx = (margin.size.width - margin.position.x); mx -= margin.position.x; ofs.x = -(ofs.x + mx); } if (scale.y < 0) { float my = margin.size.height - margin.position.y; my -= margin.position.y; ofs.y = -(ofs.y + my); } Rect2 dr(p_rect.position + ofs * scale, src_c.size * scale); r_rect = dr; r_src_rect = src_c; return true; } bool AtlasTexture::is_pixel_opaque(int p_x, int p_y) const { if (!atlas.is_valid()) return true; int x = p_x + region.position.x - margin.position.x; int y = p_y + region.position.y - margin.position.y; // margin edge may outside of atlas if (x < 0 || x >= atlas->get_width()) return false; if (y < 0 || y >= atlas->get_height()) return false; return atlas->is_pixel_opaque(x, y); } AtlasTexture::AtlasTexture() { filter_clip = false; } ////////////////////////////////////////// int LargeTexture::get_width() const { return size.width; } int LargeTexture::get_height() const { return size.height; } RID LargeTexture::get_rid() const { return RID(); } bool LargeTexture::has_alpha() const { for (int i = 0; i < pieces.size(); i++) { if (pieces[i].texture->has_alpha()) return true; } return false; } void LargeTexture::set_flags(uint32_t p_flags) { for (int i = 0; i < pieces.size(); i++) { pieces.write[i].texture->set_flags(p_flags); } } uint32_t LargeTexture::get_flags() const { if (pieces.size()) return pieces[0].texture->get_flags(); return 0; } int LargeTexture::add_piece(const Point2 &p_offset, const Ref<Texture> &p_texture) { ERR_FAIL_COND_V(p_texture.is_null(), -1); Piece p; p.offset = p_offset; p.texture = p_texture; pieces.push_back(p); return pieces.size() - 1; } void LargeTexture::set_piece_offset(int p_idx, const Point2 &p_offset) { ERR_FAIL_INDEX(p_idx, pieces.size()); pieces.write[p_idx].offset = p_offset; }; void LargeTexture::set_piece_texture(int p_idx, const Ref<Texture> &p_texture) { ERR_FAIL_COND(p_texture == this); ERR_FAIL_INDEX(p_idx, pieces.size()); pieces.write[p_idx].texture = p_texture; }; void LargeTexture::set_size(const Size2 &p_size) { size = p_size; } void LargeTexture::clear() { pieces.clear(); size = Size2i(); } Array LargeTexture::_get_data() const { Array arr; for (int i = 0; i < pieces.size(); i++) { arr.push_back(pieces[i].offset); arr.push_back(pieces[i].texture); } arr.push_back(Size2(size)); return arr; } void LargeTexture::_set_data(const Array &p_array) { ERR_FAIL_COND(p_array.size() < 1); ERR_FAIL_COND(!(p_array.size() & 1)); clear(); for (int i = 0; i < p_array.size() - 1; i += 2) { add_piece(p_array[i], p_array[i + 1]); } size = Size2(p_array[p_array.size() - 1]); } int LargeTexture::get_piece_count() const { return pieces.size(); } Vector2 LargeTexture::get_piece_offset(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, pieces.size(), Vector2()); return pieces[p_idx].offset; } Ref<Texture> LargeTexture::get_piece_texture(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, pieces.size(), Ref<Texture>()); return pieces[p_idx].texture; } Ref<Image> LargeTexture::to_image() const { Ref<Image> img = memnew(Image(this->get_width(), this->get_height(), false, Image::FORMAT_RGBA8)); for (int i = 0; i < pieces.size(); i++) { Ref<Image> src_img = pieces[i].texture->get_data(); img->blit_rect(src_img, Rect2(0, 0, src_img->get_width(), src_img->get_height()), pieces[i].offset); } return img; } void LargeTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("add_piece", "ofs", "texture"), &LargeTexture::add_piece); ClassDB::bind_method(D_METHOD("set_piece_offset", "idx", "ofs"), &LargeTexture::set_piece_offset); ClassDB::bind_method(D_METHOD("set_piece_texture", "idx", "texture"), &LargeTexture::set_piece_texture); ClassDB::bind_method(D_METHOD("set_size", "size"), &LargeTexture::set_size); ClassDB::bind_method(D_METHOD("clear"), &LargeTexture::clear); ClassDB::bind_method(D_METHOD("get_piece_count"), &LargeTexture::get_piece_count); ClassDB::bind_method(D_METHOD("get_piece_offset", "idx"), &LargeTexture::get_piece_offset); ClassDB::bind_method(D_METHOD("get_piece_texture", "idx"), &LargeTexture::get_piece_texture); ClassDB::bind_method(D_METHOD("_set_data", "data"), &LargeTexture::_set_data); ClassDB::bind_method(D_METHOD("_get_data"), &LargeTexture::_get_data); ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "_data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_data", "_get_data"); } void LargeTexture::draw(RID p_canvas_item, const Point2 &p_pos, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { for (int i = 0; i < pieces.size(); i++) { // TODO pieces[i].texture->draw(p_canvas_item, pieces[i].offset + p_pos, p_modulate, p_transpose, p_normal_map); } } void LargeTexture::draw_rect(RID p_canvas_item, const Rect2 &p_rect, bool p_tile, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map) const { //tiling not supported for this if (size.x == 0 || size.y == 0) return; Size2 scale = p_rect.size / size; for (int i = 0; i < pieces.size(); i++) { // TODO pieces[i].texture->draw_rect(p_canvas_item, Rect2(pieces[i].offset * scale + p_rect.position, pieces[i].texture->get_size() * scale), false, p_modulate, p_transpose, p_normal_map); } } void LargeTexture::draw_rect_region(RID p_canvas_item, const Rect2 &p_rect, const Rect2 &p_src_rect, const Color &p_modulate, bool p_transpose, const Ref<Texture> &p_normal_map, bool p_clip_uv) const { //tiling not supported for this if (p_src_rect.size.x == 0 || p_src_rect.size.y == 0) return; Size2 scale = p_rect.size / p_src_rect.size; for (int i = 0; i < pieces.size(); i++) { // TODO Rect2 rect(pieces[i].offset, pieces[i].texture->get_size()); if (!p_src_rect.intersects(rect)) continue; Rect2 local = p_src_rect.clip(rect); Rect2 target = local; target.size *= scale; target.position = p_rect.position + (p_src_rect.position + rect.position) * scale; local.position -= rect.position; pieces[i].texture->draw_rect_region(p_canvas_item, target, local, p_modulate, p_transpose, p_normal_map, false); } } bool LargeTexture::is_pixel_opaque(int p_x, int p_y) const { for (int i = 0; i < pieces.size(); i++) { // TODO if (!pieces[i].texture.is_valid()) continue; Rect2 rect(pieces[i].offset, pieces[i].texture->get_size()); if (rect.has_point(Point2(p_x, p_y))) { return pieces[i].texture->is_pixel_opaque(p_x - rect.position.x, p_y - rect.position.y); } } return true; } LargeTexture::LargeTexture() { } /////////////////////////////////////////////// void CubeMap::set_flags(uint32_t p_flags) { flags = p_flags; if (_is_valid()) VS::get_singleton()->texture_set_flags(cubemap, flags); } uint32_t CubeMap::get_flags() const { return flags; } void CubeMap::set_side(Side p_side, const Ref<Image> &p_image) { ERR_FAIL_COND(p_image->empty()); ERR_FAIL_INDEX(p_side, 6); if (!_is_valid()) { format = p_image->get_format(); w = p_image->get_width(); h = p_image->get_height(); VS::get_singleton()->texture_allocate(cubemap, w, h, 0, p_image->get_format(), VS::TEXTURE_TYPE_CUBEMAP, flags); } VS::get_singleton()->texture_set_data(cubemap, p_image, VS::CubeMapSide(p_side)); valid[p_side] = true; } Ref<Image> CubeMap::get_side(Side p_side) const { if (!valid[p_side]) return Ref<Image>(); return VS::get_singleton()->texture_get_data(cubemap, VS::CubeMapSide(p_side)); } Image::Format CubeMap::get_format() const { return format; } int CubeMap::get_width() const { return w; } int CubeMap::get_height() const { return h; } RID CubeMap::get_rid() const { return cubemap; } void CubeMap::set_storage(Storage p_storage) { storage = p_storage; } CubeMap::Storage CubeMap::get_storage() const { return storage; } void CubeMap::set_lossy_storage_quality(float p_lossy_storage_quality) { lossy_storage_quality = p_lossy_storage_quality; } float CubeMap::get_lossy_storage_quality() const { return lossy_storage_quality; } void CubeMap::set_path(const String &p_path, bool p_take_over) { if (cubemap.is_valid()) { VisualServer::get_singleton()->texture_set_path(cubemap, p_path); } Resource::set_path(p_path, p_take_over); } bool CubeMap::_set(const StringName &p_name, const Variant &p_value) { if (p_name == "side/left") { set_side(SIDE_LEFT, p_value); } else if (p_name == "side/right") { set_side(SIDE_RIGHT, p_value); } else if (p_name == "side/bottom") { set_side(SIDE_BOTTOM, p_value); } else if (p_name == "side/top") { set_side(SIDE_TOP, p_value); } else if (p_name == "side/front") { set_side(SIDE_FRONT, p_value); } else if (p_name == "side/back") { set_side(SIDE_BACK, p_value); } else if (p_name == "storage") { storage = Storage(p_value.operator int()); } else if (p_name == "lossy_quality") { lossy_storage_quality = p_value; } else return false; return true; } bool CubeMap::_get(const StringName &p_name, Variant &r_ret) const { if (p_name == "side/left") { r_ret = get_side(SIDE_LEFT); } else if (p_name == "side/right") { r_ret = get_side(SIDE_RIGHT); } else if (p_name == "side/bottom") { r_ret = get_side(SIDE_BOTTOM); } else if (p_name == "side/top") { r_ret = get_side(SIDE_TOP); } else if (p_name == "side/front") { r_ret = get_side(SIDE_FRONT); } else if (p_name == "side/back") { r_ret = get_side(SIDE_BACK); } else if (p_name == "storage") { r_ret = storage; } else if (p_name == "lossy_quality") { r_ret = lossy_storage_quality; } else return false; return true; } void CubeMap::_get_property_list(List<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(Variant::OBJECT, "side/left", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::OBJECT, "side/right", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::OBJECT, "side/bottom", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::OBJECT, "side/top", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::OBJECT, "side/front", PROPERTY_HINT_RESOURCE_TYPE, "Image")); p_list->push_back(PropertyInfo(Variant::OBJECT, "side/back", PROPERTY_HINT_RESOURCE_TYPE, "Image")); } void CubeMap::_bind_methods() { ClassDB::bind_method(D_METHOD("get_width"), &CubeMap::get_width); ClassDB::bind_method(D_METHOD("get_height"), &CubeMap::get_height); ClassDB::bind_method(D_METHOD("set_flags", "flags"), &CubeMap::set_flags); ClassDB::bind_method(D_METHOD("get_flags"), &CubeMap::get_flags); ClassDB::bind_method(D_METHOD("set_side", "side", "image"), &CubeMap::set_side); ClassDB::bind_method(D_METHOD("get_side", "side"), &CubeMap::get_side); ClassDB::bind_method(D_METHOD("set_storage", "mode"), &CubeMap::set_storage); ClassDB::bind_method(D_METHOD("get_storage"), &CubeMap::get_storage); ClassDB::bind_method(D_METHOD("set_lossy_storage_quality", "quality"), &CubeMap::set_lossy_storage_quality); ClassDB::bind_method(D_METHOD("get_lossy_storage_quality"), &CubeMap::get_lossy_storage_quality); ADD_PROPERTY(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter"), "set_flags", "get_flags"); ADD_PROPERTY(PropertyInfo(Variant::INT, "storage_mode", PROPERTY_HINT_ENUM, "Raw,Lossy Compressed,Lossless Compressed"), "set_storage", "get_storage"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "lossy_storage_quality"), "set_lossy_storage_quality", "get_lossy_storage_quality"); BIND_ENUM_CONSTANT(STORAGE_RAW); BIND_ENUM_CONSTANT(STORAGE_COMPRESS_LOSSY); BIND_ENUM_CONSTANT(STORAGE_COMPRESS_LOSSLESS); BIND_ENUM_CONSTANT(SIDE_LEFT); BIND_ENUM_CONSTANT(SIDE_RIGHT); BIND_ENUM_CONSTANT(SIDE_BOTTOM); BIND_ENUM_CONSTANT(SIDE_TOP); BIND_ENUM_CONSTANT(SIDE_FRONT); BIND_ENUM_CONSTANT(SIDE_BACK); BIND_ENUM_CONSTANT(FLAG_MIPMAPS); BIND_ENUM_CONSTANT(FLAG_REPEAT); BIND_ENUM_CONSTANT(FLAG_FILTER); BIND_ENUM_CONSTANT(FLAGS_DEFAULT); } CubeMap::CubeMap() { w = h = 0; flags = FLAGS_DEFAULT; for (int i = 0; i < 6; i++) valid[i] = false; cubemap = VisualServer::get_singleton()->texture_create(); storage = STORAGE_RAW; lossy_storage_quality = 0.7; } CubeMap::~CubeMap() { VisualServer::get_singleton()->free(cubemap); } /* BIND_ENUM(CubeMapSize); BIND_ENUM_CONSTANT( FLAG_CUBEMAP ); BIND_ENUM_CONSTANT( CUBEMAP_LEFT ); BIND_ENUM_CONSTANT( CUBEMAP_RIGHT ); BIND_ENUM_CONSTANT( CUBEMAP_BOTTOM ); BIND_ENUM_CONSTANT( CUBEMAP_TOP ); BIND_ENUM_CONSTANT( CUBEMAP_FRONT ); BIND_ENUM_CONSTANT( CUBEMAP_BACK ); */ /////////////////////////// void CurveTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_width", "width"), &CurveTexture::set_width); ClassDB::bind_method(D_METHOD("set_curve", "curve"), &CurveTexture::set_curve); ClassDB::bind_method(D_METHOD("get_curve"), &CurveTexture::get_curve); ClassDB::bind_method(D_METHOD("_update"), &CurveTexture::_update); ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "32,4096"), "set_width", "get_width"); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "curve", PROPERTY_HINT_RESOURCE_TYPE, "Curve"), "set_curve", "get_curve"); } void CurveTexture::set_width(int p_width) { ERR_FAIL_COND(p_width < 32 || p_width > 4096); _width = p_width; _update(); } int CurveTexture::get_width() const { return _width; } void CurveTexture::ensure_default_setup(float p_min, float p_max) { if (_curve.is_null()) { Ref<Curve> curve = Ref<Curve>(memnew(Curve)); curve->add_point(Vector2(0, 1)); curve->add_point(Vector2(1, 1)); curve->set_min_value(p_min); curve->set_max_value(p_max); set_curve(curve); // Min and max is 0..1 by default } } void CurveTexture::set_curve(Ref<Curve> p_curve) { if (_curve != p_curve) { if (_curve.is_valid()) { _curve->disconnect(CoreStringNames::get_singleton()->changed, this, "_update"); } _curve = p_curve; if (_curve.is_valid()) { _curve->connect(CoreStringNames::get_singleton()->changed, this, "_update"); } _update(); } } void CurveTexture::_update() { PoolVector<uint8_t> data; data.resize(_width * sizeof(float)); // The array is locked in that scope { PoolVector<uint8_t>::Write wd8 = data.write(); float *wd = (float *)wd8.ptr(); if (_curve.is_valid()) { Curve &curve = **_curve; for (int i = 0; i < _width; ++i) { float t = i / static_cast<float>(_width); wd[i] = curve.interpolate_baked(t); } } else { for (int i = 0; i < _width; ++i) { wd[i] = 0; } } } Ref<Image> image = memnew(Image(_width, 1, false, Image::FORMAT_RF, data)); VS::get_singleton()->texture_allocate(_texture, _width, 1, 0, Image::FORMAT_RF, VS::TEXTURE_TYPE_2D, VS::TEXTURE_FLAG_FILTER); VS::get_singleton()->texture_set_data(_texture, image); emit_changed(); } Ref<Curve> CurveTexture::get_curve() const { return _curve; } RID CurveTexture::get_rid() const { return _texture; } CurveTexture::CurveTexture() { _width = 2048; _texture = VS::get_singleton()->texture_create(); } CurveTexture::~CurveTexture() { VS::get_singleton()->free(_texture); } ////////////////// //setter and getter names for property serialization #define COLOR_RAMP_GET_OFFSETS "get_offsets" #define COLOR_RAMP_GET_COLORS "get_colors" #define COLOR_RAMP_SET_OFFSETS "set_offsets" #define COLOR_RAMP_SET_COLORS "set_colors" GradientTexture::GradientTexture() { update_pending = false; width = 2048; texture = VS::get_singleton()->texture_create(); _queue_update(); } GradientTexture::~GradientTexture() { VS::get_singleton()->free(texture); } void GradientTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_gradient", "gradient"), &GradientTexture::set_gradient); ClassDB::bind_method(D_METHOD("get_gradient"), &GradientTexture::get_gradient); ClassDB::bind_method(D_METHOD("set_width", "width"), &GradientTexture::set_width); ClassDB::bind_method(D_METHOD("_update"), &GradientTexture::_update); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "gradient", PROPERTY_HINT_RESOURCE_TYPE, "Gradient"), "set_gradient", "get_gradient"); ADD_PROPERTY(PropertyInfo(Variant::INT, "width", PROPERTY_HINT_RANGE, "1,2048,1,or_greater"), "set_width", "get_width"); } void GradientTexture::set_gradient(Ref<Gradient> p_gradient) { if (p_gradient == gradient) return; if (gradient.is_valid()) { gradient->disconnect(CoreStringNames::get_singleton()->changed, this, "_update"); } gradient = p_gradient; if (gradient.is_valid()) { gradient->connect(CoreStringNames::get_singleton()->changed, this, "_update"); } _update(); emit_changed(); } Ref<Gradient> GradientTexture::get_gradient() const { return gradient; } void GradientTexture::_queue_update() { if (update_pending) return; update_pending = true; call_deferred("_update"); } void GradientTexture::_update() { update_pending = false; if (gradient.is_null()) return; PoolVector<uint8_t> data; data.resize(width * 4); { PoolVector<uint8_t>::Write wd8 = data.write(); Gradient &g = **gradient; for (int i = 0; i < width; i++) { float ofs = float(i) / (width - 1); Color color = g.get_color_at_offset(ofs); wd8[i * 4 + 0] = uint8_t(CLAMP(color.r * 255.0, 0, 255)); wd8[i * 4 + 1] = uint8_t(CLAMP(color.g * 255.0, 0, 255)); wd8[i * 4 + 2] = uint8_t(CLAMP(color.b * 255.0, 0, 255)); wd8[i * 4 + 3] = uint8_t(CLAMP(color.a * 255.0, 0, 255)); } } Ref<Image> image = memnew(Image(width, 1, false, Image::FORMAT_RGBA8, data)); VS::get_singleton()->texture_allocate(texture, width, 1, 0, Image::FORMAT_RGBA8, VS::TEXTURE_TYPE_2D, VS::TEXTURE_FLAG_FILTER); VS::get_singleton()->texture_set_data(texture, image); emit_changed(); } void GradientTexture::set_width(int p_width) { width = p_width; _queue_update(); } int GradientTexture::get_width() const { return width; } Ref<Image> GradientTexture::get_data() const { return VisualServer::get_singleton()->texture_get_data(texture); } ////////////////////////////////////// void ProxyTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_base", "base"), &ProxyTexture::set_base); ClassDB::bind_method(D_METHOD("get_base"), &ProxyTexture::get_base); ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "base", PROPERTY_HINT_RESOURCE_TYPE, "Texture"), "set_base", "get_base"); } void ProxyTexture::set_base(const Ref<Texture> &p_texture) { ERR_FAIL_COND(p_texture == this); base = p_texture; if (base.is_valid()) { VS::get_singleton()->texture_set_proxy(proxy, base->get_rid()); } else { VS::get_singleton()->texture_set_proxy(proxy, RID()); } } Ref<Texture> ProxyTexture::get_base() const { return base; } int ProxyTexture::get_width() const { if (base.is_valid()) return base->get_width(); return 1; } int ProxyTexture::get_height() const { if (base.is_valid()) return base->get_height(); return 1; } RID ProxyTexture::get_rid() const { return proxy; } bool ProxyTexture::has_alpha() const { if (base.is_valid()) return base->has_alpha(); return false; } void ProxyTexture::set_flags(uint32_t p_flags) { } uint32_t ProxyTexture::get_flags() const { if (base.is_valid()) return base->get_flags(); return 0; } ProxyTexture::ProxyTexture() { proxy = VS::get_singleton()->texture_create(); } ProxyTexture::~ProxyTexture() { VS::get_singleton()->free(proxy); } ////////////////////////////////////////////// void AnimatedTexture::_update_proxy() { RWLockRead r(rw_lock); float delta; if (prev_ticks == 0) { delta = 0; prev_ticks = OS::get_singleton()->get_ticks_usec(); } else { uint64_t ticks = OS::get_singleton()->get_ticks_usec(); delta = float(double(ticks - prev_ticks) / 1000000.0); prev_ticks = ticks; } time += delta; float limit; if (fps == 0) { limit = 0; } else { limit = 1.0 / fps; } int iter_max = frame_count; while (iter_max) { float frame_limit = limit + frames[current_frame].delay_sec; if (time > frame_limit) { current_frame++; if (current_frame >= frame_count) { current_frame = 0; } time -= frame_limit; } else { break; } iter_max--; } if (frames[current_frame].texture.is_valid()) { VisualServer::get_singleton()->texture_set_proxy(proxy, frames[current_frame].texture->get_rid()); } } void AnimatedTexture::set_frames(int p_frames) { ERR_FAIL_COND(p_frames < 1 || p_frames > MAX_FRAMES); RWLockWrite r(rw_lock); frame_count = p_frames; } int AnimatedTexture::get_frames() const { return frame_count; } void AnimatedTexture::set_frame_texture(int p_frame, const Ref<Texture> &p_texture) { ERR_FAIL_COND(p_texture == this); ERR_FAIL_INDEX(p_frame, MAX_FRAMES); RWLockWrite w(rw_lock); frames[p_frame].texture = p_texture; } Ref<Texture> AnimatedTexture::get_frame_texture(int p_frame) const { ERR_FAIL_INDEX_V(p_frame, MAX_FRAMES, Ref<Texture>()); RWLockRead r(rw_lock); return frames[p_frame].texture; } void AnimatedTexture::set_frame_delay(int p_frame, float p_delay_sec) { ERR_FAIL_INDEX(p_frame, MAX_FRAMES); RWLockRead r(rw_lock); frames[p_frame].delay_sec = p_delay_sec; } float AnimatedTexture::get_frame_delay(int p_frame) const { ERR_FAIL_INDEX_V(p_frame, MAX_FRAMES, 0); RWLockRead r(rw_lock); return frames[p_frame].delay_sec; } void AnimatedTexture::set_fps(float p_fps) { ERR_FAIL_COND(p_fps < 0 || p_fps >= 1000); fps = p_fps; } float AnimatedTexture::get_fps() const { return fps; } int AnimatedTexture::get_width() const { RWLockRead r(rw_lock); if (!frames[current_frame].texture.is_valid()) { return 1; } return frames[current_frame].texture->get_width(); } int AnimatedTexture::get_height() const { RWLockRead r(rw_lock); if (!frames[current_frame].texture.is_valid()) { return 1; } return frames[current_frame].texture->get_height(); } RID AnimatedTexture::get_rid() const { return proxy; } bool AnimatedTexture::has_alpha() const { RWLockRead r(rw_lock); if (!frames[current_frame].texture.is_valid()) { return false; } return frames[current_frame].texture->has_alpha(); } Ref<Image> AnimatedTexture::get_data() const { RWLockRead r(rw_lock); if (!frames[current_frame].texture.is_valid()) { return Ref<Image>(); } return frames[current_frame].texture->get_data(); } bool AnimatedTexture::is_pixel_opaque(int p_x, int p_y) const { RWLockRead r(rw_lock); if (frames[current_frame].texture.is_valid()) { return frames[current_frame].texture->is_pixel_opaque(p_x, p_y); } return true; } void AnimatedTexture::set_flags(uint32_t p_flags) { } uint32_t AnimatedTexture::get_flags() const { RWLockRead r(rw_lock); if (!frames[current_frame].texture.is_valid()) { return 0; } return frames[current_frame].texture->get_flags(); } void AnimatedTexture::_validate_property(PropertyInfo &property) const { String prop = property.name; if (prop.begins_with("frame_")) { int frame = prop.get_slicec('/', 0).get_slicec('_', 1).to_int(); if (frame >= frame_count) { property.usage = 0; } } } void AnimatedTexture::_bind_methods() { ClassDB::bind_method(D_METHOD("set_frames", "frames"), &AnimatedTexture::set_frames); ClassDB::bind_method(D_METHOD("get_frames"), &AnimatedTexture::get_frames); ClassDB::bind_method(D_METHOD("set_fps", "fps"), &AnimatedTexture::set_fps); ClassDB::bind_method(D_METHOD("get_fps"), &AnimatedTexture::get_fps); ClassDB::bind_method(D_METHOD("set_frame_texture", "frame", "texture"), &AnimatedTexture::set_frame_texture); ClassDB::bind_method(D_METHOD("get_frame_texture", "frame"), &AnimatedTexture::get_frame_texture); ClassDB::bind_method(D_METHOD("set_frame_delay", "frame", "delay"), &AnimatedTexture::set_frame_delay); ClassDB::bind_method(D_METHOD("get_frame_delay", "frame"), &AnimatedTexture::get_frame_delay); ClassDB::bind_method(D_METHOD("_update_proxy"), &AnimatedTexture::_update_proxy); ADD_PROPERTY(PropertyInfo(Variant::INT, "frames", PROPERTY_HINT_RANGE, "1," + itos(MAX_FRAMES), PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_UPDATE_ALL_IF_MODIFIED), "set_frames", "get_frames"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "fps", PROPERTY_HINT_RANGE, "0,1024,0.1"), "set_fps", "get_fps"); for (int i = 0; i < MAX_FRAMES; i++) { ADD_PROPERTYI(PropertyInfo(Variant::OBJECT, "frame_" + itos(i) + "/texture", PROPERTY_HINT_RESOURCE_TYPE, "Texture", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "set_frame_texture", "get_frame_texture", i); ADD_PROPERTYI(PropertyInfo(Variant::REAL, "frame_" + itos(i) + "/delay_sec", PROPERTY_HINT_RANGE, "0.0,16.0,0.01", PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_INTERNAL), "set_frame_delay", "get_frame_delay", i); } BIND_CONSTANT(MAX_FRAMES); } AnimatedTexture::AnimatedTexture() { proxy = VS::get_singleton()->texture_create(); VisualServer::get_singleton()->texture_set_force_redraw_if_visible(proxy, true); time = 0; frame_count = 1; fps = 4; prev_ticks = 0; current_frame = 0; VisualServer::get_singleton()->connect("frame_pre_draw", this, "_update_proxy"); #ifndef NO_THREADS rw_lock = RWLock::create(); #else rw_lock = NULL; #endif } AnimatedTexture::~AnimatedTexture() { VS::get_singleton()->free(proxy); if (rw_lock) { memdelete(rw_lock); } } /////////////////////////////// void TextureLayered::set_flags(uint32_t p_flags) { flags = p_flags; if (texture.is_valid()) { VS::get_singleton()->texture_set_flags(texture, flags); } } uint32_t TextureLayered::get_flags() const { return flags; } Image::Format TextureLayered::get_format() const { return format; } uint32_t TextureLayered::get_width() const { return width; } uint32_t TextureLayered::get_height() const { return height; } uint32_t TextureLayered::get_depth() const { return depth; } void TextureLayered::_set_data(const Dictionary &p_data) { ERR_FAIL_COND(!p_data.has("width")); ERR_FAIL_COND(!p_data.has("height")); ERR_FAIL_COND(!p_data.has("depth")); ERR_FAIL_COND(!p_data.has("format")); ERR_FAIL_COND(!p_data.has("flags")); ERR_FAIL_COND(!p_data.has("layers")); int w = p_data["width"]; int h = p_data["height"]; int d = p_data["depth"]; Image::Format format = Image::Format(int(p_data["format"])); int flags = p_data["flags"]; Array layers = p_data["layers"]; ERR_FAIL_COND(layers.size() != d); create(w, h, d, format, flags); for (int i = 0; i < layers.size(); i++) { Ref<Image> img = layers[i]; ERR_CONTINUE(!img.is_valid()); ERR_CONTINUE(img->get_format() != format); ERR_CONTINUE(img->get_width() != w); ERR_CONTINUE(img->get_height() != h); set_layer_data(img, i); } } Dictionary TextureLayered::_get_data() const { Dictionary d; d["width"] = width; d["height"] = height; d["depth"] = depth; d["flags"] = flags; d["format"] = format; Array layers; for (int i = 0; i < depth; i++) { layers.push_back(get_layer_data(i)); } d["layers"] = layers; return d; } void TextureLayered::create(uint32_t p_width, uint32_t p_height, uint32_t p_depth, Image::Format p_format, uint32_t p_flags) { VS::get_singleton()->texture_allocate(texture, p_width, p_height, p_depth, p_format, is_3d ? VS::TEXTURE_TYPE_3D : VS::TEXTURE_TYPE_2D_ARRAY, p_flags); width = p_width; height = p_height; depth = p_depth; format = p_format; flags = p_flags; } void TextureLayered::set_layer_data(const Ref<Image> &p_image, int p_layer) { ERR_FAIL_COND(!texture.is_valid()); VS::get_singleton()->texture_set_data(texture, p_image, p_layer); } Ref<Image> TextureLayered::get_layer_data(int p_layer) const { ERR_FAIL_COND_V(!texture.is_valid(), Ref<Image>()); return VS::get_singleton()->texture_get_data(texture, p_layer); } void TextureLayered::set_data_partial(const Ref<Image> &p_image, int p_x_ofs, int p_y_ofs, int p_z, int p_mipmap) { ERR_FAIL_COND(!texture.is_valid()); VS::get_singleton()->texture_set_data_partial(texture, p_image, 0, 0, p_image->get_width(), p_image->get_height(), p_x_ofs, p_y_ofs, p_mipmap, p_z); } RID TextureLayered::get_rid() const { return texture; } void TextureLayered::set_path(const String &p_path, bool p_take_over) { if (texture.is_valid()) { VS::get_singleton()->texture_set_path(texture, p_path); } Resource::set_path(p_path, p_take_over); } void TextureLayered::_bind_methods() { ClassDB::bind_method(D_METHOD("set_flags", "flags"), &TextureLayered::set_flags); ClassDB::bind_method(D_METHOD("get_flags"), &TextureLayered::get_flags); ClassDB::bind_method(D_METHOD("get_format"), &TextureLayered::get_format); ClassDB::bind_method(D_METHOD("get_width"), &TextureLayered::get_width); ClassDB::bind_method(D_METHOD("get_height"), &TextureLayered::get_height); ClassDB::bind_method(D_METHOD("get_depth"), &TextureLayered::get_depth); ClassDB::bind_method(D_METHOD("create", "width", "height", "depth", "format", "flags"), &TextureLayered::create, DEFVAL(FLAGS_DEFAULT)); ClassDB::bind_method(D_METHOD("set_layer_data", "image", "layer"), &TextureLayered::set_layer_data); ClassDB::bind_method(D_METHOD("get_layer_data", "layer"), &TextureLayered::get_layer_data); ClassDB::bind_method(D_METHOD("set_data_partial", "image", "x_offset", "y_offset", "layer", "mipmap"), &TextureLayered::set_data_partial, DEFVAL(0)); ClassDB::bind_method(D_METHOD("_set_data", "data"), &TextureLayered::_set_data); ClassDB::bind_method(D_METHOD("_get_data"), &TextureLayered::_get_data); ADD_PROPERTY(PropertyInfo(Variant::INT, "flags", PROPERTY_HINT_FLAGS, "Mipmaps,Repeat,Filter"), "set_flags", "get_flags"); ADD_PROPERTY(PropertyInfo(Variant::DICTIONARY, "data", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), "_set_data", "_get_data"); BIND_ENUM_CONSTANT(FLAG_MIPMAPS); BIND_ENUM_CONSTANT(FLAG_REPEAT); BIND_ENUM_CONSTANT(FLAG_FILTER); BIND_ENUM_CONSTANT(FLAGS_DEFAULT); } TextureLayered::TextureLayered(bool p_3d) { is_3d = p_3d; format = Image::FORMAT_MAX; flags = FLAGS_DEFAULT; width = 0; height = 0; depth = 0; texture = VS::get_singleton()->texture_create(); } TextureLayered::~TextureLayered() { if (texture.is_valid()) { VS::get_singleton()->free(texture); } } RES ResourceFormatLoaderTextureLayered::load(const String &p_path, const String &p_original_path, Error *r_error) { if (r_error) { *r_error = ERR_CANT_OPEN; } Ref<TextureLayered> lt; Ref<Texture3D> tex3d; Ref<TextureArray> texarr; if (p_path.ends_with("tex3d")) { tex3d.instance(); lt = tex3d; } else if (p_path.ends_with("texarr")) { texarr.instance(); lt = texarr; } else { ERR_EXPLAIN("Unrecognized layered texture extension"); ERR_FAIL_V(RES()); } FileAccess *f = FileAccess::open(p_path, FileAccess::READ); ERR_FAIL_COND_V(!f, RES()); uint8_t header[5] = { 0, 0, 0, 0, 0 }; f->get_buffer(header, 4); if (header[0] == 'G' && header[1] == 'D' && header[2] == '3' && header[3] == 'T') { if (tex3d.is_null()) { memdelete(f); ERR_FAIL_COND_V(tex3d.is_null(), RES()) } } else if (header[0] == 'G' && header[1] == 'D' && header[2] == 'A' && header[3] == 'T') { if (texarr.is_null()) { memdelete(f); ERR_FAIL_COND_V(texarr.is_null(), RES()) } } else { ERR_EXPLAIN("Unrecognized layered texture file format: " + String((const char *)header)); ERR_FAIL_V(RES()); } int tw = f->get_32(); int th = f->get_32(); int td = f->get_32(); int flags = f->get_32(); //texture flags! Image::Format format = Image::Format(f->get_32()); uint32_t compression = f->get_32(); // 0 - lossless (PNG), 1 - vram, 2 - uncompressed lt->create(tw, th, td, format, flags); for (int layer = 0; layer < td; layer++) { Ref<Image> image; image.instance(); if (compression == COMPRESSION_LOSSLESS) { //look for a PNG file inside int mipmaps = f->get_32(); Vector<Ref<Image> > mipmap_images; for (int i = 0; i < mipmaps; i++) { uint32_t size = f->get_32(); PoolVector<uint8_t> pv; pv.resize(size); { PoolVector<uint8_t>::Write w = pv.write(); f->get_buffer(w.ptr(), size); } Ref<Image> img = Image::lossless_unpacker(pv); if (img.is_null() || img->empty() || format != img->get_format()) { if (r_error) { *r_error = ERR_FILE_CORRUPT; } memdelete(f); ERR_FAIL_V(RES()); } mipmap_images.push_back(img); } if (mipmap_images.size() == 1) { image = mipmap_images[0]; } else { int total_size = Image::get_image_data_size(tw, th, format, true); PoolVector<uint8_t> img_data; img_data.resize(total_size); { PoolVector<uint8_t>::Write w = img_data.write(); int ofs = 0; for (int i = 0; i < mipmap_images.size(); i++) { PoolVector<uint8_t> id = mipmap_images[i]->get_data(); int len = id.size(); PoolVector<uint8_t>::Read r = id.read(); copymem(&w[ofs], r.ptr(), len); ofs += len; } } image->create(tw, th, true, format, img_data); if (image->empty()) { if (r_error) { *r_error = ERR_FILE_CORRUPT; } memdelete(f); ERR_FAIL_V(RES()); } } } else { //look for regular format bool mipmaps = (flags & Texture::FLAG_MIPMAPS); int total_size = Image::get_image_data_size(tw, th, format, mipmaps); PoolVector<uint8_t> img_data; img_data.resize(total_size); { PoolVector<uint8_t>::Write w = img_data.write(); int bytes = f->get_buffer(w.ptr(), total_size); if (bytes != total_size) { if (r_error) { *r_error = ERR_FILE_CORRUPT; memdelete(f); } ERR_FAIL_V(RES()); } } image->create(tw, th, mipmaps, format, img_data); } lt->set_layer_data(image, layer); } if (r_error) *r_error = OK; return lt; } void ResourceFormatLoaderTextureLayered::get_recognized_extensions(List<String> *p_extensions) const { p_extensions->push_back("tex3d"); p_extensions->push_back("texarr"); } bool ResourceFormatLoaderTextureLayered::handles_type(const String &p_type) const { return p_type == "Texture3D" || p_type == "TextureArray"; } String ResourceFormatLoaderTextureLayered::get_resource_type(const String &p_path) const { if (p_path.get_extension().to_lower() == "tex3d") return "Texture3D"; if (p_path.get_extension().to_lower() == "texarr") return "TextureArray"; return ""; }
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "AnimGraphPrivatePCH.h" #include "GraphEditorActions.h" #include "ScopedTransaction.h" #include "AnimGraphNode_BlendListByBool.h" ///////////////////////////////////////////////////// // UAnimGraphNode_BlendListByBool #define LOCTEXT_NAMESPACE "A3Nodes" UAnimGraphNode_BlendListByBool::UAnimGraphNode_BlendListByBool(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } FText UAnimGraphNode_BlendListByBool::GetNodeTitle(ENodeTitleType::Type TitleType) const { return LOCTEXT("UAnimGraphNode_BlendListByBool_Tooltip", "Blend Poses by bool"); } FText UAnimGraphNode_BlendListByBool::GetTooltipText() const { return LOCTEXT("UAnimGraphNode_BlendListByBool_Title", "Blend List (by bool)"); } void UAnimGraphNode_BlendListByBool::CustomizePinData(UEdGraphPin* Pin, FName SourcePropertyName, int32 ArrayIndex) const { FName BlendPoses(TEXT("BlendPose")); FName BlendTimes(TEXT("BlendTime")); if (ArrayIndex != INDEX_NONE) { // Note: This is intentionally flipped, as it looks better with true as the topmost element! FFormatNamedArguments Args; Args.Add(TEXT("TrueFalse"), (ArrayIndex == 0) ? LOCTEXT("True", "True") : LOCTEXT("False", "False")); if (SourcePropertyName == BlendPoses) { Pin->PinFriendlyName = FText::Format(LOCTEXT("BoolPoseFriendlyName", "{TrueFalse} Pose"), Args); } else if (SourcePropertyName == BlendTimes) { Pin->PinFriendlyName = FText::Format(LOCTEXT("BoolBlendTimeFriendlyName", "{TrueFalse} Blend Time"), Args); } } } #undef LOCTEXT_NAMESPACE
#include <iostream> #include <cstring> /* * ___ __ __ ____ _ ____ ___ ___ ____ * / _ \| \/ | _ \ / \ | _ \_ _/ _ \/ ___| * | | | | |\/| | |_) | / _ \ | | | | | | | \___ \ * | |_| | | | | __/ / ___ \| |_| | | |_| |___) | * \___/|_| |_|_| /_/ \_\____/___\___/|____/ * * * no-xml API but still core dump * * */ #include <iostream> #include <mpi.h> #include <omp.h> #include <adios.h> static const char* data_filename = "data/11.bp"; static const size_t line_size = 53; static const size_t nb_lines = 5; static int64_t adios_handle; static int64_t adios_group_id; static uint64_t data_id; int main (int argc, char** argv) { int64_t adios_handle; char hola [5][53]; MPI_Comm comm = MPI_COMM_WORLD; MPI_Init (&argc, &argv); omp_set_num_threads(5); strncpy (&hola[0][0], R"( _ _ _ _ _ _ _ )", 53); strncpy (&hola[1][0], R"((_) |__ ___ | | __ _ / \ __| (_) ___ ___| |)", 53); strncpy (&hola[2][0], R"(| | '_ \ / _ \| |/ _` | / _ \ / _` | |/ _ \/ __| |)", 53); strncpy (&hola[3][0], R"(| | | | | (_) | | (_| | / ___ \ (_| | | (_) \__ \_|)", 53); strncpy (&hola[4][0], R"(\_|_| |_|\___/|_|\__,_| /_/ \_\__,_|_|\___/|___(_))", 53); adios_init_noxml (comm); adios_declare_group (&adios_group_id,"report", "", adios_stat_no); adios_select_method (adios_group_id, "MPI", "verbose=3", ""); adios_define_var (adios_group_id, "line_size", "", adios_integer, 0,0,0); adios_define_var (adios_group_id, "nb_lines", "", adios_integer, 0,0,0); for (int i = 0; i < 5; i++) { adios_define_var (adios_group_id, "line_idx", "", adios_integer, 0,0,0); int var_id = adios_define_var (adios_group_id, "hola_data", "", adios_byte, "1,line_size", "nb_lines,line_size", "line_idx,0"); adios_set_transform (var_id, "none"); } adios_open (&adios_handle, "report", data_filename, "w", comm); adios_write (adios_handle, "line_size", &line_size); adios_write (adios_handle, "nb_lines", &nb_lines); #pragma omp parallel for for (int i = 0; i < 5; i++) { adios_write (adios_handle, "line_idx", &i); adios_write (adios_handle, "hola_data", &hola[i]); } adios_close (adios_handle); // write struct in ADIOS file // for (int i = 0; i < 5; i++) std::cout << hola[i] << std::endl; adios_finalize(0); MPI_Finalize(); return 0; }
// MusicXML Class Library // Copyright (c) by Matthew James Briggs // Distributed under the MIT License #include "../../core/elements/Tuplet.h" #include "../../core/FromXElement.h" #include "../../core/elements/TupletActual.h" #include "../../core/elements/TupletNormal.h" #include <iostream> namespace mx { namespace core { Tuplet::Tuplet() :myAttributes( std::make_shared<TupletAttributes>() ) ,myTupletActual( makeTupletActual() ) ,myHasTupletActual( false ) ,myTupletNormal( makeTupletNormal() ) ,myHasTupletNormal( false ) {} bool Tuplet::hasAttributes() const { return myAttributes->hasValues(); } std::ostream& Tuplet::streamAttributes( std::ostream& os ) const { return myAttributes->toStream( os ); } std::ostream& Tuplet::streamName( std::ostream& os ) const { os << "tuplet"; return os; } bool Tuplet::hasContents() const { return myHasTupletActual || myHasTupletNormal; } std::ostream& Tuplet::streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const { if ( myHasTupletActual ) { os << std::endl; myTupletActual->toStream( os, indentLevel+1 ); } if ( myHasTupletNormal ) { os << std::endl; myTupletNormal->toStream( os, indentLevel+1 ); } isOneLineOnly = ! hasContents(); if ( ! isOneLineOnly ) { os << std::endl; } return os; } TupletAttributesPtr Tuplet::getAttributes() const { return myAttributes; } void Tuplet::setAttributes( const TupletAttributesPtr& value ) { if ( value ) { myAttributes = value; } } TupletActualPtr Tuplet::getTupletActual() const { return myTupletActual; } void Tuplet::setTupletActual( const TupletActualPtr& value ) { if( value ) { myTupletActual = value; } } bool Tuplet::getHasTupletActual() const { return myHasTupletActual; } void Tuplet::setHasTupletActual( const bool value ) { myHasTupletActual = value; } TupletNormalPtr Tuplet::getTupletNormal() const { return myTupletNormal; } void Tuplet::setTupletNormal( const TupletNormalPtr& value ) { if( value ) { myTupletNormal = value; } } bool Tuplet::getHasTupletNormal() const { return myHasTupletNormal; } void Tuplet::setHasTupletNormal( const bool value ) { myHasTupletNormal = value; } bool Tuplet::fromXElement( std::ostream& message, xml::XElement& xelement ) { bool isSuccess = true; isSuccess &= myAttributes->fromXElement( message, xelement ); auto endIter = xelement.end(); for( auto it = xelement.begin(); it != endIter; ++it ) { if ( importElement( message, *it, isSuccess, *myTupletActual, myHasTupletActual ) ) { continue; } if ( importElement( message, *it, isSuccess, *myTupletNormal, myHasTupletNormal ) ) { continue; } } return isSuccess; } } }
/**************************************************************************************** * @author: kzvd4729 created: Apr/25/2020 11:17 * solution_verdict: Accepted language: GNU C++14 * run_time: 295 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/659/problem/G ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6,mod=1e9+7; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=1;i<=n;i++)cin>>aa[i]; int a=-1,b=-1,c=-1,d=-1,e=-1,f=-1; int ans=aa[1]-1;a=2,b=aa[1],c=1; for(int i=2;i<=n;i++) { if(aa[i]>=aa[i-1]) { int sm=0; if(a!=-1&&a<=b)sm=(sm+1LL*(b-a+1)*c)%mod; if(d!=-1&&d<=e)sm=(sm+1LL*(e-d+1)*f)%mod; sm++;ans=(ans+1LL*(aa[i-1]-1)*sm)%mod; a=2,b=aa[i-1],c=sm; ans=(ans+aa[i]-aa[i-1])%mod; d=aa[i-1]+1,e=aa[i],f=1; } else { int sm=0; b=min(b,aa[i]);e=min(e,aa[i]); if(a!=-1&&a<=b)sm=(sm+1LL*(b-a+1)*c)%mod; if(d!=-1&&d<=e)sm=(sm+1LL*(e-d+1)*f)%mod; sm++;ans=(ans+1LL*(aa[i]-1)*sm)%mod; d=-1;a=2,b=aa[i],c=sm; } } cout<<ans<<endl; return 0; }
// Copyright (c) 2014-2017 Michael J. Sullivan // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file. #include "epoch_leak.hpp"
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpcserver.h" #include "base58.h" #include "init.h" #include "main.h" #include "ui_interface.h" #include "util.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <boost/algorithm/string.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/iostreams/concepts.hpp> #include <boost/iostreams/stream.hpp> #include <boost/shared_ptr.hpp> #include "json/json_spirit_writer_template.h" using namespace std; using namespace boost; using namespace boost::asio; using namespace json_spirit; static std::string strRPCUserColonPass; // These are created by StartRPCThreads, destroyed in StopRPCThreads static asio::io_service* rpc_io_service = NULL; static map<string, boost::shared_ptr<deadline_timer> > deadlineTimers; static ssl::context* rpc_ssl_context = NULL; static boost::thread_group* rpc_worker_group = NULL; static boost::asio::io_service::work *rpc_dummy_work = NULL; static std::vector< boost::shared_ptr<ip::tcp::acceptor> > rpc_acceptors; void RPCTypeCheck(const Array& params, const list<Value_type>& typesExpected, bool fAllowNull) { unsigned int i = 0; BOOST_FOREACH(Value_type t, typesExpected) { if (params.size() <= i) break; const Value& v = params[i]; if (!((v.type() == t) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s, got %s", Value_type_name[t], Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } i++; } } void RPCTypeCheck(const Object& o, const map<string, Value_type>& typesExpected, bool fAllowNull) { BOOST_FOREACH(const PAIRTYPE(string, Value_type)& t, typesExpected) { const Value& v = find_value(o, t.first); if (!fAllowNull && v.type() == null_type) throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Missing %s", t.first)); if (!((v.type() == t.second) || (fAllowNull && (v.type() == null_type)))) { string err = strprintf("Expected type %s for %s, got %s", Value_type_name[t.second], t.first, Value_type_name[v.type()]); throw JSONRPCError(RPC_TYPE_ERROR, err); } } } int64_t AmountFromValue(const Value& value) { double dAmount = value.get_real(); if (dAmount <= 0.0 || dAmount > 50000000000.0) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); int64_t nAmount = roundint64(dAmount * COIN); if (!MoneyRange(nAmount)) throw JSONRPCError(RPC_TYPE_ERROR, "Invalid amount"); return nAmount; } Value ValueFromAmount(int64_t amount) { return (double)amount / (double)COIN; } std::string HexBits(unsigned int nBits) { union { int32_t nBits; char cBits[4]; } uBits; uBits.nBits = htonl((int32_t)nBits); return HexStr(BEGIN(uBits.cBits), END(uBits.cBits)); } uint256 ParseHashV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) // Note: IsHex("") is false throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); uint256 result; result.SetHex(strHex); return result; } uint256 ParseHashO(const Object& o, string strKey) { return ParseHashV(find_value(o, strKey), strKey); } vector<unsigned char> ParseHexV(const Value& v, string strName) { string strHex; if (v.type() == str_type) strHex = v.get_str(); if (!IsHex(strHex)) throw JSONRPCError(RPC_INVALID_PARAMETER, strName+" must be hexadecimal string (not '"+strHex+"')"); return ParseHex(strHex); } vector<unsigned char> ParseHexO(const Object& o, string strKey) { return ParseHexV(find_value(o, strKey), strKey); } /// /// Note: This interface may still be subject to change. /// string CRPCTable::help(string strCommand) const { string strRet; set<rpcfn_type> setDone; for (map<string, const CRPCCommand*>::const_iterator mi = mapCommands.begin(); mi != mapCommands.end(); ++mi) { const CRPCCommand *pcmd = mi->second; string strMethod = mi->first; // We already filter duplicates, but these deprecated screw up the sort order if (strMethod.find("label") != string::npos) continue; if (strCommand != "" && strMethod != strCommand) continue; #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) continue; #endif try { Array params; rpcfn_type pfn = pcmd->actor; if (setDone.insert(pfn).second) (*pfn)(params, true); } catch (std::exception& e) { // Help text is returned in an exception string strHelp = string(e.what()); if (strCommand == "") if (strHelp.find('\n') != string::npos) strHelp = strHelp.substr(0, strHelp.find('\n')); strRet += strHelp + "\n"; } } if (strRet == "") strRet = strprintf("help: unknown command: %s\n", strCommand); strRet = strRet.substr(0,strRet.size()-1); return strRet; } Value help(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "help ( \"command\" )\n" "\nList all commands, or get help for a specified command.\n" "\nArguments:\n" "1. \"command\" (string, optional) The command to get help on\n" "\nResult:\n" "\"text\" (string) The help text\n" ); string strCommand; if (params.size() > 0) strCommand = params[0].get_str(); return tableRPC.help(strCommand); } Value stop(const Array& params, bool fHelp) { // Accept the deprecated and ignored 'detach' boolean argument if (fHelp || params.size() > 1) throw runtime_error( "stop\n" "\nStop Smileycoin server."); // Shutdown will take long enough that the response should get back StartShutdown(); return "Smileycoin server stopping"; } // // Call Table // static const CRPCCommand vRPCCommands[] = { // name actor (function) okSafeMode threadSafe reqWallet // ------------------------ ----------------------- ---------- ---------- --------- /* Overall control/query calls */ { "getinfo", &getinfo, true, false, false }, /* uses wallet if enabled */ { "help", &help, true, true, false }, { "stop", &stop, true, true, false }, /* P2P networking */ { "getnetworkinfo", &getnetworkinfo, true, false, false }, { "addnode", &addnode, true, true, false }, { "getaddednodeinfo", &getaddednodeinfo, true, true, false }, { "getconnectioncount", &getconnectioncount, true, false, false }, { "getnettotals", &getnettotals, true, true, false }, { "getpeerinfo", &getpeerinfo, true, false, false }, { "ping", &ping, true, false, false }, /* Block chain and UTXO */ { "adddex", &adddex, false, false, false }, { "addubi", &addubi, false, false, false }, { "addchapter", &addchapter, false, false, false }, { "getaddressinfo", &getaddressinfo, false, false, false }, { "getrichaddresses", &getrichaddresses, false, false, false }, { "createservice", &createservice, false, false, false }, { "createticket", &createticket, false, false, false }, { "buyticket", &buyticket, false, false, false }, { "deleteservice", &deleteservice, false, false, false }, { "getserviceaddresses", &getserviceaddresses, false, false, false }, { "getticketlist", &getticketlist, false, false, false }, { "getubilist", &getubilist, false, false, false }, { "getdexlist", &getdexlist, false, false, false }, { "getnpolist", &getnpolist, false, false, false }, { "getbooklist", &getbooklist, false, false, false }, { "getblockchaininfo", &getblockchaininfo, true, false, false }, { "getbestblockhash", &getbestblockhash, true, false, false }, { "getblockcount", &getblockcount, true, false, false }, { "getblock", &getblock, false, false, false }, { "getblockhash", &getblockhash, false, false, false }, { "getdifficulty", &getdifficulty, true, false, false }, { "getrawmempool", &getrawmempool, true, false, false }, { "gettxout", &gettxout, true, false, false }, { "gettxoutsetinfo", &gettxoutsetinfo, true, false, false }, { "verifychain", &verifychain, true, false, false }, /* Mining */ { "getblocktemplate", &getblocktemplate, true, false, false }, { "getmininginfo", &getmininginfo, true, false, false }, // { "getnetworkhashps", &getnetworkhashps, true, false, false }, { "submitblock", &submitblock, false, false, false }, /* Raw transactions */ { "createrawtransaction", &createrawtransaction, false, false, false }, { "decoderawtransaction", &decoderawtransaction, false, false, false }, { "decodescript", &decodescript, false, false, false }, { "getrawtransaction", &getrawtransaction, false, false, false }, { "sendrawtransaction", &sendrawtransaction, false, false, false }, { "signrawtransaction", &signrawtransaction, false, false, false }, /* uses wallet if enabled */ /* Utility functions */ { "createmultisig", &createmultisig, true, true , false }, { "validateaddress", &validateaddress, true, false, false }, /* uses wallet if enabled */ { "verifymessage", &verifymessage, false, false, false }, #ifdef ENABLE_WALLET /* Wallet */ { "addmultisigaddress", &addmultisigaddress, false, false, true }, { "backupwallet", &backupwallet, true, false, true }, { "dumpprivkey", &dumpprivkey, true, false, true }, { "dumpwallet", &dumpwallet, true, false, true }, { "encryptwallet", &encryptwallet, false, false, true }, { "getaccountaddress", &getaccountaddress, true, false, true }, { "getaccount", &getaccount, false, false, true }, { "getaddressesbyaccount", &getaddressesbyaccount, true, false, true }, { "getbalance", &getbalance, false, false, true }, { "getnewaddress", &getnewaddress, true, false, true }, { "getrawchangeaddress", &getrawchangeaddress, true, false, true }, { "getreceivedbyaccount", &getreceivedbyaccount, false, false, true }, { "getreceivedbyaddress", &getreceivedbyaddress, false, false, true }, { "gettransaction", &gettransaction, false, false, true }, { "getunconfirmedbalance", &getunconfirmedbalance, false, false, true }, { "getwalletinfo", &getwalletinfo, true, false, true }, { "importprivkey", &importprivkey, false, false, true }, { "importwallet", &importwallet, false, false, true }, { "keypoolrefill", &keypoolrefill, true, false, true }, { "listaccounts", &listaccounts, false, false, true }, { "listaddressgroupings", &listaddressgroupings, false, false, true }, { "listlockunspent", &listlockunspent, false, false, true }, { "listreceivedbyaccount", &listreceivedbyaccount, false, false, true }, { "listreceivedbyaddress", &listreceivedbyaddress, false, false, true }, { "listsinceblock", &listsinceblock, false, false, true }, { "listtransactions", &listtransactions, false, false, true }, { "listunspent", &listunspent, false, false, true }, { "lockunspent", &lockunspent, false, false, true }, { "move", &movecmd, false, false, true }, { "sendfrom", &sendfrom, false, false, true }, { "sendmany", &sendmany, false, false, true }, { "sendtoaddress", &sendtoaddress, false, false, true }, { "setaccount", &setaccount, true, false, true }, { "settxfee", &settxfee, false, false, true }, { "signmessage", &signmessage, false, false, true }, { "encryptmessage", &encryptmessage, false, false, true }, { "decryptmessage", &decryptmessage, false, false, true }, { "walletlock", &walletlock, true, false, true }, { "walletpassphrasechange", &walletpassphrasechange, false, false, true }, { "walletpassphrase", &walletpassphrase, true, false, true }, /* Wallet-enabled mining */ { "getgenerate", &getgenerate, true, false, false }, { "gethashespersec", &gethashespersec, true, false, false }, { "getwork", &getwork, true, false, true }, { "setgenerate", &setgenerate, true, true, false }, { "getjoke", &getjoke, false, false, true }, #endif // ENABLE_WALLET }; CRPCTable::CRPCTable() { unsigned int vcidx; for (vcidx = 0; vcidx < (sizeof(vRPCCommands) / sizeof(vRPCCommands[0])); vcidx++) { const CRPCCommand *pcmd; pcmd = &vRPCCommands[vcidx]; mapCommands[pcmd->name] = pcmd; } } const CRPCCommand *CRPCTable::operator[](string name) const { map<string, const CRPCCommand*>::const_iterator it = mapCommands.find(name); if (it == mapCommands.end()) return NULL; return (*it).second; } bool HTTPAuthorized(map<string, string>& mapHeaders) { string strAuth = mapHeaders["authorization"]; if (strAuth.substr(0,6) != "Basic ") return false; string strUserPass64 = strAuth.substr(6); boost::trim(strUserPass64); string strUserPass = DecodeBase64(strUserPass64); return TimingResistantEqual(strUserPass, strRPCUserColonPass); } void ErrorReply(std::ostream& stream, const Object& objError, const Value& id) { // Send error reply from json-rpc error object int nStatus = HTTP_INTERNAL_SERVER_ERROR; int code = find_value(objError, "code").get_int(); if (code == RPC_INVALID_REQUEST) nStatus = HTTP_BAD_REQUEST; else if (code == RPC_METHOD_NOT_FOUND) nStatus = HTTP_NOT_FOUND; string strReply = JSONRPCReply(Value::null, objError, id); stream << HTTPReply(nStatus, strReply, false) << std::flush; } bool ClientAllowed(const boost::asio::ip::address& address) { // Make sure that IPv4-compatible and IPv4-mapped IPv6 addresses are treated as IPv4 addresses if (address.is_v6() && (address.to_v6().is_v4_compatible() || address.to_v6().is_v4_mapped())) return ClientAllowed(address.to_v6().to_v4()); if (address == asio::ip::address_v4::loopback() || address == asio::ip::address_v6::loopback() || (address.is_v4() // Check whether IPv4 addresses match 127.0.0.0/8 (loopback subnet) && (address.to_v4().to_ulong() & 0xff000000) == 0x7f000000)) return true; const string strAddress = address.to_string(); const vector<string>& vAllow = mapMultiArgs["-rpcallowip"]; BOOST_FOREACH(string strAllow, vAllow) if (WildcardMatch(strAddress, strAllow)) return true; return false; } class AcceptedConnection { public: virtual ~AcceptedConnection() {} virtual std::iostream& stream() = 0; virtual std::string peer_address_to_string() const = 0; virtual void close() = 0; }; template <typename Protocol> class AcceptedConnectionImpl : public AcceptedConnection { public: AcceptedConnectionImpl( asio::io_service& io_service, ssl::context &context, bool fUseSSL) : sslStream(io_service, context), _d(sslStream, fUseSSL), _stream(_d) { } virtual std::iostream& stream() { return _stream; } virtual std::string peer_address_to_string() const { return peer.address().to_string(); } virtual void close() { _stream.close(); } typename Protocol::endpoint peer; asio::ssl::stream<typename Protocol::socket> sslStream; private: SSLIOStreamDevice<Protocol> _d; iostreams::stream< SSLIOStreamDevice<Protocol> > _stream; }; void ServiceConnection(AcceptedConnection *conn); // Forward declaration required for RPCListen #if BOOST_VERSION >= 106000 template <typename Protocol> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, #else template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, #endif ssl::context& context, bool fUseSSL, boost::shared_ptr< AcceptedConnection > conn, const boost::system::error_code& error); /** * Sets up I/O resources to accept and handle a new connection. */ #if BOOST_VERSION >= 106000 template <typename Protocol> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, #else template <typename Protocol, typename SocketAcceptorService> static void RPCListen(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, #endif ssl::context& context, const bool fUseSSL) { // Accept connection boost::shared_ptr< AcceptedConnectionImpl<Protocol> > conn(new AcceptedConnectionImpl<Protocol>(GetIOServiceFromPtr(acceptor), context, fUseSSL)); acceptor->async_accept( conn->sslStream.lowest_layer(), conn->peer, #if BOOST_VERSION >= 106000 boost::bind(&RPCAcceptHandler<Protocol>, #else boost::bind(&RPCAcceptHandler<Protocol, SocketAcceptorService>, #endif acceptor, boost::ref(context), fUseSSL, conn, _1)); } /** * Accept and handle incoming connection. */ #if BOOST_VERSION >= 106000 template <typename Protocol> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol> > acceptor, #else template <typename Protocol, typename SocketAcceptorService> static void RPCAcceptHandler(boost::shared_ptr< basic_socket_acceptor<Protocol, SocketAcceptorService> > acceptor, #endif ssl::context& context, const bool fUseSSL, boost::shared_ptr< AcceptedConnection > conn, const boost::system::error_code& error) { // Immediately start accepting new connections, except when we're cancelled or our socket is closed. if (error != asio::error::operation_aborted && acceptor->is_open()) RPCListen(acceptor, context, fUseSSL); AcceptedConnectionImpl<ip::tcp>* tcp_conn = dynamic_cast< AcceptedConnectionImpl<ip::tcp>* >(conn.get()); if (error) { // TODO: Actually handle errors LogPrintf("%s: Error: %s\n", __func__, error.message()); } // Restrict callers by IP. It is important to // do this before starting client thread, to filter out // certain DoS and misbehaving clients. else if (tcp_conn && !ClientAllowed(tcp_conn->peer.address())) { // Only send a 403 if we're not using SSL to prevent a DoS during the SSL handshake. if (!fUseSSL) conn->stream() << HTTPReply(HTTP_FORBIDDEN, "", false) << std::flush; conn->close(); } else { ServiceConnection(conn.get()); conn->close(); } } void StartRPCThreads() { strRPCUserColonPass = mapArgs["-rpcuser"] + ":" + mapArgs["-rpcpassword"]; if (((mapArgs["-rpcpassword"] == "") || (mapArgs["-rpcuser"] == mapArgs["-rpcpassword"])) && Params().RequireRPCPassword()) { unsigned char rand_pwd[32]; RAND_bytes(rand_pwd, 32); string strWhatAmI = "To use smileycoind"; if (mapArgs.count("-server")) strWhatAmI = strprintf(_("To use the %s option"), "\"-server\""); else if (mapArgs.count("-daemon")) strWhatAmI = strprintf(_("To use the %s option"), "\"-daemon\""); uiInterface.ThreadSafeMessageBox(strprintf( _("%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=smileycoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Smileycoin Alert\" admin@foo.com\n"), strWhatAmI, GetConfigFile().string(), EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32)), "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } assert(rpc_io_service == NULL); rpc_io_service = new asio::io_service(); #if BOOST_VERSION >= 106000 rpc_ssl_context = new ssl::context(ssl::context::sslv23); #else rpc_ssl_context = new ssl::context(*rpc_io_service, ssl::context::sslv23); #endif const bool fUseSSL = GetBoolArg("-rpcssl", false); if (fUseSSL) { rpc_ssl_context->set_options(ssl::context::no_sslv2); filesystem::path pathCertFile(GetArg("-rpcsslcertificatechainfile", "server.cert")); if (!pathCertFile.is_complete()) pathCertFile = filesystem::path(GetDataDir()) / pathCertFile; if (filesystem::exists(pathCertFile)) rpc_ssl_context->use_certificate_chain_file(pathCertFile.string()); else LogPrintf("ThreadRPCServer ERROR: missing server certificate file %s\n", pathCertFile.string()); filesystem::path pathPKFile(GetArg("-rpcsslprivatekeyfile", "server.pem")); if (!pathPKFile.is_complete()) pathPKFile = filesystem::path(GetDataDir()) / pathPKFile; if (filesystem::exists(pathPKFile)) rpc_ssl_context->use_private_key_file(pathPKFile.string(), ssl::context::pem); else LogPrintf("ThreadRPCServer ERROR: missing server private key file %s\n", pathPKFile.string()); string strCiphers = GetArg("-rpcsslciphers", "TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH"); #if BOOST_VERSION >= 106000 SSL_CTX_set_cipher_list(rpc_ssl_context->native_handle(), strCiphers.c_str()); #else SSL_CTX_set_cipher_list(rpc_ssl_context->impl(), strCiphers.c_str()); #endif } // Try a dual IPv6/IPv4 socket, falling back to separate IPv4 and IPv6 sockets const bool loopback = !mapArgs.count("-rpcallowip"); asio::ip::address bindAddress = loopback ? asio::ip::address_v6::loopback() : asio::ip::address_v6::any(); ip::tcp::endpoint endpoint(bindAddress, GetArg("-rpcport", Params().RPCPort())); boost::system::error_code v6_only_error; bool fListening = false; std::string strerr; try { boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); // Try making the socket dual IPv6/IPv4 (if listening on the "any" address) acceptor->set_option(boost::asio::ip::v6_only(loopback), v6_only_error); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); rpc_acceptors.push_back(acceptor); fListening = true; } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s"), endpoint.port(), e.what()); } try { // If dual IPv6/IPv4 failed (or we're opening loopback interfaces only), open IPv4 separately if (!fListening || loopback || v6_only_error) { bindAddress = loopback ? asio::ip::address_v4::loopback() : asio::ip::address_v4::any(); endpoint.address(bindAddress); boost::shared_ptr<ip::tcp::acceptor> acceptor(new ip::tcp::acceptor(*rpc_io_service)); acceptor->open(endpoint.protocol()); acceptor->set_option(boost::asio::ip::tcp::acceptor::reuse_address(true)); acceptor->bind(endpoint); acceptor->listen(socket_base::max_connections); RPCListen(acceptor, *rpc_ssl_context, fUseSSL); rpc_acceptors.push_back(acceptor); fListening = true; } } catch(boost::system::system_error &e) { strerr = strprintf(_("An error occurred while setting up the RPC port %u for listening on IPv4: %s"), endpoint.port(), e.what()); } if (!fListening) { uiInterface.ThreadSafeMessageBox(strerr, "", CClientUIInterface::MSG_ERROR); StartShutdown(); return; } rpc_worker_group = new boost::thread_group(); for (int i = 0; i < GetArg("-rpcthreads", 4); i++) rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } void StartDummyRPCThread() { if(rpc_io_service == NULL) { rpc_io_service = new asio::io_service(); /* Create dummy "work" to keep the thread from exiting when no timeouts active, * see http://www.boost.org/doc/libs/1_51_0/doc/html/boost_asio/reference/io_service.html#boost_asio.reference.io_service.stopping_the_io_service_from_running_out_of_work */ rpc_dummy_work = new asio::io_service::work(*rpc_io_service); rpc_worker_group = new boost::thread_group(); rpc_worker_group->create_thread(boost::bind(&asio::io_service::run, rpc_io_service)); } } void StopRPCThreads() { if (rpc_io_service == NULL) return; // First, cancel all timers and acceptors // This is not done automatically by ->stop(), and in some cases the destructor of // asio::io_service can hang if this is skipped. boost::system::error_code ec; BOOST_FOREACH(const boost::shared_ptr<ip::tcp::acceptor> &acceptor, rpc_acceptors) { acceptor->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling acceptor", __func__, ec.message()); } rpc_acceptors.clear(); BOOST_FOREACH(const PAIRTYPE(std::string, boost::shared_ptr<deadline_timer>) &timer, deadlineTimers) { timer.second->cancel(ec); if (ec) LogPrintf("%s: Warning: %s when cancelling timer", __func__, ec.message()); } deadlineTimers.clear(); rpc_io_service->stop(); if (rpc_worker_group != NULL) rpc_worker_group->join_all(); delete rpc_dummy_work; rpc_dummy_work = NULL; delete rpc_worker_group; rpc_worker_group = NULL; delete rpc_ssl_context; rpc_ssl_context = NULL; delete rpc_io_service; rpc_io_service = NULL; } void RPCRunHandler(const boost::system::error_code& err, boost::function<void(void)> func) { if (!err) func(); } void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds) { assert(rpc_io_service != NULL); if (deadlineTimers.count(name) == 0) { deadlineTimers.insert(make_pair(name, boost::shared_ptr<deadline_timer>(new deadline_timer(*rpc_io_service)))); } deadlineTimers[name]->expires_from_now(posix_time::seconds(nSeconds)); deadlineTimers[name]->async_wait(boost::bind(RPCRunHandler, _1, func)); } class JSONRequest { public: Value id; string strMethod; Array params; JSONRequest() { id = Value::null; } void parse(const Value& valRequest); }; void JSONRequest::parse(const Value& valRequest) { // Parse request if (valRequest.type() != obj_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Invalid Request object"); const Object& request = valRequest.get_obj(); // Parse id now so errors from here on will have the id id = find_value(request, "id"); // Parse method Value valMethod = find_value(request, "method"); if (valMethod.type() == null_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Missing method"); if (valMethod.type() != str_type) throw JSONRPCError(RPC_INVALID_REQUEST, "Method must be a string"); strMethod = valMethod.get_str(); if (strMethod != "getwork" && strMethod != "getblocktemplate") LogPrint("rpc", "ThreadRPCServer method=%s\n", strMethod); // Parse params Value valParams = find_value(request, "params"); if (valParams.type() == array_type) params = valParams.get_array(); else if (valParams.type() == null_type) params = Array(); else throw JSONRPCError(RPC_INVALID_REQUEST, "Params must be an array"); } static Object JSONRPCExecOne(const Value& req) { Object rpc_result; JSONRequest jreq; try { jreq.parse(req); Value result = tableRPC.execute(jreq.strMethod, jreq.params); rpc_result = JSONRPCReplyObj(result, Value::null, jreq.id); } catch (Object& objError) { rpc_result = JSONRPCReplyObj(Value::null, objError, jreq.id); } catch (std::exception& e) { rpc_result = JSONRPCReplyObj(Value::null, JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); } return rpc_result; } static string JSONRPCExecBatch(const Array& vReq) { Array ret; for (unsigned int reqIdx = 0; reqIdx < vReq.size(); reqIdx++) ret.push_back(JSONRPCExecOne(vReq[reqIdx])); return write_string(Value(ret), false) + "\n"; } void ServiceConnection(AcceptedConnection *conn) { bool fRun = true; while (fRun && !ShutdownRequested()) { int nProto = 0; map<string, string> mapHeaders; string strRequest, strMethod, strURI; // Read HTTP request line if (!ReadHTTPRequestLine(conn->stream(), nProto, strMethod, strURI)) break; // Read HTTP message headers and body ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; break; } // Check authorization if (mapHeaders.count("authorization") == 0) { conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (!HTTPAuthorized(mapHeaders)) { LogPrintf("ThreadRPCServer incorrect password attempt from %s\n", conn->peer_address_to_string()); /* Deter brute-forcing short passwords. If this results in a DoS the user really shouldn't have their RPC port exposed. */ if (mapArgs["-rpcpassword"].size() < 20) MilliSleep(250); conn->stream() << HTTPReply(HTTP_UNAUTHORIZED, "", false) << std::flush; break; } if (mapHeaders["connection"] == "close") fRun = false; JSONRequest jreq; try { // Parse request Value valRequest; if (!read_string(strRequest, valRequest)) throw JSONRPCError(RPC_PARSE_ERROR, "Parse error"); string strReply; // singleton request if (valRequest.type() == obj_type) { jreq.parse(valRequest); Value result = tableRPC.execute(jreq.strMethod, jreq.params); // Send reply strReply = JSONRPCReply(result, Value::null, jreq.id); // array of requests } else if (valRequest.type() == array_type) strReply = JSONRPCExecBatch(valRequest.get_array()); else throw JSONRPCError(RPC_PARSE_ERROR, "Top-level object parse error"); conn->stream() << HTTPReply(HTTP_OK, strReply, fRun) << std::flush; } catch (Object& objError) { ErrorReply(conn->stream(), objError, jreq.id); break; } catch (std::exception& e) { ErrorReply(conn->stream(), JSONRPCError(RPC_PARSE_ERROR, e.what()), jreq.id); break; } } } json_spirit::Value CRPCTable::execute(const std::string &strMethod, const json_spirit::Array &params) const { // Find method const CRPCCommand *pcmd = tableRPC[strMethod]; if (!pcmd) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found"); #ifdef ENABLE_WALLET if (pcmd->reqWallet && !pwalletMain) throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)"); #endif // Observe safe mode string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", false) && !pcmd->okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning); try { // Execute Value result; { if (pcmd->threadSafe) result = pcmd->actor(params, false); #ifdef ENABLE_WALLET else if (!pwalletMain) { LOCK(cs_main); result = pcmd->actor(params, false); } else { LOCK2(cs_main, pwalletMain->cs_wallet); result = pcmd->actor(params, false); } #else // ENABLE_WALLET else { LOCK(cs_main); result = pcmd->actor(params, false); } #endif // !ENABLE_WALLET } return result; } catch (std::exception& e) { throw JSONRPCError(RPC_MISC_ERROR, e.what()); } } std::string HelpExampleCli(string methodname, string args){ return "> smileycoin-cli " + methodname + " " + args + "\n"; } std::string HelpExampleRpc(string methodname, string args){ return "> curl --user myusername --data-binary '{\"jsonrpc\": \"1.0\", \"id\":\"curltest\", " "\"method\": \"" + methodname + "\", \"params\": [" + args + "] }' -H 'content-type: text/plain;' http://127.0.0.1:9332/\n"; } const CRPCTable tableRPC;
// _ _____ __________ // | | / / _ | / __/_ __/ Visibility // | |/ / __ |_\ \ / / Across // |___/_/ |_/___/ /_/ Space and Time // // SPDX-FileCopyrightText: (c) 2018 The VAST Contributors // SPDX-License-Identifier: BSD-3-Clause #include "vast/system/spawn_exporter.hpp" #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/defaults.hpp" #include "vast/logger.hpp" #include "vast/query_options.hpp" #include "vast/system/exporter.hpp" #include "vast/system/make_transforms.hpp" #include "vast/system/node.hpp" #include "vast/system/spawn_arguments.hpp" #include "vast/system/transformer.hpp" #include <caf/actor.hpp> #include <caf/event_based_actor.hpp> #include <caf/expected.hpp> #include <caf/send.hpp> #include <caf/settings.hpp> #include <caf/typed_event_based_actor.hpp> namespace vast::system { caf::expected<caf::actor> spawn_exporter(node_actor::stateful_pointer<node_state> self, spawn_arguments& args) { VAST_TRACE_SCOPE("{}", VAST_ARG(args)); // Parse given expression. auto expr = get_expression(args); if (!expr) return expr.error(); auto transforms = make_transforms(transforms_location::server_export, args.inv.options); if (!transforms) return transforms.error(); // Parse query options. auto query_opts = no_query_options; if (get_or(args.inv.options, "vast.export.continuous", false)) query_opts = query_opts + continuous; if (get_or(args.inv.options, "vast.export.unified", false)) query_opts = unified; // Default to historical if no options provided. if (query_opts == no_query_options) query_opts = historical; // Mark the query as low priority if explicitly requested. if (get_or(args.inv.options, "vast.export.low-priority", false)) query_opts = query_opts + low_priority; auto handle = self->spawn(exporter, *expr, query_opts, std::move(*transforms)); VAST_VERBOSE("{} spawned an exporter for {}", *self, to_string(*expr)); // Wire the exporter to all components. auto [accountant, importer, index] = self->state.registry.find<accountant_actor, importer_actor, index_actor>(); if (accountant) self->send(handle, accountant); if (importer && has_continuous_option(query_opts)) self ->request(importer, caf::infinite, static_cast<stream_sink_actor<table_slice>>(handle)) .then( [=](caf::outbound_stream_slot<table_slice>) { // nop }, [=, importer = importer](caf::error err) { VAST_ERROR("{} failed to connect to importer {}: {}", *self, importer, err); }); if (index) { VAST_DEBUG("{} connects index to new exporter", *self); self->send(handle, index); } // Setting max-events to 0 means infinite. auto max_events = get_or(args.inv.options, "vast.export.max-events", defaults::export_::max_events); if (max_events > 0) self->send(handle, atom::extract_v, static_cast<uint64_t>(max_events)); else self->send(handle, atom::extract_v); return caf::actor_cast<caf::actor>(handle); } } // namespace vast::system
/* * * Copyright 2017 gRPC authors. * * 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 <grpc/support/port_platform.h> #include "src/core/ext/filters/client_channel/proxy_mapper_registry.h" #include <algorithm> #include <memory> #include <utility> #include <vector> namespace grpc_core { namespace { using ProxyMapperList = std::vector<std::unique_ptr<ProxyMapperInterface>>; ProxyMapperList* g_proxy_mapper_list; } // namespace void ProxyMapperRegistry::Init() { if (g_proxy_mapper_list == nullptr) { g_proxy_mapper_list = new ProxyMapperList(); } } void ProxyMapperRegistry::Shutdown() { delete g_proxy_mapper_list; // Clean up in case we re-initialze later. // TODO(roth): This should ideally live in Init(). However, if we did this // there, then we would do it AFTER we start registering proxy mappers from // third-party plugins, so they'd never show up (and would leak memory). // We probably need some sort of dependency system for plugins to fix // this. g_proxy_mapper_list = nullptr; } void ProxyMapperRegistry::Register( bool at_start, std::unique_ptr<ProxyMapperInterface> mapper) { Init(); if (at_start) { g_proxy_mapper_list->insert(g_proxy_mapper_list->begin(), std::move(mapper)); } else { g_proxy_mapper_list->emplace_back(std::move(mapper)); } } bool ProxyMapperRegistry::MapName(const char* server_uri, const grpc_channel_args* args, char** name_to_resolve, grpc_channel_args** new_args) { Init(); for (const auto& mapper : *g_proxy_mapper_list) { if (mapper->MapName(server_uri, args, name_to_resolve, new_args)) { return true; } } return false; } bool ProxyMapperRegistry::MapAddress(const grpc_resolved_address& address, const grpc_channel_args* args, grpc_resolved_address** new_address, grpc_channel_args** new_args) { Init(); for (const auto& mapper : *g_proxy_mapper_list) { if (mapper->MapAddress(address, args, new_address, new_args)) { return true; } } return false; } } // namespace grpc_core
#include <liegroups/se2.hpp> #include <liegroups/se2_io.hpp> #include <liegroups/so3.hpp> #include <liegroups/so3_io.hpp> #include <liegroups/se3.hpp> #include <liegroups/se3_io.hpp> #include <cstdlib> #include <cassert> #include <vector> #include <iostream> using namespace std; using namespace liegroups; double rand_uniform() { return (double)std::rand() / (double)RAND_MAX; } template <int N, class S> void random_vec(S x[N], S scale = (S)1) { for (int i=0; i<N; ++i) x[i] = scale * (S)(rand_uniform()*2.0 - 1.0); } template <class G> void update_mean(const std::vector<G> &samples, G &mu) { const int N = G::DoF; double sum[N]; for (int k=0; k<N; ++k) sum[k] = 0.0; for (size_t i=0; i<samples.size(); ++i) { double eps[N]; log(eps, samples[i] * inverse(mu)); for (int k=0; k<N; ++k) sum[k] += eps[k]; } const double inv_n = 1.0 / (double)samples.size(); for (int k=0; k<N; ++k) sum[k] *= inv_n; G delta; exp(delta, sum); mu = delta * mu; rectify(mu); } template <class S> ostream &print_mat(ostream &out, const S x[], int m, int n) { const int w = out.precision() + 6; for (int i=0; i<m; ++i) { for (int j=0; j<n; ++j) { out.width(w); out << x[i*n + j]; } out << endl; } return out; } int main(int argc, char *argv[]) { typedef SO3<double> G; const int N = G::DoF; double eps[N]; random_vec<N>(eps); G mu; exp(mu, eps); std::vector<G> samples(100); for (size_t i=0; i<samples.size(); ++i) { random_vec<N>(eps); G delta; exp(delta, eps); samples[i] = delta * mu; } mu = samples[0]; for (int pass=0; pass<10; ++pass) { update_mean(samples, mu); } double cov[N*N]; for (int k=0; k<N*N; ++k) cov[k] = 0.0; for (size_t i=0; i<samples.size(); ++i) { double eps[N]; log(eps, samples[i] * inverse(mu)); for (int j=0; j<N; ++j) { for (int k=j; k<N; ++k) { cov[j*N+k] += eps[j] * eps[k]; } } } const double inv_n = 1.0 / (double)samples.size(); for (int j=0; j<N; ++j) { for (int k=j; k<N; ++k) { cov[j*N+k] *= inv_n; cov[k*N+j] = cov[j*N+k]; } } cout.precision(15); cout << mu << endl; print_mat(cout, cov, N, N); return 0; }
#pragma once #ifndef GREEZEZ_MPSCQUEUE_HPP #define GREEZEZ_MPSCQUEUE_HPP namespace greezez { namespace mpsc { class Produser { public: Produser() { } ~Produser() { } private: }; class Consumer { public: Consumer() { } ~Consumer() { } private: }; } } #endif // !GREEZEZ_MPSCQUEUE_HPP
/* MIT License - Copyright (c) 2019-2021 Francis Van Roie For full license information read the LICENSE file in the project folder */ // USAGE: - Copy this file and rename it to my_custom.cpp // - Change false to true on line 9 #include "hasplib.h" #if defined(HASP_USE_CUSTOM) && false // <-- set this to true in your code #include "hasp_debug.h" #include "custom/my_custom.h" void custom_setup() { // Initialization code here randomSeed(millis()); } void custom_loop() { // Non-blocking code here, this should execute very fast! } void custom_every_second() { Serial.print("#"); } void custom_every_5seconds() { LOG_VERBOSE(TAG_CUSTOM, "5 seconds have passsed..."); dispatch_state_subtopic("my_sensor","{\"test\":123}"); } bool custom_pin_in_use(uint8_t pin) { if(pin == 1024) return true; // fictuous used pin // otherwise the pin is not used return false; } void custom_get_sensors(JsonDocument& doc) { /* Sensor Name */ JsonObject sensor = doc.createNestedObject(F("Custom")); /* Key-Value pair of the sensor value */ sensor[F("Random")] = random(256); } void custom_topic_payload(const char* topic, const char* payload, uint8_t source){ // Not used } #endif // HASP_USE_CUSTOM
// Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The ALLMN Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "chainparams.h" #include "clientversion.h" #include "validation.h" #include "net.h" #include "net_processing.h" #include "netbase.h" #include "protocol.h" #include "sync.h" #include "timedata.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "version.h" #include <boost/foreach.hpp> #include <univalue.h> using namespace std; UniValue getconnectioncount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" "\nResult:\n" "n (numeric) The connection count\n" "\nExamples:\n" + HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL); } UniValue ping(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n" "\nExamples:\n" + HelpExampleCli("ping", "") + HelpExampleRpc("ping", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Request that each node send a ping during next message processing pass g_connman->ForEachNode([](CNode* pnode) { pnode->fPingQueued = true; }); return NullUniValue; } UniValue getpeerinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nResult:\n" "[\n" " {\n" " \"id\": n, (numeric) Peer index\n" " \"addr\":\"host:port\", (string) The ip address and port of the peer\n" " \"addrlocal\":\"ip:port\", (string) local address\n" " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n" " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"timeoffset\": ttt, (numeric) The time offset in seconds\n" " \"pingtime\": n, (numeric) ping time (if available)\n" " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n" " \"pingwait\": n, (numeric) ping wait (if non-zero)\n" " \"version\": v, (numeric) The peer version, such as 7001\n" " \"subver\": \"/ALLMN Core:x.x.x/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score\n" " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n" " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n" " \"inflight\": [\n" " n, (numeric) The heights of blocks we're currently asking from this peer\n" " ...\n" " ]\n" " \"bytessent_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n" " ...\n" " }\n" " \"bytesrecv_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes received aggregated by message type\n" " ...\n" " }\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); vector<CNodeStats> vstats; g_connman->GetNodeStats(vstats); UniValue ret(UniValue::VARR); BOOST_FOREACH(const CNodeStats& stats, vstats) { UniValue obj(UniValue::VOBJ); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.push_back(Pair("id", stats.nodeid)); obj.push_back(Pair("addr", stats.addrName)); if (!(stats.addrLocal.empty())) obj.push_back(Pair("addrlocal", stats.addrLocal)); obj.push_back(Pair("services", strprintf("%016x", stats.nServices))); obj.push_back(Pair("relaytxes", stats.fRelayTxes)); obj.push_back(Pair("lastsend", stats.nLastSend)); obj.push_back(Pair("lastrecv", stats.nLastRecv)); obj.push_back(Pair("bytessent", stats.nSendBytes)); obj.push_back(Pair("bytesrecv", stats.nRecvBytes)); obj.push_back(Pair("conntime", stats.nTimeConnected)); obj.push_back(Pair("timeoffset", stats.nTimeOffset)); if (stats.dPingTime > 0.0) obj.push_back(Pair("pingtime", stats.dPingTime)); if (stats.dMinPing < std::numeric_limits<int64_t>::max()/1e6) obj.push_back(Pair("minping", stats.dMinPing)); if (stats.dPingWait > 0.0) obj.push_back(Pair("pingwait", stats.dPingWait)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); if (fStateStats) { obj.push_back(Pair("banscore", statestats.nMisbehavior)); obj.push_back(Pair("synced_headers", statestats.nSyncHeight)); obj.push_back(Pair("synced_blocks", statestats.nCommonHeight)); UniValue heights(UniValue::VARR); BOOST_FOREACH(int height, statestats.vHeightInFlight) { heights.push_back(height); } obj.push_back(Pair("inflight", heights)); } obj.push_back(Pair("whitelisted", stats.fWhitelisted)); UniValue sendPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapSendBytesPerMsgCmd) { if (i.second > 0) sendPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd)); UniValue recvPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapRecvBytesPerMsgCmd) { if (i.second > 0) recvPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytesrecv_per_msg", recvPerMsgCmd)); ret.push_back(obj); } return ret; } UniValue addnode(const UniValue& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n" "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:20500\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:20500\", \"onetry\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; g_connman->OpenNetworkConnection(addr, NULL, strNode.c_str()); return NullUniValue; } if (strCommand == "add") { if(!g_connman->AddNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added"); } else if(strCommand == "remove") { if(!g_connman->RemoveAddedNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } return NullUniValue; } UniValue disconnectnode(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "disconnectnode \"node\" \n" "\nImmediately disconnects from the specified node.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "\nExamples:\n" + HelpExampleCli("disconnectnode", "\"192.168.0.6:8333\"") + HelpExampleRpc("disconnectnode", "\"192.168.0.6:8333\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); bool ret = g_connman->DisconnectNode(params[0].get_str()); if (!ret) throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes"); return NullUniValue; } UniValue getaddednodeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo dummy ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "\nArguments:\n" "1. dummy (boolean, required) Kept for historical purposes but ignored\n" "2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node ip address or name (as provided to addnode)\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [ (list of objects) Only when connected = true\n" " {\n" " \"address\" : \"192.168.0.201:20500\", (string) The allmn server IP and port we're connected to\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo(); if (params.size() == 2) { bool found = false; for (const AddedNodeInfo& info : vInfo) { if (info.strAddedNode == params[1].get_str()) { vInfo.assign(1, info); found = true; break; } } if (!found) { throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } } UniValue ret(UniValue::VARR); for (const AddedNodeInfo& info : vInfo) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", info.strAddedNode)); obj.push_back(Pair("connected", info.fConnected)); UniValue addresses(UniValue::VARR); if (info.fConnected) { UniValue address(UniValue::VOBJ); address.push_back(Pair("address", info.resolvedAddress.ToString())); address.push_back(Pair("connected", info.fInbound ? "inbound" : "outbound")); addresses.push_back(address); } obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } UniValue getnettotals(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" "\nResult:\n" "{\n" " \"totalbytesrecv\": n, (numeric) Total bytes received\n" " \"totalbytessent\": n, (numeric) Total bytes sent\n" " \"timemillis\": t, (numeric) Total cpu time\n" " \"uploadtarget\":\n" " {\n" " \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n" " \"target\": n, (numeric) Target in bytes\n" " \"target_reached\": true|false, (boolean) True if target is reached\n" " \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n" " \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n" " \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("totalbytesrecv", g_connman->GetTotalBytesRecv())); obj.push_back(Pair("totalbytessent", g_connman->GetTotalBytesSent())); obj.push_back(Pair("timemillis", GetTimeMillis())); UniValue outboundLimit(UniValue::VOBJ); outboundLimit.push_back(Pair("timeframe", g_connman->GetMaxOutboundTimeframe())); outboundLimit.push_back(Pair("target", g_connman->GetMaxOutboundTarget())); outboundLimit.push_back(Pair("target_reached", g_connman->OutboundTargetReached(false))); outboundLimit.push_back(Pair("serve_historical_blocks", !g_connman->OutboundTargetReached(true))); outboundLimit.push_back(Pair("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft())); outboundLimit.push_back(Pair("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle())); obj.push_back(Pair("uploadtarget", outboundLimit)); return obj; } static UniValue GetNetworksInfo() { UniValue networks(UniValue::VARR); for(int n=0; n<NET_MAX; ++n) { enum Network network = static_cast<enum Network>(n); if(network == NET_UNROUTABLE) continue; proxyType proxy; UniValue obj(UniValue::VOBJ); GetProxy(network, proxy); obj.push_back(Pair("name", GetNetworkName(network))); obj.push_back(Pair("limited", IsLimited(network))); obj.push_back(Pair("reachable", IsReachable(network))); obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())); obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials)); networks.push_back(obj); } return networks; } UniValue getnetworkinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getnetworkinfo\n" "Returns an object containing various state info regarding P2P networking.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"subversion\": \"/ALLMN Core:x.x.x/\", (string) the server subversion string\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n" " \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"networkactive\": true|false, (bool) whether p2p networking is enabled\n" " \"networks\": [ (array) information per network\n" " {\n" " \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n" " \"limited\": true|false, (boolean) is the network limited using -onlynet?\n" " \"reachable\": true|false, (boolean) is the network reachable?\n" " \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n" " }\n" " ,...\n" " ],\n" " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT + "/kB\n" " \"localaddresses\": [ (array) list of local addresses\n" " {\n" " \"address\": \"xxxx\", (string) network address\n" " \"port\": xxx, (numeric) network port\n" " \"score\": xxx (numeric) relative score\n" " }\n" " ,...\n" " ]\n" " \"warnings\": \"...\" (string) any network warnings (such as alert messages) \n" "}\n" "\nExamples:\n" + HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("version", CLIENT_VERSION)); obj.push_back(Pair("subversion", strSubVersion)); obj.push_back(Pair("protocolversion",PROTOCOL_VERSION)); if(g_connman) obj.push_back(Pair("localservices", strprintf("%016x", g_connman->GetLocalServices()))); obj.push_back(Pair("localrelay", fRelayTxes)); obj.push_back(Pair("timeoffset", GetTimeOffset())); if (g_connman) { obj.push_back(Pair("networkactive", g_connman->GetNetworkActive())); obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL))); } obj.push_back(Pair("networks", GetNetworksInfo())); obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); UniValue localAddresses(UniValue::VARR); { LOCK(cs_mapLocalHost); BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost) { UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", item.first.ToString())); rec.push_back(Pair("port", item.second.nPort)); rec.push_back(Pair("score", item.second.nScore)); localAddresses.push_back(rec); } } obj.push_back(Pair("localaddresses", localAddresses)); obj.push_back(Pair("warnings", GetWarnings("statusbar"))); return obj; } UniValue setban(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 2) strCommand = params[1].get_str(); if (fHelp || params.size() < 2 || (strCommand != "add" && strCommand != "remove")) throw runtime_error( "setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n" "\nAttempts add or remove a IP/Subnet from the banned list.\n" "\nArguments:\n" "1. \"ip(/netmask)\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n" "2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n" "3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n" "4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n" "\nExamples:\n" + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400") + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"") + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); CSubNet subNet; CNetAddr netAddr; bool isSubnet = false; if (params[0].get_str().find("/") != string::npos) isSubnet = true; if (!isSubnet) { CNetAddr resolved; LookupHost(params[0].get_str().c_str(), resolved, false); netAddr = resolved; } else LookupSubNet(params[0].get_str().c_str(), subNet); if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) ) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Invalid IP/Subnet"); if (strCommand == "add") { if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned"); int64_t banTime = 0; //use standard bantime if not specified if (params.size() >= 3 && !params[2].isNull()) banTime = params[2].get_int64(); bool absolute = false; if (params.size() == 4 && params[3].isTrue()) absolute = true; isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute); } else if(strCommand == "remove") { if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) )) throw JSONRPCError(RPC_MISC_ERROR, "Error: Unban failed"); } return NullUniValue; } UniValue listbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "listbanned\n" "\nList all banned IPs/Subnets.\n" "\nExamples:\n" + HelpExampleCli("listbanned", "") + HelpExampleRpc("listbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); banmap_t banMap; g_connman->GetBanned(banMap); UniValue bannedAddresses(UniValue::VARR); for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++) { CBanEntry banEntry = (*it).second; UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", (*it).first.ToString())); rec.push_back(Pair("banned_until", banEntry.nBanUntil)); rec.push_back(Pair("ban_created", banEntry.nCreateTime)); rec.push_back(Pair("ban_reason", banEntry.banReasonToString())); bannedAddresses.push_back(rec); } return bannedAddresses; } UniValue clearbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "clearbanned\n" "\nClear all banned IPs.\n" "\nExamples:\n" + HelpExampleCli("clearbanned", "") + HelpExampleRpc("clearbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->ClearBanned(); return NullUniValue; } UniValue setnetworkactive(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) { throw runtime_error( "setnetworkactive true|false\n" "Disable/enable all p2p network activity." ); } if (!g_connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } g_connman->SetNetworkActive(params[0].get_bool()); return g_connman->GetNetworkActive(); }
// Generated by Haxe 4.2.2 #include <hxcpp.h> #ifndef INCLUDED_haxe_Exception #include <haxe/Exception.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_lime_utils_Log #include <lime/utils/Log.h> #endif #ifndef INCLUDED_openfl_display3D__internal_ATFReader #include <openfl/display3D/_internal/ATFReader.h> #endif #ifndef INCLUDED_openfl_errors_Error #include <openfl/errors/Error.h> #endif #ifndef INCLUDED_openfl_errors_IllegalOperationError #include <openfl/errors/IllegalOperationError.h> #endif #ifndef INCLUDED_openfl_utils_ByteArrayData #include <openfl/utils/ByteArrayData.h> #endif #ifndef INCLUDED_openfl_utils_IDataInput #include <openfl/utils/IDataInput.h> #endif #ifndef INCLUDED_openfl_utils_IDataOutput #include <openfl/utils/IDataOutput.h> #endif #ifndef INCLUDED_openfl_utils__ByteArray_ByteArray_Impl_ #include <openfl/utils/_ByteArray/ByteArray_Impl_.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_29_new,"openfl.display3D._internal.ATFReader","new",0x924c0ddd,"openfl.display3D._internal.ATFReader.new","openfl/display3D/_internal/ATFReader.hx",29,0x2cd00676) HX_LOCAL_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_75_readHeader,"openfl.display3D._internal.ATFReader","readHeader",0x065709a6,"openfl.display3D._internal.ATFReader.readHeader","openfl/display3D/_internal/ATFReader.hx",75,0x2cd00676) HX_LOCAL_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_113_readTextures,"openfl.display3D._internal.ATFReader","readTextures",0xb2f8ef91,"openfl.display3D._internal.ATFReader.readTextures","openfl/display3D/_internal/ATFReader.hx",113,0x2cd00676) HX_LOCAL_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_145___readUInt24,"openfl.display3D._internal.ATFReader","__readUInt24",0x5d1343b5,"openfl.display3D._internal.ATFReader.__readUInt24","openfl/display3D/_internal/ATFReader.hx",145,0x2cd00676) HX_LOCAL_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_154___readUInt32,"openfl.display3D._internal.ATFReader","__readUInt32",0x5d134492,"openfl.display3D._internal.ATFReader.__readUInt32","openfl/display3D/_internal/ATFReader.hx",154,0x2cd00676) HX_LOCAL_STACK_FRAME(_hx_pos_4af6cd3d88d54aa0_29_boot,"openfl.display3D._internal.ATFReader","boot",0x68591415,"openfl.display3D._internal.ATFReader.boot","openfl/display3D/_internal/ATFReader.hx",29,0x2cd00676) namespace openfl{ namespace display3D{ namespace _internal{ void ATFReader_obj::__construct( ::openfl::utils::ByteArrayData data,int byteArrayOffset){ HX_GC_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_29_new) HXLINE( 36) this->version = 0; HXLINE( 41) data->position = byteArrayOffset; HXLINE( 42) ::String signature = data->readUTFBytes(3); HXLINE( 43) data->position = byteArrayOffset; HXLINE( 45) if ((signature != HX_("ATF",f3,9b,31,00))) { HXLINE( 47) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF signature not found",a0,f7,2f,3a)))); } HXLINE( 50) int length = 0; HXLINE( 53) if ((data->b->__get((byteArrayOffset + 6)) == 255)) { HXLINE( 55) this->version = ( (int)(data->b->__get((byteArrayOffset + 7))) ); HXLINE( 56) data->position = (byteArrayOffset + 8); HXLINE( 57) length = this->_hx___readUInt32(data); } else { HXLINE( 61) this->version = 0; HXLINE( 62) data->position = (byteArrayOffset + 3); HXLINE( 63) length = this->_hx___readUInt24(data); } HXLINE( 66) int a = (byteArrayOffset + length); HXDLIN( 66) int b = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(data); HXDLIN( 66) bool aNeg = (a < 0); HXDLIN( 66) bool bNeg = (b < 0); HXDLIN( 66) bool _hx_tmp; HXDLIN( 66) if ((aNeg != bNeg)) { HXLINE( 66) _hx_tmp = aNeg; } else { HXLINE( 66) _hx_tmp = (a > b); } HXDLIN( 66) if (_hx_tmp) { HXLINE( 68) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF length exceeds byte array length",d7,29,45,0f)))); } HXLINE( 71) this->data = data; } Dynamic ATFReader_obj::__CreateEmpty() { return new ATFReader_obj; } void *ATFReader_obj::_hx_vtable = 0; Dynamic ATFReader_obj::__Create(::hx::DynamicArray inArgs) { ::hx::ObjectPtr< ATFReader_obj > _hx_result = new ATFReader_obj(); _hx_result->__construct(inArgs[0],inArgs[1]); return _hx_result; } bool ATFReader_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x1cbf0639; } bool ATFReader_obj::readHeader(int _hx___width,int _hx___height,bool cubeMap){ HX_GC_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_75_readHeader) HXLINE( 76) int tdata = this->data->readUnsignedByte(); HXLINE( 77) int type = ::hx::UShr(tdata,7); HXLINE( 79) bool _hx_tmp; HXDLIN( 79) if (!(cubeMap)) { HXLINE( 79) _hx_tmp = (type != 0); } else { HXLINE( 79) _hx_tmp = false; } HXDLIN( 79) if (_hx_tmp) { HXLINE( 81) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map not expected",a7,74,ca,c8)))); } HXLINE( 84) bool _hx_tmp1; HXDLIN( 84) if (cubeMap) { HXLINE( 84) _hx_tmp1 = (type != 1); } else { HXLINE( 84) _hx_tmp1 = false; } HXDLIN( 84) if (_hx_tmp1) { HXLINE( 86) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF Cube map expected",fa,fe,ed,52)))); } HXLINE( 89) this->cubeMap = cubeMap; HXLINE( 91) this->atfFormat = (tdata & 127); HXLINE( 94) bool _hx_tmp2; HXDLIN( 94) if ((this->atfFormat != 3)) { HXLINE( 94) _hx_tmp2 = (this->atfFormat != 5); } else { HXLINE( 94) _hx_tmp2 = false; } HXDLIN( 94) if (_hx_tmp2) { HXLINE( 96) ::lime::utils::Log_obj::warn(HX_("Only ATF block compressed textures without JPEG-XR+LZMA are supported",25,8c,50,6a),::hx::SourceInfo(HX_("openfl/display3D/_internal/ATFReader.hx",76,06,d0,2c),96,HX_("openfl.display3D._internal.ATFReader",6b,db,a6,4b),HX_("readHeader",83,ed,7b,f6))); } HXLINE( 99) this->width = (1 << this->data->readUnsignedByte()); HXLINE( 100) this->height = (1 << this->data->readUnsignedByte()); HXLINE( 102) bool _hx_tmp3; HXDLIN( 102) if ((this->width == _hx___width)) { HXLINE( 102) _hx_tmp3 = (this->height != _hx___height); } else { HXLINE( 102) _hx_tmp3 = true; } HXDLIN( 102) if (_hx_tmp3) { HXLINE( 104) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("ATF width and height dont match",3f,49,15,70)))); } HXLINE( 107) this->mipCount = this->data->readUnsignedByte(); HXLINE( 109) return (this->atfFormat == 5); } HX_DEFINE_DYNAMIC_FUNC3(ATFReader_obj,readHeader,return ) void ATFReader_obj::readTextures( ::Dynamic uploadCallback){ HX_GC_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_113_readTextures) HXLINE( 116) int gpuFormats; HXDLIN( 116) if ((this->version < 3)) { HXLINE( 116) gpuFormats = 3; } else { HXLINE( 116) gpuFormats = 4; } HXLINE( 117) int sideCount; HXDLIN( 117) if (this->cubeMap) { HXLINE( 117) sideCount = 6; } else { HXLINE( 117) sideCount = 1; } HXLINE( 119) { HXLINE( 119) int _g = 0; HXDLIN( 119) int _g1 = sideCount; HXDLIN( 119) while((_g < _g1)){ HXLINE( 119) _g = (_g + 1); HXDLIN( 119) int side = (_g - 1); HXLINE( 121) { HXLINE( 121) int _g1 = 0; HXDLIN( 121) int _g2 = this->mipCount; HXDLIN( 121) while((_g1 < _g2)){ HXLINE( 121) _g1 = (_g1 + 1); HXDLIN( 121) int level = (_g1 - 1); HXLINE( 123) { HXLINE( 123) int _g = 0; HXDLIN( 123) int _g2 = gpuFormats; HXDLIN( 123) while((_g < _g2)){ HXLINE( 123) _g = (_g + 1); HXDLIN( 123) int gpuFormat = (_g - 1); HXLINE( 125) int blockLength; HXDLIN( 125) if ((this->version == 0)) { HXLINE( 125) blockLength = this->_hx___readUInt24(this->data); } else { HXLINE( 125) blockLength = this->_hx___readUInt32(this->data); } HXLINE( 127) int a = (this->data->position + blockLength); HXDLIN( 127) int b = ::openfl::utils::_ByteArray::ByteArray_Impl__obj::get_length(this->data); HXDLIN( 127) bool aNeg = (a < 0); HXDLIN( 127) bool bNeg = (b < 0); HXDLIN( 127) bool _hx_tmp; HXDLIN( 127) if ((aNeg != bNeg)) { HXLINE( 127) _hx_tmp = aNeg; } else { HXLINE( 127) _hx_tmp = (a > b); } HXDLIN( 127) if (_hx_tmp) { HXLINE( 129) HX_STACK_DO_THROW(::haxe::Exception_obj::thrown( ::openfl::errors::IllegalOperationError_obj::__alloc( HX_CTX ,HX_("Block length exceeds ATF file length",15,23,c0,24)))); } HXLINE( 132) bool aNeg1 = (blockLength < 0); HXDLIN( 132) bool bNeg1 = (0 < 0); HXDLIN( 132) bool _hx_tmp1; HXDLIN( 132) if ((aNeg1 != bNeg1)) { HXLINE( 132) _hx_tmp1 = aNeg1; } else { HXLINE( 132) _hx_tmp1 = (blockLength > 0); } HXDLIN( 132) if (_hx_tmp1) { HXLINE( 134) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(blockLength); HXLINE( 135) { HXLINE( 135) ::openfl::utils::ByteArrayData this1 = this->data; HXDLIN( 135) this1->readBytes(::openfl::utils::_ByteArray::ByteArray_Impl__obj::fromBytes(bytes),0,blockLength); } HXLINE( 137) uploadCallback(side,level,gpuFormat,(this->width >> level),(this->height >> level),blockLength,bytes); } } } } } } } } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,readTextures,(void)) int ATFReader_obj::_hx___readUInt24( ::openfl::utils::ByteArrayData data){ HX_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_145___readUInt24) HXLINE( 146) int value = (data->readUnsignedByte() << 16); HXLINE( 148) value = (value | (data->readUnsignedByte() << 8)); HXLINE( 149) value = (value | data->readUnsignedByte()); HXLINE( 150) return value; } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt24,return ) int ATFReader_obj::_hx___readUInt32( ::openfl::utils::ByteArrayData data){ HX_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_154___readUInt32) HXLINE( 155) int value = (data->readUnsignedByte() << 24); HXLINE( 157) value = (value | (data->readUnsignedByte() << 16)); HXLINE( 158) value = (value | (data->readUnsignedByte() << 8)); HXLINE( 159) value = (value | data->readUnsignedByte()); HXLINE( 160) return value; } HX_DEFINE_DYNAMIC_FUNC1(ATFReader_obj,_hx___readUInt32,return ) ::hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__new( ::openfl::utils::ByteArrayData data,int byteArrayOffset) { ::hx::ObjectPtr< ATFReader_obj > __this = new ATFReader_obj(); __this->__construct(data,byteArrayOffset); return __this; } ::hx::ObjectPtr< ATFReader_obj > ATFReader_obj::__alloc(::hx::Ctx *_hx_ctx, ::openfl::utils::ByteArrayData data,int byteArrayOffset) { ATFReader_obj *__this = (ATFReader_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(ATFReader_obj), true, "openfl.display3D._internal.ATFReader")); *(void **)__this = ATFReader_obj::_hx_vtable; __this->__construct(data,byteArrayOffset); return __this; } ATFReader_obj::ATFReader_obj() { } void ATFReader_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(ATFReader); HX_MARK_MEMBER_NAME(atfFormat,"atfFormat"); HX_MARK_MEMBER_NAME(cubeMap,"cubeMap"); HX_MARK_MEMBER_NAME(data,"data"); HX_MARK_MEMBER_NAME(height,"height"); HX_MARK_MEMBER_NAME(mipCount,"mipCount"); HX_MARK_MEMBER_NAME(version,"version"); HX_MARK_MEMBER_NAME(width,"width"); HX_MARK_END_CLASS(); } void ATFReader_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(atfFormat,"atfFormat"); HX_VISIT_MEMBER_NAME(cubeMap,"cubeMap"); HX_VISIT_MEMBER_NAME(data,"data"); HX_VISIT_MEMBER_NAME(height,"height"); HX_VISIT_MEMBER_NAME(mipCount,"mipCount"); HX_VISIT_MEMBER_NAME(version,"version"); HX_VISIT_MEMBER_NAME(width,"width"); } ::hx::Val ATFReader_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"data") ) { return ::hx::Val( data ); } break; case 5: if (HX_FIELD_EQ(inName,"width") ) { return ::hx::Val( width ); } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { return ::hx::Val( height ); } break; case 7: if (HX_FIELD_EQ(inName,"cubeMap") ) { return ::hx::Val( cubeMap ); } if (HX_FIELD_EQ(inName,"version") ) { return ::hx::Val( version ); } break; case 8: if (HX_FIELD_EQ(inName,"mipCount") ) { return ::hx::Val( mipCount ); } break; case 9: if (HX_FIELD_EQ(inName,"atfFormat") ) { return ::hx::Val( atfFormat ); } break; case 10: if (HX_FIELD_EQ(inName,"readHeader") ) { return ::hx::Val( readHeader_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"readTextures") ) { return ::hx::Val( readTextures_dyn() ); } if (HX_FIELD_EQ(inName,"__readUInt24") ) { return ::hx::Val( _hx___readUInt24_dyn() ); } if (HX_FIELD_EQ(inName,"__readUInt32") ) { return ::hx::Val( _hx___readUInt32_dyn() ); } } return super::__Field(inName,inCallProp); } ::hx::Val ATFReader_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp) { switch(inName.length) { case 4: if (HX_FIELD_EQ(inName,"data") ) { data=inValue.Cast< ::openfl::utils::ByteArrayData >(); return inValue; } break; case 5: if (HX_FIELD_EQ(inName,"width") ) { width=inValue.Cast< int >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; } break; case 7: if (HX_FIELD_EQ(inName,"cubeMap") ) { cubeMap=inValue.Cast< bool >(); return inValue; } if (HX_FIELD_EQ(inName,"version") ) { version=inValue.Cast< int >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"mipCount") ) { mipCount=inValue.Cast< int >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"atfFormat") ) { atfFormat=inValue.Cast< int >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void ATFReader_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("atfFormat",aa,d3,04,9c)); outFields->push(HX_("cubeMap",a7,4c,d0,8c)); outFields->push(HX_("data",2a,56,63,42)); outFields->push(HX_("height",e7,07,4c,02)); outFields->push(HX_("mipCount",9b,6a,51,0e)); outFields->push(HX_("version",18,e7,f1,7c)); outFields->push(HX_("width",06,b6,62,ca)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static ::hx::StorageInfo ATFReader_obj_sMemberStorageInfo[] = { {::hx::fsInt,(int)offsetof(ATFReader_obj,atfFormat),HX_("atfFormat",aa,d3,04,9c)}, {::hx::fsBool,(int)offsetof(ATFReader_obj,cubeMap),HX_("cubeMap",a7,4c,d0,8c)}, {::hx::fsObject /* ::openfl::utils::ByteArrayData */ ,(int)offsetof(ATFReader_obj,data),HX_("data",2a,56,63,42)}, {::hx::fsInt,(int)offsetof(ATFReader_obj,height),HX_("height",e7,07,4c,02)}, {::hx::fsInt,(int)offsetof(ATFReader_obj,mipCount),HX_("mipCount",9b,6a,51,0e)}, {::hx::fsInt,(int)offsetof(ATFReader_obj,version),HX_("version",18,e7,f1,7c)}, {::hx::fsInt,(int)offsetof(ATFReader_obj,width),HX_("width",06,b6,62,ca)}, { ::hx::fsUnknown, 0, null()} }; static ::hx::StaticInfo *ATFReader_obj_sStaticStorageInfo = 0; #endif static ::String ATFReader_obj_sMemberFields[] = { HX_("atfFormat",aa,d3,04,9c), HX_("cubeMap",a7,4c,d0,8c), HX_("data",2a,56,63,42), HX_("height",e7,07,4c,02), HX_("mipCount",9b,6a,51,0e), HX_("version",18,e7,f1,7c), HX_("width",06,b6,62,ca), HX_("readHeader",83,ed,7b,f6), HX_("readTextures",ae,44,04,a1), HX_("__readUInt24",d2,98,1e,4b), HX_("__readUInt32",af,99,1e,4b), ::String(null()) }; ::hx::Class ATFReader_obj::__mClass; void ATFReader_obj::__register() { ATFReader_obj _hx_dummy; ATFReader_obj::_hx_vtable = *(void **)&_hx_dummy; ::hx::Static(__mClass) = new ::hx::Class_obj(); __mClass->mName = HX_("openfl.display3D._internal.ATFReader",6b,db,a6,4b); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &::hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &::hx::Class_obj::SetNoStaticField; __mClass->mStatics = ::hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = ::hx::Class_obj::dupFunctions(ATFReader_obj_sMemberFields); __mClass->mCanCast = ::hx::TCanCast< ATFReader_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ATFReader_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ATFReader_obj_sStaticStorageInfo; #endif ::hx::_hx_RegisterClass(__mClass->mName, __mClass); } void ATFReader_obj::__boot() { { HX_STACKFRAME(&_hx_pos_4af6cd3d88d54aa0_29_boot) HXDLIN( 29) __mClass->__meta__ = ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("obj",f7,8f,54,00), ::Dynamic(::hx::Anon_obj::Create(1) ->setFixed(0,HX_("SuppressWarnings",0c,d3,d2,00),::cpp::VirtualArray_obj::__new(1)->init(0,HX_("checkstyle:FieldDocComment",70,56,1b,20)))))); } } } // end namespace openfl } // end namespace display3D } // end namespace _internal
// Std. Includes #include <string> // GLEW #define GLEW_STATIC #include <GL/glew.h> // GLFW #include <GLFW/glfw3.h> // GL includes #include "Headers/Shader.h" #include "camera.h" // GLM Mathemtics #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // Other Libs #include "SOIL2/SOIL2.h" // Properties const GLuint WIDTH = 800, HEIGHT = 600; int SCREEN_WIDTH, SCREEN_HEIGHT; // Function prototypes void KeyCallback( GLFWwindow *window, int key, int scancode, int action, int mode ); void ScrollCallback( GLFWwindow *window, double xOffset, double yOffset ); void MouseCallback( GLFWwindow *window, double xPos, double yPos ); void DoMovement( ); // Camera Camera camera(glm::vec3( 0.0f, 0.0f, 3.0f ) ); GLfloat lastX = WIDTH / 2.0; GLfloat lastY = HEIGHT / 2.0; bool keys[1024]; bool firstMouse = true; GLfloat deltaTime = 0.0f; GLfloat lastFrame = 0.0f; // The MAIN function, from here we start our application and run our Game loop int main( ) { // Init GLFW glfwInit( ); glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 ); glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 ); glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE ); glfwWindowHint( GLFW_RESIZABLE, GL_FALSE ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); GLFWwindow* window = glfwCreateWindow( WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr ); // Windowed if ( nullptr == window ) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate( ); return EXIT_FAILURE; } glfwMakeContextCurrent( window ); glfwGetFramebufferSize( window, &SCREEN_WIDTH, &SCREEN_HEIGHT ); // Set the required callback functions glfwSetKeyCallback( window, KeyCallback ); glfwSetCursorPosCallback( window, MouseCallback ); glfwSetScrollCallback( window, ScrollCallback ); // Options, removes the mouse cursor for a more immersive experience glfwSetInputMode( window, GLFW_CURSOR, GLFW_CURSOR_DISABLED ); // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions glewExperimental = GL_TRUE; // Initialize GLEW to setup the OpenGL Function pointers if ( GLEW_OK != glewInit( ) ) { std::cout << "Failed to initialize GLEW" << std::endl; return EXIT_FAILURE; } // Define the viewport dimensions glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT ); // Setup some OpenGL options glEnable( GL_DEPTH_TEST ); // enable alpha support glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); // Setup and compile our shaders Shader ourShader( "../Agreste-Game-Engine-Raspbian/Shaders/coreV.vs", "../Agreste-Game-Engine-Raspbian/Shaders/coreF.fs" ); // Set up our vertex data (and buffer(s)) and attribute pointers GLfloat vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f ), glm::vec3( 2.0f, 5.0f, -15.0f ), glm::vec3( -1.5f, -2.2f, -2.5f ), glm::vec3( -3.8f, -2.0f, -12.3f ), glm::vec3( 2.4f, -0.4f, -3.5f ), glm::vec3( -1.7f, 3.0f, -7.5f ), glm::vec3( 1.3f, -2.0f, -2.5f ), glm::vec3( 1.5f, 2.0f, -2.5f ), glm::vec3( 1.5f, 0.2f, -1.5f ), glm::vec3( -1.3f, 1.0f, -1.5f ) }; GLuint VBO, VAO; glGenVertexArrays( 1, &VAO ); glGenBuffers( 1, &VBO ); // Bind our Vertex Array Object first, then bind and set our buffers and pointers. glBindVertexArray( VAO ); glBindBuffer( GL_ARRAY_BUFFER, VBO ); glBufferData( GL_ARRAY_BUFFER, sizeof( vertices ), vertices, GL_STATIC_DRAW ); // Position attribute glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof( GLfloat ), ( GLvoid * )0 ); glEnableVertexAttribArray( 0 ); // TexCoord attribute glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof( GLfloat ), ( GLvoid * )( 3 * sizeof( GLfloat ) ) ); glEnableVertexAttribArray( 2 ); glBindVertexArray( 0 ); // Unbind VAO // Load and create a texture GLuint texture; // --== TEXTURE == -- glGenTextures( 1, &texture ); glBindTexture( GL_TEXTURE_2D, texture ); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object // Set our texture parameters glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT ); // Set texture filtering glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); // Load, create texture and generate mipmaps int width, height; unsigned char *image = SOIL_load_image( "../Agreste-Game-Engine-Raspbian/Images/image1.jpg", &width, &height, 0, SOIL_LOAD_RGB ); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image ); glGenerateMipmap( GL_TEXTURE_2D ); SOIL_free_image_data( image ); glBindTexture( GL_TEXTURE_2D, 0 ); // Unbind texture when done, so we won't accidentily mess up our texture. // Game loop while( !glfwWindowShouldClose( window ) ) { // Set frame time GLfloat currentFrame = glfwGetTime( ); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // Check and call events glfwPollEvents( ); DoMovement( ); // Clear the colorbuffer glClearColor( 0.2f, 0.3f, 0.3f, 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Draw our first triangle ourShader.Use( ); // Bind Textures using texture units glActiveTexture( GL_TEXTURE0 ); glBindTexture( GL_TEXTURE_2D, texture ); glUniform1i( glGetUniformLocation( ourShader.Program, "ourTexture1" ), 0 ); glm::mat4 projection(1); projection = glm::perspective(camera.GetZoom( ), (GLfloat)SCREEN_WIDTH/(GLfloat)SCREEN_HEIGHT, 0.1f, 1000.0f); // Create camera transformation glm::mat4 view(1); view = camera.GetViewMatrix( ); // Get the uniform locations GLint modelLoc = glGetUniformLocation( ourShader.Program, "model" ); GLint viewLoc = glGetUniformLocation( ourShader.Program, "view" ); GLint projLoc = glGetUniformLocation( ourShader.Program, "projection" ); // Pass the matrices to the shader glUniformMatrix4fv( viewLoc, 1, GL_FALSE, glm::value_ptr( view ) ); glUniformMatrix4fv( projLoc, 1, GL_FALSE, glm::value_ptr( projection ) ); glBindVertexArray( VAO ); for( GLuint i = 0; i < 10; i++ ) { // Calculate the model matrix for each object and pass it to shader before drawing glm::mat4 model(1); model = glm::translate( model, cubePositions[i] ); GLfloat angle = 20.0f * i; model = glm::rotate(model, angle, glm::vec3( 1.0f, 0.3f, 0.5f ) ); glUniformMatrix4fv( modelLoc, 1, GL_FALSE, glm::value_ptr( model ) ); glDrawArrays( GL_TRIANGLES, 0, 36 ); } glBindVertexArray( 0 ); // Swap the buffers glfwSwapBuffers( window ); } // Properly de-allocate all resources once they've outlived their purpose glDeleteVertexArrays( 1, &VAO ); glDeleteBuffers( 1, &VBO ); glfwTerminate( ); return EXIT_SUCCESS; } // Moves/alters the camera positions based on user input void DoMovement( ) { // Camera controls if( keys[GLFW_KEY_W] || keys[GLFW_KEY_UP] ) { camera.ProcessKeyboard( FORWARD, deltaTime ); } if( keys[GLFW_KEY_S] || keys[GLFW_KEY_DOWN] ) { camera.ProcessKeyboard( BACKWARD, deltaTime ); } if( keys[GLFW_KEY_A] || keys[GLFW_KEY_LEFT] ) { camera.ProcessKeyboard( LEFT, deltaTime ); } if( keys[GLFW_KEY_D] || keys[GLFW_KEY_RIGHT] ) { camera.ProcessKeyboard( RIGHT, deltaTime ); } } // Is called whenever a key is pressed/released via GLFW void KeyCallback( GLFWwindow *window, int key, int scancode, int action, int mode ) { if( key == GLFW_KEY_ESCAPE && action == GLFW_PRESS ) { glfwSetWindowShouldClose(window, GL_TRUE); } if ( key >= 0 && key < 1024 ) { if( action == GLFW_PRESS ) { keys[key] = true; } else if( action == GLFW_RELEASE ) { keys[key] = false; } } } void MouseCallback( GLFWwindow *window, double xPos, double yPos ) { if( firstMouse ) { lastX = xPos; lastY = yPos; firstMouse = false; } GLfloat xOffset = xPos - lastX; GLfloat yOffset = lastY - yPos; // Reversed since y-coordinates go from bottom to left lastX = xPos; lastY = yPos; camera.ProcessMouseMovement( xOffset, yOffset ); } void ScrollCallback( GLFWwindow *window, double xOffset, double yOffset ) { camera.ProcessMouseScroll( yOffset ); }
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // <vector> // void assign(size_type n, const_reference v); #include <vector> #include <algorithm> #include <cassert> #include "test_macros.h" #include "min_allocator.h" #include "asan_testing.h" bool is6(int x) { return x == 6; } template <typename Vec> void test ( Vec &v ) { v.assign(5, 6); assert(v.size() == 5); assert(is_contiguous_container_asan_correct(v)); assert(std::all_of(v.begin(), v.end(), is6)); } int main(int, char**) { { typedef std::vector<int> V; V d1; V d2; d2.reserve(10); // no reallocation during assign. test(d1); test(d2); } #if TEST_STD_VER >= 11 { typedef std::vector<int, min_allocator<int>> V; V d1; V d2; d2.reserve(10); // no reallocation during assign. test(d1); test(d2); } #endif return 0; }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_ATANH_HPP_INCLUDED #define NT2_TOOLBOX_HYPERBOLIC_FUNCTIONS_SIMD_COMMON_ATANH_HPP_INCLUDED #include <nt2/toolbox/hyperbolic/functions/atanh.hpp> #include <nt2/sdk/meta/as_floating.hpp> #include <nt2/sdk/simd/meta/is_real_convertible.hpp> #include <nt2/include/constants/digits.hpp> #include <nt2/include/constants/real.hpp> #include <nt2/sdk/meta/strip.hpp> #include <nt2/include/functions/simd/abs.hpp> #include <nt2/include/functions/simd/if_else.hpp> #include <nt2/include/functions/simd/sqr.hpp> #include <nt2/include/functions/simd/fma.hpp> #include <nt2/include/functions/simd/log1p.hpp> #include <nt2/include/functions/simd/log.hpp> #include <nt2/include/functions/simd/oneminus.hpp> #include <nt2/include/functions/simd/oneplus.hpp> #include <nt2/include/functions/simd/tofloat.hpp> #include <nt2/include/functions/simd/sign.hpp> ///////////////////////////////////////////////////////////////////////////// // Implementation when type A0 is arithmetic_ ///////////////////////////////////////////////////////////////////////////// namespace nt2 { namespace ext { NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::atanh_, tag::cpu_ , (A0)(X) , ((simd_<arithmetic_<A0>,X>)) ) { typedef typename meta::as_floating<A0>::type result_type; NT2_FUNCTOR_CALL(1) { return nt2::atanh(tofloat(a0)); } }; } } ///////////////////////////////////////////////////////////////////////////// // Implementation when type A0 is floating_ ///////////////////////////////////////////////////////////////////////////// namespace nt2 { namespace ext { NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::atanh_, tag::cpu_ , (A0)(X) , ((simd_<floating_<A0>,X>)) ) { typedef typename meta::as_floating<A0>::type result_type; NT2_FUNCTOR_CALL(1) { A0 absa0 = nt2::abs(a0); // const A0 small_mask = is_lt(absa0, Twotom10<A0>()); /* x < 2**-10 */ // return select(small_mask, // a0*madd(Third<A0>(), sqr(a0), One<A0>()), // sign(a0)*Half<A0>()*log1p(Two<A0>()*absa0/(One<A0>()-absa0)) // ); A0 t = absa0+absa0; return sign(a0)*Half<A0>()*sel(lt(absa0, Half<A0>()), log1p(t+t*absa0/(One<A0>()-absa0)), log1p(t/(One<A0>()-absa0))); } }; } } #endif
#include "HKConnection.h" #include "HKServer.h" #include "HKAccessory.h" #include "HKLog.h" uint8_t SHARED_REQUEST_BUFFER[SHARED_REQUEST_BUFFER_LEN] = {0}; uint8_t SHARED_RESPONSE_BUFFER[SHARED_RESPONSE_BUFFER_LEN] = {0}; uint8_t SHARED_TEMP_CRYPTO_BUFFER[SHARED_TEMP_CRYPTO_BUFFER_LEN] = {0}; LEDStatus RGB_STATUS_YELLOW(RGB_COLOR_YELLOW, LED_PATTERN_FADE, LED_PRIORITY_IMPORTANT); void generateAccessoryKey(ed25519_key *key) { int r = wc_ed25519_init(key); hkLog.info("wc_ed25519_init key: r:%d", r); WC_RNG rng; r = wc_ed25519_make_key(&rng, ED25519_KEY_SIZE, key); hkLog.info("wc_ed25519_make_key key: r:%d", r); print_hex_memory(key, sizeof(ed25519_key)); } HKConnection::HKConnection(HKServer *s, TCPClient c) { client = c; server = s; //generateAccessoryKey(&accessoryKey); snprintf(c_ID, CLIENT_ID_MAX_LENGTH, "%d.%d.%d.%d", client.remoteIP()[0], client.remoteIP()[1], client.remoteIP()[2], client.remoteIP()[3]); } HKConnection::~HKConnection() { for (uint i = 0; i < notifiableCharacteristics.size(); i++) { notifiableCharacteristics.at(i)->removeNotifiedConnection(this); } if(hasSrp){ wc_SrpTerm(&srp); } } HKConnection::operator bool() { return client; } void HKConnection::writeEncryptedData(uint8_t *payload, size_t size) { hkLog.info("writeEncryptedData responseLen:%d", size); byte nonce[12] = {0}; delay(100); memset(SHARED_TEMP_CRYPTO_BUFFER, 0, SHARED_TEMP_CRYPTO_BUFFER_LEN); uint payload_offset = 0; int part = 0; while (payload_offset < size) { size_t chunk_size = size - payload_offset; if (chunk_size > 1024) chunk_size = 1024; byte aead[2] = {(byte)(chunk_size % 256), (byte)(chunk_size / 256)}; memcpy(SHARED_TEMP_CRYPTO_BUFFER, aead, 2); byte i = 4; int x = readsCount++; while (x) { nonce[i++] = x % 256; x /= 256; } int r = wc_ChaCha20Poly1305_Encrypt( (const byte *)readKey, nonce, aead, 2, (const byte *)payload + payload_offset, chunk_size, (byte *)SHARED_TEMP_CRYPTO_BUFFER + 2, (byte *)(SHARED_TEMP_CRYPTO_BUFFER + chunk_size + 2)); if (r) { hkLog.info("Failed to chacha encrypt payload (code %d)", r); client.stop(); return; } payload_offset += chunk_size; part++; if (isConnected()) { int bytes = client.write(SHARED_TEMP_CRYPTO_BUFFER, chunk_size + 16 + 2); int err = client.getWriteError(); if (err != 0) { hkLog.warn("writeEncryptedData:: failed (error = %d), number of bytes written: %d", err, bytes); } } } } void HKConnection::decryptData(uint8_t *payload, size_t *size) { memset(SHARED_TEMP_CRYPTO_BUFFER, 0, SHARED_REQUEST_BUFFER_LEN); uint8_t *decryptedData = SHARED_TEMP_CRYPTO_BUFFER; size_t decryptedTotalSize = 0; size_t payload_size = *size; size_t *decrypted_size = size; const size_t block_size = 1024 + 16 + 2; size_t required_decrypted_size = payload_size / block_size * 1024 + payload_size % block_size - 16 - 2; if (*decrypted_size < required_decrypted_size) { *decrypted_size = required_decrypted_size; } decryptedTotalSize = required_decrypted_size; byte nonce[12]; memset(nonce, 0, sizeof(nonce)); uint payload_offset = 0; int decrypted_offset = 0; while (payload_offset < payload_size) { size_t chunk_size = payload[payload_offset] + payload[payload_offset + 1] * 256; if (chunk_size + 18 > payload_size - payload_offset) { // Unfinished chunk break; } byte i = 4; int x = writesCount++; while (x) { nonce[i++] = x % 256; x /= 256; } int r = wc_ChaCha20Poly1305_Decrypt( (const byte *)writeKey, nonce, payload + payload_offset, 2, (const byte *)payload + payload_offset + 2, chunk_size, (const byte *)payload + payload_offset + 2 + chunk_size, decryptedData + decrypted_offset); if (r) { hkLog.warn("Failed to chacha decrypt payload (code %d)", r); *size = 0; return; } decrypted_offset += chunk_size; payload_offset += chunk_size + 0x12; // 0x10 is for some auth bytes } memset(payload, 0, *size); memcpy(payload, decryptedData, decryptedTotalSize); *size = decryptedTotalSize; } void HKConnection::readData(uint8_t *buffer, size_t *size) { int total = 0; int bufferSize = 0; if (isConnected()) { while (int availableBytes = client.available()) { bufferSize += availableBytes; int len = client.read(buffer + total, availableBytes); total += len; } } *size = total; if (isEncrypted && total > 0) { decryptData(buffer, size); } } void HKConnection::writeData(uint8_t *responseBuffer, size_t responseLen) { if (isConnected()) { if (isEncrypted) { writeEncryptedData((uint8_t *)responseBuffer, responseLen); } else { hkLog.info("writeData responseLen:%d", responseLen); client.write((uint8_t *)responseBuffer, (size_t)responseLen); } } } bool HKConnection::handleConnection(bool maxConnectionsVictim) { size_t len = 0; memset(SHARED_REQUEST_BUFFER, 0, SHARED_REQUEST_BUFFER_LEN); readData(SHARED_REQUEST_BUFFER, &len); bool result = false; if (len > 0) { lastKeepAliveMs = millis(); RGB_STATUS_YELLOW.setActive(true); hkLog.info("Request Message read length: %d ", len); HKNetworkMessage msg((const char *)SHARED_REQUEST_BUFFER); if (!strcmp(msg.directory, "pair-setup")) { hkLog.info("Handling Pair Setup..."); #ifdef DEBUG_PARTICLE_EVENTS Particle.publish("homekit/pair-setup", clientID(), PRIVATE); #endif handlePairSetup((const char *)SHARED_REQUEST_BUFFER); } else if (!strcmp(msg.directory, "pair-verify")) { if (!maxConnectionsVictim) { hkLog.info("Handling Pair Verify..."); #ifdef DEBUG_PARTICLE_EVENTS Particle.publish("homekit/pair-verify", clientID(), PRIVATE); #endif if (handlePairVerify((const char *)SHARED_REQUEST_BUFFER)) { isEncrypted = true; server->setPaired(true); } } else { #ifdef DEBUG_PARTICLE_EVENTS Particle.publish("homekit/connection-limit", clientID(), PRIVATE); #endif //max connections has been reached. memset(SHARED_RESPONSE_BUFFER, 0, SHARED_RESPONSE_BUFFER_LEN); int len = snprintf((char *)SHARED_RESPONSE_BUFFER, SHARED_RESPONSE_BUFFER_LEN, "HTTP/1.1 503 Service Unavailable\r\n\r\n"); hkLog.info("Max connections reached, sending response to %s data: %s", clientID(), SHARED_RESPONSE_BUFFER); writeData((byte *)SHARED_RESPONSE_BUFFER, len); close(); } } else if (!strcmp(msg.directory, "identify")) { client.stop(); } else if (isEncrypted) { //connection is secured hkLog.info("Handling message request: %s", msg.directory); #ifdef DEBUG_PARTICLE_EVENTS Particle.publish("homekit/accessory", clientID(), PRIVATE); #endif handleAccessoryRequest((const char *)SHARED_REQUEST_BUFFER, len); } result = true; RGB_STATUS_YELLOW.setActive(false); } processPostedCharacteristics(); return result; } void HKConnection::announce(char *desc) { memset(SHARED_RESPONSE_BUFFER, 0, SHARED_RESPONSE_BUFFER_LEN); int len = snprintf((char*)SHARED_RESPONSE_BUFFER, SHARED_RESPONSE_BUFFER_LEN, "EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %u\r\n\r\n%s", strlen(desc), desc); hkLog.info("Announce: %s, data: %s", clientID(), SHARED_RESPONSE_BUFFER); writeData((byte *)SHARED_RESPONSE_BUFFER, len); } void HKConnection::processPostedCharacteristics() { for (uint i = 0; i < postedCharacteristics.size(); i++) { characteristics *c = postedCharacteristics.at(i); int len = snprintf(NULL, 0, "{\"characteristics\":[{\"aid\": %d, \"iid\": %d, \"value\": %s}]}", c->accessory->aid, c->iid, c->value(NULL).c_str()); char buffer[len + 1] = {0}; snprintf(buffer, len + 1, "{\"characteristics\":[{\"aid\": %d, \"iid\": %d, \"value\": %s}]}", c->accessory->aid, c->iid, c->value(NULL).c_str()); announce(buffer); } postedCharacteristics.clear(); } int wc_SrpSetKeyH(Srp *srp, byte *secret, word32 size) { SrpHash hash; int r = BAD_FUNC_ARG; srp->key = (byte *)XMALLOC(SHA512_DIGEST_SIZE, NULL, DYNAMIC_TYPE_SRP); if (!srp->key) return MEMORY_E; srp->keySz = SHA512_DIGEST_SIZE; r = wc_InitSha512(&hash.data.sha512); if (!r) r = wc_Sha512Update(&hash.data.sha512, secret, size); if (!r) r = wc_Sha512Final(&hash.data.sha512, srp->key); // clean up hash data from stack for security memset(&hash, 0, sizeof(hash)); return r; } bool HKConnection::handlePairVerify(const char *buffer) { bool completed = false; char state = State_Pair_Verify_M1; HKNetworkMessage msg(buffer); HKNetworkResponse response = HKNetworkResponse(200); bcopy(msg.data.dataPtrForIndex(6), &state, 1); switch (state) { case State_Pair_Verify_M1: { server->progressPtr(Progress_Pair_Verify_M1); hkLog.info("Pair Verify M1"); curve25519_key controllerKey; int r = wc_curve25519_init(&controllerKey); if (r) hkLog.warn("wc_curve25519_init key: r:%d", r); r = wc_curve25519_import_public_ex((const byte *)msg.data.dataPtrForIndex(3), 32, &controllerKey, EC25519_LITTLE_ENDIAN); if (r) hkLog.warn("wc_curve25519_import_public_ex: r:%d", r); memcpy(&controllerKeyData, msg.data.dataPtrForIndex(3), 32); curve25519_key secretKey; r = wc_curve25519_init(&secretKey); if (r) hkLog.warn("wc_curve25519_init: r:%d", r); WC_RNG rng; wc_curve25519_make_key(&rng, CURVE25519_KEYSIZE, &secretKey); if (r) hkLog.warn("wc_curve25519_make_key: r:%d", r); word32 publicSecretKeySize = CURVE25519_KEYSIZE; r = wc_curve25519_export_public_ex(&secretKey, publicSecretKeyData, &publicSecretKeySize, EC25519_LITTLE_ENDIAN); if (r) hkLog.warn("wc_curve25519_export_public_ex: r:%d", r); word32 sharedKeySize = CURVE25519_KEYSIZE; r = wc_curve25519_shared_secret_ex(&secretKey, &controllerKey, sharedKey, &sharedKeySize, EC25519_LITTLE_ENDIAN); if (r) hkLog.warn("crypto_curve25519_shared_secret: %d", r); int accessoryInfoSize = CURVE25519_KEYSIZE + CURVE25519_KEYSIZE + server->getDeviceIdentity().length(); byte accessoryInfo[accessoryInfoSize]; memcpy(accessoryInfo, publicSecretKeyData, CURVE25519_KEYSIZE); memcpy(&accessoryInfo[CURVE25519_KEYSIZE], server->getDeviceIdentity().c_str(), server->getDeviceIdentity().length()); memcpy(&accessoryInfo[CURVE25519_KEYSIZE + server->getDeviceIdentity().length()], msg.data.dataPtrForIndex(3), CURVE25519_KEYSIZE); word32 accessorySignSize = ED25519_SIG_SIZE; byte accesorySign[accessorySignSize]; r = wc_ed25519_sign_msg(accessoryInfo, accessoryInfoSize, accesorySign, &accessorySignSize, accessoryKey); if (r) hkLog.warn("wc_ed25519_sign_msg: r:%d", r); HKNetworkMessageDataRecord signRecord; signRecord.activate = true; signRecord.data = new char[accessorySignSize]; signRecord.index = 10; signRecord.length = accessorySignSize; memcpy(signRecord.data, accesorySign, accessorySignSize); HKNetworkMessageDataRecord idRecord; idRecord.index = 1; idRecord.activate = true; idRecord.length = server->getDeviceIdentity().length(); idRecord.data = new char[idRecord.length]; memcpy(idRecord.data, server->getDeviceIdentity().c_str(), idRecord.length); HKNetworkMessageData data; data.addRecord(signRecord); data.addRecord(idRecord); char salt[] = "Pair-Verify-Encrypt-Salt"; char info[] = "Pair-Verify-Encrypt-Info"; r = wc_HKDF(SHA512, (const byte *)sharedKey, sharedKeySize, (const byte *)salt, strlen(salt), (const byte *)info, strlen(info), sessionKeyData, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); const char *plainMsg = 0; unsigned short msgLen = 0; data.rawData(&plainMsg, &msgLen); byte encryptMsg[msgLen + 16]; r = wc_ChaCha20Poly1305_Encrypt( (const byte *)sessionKeyData, (const byte *)"\x0\x0\x0\x0PV-Msg02", NULL, 0, (const byte *)plainMsg, msgLen, (byte *)encryptMsg, (byte *)(encryptMsg + msgLen)); if (r) hkLog.warn("wc_ChaCha20Poly1305_Encrypt: r:%d", r); HKNetworkMessageDataRecord stage; stage.activate = true; stage.data = new char; stage.data[0] = State_Pair_Verify_M2; stage.index = 6; stage.length = 1; HKNetworkMessageDataRecord encryptRecord; encryptRecord.activate = true; encryptRecord.index = 5; encryptRecord.length = msgLen + 16; encryptRecord.data = new char[encryptRecord.length]; memcpy(encryptRecord.data, encryptMsg, encryptRecord.length); HKNetworkMessageDataRecord pubKeyRecord; pubKeyRecord.activate = true; pubKeyRecord.data = new char[publicSecretKeySize]; pubKeyRecord.index = 3; pubKeyRecord.length = publicSecretKeySize; memcpy(pubKeyRecord.data, publicSecretKeyData, publicSecretKeySize); response.data.addRecord(stage); response.data.addRecord(pubKeyRecord); response.data.addRecord(encryptRecord); delete[] plainMsg; server->progressPtr(Progress_Pair_Verify_M2); } break; case State_Pair_Verify_M3: { hkLog.info("Pair Verify M3"); server->progressPtr(Progress_Pair_Verify_M3); char *encryptedData = msg.data.dataPtrForIndex(5); short packageLen = msg.data.lengthForIndex(5); byte decryptedData[packageLen - 16]; int r = wc_ChaCha20Poly1305_Decrypt( (const byte *)sessionKeyData, (const byte *)"\x0\x0\x0\x0PV-Msg03", NULL, 0, (const byte *)encryptedData, packageLen - 16, (const byte *)encryptedData + packageLen - 16, decryptedData); if (r) hkLog.warn("wc_ChaCha20Poly1305_Decrypt: r:%d", r); HKNetworkMessageData subData = HKNetworkMessageData((char *)decryptedData, packageLen - 16); HKKeyRecord rec = server->persistor->getKey(subData.dataPtrForIndex(1)); int controllerInfoSize = CURVE25519_KEYSIZE + CURVE25519_KEYSIZE + subData.lengthForIndex(1); byte controllerInfo[controllerInfoSize]; memcpy(controllerInfo, controllerKeyData, CURVE25519_KEYSIZE); memcpy(&controllerInfo[CURVE25519_KEYSIZE], subData.dataPtrForIndex(1), subData.lengthForIndex(1)); memcpy(&controllerInfo[CURVE25519_KEYSIZE + subData.lengthForIndex(1)], publicSecretKeyData, CURVE25519_KEYSIZE); ed25519_key clKey; r = wc_ed25519_init(&clKey); if (r) hkLog.warn("wc_ed25519_init: r:%d", r); r = wc_ed25519_import_public((const byte *)rec.publicKey, ED25519_PUB_KEY_SIZE, &clKey); if (r) hkLog.warn("wc_ed25519_import_public: r:%d", r); int verified = 0; r = wc_ed25519_verify_msg((byte *)subData.dataPtrForIndex(10), subData.lengthForIndex(10), (const byte *)controllerInfo, controllerInfoSize, &verified, &clKey); if (r) hkLog.warn("wc_ed25519_verify_msg: r:%d", r); if (verified) { completed = true; HKNetworkMessageDataRecord stage; stage.activate = true; stage.data = new char; stage.data[0] = State_Pair_Verify_M4; stage.index = 6; stage.length = 1; response.data.addRecord(stage); //hkdf const char salt[] = "Control-Salt"; const char read_info[] = "Control-Read-Encryption-Key"; const char write_info[] = "Control-Write-Encryption-Key"; r = wc_HKDF(SHA512, (const byte *)sharedKey, CHACHA20_POLY1305_AEAD_KEYSIZE, (const byte *)salt, strlen(salt), (const byte *)read_info, strlen(read_info), readKey, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); r = wc_HKDF(SHA512, (const byte *)sharedKey, CHACHA20_POLY1305_AEAD_KEYSIZE, (const byte *)salt, strlen(salt), (const byte *)write_info, strlen(write_info), writeKey, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); hkLog.info("Pair verified, secure connection established"); server->progressPtr(Progress_Pair_Verify_M4); } else { HKNetworkMessageDataRecord error; error.activate = true; error.data = new char[1]; error.data[0] = 2; error.index = 7; error.length = 1; response.data.addRecord(error); hkLog.warn("Pair NOT verified."); server->progressPtr(Progress_Error); } } } char *responseBuffer = 0; int responseLen = 0; response.getBinaryPtr(&responseBuffer, &responseLen); if (responseBuffer) { writeData((byte *)responseBuffer, responseLen); delete[] responseBuffer; } else { hkLog.info("Why empty response"); } return completed; } void HKConnection::handlePairSetup(const char *buffer) { bool completed = false; HKNetworkMessageDataRecord stateRecord; stateRecord.activate = true; stateRecord.data = new char[1]; stateRecord.length = 1; stateRecord.index = 6; PairSetupState_t state = State_M1_SRPStartRequest; char *responseBuffer = 0; int responseLen = 0; HKNetworkMessage msg = HKNetworkMessage(buffer); HKNetworkResponse mResponse(200); state = (PairSetupState_t)(*msg.data.dataPtrForIndex(6)); hkLog.info("State: %d", state); *stateRecord.data = (char)state + 1; switch (state) { case State_M1_SRPStartRequest: { server->progressPtr(Progress_M1_SRPStartRequest); hkLog.info("State_M1_SRPStartRequest"); stateRecord.data[0] = State_M2_SRPStartRespond; HKNetworkMessageDataRecord saltRec; HKNetworkMessageDataRecord publicKeyRec; byte salt[16]; for (int i = 0; i < 16; i++) { salt[i] = rand(); } int r = wc_SrpInit(&srp, SRP_TYPE_SHA512, SRP_CLIENT_SIDE); hasSrp = true; srp.keyGenFunc_cb = wc_SrpSetKeyH; if (!r) r = wc_SrpSetUsername(&srp, (const byte *)"Pair-Setup", strlen("Pair-Setup")); if (r) hkLog.warn("wc_SrpSetUsername: r:%d", r); if (!r) r = wc_SrpSetParams(&srp, (const byte *)N, sizeof(N), (const byte *)generator, 1, salt, 16); if (r) hkLog.warn("wc_SrpSetParams: r:%d", r); if (!r) r = wc_SrpSetPassword(&srp, (const byte *)server->getPasscode().c_str(), server->getPasscode().length()); if (r) hkLog.warn("wc_SrpSetPassword: r:%d", r); if (!r) r = wc_SrpGetVerifier(&srp, (byte *)publicKey, &publicKeyLength); //use publicKey to store v if (r) hkLog.warn("wc_SrpGetVerifier: r:%d", r); srp.side = SRP_SERVER_SIDE; //switch to server mode if (!r) r = wc_SrpSetVerifier(&srp, (byte *)publicKey, publicKeyLength); if (r) hkLog.warn("wc_SrpSetVerifier: r:%d", r); if (!r) r = wc_SrpGetPublic(&srp, (byte *)publicKey, &publicKeyLength); if (r) hkLog.warn("wc_SrpGetPublic: r:%d", r); saltRec.index = 2; saltRec.activate = true; saltRec.length = sizeof(salt); saltRec.data = new char[saltRec.length]; memcpy(saltRec.data, salt, saltRec.length); publicKeyRec.index = 3; publicKeyRec.activate = true; publicKeyRec.length = publicKeyLength; publicKeyRec.data = new char[publicKeyRec.length]; memcpy(publicKeyRec.data, publicKey, publicKeyRec.length); mResponse.data.addRecord(stateRecord); mResponse.data.addRecord(publicKeyRec); mResponse.data.addRecord(saltRec); server->progressPtr(Progress_M2_SRPStartRespond); } break; case State_M3_SRPVerifyRequest: { hkLog.info("State_M3_SRPVerifyRequest"); server->progressPtr(Progress_M3_SRPVerifyRequest); stateRecord.data[0] = State_M4_SRPVerifyRespond; const char *keyStr = 0; int keyLen = 0; char *proofStr = NULL; int proofLen = 0; keyStr = msg.data.dataPtrForIndex(3); keyLen = msg.data.lengthForIndex(3); char *temp = msg.data.dataPtrForIndex(4); if (temp != NULL) { proofStr = temp; proofLen = msg.data.lengthForIndex(4); } else { hkLog.info("no proof sent!"); } int r = wc_SrpComputeKey(&srp, (byte *)keyStr, keyLen, (byte *)publicKey, publicKeyLength); if (r) hkLog.warn("wc_SrpComputeKey: r:%d", r); r = wc_SrpVerifyPeersProof(&srp, (byte *)proofStr, proofLen); if (r) hkLog.warn("wc_SrpVerifyPeersProof: r:%d", r); if (r != 0) { //failed HKNetworkMessageDataRecord responseRecord; responseRecord.activate = true; responseRecord.data = new char[1]; responseRecord.data[0] = 2; responseRecord.index = 7; responseRecord.length = 1; mResponse.data.addRecord(stateRecord); mResponse.data.addRecord(responseRecord); hkLog.warn("INCORRECT PASSWORD"); wc_SrpTerm(&srp); server->progressPtr(Progress_Error); } else { //success unsigned int srpResponseLength = SRP_RESPONSE_LENGTH; char response[SRP_RESPONSE_LENGTH] = {0}; wc_SrpGetProof(&srp, (byte *)response, &srpResponseLength); //SRP_respond(srp, &response); HKNetworkMessageDataRecord responseRecord; responseRecord.activate = true; responseRecord.index = 4; responseRecord.length = srpResponseLength; responseRecord.data = new char[responseRecord.length]; memcpy(responseRecord.data, response, responseRecord.length); mResponse.data.addRecord(stateRecord); mResponse.data.addRecord(responseRecord); hkLog.info("Password is correct."); server->progressPtr(Progress_M4_SRPVerifyRespond); } } break; case State_M5_ExchangeRequest: { hkLog.info("State_M5_ExchangeRequest"); server->progressPtr(Progress_M5_ExchangeRequest); stateRecord.data[0] = State_M6_ExchangeRespond; const char *encryptedPackage = NULL; int packageLen = 0; encryptedPackage = msg.data.dataPtrForIndex(5); packageLen = msg.data.lengthForIndex(5); char encryptedData[packageLen]; memcpy(encryptedData, encryptedPackage, packageLen - 16); char mac[16]; memcpy(mac, &encryptedPackage[packageLen - 16], 16); const char salt1[] = "Pair-Setup-Encrypt-Salt"; const char info1[] = "Pair-Setup-Encrypt-Info"; uint8_t sharedKey[100]; int r = wc_HKDF(SHA512, (const byte *)srp.key, srp.keySz, (const byte *)salt1, strlen(salt1), (const byte *)info1, strlen(info1), sharedKey, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); uint8_t decryptedData[packageLen - 16]; bzero(decryptedData, packageLen - 16); r = wc_ChaCha20Poly1305_Decrypt( (const byte *)sharedKey, (const byte *)"\x0\x0\x0\x0PS-Msg05", NULL, 0, (const byte *)encryptedData, packageLen - 16, (const byte *)mac, decryptedData); hkLog.info("wc_ChaCha20Poly1305_Decrypt: r:%d", r); HKNetworkMessageData *subTLV8 = new HKNetworkMessageData((char *)decryptedData, packageLen - 16); char *controllerIdentifier = subTLV8->dataPtrForIndex(1); char *controllerPublicKey = subTLV8->dataPtrForIndex(3); size_t controllerPublicKeySize = subTLV8->lengthForIndex(3); char *controllerSignature = subTLV8->dataPtrForIndex(10); size_t controllerSignatureSize = subTLV8->lengthForIndex(10); char controllerHash[100]; server->persistor->resetPairings(); HKKeyRecord newRecord; memcpy(newRecord.controllerID, controllerIdentifier, 36); memcpy(newRecord.publicKey, controllerPublicKey, 32); server->persistor->addKey(newRecord); const char salt2[] = "Pair-Setup-Controller-Sign-Salt"; const char info2[] = "Pair-Setup-Controller-Sign-Info"; r = wc_HKDF(SHA512, (const byte *)srp.key, srp.keySz, (const byte *)salt2, strlen(salt2), (const byte *)info2, strlen(info2), (byte *)controllerHash, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); memcpy(&controllerHash[32], controllerIdentifier, 36); memcpy(&controllerHash[68], controllerPublicKey, 32); ed25519_key clKey; r = wc_ed25519_init(&clKey); if (r) hkLog.warn("wc_ed25519_init: r:%d", r); r = wc_ed25519_import_public((const byte *)controllerPublicKey, controllerPublicKeySize, &clKey); if (r) hkLog.warn("wc_ed25519_import_public: r:%d", r); int verified = 0; r = wc_ed25519_verify_msg((byte *)controllerSignature, controllerSignatureSize, (const byte *)controllerHash, 100, &verified, &clKey); if (r) hkLog.warn("wc_ed25519_verify_msg: r:%d", r); if (verified) { HKNetworkMessageData *returnTLV8 = new HKNetworkMessageData(); HKNetworkMessageDataRecord usernameRecord; usernameRecord.activate = true; usernameRecord.index = 1; usernameRecord.length = server->getDeviceIdentity().length(); usernameRecord.data = new char[usernameRecord.length]; memcpy(usernameRecord.data, server->getDeviceIdentity().c_str(), usernameRecord.length); returnTLV8->addRecord(usernameRecord); // Generate Signature const char salt3[] = "Pair-Setup-Accessory-Sign-Salt"; const char info3[] = "Pair-Setup-Accessory-Sign-Info"; size_t outputSize = 64 + server->getDeviceIdentity().length(); uint8_t output[outputSize]; r = wc_HKDF(SHA512, (const byte *)srp.key, srp.keySz, (const byte *)salt3, strlen(salt3), (const byte *)info3, strlen(info3), (byte *)output, CHACHA20_POLY1305_AEAD_KEYSIZE); if (r) hkLog.warn("wc_HKDF: r:%d", r); word32 accessoryPubKeySize = ED25519_PUB_KEY_SIZE; uint8_t accessoryPubKey[accessoryPubKeySize]; r = wc_ed25519_export_public(accessoryKey, accessoryPubKey, &accessoryPubKeySize); memcpy(&output[32], server->getDeviceIdentity().c_str(), server->getDeviceIdentity().length()); memcpy(&output[32 + server->getDeviceIdentity().length()], accessoryPubKey, accessoryPubKeySize); word32 signatureSize = 64; uint8_t signature[signatureSize]; r = wc_ed25519_sign_msg(output, outputSize, signature, &signatureSize, accessoryKey); if (r) hkLog.warn("wc_ed25519_sign_msg: r:%d", r); HKNetworkMessageDataRecord signatureRecord; signatureRecord.activate = true; signatureRecord.index = 10; signatureRecord.length = 64; signatureRecord.data = new char[64]; memcpy(signatureRecord.data, signature, signatureSize); returnTLV8->addRecord(signatureRecord); HKNetworkMessageDataRecord publicKeyRecord; publicKeyRecord.activate = true; publicKeyRecord.index = 3; publicKeyRecord.length = accessoryPubKeySize; publicKeyRecord.data = new char[accessoryPubKeySize]; memcpy(publicKeyRecord.data, accessoryPubKey, accessoryPubKeySize); returnTLV8->addRecord(publicKeyRecord); char *tlv8Data; unsigned short tlv8Len; returnTLV8->rawData((const char **)&tlv8Data, &tlv8Len); HKNetworkMessageDataRecord tlv8Record; tlv8Record.data = new char[tlv8Len + 16]; tlv8Record.length = tlv8Len + 16; bzero(tlv8Record.data, tlv8Record.length); r = wc_ChaCha20Poly1305_Encrypt( (const byte *)sharedKey, (const byte *)"\x0\x0\x0\x0PS-Msg06", NULL, 0, (const byte *)tlv8Data, tlv8Len, (byte *)tlv8Record.data, (byte *)(tlv8Record.data + tlv8Len)); if (r) hkLog.warn("wc_ChaCha20Poly1305_Encrypt: r:%d", r); tlv8Record.activate = true; tlv8Record.index = 5; //5 mResponse.data.addRecord(stateRecord); mResponse.data.addRecord(tlv8Record); completed = true; delete returnTLV8; free(tlv8Data); server->progressPtr(Progress_M6_ExchangeRespond); } else { server->progressPtr(Progress_Error); } delete subTLV8; wc_SrpTerm(&srp); } break; } mResponse.getBinaryPtr(&responseBuffer, &responseLen); if (responseBuffer) { writeData((byte *)responseBuffer, responseLen); delete[] responseBuffer; } else { hkLog.info("Why empty response"); } if (completed) { hkLog.info("Pairing completed."); } } void HKConnection::handleAccessoryRequest(const char *buffer, size_t size) { unsigned int resultLen = 0; server->progressPtr(Progress_AccessoryRequest); handleAccessory(buffer, size, (char *)SHARED_RESPONSE_BUFFER, SHARED_RESPONSE_BUFFER_LEN, &resultLen, this); server->progressPtr(Progress_AccessoryRespond); if (resultLen > 0) { writeData(SHARED_RESPONSE_BUFFER, resultLen); hkLog.info("Response to: %s, data:%s", clientID(), SHARED_RESPONSE_BUFFER); Serial.println((const char*)SHARED_RESPONSE_BUFFER); } } void HKConnection::postCharacteristicsValue(characteristics *c) { for (uint i = 0; i < postedCharacteristics.size(); i++) { characteristics *item = postedCharacteristics.at(i); if (c == item) { //already registered return; } } postedCharacteristics.push_back(c); } void HKConnection::addNotifiedCharacteristics(characteristics *c) { notifiableCharacteristics.push_back(c); }
//===------------------------- future.cpp ---------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "future" #include "string" _LIBCPP_BEGIN_NAMESPACE_STD class _LIBCPP_HIDDEN __future_error_category : public __do_message { public: virtual const char* name() const _NOEXCEPT; virtual string message(int ev) const; }; const char* __future_error_category::name() const _NOEXCEPT { return "future"; } string __future_error_category::message(int ev) const { switch (ev) { case future_errc::broken_promise: return string("The associated promise has been destructed prior " "to the associated state becoming ready."); case future_errc::future_already_retrieved: return string("The future has already been retrieved from " "the promise or packaged_task."); case future_errc::promise_already_satisfied: return string("The state of the promise has already been set."); case future_errc::no_state: return string("Operation not permitted on an object without " "an associated state."); } return string("unspecified future_errc value\n"); } const error_category& future_category() { static __future_error_category __f; return __f; } future_error::future_error(error_code __ec) : logic_error(__ec.message()), __ec_(__ec) { } future_error::~future_error() _NOEXCEPT { } void __assoc_sub_state::__on_zero_shared() _NOEXCEPT { delete this; } void __assoc_sub_state::set_value() { unique_lock<mutex> __lk(__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __state_ |= __constructed | ready; __lk.unlock(); __cv_.notify_all(); } void __assoc_sub_state::set_value_at_thread_exit() { unique_lock<mutex> __lk(__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __state_ |= __constructed; __thread_local_data()->__make_ready_at_thread_exit(this); __lk.unlock(); } void __assoc_sub_state::set_exception(exception_ptr __p) { unique_lock<mutex> __lk(__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __exception_ = __p; __state_ |= ready; __lk.unlock(); __cv_.notify_all(); } void __assoc_sub_state::set_exception_at_thread_exit(exception_ptr __p) { unique_lock<mutex> __lk(__mut_); #ifndef _LIBCPP_NO_EXCEPTIONS if (__has_value()) throw future_error(make_error_code(future_errc::promise_already_satisfied)); #endif __exception_ = __p; __thread_local_data()->__make_ready_at_thread_exit(this); __lk.unlock(); } void __assoc_sub_state::__make_ready() { unique_lock<mutex> __lk(__mut_); __state_ |= ready; __lk.unlock(); __cv_.notify_all(); } void __assoc_sub_state::copy() { unique_lock<mutex> __lk(__mut_); __sub_wait(__lk); if (__exception_ != nullptr) rethrow_exception(__exception_); } void __assoc_sub_state::wait() { unique_lock<mutex> __lk(__mut_); __sub_wait(__lk); } void __assoc_sub_state::__sub_wait(unique_lock<mutex>& __lk) { if (!__is_ready()) { if (__state_ & deferred) { __state_ &= ~deferred; __lk.unlock(); __execute(); } else while (!__is_ready()) __cv_.wait(__lk); } } void __assoc_sub_state::__execute() { #ifndef _LIBCPP_NO_EXCEPTIONS throw future_error(make_error_code(future_errc::no_state)); #endif } future<void>::future(__assoc_sub_state* __state) : __state_(__state) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_->__has_future_attached()) throw future_error(make_error_code(future_errc::future_already_retrieved)); #endif __state_->__add_shared(); __state_->__set_future_attached(); } future<void>::~future() { if (__state_) __state_->__release_shared(); } void future<void>::get() { unique_ptr<__shared_count, __release_shared_count> __(__state_); __assoc_sub_state* __s = __state_; __state_ = nullptr; __s->copy(); } promise<void>::promise() : __state_(new __assoc_sub_state) { } promise<void>::~promise() { if (__state_) { if (!__state_->__has_value() && __state_->use_count() > 1) __state_->set_exception(make_exception_ptr( future_error(make_error_code(future_errc::broken_promise)) )); __state_->__release_shared(); } } future<void> promise<void>::get_future() { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif return future<void>(__state_); } void promise<void>::set_value() { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value(); } void promise<void>::set_exception(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception(__p); } void promise<void>::set_value_at_thread_exit() { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_value_at_thread_exit(); } void promise<void>::set_exception_at_thread_exit(exception_ptr __p) { #ifndef _LIBCPP_NO_EXCEPTIONS if (__state_ == nullptr) throw future_error(make_error_code(future_errc::no_state)); #endif __state_->set_exception_at_thread_exit(__p); } shared_future<void>::~shared_future() { if (__state_) __state_->__release_shared(); } shared_future<void>& shared_future<void>::operator=(const shared_future& __rhs) { if (__rhs.__state_) __rhs.__state_->__add_shared(); if (__state_) __state_->__release_shared(); __state_ = __rhs.__state_; return *this; } _LIBCPP_END_NAMESPACE_STD
// // FILE NAME: TestEvents.cpp // // AUTHOR: Dean Roddey // // CREATED: 09/21/2009 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the main implementation file of the test program. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // ----------------------------------------------------------------------------- // Include underlying headers // ----------------------------------------------------------------------------- #include "TestEvents.hpp" // ---------------------------------------------------------------------------- // Magic macros // ---------------------------------------------------------------------------- RTTIDecls(TEventTestApp,TTestFWApp) // --------------------------------------------------------------------------- // CLASS: TEventTestApp // PREFIX: tfwapp // --------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // TEventTestApp: Constructor and Destructor // ---------------------------------------------------------------------------- TEventTestApp::TEventTestApp() { } TEventTestApp::~TEventTestApp() { } // ---------------------------------------------------------------------------- // TEventTestApp: Public, inherited methods // ---------------------------------------------------------------------------- tCIDLib::TBoolean TEventTestApp::bInitialize(TString&) { // Nothing to do return kCIDLib::True; } // Load up our tests on our parent class tCIDLib::TVoid TEventTestApp::LoadTests() { AddTest(new TTest_Scheduled1); AddTest(new TTest_TrigEvFilters); AddTest(new TTest_TrigEvStream); } tCIDLib::TVoid TEventTestApp::PostTest(const TTestFWTest&) { // Nothing to do } tCIDLib::TVoid TEventTestApp::PreTest(const TTestFWTest&) { // Nothing to do } tCIDLib::TVoid TEventTestApp::Terminate() { // Nothing to do } // ---------------------------------------------------------------------------- // Declare the test app object // ---------------------------------------------------------------------------- TEventTestApp tfwappCQCKit; // ---------------------------------------------------------------------------- // Include magic main module code. We just point it at the test thread // entry point of the test framework app class. // ---------------------------------------------------------------------------- CIDLib_MainModule ( TThread ( L"TestThread" , TMemberFunc<TEventTestApp>(&tfwappCQCKit, &TEventTestApp::eTestThread) ) )
// Copyright (c) 2014-2017 The Dash Core developers #include "cachemap.h" #include "test/test_soom.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(cachemap_tests, BasicTestingSetup) bool Compare(const CacheMap<int,int>& map1, const CacheMap<int,int>& map2 ) { if(map1.GetMaxSize() != map2.GetMaxSize()) { return false; } if(map1.GetSize() != map2.GetSize()) { return false; } const CacheMap<int,int>::list_t& items1 = map1.GetItemList(); for(CacheMap<int,int>::list_cit it = items1.begin(); it != items1.end(); ++it) { if(!map2.HasKey(it->key)) { return false; } int val = 0; if(!map2.Get(it->key, val)) { return false; } if(it->value != val) { return false; } } const CacheMap<int,int>::list_t& items2 = map2.GetItemList(); for(CacheMap<int,int>::list_cit it = items2.begin(); it != items2.end(); ++it) { if(!map1.HasKey(it->key)) { return false; } int val = 0; if(!map1.Get(it->key, val)) { return false; } if(it->value != val) { return false; } } return true; } BOOST_AUTO_TEST_CASE(cachemap_test) { // create a CacheMap limited to 10 items CacheMap<int,int> mapTest1(10); // check that the max size is 10 BOOST_CHECK(mapTest1.GetMaxSize() == 10); // check that the size is 0 BOOST_CHECK(mapTest1.GetSize() == 0); // insert (-1, -1) mapTest1.Insert(-1, -1); // make sure that the size is updated BOOST_CHECK(mapTest1.GetSize() == 1); // make sure the map contains the key BOOST_CHECK(mapTest1.HasKey(-1) == true); // add 10 items for(int i = 0; i < 10; ++i) { mapTest1.Insert(i, i); } // check that the size is 10 BOOST_CHECK(mapTest1.GetSize() == 10); // check that the map contains the expected items for(int i = 0; i < 10; ++i) { int nVal = 0; BOOST_CHECK(mapTest1.Get(i, nVal) == true); BOOST_CHECK(nVal == i); } // check that the map no longer contains the first item BOOST_CHECK(mapTest1.HasKey(-1) == false); // erase an item mapTest1.Erase(5); // check the size BOOST_CHECK(mapTest1.GetSize() == 9); // check that the map no longer contains the item BOOST_CHECK(mapTest1.HasKey(5) == false); // check that the map contains the expected items int expected[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 }; for(size_t i = 0; i < 9; ++i) { int nVal = 0; int eVal = expected[i]; BOOST_CHECK(mapTest1.Get(eVal, nVal) == true); BOOST_CHECK(nVal == eVal); } // test serialization CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << mapTest1; CacheMap<int,int> mapTest2; ss >> mapTest2; BOOST_CHECK(Compare(mapTest1, mapTest2)); // test copy constructor CacheMap<int,int> mapTest3(mapTest1); BOOST_CHECK(Compare(mapTest1, mapTest3)); // test assignment operator CacheMap<int,int> mapTest4; mapTest4 = mapTest1; BOOST_CHECK(Compare(mapTest1, mapTest4)); } BOOST_AUTO_TEST_SUITE_END()
/* ***************************************************************************** * A.L.E (Arcade Learning Environment) * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and * the Reinforcement Learning and Artificial Intelligence Laboratory * Released under the GNU General Public License; see License.txt for details. * * Based on: Stella -- "An Atari 2600 VCS Emulator" * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team * * ***************************************************************************** */ #ifndef __JAMESBOND_HPP__ #define __JAMESBOND_HPP__ #include "../RomSettings.hpp" /* RL wrapper for James Bond */ class JamesBondSettings : public RomSettings { public: JamesBondSettings(); // reset void reset(); // is end of game bool isTerminal() const; // get the most recently observed reward reward_t getReward() const; // the rom-name const char* rom() const { return "jamesbond"; } // create a new instance of the rom RomSettings* clone() const; // is an action part of the minimal set? bool isMinimal(const Action& a) const; // process the latest information from ALE void step(const System& system); // saves the state of the rom settings void saveState(Serializer & ser); // loads the state of the rom settings void loadState(Deserializer & ser); private: bool m_terminal; reward_t m_reward; reward_t m_score; }; #endif // __JAMESBOND_HPP__
// // read.hpp // ~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_READ_HPP #define ASIO_READ_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include <cstddef> #include "asio/async_result.hpp" #include "asio/basic_streambuf_fwd.hpp" #include "asio/buffer.hpp" #include "asio/error.hpp" #include "asio/detail/push_options.hpp" namespace asio { /** * @defgroup read asio::read * * @brief Attempt to read a certain amount of data from a stream before * returning. */ /*@{*/ /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size), ec); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename MutableBufferSequence> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, asio::error_code& ec, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::read(s, asio::buffer(data, size), * asio::transfer_at_least(32)); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename MutableBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, asio::error_code& ec, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename DynamicBufferSequence> std::size_t read(SyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read( * s, buffers, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename DynamicBufferSequence> std::size_t read(SyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, asio::error_code& ec, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncReadStream, typename DynamicBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, CompletionCondition completion_condition, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename DynamicBufferSequence, typename CompletionCondition> std::size_t read(SyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, CompletionCondition completion_condition, asio::error_code& ec, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); #if !defined(ASIO_NO_IOSTREAM) /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. * * @note This overload is equivalent to calling: * @code asio::read( * s, b, * asio::transfer_all()); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes transferred. * * @note This overload is equivalent to calling: * @code asio::read( * s, b, * asio::transfer_all(), ec); @endcode */ template <typename SyncReadStream, typename Allocator> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, asio::error_code& ec); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @returns The number of bytes transferred. * * @throws asio::system_error Thrown on failure. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition); /// Attempt to read a certain amount of data from a stream before returning. /** * This function is used to read a certain number of bytes of data from a * stream. The call will block until one of the following conditions is true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * read_some function. * * @param s The stream from which the data is to be read. The type must support * the SyncReadStream concept. * * @param b The basic_streambuf object into which the data will be read. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's read_some function. * * @param ec Set to indicate what error occurred, if any. * * @returns The number of bytes read. If an error occurs, returns the total * number of bytes successfully transferred prior to the error. */ template <typename SyncReadStream, typename Allocator, typename CompletionCondition> std::size_t read(SyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, asio::error_code& ec); #endif // !defined(ASIO_NO_IOSTREAM) /*@}*/ /** * @defgroup async_read asio::async_read * * @brief Start an asynchronous operation to read a certain amount of data from * a stream. */ /*@{*/ /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code * asio::async_read(s, asio::buffer(data, size), handler); * @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. * * @note This overload is equivalent to calling: * @code asio::async_read( * s, buffers, * asio::transfer_all(), * handler); @endcode */ template <typename AsyncReadStream, typename MutableBufferSequence, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, ASIO_MOVE_ARG(ReadHandler) handler, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffers are full. That is, the bytes transferred is equal to * the sum of the buffer sizes. * * @li The completion_condition function object returns 0. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers One or more buffers into which the data will be read. The sum * of the buffer sizes indicates the maximum number of bytes to read from the * stream. Although the buffers object may be copied as necessary, ownership of * the underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @par Example * To read into a single data buffer use the @ref buffer function as follows: * @code asio::async_read(s, * asio::buffer(data, size), * asio::transfer_at_least(32), * handler); @endcode * See the @ref buffer documentation for information on reading into multiple * buffers in one go, and how to use it with arrays, boost::array or * std::vector. */ template <typename AsyncReadStream, typename MutableBufferSequence, typename CompletionCondition, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, const MutableBufferSequence& buffers, CompletionCondition completion_condition, ASIO_MOVE_ARG(ReadHandler) handler, typename enable_if< is_mutable_buffer_sequence<MutableBufferSequence>::value >::type* = 0); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note This overload is equivalent to calling: * @code asio::async_read( * s, buffers, * asio::transfer_all(), * handler); @endcode */ template <typename AsyncReadStream, typename DynamicBufferSequence, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, ASIO_MOVE_ARG(ReadHandler) handler, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The specified dynamic buffer sequence is full (that is, it has reached * maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param buffers The dynamic buffer sequence into which the data will be read. * Although the buffers object may be copied as necessary, ownership of the * underlying memory blocks is retained by the caller, which must guarantee * that they remain valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). */ template <typename AsyncReadStream, typename DynamicBufferSequence, typename CompletionCondition, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, ASIO_MOVE_ARG(DynamicBufferSequence) buffers, CompletionCondition completion_condition, ASIO_MOVE_ARG(ReadHandler) handler, typename enable_if< is_dynamic_buffer_sequence<DynamicBufferSequence>::value >::type* = 0); #if !defined(ASIO_NO_IOSTREAM) /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li An error occurred. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). * * @note This overload is equivalent to calling: * @code asio::async_read( * s, b, * asio::transfer_all(), * handler); @endcode */ template <typename AsyncReadStream, typename Allocator, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, ASIO_MOVE_ARG(ReadHandler) handler); /// Start an asynchronous operation to read a certain amount of data from a /// stream. /** * This function is used to asynchronously read a certain number of bytes of * data from a stream. The function call always returns immediately. The * asynchronous operation will continue until one of the following conditions is * true: * * @li The supplied buffer is full (that is, it has reached maximum size). * * @li The completion_condition function object returns 0. * * This operation is implemented in terms of zero or more calls to the stream's * async_read_some function, and is known as a <em>composed operation</em>. The * program must ensure that the stream performs no other read operations (such * as async_read, the stream's async_read_some function, or any other composed * operations that perform reads) until this operation completes. * * @param s The stream from which the data is to be read. The type must support * the AsyncReadStream concept. * * @param b A basic_streambuf object into which the data will be read. Ownership * of the streambuf is retained by the caller, which must guarantee that it * remains valid until the handler is called. * * @param completion_condition The function object to be called to determine * whether the read operation is complete. The signature of the function object * must be: * @code std::size_t completion_condition( * // Result of latest async_read_some operation. * const asio::error_code& error, * * // Number of bytes transferred so far. * std::size_t bytes_transferred * ); @endcode * A return value of 0 indicates that the read operation is complete. A non-zero * return value indicates the maximum number of bytes to be read on the next * call to the stream's async_read_some function. * * @param handler The handler to be called when the read operation completes. * Copies will be made of the handler as required. The function signature of the * handler must be: * @code void handler( * const asio::error_code& error, // Result of operation. * * std::size_t bytes_transferred // Number of bytes copied into the * // buffers. If an error occurred, * // this will be the number of * // bytes successfully transferred * // prior to the error. * ); @endcode * Regardless of whether the asynchronous operation completes immediately or * not, the handler will not be invoked from within this function. Invocation of * the handler will be performed in a manner equivalent to using * asio::io_service::post(). */ template <typename AsyncReadStream, typename Allocator, typename CompletionCondition, typename ReadHandler> ASIO_INITFN_RESULT_TYPE(ReadHandler, void (asio::error_code, std::size_t)) async_read(AsyncReadStream& s, basic_streambuf<Allocator>& b, CompletionCondition completion_condition, ASIO_MOVE_ARG(ReadHandler) handler); #endif // !defined(ASIO_NO_IOSTREAM) /*@}*/ } // namespace asio #include "asio/detail/pop_options.hpp" #include "asio/impl/read.hpp" #endif // ASIO_READ_HPP
/* 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/lite/delegates/gpu/common/model.h" #include <initializer_list> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> namespace tflite { namespace gpu { namespace { using ::testing::UnorderedElementsAre; TEST(Model, SingleNode) { // graph_input -> node -> graph_output GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node->id, graph_output->id).ok()); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node)); EXPECT_THAT(graph.values(), UnorderedElementsAre(graph_input, graph_output)); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.FindInputs(node->id), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.FindOutputs(node->id), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.FindConsumers(graph_input->id), UnorderedElementsAre(node)); EXPECT_THAT(graph.FindProducer(graph_output->id), ::testing::Eq(node)); EXPECT_THAT(graph.FindConsumers(graph_output->id), UnorderedElementsAre()); EXPECT_THAT(graph.FindProducer(graph_input->id), ::testing::Eq(nullptr)); } TEST(Model, SingleNodeMultipleOutputs) { // graph_input -> node -> (graph_output1, graph_output2) GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output1 = graph.NewValue(); Value<TensorRefFloat32>* graph_output2 = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node->id, graph_output1->id).ok()); ASSERT_TRUE(graph.SetProducer(node->id, graph_output2->id).ok()); EXPECT_THAT(graph.FindOutputs(node->id), UnorderedElementsAre(graph_output1, graph_output2)); EXPECT_THAT(graph.FindProducer(graph_output1->id), ::testing::Eq(node)); EXPECT_THAT(graph.FindProducer(graph_output2->id), ::testing::Eq(node)); } TEST(Model, SetSameConsumer) { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input->id).ok()); EXPECT_FALSE(graph.AddConsumer(node->id, graph_input->id).ok()); } TEST(Model, RemoveConsumer) { // (graph_input1, graph_input2) -> node GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_input1 = graph.NewValue(); Value<TensorRefFloat32>* graph_input2 = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input1->id).ok()); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input2->id).ok()); EXPECT_THAT(graph.FindConsumers(graph_input1->id), UnorderedElementsAre(node)); EXPECT_THAT(graph.FindConsumers(graph_input2->id), UnorderedElementsAre(node)); EXPECT_THAT(graph.FindInputs(node->id), UnorderedElementsAre(graph_input1, graph_input2)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre()); // Now remove graph_input1 ASSERT_TRUE(graph.RemoveConsumer(node->id, graph_input1->id).ok()); EXPECT_THAT(graph.FindConsumers(graph_input1->id), UnorderedElementsAre()); EXPECT_THAT(graph.FindInputs(node->id), UnorderedElementsAre(graph_input2)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_input1)); // Can not remove it twice ASSERT_FALSE(graph.RemoveConsumer(node->id, graph_input1->id).ok()); } TEST(Model, SetSameProducer) { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); ASSERT_TRUE(graph.SetProducer(node->id, graph_output->id).ok()); EXPECT_FALSE(graph.SetProducer(node->id, graph_output->id).ok()); } TEST(Model, RemoveProducer) { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); ASSERT_TRUE(graph.SetProducer(node->id, graph_output->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre()); EXPECT_THAT(graph.FindProducer(graph_output->id), ::testing::Eq(node)); ASSERT_TRUE(graph.RemoveProducer(graph_output->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.FindProducer(graph_output->id), ::testing::Eq(nullptr)); // Can not remove producer twice ASSERT_FALSE(graph.RemoveProducer(graph_output->id).ok()); } TEST(Model, RemoveSimpleNodeDegenerateCase) { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node->id, graph_output->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node)); ASSERT_TRUE(RemoveOneInputOneOutputNode(&graph, node).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre()); EXPECT_THAT(graph.outputs(), UnorderedElementsAre()); EXPECT_THAT(graph.nodes(), UnorderedElementsAre()); } TEST(Model, RemoveSimpleNodeNoPreviousNode) { GraphFloat32 graph; Node* simple_node = graph.NewNode(); Node* consumer_node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(simple_node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(simple_node->id, value->id).ok()); ASSERT_TRUE(graph.AddConsumer(consumer_node->id, value->id).ok()); ASSERT_TRUE(graph.SetProducer(consumer_node->id, graph_output->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(simple_node, consumer_node)); ASSERT_TRUE(RemoveOneInputOneOutputNode(&graph, simple_node).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(consumer_node)); } TEST(Model, RemoveSimpleNodeNoAfterNodes) { GraphFloat32 graph; Node* simple_node = graph.NewNode(); Node* producer_node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(simple_node->id, value->id).ok()); ASSERT_TRUE(graph.SetProducer(simple_node->id, graph_output->id).ok()); ASSERT_TRUE(graph.AddConsumer(producer_node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(producer_node->id, value->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(simple_node, producer_node)); ASSERT_TRUE(RemoveOneInputOneOutputNode(&graph, simple_node).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(producer_node)); } TEST(Model, RemoveSimpleNodeGeneralCase) { GraphFloat32 graph; Node* simple_node = graph.NewNode(); Node* producer_node = graph.NewNode(); Node* consumer_node = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); Value<TensorRefFloat32>* value0 = graph.NewValue(); Value<TensorRefFloat32>* value1 = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(producer_node->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(producer_node->id, value0->id).ok()); ASSERT_TRUE(graph.AddConsumer(simple_node->id, value0->id).ok()); ASSERT_TRUE(graph.SetProducer(simple_node->id, value1->id).ok()); ASSERT_TRUE(graph.AddConsumer(consumer_node->id, value1->id).ok()); ASSERT_TRUE(graph.SetProducer(consumer_node->id, graph_output->id).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(simple_node, producer_node, consumer_node)); ASSERT_TRUE(RemoveOneInputOneOutputNode(&graph, simple_node).ok()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(producer_node, consumer_node)); } TEST(Model, CircularDependency) { { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node->id, value->id).ok()); EXPECT_FALSE(graph.SetProducer(node->id, value->id).ok()); } { GraphFloat32 graph; Node* node = graph.NewNode(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.SetProducer(node->id, value->id).ok()); EXPECT_FALSE(graph.AddConsumer(node->id, value->id).ok()); } } TEST(Model, ReassignValue) { // Before: // graph_input -> node1 -> graph_output // \ -> node2 GraphFloat32 graph; Node* node1 = graph.NewNode(); Node* node2 = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node1->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node1->id, graph_output->id).ok()); ASSERT_TRUE(graph.AddConsumer(node2->id, graph_input->id).ok()); // After: // graph_input -> node1 // \ -> node2 -> graph_output ASSERT_TRUE(graph.SetProducer(node2->id, graph_output->id).ok()); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node1, node2)); EXPECT_THAT(graph.FindInputs(node1->id), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.FindInputs(node2->id), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.FindOutputs(node1->id), UnorderedElementsAre()); EXPECT_THAT(graph.FindOutputs(node2->id), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.FindConsumers(graph_input->id), UnorderedElementsAre(node1, node2)); EXPECT_THAT(graph.FindProducer(graph_output->id), ::testing::Eq(node2)); EXPECT_THAT(graph.FindConsumers(graph_output->id), UnorderedElementsAre()); } TEST(Model, DeleteValue) { // graph_input -> node1 -> value -> node2 -> graph_output GraphFloat32 graph; Node* node1 = graph.NewNode(); Node* node2 = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node1->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node1->id, value->id).ok()); ASSERT_TRUE(graph.AddConsumer(node2->id, value->id).ok()); ASSERT_TRUE(graph.SetProducer(node2->id, graph_output->id).ok()); EXPECT_THAT(graph.values(), UnorderedElementsAre(graph_input, graph_output, value)); EXPECT_THAT(graph.FindConsumers(value->id), UnorderedElementsAre(node2)); EXPECT_THAT(graph.FindProducer(value->id), ::testing::Eq(node1)); EXPECT_THAT(graph.FindInputs(node2->id), UnorderedElementsAre(value)); EXPECT_THAT(graph.FindOutputs(node1->id), UnorderedElementsAre(value)); ASSERT_TRUE(graph.DeleteValue(value->id).ok()); value = nullptr; EXPECT_THAT(graph.values(), UnorderedElementsAre(graph_input, graph_output)); EXPECT_THAT(graph.FindInputs(node2->id), UnorderedElementsAre()); EXPECT_THAT(graph.FindOutputs(node1->id), UnorderedElementsAre()); ASSERT_TRUE(graph.DeleteValue(graph_input->id).ok()); graph_input = nullptr; EXPECT_THAT(graph.values(), UnorderedElementsAre(graph_output)); EXPECT_THAT(graph.inputs(), UnorderedElementsAre()); EXPECT_THAT(graph.FindInputs(node1->id), UnorderedElementsAre()); ASSERT_TRUE(graph.DeleteValue(graph_output->id).ok()); graph_output = nullptr; EXPECT_THAT(graph.values(), UnorderedElementsAre()); EXPECT_THAT(graph.outputs(), UnorderedElementsAre()); EXPECT_THAT(graph.FindOutputs(node2->id), UnorderedElementsAre()); } TEST(Model, DeleteNode) { // graph_input -> node1 -> value -> node2 -> graph_output // \-> node3 -> graph_output2 GraphFloat32 graph; Node* node1 = graph.NewNode(); Node* node2 = graph.NewNode(); Node* node3 = graph.NewNode(); Value<TensorRefFloat32>* graph_input = graph.NewValue(); Value<TensorRefFloat32>* graph_output = graph.NewValue(); Value<TensorRefFloat32>* graph_output2 = graph.NewValue(); Value<TensorRefFloat32>* value = graph.NewValue(); ASSERT_TRUE(graph.AddConsumer(node1->id, graph_input->id).ok()); ASSERT_TRUE(graph.SetProducer(node1->id, value->id).ok()); ASSERT_TRUE(graph.AddConsumer(node2->id, value->id).ok()); ASSERT_TRUE(graph.AddConsumer(node3->id, value->id).ok()); ASSERT_TRUE(graph.SetProducer(node2->id, graph_output->id).ok()); ASSERT_TRUE(graph.SetProducer(node3->id, graph_output2->id).ok()); EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node1, node2, node3)); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output, graph_output2)); EXPECT_THAT(graph.FindConsumers(value->id), UnorderedElementsAre(node2, node3)); EXPECT_THAT(graph.FindProducer(value->id), ::testing::Eq(node1)); EXPECT_THAT(graph.FindInputs(node2->id), UnorderedElementsAre(value)); EXPECT_THAT(graph.FindInputs(node3->id), UnorderedElementsAre(value)); // graph_input -> node1 -> value -> node2 -> graph_output // graph_output2 ASSERT_TRUE(graph.DeleteNode(node3->id).ok()); node3 = nullptr; EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node1, node2)); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_input, graph_output2)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output, graph_output2)); EXPECT_THAT(graph.FindConsumers(value->id), UnorderedElementsAre(node2)); // value -> node2 -> graph_output // graph_input // graph_output2 ASSERT_TRUE(graph.DeleteNode(node1->id).ok()); node1 = nullptr; EXPECT_THAT(graph.nodes(), UnorderedElementsAre(node2)); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(value, graph_output2, graph_input)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_input, graph_output, graph_output2)); EXPECT_THAT(graph.FindConsumers(value->id), UnorderedElementsAre(node2)); EXPECT_THAT(graph.FindProducer(value->id), ::testing::Eq(nullptr)); ASSERT_TRUE(graph.DeleteNode(node2->id).ok()); node2 = nullptr; EXPECT_THAT(graph.nodes(), UnorderedElementsAre()); EXPECT_THAT(graph.inputs(), UnorderedElementsAre(graph_output, graph_output2, graph_input, value)); EXPECT_THAT(graph.outputs(), UnorderedElementsAre(graph_output, graph_output2, graph_input, value)); EXPECT_THAT(graph.FindConsumers(value->id), UnorderedElementsAre()); EXPECT_THAT(graph.FindProducer(value->id), ::testing::Eq(nullptr)); } } // namespace } // namespace gpu } // namespace tflite
/* * UAVCAN data structure definition for libuavcan. * * Autogenerated, do not edit. * * Source file: /mnt/c/Users/BrianTaylor/Documents/Software/dronecan/dsdl/uavcan/protocol/file/40.BeginFirmwareUpdate.uavcan */ #ifndef UAVCAN_PROTOCOL_FILE_BEGINFIRMWAREUPDATE_HPP_INCLUDED #define UAVCAN_PROTOCOL_FILE_BEGINFIRMWAREUPDATE_HPP_INCLUDED #include <uavcan/build_config.hpp> #include <uavcan/node/global_data_type_registry.hpp> #include <uavcan/marshal/types.hpp> #include <uavcan/protocol/file/Path.hpp> /******************************* Source text ********************************** # # This service initiates firmware update on a remote node. # # The node that is being updated (slave) will retrieve the firmware image file 'image_file_remote_path' from the node # 'source_node_id' using the file read service, then it will update the firmware and reboot. # # The slave can explicitly reject this request if it is not possible to update the firmware at the moment # (e.g. if the node is busy). # # If the slave node accepts this request, the initiator will get a response immediately, before the update process # actually begins. # # While the firmware is being updated, the slave should set its mode (uavcan.protocol.NodeStatus.mode) to # MODE_SOFTWARE_UPDATE. # uint8 source_node_id # If this field is zero, the caller's Node ID will be used instead. Path image_file_remote_path --- # # Other error codes may be added in the future. # uint8 ERROR_OK = 0 uint8 ERROR_INVALID_MODE = 1 # Cannot perform the update in the current operating mode or state. uint8 ERROR_IN_PROGRESS = 2 # Firmware update is already in progress, and the slave doesn't want to restart. uint8 ERROR_UNKNOWN = 255 uint8 error uint8[<128] optional_error_message # Detailed description of the error. ******************************************************************************/ /********************* DSDL signature source definition *********************** uavcan.protocol.file.BeginFirmwareUpdate saturated uint8 source_node_id uavcan.protocol.file.Path image_file_remote_path --- saturated uint8 error saturated uint8[<=127] optional_error_message ******************************************************************************/ #undef source_node_id #undef image_file_remote_path #undef error #undef optional_error_message #undef ERROR_OK #undef ERROR_INVALID_MODE #undef ERROR_IN_PROGRESS #undef ERROR_UNKNOWN namespace uavcan { namespace protocol { namespace file { struct UAVCAN_EXPORT BeginFirmwareUpdate_ { template <int _tmpl> struct Request_ { typedef const Request_<_tmpl>& ParameterType; typedef Request_<_tmpl>& ReferenceType; struct ConstantTypes { }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > source_node_id; typedef ::uavcan::protocol::file::Path image_file_remote_path; }; enum { MinBitLen = FieldTypes::source_node_id::MinBitLen + FieldTypes::image_file_remote_path::MinBitLen }; enum { MaxBitLen = FieldTypes::source_node_id::MaxBitLen + FieldTypes::image_file_remote_path::MaxBitLen }; // Constants // Fields typename ::uavcan::StorageType< typename FieldTypes::source_node_id >::Type source_node_id; typename ::uavcan::StorageType< typename FieldTypes::image_file_remote_path >::Type image_file_remote_path; Request_() : source_node_id() , image_file_remote_path() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<1616 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; template <int _tmpl> struct Response_ { typedef const Response_<_tmpl>& ParameterType; typedef Response_<_tmpl>& ReferenceType; struct ConstantTypes { typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ERROR_OK; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ERROR_INVALID_MODE; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ERROR_IN_PROGRESS; typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > ERROR_UNKNOWN; }; struct FieldTypes { typedef ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate > error; typedef ::uavcan::Array< ::uavcan::IntegerSpec< 8, ::uavcan::SignednessUnsigned, ::uavcan::CastModeSaturate >, ::uavcan::ArrayModeDynamic, 127 > optional_error_message; }; enum { MinBitLen = FieldTypes::error::MinBitLen + FieldTypes::optional_error_message::MinBitLen }; enum { MaxBitLen = FieldTypes::error::MaxBitLen + FieldTypes::optional_error_message::MaxBitLen }; // Constants static const typename ::uavcan::StorageType< typename ConstantTypes::ERROR_OK >::Type ERROR_OK; // 0 static const typename ::uavcan::StorageType< typename ConstantTypes::ERROR_INVALID_MODE >::Type ERROR_INVALID_MODE; // 1 static const typename ::uavcan::StorageType< typename ConstantTypes::ERROR_IN_PROGRESS >::Type ERROR_IN_PROGRESS; // 2 static const typename ::uavcan::StorageType< typename ConstantTypes::ERROR_UNKNOWN >::Type ERROR_UNKNOWN; // 255 // Fields typename ::uavcan::StorageType< typename FieldTypes::error >::Type error; typename ::uavcan::StorageType< typename FieldTypes::optional_error_message >::Type optional_error_message; Response_() : error() , optional_error_message() { ::uavcan::StaticAssert<_tmpl == 0>::check(); // Usage check #if UAVCAN_DEBUG /* * Cross-checking MaxBitLen provided by the DSDL compiler. * This check shall never be performed in user code because MaxBitLen value * actually depends on the nested types, thus it is not invariant. */ ::uavcan::StaticAssert<1031 == MaxBitLen>::check(); #endif } bool operator==(ParameterType rhs) const; bool operator!=(ParameterType rhs) const { return !operator==(rhs); } /** * This comparison is based on @ref uavcan::areClose(), which ensures proper comparison of * floating point fields at any depth. */ bool isClose(ParameterType rhs) const; static int encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); static int decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode = ::uavcan::TailArrayOptEnabled); }; typedef Request_<0> Request; typedef Response_<0> Response; /* * Static type info */ enum { DataTypeKind = ::uavcan::DataTypeKindService }; enum { DefaultDataTypeID = 40 }; static const char* getDataTypeFullName() { return "uavcan.protocol.file.BeginFirmwareUpdate"; } static void extendDataTypeSignature(::uavcan::DataTypeSignature& signature) { signature.extend(getDataTypeSignature()); } static ::uavcan::DataTypeSignature getDataTypeSignature(); private: BeginFirmwareUpdate_(); // Don't create objects of this type. Use Request/Response instead. }; /* * Out of line struct method definitions */ template <int _tmpl> bool BeginFirmwareUpdate_::Request_<_tmpl>::operator==(ParameterType rhs) const { return source_node_id == rhs.source_node_id && image_file_remote_path == rhs.image_file_remote_path; } template <int _tmpl> bool BeginFirmwareUpdate_::Request_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(source_node_id, rhs.source_node_id) && ::uavcan::areClose(image_file_remote_path, rhs.image_file_remote_path); } template <int _tmpl> int BeginFirmwareUpdate_::Request_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::source_node_id::encode(self.source_node_id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::image_file_remote_path::encode(self.image_file_remote_path, codec, tao_mode); return res; } template <int _tmpl> int BeginFirmwareUpdate_::Request_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::source_node_id::decode(self.source_node_id, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::image_file_remote_path::decode(self.image_file_remote_path, codec, tao_mode); return res; } template <int _tmpl> bool BeginFirmwareUpdate_::Response_<_tmpl>::operator==(ParameterType rhs) const { return error == rhs.error && optional_error_message == rhs.optional_error_message; } template <int _tmpl> bool BeginFirmwareUpdate_::Response_<_tmpl>::isClose(ParameterType rhs) const { return ::uavcan::areClose(error, rhs.error) && ::uavcan::areClose(optional_error_message, rhs.optional_error_message); } template <int _tmpl> int BeginFirmwareUpdate_::Response_<_tmpl>::encode(ParameterType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::error::encode(self.error, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::optional_error_message::encode(self.optional_error_message, codec, tao_mode); return res; } template <int _tmpl> int BeginFirmwareUpdate_::Response_<_tmpl>::decode(ReferenceType self, ::uavcan::ScalarCodec& codec, ::uavcan::TailArrayOptimizationMode tao_mode) { (void)self; (void)codec; (void)tao_mode; int res = 1; res = FieldTypes::error::decode(self.error, codec, ::uavcan::TailArrayOptDisabled); if (res <= 0) { return res; } res = FieldTypes::optional_error_message::decode(self.optional_error_message, codec, tao_mode); return res; } /* * Out of line type method definitions */ inline ::uavcan::DataTypeSignature BeginFirmwareUpdate_::getDataTypeSignature() { ::uavcan::DataTypeSignature signature(0x36A8B8AA5453257BULL); Request::FieldTypes::source_node_id::extendDataTypeSignature(signature); Request::FieldTypes::image_file_remote_path::extendDataTypeSignature(signature); Response::FieldTypes::error::extendDataTypeSignature(signature); Response::FieldTypes::optional_error_message::extendDataTypeSignature(signature); return signature; } /* * Out of line constant definitions */ template <int _tmpl> const typename ::uavcan::StorageType< typename BeginFirmwareUpdate_::Response_<_tmpl>::ConstantTypes::ERROR_OK >::Type BeginFirmwareUpdate_::Response_<_tmpl>::ERROR_OK = 0U; // 0 template <int _tmpl> const typename ::uavcan::StorageType< typename BeginFirmwareUpdate_::Response_<_tmpl>::ConstantTypes::ERROR_INVALID_MODE >::Type BeginFirmwareUpdate_::Response_<_tmpl>::ERROR_INVALID_MODE = 1U; // 1 template <int _tmpl> const typename ::uavcan::StorageType< typename BeginFirmwareUpdate_::Response_<_tmpl>::ConstantTypes::ERROR_IN_PROGRESS >::Type BeginFirmwareUpdate_::Response_<_tmpl>::ERROR_IN_PROGRESS = 2U; // 2 template <int _tmpl> const typename ::uavcan::StorageType< typename BeginFirmwareUpdate_::Response_<_tmpl>::ConstantTypes::ERROR_UNKNOWN >::Type BeginFirmwareUpdate_::Response_<_tmpl>::ERROR_UNKNOWN = 255U; // 255 /* * Final typedef */ typedef BeginFirmwareUpdate_ BeginFirmwareUpdate; namespace { const ::uavcan::DefaultDataTypeRegistrator< ::uavcan::protocol::file::BeginFirmwareUpdate > _uavcan_gdtr_registrator_BeginFirmwareUpdate; } } // Namespace file } // Namespace protocol } // Namespace uavcan /* * YAML streamer specialization */ namespace uavcan { template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Request > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Request::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Request >::stream(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Request::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "source_node_id: "; YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Request::FieldTypes::source_node_id >::stream(s, obj.source_node_id, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "image_file_remote_path: "; YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Request::FieldTypes::image_file_remote_path >::stream(s, obj.image_file_remote_path, level + 1); } template <> class UAVCAN_EXPORT YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Response > { public: template <typename Stream> static void stream(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Response::ParameterType obj, const int level); }; template <typename Stream> void YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Response >::stream(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Response::ParameterType obj, const int level) { (void)s; (void)obj; (void)level; if (level > 0) { s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } } s << "error: "; YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Response::FieldTypes::error >::stream(s, obj.error, level + 1); s << '\n'; for (int pos = 0; pos < level; pos++) { s << " "; } s << "optional_error_message: "; YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Response::FieldTypes::optional_error_message >::stream(s, obj.optional_error_message, level + 1); } } namespace uavcan { namespace protocol { namespace file { template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Request::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Request >::stream(s, obj, 0); return s; } template <typename Stream> inline Stream& operator<<(Stream& s, ::uavcan::protocol::file::BeginFirmwareUpdate::Response::ParameterType obj) { ::uavcan::YamlStreamer< ::uavcan::protocol::file::BeginFirmwareUpdate::Response >::stream(s, obj, 0); return s; } } // Namespace file } // Namespace protocol } // Namespace uavcan #endif // UAVCAN_PROTOCOL_FILE_BEGINFIRMWAREUPDATE_HPP_INCLUDED
/* * Lion * (C) 1999-2007,2014 Jack Lloyd * * Botan is released under the Simplified BSD License (see license.txt) */ #include <botan/internal/lion.h> #include <botan/exceptn.h> namespace Botan { /* * Lion Encryption */ void Lion::encrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const { verify_key_set(m_key1.empty() == false); const size_t LEFT_SIZE = left_size(); const size_t RIGHT_SIZE = right_size(); secure_vector<uint8_t> buffer_vec(LEFT_SIZE); uint8_t* buffer = buffer_vec.data(); for(size_t i = 0; i != blocks; ++i) { xor_buf(buffer, in, m_key1.data(), LEFT_SIZE); m_cipher->set_key(buffer, LEFT_SIZE); m_cipher->cipher(in + LEFT_SIZE, out + LEFT_SIZE, RIGHT_SIZE); m_hash->update(out + LEFT_SIZE, RIGHT_SIZE); m_hash->final(buffer); xor_buf(out, in, buffer, LEFT_SIZE); xor_buf(buffer, out, m_key2.data(), LEFT_SIZE); m_cipher->set_key(buffer, LEFT_SIZE); m_cipher->cipher1(out + LEFT_SIZE, RIGHT_SIZE); in += m_block_size; out += m_block_size; } } /* * Lion Decryption */ void Lion::decrypt_n(const uint8_t in[], uint8_t out[], size_t blocks) const { verify_key_set(m_key1.empty() == false); const size_t LEFT_SIZE = left_size(); const size_t RIGHT_SIZE = right_size(); secure_vector<uint8_t> buffer_vec(LEFT_SIZE); uint8_t* buffer = buffer_vec.data(); for(size_t i = 0; i != blocks; ++i) { xor_buf(buffer, in, m_key2.data(), LEFT_SIZE); m_cipher->set_key(buffer, LEFT_SIZE); m_cipher->cipher(in + LEFT_SIZE, out + LEFT_SIZE, RIGHT_SIZE); m_hash->update(out + LEFT_SIZE, RIGHT_SIZE); m_hash->final(buffer); xor_buf(out, in, buffer, LEFT_SIZE); xor_buf(buffer, out, m_key1.data(), LEFT_SIZE); m_cipher->set_key(buffer, LEFT_SIZE); m_cipher->cipher1(out + LEFT_SIZE, RIGHT_SIZE); in += m_block_size; out += m_block_size; } } /* * Lion Key Schedule */ void Lion::key_schedule(const uint8_t key[], size_t length) { clear(); const size_t half = length / 2; m_key1.resize(left_size()); m_key2.resize(left_size()); clear_mem(m_key1.data(), m_key1.size()); clear_mem(m_key2.data(), m_key2.size()); copy_mem(m_key1.data(), key, half); copy_mem(m_key2.data(), key + half, half); } /* * Return the name of this type */ std::string Lion::name() const { return "Lion(" + m_hash->name() + "," + m_cipher->name() + "," + std::to_string(block_size()) + ")"; } std::unique_ptr<BlockCipher> Lion::new_object() const { return std::make_unique<Lion>(m_hash->new_object(), m_cipher->new_object(), block_size()); } /* * Clear memory of sensitive data */ void Lion::clear() { zap(m_key1); zap(m_key2); m_hash->clear(); m_cipher->clear(); } /* * Lion Constructor */ Lion::Lion(std::unique_ptr<HashFunction> hash, std::unique_ptr<StreamCipher> cipher, size_t bs) : m_block_size(std::max<size_t>(2*hash->output_length() + 1, bs)), m_hash(std::move(hash)), m_cipher(std::move(cipher)) { if(2*left_size() + 1 > m_block_size) throw Invalid_Argument(name() + ": Chosen block size is too small"); if(!m_cipher->valid_keylength(left_size())) throw Invalid_Argument(name() + ": This stream/hash combo is invalid"); } }
// // Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // #include "pch.h" using namespace std; /// /// EventMonitor.cpp /// /// Monitors a event log for new events in specified channels. /// /// EventMonitor starts a monitor thread that waits for events from EvtSubscribe /// or for a stop event to be set. The same thread processes the changes and invokes the callback. /// Note: The constructor blocks until the spwaned thread starts listening for changes or dies. /// /// The destructor signals the stop event and waits up to MONITOR_THREAD_EXIT_MAX_WAIT_MILLIS for the monitoring /// thread to exit. To prevent the thread from out-living EventMonitor, the destructor fails fast /// if the wait fails or times out. This also ensures the callback is not being called and will not be /// called once EventMonitor is destroyed. /// EventMonitor::EventMonitor( _In_ const std::vector<EventLogChannel>& EventChannels, _In_ bool EventFormatMultiLine, _In_ bool StartAtOldestRecord ) : m_eventChannels(EventChannels), m_eventFormatMultiLine(EventFormatMultiLine), m_startAtOldestRecord(StartAtOldestRecord) { m_stopEvent = NULL; m_eventMonitorThread = NULL; m_stopEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); if(!m_stopEvent) { throw std::system_error(std::error_code(GetLastError(), std::system_category()), "CreateEvent"); } m_eventMonitorThread = CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)&EventMonitor::StartEventMonitorStatic, this, 0, nullptr); if(!m_eventMonitorThread) { throw std::system_error(std::error_code(GetLastError(), std::system_category()), "CreateThread"); } } EventMonitor::~EventMonitor() { if(!SetEvent(m_stopEvent)) { logWriter.TraceError( Utility::FormatString(L"Failed to gracefully stop event log monitor %lu", GetLastError()).c_str() ); } else { // // Wait for watch thread to exit. // DWORD waitResult = WaitForSingleObject(m_eventMonitorThread, EVENT_MONITOR_THREAD_EXIT_MAX_WAIT_MILLIS); if (waitResult != WAIT_OBJECT_0) { HRESULT hr = (waitResult == WAIT_FAILED) ? HRESULT_FROM_WIN32(GetLastError()) : HRESULT_FROM_WIN32(waitResult); } } if (!m_eventMonitorThread) { CloseHandle(m_eventMonitorThread); } if (!m_stopEvent) { CloseHandle(m_stopEvent); } } /// /// Entry for the spawned event monitor thread. /// /// \param Context Callback context to the event monitor thread. /// It's EventMonitor object that started this thread. /// /// \return Status of event monitoring opeartion. /// DWORD EventMonitor::StartEventMonitorStatic( _In_ LPVOID Context ) { auto pThis = reinterpret_cast<EventMonitor*>(Context); try { DWORD status = pThis->StartEventMonitor(); if (status != ERROR_SUCCESS) { logWriter.TraceError( Utility::FormatString(L"Failed to start event log monitor. Error: %lu", status).c_str() ); } return status; } catch (std::exception& ex) { logWriter.TraceError( Utility::FormatString(L"Failed to start event log monitor. %S", ex.what()).c_str() ); return E_FAIL; } catch (...) { logWriter.TraceError( Utility::FormatString(L"Failed to start event log monitor. Unknown error occurred.").c_str() ); return E_FAIL; } } /// /// Entry for the spawned event monitor thread. Loops to wait for either the stop event in which case it exits /// or for events to be arrived. When new events are arrived, it invokes the callback, resets, /// and starts the wait again. /// /// \return Status of event monitoring opeartion. /// DWORD EventMonitor::StartEventMonitor() { DWORD status = ERROR_SUCCESS; EVT_HANDLE hSubscription = NULL; const LPWSTR pwsQuery = (LPWSTR)(L"*"); const DWORD eventsCount = 2; EnableEventLogChannels(); // // Order stop event first so that stop is prioritized if both events are already signalled (changes // are available but stop has been called). // HANDLE aWaitHandles[eventsCount]; aWaitHandles[0] = m_stopEvent; // // Get a handle to a manual reset event object that the subscription will signal // when events become available that match your query criteria. // HANDLE subscEvent = CreateEvent(NULL, TRUE, TRUE, NULL); if(!subscEvent) { return GetLastError(); } aWaitHandles[1] = subscEvent; // // Subscribe to events. // DWORD evtSubscribeFlags = this->m_startAtOldestRecord ? EvtSubscribeStartAtOldestRecord : EvtSubscribeToFutureEvents; hSubscription = EvtSubscribe(NULL, aWaitHandles[1], NULL, ConstructWindowsEventQuery(m_eventChannels).c_str(), NULL, NULL, NULL, evtSubscribeFlags); if (NULL == hSubscription) { status = GetLastError(); if (ERROR_EVT_CHANNEL_NOT_FOUND == status) logWriter.TraceError(L"Failed to subscribe to event log channel. The specified event channel was not found."); else if (ERROR_EVT_INVALID_QUERY == status) logWriter.TraceError( Utility::FormatString(L"Failed to subscribe to event log channel. Event query %s is not valid.", pwsQuery).c_str() ); else logWriter.TraceError( Utility::FormatString(L"Failed to subscribe to event log channel. Error: %lu.", status).c_str() ); } if (status == ERROR_SUCCESS) { while (true) { DWORD wait = WaitForMultipleObjects(eventsCount, aWaitHandles, FALSE, INFINITE); if (0 == wait - WAIT_OBJECT_0) // Console input { break; } else if (1 == wait - WAIT_OBJECT_0) // Query results { if (ERROR_NO_MORE_ITEMS != (status = EnumerateResults(hSubscription))) { break; } status = ERROR_SUCCESS; ResetEvent(aWaitHandles[1]); } else { if (WAIT_FAILED == wait) { logWriter.TraceError( Utility::FormatString(L"Failed to subscribe to event log channel. Wait operation on event handle failed. Error: %lu.", GetLastError()).c_str() ); } break; } } } if (hSubscription) { EvtClose(hSubscription); } if(subscEvent) { CloseHandle(subscEvent); } return status; } /// /// Constructs and returns an XML Query for Windows Event collection using the supplied parameters. /// /// \param EventChannels Supplies the event channels to query. /// /// \return XML Query for Windows Event collection. /// std::wstring EventMonitor::ConstructWindowsEventQuery( _In_ const std::vector<EventLogChannel>& EventChannels ) { // // Construct the query // std::wstring query = LR"(<QueryList>)"; query += LR"(<Query Id="0" Path="System">)"; for (const auto& eventChannel : EventChannels) { // // Construct the query portion for the log level // std::wstring logLevelQuery = L""; logLevelQuery = L"("; if (eventChannel.Level >= EventChannelLogLevel::Critical) { logLevelQuery += L"Level=1 or "; } if (eventChannel.Level >= EventChannelLogLevel::Error) { logLevelQuery += L"Level=2 or "; } if (eventChannel.Level >= EventChannelLogLevel::Warning) { logLevelQuery += L"Level=3 or "; } if (eventChannel.Level >= EventChannelLogLevel::Information) { logLevelQuery += L"Level=4 or "; } if (eventChannel.Level >= EventChannelLogLevel::Verbose) { logLevelQuery += L"Level=5 or "; } // // Remove last ' or ' // logLevelQuery.erase(logLevelQuery.size() - 4); logLevelQuery += L")"; query += Utility::FormatString( LR"(<Select Path="%s">*[System[%s)", eventChannel.Name.c_str(), logLevelQuery.c_str()); query += LR"(]]</Select>)"; } query += LR"(</Query>)"; query += LR"(</QueryList>)"; return query; } /// /// Enumerate the events in the result set. /// /// \param EventChannels The handle to the subscription that EvtSubscribe function returned. /// /// \return A DWORD with a windows error value. If the function succeded, it returns /// ERROR_SUCCESS. /// DWORD EventMonitor::EnumerateResults( _In_ EVT_HANDLE hResults ) { DWORD status = ERROR_SUCCESS; EVT_HANDLE hEvents[EVENT_ARRAY_SIZE]; DWORD dwReturned = 0; while (true) { // // Get a block of events from the result set. // if (!EvtNext(hResults, EVENT_ARRAY_SIZE, hEvents, INFINITE, 0, &dwReturned)) { if (ERROR_NO_MORE_ITEMS != (status = GetLastError())) { logWriter.TraceError( Utility::FormatString(L"Failed to query next event. Error: %lu.", status).c_str() ); } goto cleanup; } // // For each event, call the PrintEvent function which renders the // event for display. // for (DWORD i = 0; i < dwReturned; i++) { status = PrintEvent(hEvents[i]); if (ERROR_SUCCESS != status) { logWriter.TraceWarning( Utility::FormatString(L"Failed to render event log event. The event will not be processed. Error: %lu.", status).c_str() ); status = ERROR_SUCCESS; } EvtClose(hEvents[i]); hEvents[i] = NULL; } } cleanup: // // Closes any events in case an error occurred above. // for (DWORD i = 0; i < dwReturned; i++) { if (NULL != hEvents[i]) { EvtClose(hEvents[i]); } } return status; } /// /// Constructs an EventLog object with the contents of an event's value paths. /// /// \param EventHandle Supplies a handle to an event, used to extract value paths. /// \param AdditionalValuePaths Supplies additional values to include in the returned EventLog object. /// /// \return DWORD /// DWORD EventMonitor::PrintEvent( _In_ const HANDLE& EventHandle ) { DWORD status = ERROR_SUCCESS; DWORD bytesWritten = 0; EVT_HANDLE renderContext = NULL; EVT_HANDLE publisher = NULL; static constexpr LPCWSTR defaultValuePaths[] = { L"Event/System/Provider/@Name", L"Event/System/Channel", L"Event/System/EventID", L"Event/System/Level", L"Event/System/TimeCreated/@SystemTime", }; const static std::vector<std::wstring> c_LevelToString = { L"Unknown", L"Critical", L"Error", L"Warning", L"Information", L"Verbose", }; const static DWORD defaultValuePathsCount = sizeof(defaultValuePaths) / sizeof(LPCWSTR); try { // // Construct the value paths that will be used to query the events // std::vector<LPCWSTR> valuePaths(defaultValuePaths, defaultValuePaths + defaultValuePathsCount); // // Collect event system properties // renderContext = EvtCreateRenderContext(static_cast<DWORD>(valuePaths.size()), &valuePaths[0], EvtRenderContextValues); if (!renderContext) { return GetLastError(); } DWORD propertyCount = 0; DWORD bufferSize = 0; std::vector<EVT_VARIANT> variants; EvtRender(renderContext, EventHandle, EvtRenderEventValues, 0, nullptr, &bufferSize, &propertyCount); if (ERROR_INVALID_HANDLE == GetLastError()) { status = ERROR_INVALID_HANDLE; } if (ERROR_INSUFFICIENT_BUFFER == (status = GetLastError())) { status = ERROR_SUCCESS; } if (status == ERROR_SUCCESS) { // // Allocate more memory to accommodate modulus // variants.resize((bufferSize / sizeof(EVT_VARIANT)) + 1, EVT_VARIANT{}); if(!EvtRender( renderContext, EventHandle, EvtRenderEventValues, bufferSize, &variants[0], &bufferSize, &propertyCount)) { status = GetLastError(); logWriter.TraceError( Utility::FormatString(L"Failed to render event. Error: %lu", status).c_str() ); } } if (status == ERROR_SUCCESS) { // // Extract the variant values for each queried property. If the variant failed to get a valid type // set a default value. // std::wstring providerName = (EvtVarTypeString != variants[0].Type) ? L"" : variants[0].StringVal; std::wstring channelName = (EvtVarTypeString != variants[1].Type) ? L"" : variants[1].StringVal; UINT16 eventId = (EvtVarTypeUInt16 != variants[2].Type) ? 0 : variants[2].UInt16Val; UINT8 level = (EvtVarTypeByte != variants[3].Type) ? 0 : variants[3].ByteVal; ULARGE_INTEGER fileTimeAsInt{}; fileTimeAsInt.QuadPart = (EvtVarTypeFileTime != variants[4].Type) ? 0 : variants[4].FileTimeVal; FILETIME fileTimeCreated{ fileTimeAsInt.LowPart, fileTimeAsInt.HighPart }; // // Collect user message // publisher = EvtOpenPublisherMetadata(nullptr, providerName.c_str(), nullptr, 0, 0); if (publisher) { EvtFormatMessage(publisher, EventHandle, 0, 0, nullptr, EvtFormatMessageEvent, 0, nullptr, &bufferSize); status = GetLastError(); if (status != ERROR_EVT_MESSAGE_NOT_FOUND) { if (ERROR_INSUFFICIENT_BUFFER == status) { status = ERROR_SUCCESS; } if (m_eventMessageBuffer.capacity() < bufferSize) { m_eventMessageBuffer.resize(bufferSize); } if (!EvtFormatMessage( publisher, EventHandle, 0, 0, nullptr, EvtFormatMessageEvent, bufferSize, &m_eventMessageBuffer[0], &bufferSize)) { status = GetLastError(); } } else { status = ERROR_SUCCESS; } } if (status == ERROR_SUCCESS) { std::wstring formattedEvent = Utility::FormatString( L"<Source>EventLog</Source><Time>%s</Time><LogEntry><Channel>%s</Channel><Level>%s</Level><EventId>%u</EventId><Message>%s</Message></LogEntry>", Utility::FileTimeToString(fileTimeCreated).c_str(), channelName.c_str(), c_LevelToString[static_cast<UINT8>(level)].c_str(), eventId, (LPWSTR)(&m_eventMessageBuffer[0])); // // If the multi-line option is disabled, remove all new lines from the output. // if (!this->m_eventFormatMultiLine) { std::transform(formattedEvent.begin(), formattedEvent.end(), formattedEvent.begin(), [](WCHAR ch) { switch (ch) { case L'\r': case L'\n': return L' '; } return ch; }); } logWriter.WriteConsoleLog(formattedEvent); } } } catch(...) { logWriter.TraceWarning(L"Failed to render event log event. The event will not be processed."); } if (publisher) { EvtClose(publisher); } if (renderContext) { EvtClose(renderContext); } return status; } /// Enables all monitored event log channels. /// /// \return None /// void EventMonitor::EnableEventLogChannels() { for (const auto& eventChannel : m_eventChannels) { EnableEventLogChannel(eventChannel.Name.c_str()); } } /// Enables or disables an Event Log channel. /// /// \param ChannelPath Full path to the event log channel. /// /// \return None /// void EventMonitor::EnableEventLogChannel( _In_ LPCWSTR ChannelPath ) { DWORD status = ERROR_SUCCESS; EVT_HANDLE channelConfig = NULL; EVT_VARIANT propValue; DWORD dwPropValSize; // // Open the channel configuration. // channelConfig = EvtOpenChannelConfig(NULL, ChannelPath, 0); if (NULL == channelConfig) { status = GetLastError(); goto Exit; } if (EvtGetChannelConfigProperty(channelConfig, EvtChannelConfigEnabled, 0, sizeof(EVT_VARIANT), &propValue, &dwPropValSize)) { // // Return if event channel is slready enabled. // if (propValue.BooleanVal) { goto Exit; } } else { status = GetLastError(); logWriter.TraceError( Utility::FormatString(L"Failed to query event channel configuration. Channel: %ws Error: 0x%X", ChannelPath, status).c_str() ); } // // Set the Enabled property. // propValue.Type = EvtVarTypeBoolean; propValue.Count = 1; propValue.BooleanVal = true; if (!EvtSetChannelConfigProperty( channelConfig, EvtChannelConfigEnabled, 0, &propValue )) { status = GetLastError(); goto Exit; } // // Save changes. // if (!EvtSaveChannelConfig(channelConfig, 0)) { status = GetLastError(); if (status == ERROR_EVT_INVALID_OPERATION_OVER_ENABLED_DIRECT_CHANNEL) { // // The channel is already enabled. // status = ERROR_SUCCESS; } else { goto Exit; } } status = ERROR_SUCCESS; Exit: if (ERROR_SUCCESS != status) { logWriter.TraceError( Utility::FormatString(L"Failed to enable event channel %ws: 0x%X", ChannelPath, status).c_str() ); } if (channelConfig != NULL) { EvtClose(channelConfig); } }
#ifndef _ACF_PROCESS_APU_COMPUTE_BRIEF_DESCRIPTOR #define _ACF_PROCESS_APU_COMPUTE_BRIEF_DESCRIPTOR #include <acf_process_apu.h> #include <apex_launcher.hpp> #include <stdint.h> #include <COMPUTE_BRIEF_DESCRIPTOR_APU_LOAD.h> //APU load associated with this process //SCENARIO LIST************************************************* static acf_scenario_buffer_data gScenarioBufferData0_COMPUTE_BRIEF_DESCRIPTOR[] = {{36, 36, 2, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {64, 1, 1, 0, {0, 0, 0, 0}}, {4096, 1, 2, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {2048, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}, {1, 1, 1, 0, {0, 0, 0, 0}}}; static acf_scenario_kernel_data gScenarioKernelData0_COMPUTE_BRIEF_DESCRIPTOR[] = {{0, 0}}; static acf_scenario gScenarioArray_COMPUTE_BRIEF_DESCRIPTOR[] = { {0, 0, 2656, 16512, 0, gScenarioBufferData0_COMPUTE_BRIEF_DESCRIPTOR, 192, gScenarioKernelData0_COMPUTE_BRIEF_DESCRIPTOR, 4} }; static acf_scenario_list gScenarioList_COMPUTE_BRIEF_DESCRIPTOR = { 1, //number of scenarios gScenarioArray_COMPUTE_BRIEF_DESCRIPTOR}; //************************************************************** class COMPUTE_BRIEF_DESCRIPTOR : public ACF_Process_APU { public: COMPUTE_BRIEF_DESCRIPTOR(int32_t apex_id = 0) : ACF_Process_APU(apex_id) {} int32_t Initialize() { int32_t lRetVal = 0; if (!Initialized()) //initialization steps that only need to occur once { SetProcessIdentifier("COMPUTE_BRIEF_DESCRIPTOR"); lRetVal = NonParametricInitialization(); if (lRetVal != 0) return lRetVal; lRetVal |= mpApexTask->SetupHw("COMPUTE_BRIEF_DESCRIPTOR", COMPUTE_BRIEF_DESCRIPTOR_LOAD_SEGMENTS, COMPUTE_BRIEF_DESCRIPTOR_LOAD_PMEM, COMPUTE_BRIEF_DESCRIPTOR_LOAD_PMEM_SIZE, COMPUTE_BRIEF_DESCRIPTOR_LOAD_DMEM, COMPUTE_BRIEF_DESCRIPTOR_LOAD_DMEM_SIZE, 0, 0); //assuming _LOAD_CMEM does not exist SetApuStdioInfo(COMPUTE_BRIEF_DESCRIPTOR_APEX_LOG_BUFFER, COMPUTE_BRIEF_DESCRIPTOR_APEX_LOG_SIZE); if (lRetVal != 0) return lRetVal; //***NOTE: the order in which the following ports are added is meaningful; do not change! AddPort("INPUT", icp::DATATYPE_08U, 1, 1, 36, 36, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0); AddPort("FILTER_TYPE", icp::DATATYPE_08U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 4, 0, 0, 0, 0, 0); AddPort("SMPL_PACKET", icp::DATATYPE_32U, 1, 1, 2048, 1, 0, 1, 1, 0, 1, 0, 5, 0, 0, 0, 0, 0); AddPort("NR_PACKETS_UL", icp::DATATYPE_32U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 6, 0, 0, 0, 0, 0); AddPort("NR_PACKETS_UR", icp::DATATYPE_32U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 7, 0, 0, 0, 0, 0); AddPort("NR_PACKETS_LL", icp::DATATYPE_32U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 8, 0, 0, 0, 0, 0); AddPort("NR_PACKETS_LR", icp::DATATYPE_32U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 9, 0, 0, 0, 0, 0); AddPort("PATCH_SIZE", icp::DATATYPE_08U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 10, 0, 0, 0, 0, 0); AddPort("DESC_SIZE", icp::DATATYPE_08U, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 11, 0, 0, 0, 0, 0); AddPort("COUNT", icp::DATATYPE_32U, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0); AddPort("DESCRIPTOR_OUT", icp::DATATYPE_08U, 1, 1, 64, 1, 1, 0, 0, 0, 1, 1, 2, 0, 0, 0, 0, 0); CfgScenarios(&gScenarioList_COMPUTE_BRIEF_DESCRIPTOR); FlagAsInitialized(); } lRetVal = SelectApuConfiguration(mApuCfg, mApexId); //by default mApuCfg = ACF_APU_CFG__APEX0_DEFAULT and mApexId = 0 return lRetVal; } }; #endif //_ACF_PROCESS_APU_COMPUTE_BRIEF_DESCRIPTOR
#ifndef __AANIMAL_H__ #define __AANIMAL_H__ #include <string> using std::string; class AAnimal { protected: string _type; public: // Constructors AAnimal(); // Destructor virtual ~AAnimal(); // Getters / Setters const string& getType() const; // Abstract Methods virtual void makeSound() const = 0; private: // Disabled Members AAnimal(const AAnimal& other); AAnimal& operator=(const AAnimal& assign); }; #endif // __AANIMAL_H__
#include <bdsg/overlays/vectorizable_overlays.hpp> #include <functional> #include <handlegraph/handle_graph.hpp> #include <handlegraph/path_handle_graph.hpp> #include <handlegraph/path_metadata.hpp> #include <handlegraph/types.hpp> #include <iterator> #include <memory> #include <sstream> // __str__ #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> #include <pybind11/pybind11.h> #include <functional> #include <string> #include <pybind11/stl.h> #include <pybind11/stl_bind.h> #include <pybind11/functional.h> #include <fstream> #include <bdsg/internal/binder_hook_compile.hpp> #ifndef BINDER_PYBIND11_TYPE_CASTER #define BINDER_PYBIND11_TYPE_CASTER PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>); PYBIND11_DECLARE_HOLDER_TYPE(T, T*); PYBIND11_MAKE_OPAQUE(std::shared_ptr<void>); #endif // bdsg::VectorizableOverlay file:bdsg/overlays/vectorizable_overlays.hpp line:34 struct PyCallBack_bdsg_VectorizableOverlay : public bdsg::VectorizableOverlay { using bdsg::VectorizableOverlay::VectorizableOverlay; bool has_node(long long a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "has_node"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::has_node(a0); } struct handlegraph::handle_t get_handle(const long long & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::get_handle(a0, a1); } long long get_id(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::get_id(a0); } bool get_is_reverse(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_is_reverse"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::get_is_reverse(a0); } struct handlegraph::handle_t flip(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "flip"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::flip(a0); } unsigned long get_length(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_length"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_length(a0); } std::string get_sequence(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_sequence"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return VectorizableOverlay::get_sequence(a0); } unsigned long get_degree(const struct handlegraph::handle_t & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_degree"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_degree(a0, a1); } bool has_edge(const struct handlegraph::handle_t & a0, const struct handlegraph::handle_t & a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "has_edge"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::has_edge(a0, a1); } char get_base(const struct handlegraph::handle_t & a0, unsigned long a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_base"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<char>::value) { static pybind11::detail::overload_caster_t<char> caster; return pybind11::detail::cast_ref<char>(std::move(o), caster); } else return pybind11::detail::cast_safe<char>(std::move(o)); } return VectorizableOverlay::get_base(a0, a1); } std::string get_subsequence(const struct handlegraph::handle_t & a0, unsigned long a1, unsigned long a2) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_subsequence"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return VectorizableOverlay::get_subsequence(a0, a1, a2); } unsigned long get_node_count() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_node_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_node_count(); } long long min_node_id() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "min_node_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::min_node_id(); } long long max_node_id() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "max_node_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::max_node_id(); } unsigned long node_vector_offset(const long long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "node_vector_offset"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::node_vector_offset(a0); } long long node_at_vector_offset(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "node_at_vector_offset"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::node_at_vector_offset(a0); } unsigned long edge_index(const struct std::pair<struct handlegraph::handle_t, struct handlegraph::handle_t> & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "edge_index"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::edge_index(a0); } unsigned long id_to_rank(const long long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "id_to_rank"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::id_to_rank(a0); } long long rank_to_id(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "rank_to_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::rank_to_id(a0); } struct handlegraph::handle_t get_underlying_handle(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_underlying_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::get_underlying_handle(a0); } void index_nodes_and_edges() override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "index_nodes_and_edges"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<void>::value) { static pybind11::detail::overload_caster_t<void> caster; return pybind11::detail::cast_ref<void>(std::move(o), caster); } else return pybind11::detail::cast_safe<void>(std::move(o)); } return VectorizableOverlay::index_nodes_and_edges(); } unsigned long handle_to_rank(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "handle_to_rank"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return RankedHandleGraph::handle_to_rank(a0); } struct handlegraph::handle_t rank_to_handle(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "rank_to_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return RankedHandleGraph::rank_to_handle(a0); } unsigned long get_edge_count() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_edge_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return HandleGraph::get_edge_count(); } unsigned long get_total_length() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "get_total_length"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return HandleGraph::get_total_length(); } bool follow_edges_impl(const struct handlegraph::handle_t & a0, bool a1, const class std::function<bool (const struct handlegraph::handle_t &)> & a2) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "follow_edges_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } pybind11::pybind11_fail("Tried to call pure virtual function \"HandleGraph::follow_edges_impl\""); } bool for_each_handle_impl(const class std::function<bool (const struct handlegraph::handle_t &)> & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::VectorizableOverlay *>(this), "for_each_handle_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } pybind11::pybind11_fail("Tried to call pure virtual function \"HandleGraph::for_each_handle_impl\""); } }; // bdsg::PathVectorizableOverlay file:bdsg/overlays/vectorizable_overlays.hpp line:197 struct PyCallBack_bdsg_PathVectorizableOverlay : public bdsg::PathVectorizableOverlay { using bdsg::PathVectorizableOverlay::PathVectorizableOverlay; unsigned long get_path_count() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_path_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return PathVectorizableOverlay::get_path_count(); } bool has_path(const std::string & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "has_path"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::has_path(a0); } struct handlegraph::path_handle_t get_path_handle(const std::string & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_path_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::path_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::path_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::path_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::path_handle_t>(std::move(o)); } return PathVectorizableOverlay::get_path_handle(a0); } std::string get_path_name(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_path_name"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return PathVectorizableOverlay::get_path_name(a0); } bool get_is_circular(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_is_circular"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::get_is_circular(a0); } unsigned long get_step_count(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_step_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return PathVectorizableOverlay::get_step_count(a0); } struct handlegraph::handle_t get_handle_of_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_handle_of_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return PathVectorizableOverlay::get_handle_of_step(a0); } struct handlegraph::path_handle_t get_path_handle_of_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_path_handle_of_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::path_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::path_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::path_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::path_handle_t>(std::move(o)); } return PathVectorizableOverlay::get_path_handle_of_step(a0); } struct handlegraph::step_handle_t path_begin(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "path_begin"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::path_begin(a0); } struct handlegraph::step_handle_t path_end(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "path_end"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::path_end(a0); } struct handlegraph::step_handle_t path_back(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "path_back"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::path_back(a0); } struct handlegraph::step_handle_t path_front_end(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "path_front_end"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::path_front_end(a0); } bool has_next_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "has_next_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::has_next_step(a0); } bool has_previous_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "has_previous_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::has_previous_step(a0); } struct handlegraph::step_handle_t get_next_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_next_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::get_next_step(a0); } struct handlegraph::step_handle_t get_previous_step(const struct handlegraph::step_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_previous_step"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::step_handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::step_handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::step_handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::step_handle_t>(std::move(o)); } return PathVectorizableOverlay::get_previous_step(a0); } bool for_each_path_handle_impl(const class std::function<bool (const struct handlegraph::path_handle_t &)> & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "for_each_path_handle_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::for_each_path_handle_impl(a0); } bool for_each_step_on_handle_impl(const struct handlegraph::handle_t & a0, const class std::function<bool (const struct handlegraph::step_handle_t &)> & a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "for_each_step_on_handle_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathVectorizableOverlay::for_each_step_on_handle_impl(a0, a1); } bool has_node(long long a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "has_node"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::has_node(a0); } struct handlegraph::handle_t get_handle(const long long & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::get_handle(a0, a1); } long long get_id(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::get_id(a0); } bool get_is_reverse(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_is_reverse"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::get_is_reverse(a0); } struct handlegraph::handle_t flip(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "flip"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::flip(a0); } unsigned long get_length(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_length"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_length(a0); } std::string get_sequence(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_sequence"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return VectorizableOverlay::get_sequence(a0); } unsigned long get_degree(const struct handlegraph::handle_t & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_degree"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_degree(a0, a1); } bool has_edge(const struct handlegraph::handle_t & a0, const struct handlegraph::handle_t & a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "has_edge"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return VectorizableOverlay::has_edge(a0, a1); } char get_base(const struct handlegraph::handle_t & a0, unsigned long a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_base"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<char>::value) { static pybind11::detail::overload_caster_t<char> caster; return pybind11::detail::cast_ref<char>(std::move(o), caster); } else return pybind11::detail::cast_safe<char>(std::move(o)); } return VectorizableOverlay::get_base(a0, a1); } std::string get_subsequence(const struct handlegraph::handle_t & a0, unsigned long a1, unsigned long a2) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_subsequence"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return VectorizableOverlay::get_subsequence(a0, a1, a2); } unsigned long get_node_count() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_node_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::get_node_count(); } long long min_node_id() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "min_node_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::min_node_id(); } long long max_node_id() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "max_node_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::max_node_id(); } unsigned long node_vector_offset(const long long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "node_vector_offset"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::node_vector_offset(a0); } long long node_at_vector_offset(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "node_at_vector_offset"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::node_at_vector_offset(a0); } unsigned long edge_index(const struct std::pair<struct handlegraph::handle_t, struct handlegraph::handle_t> & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "edge_index"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::edge_index(a0); } unsigned long id_to_rank(const long long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "id_to_rank"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return VectorizableOverlay::id_to_rank(a0); } long long rank_to_id(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "rank_to_id"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<long long>::value) { static pybind11::detail::overload_caster_t<long long> caster; return pybind11::detail::cast_ref<long long>(std::move(o), caster); } else return pybind11::detail::cast_safe<long long>(std::move(o)); } return VectorizableOverlay::rank_to_id(a0); } struct handlegraph::handle_t get_underlying_handle(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_underlying_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return VectorizableOverlay::get_underlying_handle(a0); } void index_nodes_and_edges() override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "index_nodes_and_edges"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<void>::value) { static pybind11::detail::overload_caster_t<void> caster; return pybind11::detail::cast_ref<void>(std::move(o), caster); } else return pybind11::detail::cast_safe<void>(std::move(o)); } return VectorizableOverlay::index_nodes_and_edges(); } unsigned long handle_to_rank(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "handle_to_rank"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return RankedHandleGraph::handle_to_rank(a0); } struct handlegraph::handle_t rank_to_handle(const unsigned long & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "rank_to_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<struct handlegraph::handle_t>::value) { static pybind11::detail::overload_caster_t<struct handlegraph::handle_t> caster; return pybind11::detail::cast_ref<struct handlegraph::handle_t>(std::move(o), caster); } else return pybind11::detail::cast_safe<struct handlegraph::handle_t>(std::move(o)); } return RankedHandleGraph::rank_to_handle(a0); } unsigned long get_edge_count() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_edge_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return HandleGraph::get_edge_count(); } unsigned long get_total_length() const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_total_length"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return HandleGraph::get_total_length(); } bool follow_edges_impl(const struct handlegraph::handle_t & a0, bool a1, const class std::function<bool (const struct handlegraph::handle_t &)> & a2) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "follow_edges_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } pybind11::pybind11_fail("Tried to call pure virtual function \"HandleGraph::follow_edges_impl\""); } bool for_each_handle_impl(const class std::function<bool (const struct handlegraph::handle_t &)> & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "for_each_handle_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } pybind11::pybind11_fail("Tried to call pure virtual function \"HandleGraph::for_each_handle_impl\""); } unsigned long get_step_count(const struct handlegraph::handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_step_count"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return PathHandleGraph::get_step_count(a0); } class std::vector<handlegraph::step_handle_t> steps_of_handle(const struct handlegraph::handle_t & a0, bool a1) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "steps_of_handle"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1); if (pybind11::detail::cast_is_temporary_value_reference<class std::vector<handlegraph::step_handle_t>>::value) { static pybind11::detail::overload_caster_t<class std::vector<handlegraph::step_handle_t>> caster; return pybind11::detail::cast_ref<class std::vector<handlegraph::step_handle_t>>(std::move(o), caster); } else return pybind11::detail::cast_safe<class std::vector<handlegraph::step_handle_t>>(std::move(o)); } return PathHandleGraph::steps_of_handle(a0, a1); } bool is_empty(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "is_empty"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathHandleGraph::is_empty(a0); } enum handlegraph::PathSense get_sense(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_sense"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<enum handlegraph::PathSense>::value) { static pybind11::detail::overload_caster_t<enum handlegraph::PathSense> caster; return pybind11::detail::cast_ref<enum handlegraph::PathSense>(std::move(o), caster); } else return pybind11::detail::cast_safe<enum handlegraph::PathSense>(std::move(o)); } return PathMetadata::get_sense(a0); } std::string get_sample_name(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_sample_name"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return PathMetadata::get_sample_name(a0); } std::string get_locus_name(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_locus_name"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<std::string>::value) { static pybind11::detail::overload_caster_t<std::string> caster; return pybind11::detail::cast_ref<std::string>(std::move(o), caster); } else return pybind11::detail::cast_safe<std::string>(std::move(o)); } return PathMetadata::get_locus_name(a0); } unsigned long get_haplotype(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_haplotype"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return PathMetadata::get_haplotype(a0); } unsigned long get_phase_block(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_phase_block"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<unsigned long>::value) { static pybind11::detail::overload_caster_t<unsigned long> caster; return pybind11::detail::cast_ref<unsigned long>(std::move(o), caster); } else return pybind11::detail::cast_safe<unsigned long>(std::move(o)); } return PathMetadata::get_phase_block(a0); } using _binder_ret_0 = struct std::pair<unsigned long, unsigned long>; _binder_ret_0 get_subrange(const struct handlegraph::path_handle_t & a0) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "get_subrange"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0); if (pybind11::detail::cast_is_temporary_value_reference<_binder_ret_0>::value) { static pybind11::detail::overload_caster_t<_binder_ret_0> caster; return pybind11::detail::cast_ref<_binder_ret_0>(std::move(o), caster); } else return pybind11::detail::cast_safe<_binder_ret_0>(std::move(o)); } return PathMetadata::get_subrange(a0); } bool for_each_path_matching_impl(const class std::unordered_set<enum handlegraph::PathSense, struct std::hash<enum handlegraph::PathSense>, struct std::equal_to<enum handlegraph::PathSense>, class std::allocator<enum handlegraph::PathSense> > * a0, const class std::unordered_set<std::string, struct std::hash<std::string>, struct std::equal_to<std::string >, class std::allocator<std::string > > * a1, const class std::unordered_set<std::string, struct std::hash<std::string>, struct std::equal_to<std::string >, class std::allocator<std::string > > * a2, const class std::function<bool (const struct handlegraph::path_handle_t &)> & a3) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "for_each_path_matching_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2, a3); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathMetadata::for_each_path_matching_impl(a0, a1, a2, a3); } bool for_each_step_of_sense_impl(const struct handlegraph::handle_t & a0, const enum handlegraph::PathSense & a1, const class std::function<bool (const struct handlegraph::step_handle_t &)> & a2) const override { pybind11::gil_scoped_acquire gil; pybind11::function overload = pybind11::get_overload(static_cast<const bdsg::PathVectorizableOverlay *>(this), "for_each_step_of_sense_impl"); if (overload) { auto o = overload.operator()<pybind11::return_value_policy::reference>(a0, a1, a2); if (pybind11::detail::cast_is_temporary_value_reference<bool>::value) { static pybind11::detail::overload_caster_t<bool> caster; return pybind11::detail::cast_ref<bool>(std::move(o), caster); } else return pybind11::detail::cast_safe<bool>(std::move(o)); } return PathMetadata::for_each_step_of_sense_impl(a0, a1, a2); } }; void bind_bdsg_overlays_vectorizable_overlays(std::function< pybind11::module &(std::string const &namespace_) > &M) { { // bdsg::VectorizableOverlay file:bdsg/overlays/vectorizable_overlays.hpp line:34 pybind11::class_<bdsg::VectorizableOverlay, std::shared_ptr<bdsg::VectorizableOverlay>, PyCallBack_bdsg_VectorizableOverlay, handlegraph::VectorizableHandleGraph, handlegraph::ExpandingOverlayGraph> cl(M("bdsg"), "VectorizableOverlay", ""); cl.def( pybind11::init<const class handlegraph::HandleGraph *>(), pybind11::arg("graph") ); cl.def( pybind11::init( [](){ return new bdsg::VectorizableOverlay(); }, [](){ return new PyCallBack_bdsg_VectorizableOverlay(); } ) ); cl.def("has_node", (bool (bdsg::VectorizableOverlay::*)(long long) const) &bdsg::VectorizableOverlay::has_node, "Method to check if a node exists by ID\n\nC++: bdsg::VectorizableOverlay::has_node(long long) const --> bool", pybind11::arg("node_id")); cl.def("get_handle", [](bdsg::VectorizableOverlay const &o, const long long & a0) -> handlegraph::handle_t { return o.get_handle(a0); }, "", pybind11::arg("node_id")); cl.def("get_handle", (struct handlegraph::handle_t (bdsg::VectorizableOverlay::*)(const long long &, bool) const) &bdsg::VectorizableOverlay::get_handle, "Look up the handle for the node with the given ID in the given orientation\n\nC++: bdsg::VectorizableOverlay::get_handle(const long long &, bool) const --> struct handlegraph::handle_t", pybind11::arg("node_id"), pybind11::arg("is_reverse")); cl.def("get_id", (long long (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::get_id, "Get the ID from a handle\n\nC++: bdsg::VectorizableOverlay::get_id(const struct handlegraph::handle_t &) const --> long long", pybind11::arg("handle")); cl.def("get_is_reverse", (bool (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::get_is_reverse, "Get the orientation of a handle\n\nC++: bdsg::VectorizableOverlay::get_is_reverse(const struct handlegraph::handle_t &) const --> bool", pybind11::arg("handle")); cl.def("flip", (struct handlegraph::handle_t (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::flip, "Invert the orientation of a handle (potentially without getting its ID)\n\nC++: bdsg::VectorizableOverlay::flip(const struct handlegraph::handle_t &) const --> struct handlegraph::handle_t", pybind11::arg("handle")); cl.def("get_length", (unsigned long (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::get_length, "Get the length of a node\n\nC++: bdsg::VectorizableOverlay::get_length(const struct handlegraph::handle_t &) const --> unsigned long", pybind11::arg("handle")); cl.def("get_sequence", (std::string (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::get_sequence, "Get the sequence of a node, presented in the handle's local forward orientation.\n\nC++: bdsg::VectorizableOverlay::get_sequence(const struct handlegraph::handle_t &) const --> std::string", pybind11::arg("handle")); cl.def("get_degree", (unsigned long (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &, bool) const) &bdsg::VectorizableOverlay::get_degree, "Get the number of edges on the right (go_left = false) or left (go_left\n = true) side of the given handle. The default implementation is O(n) in\n the number of edges returned, but graph implementations that track this\n information more efficiently can override this method.\n\nC++: bdsg::VectorizableOverlay::get_degree(const struct handlegraph::handle_t &, bool) const --> unsigned long", pybind11::arg("handle"), pybind11::arg("go_left")); cl.def("has_edge", (bool (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &, const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::has_edge, "Returns true if there is an edge that allows traversal from the left\n handle to the right handle. By default O(n) in the number of edges\n on left, but can be overridden with more efficient implementations.\n\nC++: bdsg::VectorizableOverlay::has_edge(const struct handlegraph::handle_t &, const struct handlegraph::handle_t &) const --> bool", pybind11::arg("left"), pybind11::arg("right")); cl.def("get_base", (char (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &, unsigned long) const) &bdsg::VectorizableOverlay::get_base, "Returns one base of a handle's sequence, in the orientation of the\n handle.\n\nC++: bdsg::VectorizableOverlay::get_base(const struct handlegraph::handle_t &, unsigned long) const --> char", pybind11::arg("handle"), pybind11::arg("index")); cl.def("get_subsequence", (std::string (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &, unsigned long, unsigned long) const) &bdsg::VectorizableOverlay::get_subsequence, "Returns a substring of a handle's sequence, in the orientation of the\n handle. If the indicated substring would extend beyond the end of the\n handle's sequence, the return value is truncated to the sequence's end.\n\nC++: bdsg::VectorizableOverlay::get_subsequence(const struct handlegraph::handle_t &, unsigned long, unsigned long) const --> std::string", pybind11::arg("handle"), pybind11::arg("index"), pybind11::arg("size")); cl.def("get_node_count", (unsigned long (bdsg::VectorizableOverlay::*)() const) &bdsg::VectorizableOverlay::get_node_count, "Return the number of nodes in the graph\n\nC++: bdsg::VectorizableOverlay::get_node_count() const --> unsigned long"); cl.def("min_node_id", (long long (bdsg::VectorizableOverlay::*)() const) &bdsg::VectorizableOverlay::min_node_id, "Return the smallest ID in the graph, or some smaller number if the\n smallest ID is unavailable. Return value is unspecified if the graph is empty.\n\nC++: bdsg::VectorizableOverlay::min_node_id() const --> long long"); cl.def("max_node_id", (long long (bdsg::VectorizableOverlay::*)() const) &bdsg::VectorizableOverlay::max_node_id, "Return the largest ID in the graph, or some larger number if the\n largest ID is unavailable. Return value is unspecified if the graph is empty.\n\nC++: bdsg::VectorizableOverlay::max_node_id() const --> long long"); cl.def("node_vector_offset", (unsigned long (bdsg::VectorizableOverlay::*)(const long long &) const) &bdsg::VectorizableOverlay::node_vector_offset, "Return the start position of the node in a (possibly implict) sorted array\n constructed from the concatenation of the node sequences\n\nC++: bdsg::VectorizableOverlay::node_vector_offset(const long long &) const --> unsigned long", pybind11::arg("node_id")); cl.def("node_at_vector_offset", (long long (bdsg::VectorizableOverlay::*)(const unsigned long &) const) &bdsg::VectorizableOverlay::node_at_vector_offset, "Return the node overlapping the given offset in the implicit node vector\n\nC++: bdsg::VectorizableOverlay::node_at_vector_offset(const unsigned long &) const --> long long", pybind11::arg("offset")); cl.def("edge_index", (unsigned long (bdsg::VectorizableOverlay::*)(const struct std::pair<struct handlegraph::handle_t, struct handlegraph::handle_t> &) const) &bdsg::VectorizableOverlay::edge_index, "Return a unique index among edges in the graph\n\nC++: bdsg::VectorizableOverlay::edge_index(const struct std::pair<struct handlegraph::handle_t, struct handlegraph::handle_t> &) const --> unsigned long", pybind11::arg("edge")); cl.def("id_to_rank", (unsigned long (bdsg::VectorizableOverlay::*)(const long long &) const) &bdsg::VectorizableOverlay::id_to_rank, "Return the rank of a node (ranks start at 1)\n\nC++: bdsg::VectorizableOverlay::id_to_rank(const long long &) const --> unsigned long", pybind11::arg("node_id")); cl.def("rank_to_id", (long long (bdsg::VectorizableOverlay::*)(const unsigned long &) const) &bdsg::VectorizableOverlay::rank_to_id, "Return the node with a given rank\n\nC++: bdsg::VectorizableOverlay::rank_to_id(const unsigned long &) const --> long long", pybind11::arg("rank")); cl.def("get_underlying_handle", (struct handlegraph::handle_t (bdsg::VectorizableOverlay::*)(const struct handlegraph::handle_t &) const) &bdsg::VectorizableOverlay::get_underlying_handle, "Returns the handle in the underlying graph that corresponds to a handle in the\n overlay\n\nC++: bdsg::VectorizableOverlay::get_underlying_handle(const struct handlegraph::handle_t &) const --> struct handlegraph::handle_t", pybind11::arg("handle")); } { // bdsg::PathVectorizableOverlay file:bdsg/overlays/vectorizable_overlays.hpp line:197 pybind11::class_<bdsg::PathVectorizableOverlay, std::shared_ptr<bdsg::PathVectorizableOverlay>, PyCallBack_bdsg_PathVectorizableOverlay, bdsg::VectorizableOverlay, handlegraph::PathHandleGraph> cl(M("bdsg"), "PathVectorizableOverlay", ""); cl.def( pybind11::init<const class handlegraph::PathHandleGraph *>(), pybind11::arg("path_graph") ); cl.def( pybind11::init( [](){ return new bdsg::PathVectorizableOverlay(); }, [](){ return new PyCallBack_bdsg_PathVectorizableOverlay(); } ) ); cl.def("get_path_count", (unsigned long (bdsg::PathVectorizableOverlay::*)() const) &bdsg::PathVectorizableOverlay::get_path_count, "Returns the number of paths stored in the graph\n\nC++: bdsg::PathVectorizableOverlay::get_path_count() const --> unsigned long"); cl.def("has_path", (bool (bdsg::PathVectorizableOverlay::*)(const std::string &) const) &bdsg::PathVectorizableOverlay::has_path, "Determine if a path name exists and is legal to get a path handle for.\n\nC++: bdsg::PathVectorizableOverlay::has_path(const std::string &) const --> bool", pybind11::arg("path_name")); cl.def("get_path_handle", (struct handlegraph::path_handle_t (bdsg::PathVectorizableOverlay::*)(const std::string &) const) &bdsg::PathVectorizableOverlay::get_path_handle, "Look up the path handle for the given path name.\n The path with that name must exist.\n\nC++: bdsg::PathVectorizableOverlay::get_path_handle(const std::string &) const --> struct handlegraph::path_handle_t", pybind11::arg("path_name")); cl.def("get_path_name", (std::string (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::get_path_name, "Look up the name of a path from a handle to it\n\nC++: bdsg::PathVectorizableOverlay::get_path_name(const struct handlegraph::path_handle_t &) const --> std::string", pybind11::arg("path_handle")); cl.def("get_is_circular", (bool (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::get_is_circular, "Look up whether a path is circular\n\nC++: bdsg::PathVectorizableOverlay::get_is_circular(const struct handlegraph::path_handle_t &) const --> bool", pybind11::arg("path_handle")); cl.def("get_step_count", (unsigned long (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::get_step_count, "Returns the number of node steps in the path\n\nC++: bdsg::PathVectorizableOverlay::get_step_count(const struct handlegraph::path_handle_t &) const --> unsigned long", pybind11::arg("path_handle")); cl.def("get_handle_of_step", (struct handlegraph::handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::get_handle_of_step, "Get a node handle (node ID and orientation) from a handle to an step on a path\n\nC++: bdsg::PathVectorizableOverlay::get_handle_of_step(const struct handlegraph::step_handle_t &) const --> struct handlegraph::handle_t", pybind11::arg("step_handle")); cl.def("get_path_handle_of_step", (struct handlegraph::path_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::get_path_handle_of_step, "Returns a handle to the path that an step is on\n\nC++: bdsg::PathVectorizableOverlay::get_path_handle_of_step(const struct handlegraph::step_handle_t &) const --> struct handlegraph::path_handle_t", pybind11::arg("step_handle")); cl.def("path_begin", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::path_begin, "Get a handle to the first step, which will be an arbitrary step in a circular path\n that we consider \"first\" based on our construction of the path. If the path is empty,\n then the implementation must return the same value as path_end().\n\nC++: bdsg::PathVectorizableOverlay::path_begin(const struct handlegraph::path_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("path_handle")); cl.def("path_end", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::path_end, "Get a handle to a fictitious position past the end of a path. This position is\n returned by get_next_step for the final step in a path in a non-circular path.\n Note: get_next_step will *NEVER* return this value for a circular path.\n\nC++: bdsg::PathVectorizableOverlay::path_end(const struct handlegraph::path_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("path_handle")); cl.def("path_back", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::path_back, "Get a handle to the last step, which will be an arbitrary step in a circular path that\n we consider \"last\" based on our construction of the path. If the path is empty\n then the implementation must return the same value as path_front_end().\n\nC++: bdsg::PathVectorizableOverlay::path_back(const struct handlegraph::path_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("path_handle")); cl.def("path_front_end", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::path_handle_t &) const) &bdsg::PathVectorizableOverlay::path_front_end, "Get a handle to a fictitious position before the beginning of a path. This position is\n return by get_previous_step for the first step in a path in a non-circular path.\n Note: get_previous_step will *NEVER* return this value for a circular path.\n\nC++: bdsg::PathVectorizableOverlay::path_front_end(const struct handlegraph::path_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("path_handle")); cl.def("has_next_step", (bool (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::has_next_step, "Returns true if the step is not the last step in a non-circular path.\n\nC++: bdsg::PathVectorizableOverlay::has_next_step(const struct handlegraph::step_handle_t &) const --> bool", pybind11::arg("step_handle")); cl.def("has_previous_step", (bool (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::has_previous_step, "Returns true if the step is not the first step in a non-circular path.\n\nC++: bdsg::PathVectorizableOverlay::has_previous_step(const struct handlegraph::step_handle_t &) const --> bool", pybind11::arg("step_handle")); cl.def("get_next_step", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::get_next_step, "Returns a handle to the next step on the path. If the given step is the final step\n of a non-circular path, this method has undefined behavior. In a circular path,\n the \"last\" step will loop around to the \"first\" step.\n\nC++: bdsg::PathVectorizableOverlay::get_next_step(const struct handlegraph::step_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("step_handle")); cl.def("get_previous_step", (struct handlegraph::step_handle_t (bdsg::PathVectorizableOverlay::*)(const struct handlegraph::step_handle_t &) const) &bdsg::PathVectorizableOverlay::get_previous_step, "Returns a handle to the previous step on the path. If the given step is the first\n step of a non-circular path, this method has undefined behavior. In a circular path,\n it will loop around from the \"first\" step (i.e. the one returned by path_begin) to\n the \"last\" step.\n\nC++: bdsg::PathVectorizableOverlay::get_previous_step(const struct handlegraph::step_handle_t &) const --> struct handlegraph::step_handle_t", pybind11::arg("step_handle")); } }
#include <cstdio> #include <algorithm> using namespace std; int main() { int N, P; scanf("%d %d", &N, &P); static const int M = 10000; static int from[M], to[M]; for (int i = 0; i < P; i++) { scanf("%d %d", &from[i], &to[i]); --from[i]; --to[i]; if (from[i] > to[i]) { swap(from[i], to[i]); } } int ans = 10000; for (int i = 0; i < N; i++) { // do not use the edge: (i) - (i+1) static int v[1000]; fill_n(v, N, 0); for (int j = 0; j < P; j++) { if (from[j] <= i && i+1 <= to[j]) { ++v[0]; --v[from[j]]; ++v[to[j]]; } else { ++v[from[j]]; --v[to[j]]; } } int c = 0; int acc = 0; for (int j = 0; j < N; j++) { acc += v[j]; if (acc > 0) { ++c; } } ans = min(ans, c); } printf("%d\n", ans); return 0; }
#include "MapScreen.h" #include "Strategic_Event_Handler.h" #include "MemMan.h" #include "Item_Types.h" #include "Items.h" #include "Handle_Items.h" #include "LaptopSave.h" #include "Tactical_Save.h" #include "StrategicMap.h" #include "Quests.h" #include "Soldier_Profile.h" #include "Game_Event_Hook.h" #include "Game_Clock.h" #include "Interface_Dialogue.h" #include "Random.h" #include "Overhead.h" #include "Strategic_Town_Loyalty.h" #include "Soldier_Init_List.h" #include "SaveLoadMap.h" #include "Soldier_Create.h" #include "Soldier_Add.h" #include "OppList.h" #include "EMail.h" #include "Structure_Wrap.h" #include "History.h" #include "BobbyRMailOrder.h" #include "ShippingDestinationModel.h" #include "ContentManager.h" #include "GameInstance.h" #include "policy/GamePolicy.h" #include "strategic/NpcPlacementModel.h" #include "MercProfile.h" #include "MercProfileInfo.h" UINT32 guiPabloExtraDaysBribed = 0; UINT8 gubCambriaMedicalObjects; static BOOLEAN CloseCrate(const INT16 x, const INT16 y, const INT8 z, const GridNo grid_no) { // Determine if the sector is loaded if (gWorldSectorX == x && gWorldSectorY == y && gbWorldSectorZ == z) { SetOpenableStructureToClosed(grid_no, 0); return TRUE; } else { ChangeStatusOfOpenableStructInUnloadedSector(x, y, z, grid_no, FALSE); return FALSE; } } static void DropOffItemsInDestination(UINT8 ubOrderNum, const ShippingDestinationModel* shippingDest); void BobbyRayPurchaseEventCallback(const UINT8 ubOrderID) { static UINT8 ubShipmentsSinceNoBribes = 0; NewBobbyRayOrderStruct* const shipment = &gpNewBobbyrShipments[ubOrderID]; auto dest = GCM->getShippingDestination(shipment->ubDeliveryLoc); if (shipment->fActive && dest->canDeliver && !dest->isPrimary) { // the delivery is not for Drassen, use a simple logic (reliable delivery) to handle delivery arrival there DropOffItemsInDestination(ubOrderID, dest); return; } UINT16 usStandardMapPos = dest->deliverySectorGridNo; auto destSector = StrategicMap[SECTOR_INFO_TO_STRATEGIC_INDEX(dest->getDeliverySector())]; if (CheckFact(FACT_NEXT_PACKAGE_CAN_BE_LOST, 0)) { SetFactFalse(FACT_NEXT_PACKAGE_CAN_BE_LOST); if (Random(100) < 50) { // lose the whole shipment! shipment->fActive = FALSE; SetFactTrue(FACT_LAST_SHIPMENT_CRASHED); return; } } else if (CheckFact(FACT_NEXT_PACKAGE_CAN_BE_DELAYED, 0)) { // shipment went to wrong airport... reroute all items to a temporary // gridno to represent the other airport (and damage them) SetFactTrue(FACT_LAST_SHIPMENT_WENT_TO_WRONG_AIRPORT); SetFactFalse(FACT_NEXT_PACKAGE_CAN_BE_DELAYED); usStandardMapPos = LOST_SHIPMENT_GRIDNO; } else if (gTownLoyalty[destSector.bNameId].ubRating < 20 || destSector.fEnemyControlled) { // loss of the whole shipment shipment->fActive = FALSE; SetFactTrue(FACT_AGENTS_PREVENTED_SHIPMENT); return; } //Must get the total number of items ( all item types plus how many of each item type ordered ) BOOLEAN fThisShipmentIsFromJohnKulba = FALSE; //if it is, dont add an email UINT16 usNumberOfItems = 0; for (UINT8 i = 0; i < shipment->ubNumberPurchases; ++i) { const BobbyRayPurchaseStruct* const purchase = &shipment->BobbyRayPurchase[i]; // Count how many items were purchased usNumberOfItems += purchase->ubNumberPurchased; //if any items are AutoMags if (purchase->usItemIndex == AUTOMAG_III) { //This shipment is from John Kulba, dont add an email from bobby ray fThisShipmentIsFromJohnKulba = TRUE; } } const BOOLEAN fSectorLoaded = CloseCrate(dest->deliverySectorX, dest->deliverySectorY, dest->deliverySectorZ, dest->deliverySectorGridNo); OBJECTTYPE* pObject = NULL; OBJECTTYPE* pStolenObject = NULL; if (!fSectorLoaded) // if we are NOT currently in the right sector { //build an array of objects to be added pObject = new OBJECTTYPE[usNumberOfItems]{}; pStolenObject = new OBJECTTYPE[usNumberOfItems]{}; } // check for potential theft UINT32 uiChanceOfTheft; if (CheckFact(FACT_PABLO_WONT_STEAL, 0) || gamepolicy(pablo_wont_steal)) { uiChanceOfTheft = 0; } else if (CheckFact(FACT_PABLOS_BRIBED, 0)) { // Since Pacos has some money, reduce record of # of shipments since last bribed... ubShipmentsSinceNoBribes /= 2; uiChanceOfTheft = 0; } else { ++ubShipmentsSinceNoBribes; // this chance might seem high but it's only applied at most to every second item uiChanceOfTheft = 12 + Random(4 * ubShipmentsSinceNoBribes); } UINT32 uiCount = 0; UINT32 uiStolenCount = 0; BOOLEAN fPablosStoleSomething = FALSE; BOOLEAN fPablosStoleLastItem = FALSE; for (UINT8 i = 0; i < shipment->ubNumberPurchases; ++i) { const BobbyRayPurchaseStruct* const purchase = &shipment->BobbyRayPurchase[i]; UINT16 const usItem = purchase->usItemIndex; OBJECTTYPE Object; CreateItem(usItem, purchase->bItemQuality, &Object); if (GCM->getItem(usItem)->getItemClass() == IC_GUN) { /* Empty out the bullets put in by CreateItem(). We now sell all guns * empty of bullets. This is done for BobbyR simply to be consistent with * the dealers in Arulco, who must sell guns empty to prevent ammo cheats * by players. */ Object.ubGunShotsLeft = 0; } //add all the items that were purchased UINT8 const ubItemsPurchased = purchase->ubNumberPurchased; UINT8 ubItemsDelivered = 0; for (UINT8 j = 0; j < ubItemsPurchased; ++j) { // Pablos might steal stuff but only: // - if it's one of a group of items // - if he didn't steal the previous item in the group (so he never steals > 50%) // - if he has been bribed, he only sneaks out stuff which is cheap if (fSectorLoaded) { // add ubItemsPurchased to the chance of theft so the chance increases when there are more items of a kind being ordered if (!fPablosStoleLastItem && uiChanceOfTheft > 0 && Random(100) < uiChanceOfTheft + ubItemsPurchased) { ++uiStolenCount; fPablosStoleSomething = TRUE; fPablosStoleLastItem = TRUE; } else { fPablosStoleLastItem = FALSE; if (usStandardMapPos == LOST_SHIPMENT_GRIDNO) { // damage the item a random amount! const INT8 status = (70 + Random(11)) * (INT32)Object.bStatus[0] / 100; Object.bStatus[0] = MAX(1, status); AddItemToPool(usStandardMapPos, &Object, INVISIBLE, 0, 0, 0); } else { // record # delivered for later addition... ++ubItemsDelivered; } } } else { if (j > 1 && !fPablosStoleLastItem && uiChanceOfTheft > 0 && Random(100) < uiChanceOfTheft + j) { pStolenObject[uiStolenCount] = Object; ++uiStolenCount; fPablosStoleSomething = TRUE; fPablosStoleLastItem = TRUE; } else { fPablosStoleLastItem = FALSE; /* else we are not currently in the sector, so we build an array of * items to add in one lump add the item to the item array */ if (usStandardMapPos == LOST_SHIPMENT_GRIDNO) { // damage the item a random amount! const INT8 status = (70 + Random(11)) * (INT32)Object.bStatus[0] / 100; Object.bStatus[0] = MAX(1, status); pObject[uiCount++] = Object; } else { ++ubItemsDelivered; } } } } if (purchase->ubNumberPurchased == 1 && ubItemsDelivered == 1) { // the item in Object will be the item to deliver if (fSectorLoaded) { AddItemToPool(usStandardMapPos, &Object, INVISIBLE, 0, 0, 0); } else { pObject[uiCount++] = Object; } } else { while (ubItemsDelivered) { // treat 0s as 1s :-) const UINT8 ubTempNumItems = __min(ubItemsDelivered, __max(1, GCM->getItem(usItem)->getPerPocket())); CreateItems(usItem, purchase->bItemQuality, ubTempNumItems, &Object); // stack as many as possible if (fSectorLoaded) { AddItemToPool(usStandardMapPos, &Object, INVISIBLE, 0, 0, 0); } else { pObject[uiCount++] = Object; } ubItemsDelivered -= ubTempNumItems; } } } //if we are NOT currently in the sector if (!fSectorLoaded) { //add all the items from the array that was built above //The item are to be added to the Top part of Drassen, grid loc's 10112, 9950 AddItemsToUnLoadedSector(dest->deliverySectorX, dest->deliverySectorY, dest->deliverySectorZ, usStandardMapPos, uiCount, pObject, 0, 0, 0, INVISIBLE); if (uiStolenCount > 0) { AddItemsToUnLoadedSector(dest->deliverySectorX, dest->deliverySectorY, dest->deliverySectorZ, PABLOS_STOLEN_DEST_GRIDNO, uiStolenCount, pStolenObject, 0, 0, 0, INVISIBLE); } delete[] pObject; delete[] pStolenObject; } if (fPablosStoleSomething) { SetFactTrue(FACT_PABLOS_STOLE_FROM_LATEST_SHIPMENT); } else { SetFactFalse(FACT_PABLOS_STOLE_FROM_LATEST_SHIPMENT); } SetFactFalse(FACT_LARGE_SIZED_OLD_SHIPMENT_WAITING); if (CheckFact(FACT_NEXT_PACKAGE_CAN_BE_DELAYED, 0)) { SetFactFalse(FACT_MEDIUM_SIZED_SHIPMENT_WAITING); SetFactFalse(FACT_LARGE_SIZED_SHIPMENT_WAITING); SetFactFalse(FACT_REALLY_NEW_BOBBYRAY_SHIPMENT_WAITING); } else { if (usNumberOfItems - uiStolenCount <= 5) { SetFactFalse(FACT_MEDIUM_SIZED_SHIPMENT_WAITING); SetFactFalse(FACT_LARGE_SIZED_SHIPMENT_WAITING); } else if (usNumberOfItems - uiStolenCount <= 15) { SetFactTrue(FACT_MEDIUM_SIZED_SHIPMENT_WAITING); SetFactFalse(FACT_LARGE_SIZED_SHIPMENT_WAITING); } else { SetFactFalse(FACT_MEDIUM_SIZED_SHIPMENT_WAITING); SetFactTrue(FACT_LARGE_SIZED_SHIPMENT_WAITING); } // this shipment isn't old yet... SetFactTrue(FACT_REALLY_NEW_BOBBYRAY_SHIPMENT_WAITING); // set up even to make shipment "old" AddSameDayStrategicEvent(EVENT_SET_BY_NPC_SYSTEM, GetWorldMinutesInDay() + 120, FACT_REALLY_NEW_BOBBYRAY_SHIPMENT_WAITING); } //We have received the shipment so fActice becomes fALSE shipment->fActive = FALSE; //Stop time compression the game StopTimeCompression(); //if the shipment is NOT from John Kulba, send an email if (!fThisShipmentIsFromJohnKulba) { //Add an email from Bobby r telling the user the shipment 'Should' be there AddEmail(dest->emailOffset, dest->emailLength, BOBBY_R, GetWorldTotalMin()); } else { //if the shipment is from John Kulba //Add an email from kulba telling the user the shipment is there AddEmail(JOHN_KULBA_GIFT_IN_DRASSEN, JOHN_KULBA_GIFT_IN_DRASSEN_LENGTH, JOHN_KULBA, GetWorldTotalMin()); } } static void HandleDelayedItemsArrival(UINT32 uiReason) { // This function moves all the items that Pablos has stolen // (or items that were delayed) to the arrival location for new shipments, INT16 sStartGridNo; UINT8 ubLoop; OBJECTTYPE Object; auto shippingDest = GCM->getPrimaryShippingDestination(); if (uiReason == NPC_SYSTEM_EVENT_ACTION_PARAM_BONUS + NPC_ACTION_RETURN_STOLEN_SHIPMENT_ITEMS ) { if ( gMercProfiles[ PABLO ].bMercStatus == MERC_IS_DEAD ) { // nothing arrives then! return; } // update some facts... SetFactTrue( FACT_PABLO_RETURNED_GOODS ); SetFactFalse( FACT_PABLO_PUNISHED_BY_PLAYER ); sStartGridNo = PABLOS_STOLEN_DEST_GRIDNO; // add random items for (ubLoop = 0; ubLoop < 2; ubLoop++) { switch( Random( 10 ) ) { case 0: // 1 in 10 chance of a badly damaged gas mask CreateItem( GASMASK, (INT8) (20 + Random( 10 )), &Object ); break; case 1: case 2: // 2 in 10 chance of a battered Desert Eagle CreateItem( DESERTEAGLE, (INT8) (40 + Random( 10 )), &Object ); break; case 3: case 4: case 5: // 3 in 10 chance of a stun grenade CreateItem( STUN_GRENADE, (INT8) (70 + Random( 10 )), &Object ); break; case 6: case 7: case 8: case 9: // 4 in 10 chance of two 38s! CreateItems( SW38, (INT8) (90 + Random( 10 )), 2, &Object ); break; } if ( ( gWorldSectorX == shippingDest->deliverySectorX) && ( gWorldSectorY == shippingDest->deliverySectorY) && ( gbWorldSectorZ == shippingDest->deliverySectorZ ) ) { AddItemToPool(shippingDest->deliverySectorGridNo, &Object, INVISIBLE, 0, 0, 0); } else { AddItemsToUnLoadedSector(shippingDest->deliverySectorX, shippingDest->deliverySectorY, shippingDest->deliverySectorZ, shippingDest->deliverySectorGridNo, 1, &Object, 0, 0, 0, INVISIBLE); } } } else if (uiReason == FACT_PACKAGE_DAMAGED) { sStartGridNo = LOST_SHIPMENT_GRIDNO; } else { return; } // If the Drassen airport sector is already loaded, move the item pools... if ( ( gWorldSectorX == shippingDest->deliverySectorX ) && ( gWorldSectorY == shippingDest->deliverySectorY ) && ( gbWorldSectorZ == shippingDest->deliverySectorZ ) ) { // sector is loaded! // just move the hidden item pool MoveItemPools( sStartGridNo, shippingDest->deliverySectorGridNo ); } else { // otherwise load the saved items from the item file and change the records of their locations std::vector<WORLDITEM> pTemp = LoadWorldItemsFromTempItemFile(shippingDest->deliverySectorX, shippingDest->deliverySectorY, shippingDest->deliverySectorZ); for (WORLDITEM& wi : pTemp) { if (wi.sGridNo == PABLOS_STOLEN_DEST_GRIDNO) { wi.sGridNo = shippingDest->deliverySectorGridNo; } } SaveWorldItemsToTempItemFile(shippingDest->deliverySectorX, shippingDest->deliverySectorY, shippingDest->deliverySectorZ, pTemp); } } void AddSecondAirportAttendant( void ) { // add the second airport attendant to the Drassen airport... MERCPROFILESTRUCT& sal = GetProfile(SAL); auto shippingDest = GCM->getPrimaryShippingDestination(); sal.sSectorX = shippingDest->deliverySectorX; sal.sSectorY = shippingDest->deliverySectorY; sal.bSectorZ = shippingDest->deliverySectorZ; } static void SetPabloToUnbribed(void) { if (guiPabloExtraDaysBribed > 0) { // set new event for later on, because the player gave Pablo more money! AddFutureDayStrategicEvent( EVENT_SET_BY_NPC_SYSTEM, GetWorldMinutesInDay(), FACT_PABLOS_BRIBED, guiPabloExtraDaysBribed ); guiPabloExtraDaysBribed = 0; } else { SetFactFalse( FACT_PABLOS_BRIBED ); } } static void HandlePossiblyDamagedPackage(void) { if (Random( 100 ) < 70) { SetFactTrue( FACT_PACKAGE_DAMAGED ); HandleDelayedItemsArrival( FACT_PACKAGE_DAMAGED ); } else { // shipment lost forever! SetFactTrue( FACT_PACKAGE_LOST_PERMANENTLY ); } // whatever happened, the shipment is no longer delayed SetFactFalse( FACT_SHIPMENT_DELAYED_24_HOURS ); } void CheckForKingpinsMoneyMissing( BOOLEAN fFirstCheck ) { UINT32 uiTotalCash = 0; BOOLEAN fKingpinWillDiscover = FALSE, fKingpinDiscovers = FALSE; // money in D5b1 must be less than 30k CFOR_EACH_WORLD_ITEM(wi) { OBJECTTYPE const& o = wi.o; if (o.usItem == MONEY) uiTotalCash += o.uiMoneyAmount; } // This function should be called every time sector D5/B1 is unloaded! if ( fFirstCheck ) { if ( CheckFact( FACT_KINGPIN_WILL_LEARN_OF_MONEY_GONE, 0 ) == TRUE ) { // unnecessary return; } if ( uiTotalCash < 30000 ) { // add history log here AddHistoryToPlayersLog( HISTORY_FOUND_MONEY, 0, GetWorldTotalMin(), gWorldSectorX, gWorldSectorY ); SetFactTrue( FACT_KINGPIN_WILL_LEARN_OF_MONEY_GONE ); } } if ( CheckFact( FACT_KINGPIN_DEAD, 0 ) == TRUE ) { return; } if ( uiTotalCash < 30000 ) { if ( fFirstCheck ) { // add event to make Kingpin aware, two days from now fKingpinWillDiscover = TRUE; } else { fKingpinDiscovers = TRUE; } } if ( fKingpinWillDiscover ) { // set event for next day to check for real AddFutureDayStrategicEvent( EVENT_SET_BY_NPC_SYSTEM, Random( 120 ), FACT_KINGPIN_KNOWS_MONEY_GONE, 1 ); // the sector is unloaded NOW so set Kingpin's balance and remove the cash gMercProfiles[ KINGPIN ].iBalance = - (30000 - (INT32) uiTotalCash); // remove all money from map FOR_EACH_WORLD_ITEM(wi) { if (wi.o.usItem == MONEY) wi.fExists = FALSE; // remove! } } else if ( fKingpinDiscovers ) { // ok start things up here! SetFactTrue( FACT_KINGPIN_KNOWS_MONEY_GONE ); // set event 2 days from now that if the player has not given Kingpin his money back, // he sends email to the player AddFutureDayStrategicEvent( EVENT_SET_BY_NPC_SYSTEM, Random( 120 ), FACT_KINGPIN_KNOWS_MONEY_GONE, 2 ); } } void HandleNPCSystemEvent( UINT32 uiEvent ) { if (uiEvent < NPC_SYSTEM_EVENT_ACTION_PARAM_BONUS) { switch( uiEvent ) { case FACT_PABLOS_BRIBED: // set Pacos to unbribed SetPabloToUnbribed(); break; case FACT_REALLY_NEW_BOBBYRAY_SHIPMENT_WAITING: // the shipment is no longer really new SetFactFalse( FACT_REALLY_NEW_BOBBYRAY_SHIPMENT_WAITING ); if (CheckFact( FACT_LARGE_SIZED_SHIPMENT_WAITING, 0 )) { // set "really heavy old shipment" fact SetFactTrue( FACT_LARGE_SIZED_OLD_SHIPMENT_WAITING ); } break; case FACT_SHIPMENT_DELAYED_24_HOURS: case FACT_24_HOURS_SINCE_DOCTOR_TALKED_TO: case FACT_24_HOURS_SINCE_JOEY_RESCUED: SetFactTrue((Fact)uiEvent); break; case FACT_KINGPIN_KNOWS_MONEY_GONE: // more generally events for kingpin quest if (!CheckFact(FACT_KINGPIN_KNOWS_MONEY_GONE, 0)) { // check for real whether to start quest CheckForKingpinsMoneyMissing( FALSE ); } else if (!CheckFact(FACT_KINGPIN_DEAD, 0)) { if ( gubQuest[ QUEST_KINGPIN_MONEY ] == QUESTNOTSTARTED ) { // KP knows money is gone, hasn't told player, if this event is called then the 2 // days are up... send email AddEmail( KING_PIN_LETTER, KING_PIN_LETTER_LENGTH, KING_PIN, GetWorldTotalMin() ); StartQuest( QUEST_KINGPIN_MONEY, 5, MAP_ROW_D ); // add event to send terrorists two days from now AddFutureDayStrategicEvent( EVENT_SET_BY_NPC_SYSTEM, Random( 120 ), FACT_KINGPIN_KNOWS_MONEY_GONE, 2 ); } else if ( gubQuest[ QUEST_KINGPIN_MONEY ] == QUESTINPROGRESS ) { // knows money gone, quest is still in progress // event indicates Kingpin can start to send terrorists SetFactTrue( FACT_KINGPIN_CAN_SEND_ASSASSINS ); gMercProfiles[ SPIKE ].sSectorX = 5; gMercProfiles[ SPIKE ].sSectorY = MAP_ROW_C; gTacticalStatus.fCivGroupHostile[ KINGPIN_CIV_GROUP ] = CIV_GROUP_WILL_BECOME_HOSTILE; } } break; } } else { switch( uiEvent - NPC_SYSTEM_EVENT_ACTION_PARAM_BONUS ) { case NPC_ACTION_RETURN_STOLEN_SHIPMENT_ITEMS: HandleDelayedItemsArrival( uiEvent ); break; case NPC_ACTION_SET_RANDOM_PACKAGE_DAMAGE_TIMER: HandlePossiblyDamagedPackage(); break; case NPC_ACTION_ENABLE_CAMBRIA_DOCTOR_BONUS: SetFactTrue( FACT_WILLIS_HEARD_ABOUT_JOEY_RESCUE ); break; case NPC_ACTION_TRIGGER_END_OF_FOOD_QUEST: if ( gMercProfiles[ FATHER ].bMercStatus != MERC_IS_DEAD ) { EndQuest( QUEST_FOOD_ROUTE, 10, MAP_ROW_A ); SetFactTrue( FACT_FOOD_QUEST_OVER ); } break; case NPC_ACTION_DELAYED_MAKE_BRENDA_LEAVE: //IC: //TriggerNPCRecord(BRENDA, 9); SetFactTrue( FACT_BRENDA_PATIENCE_TIMER_EXPIRED ); break; case NPC_ACTION_SET_DELAY_TILL_GIRLS_AVAILABLE: HandleNPCDoAction( 107, NPC_ACTION_SET_GIRLS_AVAILABLE, 0 ); break; case NPC_ACTION_READY_ROBOT: { if ( CheckFact( FACT_FIRST_ROBOT_DESTROYED, 0 ) ) { // second robot ready SetFactTrue( FACT_ROBOT_READY_SECOND_TIME ); // resurrect robot gMercProfiles[ ROBOT ].bLife = gMercProfiles[ ROBOT ].bLifeMax; gMercProfiles[ ROBOT ].bMercStatus = MERC_OK; } else { // first robot ready SetFactTrue( FACT_ROBOT_READY ); } gMercProfiles[ ROBOT ].sSectorX = gMercProfiles[ MADLAB ].sSectorX; gMercProfiles[ ROBOT ].sSectorY = gMercProfiles[ MADLAB ].sSectorY; gMercProfiles[ ROBOT ].bSectorZ = gMercProfiles[ MADLAB ].bSectorZ; } break; case NPC_ACTION_ADD_JOEY_TO_WORLD: // If Joey is not dead, escorted, or already delivered if ( gMercProfiles[ JOEY ].bMercStatus != MERC_IS_DEAD && !CheckFact( FACT_JOEY_ESCORTED, 0 ) && gMercProfiles[ JOEY ].sSectorX == 4 && gMercProfiles[ JOEY ].sSectorY == MAP_ROW_D && gMercProfiles[ JOEY ].bSectorZ == 1 ) { const SOLDIERTYPE* const pJoey = FindSoldierByProfileID(JOEY); if (pJoey ) { // he's in the currently loaded sector...delay this an hour! AddSameDayStrategicEvent( EVENT_SET_BY_NPC_SYSTEM, GetWorldMinutesInDay() + 60, NPC_SYSTEM_EVENT_ACTION_PARAM_BONUS + NPC_ACTION_ADD_JOEY_TO_WORLD ); } else { // move Joey from caves to San Mona gMercProfiles[ JOEY ].sSectorX = 5; gMercProfiles[ JOEY ].sSectorY = MAP_ROW_C; gMercProfiles[ JOEY ].bSectorZ = 0; } } break; case NPC_ACTION_SEND_ENRICO_MIGUEL_EMAIL: AddEmail( ENRICO_MIGUEL, ENRICO_MIGUEL_LENGTH, MAIL_ENRICO, GetWorldTotalMin() ); break; case NPC_ACTION_TIMER_FOR_VEHICLE: SetFactTrue( FACT_OK_USE_HUMMER ); break; case NPC_ACTION_FREE_KIDS: SetFactTrue( FACT_KIDS_ARE_FREE ); break; default: break; } } } void HandleEarlyMorningEvents( void ) { UINT32 cnt; UINT32 uiAmount; // loop through all *NPCs* and reset "default response used recently" flags for (const MercProfile* profile : GCM->listMercProfiles()) { if (!profile->isNPCorRPC()) continue; MERCPROFILESTRUCT& p = profile->getStruct(); p.bFriendlyOrDirectDefaultResponseUsedRecently = FALSE; p.bRecruitDefaultResponseUsedRecently = FALSE; p.bThreatenDefaultResponseUsedRecently = FALSE; p.ubMiscFlags2 &= (~PROFILE_MISC_FLAG2_BANDAGED_TODAY); } // reset Father Walker's drunkenness level! gMercProfiles[ FATHER ].bNPCData = (INT8) Random( 4 ); // set Walker's location if ( Random( 2 ) ) { // move the father to the other sector, provided neither are loaded if ( ! ( ( gWorldSectorX == 13) && ( ( gWorldSectorY == MAP_ROW_C) || gWorldSectorY == MAP_ROW_D ) && ( gbWorldSectorZ == 0 ) ) ) { gMercProfiles[ FATHER ].sSectorX = 13; // swap his location if (gMercProfiles[ FATHER ].sSectorY == MAP_ROW_C) { gMercProfiles[ FATHER ].sSectorY = MAP_ROW_D; } else { gMercProfiles[ FATHER ].sSectorY = MAP_ROW_C; } } } if( gMercProfiles[ TONY ].ubLastDateSpokenTo > 0 && !( gWorldSectorX == 5 && gWorldSectorY == MAP_ROW_C && gbWorldSectorZ == 0 ) ) { // San Mona C5 is not loaded so make Tony possibly not available if (Random( 4 )) { // Tony IS available SetFactFalse( FACT_TONY_NOT_AVAILABLE ); gMercProfiles[ TONY ].sSectorX = 5; gMercProfiles[ TONY ].sSectorY = MAP_ROW_C; } else { // Tony is NOT available SetFactTrue( FACT_TONY_NOT_AVAILABLE ); gMercProfiles[ TONY ].sSectorX = 0; gMercProfiles[ TONY ].sSectorY = 0; } } if ( gMercProfiles[ DEVIN ].ubLastDateSpokenTo == 0 ) { // Does Devin move? gMercProfiles[ DEVIN ].bNPCData++; if ( gMercProfiles[ DEVIN ].bNPCData > 3 ) { if ( ! ( (gWorldSectorX == gMercProfiles[ DEVIN ].sSectorX) && (gWorldSectorY == gMercProfiles[DEVIN].sSectorY) && (gbWorldSectorZ == 0) ) ) { // ok, Devin's sector not loaded, so time to move! // might be same sector as before, if so, oh well! auto placement = GCM->getNpcPlacement(DEVIN); UINT8 sector = placement->pickPlacementSector(); gMercProfiles[DEVIN].sSectorX = SECTORX(sector); gMercProfiles[DEVIN].sSectorY = SECTORY(sector); } } } // Does Hamous move? // stop moving the truck if Hamous is dead!! // stop moving them if the player has the truck or Hamous is hired! if (gMercProfiles[HAMOUS].bLife > 0 && FindSoldierByProfileIDOnPlayerTeam(HAMOUS) == NULL && FindSoldierByProfileIDOnPlayerTeam(PROF_ICECREAM) == NULL && (gWorldSectorX != gMercProfiles[HAMOUS].sSectorX || gWorldSectorY != gMercProfiles[HAMOUS].sSectorY || gbWorldSectorZ != 0)) { // ok, HAMOUS's sector not loaded, so time to move! // might be same sector as before, if so, oh well! auto placement = GCM->getNpcPlacement(HAMOUS); UINT8 sector = placement->pickPlacementSector(); gMercProfiles[HAMOUS].sSectorX = SECTORX(sector); gMercProfiles[HAMOUS].sSectorY = SECTORY(sector); gMercProfiles[PROF_ICECREAM].sSectorX = SECTORX(sector); gMercProfiles[PROF_ICECREAM].sSectorY = SECTORY(sector); } // Does Rat take off? if ( gMercProfiles[ RAT ].bNPCData != 0 ) { gMercProfiles[ RAT ].sSectorX = 0; gMercProfiles[ RAT ].sSectorY = 0; gMercProfiles[ RAT ].bSectorZ = 0; } // Empty money from pockets of Vince 69, Willis 80, and Jenny 132 SetMoneyInSoldierProfile( VINCE, 0 ); SetMoneyInSoldierProfile( STEVE, 0 ); // Steven Willis SetMoneyInSoldierProfile( JENNY, 0 ); // Vince is no longer expecting money SetFactFalse( FACT_VINCE_EXPECTING_MONEY ); // Reset Darren's balance and money gMercProfiles[ DARREN ].iBalance = 0; SetMoneyInSoldierProfile( DARREN, 15000 ); // set Carmen to be placed on the map in case he moved and is waiting off screen if (gMercProfiles[ CARMEN ].ubMiscFlags2 & PROFILE_MISC_FLAG2_DONT_ADD_TO_SECTOR) { gMercProfiles[ CARMEN ].ubMiscFlags2 &= ~(PROFILE_MISC_FLAG2_DONT_ADD_TO_SECTOR); // move Carmen to C13 gMercProfiles[ CARMEN ].sSectorX = 13; gMercProfiles[ CARMEN ].sSectorY = MAP_ROW_C; gMercProfiles[ CARMEN ].bSectorZ = 0; // we should also reset # of terrorist heads and give him cash if (gMercProfiles[ CARMEN ].bNPCData2 > 0) { if (gMercProfiles[ CARMEN ].uiMoney < 10000) { uiAmount = 0; } else { uiAmount = gMercProfiles[ CARMEN ].uiMoney; } uiAmount += 10000 * gMercProfiles[ CARMEN ].bNPCData2; SetMoneyInSoldierProfile( CARMEN, uiAmount ); gMercProfiles[ CARMEN ].bNPCData2 = 0; for ( cnt = HEAD_1; cnt <= HEAD_7; cnt++ ) { RemoveObjectFromSoldierProfile( CARMEN, (UINT8) cnt ); } } } else { // randomize where he'll be today... so long as his sector's not loaded if ( gMercProfiles[ CARMEN ].sSectorX != gWorldSectorX || gMercProfiles[ CARMEN ].sSectorY != gWorldSectorY ) { auto placement = GCM->getNpcPlacement(CARMEN); UINT8 sector = placement->pickPlacementSector(); gMercProfiles[CARMEN].sSectorX = SECTORX(sector); gMercProfiles[CARMEN].sSectorY = SECTORY(sector); // he should have $5000... unless the player forgot to meet him if (gMercProfiles[ CARMEN ].uiMoney < 5000) { SetMoneyInSoldierProfile( CARMEN, 5000 ); } } } if ( PreRandom( 3 ) == 0 ) { SetFactTrue( FACT_DAVE_HAS_GAS ); } else { SetFactFalse( FACT_DAVE_HAS_GAS ); } if ( gWorldSectorX == HOSPITAL_SECTOR_X && gWorldSectorY == HOSPITAL_SECTOR_Y && gbWorldSectorZ == HOSPITAL_SECTOR_Z ) { CheckForMissingHospitalSupplies(); } } void MakeCivGroupHostileOnNextSectorEntrance( UINT8 ubCivGroup ) { // if it's the rebels that will become hostile, reduce town loyalties NOW, not later if ( ubCivGroup == REBEL_CIV_GROUP && gTacticalStatus.fCivGroupHostile[ ubCivGroup ] == CIV_GROUP_NEUTRAL ) { ReduceLoyaltyForRebelsBetrayed(); } gTacticalStatus.fCivGroupHostile[ ubCivGroup ] = CIV_GROUP_WILL_BECOME_HOSTILE; } void RemoveAssassin( UINT8 ubProfile ) { gMercProfiles[ ubProfile ].sSectorX = 0; gMercProfiles[ ubProfile ].sSectorY = 0; gMercProfiles[ ubProfile ].bLife = gMercProfiles[ ubProfile ].bLifeMax; } void CheckForMissingHospitalSupplies( void ) { UINT8 ubMedicalObjects = 0; CFOR_EACH_WORLD_ITEM(wi) { // loop through all items, look for ownership if (wi.o.usItem != OWNERSHIP || wi.o.ubOwnerCivGroup != DOCTORS_CIV_GROUP) continue; const ITEM_POOL* pItemPool = GetItemPool(wi.sGridNo, 0); while( pItemPool ) { OBJECTTYPE const& o = GetWorldItem(pItemPool->iItemIndex).o; if (o.bStatus[0] > 60) { if (o.usItem == FIRSTAIDKIT || o.usItem == MEDICKIT || o.usItem == REGEN_BOOSTER || o.usItem == ADRENALINE_BOOSTER) { ubMedicalObjects++; } } pItemPool = pItemPool->pNext; } } if ( CheckFact( FACT_PLAYER_STOLE_MEDICAL_SUPPLIES_AGAIN, 0 ) == TRUE ) { // player returning stuff! if back to full then can operate if ( ubMedicalObjects >= gubCambriaMedicalObjects ) { SetFactFalse( FACT_PLAYER_STOLE_MEDICAL_SUPPLIES_AGAIN ); SetFactFalse( FACT_PLAYER_STOLE_MEDICAL_SUPPLIES ); return; } } if ( ubMedicalObjects < gubCambriaMedicalObjects ) { // player's stolen something! if (!CheckFact(FACT_PLAYER_STOLE_MEDICAL_SUPPLIES, 0)) { SetFactTrue( FACT_PLAYER_STOLE_MEDICAL_SUPPLIES ); } // if only 1/5 or less left, give up the ghost if ( ubMedicalObjects * 5 <= gubCambriaMedicalObjects ) { // run out! SetFactTrue( FACT_PLAYER_STOLE_MEDICAL_SUPPLIES_AGAIN ); } } } static void DropOffItemsInDestination(UINT8 ubOrderNum, const ShippingDestinationModel* shippingDest) { OBJECTTYPE Object; UINT32 uiCount = 0; OBJECTTYPE *pObject=NULL; UINT16 usNumberOfItems=0, usItem; UINT8 ubItemsDelivered, ubTempNumItems; UINT32 i; //if the player doesnt "own" the sector, if (StrategicMap[SECTOR_INFO_TO_STRATEGIC_INDEX(shippingDest->getDeliverySector())].fEnemyControlled) { //the items disappear gpNewBobbyrShipments[ ubOrderNum ].fActive = FALSE; return; } const BOOLEAN fSectorLoaded = CloseCrate(shippingDest->deliverySectorX, shippingDest->deliverySectorY, shippingDest->deliverySectorZ, shippingDest->deliverySectorGridNo); for(i=0; i<gpNewBobbyrShipments[ ubOrderNum ].ubNumberPurchases; i++) { // Count how many items were purchased usNumberOfItems += gpNewBobbyrShipments[ ubOrderNum ].BobbyRayPurchase[i].ubNumberPurchased; } //if we are NOT currently in the right sector if( !fSectorLoaded ) { //build an array of objects to be added pObject = new OBJECTTYPE[usNumberOfItems]{}; } uiCount = 0; //loop through the number of purchases for (i = 0; i < gpNewBobbyrShipments[0].ubNumberPurchases; i++)// FIXME shipment ubOrderNum instead of 0 { ubItemsDelivered = gpNewBobbyrShipments[ ubOrderNum ].BobbyRayPurchase[i].ubNumberPurchased; usItem = gpNewBobbyrShipments[ ubOrderNum ].BobbyRayPurchase[i].usItemIndex; while ( ubItemsDelivered ) { // treat 0s as 1s :-) ubTempNumItems = __min( ubItemsDelivered, __max( 1, GCM->getItem(usItem )->getPerPocket() ) ); CreateItems( usItem, gpNewBobbyrShipments[ ubOrderNum ].BobbyRayPurchase[i].bItemQuality, ubTempNumItems, &Object ); // stack as many as possible if( fSectorLoaded ) { AddItemToPool(shippingDest->deliverySectorGridNo, &Object, INVISIBLE, 0, 0, 0); } else { pObject[uiCount] = Object; uiCount++; } ubItemsDelivered -= ubTempNumItems; } } //if the sector WASNT loaded if( !fSectorLoaded ) { //add all the items from the array that was built above //The item are to be added to the Top part of Drassen, grid loc's 10112, 9950 AddItemsToUnLoadedSector(shippingDest->deliverySectorX, shippingDest->deliverySectorY, shippingDest->deliverySectorZ, shippingDest->deliverySectorGridNo, uiCount, pObject, 0, 0, 0, INVISIBLE); delete[] pObject; pObject = NULL; } //mark that the shipment has arrived gpNewBobbyrShipments[ ubOrderNum ].fActive = FALSE; if (shippingDest->emailOffset) { //Add an email telling the user the shipment is there AddEmail(shippingDest->emailOffset, shippingDest->emailLength, BOBBY_R, GetWorldTotalMin()); } else { SLOGW("Bobby Ray shipment arrived but no email template found."); } }
// Copyright (c) 2009-2021 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // this include is necessary to get MPI included before anything else to support intel MPI #include "hoomd/ExecutionConfiguration.h" #include <algorithm> #include <iostream> #include <memory> #include "hoomd/Initializers.h" #include "hoomd/md/NeighborList.h" #include "hoomd/md/NeighborListBinned.h" #include "hoomd/md/NeighborListStencil.h" #include "hoomd/md/NeighborListTree.h" #ifdef ENABLE_HIP #include "hoomd/md/NeighborListGPU.h" #include "hoomd/md/NeighborListGPUBinned.h" #include "hoomd/md/NeighborListGPUStencil.h" #include "hoomd/md/NeighborListGPUTree.h" #endif using namespace std; using namespace hoomd; using namespace hoomd::md; #include "hoomd/test/upp11_config.h" HOOMD_UP_MAIN(); //! Performs basic functionality tests on a neighbor list template<class NL> void neighborlist_basic_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { ///////////////////////////////////////////////////////// // start with the simplest possible test: 2 particles in a huge box std::shared_ptr<SystemDefinition> sysdef_2( new SystemDefinition(2, BoxDim(25.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_2 = sysdef_2->getParticleData(); { ArrayHandle<Scalar4> h_pos(pdata_2->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = h_pos.data[0].y = h_pos.data[0].z = 0.0; h_pos.data[1].x = h_pos.data[1].y = h_pos.data[1].z = 3.25; h_pos.data[0].w = 0.0; h_pos.data[1].w = 0.0; pdata_2->notifyParticleSort(); } // test construction of the neighborlist std::shared_ptr<NeighborList> nlist_2(new NL(sysdef_2, 0.25)); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist_2->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; } nlist_2->addRCutMatrix(r_cut); nlist_2->compute(1); // with the given radius, there should be no neighbors: check that { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); } // adjust the radius to include the particles and see if we get some now { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 5.5; nlist_2->notifyRCutMatrixChange(); } nlist_2->compute(2); // some neighbor lists default to full because they don't support half: ignore them if (nlist_2->getStorageMode() == NeighborList::half) { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_2->getNListArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_nlist.data[0], 1); // since this is a half list, only 0 stores 1 as a neighbor CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); } // change to full mode to check that nlist_2->setStorageMode(NeighborList::full); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 5.5; nlist_2->notifyRCutMatrixChange(); } nlist_2->setRBuff(0.5); nlist_2->compute(3); { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_2->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_2->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 0], 0); } //////////////////////////////////////////////////////////////////// // now, lets do a more thorough test and include boundary conditions // there are way too many permutations to test here, so I will simply // test +x, -x, +y, -y, +z, and -z independently // build a 6 particle system with particles across each boundary std::shared_ptr<SystemDefinition> sysdef_6( new SystemDefinition(6, BoxDim(20.0, 40.0, 60.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_6 = sysdef_6->getParticleData(); { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = Scalar(-9.6); h_pos.data[0].y = 0; h_pos.data[0].z = 0.0; h_pos.data[0].w = 0.0; h_pos.data[1].x = Scalar(9.6); h_pos.data[1].y = 0; h_pos.data[1].z = 0.0; h_pos.data[1].w = 0.0; h_pos.data[2].x = 0; h_pos.data[2].y = Scalar(-19.6); h_pos.data[2].z = 0.0; h_pos.data[2].w = 0.0; h_pos.data[3].x = 0; h_pos.data[3].y = Scalar(19.6); h_pos.data[3].z = 0.0; h_pos.data[3].w = 0.0; h_pos.data[4].x = 0; h_pos.data[4].y = 0; h_pos.data[4].z = Scalar(-29.6); h_pos.data[4].w = 0.0; h_pos.data[5].x = 0; h_pos.data[5].y = 0; h_pos.data[5].z = Scalar(29.6); h_pos.data[5].w = 0.0; pdata_6->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_6(new NL(sysdef_6, 0.25)); nlist_6->addRCutMatrix(r_cut); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; nlist_6->notifyRCutMatrixChange(); } nlist_6->setStorageMode(NeighborList::full); nlist_6->compute(0); // verify the neighbor list { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); // check for right number of neighbors CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); CHECK_EQUAL_UINT(h_n_neigh.data[3], 1); CHECK_EQUAL_UINT(h_n_neigh.data[4], 1); CHECK_EQUAL_UINT(h_n_neigh.data[5], 1); // the answer we expect unsigned int check_nbrs[] = {1, 0, 3, 2, 5, 4}; // validate that the neighbors are correct for (unsigned int i = 0; i < 6; ++i) { UP_ASSERT_EQUAL(h_nlist.data[h_head_list.data[i]], check_nbrs[i]); } } // swap the order of the particles around to look for subtle directional bugs { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[1].x = Scalar(-9.6); h_pos.data[1].y = 0; h_pos.data[1].z = 0.0; h_pos.data[0].x = Scalar(9.6); h_pos.data[0].y = 0; h_pos.data[0].z = 0.0; h_pos.data[3].x = 0; h_pos.data[3].y = Scalar(-19.6); h_pos.data[3].z = 0.0; h_pos.data[2].x = 0; h_pos.data[2].y = Scalar(19.6); h_pos.data[2].z = 0.0; h_pos.data[5].x = 0; h_pos.data[5].y = 0; h_pos.data[5].z = Scalar(-29.6); h_pos.data[4].x = 0; h_pos.data[4].y = 0; h_pos.data[4].z = Scalar(29.6); pdata_6->notifyParticleSort(); } // verify the neighbor list nlist_6->compute(1); { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); // check for right number of nbrs CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); CHECK_EQUAL_UINT(h_n_neigh.data[3], 1); CHECK_EQUAL_UINT(h_n_neigh.data[4], 1); CHECK_EQUAL_UINT(h_n_neigh.data[5], 1); // the answer we expect unsigned int check_nbrs[] = {1, 0, 3, 2, 5, 4}; for (unsigned int i = 0; i < 6; ++i) { UP_ASSERT_EQUAL(h_nlist.data[h_head_list.data[i]], check_nbrs[i]); } } // one last test, we should check that more than one neighbor can be generated { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0; h_pos.data[0].y = 0; h_pos.data[0].z = 0.0; h_pos.data[1].x = 0; h_pos.data[1].y = 0; h_pos.data[1].z = 0.0; h_pos.data[2].x = 0; h_pos.data[2].y = Scalar(-19.6); h_pos.data[2].z = 0.0; h_pos.data[3].x = 0; h_pos.data[3].y = Scalar(19.6); h_pos.data[3].z = 0.0; h_pos.data[4].x = 0; h_pos.data[4].y = 0; h_pos.data[4].z = 0; h_pos.data[5].x = 0; h_pos.data[5].y = 0; h_pos.data[5].z = 0; pdata_6->notifyParticleSort(); } nlist_6->compute(20); { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 3); vector<unsigned int> nbrs(3, 0); for (unsigned int i = 0; i < 3; ++i) { nbrs[i] = h_nlist.data[h_head_list.data[0] + i]; } // sort the neighbors because it doesn't matter what order they are stored in, just that // they all are there sort(nbrs.begin(), nbrs.end()); // the answer we expect unsigned int check_nbrs[] = {1, 4, 5}; for (unsigned int i = 0; i < 3; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } } //! Test neighborlist functionality with particles with different numbers of neighbors template<class NL> void neighborlist_particle_asymm_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { std::shared_ptr<SystemDefinition> sysdef_3( new SystemDefinition(3, BoxDim(40.0, 40.0, 60.0), 2, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_3 = sysdef_3->getParticleData(); // check that pair cutoffs are set independently { ArrayHandle<Scalar4> h_pos(pdata_3->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0.0; h_pos.data[0].y = 0.0; h_pos.data[0].z = 0.0; h_pos.data[0].w = __int_as_scalar(1); h_pos.data[1].x = Scalar(1.2); h_pos.data[1].y = 0.0; h_pos.data[1].z = 0.0; h_pos.data[1].w = __int_as_scalar(0); h_pos.data[2].x = Scalar(3.5); h_pos.data[2].y = 0.0; h_pos.data[2].z = 0.0; h_pos.data[2].w = __int_as_scalar(1); pdata_3->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_3(new NL(sysdef_3, 0.25)); nlist_3->setStorageMode(NeighborList::full); Index2D type_pair_idx = nlist_3->getTypePairIndexer(); auto r_cut = std::make_shared<GlobalArray<Scalar>>(type_pair_idx.getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[type_pair_idx(0, 0)] = 1.0; h_r_cut.data[type_pair_idx(1, 1)] = 3.0; h_r_cut.data[type_pair_idx(0, 1)] = 2.0; h_r_cut.data[type_pair_idx(1, 0)] = 2.0; } nlist_3->addRCutMatrix(r_cut); nlist_3->compute(0); // 1 is neighbor of 0 but not of 2 { ArrayHandle<unsigned int> h_n_neigh(nlist_3->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_3->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_3->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 0); } // now change the cutoff so that 2 is neighbors with 0 but not 1 { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[type_pair_idx(1, 1)] = 3.5; nlist_3->notifyRCutMatrixChange(); } nlist_3->compute(1); { ArrayHandle<unsigned int> h_n_neigh(nlist_3->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_3->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_3->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 2); vector<unsigned int> nbrs(2, 0); nbrs[0] = h_nlist.data[h_head_list.data[0] + 0]; nbrs[1] = h_nlist.data[h_head_list.data[0] + 1]; sort(nbrs.begin(), nbrs.end()); unsigned int check_nbrs[] = {1, 2}; for (unsigned int i = 0; i < 2; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 0], 0); } // now change the cutoff so that all are neighbors { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[type_pair_idx(0, 1)] = 2.5; h_r_cut.data[type_pair_idx(1, 0)] = 2.5; nlist_3->notifyRCutMatrixChange(); } nlist_3->compute(20); { ArrayHandle<unsigned int> h_n_neigh(nlist_3->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_3->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_3->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 2); CHECK_EQUAL_UINT(h_n_neigh.data[1], 2); CHECK_EQUAL_UINT(h_n_neigh.data[2], 2); } // check what happens with particle resize by first keeping number below the 8 default, and then // bumping over this do this with size 18 so that NeighborListGPU is forced to use kernel call // with multiple levels at m_bin_size = 4 std::shared_ptr<SystemDefinition> sysdef_18( new SystemDefinition(18, BoxDim(40.0, 40.0, 40.0), 2, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_18 = sysdef_18->getParticleData(); { ArrayHandle<Scalar4> h_pos(pdata_18->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0.0; h_pos.data[0].y = 0.0; h_pos.data[0].z = 0.0; h_pos.data[0].w = __int_as_scalar(1); h_pos.data[1].x = 0.0; h_pos.data[1].y = 0.0; h_pos.data[1].z = 0.0; h_pos.data[1].w = __int_as_scalar(1); h_pos.data[2].x = 0.0; h_pos.data[2].y = 0.0; h_pos.data[2].z = 0.0; h_pos.data[2].w = __int_as_scalar(1); h_pos.data[3].x = Scalar(10.0); h_pos.data[3].y = 0.0; h_pos.data[3].z = 0.0; h_pos.data[3].w = __int_as_scalar(1); h_pos.data[4].x = Scalar(0.9); h_pos.data[4].y = 0.0; h_pos.data[4].z = 0.0; h_pos.data[4].w = __int_as_scalar(0); h_pos.data[5].x = Scalar(-0.9); h_pos.data[5].y = 0.0; h_pos.data[5].z = 0.0; h_pos.data[5].w = __int_as_scalar(0); h_pos.data[6].x = 0.0; h_pos.data[6].y = Scalar(0.9); h_pos.data[6].z = 0.0; h_pos.data[6].w = __int_as_scalar(0); h_pos.data[7].x = 0.0; h_pos.data[7].y = Scalar(-0.9); h_pos.data[7].z = 0.0; h_pos.data[7].w = __int_as_scalar(0); h_pos.data[8].x = 0.0; h_pos.data[8].y = 0.0; h_pos.data[8].z = Scalar(0.9); h_pos.data[8].w = __int_as_scalar(0); h_pos.data[9].x = 0.0; h_pos.data[9].y = 0.0; h_pos.data[9].z = Scalar(-0.9); h_pos.data[9].w = __int_as_scalar(0); h_pos.data[10].x = Scalar(0.9); h_pos.data[10].y = 0.0; h_pos.data[10].z = 0.0; h_pos.data[10].w = __int_as_scalar(0); h_pos.data[11].x = Scalar(-0.9); h_pos.data[11].y = 0.0; h_pos.data[11].z = 0.0; h_pos.data[11].w = __int_as_scalar(0); h_pos.data[12].x = 0.0; h_pos.data[12].y = Scalar(0.9); h_pos.data[12].z = 0.0; h_pos.data[12].w = __int_as_scalar(0); h_pos.data[13].x = 0.0; h_pos.data[13].y = Scalar(-0.9); h_pos.data[13].z = 0.0; h_pos.data[13].w = __int_as_scalar(0); h_pos.data[14].x = 0.0; h_pos.data[14].y = 0.0; h_pos.data[14].z = Scalar(0.9); h_pos.data[14].w = __int_as_scalar(0); h_pos.data[15].x = 0.0; h_pos.data[15].y = 0.0; h_pos.data[15].z = Scalar(-0.9); h_pos.data[15].w = __int_as_scalar(0); h_pos.data[16].x = Scalar(-10.0); h_pos.data[16].y = 0.0; h_pos.data[16].z = 0.0; h_pos.data[16].w = __int_as_scalar(1); h_pos.data[17].x = 0.0; h_pos.data[17].y = Scalar(10.0); h_pos.data[17].z = 0.0; h_pos.data[17].w = __int_as_scalar(1); pdata_18->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_18(new NL(sysdef_18, 0.05)); type_pair_idx = nlist_18->getTypePairIndexer(); r_cut = std::make_shared<GlobalArray<Scalar>>(type_pair_idx.getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[type_pair_idx(0, 0)] = 1.0; h_r_cut.data[type_pair_idx(1, 1)] = 1.0; h_r_cut.data[type_pair_idx(0, 1)] = 1.0; h_r_cut.data[type_pair_idx(1, 0)] = 1.0; } nlist_18->addRCutMatrix(r_cut); nlist_18->setStorageMode(NeighborList::full); nlist_18->compute(0); // 0-2 have 15 neighbors, 3 and 16 have no neighbors, and all others have 4 neighbors { ArrayHandle<unsigned int> h_n_neigh(nlist_18->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_18->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_18->getHeadList(), access_location::host, access_mode::read); for (unsigned int i = 0; i < 18; ++i) { if (i < 3) { CHECK_EQUAL_UINT(h_n_neigh.data[i], 14); } else if (i == 3 || i >= 16) { CHECK_EQUAL_UINT(h_n_neigh.data[i], 0); } else { CHECK_EQUAL_UINT(h_n_neigh.data[i], 4); } } } // bring in particle 3, 16, and 17, which should force a resize on particle type 1 { ArrayHandle<Scalar4> h_pos(pdata_18->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[3].x = 0.0; h_pos.data[16].x = 0.0; h_pos.data[17].y = 0.0; pdata_18->notifyParticleSort(); } nlist_18->compute(20); { ArrayHandle<unsigned int> h_n_neigh(nlist_18->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_18->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_18->getHeadList(), access_location::host, access_mode::read); for (unsigned int i = 0; i < 18; ++i) { if (i <= 3 || i >= 16) { CHECK_EQUAL_UINT(h_n_neigh.data[i], 17); } else { CHECK_EQUAL_UINT(h_n_neigh.data[i], 7); } } } // collapse all particles onto self and force a resize { ArrayHandle<Scalar4> h_pos(pdata_18->getPositions(), access_location::host, access_mode::readwrite); for (unsigned int i = 4; i < 16; ++i) { h_pos.data[i].x = 0.0; h_pos.data[i].y = 0.0; h_pos.data[i].z = 0.0; } pdata_18->notifyParticleSort(); } nlist_18->compute(40); { ArrayHandle<unsigned int> h_n_neigh(nlist_18->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_18->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_18->getHeadList(), access_location::host, access_mode::read); for (unsigned int i = 0; i < 18; ++i) { CHECK_EQUAL_UINT(h_n_neigh.data[i], 17); } } } //! Test neighborlist functionality with changing types template<class NL> void neighborlist_type_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { std::shared_ptr<SystemDefinition> sysdef_6( new SystemDefinition(6, BoxDim(40.0, 40.0, 40.0), 8, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_6 = sysdef_6->getParticleData(); // test 1: 4 types, but missing two in the middle { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); for (unsigned int cur_p = 0; cur_p < 6; ++cur_p) { if (cur_p < 5) { h_pos.data[cur_p] = make_scalar4(-1.0, 0.0, 0.0, __int_as_scalar(3)); } else { h_pos.data[cur_p] = make_scalar4(1.0, 0.0, 0.0, __int_as_scalar(0)); } } pdata_6->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_6(new NL(sysdef_6, 0.1)); Index2D type_pair_idx = nlist_6->getTypePairIndexer(); auto r_cut = std::make_shared<GlobalArray<Scalar>>(type_pair_idx.getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); for (unsigned int i = 0; i < type_pair_idx.getW(); i++) { for (unsigned int j = 0; j < type_pair_idx.getH(); j++) { h_r_cut.data[type_pair_idx(i, j)] = 3.0; } } } nlist_6->addRCutMatrix(r_cut); nlist_6->setStorageMode(NeighborList::full); nlist_6->compute(0); // everybody should neighbor everybody else { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 5); CHECK_EQUAL_UINT(h_n_neigh.data[1], 5); CHECK_EQUAL_UINT(h_n_neigh.data[2], 5); CHECK_EQUAL_UINT(h_n_neigh.data[3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[4], 5); CHECK_EQUAL_UINT(h_n_neigh.data[5], 5); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); for (unsigned int cur_p = 0; cur_p < 6; ++cur_p) { vector<unsigned int> nbrs(5, 0), check_nbrs; // create the sorted list of computed neighbors for (unsigned int cur_neigh = 0; cur_neigh < 5; ++cur_neigh) { nbrs[cur_neigh] = h_nlist.data[h_head_list.data[cur_p] + cur_neigh]; } sort(nbrs.begin(), nbrs.end()); // create the list of expected neighbors (everybody except for myself) check_nbrs.reserve(5); for (unsigned int i = 0; i < 6; ++i) { if (i != cur_p) { check_nbrs.push_back(i); } } sort(check_nbrs.begin(), check_nbrs.end()); for (unsigned int i = 0; i < 5; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } } type_pair_idx = nlist_6->getTypePairIndexer(); r_cut->resize(type_pair_idx.getNumElements()); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); // set r_cut to 3.0 for all type pairs for (unsigned int i = 0; i < type_pair_idx.getW(); i++) { for (unsigned int j = 0; j < type_pair_idx.getH(); j++) { h_r_cut.data[type_pair_idx(i, j)] = 3.0; } } // then disable the interaction between type 6 and all other particles for (unsigned int cur_type = 0; cur_type < pdata_6->getNTypes(); ++cur_type) { h_r_cut.data[type_pair_idx(6, cur_type)] = -1.0; h_r_cut.data[type_pair_idx(cur_type, 6)] = -1.0; } } nlist_6->notifyRCutMatrixChange(); // shuffle all of the particle types and retest { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].w = __int_as_scalar(2); h_pos.data[1].w = __int_as_scalar(4); h_pos.data[2].w = __int_as_scalar(0); h_pos.data[3].w = __int_as_scalar(1); h_pos.data[4].w = __int_as_scalar(7); h_pos.data[5].w = __int_as_scalar(6); pdata_6->notifyParticleSort(); } nlist_6->compute(30); // particle 5 (type 6) should have no neighbors, all others have 4 { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 4); CHECK_EQUAL_UINT(h_n_neigh.data[1], 4); CHECK_EQUAL_UINT(h_n_neigh.data[2], 4); CHECK_EQUAL_UINT(h_n_neigh.data[3], 4); CHECK_EQUAL_UINT(h_n_neigh.data[4], 4); CHECK_EQUAL_UINT(h_n_neigh.data[5], 0); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); // just check the first 5 particles, since the last has no neighbors for (unsigned int cur_p = 0; cur_p < 5; ++cur_p) { vector<unsigned int> nbrs(4, 0), check_nbrs; // create the sorted list of computed neighbors for (unsigned int cur_neigh = 0; cur_neigh < 4; ++cur_neigh) { nbrs[cur_neigh] = h_nlist.data[h_head_list.data[cur_p] + cur_neigh]; } sort(nbrs.begin(), nbrs.end()); // create the list of expected neighbors (everybody except for myself) check_nbrs.reserve(5); for (unsigned int i = 0; i < 5; ++i) { if (i != cur_p) { check_nbrs.push_back(i); } } sort(check_nbrs.begin(), check_nbrs.end()); for (unsigned int i = 0; i < 4; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } } } //! Tests the ability of the neighbor list to exclude particle pairs template<class NL> void neighborlist_exclusion_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { std::shared_ptr<SystemDefinition> sysdef_6( new SystemDefinition(6, BoxDim(20.0, 40.0, 60.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_6 = sysdef_6->getParticleData(); // lets make this test simple: put all 6 particles on top of each other and // see if the exclusion code can ignore 4 of the particles { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0; h_pos.data[0].y = 0; h_pos.data[0].z = 0.0; h_pos.data[0].w = 0.0; h_pos.data[1].x = 0; h_pos.data[1].y = 0; h_pos.data[1].z = 0.0; h_pos.data[1].w = 0.0; h_pos.data[2].x = 0; h_pos.data[2].y = 0; h_pos.data[2].z = 0.0; h_pos.data[2].w = 0.0; h_pos.data[3].x = 0; h_pos.data[3].y = 0; h_pos.data[3].z = 0.0; h_pos.data[3].w = 0.0; h_pos.data[4].x = 0; h_pos.data[4].y = 0; h_pos.data[4].z = 0; h_pos.data[4].w = 0.0; h_pos.data[5].x = 0; h_pos.data[5].y = 0; h_pos.data[5].z = 0; h_pos.data[5].w = 0.0; pdata_6->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_6(new NL(sysdef_6, 0.25)); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist_6->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; } nlist_6->addRCutMatrix(r_cut); nlist_6->setStorageMode(NeighborList::full); nlist_6->addExclusion(0, 1); nlist_6->addExclusion(0, 2); nlist_6->addExclusion(0, 3); nlist_6->addExclusion(0, 4); nlist_6->compute(0); { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); // UP_ASSERT(nli.getW() >= 6); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 0], 5); CHECK_EQUAL_UINT(h_n_neigh.data[1], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 0], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 1], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 1], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[3], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 1], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[4], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 1], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 2], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[5], 5); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 2], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 3], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 4], 4); } } //! Tests the ability of the neighbor list to exclude particles from the same body template<class NL> void neighborlist_body_filter_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { std::shared_ptr<SystemDefinition> sysdef_6( new SystemDefinition(6, BoxDim(20.0, 40.0, 60.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_6 = sysdef_6->getParticleData(); // lets make this test simple: put all 6 particles on top of each other and // see if the exclusion code can ignore 4 of the particles { ArrayHandle<Scalar4> h_pos(pdata_6->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<unsigned int> h_body(pdata_6->getBodies(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0; h_pos.data[0].y = 0; h_pos.data[0].z = 0; h_pos.data[0].w = 0.0; h_body.data[0] = NO_BODY; h_pos.data[1].x = 0; h_pos.data[1].y = 0; h_pos.data[1].z = 0; h_pos.data[1].w = 0.0; h_body.data[1] = 0; h_pos.data[2].x = 0; h_pos.data[2].y = 0; h_pos.data[2].z = 0; h_pos.data[2].w = 0.0; h_body.data[2] = 1; h_pos.data[3].x = 0; h_pos.data[3].y = 0; h_pos.data[3].z = 0; h_pos.data[3].w = 0.0; h_body.data[3] = 0; h_pos.data[4].x = 0; h_pos.data[4].y = 0; h_pos.data[4].z = 0; h_pos.data[4].w = 0.0; h_body.data[4] = 1; h_pos.data[5].x = 0; h_pos.data[5].y = 0; h_pos.data[5].z = 0; h_pos.data[5].w = 0.0; h_body.data[5] = NO_BODY; pdata_6->notifyParticleSort(); } std::shared_ptr<NeighborList> nlist_6(new NL(sysdef_6, 0.25)); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist_6->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; } nlist_6->addRCutMatrix(r_cut); nlist_6->setFilterBody(true); nlist_6->setStorageMode(NeighborList::full); nlist_6->compute(0); { ArrayHandle<unsigned int> h_n_neigh(nlist_6->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_6->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_6->getHeadList(), access_location::host, access_mode::read); // UP_ASSERT(nli.getW() >= 6); CHECK_EQUAL_UINT(h_n_neigh.data[0], 5); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 0], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 1], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 2], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 3], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0] + 4], 5); CHECK_EQUAL_UINT(h_n_neigh.data[1], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 1], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 2], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[3], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 1], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 2], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[3] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[4], 4); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 2], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[4] + 3], 5); CHECK_EQUAL_UINT(h_n_neigh.data[5], 5); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 0], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 2], 2); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 3], 3); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[5] + 4], 4); } } //! Tests the ability of the neighbor list to filter by diameter template<class NL> void neighborlist_diameter_shift_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { ///////////////////////////////////////////////////////// // start with the simplest possible test: 3 particles in a huge box std::shared_ptr<SystemDefinition> sysdef_3( new SystemDefinition(4, BoxDim(25.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_3 = sysdef_3->getParticleData(); { ArrayHandle<Scalar4> h_pos(pdata_3->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_diameter(pdata_3->getDiameters(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0; h_pos.data[0].y = 0; h_pos.data[0].z = 0.0; h_pos.data[0].w = 0.0; h_diameter.data[0] = 3.0; h_pos.data[2].x = 0; h_pos.data[2].y = 0; h_pos.data[2].z = 2.5; h_pos.data[2].w = 0.0; h_diameter.data[2] = 2.0; h_pos.data[1].x = 0; h_pos.data[1].y = 0; h_pos.data[1].z = -3.0; h_pos.data[1].w = 0.0; h_diameter.data[1] = 1.0; h_pos.data[3].x = 0; h_pos.data[3].y = 2.51; h_pos.data[3].z = 0; h_pos.data[3].w = 0.0; h_diameter.data[3] = 0; pdata_3->notifyParticleSort(); } // test construction of the neighborlist std::shared_ptr<NeighborList> nlist_2(new NL(sysdef_3, 0.5)); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist_2->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 1.5; } nlist_2->addRCutMatrix(r_cut); nlist_2->compute(1); nlist_2->setStorageMode(NeighborList::full); // with the given settings, there should be no neighbors: check that { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 0); } // enable diameter shifting nlist_2->setDiameterShift(true); nlist_2->setMaximumDiameter(3.0); nlist_2->compute(2); // the particle 0 should now be neighbors with 1 and 2 { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_2->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_2->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 2); { vector<unsigned int> nbrs(2, 0); nbrs[0] = h_nlist.data[h_head_list.data[0] + 0]; nbrs[1] = h_nlist.data[h_head_list.data[0] + 1]; sort(nbrs.begin(), nbrs.end()); unsigned int check_nbrs[] = {1, 2}; for (unsigned int i = 0; i < 2; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2]], 0); } } //! Tests the ability of the neighbor list to filter by diameter, wrapping across periodic boundary //! conditions template<class NL> void neighborlist_diameter_shift_periodic_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { ///////////////////////////////////////////////////////// // 3 particles in a huge box, close to boundaries std::shared_ptr<SystemDefinition> sysdef_3( new SystemDefinition(4, BoxDim(25.0), 1, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_3 = sysdef_3->getParticleData(); { ArrayHandle<Scalar4> h_pos(pdata_3->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar> h_diameter(pdata_3->getDiameters(), access_location::host, access_mode::readwrite); h_pos.data[0].x = 0; h_pos.data[0].y = 12; h_pos.data[0].z = -10.5; h_pos.data[0].w = 0.0; h_diameter.data[0] = 3.0; h_pos.data[2].x = 0; h_pos.data[2].y = 12; h_pos.data[2].z = -8; h_pos.data[2].w = 0.0; h_diameter.data[2] = 2.0; h_pos.data[1].x = 0; h_pos.data[1].y = 12; h_pos.data[1].z = 11.5; h_pos.data[1].w = 0.0; h_diameter.data[1] = 1.0; h_pos.data[3].x = 0; h_pos.data[3].y = -10.49; h_pos.data[3].z = -10.5; h_pos.data[3].w = 0.0; h_diameter.data[3] = 0; pdata_3->notifyParticleSort(); } // test construction of the neighborlist std::shared_ptr<NeighborList> nlist_2(new NL(sysdef_3, 0.5)); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist_2->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 1.5; } nlist_2->addRCutMatrix(r_cut); nlist_2->compute(1); nlist_2->setStorageMode(NeighborList::full); // with the given settings, there should be no neighbors: check that { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 0); } // enable diameter shifting nlist_2->setDiameterShift(true); nlist_2->setMaximumDiameter(3.0); nlist_2->compute(2); // the particle 0 should now be neighbors with 1 and 2 { ArrayHandle<unsigned int> h_n_neigh(nlist_2->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist_2->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist_2->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 2); { vector<unsigned int> nbrs(2, 0); nbrs[0] = h_nlist.data[h_head_list.data[0] + 0]; nbrs[1] = h_nlist.data[h_head_list.data[0] + 1]; sort(nbrs.begin(), nbrs.end()); unsigned int check_nbrs[] = {1, 2}; for (unsigned int i = 0; i < 2; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2]], 0); } } //! Test two implementations of NeighborList and verify that the output is identical template<class NLA, class NLB> void neighborlist_comparison_test(std::shared_ptr<ExecutionConfiguration> exec_conf) { // construct the particle system RandomInitializer init(1000, Scalar(0.016778), Scalar(0.9), "A"); std::shared_ptr<SnapshotSystemData<Scalar>> snap = init.getSnapshot(); std::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(snap, exec_conf)); std::shared_ptr<ParticleData> pdata = sysdef->getParticleData(); std::shared_ptr<NeighborList> nlist1(new NLA(sysdef, Scalar(0.4))); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist1->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; } nlist1->addRCutMatrix(r_cut); nlist1->setStorageMode(NeighborList::full); std::shared_ptr<NeighborList> nlist2(new NLB(sysdef, Scalar(0.4))); nlist2->addRCutMatrix(r_cut); nlist2->setStorageMode(NeighborList::full); // setup some exclusions: try to fill out all four exclusions for each particle for (unsigned int i = 0; i < pdata->getN() - 2; i++) { nlist1->addExclusion(i, i + 1); nlist1->addExclusion(i, i + 2); nlist2->addExclusion(i, i + 1); nlist2->addExclusion(i, i + 2); } // compute each of the lists nlist1->compute(0); nlist2->compute(0); // verify that both new ones match the basic ArrayHandle<unsigned int> h_n_neigh1(nlist1->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist1(nlist1->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list1(nlist1->getHeadList(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_n_neigh2(nlist2->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist2(nlist2->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list2(nlist2->getHeadList(), access_location::host, access_mode::read); // temporary vectors for holding the lists: they will be sorted for compariso std::vector<unsigned int> tmp_list2; // check to make sure that every neighbor matches for (unsigned int i = 0; i < pdata->getN(); i++) { UP_ASSERT(h_n_neigh2.data[i] >= h_n_neigh1.data[i]); // test list std::vector<unsigned int> test_list(h_n_neigh2.data[i]); for (unsigned int j = 0; j < h_n_neigh2.data[i]; ++j) { test_list[j] = h_nlist2.data[h_head_list2.data[i] + j]; } // check all elements from ref list are in the test list for (unsigned int j = 0; j < h_n_neigh1.data[i]; ++j) { const size_t ref_idx = h_nlist1.data[h_head_list1.data[i] + j]; bool found = std::find(test_list.begin(), test_list.end(), ref_idx) != test_list.end(); if (!found) { std::cout << "Neighbor " << ref_idx << " from reference list not found in test list for particle " << i << "." << std::endl; UP_ASSERT(false); } } } } //! Test that a NeighborList can successfully exclude a ridiculously large number of particles template<class NL> void neighborlist_large_ex_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { // construct the particle system RandomInitializer init(1000, Scalar(0.016778), Scalar(0.9), "A"); std::shared_ptr<SnapshotSystemData<Scalar>> snap = init.getSnapshot(); std::shared_ptr<SystemDefinition> sysdef(new SystemDefinition(snap, exec_conf)); std::shared_ptr<ParticleData> pdata = sysdef->getParticleData(); std::shared_ptr<NeighborList> nlist(new NL(sysdef, Scalar(0.4))); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 8.0; } nlist->addRCutMatrix(r_cut); nlist->setStorageMode(NeighborList::full); // add every single neighbor as an exclusion nlist->compute(0); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); for (unsigned int i = 0; i < pdata->getN(); i++) { for (unsigned int neigh = 0; neigh < h_n_neigh.data[i]; neigh++) { unsigned int j = h_nlist.data[h_head_list.data[i] + neigh]; nlist->addExclusion(i, j); } } } // compute the nlist again nlist->compute(0); // verify that there are now 0 neighbors for each particle ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); // check to make sure that every neighbor matches for (unsigned int i = 0; i < pdata->getN(); i++) { CHECK_EQUAL_UINT(h_n_neigh.data[i], 0); } } //! Test that NeighborList can exclude particles correctly when cutoff radius is negative template<class NL> void neighborlist_cutoff_exclude_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { // Initialize a system of 3 particles each having a distinct type std::shared_ptr<SystemDefinition> sysdef_3( new SystemDefinition(3, BoxDim(25.0), 3, 0, 0, 0, 0, exec_conf)); std::shared_ptr<ParticleData> pdata_3 = sysdef_3->getParticleData(); // put the particles on top of each other, the worst case scenario for inclusion / exclusion // since the distance between them is zero { ArrayHandle<Scalar4> h_pos(pdata_3->getPositions(), access_location::host, access_mode::overwrite); for (unsigned int i = 0; i < pdata_3->getN(); ++i) { h_pos.data[i] = make_scalar4(0.0, 0.0, 0.0, __int_as_scalar(i)); } } std::shared_ptr<NeighborList> nlist(new NL(sysdef_3, Scalar(0.4))); Index2D type_pair_idx = nlist->getTypePairIndexer(); auto r_cut = std::make_shared<GlobalArray<Scalar>>(type_pair_idx.getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); // Ignore all interactions for (unsigned int i = 0; i < pdata_3->getNTypes(); ++i) { for (unsigned int j = i; j < pdata_3->getNTypes(); ++j) { h_r_cut.data[type_pair_idx(i, j)] = -1.0; h_r_cut.data[type_pair_idx(j, i)] = -1.0; } } h_r_cut.data[0] = 3.0; } nlist->addRCutMatrix(r_cut); nlist->setStorageMode(NeighborList::full); // compute the neighbor list, each particle should have no neighbors nlist->compute(0); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); CHECK_EQUAL_UINT(h_n_neigh.data[2], 0); } { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); // turn on cross interaction with B particle for (unsigned int i = 0; i < pdata_3->getNTypes(); ++i) { h_r_cut.data[type_pair_idx(1, i)] = 1.0; h_r_cut.data[type_pair_idx(i, 1)] = 1.0; } } nlist->notifyRCutMatrixChange(); nlist->compute(1); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 2); // B ignores itself, but gets everyone else as a neighbor CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0]], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2]], 1); vector<unsigned int> nbrs(2, 0); nbrs[0] = h_nlist.data[h_head_list.data[1] + 0]; nbrs[1] = h_nlist.data[h_head_list.data[1] + 1]; sort(nbrs.begin(), nbrs.end()); unsigned int check_nbrs[] = {0, 2}; for (unsigned int i = 0; i < 2; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } // turn A-C on and B-C off with things very close to the < 0.0 criterion as a pathological // case { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[type_pair_idx(0, 2)] = 0.00001; h_r_cut.data[type_pair_idx(2, 0)] = 0.00001; h_r_cut.data[type_pair_idx(1, 2)] = -0.00001; h_r_cut.data[type_pair_idx(2, 1)] = -0.00001; } nlist->notifyRCutMatrixChange(); nlist->compute(3); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 2); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); CHECK_EQUAL_UINT(h_n_neigh.data[2], 1); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[2]], 0); vector<unsigned int> nbrs(2, 0); nbrs[0] = h_nlist.data[h_head_list.data[0] + 0]; nbrs[1] = h_nlist.data[h_head_list.data[0] + 1]; sort(nbrs.begin(), nbrs.end()); unsigned int check_nbrs[] = {1, 2}; for (unsigned int i = 0; i < 2; ++i) { UP_ASSERT_EQUAL(nbrs[i], check_nbrs[i]); } } } //! Tests for correctness of neighbor search in 2d systems template<class NL> void neighborlist_2d_tests(std::shared_ptr<ExecutionConfiguration> exec_conf) { auto sysdef = std::make_shared<SystemDefinition>(2, BoxDim(10.0, 10.0, 0.01), 1, 0, 0, 0, 0, exec_conf); sysdef->setNDimensions(2); auto pdata = sysdef->getParticleData(); auto nlist = std::make_shared<NL>(sysdef, 0.25); auto r_cut = std::make_shared<GlobalArray<Scalar>>(nlist->getTypePairIndexer().getNumElements(), exec_conf); { ArrayHandle<Scalar> h_r_cut(*r_cut, access_location::host, access_mode::overwrite); h_r_cut.data[0] = 3.0; } nlist->addRCutMatrix(r_cut); nlist->setStorageMode(NeighborList::full); // non-interacting inside the box { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = h_pos.data[0].y = 0.0; h_pos.data[1].x = h_pos.data[1].y = 3.0; h_pos.data[0].z = h_pos.data[1].z = 0.0; h_pos.data[0].w = __int_as_scalar(0.0); h_pos.data[1].w = __int_as_scalar(0.0); } nlist->compute(0); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); } // interacting inside the box { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = h_pos.data[0].y = 0.0; h_pos.data[1].x = h_pos.data[1].y = 1.0; } nlist->compute(1); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0]], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); } // non-interacting through boundary { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = h_pos.data[0].y = 4.9; h_pos.data[1].x = h_pos.data[1].y = -2.1; } nlist->compute(2); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); } // interacting through boundary { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = h_pos.data[0].y = 4.9; h_pos.data[1].x = h_pos.data[1].y = -4.9; } nlist->compute(3); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0]], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); } // non-interacting through other boundary { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = -4.9; h_pos.data[0].y = 4.9; h_pos.data[1].x = 2.1; h_pos.data[1].y = -2.1; } nlist->compute(4); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 0); CHECK_EQUAL_UINT(h_n_neigh.data[1], 0); } // interacting through other boundary { ArrayHandle<Scalar4> h_pos(pdata->getPositions(), access_location::host, access_mode::readwrite); h_pos.data[0].x = -4.9; h_pos.data[0].y = 4.9; h_pos.data[1].x = 4.9; h_pos.data[1].y = -4.9; } nlist->compute(5); { ArrayHandle<unsigned int> h_n_neigh(nlist->getNNeighArray(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_n_neigh.data[0], 1); CHECK_EQUAL_UINT(h_n_neigh.data[1], 1); ArrayHandle<unsigned int> h_nlist(nlist->getNListArray(), access_location::host, access_mode::read); ArrayHandle<size_t> h_head_list(nlist->getHeadList(), access_location::host, access_mode::read); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[0]], 1); CHECK_EQUAL_UINT(h_nlist.data[h_head_list.data[1]], 0); } } /////////////// // BINNED CPU /////////////// //! basic test case for binned class UP_TEST(NeighborListBinned_basic) { neighborlist_basic_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! exclusion test case for binned class UP_TEST(NeighborListBinned_exclusion) { neighborlist_exclusion_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! large exclusion test case for binned class UP_TEST(NeighborListBinned_large_ex) { neighborlist_large_ex_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! body filter test case for binned class UP_TEST(NeighborListBinned_body_filter) { neighborlist_body_filter_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for binned class UP_TEST(NeighborListBinned_diameter_shift) { neighborlist_diameter_shift_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for binned class with periodic boundary conditions UP_TEST(NeighborListBinned_diameter_shift_periodic) { neighborlist_diameter_shift_periodic_tests<NeighborListBinned>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! particle asymmetry test case for binned class UP_TEST(NeighborListBinned_particle_asymm) { neighborlist_particle_asymm_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! cutoff exclusion test case for binned class UP_TEST(NeighborListBinned_cutoff_exclude) { neighborlist_cutoff_exclude_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! type test case for binned class UP_TEST(NeighborListBinned_type) { neighborlist_type_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! 2d tests for binned class UP_TEST(NeighborListBinned_2d) { neighborlist_2d_tests<NeighborListBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //////////////////// // STENCIL CPU //////////////////// //! basic test case for stencil class UP_TEST(NeighborListStencil_basic) { neighborlist_basic_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! exclusion test case for stencil class UP_TEST(NeighborListStencil_exclusion) { neighborlist_exclusion_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! large exclusion test case for stencil class UP_TEST(NeighborListStencil_large_ex) { neighborlist_large_ex_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! body filter test case for stencil class UP_TEST(NeighborListStencil_body_filter) { neighborlist_body_filter_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for stencil class UP_TEST(NeighborListStencil_diameter_shift) { neighborlist_diameter_shift_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for binned class with periodic boundary conditions UP_TEST(NeighborListStencil_diameter_shift_periodic) { neighborlist_diameter_shift_periodic_tests<NeighborListStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! particle asymmetry test case for stencil class UP_TEST(NeighborListStencil_particle_asymm) { neighborlist_particle_asymm_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! cutoff exclusion test case for stencil class UP_TEST(NeighborListStencil_cutoff_exclude) { neighborlist_cutoff_exclude_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! type test case for stencil class UP_TEST(NeighborListStencil_type) { neighborlist_type_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! 2d tests for stencil class UP_TEST(NeighborListStencil_2d) { neighborlist_2d_tests<NeighborListStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! comparison test case for stencil class UP_TEST(NeighborListStencil_comparison) { neighborlist_comparison_test<NeighborListBinned, NeighborListStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } /////////////// // TREE CPU /////////////// //! basic test case for tree class UP_TEST(NeighborListTree_basic) { neighborlist_basic_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! exclusion test case for tree class UP_TEST(NeighborListTree_exclusion) { neighborlist_exclusion_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! large exclusion test case for tree class UP_TEST(NeighborListTree_large_ex) { neighborlist_large_ex_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! body filter test case for tree class UP_TEST(NeighborListTree_body_filter) { neighborlist_body_filter_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for binned class UP_TEST(NeighborListTree_diameter_shift) { neighborlist_diameter_shift_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! diameter filter test case for binned class with periodic boundary conditions UP_TEST(NeighborListTree_diameter_shift_periodic) { neighborlist_diameter_shift_periodic_tests<NeighborListTree>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! particle asymmetry test case for tree class UP_TEST(NeighborListTree_particle_asymm) { neighborlist_particle_asymm_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! cutoff exclusion test case for tree class UP_TEST(NeighborListTree_cutoff_exclude) { neighborlist_cutoff_exclude_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! type test case for tree class UP_TEST(NeighborListTree_type) { neighborlist_type_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! 2d tests for tree class UP_TEST(NeighborListTree_2d) { neighborlist_2d_tests<NeighborListTree>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } //! comparison test case for tree class UP_TEST(NeighborListTree_comparison) { neighborlist_comparison_test<NeighborListBinned, NeighborListTree>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::CPU))); } #ifdef ENABLE_HIP /////////////// // BINNED GPU /////////////// //! basic test case for GPUBinned class UP_TEST(NeighborListGPUBinned_basic) { neighborlist_basic_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! exclusion test case for GPUBinned class UP_TEST(NeighborListGPUBinned_exclusion) { neighborlist_exclusion_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! large exclusion test case for GPUBinned class UP_TEST(NeighborListGPUBinned_large_ex) { neighborlist_large_ex_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! body filter test case for GPUBinned class UP_TEST(NeighborListGPUBinned_body_filter) { neighborlist_body_filter_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! diameter filter test case for GPUBinned class UP_TEST(NeighborListGPUBinned_diameter_shift) { neighborlist_diameter_shift_tests<NeighborListGPUBinned>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! diameter filter test case for GPUBinned class with periodic boundary conditions UP_TEST(NeighborListGPUBinned_diameter_shift_periodic) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_diameter_shift_periodic_tests<NeighborListGPUBinned>(exec_conf); } //! particle asymmetry test case for GPUBinned class UP_TEST(NeighborListGPUBinned_particle_asymm) { neighborlist_particle_asymm_tests<NeighborListGPUBinned>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! cutoff exclusion test case for GPUBinned class UP_TEST(NeighborListGPUBinned_cutoff_exclude) { neighborlist_cutoff_exclude_tests<NeighborListGPUBinned>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! type test case for GPUBinned class UP_TEST(NeighborListGPUBinned_type) { neighborlist_type_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! 2d tests for GPUBinned class UP_TEST(NeighborListGPUBinned_2d) { neighborlist_2d_tests<NeighborListGPUBinned>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! comparison test case for GPUBinned class UP_TEST(NeighborListGPUBinned_comparison) { neighborlist_comparison_test<NeighborListBinned, NeighborListGPUBinned>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } /////////////// // STENCIL GPU /////////////// //! basic test case for GPUStencil class UP_TEST(NeighborListGPUStencil_basic) { neighborlist_basic_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! exclusion test case for GPUStencil class UP_TEST(NeighborListGPUStencil_exclusion) { neighborlist_exclusion_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! large exclusion test case for GPUStencil class UP_TEST(NeighborListGPUStencil_large_ex) { neighborlist_large_ex_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! body filter test case for GPUStencil class UP_TEST(NeighborListGPUStencil_body_filter) { neighborlist_body_filter_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! diameter filter test case for GPUStencil class UP_TEST(NeighborListGPUStencil_diameter_shift) { neighborlist_diameter_shift_tests<NeighborListGPUStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! diameter filter test case for GPUStencil class with periodic boundary conditions UP_TEST(NeighborListGPUStencil_diameter_shift_periodic) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_diameter_shift_periodic_tests<NeighborListGPUStencil>(exec_conf); } //! particle asymmetry test case for GPUStencil class UP_TEST(NeighborListGPUStencil_particle_asymm) { neighborlist_particle_asymm_tests<NeighborListGPUStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! cutoff exclusion test case for GPUStencil class UP_TEST(NeighborListGPUStencil_cutoff_exclude) { neighborlist_cutoff_exclude_tests<NeighborListGPUStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! type test case for GPUStencil class UP_TEST(NeighborListGPUStencil_type) { neighborlist_type_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! 2d tests for GPUStencil class UP_TEST(NeighborListGPUStencil_2d) { neighborlist_2d_tests<NeighborListGPUStencil>(std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! comparison test case for GPUStencil class against Stencil on cpu UP_TEST(NeighborListGPUStencil_cpu_comparison) { neighborlist_comparison_test<NeighborListStencil, NeighborListGPUStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } //! comparison test case for GPUStencil class against GPUBinned UP_TEST(NeighborListGPUStencil_binned_comparison) { neighborlist_comparison_test<NeighborListGPUBinned, NeighborListGPUStencil>( std::shared_ptr<ExecutionConfiguration>( new ExecutionConfiguration(ExecutionConfiguration::GPU))); } /////////////// // TREE GPU /////////////// //! basic test case for GPUTree class UP_TEST(NeighborListGPUTree_basic) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_basic_tests<NeighborListGPUTree>(exec_conf); } //! exclusion test case for GPUTree class UP_TEST(NeighborListGPUTree_exclusion) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_exclusion_tests<NeighborListGPUTree>(exec_conf); } //! large exclusion test case for GPUTree class UP_TEST(NeighborListGPUTree_large_ex) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_large_ex_tests<NeighborListGPUTree>(exec_conf); } //! body filter test case for GPUTree class UP_TEST(NeighborListGPUTree_body_filter) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_body_filter_tests<NeighborListGPUTree>(exec_conf); } //! diameter filter test case for GPUTree class UP_TEST(NeighborListGPUTree_diameter_shift) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_diameter_shift_tests<NeighborListGPUTree>(exec_conf); } //! diameter filter test case for GPUTree class with periodic boundary conditions UP_TEST(NeighborListGPUTree_diameter_shift_periodic) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_diameter_shift_periodic_tests<NeighborListGPUTree>(exec_conf); } //! particle asymmetry test case for GPUTree class UP_TEST(NeighborListGPUTree_particle_asymm) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_particle_asymm_tests<NeighborListGPUTree>(exec_conf); } //! cutoff exclusion test case for GPUTree class UP_TEST(NeighborListGPUTree_cutoff_exclude) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_cutoff_exclude_tests<NeighborListGPUTree>(exec_conf); } //! type test case for tree class UP_TEST(NeighborListGPUTree_type) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_type_tests<NeighborListGPUTree>(exec_conf); } //! 2d tests for tree class UP_TEST(NeighborListGPUTree_2d) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_2d_tests<NeighborListGPUTree>(exec_conf); } //! comparison test case for GPUTree class with itself UP_TEST(NeighborListGPUTree_cpu_comparison) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_comparison_test<NeighborListTree, NeighborListGPUTree>(exec_conf); } //! comparison test case for GPUTree class with GPUBinned UP_TEST(NeighborListGPUTree_binned_comparison) { std::shared_ptr<ExecutionConfiguration> exec_conf( new ExecutionConfiguration(ExecutionConfiguration::GPU)); neighborlist_comparison_test<NeighborListGPUBinned, NeighborListGPUTree>(exec_conf); } #endif
// Copyright 2019 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 "content/shell/browser/web_test/mojo_echo.h" #include "mojo/public/cpp/bindings/self_owned_receiver.h" namespace content { // static void MojoEcho::Bind(mojo::PendingReceiver<mojom::MojoEcho> receiver) { mojo::MakeSelfOwnedReceiver(std::make_unique<MojoEcho>(), std::move(receiver)); } MojoEcho::MojoEcho() = default; MojoEcho::~MojoEcho() = default; void MojoEcho::EchoBoolFromUnion(mojom::TestUnionPtr test_union, EchoBoolFromUnionCallback callback) { std::move(callback).Run(test_union->get_bool_value()); } void MojoEcho::EchoInt32FromUnion(mojom::TestUnionPtr test_union, EchoInt32FromUnionCallback callback) { std::move(callback).Run(test_union->get_int32_value()); } void MojoEcho::EchoStringFromUnion(mojom::TestUnionPtr test_union, EchoStringFromUnionCallback callback) { std::move(callback).Run(test_union->get_string_value()); } void MojoEcho::EchoBoolAsUnion(bool value, EchoBoolAsUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewBoolValue(value)); } void MojoEcho::EchoInt32AsUnion(int32_t value, EchoInt32AsUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewInt32Value(value)); } void MojoEcho::EchoStringAsUnion(const std::string& value, EchoStringAsUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewStringValue(value)); } void MojoEcho::EchoNullFromOptionalUnion( mojom::TestUnionPtr test_union, EchoNullFromOptionalUnionCallback callback) { DCHECK(!test_union); std::move(callback).Run(); } void MojoEcho::EchoBoolFromOptionalUnion( mojom::TestUnionPtr test_union, EchoBoolFromOptionalUnionCallback callback) { std::move(callback).Run(test_union->get_bool_value()); } void MojoEcho::EchoInt32FromOptionalUnion( mojom::TestUnionPtr test_union, EchoInt32FromOptionalUnionCallback callback) { std::move(callback).Run(test_union->get_int32_value()); } void MojoEcho::EchoStringFromOptionalUnion( mojom::TestUnionPtr test_union, EchoStringFromOptionalUnionCallback callback) { std::move(callback).Run(test_union->get_string_value()); } void MojoEcho::EchoNullAsOptionalUnion( EchoNullAsOptionalUnionCallback callback) { std::move(callback).Run(nullptr); } void MojoEcho::EchoBoolAsOptionalUnion( bool value, EchoBoolAsOptionalUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewBoolValue(value)); } void MojoEcho::EchoInt32AsOptionalUnion( int32_t value, EchoInt32AsOptionalUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewInt32Value(value)); } void MojoEcho::EchoStringAsOptionalUnion( const std::string& value, EchoStringAsOptionalUnionCallback callback) { std::move(callback).Run(mojom::TestUnion::NewStringValue(value)); } void MojoEcho::EchoInt8FromNestedUnion( mojom::NestedUnionPtr test_union, EchoInt8FromNestedUnionCallback callback) { std::move(callback).Run(test_union->get_int8_value()); } void MojoEcho::EchoBoolFromNestedUnion( mojom::NestedUnionPtr test_union, EchoBoolFromNestedUnionCallback callback) { std::move(callback).Run(test_union->get_union_value()->get_bool_value()); } void MojoEcho::EchoStringFromNestedUnion( mojom::NestedUnionPtr test_union, EchoStringFromNestedUnionCallback callback) { std::move(callback).Run(test_union->get_union_value()->get_string_value()); } void MojoEcho::EchoInt8AsNestedUnion(int8_t value, EchoInt8AsNestedUnionCallback callback) { std::move(callback).Run(mojom::NestedUnion::NewInt8Value(value)); } void MojoEcho::EchoBoolAsNestedUnion(bool value, EchoBoolAsNestedUnionCallback callback) { std::move(callback).Run( mojom::NestedUnion::NewUnionValue(mojom::TestUnion::NewBoolValue(value))); } void MojoEcho::EchoStringAsNestedUnion( const std::string& value, EchoStringAsNestedUnionCallback callback) { std::move(callback).Run(mojom::NestedUnion::NewUnionValue( mojom::TestUnion::NewStringValue(value))); } void MojoEcho::EchoNullFromOptionalNestedUnion( mojom::NestedUnionPtr test_union, EchoNullFromOptionalNestedUnionCallback callback) { DCHECK(!test_union); std::move(callback).Run(); } void MojoEcho::EchoInt8FromOptionalNestedUnion( mojom::NestedUnionPtr test_union, EchoInt8FromOptionalNestedUnionCallback callback) { std::move(callback).Run(test_union->get_int8_value()); } void MojoEcho::EchoBoolFromOptionalNestedUnion( mojom::NestedUnionPtr test_union, EchoBoolFromOptionalNestedUnionCallback callback) { std::move(callback).Run(test_union->get_union_value()->get_bool_value()); } void MojoEcho::EchoStringFromOptionalNestedUnion( mojom::NestedUnionPtr test_union, EchoStringFromOptionalNestedUnionCallback callback) { std::move(callback).Run(test_union->get_union_value()->get_string_value()); } void MojoEcho::EchoNullAsOptionalNestedUnion( EchoNullAsOptionalNestedUnionCallback callback) { std::move(callback).Run(nullptr); } void MojoEcho::EchoInt8AsOptionalNestedUnion( int8_t value, EchoInt8AsOptionalNestedUnionCallback callback) { std::move(callback).Run(mojom::NestedUnion::NewInt8Value(value)); } void MojoEcho::EchoBoolAsOptionalNestedUnion( bool value, EchoBoolAsOptionalNestedUnionCallback callback) { std::move(callback).Run( mojom::NestedUnion::NewUnionValue(mojom::TestUnion::NewBoolValue(value))); } void MojoEcho::EchoStringAsOptionalNestedUnion( const std::string& value, EchoStringAsOptionalNestedUnionCallback callback) { std::move(callback).Run(mojom::NestedUnion::NewUnionValue( mojom::TestUnion::NewStringValue(value))); } } // namespace content
/* * Copyright (c) 2016, The OpenThread 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: * 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. */ /** * @file * This file implements the OpenThread Link API. */ #include "openthread-core-config.h" #include <openthread/link.h> #include "common/as_core_type.hpp" #include "common/locator_getters.hpp" #include "mac/mac.hpp" #include "radio/radio.hpp" using namespace ot; uint8_t otLinkGetChannel(otInstance *aInstance) { Instance &instance = AsCoreType(aInstance); uint8_t channel; #if OPENTHREAD_CONFIG_LINK_RAW_ENABLE if (instance.Get<Mac::LinkRaw>().IsEnabled()) { channel = instance.Get<Mac::LinkRaw>().GetChannel(); } else #endif { channel = instance.Get<Mac::Mac>().GetPanChannel(); } return channel; } otError otLinkSetChannel(otInstance *aInstance, uint8_t aChannel) { Error error; Instance &instance = AsCoreType(aInstance); #if OPENTHREAD_CONFIG_LINK_RAW_ENABLE if (instance.Get<Mac::LinkRaw>().IsEnabled()) { error = instance.Get<Mac::LinkRaw>().SetChannel(aChannel); ExitNow(); } #endif VerifyOrExit(instance.Get<Mle::MleRouter>().IsDisabled(), error = kErrorInvalidState); SuccessOrExit(error = instance.Get<Mac::Mac>().SetPanChannel(aChannel)); instance.Get<MeshCoP::ActiveDatasetManager>().Clear(); instance.Get<MeshCoP::PendingDatasetManager>().Clear(); exit: return error; } uint32_t otLinkGetSupportedChannelMask(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetSupportedChannelMask().GetMask(); } otError otLinkSetSupportedChannelMask(otInstance *aInstance, uint32_t aChannelMask) { Error error = kErrorNone; Instance &instance = AsCoreType(aInstance); VerifyOrExit(instance.Get<Mle::MleRouter>().IsDisabled(), error = kErrorInvalidState); instance.Get<Mac::Mac>().SetSupportedChannelMask(Mac::ChannelMask(aChannelMask)); exit: return error; } const otExtAddress *otLinkGetExtendedAddress(otInstance *aInstance) { return &AsCoreType(aInstance).Get<Mac::Mac>().GetExtAddress(); } otError otLinkSetExtendedAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { Error error = kErrorNone; Instance &instance = AsCoreType(aInstance); OT_ASSERT(aExtAddress != nullptr); VerifyOrExit(instance.Get<Mle::MleRouter>().IsDisabled(), error = kErrorInvalidState); instance.Get<Mac::Mac>().SetExtAddress(AsCoreType(aExtAddress)); instance.Get<Mle::MleRouter>().UpdateLinkLocalAddress(); exit: return error; } void otLinkGetFactoryAssignedIeeeEui64(otInstance *aInstance, otExtAddress *aEui64) { AsCoreType(aInstance).Get<Radio>().GetIeeeEui64(AsCoreType(aEui64)); } otPanId otLinkGetPanId(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetPanId(); } otError otLinkSetPanId(otInstance *aInstance, otPanId aPanId) { Error error = kErrorNone; Instance &instance = AsCoreType(aInstance); VerifyOrExit(instance.Get<Mle::MleRouter>().IsDisabled(), error = kErrorInvalidState); instance.Get<Mac::Mac>().SetPanId(aPanId); instance.Get<MeshCoP::ActiveDatasetManager>().Clear(); instance.Get<MeshCoP::PendingDatasetManager>().Clear(); exit: return error; } uint32_t otLinkGetPollPeriod(otInstance *aInstance) { return AsCoreType(aInstance).Get<DataPollSender>().GetKeepAlivePollPeriod(); } otError otLinkSetPollPeriod(otInstance *aInstance, uint32_t aPollPeriod) { return AsCoreType(aInstance).Get<DataPollSender>().SetExternalPollPeriod(aPollPeriod); } otError otLinkSendDataRequest(otInstance *aInstance) { return AsCoreType(aInstance).Get<DataPollSender>().SendDataPoll(); } otShortAddress otLinkGetShortAddress(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetShortAddress(); } uint8_t otLinkGetMaxFrameRetriesDirect(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetMaxFrameRetriesDirect(); } void otLinkSetMaxFrameRetriesDirect(otInstance *aInstance, uint8_t aMaxFrameRetriesDirect) { AsCoreType(aInstance).Get<Mac::Mac>().SetMaxFrameRetriesDirect(aMaxFrameRetriesDirect); } #if OPENTHREAD_FTD uint8_t otLinkGetMaxFrameRetriesIndirect(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetMaxFrameRetriesIndirect(); } void otLinkSetMaxFrameRetriesIndirect(otInstance *aInstance, uint8_t aMaxFrameRetriesIndirect) { AsCoreType(aInstance).Get<Mac::Mac>().SetMaxFrameRetriesIndirect(aMaxFrameRetriesIndirect); } #endif // OPENTHREAD_FTD #if OPENTHREAD_CONFIG_MAC_FILTER_ENABLE otMacFilterAddressMode otLinkFilterGetAddressMode(otInstance *aInstance) { return MapEnum(AsCoreType(aInstance).Get<Mac::Filter>().GetMode()); } void otLinkFilterSetAddressMode(otInstance *aInstance, otMacFilterAddressMode aMode) { AsCoreType(aInstance).Get<Mac::Filter>().SetMode(MapEnum(aMode)); } otError otLinkFilterAddAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { OT_ASSERT(aExtAddress != nullptr); return AsCoreType(aInstance).Get<Mac::Filter>().AddAddress(AsCoreType(aExtAddress)); } void otLinkFilterRemoveAddress(otInstance *aInstance, const otExtAddress *aExtAddress) { OT_ASSERT(aExtAddress != nullptr); AsCoreType(aInstance).Get<Mac::Filter>().RemoveAddress(AsCoreType(aExtAddress)); } void otLinkFilterClearAddresses(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Filter>().ClearAddresses(); } otError otLinkFilterGetNextAddress(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) { OT_ASSERT(aIterator != nullptr && aEntry != nullptr); return AsCoreType(aInstance).Get<Mac::Filter>().GetNextAddress(*aIterator, *aEntry); } otError otLinkFilterAddRssIn(otInstance *aInstance, const otExtAddress *aExtAddress, int8_t aRss) { OT_ASSERT(aExtAddress != nullptr); return AsCoreType(aInstance).Get<Mac::Filter>().AddRssIn(AsCoreType(aExtAddress), aRss); } void otLinkFilterRemoveRssIn(otInstance *aInstance, const otExtAddress *aExtAddress) { OT_ASSERT(aExtAddress != nullptr); AsCoreType(aInstance).Get<Mac::Filter>().RemoveRssIn(AsCoreType(aExtAddress)); } void otLinkFilterSetDefaultRssIn(otInstance *aInstance, int8_t aRss) { AsCoreType(aInstance).Get<Mac::Filter>().SetDefaultRssIn(aRss); } void otLinkFilterClearDefaultRssIn(otInstance *aInstance) { AsCoreType(aInstance).Get<Mac::Filter>().ClearDefaultRssIn(); } void otLinkFilterClearAllRssIn(otInstance *aInstance) { AsCoreType(aInstance).Get<Mac::Filter>().ClearAllRssIn(); } otError otLinkFilterGetNextRssIn(otInstance *aInstance, otMacFilterIterator *aIterator, otMacFilterEntry *aEntry) { OT_ASSERT(aIterator != nullptr && aEntry != nullptr); return AsCoreType(aInstance).Get<Mac::Filter>().GetNextRssIn(*aIterator, *aEntry); } #if OPENTHREAD_CONFIG_RADIO_LINK_IEEE_802_15_4_ENABLE void otLinkSetRadioFilterEnabled(otInstance *aInstance, bool aFilterEnabled) { return AsCoreType(aInstance).Get<Mac::Mac>().SetRadioFilterEnabled(aFilterEnabled); } bool otLinkIsRadioFilterEnabled(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsRadioFilterEnabled(); } #endif #endif // OPENTHREAD_CONFIG_MAC_FILTER_ENABLE uint8_t otLinkConvertRssToLinkQuality(otInstance *aInstance, int8_t aRss) { return LinkQualityInfo::ConvertRssToLinkQuality(AsCoreType(aInstance).Get<Mac::Mac>().GetNoiseFloor(), aRss); } int8_t otLinkConvertLinkQualityToRss(otInstance *aInstance, uint8_t aLinkQuality) { return LinkQualityInfo::ConvertLinkQualityToRss(AsCoreType(aInstance).Get<Mac::Mac>().GetNoiseFloor(), static_cast<LinkQuality>(aLinkQuality)); } #if OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE const uint32_t *otLinkGetTxDirectRetrySuccessHistogram(otInstance *aInstance, uint8_t *aNumberOfEntries) { return AsCoreType(aInstance).Get<Mac::Mac>().GetDirectRetrySuccessHistogram(*aNumberOfEntries); } const uint32_t *otLinkGetTxIndirectRetrySuccessHistogram(otInstance *aInstance, uint8_t *aNumberOfEntries) { const uint32_t *histogram = nullptr; #if OPENTHREAD_FTD histogram = AsCoreType(aInstance).Get<Mac::Mac>().GetIndirectRetrySuccessHistogram(*aNumberOfEntries); #else OT_UNUSED_VARIABLE(aInstance); *aNumberOfEntries = 0; #endif return histogram; } void otLinkResetTxRetrySuccessHistogram(otInstance *aInstance) { AsCoreType(aInstance).Get<Mac::Mac>().ResetRetrySuccessHistogram(); } #endif // OPENTHREAD_CONFIG_MAC_RETRY_SUCCESS_HISTOGRAM_ENABLE void otLinkSetPcapCallback(otInstance *aInstance, otLinkPcapCallback aPcapCallback, void *aCallbackContext) { AsCoreType(aInstance).Get<Mac::Mac>().SetPcapCallback(aPcapCallback, aCallbackContext); } bool otLinkIsPromiscuous(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsPromiscuous(); } otError otLinkSetPromiscuous(otInstance *aInstance, bool aPromiscuous) { Error error = kErrorNone; Instance &instance = AsCoreType(aInstance); // cannot enable IEEE 802.15.4 promiscuous mode if the Thread interface is enabled VerifyOrExit(!instance.Get<ThreadNetif>().IsUp(), error = kErrorInvalidState); instance.Get<Mac::Mac>().SetPromiscuous(aPromiscuous); exit: return error; } otError otLinkSetEnabled(otInstance *aInstance, bool aEnable) { Error error = kErrorNone; Instance &instance = AsCoreType(aInstance); // cannot disable the link layer if the Thread interface is enabled VerifyOrExit(!instance.Get<ThreadNetif>().IsUp(), error = kErrorInvalidState); instance.Get<Mac::Mac>().SetEnabled(aEnable); exit: return error; } bool otLinkIsEnabled(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsEnabled(); } const otMacCounters *otLinkGetCounters(otInstance *aInstance) { return &AsCoreType(aInstance).Get<Mac::Mac>().GetCounters(); } void otLinkResetCounters(otInstance *aInstance) { AsCoreType(aInstance).Get<Mac::Mac>().ResetCounters(); } otError otLinkActiveScan(otInstance * aInstance, uint32_t aScanChannels, uint16_t aScanDuration, otHandleActiveScanResult aCallback, void * aCallbackContext) { return AsCoreType(aInstance).Get<Mac::Mac>().ActiveScan(aScanChannels, aScanDuration, aCallback, aCallbackContext); } bool otLinkIsActiveScanInProgress(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsActiveScanInProgress(); } otError otLinkEnergyScan(otInstance * aInstance, uint32_t aScanChannels, uint16_t aScanDuration, otHandleEnergyScanResult aCallback, void * aCallbackContext) { return AsCoreType(aInstance).Get<Mac::Mac>().EnergyScan(aScanChannels, aScanDuration, aCallback, aCallbackContext); } bool otLinkIsEnergyScanInProgress(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsEnergyScanInProgress(); } bool otLinkIsInTransmitState(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().IsInTransmitState(); } uint16_t otLinkGetCcaFailureRate(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetCcaFailureRate(); } #if OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE uint8_t otLinkCslGetChannel(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetCslChannel(); } otError otLinkCslSetChannel(otInstance *aInstance, uint8_t aChannel) { Error error = kErrorNone; VerifyOrExit(Radio::IsCslChannelValid(aChannel), error = kErrorInvalidArgs); AsCoreType(aInstance).Get<Mac::Mac>().SetCslChannel(aChannel); exit: return error; } uint16_t otLinkCslGetPeriod(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mac::Mac>().GetCslPeriod(); } otError otLinkCslSetPeriod(otInstance *aInstance, uint16_t aPeriod) { Error error = kErrorNone; VerifyOrExit((aPeriod == 0 || kMinCslPeriod <= aPeriod), error = kErrorInvalidArgs); AsCoreType(aInstance).Get<Mac::Mac>().SetCslPeriod(aPeriod); exit: return error; } uint32_t otLinkCslGetTimeout(otInstance *aInstance) { return AsCoreType(aInstance).Get<Mle::MleRouter>().GetCslTimeout(); } otError otLinkCslSetTimeout(otInstance *aInstance, uint32_t aTimeout) { Error error = kErrorNone; VerifyOrExit(kMaxCslTimeout >= aTimeout, error = kErrorInvalidArgs); AsCoreType(aInstance).Get<Mle::MleRouter>().SetCslTimeout(aTimeout); exit: return error; } #endif // OPENTHREAD_CONFIG_MAC_CSL_RECEIVER_ENABLE #if OPENTHREAD_CONFIG_REFERENCE_DEVICE_ENABLE otError otLinkSendEmptyData(otInstance *aInstance) { return AsCoreType(aInstance).Get<MeshForwarder>().SendEmptyMessage(); } #endif
// $Id: utl_scope.cpp 96358 2012-11-23 19:26:43Z parsons $ /* COPYRIGHT Copyright 1992, 1993, 1994 Sun Microsystems, Inc. Printed in the United States of America. All Rights Reserved. This product is protected by copyright and distributed under the following license restricting its use. The Interface Definition Language Compiler Front End (CFE) is made available for your use provided that you include this license and copyright notice on all media and documentation and the software program in which this product is incorporated in whole or part. You may copy and extend functionality (but may not remove functionality) of the Interface Definition Language CFE without charge, but you are not authorized to license or distribute it to anyone else except as part of a product or program developed by you or with the express written consent of Sun Microsystems, Inc. ("Sun"). The names of Sun Microsystems, Inc. and any of its subsidiaries or affiliates may not be used in advertising or publicity pertaining to distribution of Interface Definition Language CFE as permitted herein. This license is effective until terminated by Sun for failure to comply with this license. Upon termination, you shall destroy or return all code and documentation for the Interface Definition Language CFE. INTERFACE DEFINITION LANGUAGE CFE IS PROVIDED AS IS WITH NO WARRANTIES OF ANY KIND INCLUDING THE WARRANTIES OF DESIGN, MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR ARISING FROM A COURSE OF DEALING, USAGE OR TRADE PRACTICE. INTERFACE DEFINITION LANGUAGE CFE IS PROVIDED WITH NO SUPPORT AND WITHOUT ANY OBLIGATION ON THE PART OF Sun OR ANY OF ITS SUBSIDIARIES OR AFFILIATES TO ASSIST IN ITS USE, CORRECTION, MODIFICATION OR ENHANCEMENT. SUN OR ANY OF ITS SUBSIDIARIES OR AFFILIATES SHALL HAVE NO LIABILITY WITH RESPECT TO THE INFRINGEMENT OF COPYRIGHTS, TRADE SECRETS OR ANY PATENTS BY INTERFACE DEFINITION LANGUAGE CFE OR ANY PART THEREOF. IN NO EVENT WILL SUN OR ANY OF ITS SUBSIDIARIES OR AFFILIATES BE LIABLE FOR ANY LOST REVENUE OR PROFITS OR OTHER SPECIAL, INDIRECT AND CONSEQUENTIAL DAMAGES, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Use, duplication, or disclosure by the government is subject to restrictions as set forth in subparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 and FAR 52.227-19. Sun, Sun Microsystems and the Sun logo are trademarks or registered trademarks of Sun Microsystems, Inc. SunSoft, Inc. 2550 Garcia Avenue Mountain View, California 94043 NOTE: SunOS, SunSoft, Sun, Solaris, Sun Microsystems or the Sun logo are trademarks or registered trademarks of Sun Microsystems, Inc. */ #include "utl_scope.h" #include "utl_identifier.h" #include "utl_err.h" #include "utl_indenter.h" #include "utl_string.h" #include "utl_strlist.h" #include "ast_valuebox.h" #include "ast_valuetype.h" #include "ast_valuetype_fwd.h" #include "ast_eventtype.h" #include "ast_eventtype_fwd.h" #include "ast_component.h" #include "ast_component_fwd.h" #include "ast_home.h" #include "ast_porttype.h" #include "ast_template_module.h" #include "ast_template_module_ref.h" #include "ast_template_module_inst.h" #include "ast_typedef.h" #include "ast_type.h" #include "ast_root.h" #include "ast_array.h" #include "ast_enum.h" #include "ast_concrete_type.h" #include "ast_sequence.h" #include "ast_string.h" #include "ast_structure_fwd.h" #include "ast_exception.h" #include "ast_constant.h" #include "ast_attribute.h" #include "ast_operation.h" #include "ast_argument.h" #include "ast_param_holder.h" #include "ast_union.h" #include "ast_union_fwd.h" #include "ast_union_branch.h" #include "ast_field.h" #include "ast_enum_val.h" #include "ast_native.h" #include "ast_factory.h" #include "ast_visitor.h" #include "ast_generator.h" #include "ast_extern.h" #include "fe_extern.h" #include "nr_extern.h" #include "global_extern.h" #include "ace/OS_NS_strings.h" // FUZZ: disable check_for_streams_include #include "ace/streams.h" #undef INCREMENT #define INCREMENT 64 // Constructors. UTL_Scope::UTL_Scope (void) : pd_scope_node_type (AST_Decl::NT_module), pd_decls (0), pd_decls_allocated (0), pd_decls_used (0), pd_local_types (0), pd_locals_allocated (0), pd_locals_used (0), pd_referenced (0), pd_referenced_allocated (0), pd_referenced_used (0), pd_name_referenced (0), pd_name_referenced_allocated (0), pd_name_referenced_used (0), has_prefix_ (0), which_pseudo_ (PSEUDO_ABSTRACTBASE) { } UTL_Scope::UTL_Scope (AST_Decl::NodeType nt) : pd_scope_node_type (nt), pd_decls (0), pd_decls_allocated (0), pd_decls_used (0), pd_local_types (0), pd_locals_allocated (0), pd_locals_used (0), pd_referenced (0), pd_referenced_allocated (0), pd_referenced_used (0), pd_name_referenced (0), pd_name_referenced_allocated (0), pd_name_referenced_used (0), has_prefix_ (0), which_pseudo_ (PSEUDO_ABSTRACTBASE) { } // Destructor. UTL_Scope::~UTL_Scope (void) { for (UTL_ScopeActiveIterator iter (this, IK_both); !iter.is_done (); iter.next ()) { AST_Decl *d = iter.item (); d->destroy (); delete d; } delete [] this->pd_decls; delete [] this->pd_local_types; delete [] this->pd_referenced; for (long i = this->pd_name_referenced_used; i--;) // NOTE test with i-- { Identifier *id = this->pd_name_referenced[i]; id->destroy (); delete id; } delete [] this->pd_name_referenced; } void UTL_Scope::destroy (void) { for (UTL_ScopeActiveIterator iter (this, IK_both); !iter.is_done (); iter.next ()) { AST_Decl *d = iter.item (); d->destroy (); delete d; } delete [] this->pd_decls; this->pd_decls = 0; this->pd_decls_allocated = 0; this->pd_decls_used = 0; delete [] this->pd_local_types; this->pd_local_types = 0; this->pd_locals_allocated = 0; this->pd_locals_used = 0; delete [] this->pd_referenced; this->pd_referenced = 0; this->pd_referenced_allocated = 0; this->pd_referenced_used = 0; for (long i = this->pd_name_referenced_used; i--;) // NOTE test with i-- { Identifier *id = this->pd_name_referenced[i]; id->destroy (); delete id; } delete [] this->pd_name_referenced; this->pd_name_referenced = 0; this->pd_name_referenced_allocated = 0; this->pd_name_referenced_used = 0; } // Protected operations. // Special version of lookup which only looks at the local name instead of // the fully scoped name, when doing lookups. This version is intended to // be used only by the frontend add_xxx functions. AST_Decl * UTL_Scope::lookup_for_add (AST_Decl *d) { if (!d) { return 0; } Identifier *id = d->local_name (); if (this->idl_keyword_clash (id)) { return 0; } return this->lookup_by_name_local (id, false); } int UTL_Scope::idl_keyword_clash (Identifier *e) { if (e->escaped ()) { return 0; } // Convert the identifier string into a // canonical (uppercase) form as a ACE_CString char *tmp = e->get_string (); ACE_CString ext_id (tmp); UTL_String::get_canonical_rep (ext_id); if (!idl_global->idl_keywords ().find (ext_id)) { if (idl_global->case_diff_error ()) { idl_global->err ()->idl_keyword_error (tmp); } else { idl_global->err ()->idl_keyword_warning (tmp); } return -1; } return 0; } bool UTL_Scope::redef_clash (AST_Decl::NodeType new_nt, AST_Decl::NodeType scope_elem_nt) { switch (new_nt) { case AST_Decl::NT_module: return scope_elem_nt != AST_Decl::NT_module; case AST_Decl::NT_struct: case AST_Decl::NT_struct_fwd: return scope_elem_nt != AST_Decl::NT_struct_fwd; case AST_Decl::NT_union: case AST_Decl::NT_union_fwd: return scope_elem_nt != AST_Decl::NT_union_fwd; case AST_Decl::NT_interface: return scope_elem_nt != AST_Decl::NT_interface_fwd; case AST_Decl::NT_component: return scope_elem_nt != AST_Decl::NT_component_fwd; case AST_Decl::NT_interface_fwd: return ( scope_elem_nt != AST_Decl::NT_interface_fwd && scope_elem_nt != AST_Decl::NT_interface); case AST_Decl::NT_component_fwd: return ( scope_elem_nt != AST_Decl::NT_component_fwd && scope_elem_nt != AST_Decl::NT_component); case AST_Decl::NT_valuetype: return scope_elem_nt != AST_Decl::NT_valuetype_fwd; case AST_Decl::NT_eventtype: return scope_elem_nt != AST_Decl::NT_eventtype_fwd; case AST_Decl::NT_valuetype_fwd: return ( scope_elem_nt != AST_Decl::NT_valuetype_fwd && scope_elem_nt != AST_Decl::NT_valuetype); case AST_Decl::NT_eventtype_fwd: return ( scope_elem_nt != AST_Decl::NT_eventtype_fwd && scope_elem_nt != AST_Decl::NT_eventtype); default: return true; } } void UTL_Scope::check_for_predef_seq (AST_Decl *d) { // Right now, we're interested only in predefined sequences // referenced in the main IDL file. If we are processing // multiple IDL files in one execution, the bits will // stay set, and be accumulated as each file is parsed. if (!idl_global->in_main_file ()) { return; } AST_Type *bt = 0; AST_Decl::NodeType nt = d->node_type (); // We are interested only in members, arguments and typedefs. switch (nt) { case AST_Decl::NT_field: case AST_Decl::NT_union_branch: case AST_Decl::NT_attr: case AST_Decl::NT_argument: bt = AST_Field::narrow_from_decl (d)->field_type (); break; case AST_Decl::NT_typedef: bt = AST_Typedef::narrow_from_decl (d)->base_type (); break; default: return; } // Check to eliminate more candidates. if (!bt->imported () || bt->node_type () != AST_Decl::NT_typedef) { return; } bt = AST_Typedef::narrow_from_decl (bt)->base_type (); nt = bt->node_type (); // Must be a sequence with only one level of typedef. if (nt != AST_Decl::NT_sequence) { return; } // Must be defined in the CORBA module. AST_Decl *p = ScopeAsDecl (bt->defined_in ()); if (ACE_OS::strcmp (p->local_name ()->get_string (), "CORBA")) { return; } // We know this narrowing will be successful. bt = AST_Sequence::narrow_from_decl (bt)->base_type (); nt = bt->node_type (); // First check for string or wstring base type. if (nt == AST_Decl::NT_string) { idl_global->string_seq_seen_ = true; return; } if (nt == AST_Decl::NT_wstring) { idl_global->wstring_seq_seen_ = true; return; } // Now check for predefined base type. AST_PredefinedType *pdt = AST_PredefinedType::narrow_from_decl (bt); if (!pdt) { return; } switch (pdt->pt ()) { case AST_PredefinedType::PT_long: idl_global->long_seq_seen_ = true; break; case AST_PredefinedType::PT_ulong: idl_global->ulong_seq_seen_ = true; break; case AST_PredefinedType::PT_longlong: idl_global->longlong_seq_seen_ = true; break; case AST_PredefinedType::PT_ulonglong: idl_global->ulonglong_seq_seen_ = true; break; case AST_PredefinedType::PT_short: idl_global->short_seq_seen_ = true; break; case AST_PredefinedType::PT_ushort: idl_global->ushort_seq_seen_ = true; break; case AST_PredefinedType::PT_float: idl_global->float_seq_seen_ = true; break; case AST_PredefinedType::PT_double: idl_global->double_seq_seen_ = true; break; case AST_PredefinedType::PT_longdouble: idl_global->longdouble_seq_seen_ = true; break; case AST_PredefinedType::PT_char: idl_global->char_seq_seen_ = true; break; case AST_PredefinedType::PT_wchar: idl_global->wchar_seq_seen_ = true; break; case AST_PredefinedType::PT_boolean: idl_global->boolean_seq_seen_ = true; break; case AST_PredefinedType::PT_octet: idl_global->octet_seq_seen_ = true; break; case AST_PredefinedType::PT_any: idl_global->any_seq_seen_ = true; break; default: break; } } // Protected Front End Scope Management Protocol. // // All members of the protocol defined in UTL_Scope simply return NULL // and don't do a thing. This ensures that runtime errors will discover // operations which should have been redefined to allow certain kinds of // AST nodes to appear in a given context. AST_Decl * UTL_Scope::fe_add_decl (AST_Decl *t) { // Already defined and cannot be redefined? Or already used? AST_Decl *d = this->lookup_for_add (t); if (d != 0) { if (!FE_Utils::can_be_redefined (d, t)) { idl_global->err ()->error3 (UTL_Error::EIDL_REDEF, t, ScopeAsDecl (this), d); return 0; } // For convenience, AST_Template_Module_Inst inherits // from AST_Field, but has a node type of NT_module. // Since we then can't add it using fe_add_module(), a // check is needed here to avoid a redefinition error, // if the instantiated module is meant to reopen a // previous one. AST_Decl::NodeType lnt = d->node_type (); AST_Decl::NodeType ant = t->node_type (); bool need_ref_check = ( lnt != AST_Decl::NT_module || ant != AST_Decl::NT_module); if (need_ref_check && this->referenced (d, t->local_name ())) { idl_global->err ()->error3 (UTL_Error::EIDL_DEF_USE, t, ScopeAsDecl (this), d); return 0; } if (t->has_ancestor (d)) { idl_global->err ()->redefinition_in_scope (t, d); return 0; } } else if (this->inherited_op_attr_clash (t)) { return 0; } if (this->arg_specific_error (t)) { return 0; } this->smart_local_add (t); // Add it to set of locally referenced symbols, unless it is // a home, in which case it will clash when the equivalent // interface is created. if (t->node_type () != AST_Decl::NT_home) { this->add_to_referenced (t, false, t->local_name ()); } return t; } AST_Field * UTL_Scope::fe_add_ref_decl (AST_Field *t) { AST_Decl *d = this->fe_add_decl (t); if (d) { AST_Type *ft = t->field_type (); UTL_ScopedName *mru = ft->last_referenced_as (); if (mru) { this->add_to_referenced (ft, false, mru->first_component ()); } } // Catches struct/union/exception which all maintain a queue // for fields as distinct from decls and enum values. AST_Structure *s = AST_Structure::narrow_from_scope (this); if (s) { s->fields ().enqueue_tail (t); } return AST_Field::narrow_from_decl (d); } AST_Structure * UTL_Scope::fe_add_full_struct_type (AST_Structure *t) { AST_Decl *predef = this->lookup_for_add (t); if (predef) { if (!FE_Utils::can_be_redefined (predef, t)) { idl_global->err ()->error3 (UTL_Error::EIDL_REDEF, t, ScopeAsDecl (this), predef); return 0; } if (referenced (predef, t->local_name ()) && !t->is_defined ()) { idl_global->err ()->error3 (UTL_Error::EIDL_DEF_USE, t, ScopeAsDecl (this), predef); return 0; } } AST_Decl::NodeType nt = ScopeAsDecl (this)->node_type (); // Decls inside a struct or union are also referenced by // fields, and so must be handled differently. if ( nt == AST_Decl::NT_struct || nt == AST_Decl::NT_union || nt == AST_Decl::NT_except) { this->add_to_local_types (t); } else { this->add_to_scope (t); } // Add it to set of locally referenced symbols. this->add_to_referenced (t, false, t->local_name ()); return t; } AST_StructureFwd * UTL_Scope::fe_add_fwd_struct_type (AST_StructureFwd *t) { // Already defined and cannot be redefined? Or already used? AST_Decl *d = this->lookup_for_add (t); if (d) { // There used to be another check here ANDed with the one below: // d->defined_in () == this. But lookup_for_add() calls only // lookup_by_name_local(), which does not bump up the scope, // and look_in_prev_mods() for modules. If look_in_prev_mods() // finds something, the scopes will NOT be the same pointer // value, but the result is what we want. if (d->node_type () == AST_Decl::NT_struct) { t->set_full_definition (AST_Structure::narrow_from_decl (d)); } else if (!FE_Utils::can_be_redefined (d, t)) { idl_global->err ()->error3 (UTL_Error::EIDL_REDEF, t, ScopeAsDecl (this), d); return 0; } else if (this->referenced (d, t->local_name ())) { idl_global->err ()->error3 (UTL_Error::EIDL_DEF_USE, t, ScopeAsDecl (this), d); return 0; } } // Add it to scope this->add_to_scope (t); // Add it to set of locally referenced symbols this->add_to_referenced (t, false, t->local_name ()); // Must check later that all struct and union forward declarations // are defined in the same IDL file. AST_record_fwd_decl (t); return t; } AST_PredefinedType * UTL_Scope::fe_add_predefined_type (AST_PredefinedType *) { return 0; } AST_Module * UTL_Scope::fe_add_module (AST_Module *) { return 0; } AST_Template_Module_Inst * UTL_Scope::fe_add_template_module_inst (AST_Template_Module_Inst *) { return 0; } AST_Template_Module_Ref * UTL_Scope::fe_add_template_module_ref (AST_Template_Module_Ref *) { return 0; } AST_Interface * UTL_Scope::fe_add_interface (AST_Interface *) { return 0; } AST_InterfaceFwd * UTL_Scope::fe_add_interface_fwd (AST_InterfaceFwd *) { return 0; } AST_ValueBox * UTL_Scope::fe_add_valuebox (AST_ValueBox *) { return 0; } AST_ValueType * UTL_Scope::fe_add_valuetype (AST_ValueType *) { return 0; } AST_ValueTypeFwd * UTL_Scope::fe_add_valuetype_fwd (AST_ValueTypeFwd *) { return 0; } AST_EventType * UTL_Scope::fe_add_eventtype (AST_EventType *) { return 0; } AST_EventTypeFwd * UTL_Scope::fe_add_eventtype_fwd (AST_EventTypeFwd *) { return 0; } AST_Component * UTL_Scope::fe_add_component (AST_Component *) { return 0; } AST_ComponentFwd * UTL_Scope::fe_add_component_fwd (AST_ComponentFwd *) { return 0; } AST_Home * UTL_Scope::fe_add_home (AST_Home *) { return 0; } AST_Exception * UTL_Scope::fe_add_exception (AST_Exception *) { return 0; } AST_Constant * UTL_Scope::fe_add_constant (AST_Constant *) { return 0; } UTL_StrList * UTL_Scope::fe_add_context (UTL_StrList *) { return 0; } UTL_NameList * UTL_Scope::fe_add_exceptions (UTL_NameList *) { return 0; } AST_Attribute * UTL_Scope::fe_add_attribute (AST_Attribute *) { return 0; } AST_Operation * UTL_Scope::fe_add_operation (AST_Operation *) { return 0; } AST_Argument * UTL_Scope::fe_add_argument (AST_Argument *) { return 0; } AST_Union * UTL_Scope::fe_add_union (AST_Union *) { return 0; } AST_UnionFwd * UTL_Scope::fe_add_union_fwd (AST_UnionFwd *) { return 0; } AST_UnionBranch * UTL_Scope::fe_add_union_branch (AST_UnionBranch *) { return 0; } AST_Structure * UTL_Scope::fe_add_structure (AST_Structure *) { return 0; } AST_StructureFwd * UTL_Scope::fe_add_structure_fwd (AST_StructureFwd *) { return 0; } AST_Field * UTL_Scope::fe_add_field (AST_Field *) { return 0; } AST_Enum * UTL_Scope::fe_add_enum (AST_Enum *) { return 0; } AST_EnumVal * UTL_Scope::fe_add_enum_val (AST_EnumVal *) { return 0; } AST_Typedef * UTL_Scope::fe_add_typedef (AST_Typedef *) { return 0; } AST_Sequence * UTL_Scope::fe_add_sequence (AST_Sequence *) { return 0; } AST_String * UTL_Scope::fe_add_string (AST_String *) { return 0; } AST_Array * UTL_Scope::fe_add_array (AST_Array *) { return 0; } AST_Native * UTL_Scope::fe_add_native (AST_Native *) { return 0; } AST_Factory * UTL_Scope::fe_add_factory (AST_Factory *) { return 0; } AST_Finder * UTL_Scope::fe_add_finder (AST_Finder *) { return 0; } AST_PortType * UTL_Scope::fe_add_porttype (AST_PortType *) { return 0; } AST_Provides * UTL_Scope::fe_add_provides (AST_Provides *) { return 0; } AST_Uses * UTL_Scope::fe_add_uses (AST_Uses *) { return 0; } AST_Publishes * UTL_Scope::fe_add_publishes (AST_Publishes *) { return 0; } AST_Emits * UTL_Scope::fe_add_emits (AST_Emits *) { return 0; } AST_Consumes * UTL_Scope::fe_add_consumes (AST_Consumes *) { return 0; } AST_Extended_Port * UTL_Scope::fe_add_extended_port (AST_Extended_Port *) { return 0; } AST_Mirror_Port * UTL_Scope::fe_add_mirror_port (AST_Mirror_Port *) { return 0; } AST_Connector * UTL_Scope::fe_add_connector (AST_Connector *) { return 0; } // Private lookup mechanism. // For dealing with lookups of 'Object' and 'TypeCode'. AST_Decl * UTL_Scope::lookup_pseudo (Identifier *e) { if (e->escaped ()) { return 0; } bool *seen = 0; char *name_string = e->get_string (); UTL_Scope *start_scope = idl_global->corba_module (); if (ACE_OS::strcasecmp (name_string, "TypeCode") == 0 || ACE_OS::strcasecmp (name_string, "TCKind") == 0) { this->which_pseudo_ = PSEUDO_TYPECODE; start_scope = this; seen = &idl_global->typecode_seen_; } else if (ACE_OS::strcasecmp (name_string, "Object") == 0) { this->which_pseudo_ = PSEUDO_OBJECT; seen = &idl_global->base_object_seen_; } else if (ACE_OS::strcasecmp (name_string, "ValueBase") == 0) { this->which_pseudo_ = PSEUDO_VALUEBASE; seen = &idl_global->valuebase_seen_; } else if (ACE_OS::strcasecmp (name_string, "AbstractBase") == 0) { this->which_pseudo_ = PSEUDO_ABSTRACTBASE; seen = &idl_global->abstractbase_seen_; } else { return 0; } for (UTL_ScopeActiveIterator i (start_scope, IK_decls); !i.is_done (); i.next ()) { AST_Decl *d = i.item (); if (e->case_compare (d->local_name ())) { // These have to be located here because we are just looking // up a scoped name - skip for imported nodes. if (idl_global->in_main_file ()) { *seen = true; } return d; } } if (this->which_pseudo_ == PSEUDO_TYPECODE) { AST_Decl *d = this->look_in_prev_mods_local (e); if (d != 0) { // Generation of #includes for Typecode.h // checks this bit, so we set it for TCKind as well. *seen = true; return d; } } return 0; } AST_Decl * UTL_Scope::look_in_prev_mods_local (Identifier *, bool /* ignore_fwd */) { return 0; } AST_Decl * UTL_Scope::special_lookup (UTL_ScopedName *, bool /* full_def_only */, AST_Decl *&/*final_parent_decl*/) { return 0; } // Lookup the node for a primitive (built-in) type. AST_Decl * UTL_Scope::lookup_primitive_type (AST_Expression::ExprType et) { UTL_Scope *search = idl_global->corba_module (); AST_PredefinedType::PredefinedType pdt = FE_Utils::ExprTypeToPredefinedType (et); /// This return value means there was no PredefinedType match /// for the ExprType. if (pdt == AST_PredefinedType::PT_pseudo) { return 0; } /// The only 'predefined type' not in the CORBA module. if (pdt == AST_PredefinedType::PT_void) { search = idl_global->root (); } for (UTL_ScopeActiveIterator i (search, IK_decls); !i.is_done(); i.next ()) { AST_Decl *as_decl = i.item (); if (as_decl->node_type () == AST_Decl::NT_pre_defined) { AST_PredefinedType *t = AST_PredefinedType::narrow_from_decl (as_decl); if (t->pt () == pdt) { if (idl_global->in_main_file ()) { switch (pdt) { case AST_PredefinedType::PT_any: idl_global->any_seen_ = true; break; case AST_PredefinedType::PT_object: idl_global->base_object_seen_ = true; break; default: break; } } return t; } } } return 0; } // Look through inherited list. Overridden in AST_Interface. AST_Decl * UTL_Scope::look_in_inherited (UTL_ScopedName *, bool ) { return 0; } // Look through supported interface list. Overridden where necessary. AST_Decl * UTL_Scope::look_in_supported (UTL_ScopedName *, bool) { return 0; } AST_Decl * UTL_Scope::lookup_by_name_local (Identifier *e, bool full_def_only) { // Will catch Object, TypeCode, TCKind, ValueBase and // AbstractBase. A non-zero result of this lookup determines the // generation of some #includes and, whether successful or not, // incurs no extra overhead. AST_Decl *d = this->lookup_pseudo (e); if (d) { return d; } if (this->idl_keyword_clash (e)) { return 0; } bool in_corba = (ACE_OS::strcmp (e->get_string (), "CORBA") == 0); // We search only the decls here, the local types are done // below as a last resort. for (UTL_ScopeActiveIterator i (this, IK_decls); !i.is_done (); i.next ()) { d = i.item ()->adjust_found (true, full_def_only); if (d != 0) { Identifier *item_name = d->local_name (); if (item_name != 0 // Right now we populate the global scope with all the CORBA basic // types, so something like 'ULong' in an IDL file will find a // match, unless we skip over these items. This is a workaround until // there's time to fix the code generation for CORBA basic types. && (in_corba || (ACE_OS::strcmp (d->name ()->head ()->get_string (), "CORBA") != 0)) && e->case_compare (item_name)) { return d; // We have found the one and only one we are looking for. } } } // Ok the name wasn't found in the current scope, if this // scope is a module, we can check it's previous openings! AST_Module *m = AST_Module::narrow_from_scope (this); if (m) { d = m->look_in_prev_mods_local (e); if (d && (!full_def_only || d->is_defined ())) { return d; } } else { // Or if this scope is an interface, we can check if // it was inherited! AST_Interface *i = AST_Interface::narrow_from_scope (this); if (i) { d = i->look_in_inherited_local (e); if (d) { return d; } } } // There are some cases where the iteration over IK_decls // above will fail because what we're searching for has been // added only to the local types. It's less complicated to // do the iteration below only as a last resort. for (UTL_ScopeActiveIterator i (this, IK_localtypes); !i.is_done (); i.next ()) { d = i.item (); if (e->case_compare (d->local_name ())) { return d; } } return 0; } AST_Decl * UTL_Scope::lookup_by_name (UTL_ScopedName *e, bool full_def_only, bool for_add) { // Empty name? Exit immediately. if (!e) { return 0; } UTL_Scope *work = this; // If name starts with "::" or "" start lookup in global scope, // if we're not there already, short_circuiting the // scope-expanding iteration below. Identifier *name = e->head (); const bool global_scope_name = work->is_global_name (name); if (global_scope_name) { // Remove the preceeding "::" or "" from the scopename e = static_cast<UTL_ScopedName *> (e->tail ()); name = e->head (); // Move directly to the root scope work = idl_global->root (); } AST_Decl *first_found_final_parent_decl= 0; const bool searching_module_path= (e->length () != 1); AST_Decl *d = searching_module_path ? work->lookup_by_name_r (e, full_def_only, first_found_final_parent_decl) : work->lookup_by_name_r (e, full_def_only); if (d == 0) { // If all else fails, look though each outer scope. for (UTL_Scope *outer = ScopeAsDecl (work)->defined_in (); outer; outer = ScopeAsDecl (outer)->defined_in ()) { AST_Decl *next_found_final_parent_decl= 0; d = outer->lookup_by_name_r (e, full_def_only, next_found_final_parent_decl); if (d != 0) { work = outer; if (first_found_final_parent_decl) { // Hidden scopes can't be used indirectly, therefore we didn't actually // find this one because the "first_found_final_parent_decl" was found and // this one just found is hidden by it. idl_global->err ()->scope_masking_error (d, first_found_final_parent_decl); d = 0; // Ignore this one; continue searching to report other ambiguous matches. } else { break; // Ok found it, stop searching. } } else if (searching_module_path && !first_found_final_parent_decl) { first_found_final_parent_decl = next_found_final_parent_decl; } } } if (for_add) { /// Doesn't add if d == 0. work->add_to_referenced (d, false, name); } return d; } AST_Decl * UTL_Scope::lookup_by_name_r (UTL_ScopedName *e, bool full_def_only) { AST_Decl *ignored= 0; return UTL_Scope::lookup_by_name_r (e, full_def_only, ignored); } AST_Decl * UTL_Scope::lookup_by_name_r (UTL_ScopedName *e, bool full_def_only, AST_Decl *&final_parent_decl) { bool work_another_level; UTL_Scope *work = this; final_parent_decl= (e->length () == 1) ? ScopeAsDecl (work) : 0; do { // Will catch Object, TypeCode, TCKind, ValueBase and // AbstractBase. A non-zero result of this lookup determines the // generation of some #includes and, whether successful or not, // incurs no extra overhead. AST_Decl *d = work->lookup_pseudo (e->head ()); if (d) { return d; } if (work->idl_keyword_clash (e->head ())) { return 0; } // Before proceeding to normal lookup, check if the name // matches a template module parameter. If so, the return // value is created on the heap and is owned by the caller // of this lookup. if (final_parent_decl) { // Since we are inside the scope of a template module, any // single-segment scoped name that matches a template // parameter name has to be a reference to that parameter, // so we return the created placeholder. If there's no // match, 0 is returned, and we proceed with the regular // lookup. AST_Param_Holder *param_holder = UTL_Scope::match_param (e); if (param_holder) { return param_holder; } } work_another_level = false; // Until we find something. bool in_corba = (ACE_OS::strcmp (e->head ()->get_string (), "CORBA") == 0); for (UTL_ScopeActiveIterator i (work, IK_decls); !i.is_done (); i.next ()) { d = i.item ()->adjust_found (true, full_def_only); if (d // Right now we populate the global scope with all the CORBA basic // types, so something like 'ULong' in an IDL file will find a // match, unless we skip over these items. This is a workaround until // there's time to fix the code generation for CORBA basic types. && (in_corba || ACE_OS::strcmp (d->name ()->head ()->get_string (), "CORBA")) && d->local_name ()->case_compare (e->head ())) { // Ok we found a match, is there any more to find? if (final_parent_decl) { return d; // Last scope name matched } UTL_Scope *next = DeclAsScope (d); // The next scope to search if (next) { work = next; work_another_level = true; e = static_cast<UTL_ScopedName *> (e->tail ()); final_parent_decl= (e->length () == 1) ? d : 0; break; } // Template weirdness, actual one we want should be // found next in this search, keep going. } } } while (work_another_level); // A rare enough case that it's worth it to separate it and // do it as a last resort. Catches anonymnous types, enums // and members with their types defined all in one statement. if (final_parent_decl) { for (UTL_ScopeActiveIterator i (work, IK_localtypes); !i.is_done (); i.next ()) { AST_Decl *d = i.item (); if (d->local_name ()->case_compare (e->head ())) { return d; } } } // Last resort, check other module openings of working scope. return work->special_lookup (e, full_def_only, final_parent_decl); } // Add a node to set of nodes referenced in this scope. void UTL_Scope::add_to_referenced (AST_Decl *e, bool recursive, Identifier *id, AST_Decl *ex) { // Empty name? Exit immediately. if (!e) { return; } // Special case for forward declared interfaces in the // scope in which they're defined. Cannot add before full // definition is seen. AST_Decl::NodeType nt = e->node_type (); if ( nt == AST_Decl::NT_interface || nt == AST_Decl::NT_component) { AST_Interface *itf = AST_Interface::narrow_from_decl (e); if (itf && itf->defined_in () == this && !itf->is_defined ()) { return; } } // Only insert if it is not there already. if (this->referenced (e, id)) { return; } // Sets the appropriate *_seen_ flag for future use. this->check_for_predef_seq (e); // Make sure there's space for one more decl. if (this->pd_referenced_allocated == this->pd_referenced_used) { long oreferenced_allocated = this->pd_referenced_allocated; this->pd_referenced_allocated += INCREMENT; AST_Decl **tmp = 0; ACE_NEW (tmp, AST_Decl *[this->pd_referenced_allocated]); for (long i = 0; i < oreferenced_allocated; ++i) { tmp [i] = this->pd_referenced [i]; } delete [] this->pd_referenced; this->pd_referenced = tmp; } // Insert new reference. if (!ex) { this->pd_referenced [this->pd_referenced_used++] = e; } else if (this->referenced (ex)) { long i; for (i = this->pd_referenced_used; 0 < i && this->pd_referenced [i - 1] != ex; --i) { this->pd_referenced [i] = this->pd_referenced [i - 1]; } this->pd_referenced [i] = e; ++this->pd_referenced_used; } // Now, if recursive is specified and "this" is not a common ancestor // of the referencing scope and the scope of definition of "e" then // add "e" to the set of referenced nodes in the parent of "this". if (recursive && !(e->has_ancestor (ScopeAsDecl (this)))) { UTL_Scope *s = e->defined_in (); if (s) { s->add_to_referenced (e, recursive, id); } } // Add the identifier arg, if non-null, to the identifier list. if (id) { this->add_to_name_referenced (id); } } void UTL_Scope::add_to_name_referenced (Identifier *id) { // Make sure we have enough space. if (this->pd_name_referenced_allocated == this->pd_name_referenced_used) { long name_referenced_allocated = this->pd_name_referenced_allocated; this->pd_name_referenced_allocated += INCREMENT; Identifier **name_tmp = 0; ACE_NEW (name_tmp, Identifier *[this->pd_name_referenced_allocated]); for (long i = 0; i < name_referenced_allocated; ++i) { name_tmp[i] = this->pd_name_referenced[i]; } delete [] this->pd_name_referenced; this->pd_name_referenced = name_tmp; } // Insert new identifier. this->pd_name_referenced[this->pd_name_referenced_used++] = id->copy (); } void UTL_Scope::replace_referenced (AST_Decl *old_decl, AST_Decl *new_decl) { for (int i = 0; i < this->pd_referenced_used; ++i) { if (this->pd_referenced[i] == old_decl) { this->pd_referenced[i] = new_decl; break; } } } void UTL_Scope::replace_scope (AST_Decl *old_decl, AST_Decl *new_decl) { for (int i = 0; i < pd_decls_used; ++i) { if (this->pd_decls[i] == old_decl) { this->pd_decls[i] = new_decl; break; } } } // Add a node to set of nodes declared in this scope. void UTL_Scope::add_to_scope (AST_Decl *e, AST_Decl *ex) { if (!e) { return; } Identifier *decl_name = e->local_name (); char *decl_string = decl_name->get_string (); AST_Decl::NodeType new_nt = e->node_type (); // First, make sure there's no clash between e, that was // just declared, and some other identifier referenced // in this scope. AST_Decl **tmp = this->pd_decls; for (long i = this->pd_decls_used; i--; // NOTE i-- test ++tmp) { // A local declaration doesn't use a scoped name. Identifier *ref_name = (*tmp)->local_name (); char *ref_string = ref_name->get_string (); // If the names compare exactly, it's a redefini8tion // error, unless they're both modules (which can be // reopened) or we have a belated definition of a // forward-declared interface. AST_Decl::NodeType scope_elem_nt = (*tmp)->node_type (); if (this->redef_clash (new_nt, scope_elem_nt) && decl_name->compare (ref_name)) { idl_global->err ()->redef_error (decl_string, ref_string); // if we try to continue from here, we risk a crash. throw Bailout (); } // If the spellings differ only by case, it's also an error, // unless one, but not both of the identifiers were escaped. else if (!(decl_name->escaped () ^ ref_name->escaped ()) && decl_name->case_compare_quiet (ref_name)) { if (idl_global->case_diff_error ()) { idl_global->err ()->name_case_error (decl_string, ref_string); // if we try to continue from here, we risk a crash. throw Bailout (); } else { idl_global->err ()->name_case_warning (decl_string, ref_string); } } } // The name of any scope except the unnamed scope formed by an operation // may not be redefined immediately within (and the root scope has no name). // As well as OBV factory construct. AST_Decl *d = ScopeAsDecl (this); AST_Decl::NodeType nt = d->node_type (); if ( nt != AST_Decl::NT_root && nt != AST_Decl::NT_op && nt != AST_Decl::NT_factory) { Identifier *parent_name = d->local_name (); if (decl_name->compare (parent_name)) { idl_global->err ()->redef_error ( decl_name->get_string (), parent_name->get_string () ); // if we try to continue from here, we risk a crash. throw Bailout (); } else if (decl_name->case_compare_quiet (parent_name)) { if (idl_global->case_diff_error ()) { idl_global->err ()->name_case_error ( decl_name->get_string (), parent_name->get_string () ); // if we try to continue from here, we risk a crash. throw Bailout (); } else { idl_global->err ()->name_case_warning ( decl_name->get_string (), parent_name->get_string () ); } } } // Now make sure there's space for one more. if (this->pd_decls_allocated == this->pd_decls_used) { long odecls_allocated = this->pd_decls_allocated; this->pd_decls_allocated += INCREMENT; ACE_NEW (tmp, AST_Decl *[pd_decls_allocated]); for (long i = 0; i < odecls_allocated; ++i) { tmp [i] = this->pd_decls [i]; } delete [] this->pd_decls; this->pd_decls = tmp; } // Insert new decl. if (!ex) { this->pd_decls [this->pd_decls_used++] = e; } else { long i; for (i = this->pd_decls_used; 0 < i && this->pd_decls [i - 1] != ex; --i) { this->pd_decls [i] = this->pd_decls [i - 1]; } this->pd_decls [i] = e; ++this->pd_decls_used; } } // Add a node to set of nodes representing manifest // types defined in this scope. void UTL_Scope::add_to_local_types (AST_Decl *e) { if (!e) { return; } // Make sure there's space for one more. if (this->pd_locals_allocated == this->pd_locals_used) { long olocals_allocated = this->pd_locals_allocated; this->pd_locals_allocated += INCREMENT; AST_Decl **tmp = 0; ACE_NEW (tmp, AST_Decl *[this->pd_locals_allocated]); for (long i = 0; i < olocals_allocated; ++i) { tmp[i] = this->pd_local_types[i]; } delete [] this->pd_local_types; this->pd_local_types = tmp; } // Insert new decl. this->pd_local_types[this->pd_locals_used++] = e; } // Has this node been referenced here before? bool UTL_Scope::referenced (AST_Decl *e, Identifier *id) { Identifier *test = e->local_name (); AST_Decl::NodeType nt = e->node_type (); AST_Decl **tmp = this->pd_referenced; for (long i = this->pd_referenced_used; i--; // NOTE test with i-- ++tmp) { // Same node? if (*tmp == e) { return true; } // Are we definging a forward declared struct, union, or interface, // or reopening a module? if (!this->redef_clash (nt, (*tmp)->node_type ()) && (*tmp)->local_name ()->compare (test)) { return false; } } // pd_referenced is a list of decls, and so there's no // way of telling how much of its scoped name was used // when it was referenced in this scope. pd_name_referenced // is a list of Identifiers that store the identifier (or // the first segment of a scoped name) used in the reference, // so we can catch these name reolution clashes. if (id) { Identifier **name_tmp = this->pd_name_referenced; for (long j = this->pd_name_referenced_used; j--; // NOTE test with j-- ++name_tmp) { // If we are a module, there is no clash, if we // are an interface, this is not the right place to // catch a clash, and if it wasn't defined in this // scope, then it's a type name for something else // that was, and it can appear any number of times // in this scope without a clash. AST_Decl::NodeType nt = e->node_type (); if ( nt != AST_Decl::NT_module && nt != AST_Decl::NT_param_holder && e->defined_in () == this && id->compare (*name_tmp)) { idl_global->err ()->redef_error (id->get_string (), (*name_tmp)->get_string ()); return true; } // No clash if one or the other of the identifiers was escaped. else if (!(id->escaped () ^ (*name_tmp)->escaped ()) && id->case_compare_quiet (*name_tmp)) { if (idl_global->case_diff_error ()) { idl_global->err ()->name_case_error ( id->get_string (), (*name_tmp)->get_string () ); } else { idl_global->err ()->name_case_warning ( id->get_string (), (*name_tmp)->get_string () ); } return true; } } } // Not found return false; } bool UTL_Scope::has_prefix (void) { return this->has_prefix_; } void UTL_Scope::has_prefix (bool val) { this->has_prefix_ = val; } // Redefinition of inherited virtual operations. // AST Dumping. void UTL_Scope::dump (ACE_OSTREAM_TYPE &o) { if (!idl_global->indent ()) { UTL_Indenter *idnt = 0; ACE_NEW (idnt, UTL_Indenter); idl_global->set_indent (idnt); } idl_global->indent ()->increase (); if (0 < this->pd_locals_used) { o << ACE_TEXT ("\n/* Locally defined types: */\n"); for (UTL_ScopeActiveIterator i (this, IK_localtypes); !i.is_done (); i.next ()) { AST_Decl *d = i.item (); if (!d->imported ()) { idl_global->indent ()->skip_to (o); d->dump (o); o << ACE_TEXT ("\n"); } } } if (0 < this->pd_decls_used) { o << ACE_TEXT ("\n/* Declarations: */\n"); for (UTL_ScopeActiveIterator j (this, IK_decls); !j.is_done (); j.next ()) { AST_Decl *d = j.item (); if (!d->imported ()) { idl_global->indent ()->skip_to (o); d->dump (o); o << ACE_TEXT (";\n"); } } } idl_global->indent ()->decrease (); } int UTL_Scope::ast_accept (ast_visitor *visitor) { return visitor->visit_scope (this); } // How many entries are defined? unsigned long UTL_Scope::nmembers (void) { return this->pd_decls_used; } AST_Param_Holder * UTL_Scope::match_param (UTL_ScopedName *e) { // If this call returns a zero value, we are not in the scope // of a template module. FE_Utils::T_PARAMLIST_INFO const *params = idl_global->current_params (); if (params == 0) { return 0; } const char *name = e->first_component ()->get_string (); FE_Utils::T_Param_Info *param = 0; unsigned long index = 0; UTL_StrList *alias_params = const_cast<UTL_StrList *> (idl_global->for_new_holder ()); if (alias_params == 0) { alias_params = const_cast<UTL_StrList *> (idl_global->alias_params ()); } UTL_String *alias_param = 0; for (FE_Utils::T_PARAMLIST_INFO::CONST_ITERATOR i (*params); i.next (param); i.advance (), ++index) { if (param->name_ == name) { /// If we are parsing this template module as a /// reference, the param holder we create must have /// the name of the corresponding aliased param. if (alias_params != 0) { unsigned long slot = 0; for (UTL_StrlistActiveIterator iter (alias_params); !iter.is_done (); iter.next (), ++slot) { if (slot == index) { alias_param = iter.item (); break; } } if (alias_param == 0) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("UTL_Scope::match_param - ") ACE_TEXT ("param not matched\n")), 0); } Identifier id (alias_param->get_string ()); UTL_ScopedName sn (&id, 0); return idl_global->gen ()->create_param_holder ( &sn, param); } else { return idl_global->gen ()->create_param_holder ( e, param); } } } return 0; } bool UTL_Scope::inherited_op_attr_clash (AST_Decl *t) { AST_Interface *i = AST_Interface::narrow_from_scope (this); if (!i) { return false; } AST_Decl *d = i->look_in_inherited (t->name (), false); if (d) { AST_Decl::NodeType nt = d->node_type (); if ( nt == AST_Decl::NT_attr || nt == AST_Decl::NT_op) { idl_global->err ()->error3 (UTL_Error::EIDL_REDEF, t, i, d); return true; } } return false; } bool UTL_Scope::arg_specific_error (AST_Decl *t) { AST_Operation *op = AST_Operation::narrow_from_scope (this); if (!op) { return false; } AST_Argument *arg = AST_Argument::narrow_from_decl (t); AST_Argument::Direction d = arg->direction (); // Cannot add OUT or INOUT argument to oneway operation. if (( d == AST_Argument::dir_OUT || d == AST_Argument::dir_INOUT) && op->flags () == AST_Operation::OP_oneway) { idl_global->err ()->error2 (UTL_Error::EIDL_ONEWAY_CONFLICT, t, op); return true; } // This error is not caught in y.tab.cpp so we check for it here. AST_Type *arg_type = arg->field_type (); if ( arg_type->node_type () == AST_Decl::NT_array && arg_type->anonymous ()) { idl_global->err ()->syntax_error (idl_global->parse_state ()); return true; } return false; } void UTL_Scope::smart_local_add (AST_Decl *t) { // Catches struct, union * exception AST_Structure *s = AST_Structure::narrow_from_scope (this); // Catches AST_Field and AST_UnionBranch. AST_Field *f = AST_Field::narrow_from_decl (t); // Decls inside a struct/union/exception are also referenced by // fields, and so must be handled differently. if (s && !f) { this->add_to_local_types (t); } else { this->add_to_scope (t); } // If we have an enum discriminator, add the label names to // the name_referenced list before we add the union branch, // so a branch name clash with a label name will be caught. AST_Union *u = AST_Union::narrow_from_scope (this); AST_UnionBranch *ub = AST_UnionBranch::narrow_from_decl (t); if (u && ub) { if (u->udisc_type () == AST_Expression::EV_enum) { ub->add_labels (u); } else { ub->coerce_labels (u); } } } // Determines if a name is global. bool UTL_Scope::is_global_name (Identifier *i) { if (!i) { return false; } ACE_CString cmp (i->get_string (), 0, false); return (cmp == "" || cmp == "::"); } AST_Decl * UTL_Scope::iter_lookup_by_name_local (AST_Decl *d, UTL_ScopedName *e, bool full_def_only) { // Remove all the layers of typedefs. while (d && d->node_type () == AST_Decl::NT_typedef) { AST_Typedef *td = AST_Typedef::narrow_from_decl (d); if (!td) { return 0; } d = td->base_type (); } if (!d) { return 0; } // Try to convert the AST_Decl to a UTL_Scope. UTL_Scope *sc = DeclAsScope (d); if (!sc) { return 0; } AST_Decl *result = 0; if (0 < sc->nmembers ()) { // Look up the first component of the scoped name. result = sc->lookup_by_name_local (e->head (), full_def_only); } else { AST_Interface *i = AST_Interface::narrow_from_decl (d); result = i ? i->look_in_inherited_local (e->head ()) : sc->look_in_prev_mods_local (e->head (), true); } UTL_ScopedName *sn = (UTL_ScopedName *) e->tail (); if (!result) { if (!sn) { result = UTL_Scope::match_param (e); } } else if (sn) { // Look up the next component of the scoped name. result = iter_lookup_by_name_local (result, sn, full_def_only); } return result; } IMPL_NARROW_FROM_SCOPE(UTL_Scope) // UTL_SCOPE_ACTIVE_ITERATOR // Constructor. UTL_ScopeActiveIterator::UTL_ScopeActiveIterator ( UTL_Scope *s, UTL_Scope::ScopeIterationKind i ) : iter_source (s), ik (i), stage (i == UTL_Scope::IK_both ? UTL_Scope::IK_localtypes : i), il (0) { } // Public operations. // Advance to next item. void UTL_ScopeActiveIterator::next (void) { this->il++; } // Get current item. AST_Decl * UTL_ScopeActiveIterator::item (void) { if (this->is_done ()) { return 0; } if (stage == UTL_Scope::IK_decls) { return this->iter_source->pd_decls[il]; } if (stage == UTL_Scope::IK_localtypes) { return this->iter_source->pd_local_types[il]; } return 0; } // Is this iteration done? bool UTL_ScopeActiveIterator::is_done (void) { long limit = (stage == UTL_Scope::IK_decls) ? iter_source->pd_decls_used : iter_source->pd_locals_used; for (;;) { // Last element? if (this->il < limit) { return false; } // Only want decls? if (this->stage == UTL_Scope::IK_decls) { return true; } // Already done local types? if (this->ik == UTL_Scope::IK_localtypes) { return true; } // Switch to next stage. this->stage = UTL_Scope::IK_decls; this->il = 0; limit = this->iter_source->pd_decls_used; } } // What kind of iterator is this? UTL_Scope::ScopeIterationKind UTL_ScopeActiveIterator::iteration_kind (void) { return this->ik; } // And where are we in the iteration? UTL_Scope::ScopeIterationKind UTL_ScopeActiveIterator::iteration_stage (void) { return this->stage; }
/* ============================================================================================ Program : High resolution Fetal and Pediatric MRI reconstruction Module : Compute image contrast measures (variance measure, L2 norm of gradient, Laplacian) File : mialtkEvaluateContrst.cxx Language: C++ Version : $Revision: 1.0 $ Copyright (c) 2017 Medical Image Analysis Laboratory (MIAL), Lausanne This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Latest modifications: April 26, 2009 =============================================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkCastImageFilter.h" #include "itkRescaleIntensityImageFilter.h" //#include "itkImageRegionIteratorWithIndex.h" #include "itkImageDuplicator.h" #include "itkRegionOfInterestImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkGradientMagnitudeImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" vnl_matrix<double> hadamard( int size ); float compute_alpha(itk::Image<float,3>::Pointer Im); int main( int argc, char * argv[] ) { if( argc < 2 ) { std::cerr << "Usage: " << std::endl; std::cerr << argv[0] << " inputImageFile " << std::endl; return EXIT_FAILURE; } const unsigned int Dimension = 3; typedef float InputPixelType; typedef float ImagePixelType; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< ImagePixelType, Dimension > ImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; typedef itk::CastImageFilter< InputImageType, ImageType > InputCastFilterType; InputCastFilterType::Pointer icastfilter = InputCastFilterType::New(); //std::cout << "Input image : " << argv[1] << std::endl; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); icastfilter->SetInput( reader->GetOutput() ); icastfilter->Update(); ImageType::Pointer inputImage = icastfilter->GetOutput(); ImageType::RegionType inputRegion = inputImage->GetLargestPossibleRegion(); ImageType::SizeType inputSize = inputRegion.GetSize(); ImageType::SizeType brainSize = inputRegion.GetSize(); typedef itk::ImageRegionIterator< ImageType > ImageIterator; ImageIterator iti( inputImage, inputRegion ); //Extract the max pixel value float maxValue = 0.0f; for (iti.GoToBegin(); !iti.IsAtEnd(); ++iti) { if(iti.Get()>=maxValue) maxValue = iti.Get(); } std::cout << "Maximum voxel value : " << maxValue << std::endl; /* ImageType::IndexType indexOrigCenter; indexOrigCenter[0] = floor(0.5 * inputSize[0]); indexOrigCenter[1] = floor(0.5 * inputSize[1]); indexOrigCenter[2] = floor(0.5 * inputSize[2]); */ //Pad the image to have a size of 128 a power of 2; int size = 256; ImageType::SizeType fixedSize; fixedSize[0] = size; fixedSize[1] = size; fixedSize[2] = size; //ImageType::RegionType brainRegion; //brainRegion.SetIndex(indexOrigCenter); //brainRegion.SetSize(fixedSize); ImageType::SizeType padBoundSize; padBoundSize[0] = fixedSize[0] - inputSize[0]; padBoundSize[1] = fixedSize[1] - inputSize[1]; padBoundSize[2] = fixedSize[2] - inputSize[2]; typedef itk::ConstantPadImageFilter <ImageType, ImageType> ConstantPadImageFilterType; ImageType::SizeType lowerExtendRegion; lowerExtendRegion[0] = ceil(0.5 * padBoundSize[0]); lowerExtendRegion[1] = ceil(0.5 * padBoundSize[1]); lowerExtendRegion[2] = ceil(0.5 * padBoundSize[2]); ImageType::SizeType upperExtendRegion; upperExtendRegion[0] = padBoundSize[0] - lowerExtendRegion[0]; upperExtendRegion[1] = padBoundSize[1] - lowerExtendRegion[1]; upperExtendRegion[2] = padBoundSize[2] - lowerExtendRegion[2]; ImageType::IndexType brainIndex = inputRegion.GetIndex(); brainIndex[0] = lowerExtendRegion[0]; brainIndex[1] = lowerExtendRegion[1]; brainIndex[2] = lowerExtendRegion[2]; //std::cout << "Brain region : " << brainRegion << std::endl; ImageType::PixelType constantPixel = 0.0; ConstantPadImageFilterType::Pointer padFilter = ConstantPadImageFilterType::New(); padFilter->SetInput(inputImage); //padFilter->SetPadBound(outputRegion); // Calls SetPadLowerBound(region) and SetPadUpperBound(region) padFilter->SetPadLowerBound(lowerExtendRegion); padFilter->SetPadUpperBound(upperExtendRegion); padFilter->SetConstant(constantPixel); padFilter->Update(); inputImage = padFilter->GetOutput(); inputRegion = inputImage->GetLargestPossibleRegion(); inputSize = inputRegion.GetSize(); ImageType::IndexType inputIndex = inputRegion.GetIndex(); //std::cout << "input region : " << inputRegion << std::endl; //std::cout << "input region : " << inputRegion << std::endl; typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROIFilterType; ROIFilterType::Pointer roiFilter = ROIFilterType::New(); roiFilter->SetInput(inputImage); roiFilter->SetRegionOfInterest(inputRegion); roiFilter->Update(); inputImage = roiFilter->GetOutput(); inputRegion = inputImage->GetLargestPossibleRegion(); inputSize = inputRegion.GetSize(); inputIndex = inputRegion.GetIndex(); //std::cout << "input region : " << inputRegion << std::endl; ImageType::IndexType brainIndexCrop; /* brainIndexCenter[0] = floor(0.5 * inputSize[0]) - 0.5 * floor(0.5 * inputSize[0]); brainIndexCenter[1] = floor(0.5 * inputSize[1]) - 0.5 * floor(0.5 * inputSize[0]); brainIndexCenter[2] = floor(0.5 * inputSize[2]) - 0.5 * floor(0.5 * inputSize[0]); brainIndexCrop[0] = inputIndex[0] + 0.5 * floor(0.5 * inputSize[0]); brainIndexCrop[1] = inputIndex[1] + 0.5 * floor(0.5 * inputSize[1]); brainIndexCrop[2] = inputIndex[2] + 0.5 * floor(0.5 * inputSize[2]); */ brainIndexCrop[0] = 0; brainIndexCrop[1] = 0; brainIndexCrop[2] = 0; ImageType::IndexType brainIndex2; brainIndex2[0] = inputIndex[0] + 0.5 * floor(0.5 * inputSize[0]); brainIndex2[1] = inputIndex[1] + 0.5 * floor(0.5 * inputSize[1]); brainIndex2[2] = inputIndex[2] + 0.5 * floor(0.5 * inputSize[2]); size=0.5*size; fixedSize[0] = size; fixedSize[1] = size; fixedSize[2] = size; ImageType::RegionType brainRegionCrop; brainRegionCrop.SetIndex(brainIndexCrop); brainRegionCrop.SetSize(fixedSize); ImageType::RegionType brainRegion2; brainRegion2.SetIndex(brainIndex2); brainRegion2.SetSize(fixedSize); //std::cout << "brain region crop: " << brainRegionCrop << std::endl; //std::cout << "brain region 2: " << brainRegion2 << std::endl; ImageType::Pointer inputImage2 = ImageType::New(); inputImage2->SetOrigin(inputImage->GetOrigin()); inputImage2->SetDirection(inputImage->GetDirection()); inputImage2->SetSpacing(inputImage->GetSpacing()); inputImage2->SetBufferedRegion(brainRegionCrop); inputImage2->SetLargestPossibleRegion(brainRegionCrop); //inputImage2->FillBuffer(0.0); inputImage2->Allocate(); ImageIterator cropIt(inputImage2,brainRegionCrop); ImageIterator inputIt(inputImage,brainRegion2); int cpt=0; float value = 0.0; for(cropIt.GoToBegin(),inputIt.GoToBegin(); !inputIt.IsAtEnd(); ++cropIt,++inputIt) { value = inputIt.Get(); cropIt.Set(value); } inputImage2->Update(); float alpha = compute_alpha(inputImage2.GetPointer()); /* typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName("/Users/sebastientourbier/Desktop/original_image2.nii.gz"); writer->SetInput(inputImage2.GetPointer()); writer->Update(); */ //inputImage = inputImage2; inputRegion = inputImage2->GetLargestPossibleRegion(); inputSize = inputRegion.GetSize(); //std::cout << "input region : " << inputRegion << std::endl; ImageType::IndexType indexCenter; indexCenter[0] = floor(0.5 * inputSize[0]); indexCenter[1] = floor(0.5 * inputSize[1]); indexCenter[2] = floor(0.5 * inputSize[2]); //std::cout << "Index center : [" << indexCenter[0] << "," << indexCenter[1] << "," << indexCenter[2] << "]" << std::endl; ImageType::RegionType bgRegion = brainRegionCrop; ImageType::RegionType fgRegion = brainRegionCrop; ImageType::SizeType bgSize; ImageType::SizeType fgSize; ImageType::IndexType bgIndexStart; ImageType::IndexType fgIndexStart; int windowRadius = 1; int bgBound = 1; int iter = 0; float bgMean = 0.0; float fgMean = 0.0; double CMI = 0.0; //Contrast Measurement Index based on the Logarithmic Image Processing (LIP) model std::cout << "#########################################################" << std::endl; while(brainRegionCrop.IsInside(bgRegion)) { iter++; //std::cout << "" << iter << std::endl; fgIndexStart[0] = indexCenter[0] - windowRadius; fgIndexStart[1] = indexCenter[1] - windowRadius; fgIndexStart[2] = indexCenter[2] - windowRadius; bgIndexStart[0] = fgIndexStart[0] - bgBound; bgIndexStart[1] = fgIndexStart[1] - bgBound; bgIndexStart[2] = fgIndexStart[2] - bgBound; fgSize[0] = 2 * windowRadius + 1; fgSize[1] = 2 * windowRadius + 1; fgSize[2] = 2 * windowRadius + 1; bgSize[0] = fgSize[0] + 2*bgBound; bgSize[1] = fgSize[1] + 2*bgBound; bgSize[2] = fgSize[2] + 2*bgBound; bgRegion.SetIndex(bgIndexStart); bgRegion.SetSize(bgSize); //bgRegion.Print(std::cout); fgRegion.SetIndex(fgIndexStart); fgRegion.SetSize(fgSize); //fgRegion.Print(std::cout); if(!brainRegionCrop.IsInside(bgRegion)) break; ImageIterator itBg( inputImage2, bgRegion ); ImageIterator itFg( inputImage2, fgRegion ); //Compute the mean value in the foreground region for (itFg.GoToBegin(); !itFg.IsAtEnd(); ++itFg) { fgMean += itFg.Get(); } fgMean = fgMean / (fgSize[0]*fgSize[1]*fgSize[2]); //std::cout << "Foreground mean : " << fgMean << " , "; //Compute the mean value in the background region for (itBg.GoToBegin(); !itBg.IsAtEnd(); ++itBg) { bgMean += itBg.Get(); } bgMean = bgMean / (bgSize[0]*bgSize[1]*bgSize[2]); //std::cout << "Background mean : " << bgMean << std::endl; //Implementation based on Mridul Trivedi et al., "A No-Reference Image Quality Index for Contrastand Sharpness Measurement", 2011 CMI += log( abs( (fgMean + bgMean - ( (fgMean*bgMean) / maxValue) ) / ( maxValue * ((fgMean - bgMean) / (maxValue - bgMean)) ) ) ); //Compute alpha : maximum of the Hadamard Transform computed for the original input image I //Implement CSMI - Contrast and Sharpness Measurement Index //std::cout << "---------------------------------------------------------" << std::endl; windowRadius++; } CMI = CMI / iter; std::cout << "Contrast Measurement Index (CMI) before mult. by alpha: " << CMI << std::endl; std::cout << "Alpha : " << alpha << std::endl; CMI = alpha * CMI; std::cout << "Contrast Measurement Index (CMI) : " << CMI << std::endl; /* double InputImageMeanIntensityValues = 0; for (iti.GoToBegin(); !iti.IsAtEnd(); ++iti) InputImageMeanIntensityValues += iti.Get(); InputImageMeanIntensityValues /= inputRegion.GetNumberOfPixels(); // std::cout << "Input image intensity mean: " << InputImageMeanIntensityValues << std::endl; double varianceSharpnessMeasure = 0; for (iti.GoToBegin(); !iti.IsAtEnd(); ++iti) varianceSharpnessMeasure += pow((iti.Get() - InputImageMeanIntensityValues),2); varianceSharpnessMeasure /= inputRegion.GetNumberOfPixels(); gradientFilter->SetInput( inputImage ); gradientFilter->Update(); ImageType::Pointer gradientMagnitudeImage = gradientFilter->GetOutput(); ImageIterator itgm( gradientMagnitudeImage, gradientMagnitudeImage->GetLargestPossibleRegion() ); double M2norm = 0; for (itgm.GoToBegin(); !itgm.IsAtEnd(); ++itgm) M2norm += pow( itgm.Get(), 2 ); std::cout << varianceSharpnessMeasure << " "; std::cout << M2norm << std::endl; */ return EXIT_SUCCESS; } vnl_matrix<double> hadamard( int matSize) { vnl_matrix<double> hadamardMat(matSize,matSize,0.0); hadamardMat(0,0) = 1.0; hadamardMat(1,0) = 1.0; hadamardMat(0,1) = 1.0; hadamardMat(1,1) = -1.0; int e = (int)(log2(matSize)); std::cout << "Exponent : " << e << std::endl; for( int l=2; l<=e; l++ ) { int block = pow(2,l); //std::cout << l << " , " << block << std::endl; for( int i=0; i<block; i++) { for( int j=0; j<block; j++) { int dup_block = pow(2,(l-1)); //std::cout << dup_block << std::endl; if( (i < dup_block) && (j >= dup_block) ) { //std::cout<< "block2" << std::endl; hadamardMat(i,j) = hadamardMat(i,j-dup_block); } else if( (i >= dup_block) && (j < dup_block) ) { //std::cout<< "block3" << std::endl; hadamardMat(i,j) = hadamardMat(i-dup_block,j); } else if( (i >= dup_block) && (j >= dup_block) ) { //std::cout<< "block4" << std::endl; hadamardMat(i,j) = -1.0 * hadamardMat(i-dup_block,j-dup_block); } else { //std::cout<< "block1" << std::endl; hadamardMat(i,j) = hadamardMat(i,j); } } } } std::cout<< "Hadamard matrix of size : " << matSize << std::endl; /* for( int i = 0; i<matSize; i++) for( int j=0; j<matSize; j++) { if(j<matSize-1) { if(hadamardMat(i,j) > 0) std::cout << " "; std::cout << hadamardMat(i,j) << " "; } else { if(hadamardMat(i,j) > 0) std::cout << " "; std::cout << hadamardMat(i,j) << std::endl; } } */ return hadamardMat; } float compute_alpha(itk::Image<float,3>::Pointer Im) { typedef itk::Image<float,3> ImageType; typedef itk::Image<float,2> SliceType; ImageType::RegionType imRegion = Im->GetLargestPossibleRegion(); ImageType::SizeType imSize = imRegion.GetSize(); ImageType::IndexType imIndex = imRegion.GetIndex(); //std::cout << Im->GetBufferedRegion() << std::endl; //std::cout << Im->GetLargestPossibleRegion() << std::endl; //Compute 3D Hadamard transform based on Matlab source code: Faster 3D Walsh - Hadamard Transform (sequency, natural) //Provided in the file exchange //Make the assumption image size along x and y directions are equal vnl_matrix<double> W = hadamard(imSize[0]); //itk::ImageDuplicator<ImageType>::Pointer duplicator = itk::ImageDuplicator<ImageType>::New(); //duplicator->SetInputImage(Im); //duplicator->Update(); ImageType::Pointer outImage = ImageType::New(); outImage->SetOrigin(Im->GetOrigin()); outImage->SetDirection(Im->GetDirection()); outImage->SetSpacing(Im->GetSpacing()); outImage->SetBufferedRegion(Im->GetLargestPossibleRegion()); outImage->Allocate(); //duplicator->GetOutput(); //First do 2D transform of the x-y-plane through all z layers typedef itk::RegionOfInterestImageFilter< ImageType, ImageType > ROI2DFilterType; ROI2DFilterType::Pointer roi2DFilter = ROI2DFilterType::New(); //std::cout << imSize << std::endl; for(int sliceID=0; sliceID<imSize[2]; sliceID++) { //std::cout << "slice id (x/y): " << sliceID << std::endl; ImageType::IndexType sliceIndex; sliceIndex[0] = imIndex[0]; sliceIndex[1] = imIndex[1]; sliceIndex[2] = sliceID; ImageType::SizeType sliceSize; sliceSize[0] = imSize[0]; sliceSize[1] = imSize[1]; sliceSize[2] = 1; ImageType::RegionType sliceRegion; sliceRegion.SetIndex(sliceIndex); sliceRegion.SetSize(sliceSize); roi2DFilter->SetInput(Im); roi2DFilter->SetRegionOfInterest(sliceRegion); roi2DFilter->Update(); ImageType::Pointer slice = roi2DFilter->GetOutput(); itk::ImageRegionIteratorWithIndex<ImageType> sliceIt(slice,slice->GetLargestPossibleRegion()); vnl_matrix<double> sliceX(imSize[0],imSize[1],0.0); //Convert slice into vnl matrix for (sliceIt.GoToBegin(); !sliceIt.IsAtEnd(); ++sliceIt) { ImageType::IndexType ind = sliceIt.GetIndex(); sliceX(ind[0],ind[1]) = sliceIt.Get(); //if(sliceX(ind[0],ind[1])>0) std::cout << sliceX(ind[0],ind[1]) << std::endl; } //Apply 2D Hadamard transform on the current slice sliceX = (W * sliceX) * W; itk::ImageRegionIteratorWithIndex<ImageType> sliceImIt(outImage,sliceRegion); for (sliceImIt.GoToBegin(); !sliceImIt.IsAtEnd(); ++sliceImIt) { ImageType::IndexType ind = sliceImIt.GetIndex(); sliceImIt.Set(sliceX(ind[0],ind[1])); } } /* typedef itk::ImageFileWriter<ImageType> WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName("/Users/sebastientourbier/Desktop/hadamard_image_2d.nii.gz"); writer->SetInput(outImage); writer->Update(); */ //Now perform 1D transform along the z direction for(int sliceID=0; sliceID<imSize[1]; sliceID++) { //std::cout << "slice id (z): " << sliceID << std::endl; ImageType::IndexType sliceIndex; sliceIndex[0] = imIndex[0]; sliceIndex[1] = sliceID; sliceIndex[2] = imIndex[2]; ImageType::SizeType sliceSize; sliceSize[0] = imSize[0]; sliceSize[1] = 1; sliceSize[2] = imSize[2]; ImageType::RegionType sliceRegion; sliceRegion.SetIndex(sliceIndex); sliceRegion.SetSize(sliceSize); roi2DFilter->SetInput(outImage); roi2DFilter->SetRegionOfInterest(sliceRegion); roi2DFilter->Update(); ImageType::Pointer slice = roi2DFilter->GetOutput(); itk::ImageRegionIteratorWithIndex<ImageType> sliceIt(slice,slice->GetLargestPossibleRegion()); vnl_matrix<double> sliceX(imSize[0],imSize[2],0.0); //Convert slice into vnl matrix for (sliceIt.GoToBegin(); !sliceIt.IsAtEnd(); ++sliceIt) { ImageType::IndexType ind = sliceIt.GetIndex(); //std::cout << ind << std::endl; sliceX(ind[0],ind[2]) = sliceIt.Get(); //if(sliceX(ind[0],ind[1])>0) std::cout << sliceX(ind[0],ind[1]) << std::endl; } //Apply 2D Hadamard transform on the current slice //float factor = 1 / pow(2,(0.5*(log2(imSize[0])))+(0.5*(log2(imSize[1])))+(0.5*(log2(imSize[2])))); //sliceX = (sliceX * W) * factor; sliceX = (sliceX * W) / sqrt(imSize[0]*imSize[1]*imSize[2]); //faster itk::ImageRegionIteratorWithIndex<ImageType> sliceImIt(outImage,sliceRegion); for (sliceImIt.GoToBegin(); !sliceImIt.IsAtEnd(); ++sliceImIt) { ImageType::IndexType ind = sliceImIt.GetIndex(); sliceImIt.Set(sliceX(ind[0],ind[2])); } } /* writer->SetFileName("/Users/sebastientourbier/Desktop/hadamard_image_3d.nii.gz"); writer->SetInput(outImage); writer->Update(); */ //Extract maximum value in the Hadamard transform : it corresponds to the value of alpha itk::ImageRegionIteratorWithIndex<ImageType> sliceImIt(outImage,outImage->GetLargestPossibleRegion()); float alpha = 0.0; for (sliceImIt.GoToBegin(); !sliceImIt.IsAtEnd(); ++sliceImIt) if(sliceImIt.Get()>=alpha) alpha = sliceImIt.Get(); return alpha; }
#include <DoubleBufferedAllocator.h> #include <FallbackAllocator.h> #include <LinearAllocator.h> #include <MallocAllocator.h> #include <PoolAllocator.h> #include <iostream> using namespace EzMemory; // Static checks // Malloc is an allocator that can align... static_assert(IsAllocator<MallocAllocator>); static_assert(AllocatorCanAlign<MallocAllocator>); // ... but does not know ownership or reset static_assert(!AllocatorKnowsOwnership<MallocAllocator>); static_assert(!AllocatorCanReset<MallocAllocator>); typedef PoolAllocator<MallocAllocator, 16, 4> PoolAlloc; // Pool allocators have all features static_assert(IsAllocator<PoolAlloc>); static_assert(AllocatorCanAlign<PoolAlloc>); static_assert(AllocatorKnowsOwnership<PoolAlloc>); static_assert(AllocatorCanReset<PoolAlloc>); typedef LinearAllocator<MallocAllocator, 1024> LinAlloc; // Linear allocators have all features static_assert(IsAllocator<LinAlloc>); static_assert(AllocatorCanAlign<LinAlloc>); static_assert(AllocatorKnowsOwnership<LinAlloc>); static_assert(AllocatorCanReset<LinAlloc>); typedef FallbackAllocator<PoolAlloc, MallocAllocator> FallbackAlloc; typedef FallbackAllocator<PoolAlloc, LinAlloc> FallbackToLin; // Fallback allocators inherit capabilities from their least capable backing // allocator static_assert(IsAllocator<FallbackAlloc>); static_assert(AllocatorCanAlign<FallbackAlloc>); static_assert(!AllocatorKnowsOwnership<FallbackAlloc>); static_assert(!AllocatorCanReset<FallbackAlloc>); static_assert(IsAllocator<FallbackToLin>); static_assert(AllocatorCanAlign<FallbackToLin>); static_assert(AllocatorKnowsOwnership<FallbackToLin>); static_assert(AllocatorCanReset<FallbackToLin>); typedef DoubleBufferedAllocator<LinAlloc> DblAlloc; // Double buffered allocators inherit capabilities from their backing // allocator (but require all features except for alignment) static_assert(IsAllocator<DblAlloc>); static_assert(AllocatorCanAlign<DblAlloc>); static_assert(AllocatorKnowsOwnership<DblAlloc>); static_assert(AllocatorCanReset<DblAlloc>); void testPoolAlloc() { MallocAllocator m; PoolAlloc p(&m); // Check the pool allocator assert(p.allocate(16)); void *pa1 = p.allocate(16); assert(pa1); assert(p.allocate(16)); assert(p.allocate(16)); // Full - deallocations should make room assert(!p.allocate(16)); p.deallocate(pa1); assert(p.allocate(16)); p.reset(); } void testFallbackAllocator_PoolToMalloc() { MallocAllocator m; PoolAlloc p(&m); FallbackAlloc fb(&p, &m); // Check the fallback allocator assert(fb.allocate(16)); assert(fb.allocate(16)); assert(fb.allocate(16)); assert(fb.allocate(16)); // Primary allocator is now full assert(fb.allocate(16)); } void testLinearAllocator() { MallocAllocator m; LinAlloc l(&m); // Check that linear allocators can use their entire buffer assert(l.allocate(512)); assert(l.allocate(512)); assert(!l.allocate(512)); l.reset(); assert(l.allocate(512)); l.reset(); // Check that failed asserts do not consume the buffer assert(!l.allocate(1025)); assert(l.allocate(1024)); l.reset(); } void testDoubleBufferedAllocator_Linear() { MallocAllocator m; LinAlloc l1(&m); LinAlloc l2(&m); DblAlloc db(&l1, &l2); // Check the double buffer assert(db.allocate(1024)); assert(!db.allocate(1)); db.flip(); assert(db.allocate(1024)); assert(!db.allocate(1)); db.flip(); assert(db.allocate(1024)); db.reset(); } int main() { testPoolAlloc(); testFallbackAllocator_PoolToMalloc(); testLinearAllocator(); testDoubleBufferedAllocator_Linear(); return 0; }
#include <cstdlib> #include <string> #include <chrono> #include <thread> #include "ros/ros.h" #include "interface.h" #include "uds.h" using namespace std; using namespace roscar::car::interface; using namespace roscar::car::roscar_common; const char *UDS_URI = "/tmp/.roscar.car.interface.soc"; int main(int argc, char **argv) { ros::init(argc, argv, "interface"); if (argc != 1) { ROS_INFO("usage: interface"); return 1; } ros::NodeHandle nh; // init interface ROS_DEBUG("init interface."); Interface::init(nh); // init uds ROS_DEBUG("init uds."); UDS uds(Interface::onSignaling); uds.start(UDS_URI); ROS_INFO("ROS Car Interface Ready."); uds.join(); return 0; }
/* SPDX-License-Identifier: Apache-2.0 */ /* * Copyright (C) 2013-2020 Intel Corporation */ #include "AMTEthernetPortSettingsClient.h" #include "AMTFCFHWSmanClient.h" #include "AMTRedirectionServiceWSManClient.h" #include "AuditLogWSManClient.h" #include "BaseWSManClient.h" #include "CancelOptInClient.h" #include "HBPWSManClient.h" #include "KVMWSManClient.h" #include "SIOWSManClient.h" #include "SyncIpClient.h" #include "TimeSynchronizationClient.h" #include "Mock_AMT_EthernetPortSettings.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include <sstream> #include <iostream> #include <string> using ::testing::AtLeast; using ::testing::Return; using namespace std; //Not tested - constructor with username and password, for all classes //Shouldn't init be private in all classes, since all methods call it anyway? /* * AMTEthernetPortSettings: * Link preference: 1 - ME * 2 - HOST * 3 - Reserved */ //TODO: Disable all AMTEthernetPortSettingsClient tests in case there's no wireless network TEST(AMTEthernetPortSettingsClient, DISABLED_Get) { AMTEthernetPortSettingsClient settings; unsigned int pLinkPreference = 0; unsigned int pLinkControl = 0; unsigned int pLinkProtection = 0; bool ret = false; EXPECT_TRUE(ret = settings.GetAMTEthernetPortSettings(&pLinkPreference, &pLinkControl, &pLinkProtection)); if (ret){ cout << "Link Preference: " << pLinkPreference << endl; cout << "Link Control: " << pLinkControl << endl << endl; cout << "Link Protection: " << pLinkProtection << endl << endl; } } TEST(AMTEthernetPortSettingsClient, DISABLED_Set1) { Mock_AMT_EthernetPortSettings mock_settings; unsigned int preference = 1; AMT_EthernetPortSettings::SetLinkPreference_INPUT input; input.LinkPreference(preference); ON_CALL(mock_settings, LinkControlExists()).WillByDefault(Return(true)); ON_CALL(mock_settings, LinkPreferenceExists()).WillByDefault(Return(true)); ON_CALL(mock_settings, LinkControl()).WillByDefault(Return(1)); ON_CALL(mock_settings, LinkPreference()).WillByDefault(Return(1)); //ON_CALL(mock_settings, SetLinkPreference(input)).WillByDefault(Return(1)); AMTEthernetPortSettingsClient client; EXPECT_TRUE(client.SetLinkPreference(1)); unsigned int pLinkPreference; unsigned int pLinkControl; unsigned int pLinkProtection; bool ret = false; EXPECT_TRUE(ret = client.GetAMTEthernetPortSettings(&pLinkPreference, &pLinkControl, &pLinkProtection)); if (ret){ EXPECT_EQ(1, pLinkPreference); EXPECT_EQ(1, pLinkControl); } } TEST(AMTEthernetPortSettingsClient, DISABLED_Set2) { AMTEthernetPortSettingsClient settings; EXPECT_TRUE(settings.SetLinkPreference(2)); unsigned int pLinkPreference; unsigned int pLinkControl; unsigned int pLinkProtection; bool ret = false; EXPECT_TRUE(ret = settings.GetAMTEthernetPortSettings(&pLinkPreference, &pLinkControl, &pLinkProtection)); if (ret){ EXPECT_EQ(2, pLinkPreference); EXPECT_EQ(2, pLinkControl); } } TEST(AMTEthernetPortSettingsClient, DISABLED_SetInvalid) { AMTEthernetPortSettingsClient settings; EXPECT_TRUE(settings.SetLinkPreference(3)); unsigned int pLinkPreference; unsigned int pLinkControl; unsigned int pLinkProtection; bool ret = false; EXPECT_TRUE(ret = settings.GetAMTEthernetPortSettings(&pLinkPreference, &pLinkControl, &pLinkProtection)); if (ret){ EXPECT_NE((unsigned int)3, pLinkPreference); EXPECT_NE((unsigned int)3, pLinkControl); } EXPECT_TRUE(ret = settings.SetLinkPreference(345)); if (ret){ EXPECT_NE((unsigned int)345, pLinkPreference); EXPECT_NE((unsigned int)345, pLinkControl); } } TEST(AMTFCFHWSmanClient, userInitiatedPolicyRule) { AMTFCFHWSmanClient fcfh; short pExist = 0; bool ret = false; EXPECT_TRUE(ret = fcfh.userInitiatedPolicyRuleExists(&pExist)); if (ret){ cout << "Does user initiated policy rule exist: " << ((pExist!=0) ? "Yes" : "No") << endl; } } TEST(AMTFCFHWSmanClient, snmpEventSubscriber) { AMTFCFHWSmanClient fcfh; short pExist = 0; bool ret = false; EXPECT_TRUE(ret = fcfh.snmpEventSubscriberExists(&pExist)); if (ret){ cout << "Does snmp event subscriber exist: " << ((pExist!=0) ? "Yes" : "No") << endl; } } TEST(AMTFCFHWSmanClient, CILAFilterCollectionSubscription) { AMTFCFHWSmanClient fcfh; short pExist = 0; bool ret = false; EXPECT_TRUE(ret = fcfh.CILAFilterCollectionSubscriptionExists(&pExist)); if (ret){ cout << "Does CILA filter collection subscription exist: " << ((pExist!=0) ? "Yes" : "No") << endl << endl; } } TEST(AMTRedirectionServiceWSManClient, terminateSession) { AMTRedirectionServiceWSManClient redir; // Session types: // IDER: 0 // SOL: 1 // Reserved: 2 unsigned int sessionType = 0; EXPECT_TRUE(redir.TerminateSession(sessionType)); } TEST(CancelOptInClient, cancelOption) { CancelOptInClient cancelOpt; unsigned int retVal = 0; bool ret = false; EXPECT_TRUE(ret = cancelOpt.CancelOptIn(&retVal)); if (ret){ cout << "Did Cancel option succeed: " << ((retVal!=0) ? "Yes" : "No") << endl; } } TEST(CancelOptInClient, getUserConsentState) { CancelOptInClient cancelOpt; bool ret = false; short state=0, policy=0; EXPECT_TRUE(ret = cancelOpt.GetUserConsentState(&state, &policy)); if (ret){ cout << "User consent state: " << state << endl; cout << "User policy: " << policy << endl << endl; } } TEST(HBPWSManClient, getConfigurationInfo) { HBPWSManClient hbpw; short controlMode=0, provisioningMethod=0; string timeStamp; std::vector<unsigned char> pCertHash; bool ret = false; EXPECT_TRUE(ret = hbpw.GetConfigurationInfo(&controlMode, &provisioningMethod, timeStamp, pCertHash)); if (ret){ cout << "Control mode: " << controlMode << endl; cout << "Provisioning method: " << provisioningMethod << endl; cout << "Time stamp: " << timeStamp << endl; } } TEST(KVMWSManClient, KVMRedirectionState) { KVMWSManClient kvm; unsigned short state = 0; bool ret = false; EXPECT_TRUE(ret = kvm.KVMRedirectionState(&state)); if (ret) { } } TEST(KVMWSManClient, GetMEBxState) { KVMWSManClient kvm; bool ret=false, state=false; EXPECT_TRUE(ret = kvm.GetMEBxState(&state)); if (ret){ cout << "MEBX state: " << state << endl; } } TEST(KVMWSManClient, TerminateKVMSession) { KVMWSManClient kvm; EXPECT_TRUE(kvm.TerminateKVMSession()); } TEST(SIOWSManClient, getSpriteLanguage) { SIOWSManClient sio; unsigned short language=0; bool ret = false; EXPECT_TRUE(ret = sio.GetSpriteLanguage(&language)); if (ret){ cout << "Sprite language is: " << language << endl; } } TEST(SIOWSManClient, setValidSpriteZoom) { SIOWSManClient sio; unsigned short lang2, zoom2 = 0; bool ret = 0; for (unsigned short zoom=1; zoom<=2; zoom++) { EXPECT_TRUE(ret = sio.SetSpriteZoom(zoom)); if (ret) { EXPECT_TRUE(ret = sio.GetSpriteParameters(&lang2, &zoom2)); if (ret) { EXPECT_EQ(zoom, zoom2); } } } } TEST(SIOWSManClient, setInvalidSpriteZoom) { SIOWSManClient sio; EXPECT_FALSE(sio.SetSpriteZoom(100)); } TEST(SIOWSManClient, getSpriteParameters) { SIOWSManClient sio; unsigned short language, zoom, lang2; bool ret = false; EXPECT_TRUE(ret = sio.GetSpriteLanguage(&language)); EXPECT_TRUE(sio.GetSpriteParameters(&lang2, &zoom)); EXPECT_EQ(lang2, language); } TEST(SyncIpClient, GetSharedStaticIpState) { SyncIpClient syncIP; bool SharedStaticIpState = false; bool ret = false; EXPECT_TRUE(ret = syncIP.GetSharedStaticIpState(&SharedStaticIpState)); if (ret){ cout << "Shared static IP state: " << ((SharedStaticIpState==true) ? "Enabled" : "Disabled") << endl; } } TEST(SyncIpClient, GetNetworkData) { SyncIpClient syncIP; bool ret=false, DHCPEnabled=false; string IPAddress, subnet, gateway, dnsAddress1, dnsAddress2; EXPECT_TRUE(ret = syncIP.GetNetworkData(DHCPEnabled, IPAddress, subnet, gateway, dnsAddress1, dnsAddress2)); if (ret){ cout << "Type of IP: " << "\t" << ((DHCPEnabled==true) ? "DHCP" : "Static") << endl; cout << "IP address: " << "\t" << ((IPAddress.compare("")==0) ? "N/A" : IPAddress) << endl; cout << "Subnet: " << "\t" << ((subnet.compare("")==0) ? "N/A" : subnet) << endl; cout << "Gateway: " << "\t" << ((gateway.compare("")==0) ? "N/A" : gateway) << endl; cout << "DNS Address 1: " << "\t" << ((dnsAddress1.compare("")==0) ? "N/A" : dnsAddress1) << endl; cout << "DNS Address 2: " << "\t" << ((dnsAddress2.compare("")==0) ? "N/A" : dnsAddress2) << endl; } } /*TEST(SyncIpClient, SetNetworkData) { SyncIpClient syncIP; bool ret, DHCPEnabled; string IPAddress, subnet, gateway, dnsAddress1, dnsAddress2; // TODO: find inputs that will work // Static --> DHCP DHCP enabled (true\1) // Static --> Static true, 100.100.100.100, 255.255.255.0 100.100.100.3 11.11.11.11 22.22.22.22 // DHSP --> Static true, 100.100.100.100, 255.255.255.0 100.100.100.3 11.11.11.11 0.0.0.0 //EXPECT_FALSE(syncIP.SetNetworkData(DHCPEnabled, IPAddress, subnet, gateway, dnsAddress1, dnsAddress2)); }*/ void printTime(unsigned int time) { time_t rawtime(time); cout << "Time is: " << ctime(&rawtime); } TEST(TimeSynchronizationClient, getTime) { TimeSynchronizationClient timeClient; unsigned int time; timeClient.GetAMTTime(time); printTime(time); } TEST(TimeSynchronizationClient, setTime) { TimeSynchronizationClient timeClient; unsigned int AMTTime, LastAMTTime; ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); cout << "Current time: \t\t" << AMTTime << endl; cout << "Setting back 100 seconds..." << endl; AMTTime -= 100; LastAMTTime = AMTTime; cout << "Time should be: \t" << AMTTime << endl; ASSERT_TRUE(timeClient.SetAMTTime(AMTTime)); ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); ASSERT_TRUE(timeClient.SetAMTTime(AMTTime)); cout << "Time is now: \t\t" << AMTTime << endl; ASSERT_TRUE(AMTTime-LastAMTTime<=1); cout << "Setting forward 100 seconds..." << endl; AMTTime += 100; LastAMTTime = AMTTime; cout << "Time should be: \t" << AMTTime << endl; ASSERT_TRUE(timeClient.SetAMTTime(AMTTime)); ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); cout << "Time is now: \t\t" << AMTTime << endl; ASSERT_TRUE(AMTTime-LastAMTTime<=1); } //Syncs FW time to local time TEST(TimeSynchronizationClient, syncLocalTime) { TimeSynchronizationClient timeClient; unsigned int AMTTime, LastAMTTime; ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); cout << "Current time: \t\t" << AMTTime << endl; cout << "Sync time..." << endl; time_t rawtime; rawtime = time(NULL); cout << "Local time: " << rawtime << endl; printTime(rawtime); AMTTime = (unsigned int)rawtime; LastAMTTime = AMTTime; ASSERT_TRUE(timeClient.SetAMTTime(AMTTime)); ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); ASSERT_TRUE(AMTTime-LastAMTTime<=1); cout << "New time: \t\t" << AMTTime << endl; printTime(AMTTime); } //Syncs FW time to UTC time TEST(TimeSynchronizationClient, syncUTCTime) { TimeSynchronizationClient timeClient; unsigned int AMTTime, UTCTime; ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); cout << "FW time: \t"; printTime(AMTTime); time_t rawtime; struct tm* tmpTime; time(&rawtime); ASSERT_NE(rawtime, -1); tmpTime = gmtime(&rawtime); UTCTime = mktime(tmpTime); cout << "UTC time: \t"; printTime(UTCTime); int diff = UTCTime-AMTTime; if (abs(diff)>30) { cout << "Difference is more than 30 seconds, sync will be performed" << endl; ASSERT_TRUE(timeClient.SetAMTTime(UTCTime)); ASSERT_TRUE(timeClient.GetAMTTime(AMTTime)); cout << "New FW time: "; printTime(AMTTime); } } TEST(TimeSynchronizationClient, getEnabledState) { TimeSynchronizationClient timeClient; bool state; ASSERT_TRUE(timeClient.GetLocalTimeSyncEnabledState(state)); cout << "Local time sync enabled state is: " << state << endl; } int main(int argc, char** argv) { /* //Add this code for filtering tests argc = 2; argv[1] = "--gtest_filter=*-*AMTEthernetPortSettingsClient*"; */ testing::InitGoogleMock(&argc, argv); //getchar(); // keep console window open until Return keystroke return RUN_ALL_TESTS(); }
// Copyright (c) 2009, V. Lepetit, EPFL // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this // list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // THIS SOFTWARE IS PROVIDED BY THE 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. // The views and conclusions contained in the software and documentation are // those // of the authors and should not be interpreted as representing official // policies, // either expressed or implied, of the FreeBSD Project. #include <iostream> using namespace std; #include "../include/epnp.h" namespace fato { PNPSolver::PNPSolver(void) { maximum_number_of_correspondences = 0; number_of_correspondences = 0; pws = 0; us = 0; alphas = 0; pcs = 0; } PNPSolver::~PNPSolver() { delete[] pws; delete[] us; delete[] alphas; delete[] pcs; } void PNPSolver::set_internal_parameters(double uc, double vc, double fu, double fv) { this->uc = uc; this->vc = vc; this->fu = fu; this->fv = fv; } void PNPSolver::setCorrespondences(std::vector<cv::Point3f>& model_pts, std::vector<cv::Point2f>& img_pts) { model_pts_ = model_pts; img_pts_ = img_pts; available_idx_.resize(model_pts_.size(), 0); for (auto i = 0; i < available_idx_.size(); ++i) { available_idx_.at(i) = i; } } void PNPSolver::solvePnP(int iterations, int min_inliers, double error, std::vector<int>& inliers) { auto curr_iter = 0; std::mt19937 mt(random_device_()); min_err_ = numeric_limits<double>::max(); max_inliers_ = 0; max_error_ = error; rotation_ = cv::Mat(3, 3, CV_64FC1, 0.0f); translation_ = cv::Mat(1, 3, CV_64FC1, 0.0f); set_maximum_number_of_correspondences(min_inliers); while (curr_iter < iterations) { std::shuffle(available_idx_.begin(), available_idx_.end(), mt); reset_correspondences(); // creating ransac correspondences for (auto i = 0; i < min_inliers; ++i) { // picking a random element in the set const auto& id = available_idx_.at(i); const cv::Point3d& mpt = model_pts_.at(id); const cv::Point2d& ipt = img_pts_.at(id); add_correspondence(mpt.x, mpt.y, mpt.z, ipt.x, ipt.y); } double R_est[3][3], t_est[3]; double err2 = compute_pose(R_est, t_est); vector<int> tmp_inliers; checkInliers(R_est, t_est, tmp_inliers); if (err2 < min_err_ & max_inliers_ <= inliers.size()) { min_err_ = err2; max_inliers_ = tmp_inliers.size(); inliers = tmp_inliers; for(auto i = 0 ; i < 3; ++i) { for(auto j = 0; j < 3; ++j) { rotation_.at<double>(i,j) = R_est[i][j]; } translation_.at<double>(i) = t_est[i]; } } curr_iter++; } // cout << "reprojection error: " << min_err_ << " inliers " << max_inliers_ // << endl; } void PNPSolver::set_maximum_number_of_correspondences(int n) { if (maximum_number_of_correspondences < n) { if (pws != 0) delete[] pws; if (us != 0) delete[] us; if (alphas != 0) delete[] alphas; if (pcs != 0) delete[] pcs; maximum_number_of_correspondences = n; pws = new double[3 * maximum_number_of_correspondences]; us = new double[2 * maximum_number_of_correspondences]; alphas = new double[4 * maximum_number_of_correspondences]; pcs = new double[3 * maximum_number_of_correspondences]; } } void PNPSolver::reset_correspondences(void) { number_of_correspondences = 0; } void PNPSolver::add_correspondence(double X, double Y, double Z, double u, double v) { pws[3 * number_of_correspondences] = X; pws[3 * number_of_correspondences + 1] = Y; pws[3 * number_of_correspondences + 2] = Z; us[2 * number_of_correspondences] = u; us[2 * number_of_correspondences + 1] = v; number_of_correspondences++; } void PNPSolver::checkInliers(const double R[3][3], const double T[3], std::vector<int>& inliers) { inliers.reserve(model_pts_.size()); for (int i = 0; i < model_pts_.size(); ++i) { const cv::Point3d& mpt = model_pts_.at(i); const cv::Point2d& ipt = img_pts_.at(i); double Xc = R[0][0] * mpt.x + R[0][1] * mpt.y + R[0][2] * mpt.z + T[0]; double Yc = R[1][0] * mpt.x + R[1][1] * mpt.y + R[1][2] * mpt.z + T[1]; double invZc = 1 / (R[2][0] * mpt.x + R[2][1] * mpt.y + R[2][2] * mpt.z + T[2]); double ue = uc + fu * Xc * invZc; double ve = vc + fv * Yc * invZc; double distX = ipt.x - ue; double distY = ipt.y - ve; double error2 = sqrt(distX * distX + distY * distY); if (error2 < max_error_) { inliers.push_back(i); } } } void PNPSolver::choose_control_points(void) { // Take C0 as the reference points centroid: cws[0][0] = cws[0][1] = cws[0][2] = 0; for (int i = 0; i < number_of_correspondences; i++) for (int j = 0; j < 3; j++) cws[0][j] += pws[3 * i + j]; for (int j = 0; j < 3; j++) cws[0][j] /= number_of_correspondences; // Take C1, C2, and C3 from PCA on the reference points: CvMat* PW0 = cvCreateMat(number_of_correspondences, 3, CV_64F); double pw0tpw0[3 * 3], dc[3], uct[3 * 3]; CvMat PW0tPW0 = cvMat(3, 3, CV_64F, pw0tpw0); CvMat DC = cvMat(3, 1, CV_64F, dc); CvMat UCt = cvMat(3, 3, CV_64F, uct); for (int i = 0; i < number_of_correspondences; i++) for (int j = 0; j < 3; j++) PW0->data.db[3 * i + j] = pws[3 * i + j] - cws[0][j]; cvMulTransposed(PW0, &PW0tPW0, 1); cvSVD(&PW0tPW0, &DC, &UCt, 0, CV_SVD_MODIFY_A | CV_SVD_U_T); cvReleaseMat(&PW0); for (int i = 1; i < 4; i++) { double k = sqrt(dc[i - 1] / number_of_correspondences); for (int j = 0; j < 3; j++) cws[i][j] = cws[0][j] + k * uct[3 * (i - 1) + j]; } } void PNPSolver::compute_barycentric_coordinates(void) { double cc[3 * 3], cc_inv[3 * 3]; CvMat CC = cvMat(3, 3, CV_64F, cc); CvMat CC_inv = cvMat(3, 3, CV_64F, cc_inv); for (int i = 0; i < 3; i++) for (int j = 1; j < 4; j++) cc[3 * i + j - 1] = cws[j][i] - cws[0][i]; cvInvert(&CC, &CC_inv, CV_SVD); double* ci = cc_inv; for (int i = 0; i < number_of_correspondences; i++) { double* pi = pws + 3 * i; double* a = alphas + 4 * i; for (int j = 0; j < 3; j++) a[1 + j] = ci[3 * j] * (pi[0] - cws[0][0]) + ci[3 * j + 1] * (pi[1] - cws[0][1]) + ci[3 * j + 2] * (pi[2] - cws[0][2]); a[0] = 1.0f - a[1] - a[2] - a[3]; } } void PNPSolver::fill_M(CvMat* M, const int row, const double* as, const double u, const double v) { double* M1 = M->data.db + row * 12; double* M2 = M1 + 12; for (int i = 0; i < 4; i++) { M1[3 * i] = as[i] * fu; M1[3 * i + 1] = 0.0; M1[3 * i + 2] = as[i] * (uc - u); M2[3 * i] = 0.0; M2[3 * i + 1] = as[i] * fv; M2[3 * i + 2] = as[i] * (vc - v); } } void PNPSolver::compute_ccs(const double* betas, const double* ut) { for (int i = 0; i < 4; i++) ccs[i][0] = ccs[i][1] = ccs[i][2] = 0.0f; for (int i = 0; i < 4; i++) { const double* v = ut + 12 * (11 - i); for (int j = 0; j < 4; j++) for (int k = 0; k < 3; k++) ccs[j][k] += betas[i] * v[3 * j + k]; } } void PNPSolver::compute_pcs(void) { for (int i = 0; i < number_of_correspondences; i++) { double* a = alphas + 4 * i; double* pc = pcs + 3 * i; for (int j = 0; j < 3; j++) pc[j] = a[0] * ccs[0][j] + a[1] * ccs[1][j] + a[2] * ccs[2][j] + a[3] * ccs[3][j]; } } double PNPSolver::compute_pose(double R[3][3], double t[3]) { choose_control_points(); compute_barycentric_coordinates(); CvMat* M = cvCreateMat(2 * number_of_correspondences, 12, CV_64F); for (int i = 0; i < number_of_correspondences; i++) fill_M(M, 2 * i, alphas + 4 * i, us[2 * i], us[2 * i + 1]); double mtm[12 * 12], d[12], ut[12 * 12]; CvMat MtM = cvMat(12, 12, CV_64F, mtm); CvMat D = cvMat(12, 1, CV_64F, d); CvMat Ut = cvMat(12, 12, CV_64F, ut); cvMulTransposed(M, &MtM, 1); cvSVD(&MtM, &D, &Ut, 0, CV_SVD_MODIFY_A | CV_SVD_U_T); cvReleaseMat(&M); double l_6x10[6 * 10], rho[6]; CvMat L_6x10 = cvMat(6, 10, CV_64F, l_6x10); CvMat Rho = cvMat(6, 1, CV_64F, rho); compute_L_6x10(ut, l_6x10); compute_rho(rho); double Betas[4][4], rep_errors[4]; double Rs[4][3][3], ts[4][3]; find_betas_approx_1(&L_6x10, &Rho, Betas[1]); gauss_newton(&L_6x10, &Rho, Betas[1]); rep_errors[1] = compute_R_and_t(ut, Betas[1], Rs[1], ts[1]); find_betas_approx_2(&L_6x10, &Rho, Betas[2]); gauss_newton(&L_6x10, &Rho, Betas[2]); rep_errors[2] = compute_R_and_t(ut, Betas[2], Rs[2], ts[2]); find_betas_approx_3(&L_6x10, &Rho, Betas[3]); gauss_newton(&L_6x10, &Rho, Betas[3]); rep_errors[3] = compute_R_and_t(ut, Betas[3], Rs[3], ts[3]); int N = 1; if (rep_errors[2] < rep_errors[1]) N = 2; if (rep_errors[3] < rep_errors[N]) N = 3; copy_R_and_t(Rs[N], ts[N], R, t); return rep_errors[N]; } void PNPSolver::copy_R_and_t(const double R_src[3][3], const double t_src[3], double R_dst[3][3], double t_dst[3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) R_dst[i][j] = R_src[i][j]; t_dst[i] = t_src[i]; } } double PNPSolver::dist2(const double* p1, const double* p2) { return (p1[0] - p2[0]) * (p1[0] - p2[0]) + (p1[1] - p2[1]) * (p1[1] - p2[1]) + (p1[2] - p2[2]) * (p1[2] - p2[2]); } double PNPSolver::dot(const double* v1, const double* v2) { return v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]; } double PNPSolver::reprojection_error(const double R[3][3], const double t[3]) { double sum2 = 0.0; for (int i = 0; i < number_of_correspondences; i++) { double* pw = pws + 3 * i; double Xc = dot(R[0], pw) + t[0]; double Yc = dot(R[1], pw) + t[1]; double inv_Zc = 1.0 / (dot(R[2], pw) + t[2]); double ue = uc + fu * Xc * inv_Zc; double ve = vc + fv * Yc * inv_Zc; double u = us[2 * i], v = us[2 * i + 1]; sum2 += sqrt((u - ue) * (u - ue) + (v - ve) * (v - ve)); } return sum2 / number_of_correspondences; } void PNPSolver::getPose(cv::Mat &R, cv::Mat &t) { R = rotation_.clone(); t = translation_.clone(); } void PNPSolver::estimate_R_and_t(double R[3][3], double t[3]) { double pc0[3], pw0[3]; pc0[0] = pc0[1] = pc0[2] = 0.0; pw0[0] = pw0[1] = pw0[2] = 0.0; for (int i = 0; i < number_of_correspondences; i++) { const double* pc = pcs + 3 * i; const double* pw = pws + 3 * i; for (int j = 0; j < 3; j++) { pc0[j] += pc[j]; pw0[j] += pw[j]; } } for (int j = 0; j < 3; j++) { pc0[j] /= number_of_correspondences; pw0[j] /= number_of_correspondences; } double abt[3 * 3], abt_d[3], abt_u[3 * 3], abt_v[3 * 3]; CvMat ABt = cvMat(3, 3, CV_64F, abt); CvMat ABt_D = cvMat(3, 1, CV_64F, abt_d); CvMat ABt_U = cvMat(3, 3, CV_64F, abt_u); CvMat ABt_V = cvMat(3, 3, CV_64F, abt_v); cvSetZero(&ABt); for (int i = 0; i < number_of_correspondences; i++) { double* pc = pcs + 3 * i; double* pw = pws + 3 * i; for (int j = 0; j < 3; j++) { abt[3 * j] += (pc[j] - pc0[j]) * (pw[0] - pw0[0]); abt[3 * j + 1] += (pc[j] - pc0[j]) * (pw[1] - pw0[1]); abt[3 * j + 2] += (pc[j] - pc0[j]) * (pw[2] - pw0[2]); } } cvSVD(&ABt, &ABt_D, &ABt_U, &ABt_V, CV_SVD_MODIFY_A); for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) R[i][j] = dot(abt_u + 3 * i, abt_v + 3 * j); const double det = R[0][0] * R[1][1] * R[2][2] + R[0][1] * R[1][2] * R[2][0] + R[0][2] * R[1][0] * R[2][1] - R[0][2] * R[1][1] * R[2][0] - R[0][1] * R[1][0] * R[2][2] - R[0][0] * R[1][2] * R[2][1]; if (det < 0) { R[2][0] = -R[2][0]; R[2][1] = -R[2][1]; R[2][2] = -R[2][2]; } t[0] = pc0[0] - dot(R[0], pw0); t[1] = pc0[1] - dot(R[1], pw0); t[2] = pc0[2] - dot(R[2], pw0); } void PNPSolver::print_pose(const double R[3][3], const double t[3]) { cout << R[0][0] << " " << R[0][1] << " " << R[0][2] << " " << t[0] << endl; cout << R[1][0] << " " << R[1][1] << " " << R[1][2] << " " << t[1] << endl; cout << R[2][0] << " " << R[2][1] << " " << R[2][2] << " " << t[2] << endl; } void PNPSolver::solve_for_sign(void) { if (pcs[2] < 0.0) { for (int i = 0; i < 4; i++) for (int j = 0; j < 3; j++) ccs[i][j] = -ccs[i][j]; for (int i = 0; i < number_of_correspondences; i++) { pcs[3 * i] = -pcs[3 * i]; pcs[3 * i + 1] = -pcs[3 * i + 1]; pcs[3 * i + 2] = -pcs[3 * i + 2]; } } } double PNPSolver::compute_R_and_t(const double* ut, const double* betas, double R[3][3], double t[3]) { compute_ccs(betas, ut); compute_pcs(); solve_for_sign(); estimate_R_and_t(R, t); return reprojection_error(R, t); } // betas10 = [B11 B12 B22 B13 B23 B33 B14 B24 B34 B44] // betas_approx_1 = [B11 B12 B13 B14] void PNPSolver::find_betas_approx_1(const CvMat* L_6x10, const CvMat* Rho, double* betas) { double l_6x4[6 * 4], b4[4]; CvMat L_6x4 = cvMat(6, 4, CV_64F, l_6x4); CvMat B4 = cvMat(4, 1, CV_64F, b4); for (int i = 0; i < 6; i++) { cvmSet(&L_6x4, i, 0, cvmGet(L_6x10, i, 0)); cvmSet(&L_6x4, i, 1, cvmGet(L_6x10, i, 1)); cvmSet(&L_6x4, i, 2, cvmGet(L_6x10, i, 3)); cvmSet(&L_6x4, i, 3, cvmGet(L_6x10, i, 6)); } cvSolve(&L_6x4, Rho, &B4, CV_SVD); if (b4[0] < 0) { betas[0] = sqrt(-b4[0]); betas[1] = -b4[1] / betas[0]; betas[2] = -b4[2] / betas[0]; betas[3] = -b4[3] / betas[0]; } else { betas[0] = sqrt(b4[0]); betas[1] = b4[1] / betas[0]; betas[2] = b4[2] / betas[0]; betas[3] = b4[3] / betas[0]; } } // betas10 = [B11 B12 B22 B13 B23 B33 B14 B24 B34 B44] // betas_approx_2 = [B11 B12 B22 ] void PNPSolver::find_betas_approx_2(const CvMat* L_6x10, const CvMat* Rho, double* betas) { double l_6x3[6 * 3], b3[3]; CvMat L_6x3 = cvMat(6, 3, CV_64F, l_6x3); CvMat B3 = cvMat(3, 1, CV_64F, b3); for (int i = 0; i < 6; i++) { cvmSet(&L_6x3, i, 0, cvmGet(L_6x10, i, 0)); cvmSet(&L_6x3, i, 1, cvmGet(L_6x10, i, 1)); cvmSet(&L_6x3, i, 2, cvmGet(L_6x10, i, 2)); } cvSolve(&L_6x3, Rho, &B3, CV_SVD); if (b3[0] < 0) { betas[0] = sqrt(-b3[0]); betas[1] = (b3[2] < 0) ? sqrt(-b3[2]) : 0.0; } else { betas[0] = sqrt(b3[0]); betas[1] = (b3[2] > 0) ? sqrt(b3[2]) : 0.0; } if (b3[1] < 0) betas[0] = -betas[0]; betas[2] = 0.0; betas[3] = 0.0; } // betas10 = [B11 B12 B22 B13 B23 B33 B14 B24 B34 B44] // betas_approx_3 = [B11 B12 B22 B13 B23 ] void PNPSolver::find_betas_approx_3(const CvMat* L_6x10, const CvMat* Rho, double* betas) { double l_6x5[6 * 5], b5[5]; CvMat L_6x5 = cvMat(6, 5, CV_64F, l_6x5); CvMat B5 = cvMat(5, 1, CV_64F, b5); for (int i = 0; i < 6; i++) { cvmSet(&L_6x5, i, 0, cvmGet(L_6x10, i, 0)); cvmSet(&L_6x5, i, 1, cvmGet(L_6x10, i, 1)); cvmSet(&L_6x5, i, 2, cvmGet(L_6x10, i, 2)); cvmSet(&L_6x5, i, 3, cvmGet(L_6x10, i, 3)); cvmSet(&L_6x5, i, 4, cvmGet(L_6x10, i, 4)); } cvSolve(&L_6x5, Rho, &B5, CV_SVD); if (b5[0] < 0) { betas[0] = sqrt(-b5[0]); betas[1] = (b5[2] < 0) ? sqrt(-b5[2]) : 0.0; } else { betas[0] = sqrt(b5[0]); betas[1] = (b5[2] > 0) ? sqrt(b5[2]) : 0.0; } if (b5[1] < 0) betas[0] = -betas[0]; betas[2] = b5[3] / betas[0]; betas[3] = 0.0; } void PNPSolver::compute_L_6x10(const double* ut, double* l_6x10) { const double* v[4]; v[0] = ut + 12 * 11; v[1] = ut + 12 * 10; v[2] = ut + 12 * 9; v[3] = ut + 12 * 8; double dv[4][6][3]; for (int i = 0; i < 4; i++) { int a = 0, b = 1; for (int j = 0; j < 6; j++) { dv[i][j][0] = v[i][3 * a] - v[i][3 * b]; dv[i][j][1] = v[i][3 * a + 1] - v[i][3 * b + 1]; dv[i][j][2] = v[i][3 * a + 2] - v[i][3 * b + 2]; b++; if (b > 3) { a++; b = a + 1; } } } for (int i = 0; i < 6; i++) { double* row = l_6x10 + 10 * i; row[0] = dot(dv[0][i], dv[0][i]); row[1] = 2.0f * dot(dv[0][i], dv[1][i]); row[2] = dot(dv[1][i], dv[1][i]); row[3] = 2.0f * dot(dv[0][i], dv[2][i]); row[4] = 2.0f * dot(dv[1][i], dv[2][i]); row[5] = dot(dv[2][i], dv[2][i]); row[6] = 2.0f * dot(dv[0][i], dv[3][i]); row[7] = 2.0f * dot(dv[1][i], dv[3][i]); row[8] = 2.0f * dot(dv[2][i], dv[3][i]); row[9] = dot(dv[3][i], dv[3][i]); } } void PNPSolver::compute_rho(double* rho) { rho[0] = dist2(cws[0], cws[1]); rho[1] = dist2(cws[0], cws[2]); rho[2] = dist2(cws[0], cws[3]); rho[3] = dist2(cws[1], cws[2]); rho[4] = dist2(cws[1], cws[3]); rho[5] = dist2(cws[2], cws[3]); } void PNPSolver::compute_A_and_b_gauss_newton(const double* l_6x10, const double* rho, double betas[4], CvMat* A, CvMat* b) { for (int i = 0; i < 6; i++) { const double* rowL = l_6x10 + i * 10; double* rowA = A->data.db + i * 4; rowA[0] = 2 * rowL[0] * betas[0] + rowL[1] * betas[1] + rowL[3] * betas[2] + rowL[6] * betas[3]; rowA[1] = rowL[1] * betas[0] + 2 * rowL[2] * betas[1] + rowL[4] * betas[2] + rowL[7] * betas[3]; rowA[2] = rowL[3] * betas[0] + rowL[4] * betas[1] + 2 * rowL[5] * betas[2] + rowL[8] * betas[3]; rowA[3] = rowL[6] * betas[0] + rowL[7] * betas[1] + rowL[8] * betas[2] + 2 * rowL[9] * betas[3]; cvmSet(b, i, 0, rho[i] - (rowL[0] * betas[0] * betas[0] + rowL[1] * betas[0] * betas[1] + rowL[2] * betas[1] * betas[1] + rowL[3] * betas[0] * betas[2] + rowL[4] * betas[1] * betas[2] + rowL[5] * betas[2] * betas[2] + rowL[6] * betas[0] * betas[3] + rowL[7] * betas[1] * betas[3] + rowL[8] * betas[2] * betas[3] + rowL[9] * betas[3] * betas[3])); } } void PNPSolver::gauss_newton(const CvMat* L_6x10, const CvMat* Rho, double betas[4]) { const int iterations_number = 5; double a[6 * 4], b[6], x[4]; CvMat A = cvMat(6, 4, CV_64F, a); CvMat B = cvMat(6, 1, CV_64F, b); CvMat X = cvMat(4, 1, CV_64F, x); for (int k = 0; k < iterations_number; k++) { compute_A_and_b_gauss_newton(L_6x10->data.db, Rho->data.db, betas, &A, &B); qr_solve(&A, &B, &X); for (int i = 0; i < 4; i++) betas[i] += x[i]; } } void PNPSolver::qr_solve(CvMat* A, CvMat* b, CvMat* X) { static int max_nr = 0; static double* A1, *A2; const int nr = A->rows; const int nc = A->cols; if (max_nr != 0 && max_nr < nr) { delete[] A1; delete[] A2; } if (max_nr < nr) { max_nr = nr; A1 = new double[nr]; A2 = new double[nr]; } double* pA = A->data.db, *ppAkk = pA; for (int k = 0; k < nc; k++) { double* ppAik = ppAkk, eta = fabs(*ppAik); for (int i = k + 1; i < nr; i++) { double elt = fabs(*ppAik); if (eta < elt) eta = elt; ppAik += nc; } if (eta == 0) { A1[k] = A2[k] = 0.0; cerr << "God damnit, A is singular, this shouldn't happen." << endl; return; } else { double* ppAik = ppAkk, sum = 0.0, inv_eta = 1. / eta; for (int i = k; i < nr; i++) { *ppAik *= inv_eta; sum += *ppAik * *ppAik; ppAik += nc; } double sigma = sqrt(sum); if (*ppAkk < 0) sigma = -sigma; *ppAkk += sigma; A1[k] = sigma * *ppAkk; A2[k] = -eta * sigma; for (int j = k + 1; j < nc; j++) { double* ppAik = ppAkk, sum = 0; for (int i = k; i < nr; i++) { sum += *ppAik * ppAik[j - k]; ppAik += nc; } double tau = sum / A1[k]; ppAik = ppAkk; for (int i = k; i < nr; i++) { ppAik[j - k] -= tau * *ppAik; ppAik += nc; } } } ppAkk += nc + 1; } // b <- Qt b double* ppAjj = pA, *pb = b->data.db; for (int j = 0; j < nc; j++) { double* ppAij = ppAjj, tau = 0; for (int i = j; i < nr; i++) { tau += *ppAij * pb[i]; ppAij += nc; } tau /= A1[j]; ppAij = ppAjj; for (int i = j; i < nr; i++) { pb[i] -= tau * *ppAij; ppAij += nc; } ppAjj += nc + 1; } // X = R-1 b double* pX = X->data.db; pX[nc - 1] = pb[nc - 1] / A2[nc - 1]; for (int i = nc - 2; i >= 0; i--) { double* ppAij = pA + i * nc + (i + 1), sum = 0; for (int j = i + 1; j < nc; j++) { sum += *ppAij * pX[j]; ppAij++; } pX[i] = (pb[i] - sum) / A2[i]; } } void PNPSolver::relative_error(double& rot_err, double& transl_err, const double Rtrue[3][3], const double ttrue[3], const double Rest[3][3], const double test[3]) { double qtrue[4], qest[4]; mat_to_quat(Rtrue, qtrue); mat_to_quat(Rest, qest); double rot_err1 = sqrt((qtrue[0] - qest[0]) * (qtrue[0] - qest[0]) + (qtrue[1] - qest[1]) * (qtrue[1] - qest[1]) + (qtrue[2] - qest[2]) * (qtrue[2] - qest[2]) + (qtrue[3] - qest[3]) * (qtrue[3] - qest[3])) / sqrt(qtrue[0] * qtrue[0] + qtrue[1] * qtrue[1] + qtrue[2] * qtrue[2] + qtrue[3] * qtrue[3]); double rot_err2 = sqrt((qtrue[0] + qest[0]) * (qtrue[0] + qest[0]) + (qtrue[1] + qest[1]) * (qtrue[1] + qest[1]) + (qtrue[2] + qest[2]) * (qtrue[2] + qest[2]) + (qtrue[3] + qest[3]) * (qtrue[3] + qest[3])) / sqrt(qtrue[0] * qtrue[0] + qtrue[1] * qtrue[1] + qtrue[2] * qtrue[2] + qtrue[3] * qtrue[3]); rot_err = min(rot_err1, rot_err2); transl_err = sqrt((ttrue[0] - test[0]) * (ttrue[0] - test[0]) + (ttrue[1] - test[1]) * (ttrue[1] - test[1]) + (ttrue[2] - test[2]) * (ttrue[2] - test[2])) / sqrt(ttrue[0] * ttrue[0] + ttrue[1] * ttrue[1] + ttrue[2] * ttrue[2]); } void PNPSolver::mat_to_quat(const double R[3][3], double q[4]) { double tr = R[0][0] + R[1][1] + R[2][2]; double n4; if (tr > 0.0f) { q[0] = R[1][2] - R[2][1]; q[1] = R[2][0] - R[0][2]; q[2] = R[0][1] - R[1][0]; q[3] = tr + 1.0f; n4 = q[3]; } else if ((R[0][0] > R[1][1]) && (R[0][0] > R[2][2])) { q[0] = 1.0f + R[0][0] - R[1][1] - R[2][2]; q[1] = R[1][0] + R[0][1]; q[2] = R[2][0] + R[0][2]; q[3] = R[1][2] - R[2][1]; n4 = q[0]; } else if (R[1][1] > R[2][2]) { q[0] = R[1][0] + R[0][1]; q[1] = 1.0f + R[1][1] - R[0][0] - R[2][2]; q[2] = R[2][1] + R[1][2]; q[3] = R[2][0] - R[0][2]; n4 = q[1]; } else { q[0] = R[2][0] + R[0][2]; q[1] = R[2][1] + R[1][2]; q[2] = 1.0f + R[2][2] - R[0][0] - R[1][1]; q[3] = R[0][1] - R[1][0]; n4 = q[2]; } double scale = 0.5f / double(sqrt(n4)); q[0] *= scale; q[1] *= scale; q[2] *= scale; q[3] *= scale; } } // end namespace
// stdafx.cpp : source file that includes just the standard includes // MMI.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h"
// Copyright (C) <2019> Intel Corporation // // SPDX-License-Identifier: Apache-2.0 #include "WebRtcConnection.h" #include "ThreadPool.h" #include "IOThreadPool.h" #include "MediaStream.h" #include <node.h> using namespace v8; void InitAll(Handle<Object> exports) { WebRtcConnection::Init(exports); MediaStream::Init(exports); ThreadPool::Init(exports); IOThreadPool::Init(exports); } NODE_MODULE(addon, InitAll)
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2015 Jean-David Gadina - www.xs-labs.com / www.digidna.net * * 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. ******************************************************************************/ /*! * @copyright (c) 2015 - Jean-David Gadina - www.xs-labs.com / www.digidna.net * @brief ... */ #ifndef OBJCXX_FOUNDATION_CLASSES_NS_USER_NOTIFICATION_CENTER_H #define OBJCXX_FOUNDATION_CLASSES_NS_USER_NOTIFICATION_CENTER_H #include <OBJCXX/Foundation/Classes/NSObject.hpp> namespace NS { class OBJCXX_EXPORT UserNotificationCenter: public Object { public: OBJCXX_USING_BASE( UserNotificationCenter, Object ) UserNotificationCenter( void ); }; } #endif /* OBJCXX_FOUNDATION_CLASSES_NS_USER_NOTIFICATION_CENTER_H */
/****************************************************************************** * Copyright 2018 Google * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifdef ESP32 // Prevent compilation on Genuino for now #include "CloudIoTCoreMQTTClient.h" #include <time.h> CONFIG_CALLBACK_SIGNATURE = NULL; void callback(char *topic, uint8_t *payload, unsigned int length) { if (configCallback != NULL) { configCallback(payload, length); } } CloudIoTCoreMQTTClient::CloudIoTCoreMQTTClient(CloudIoTCoreDevice *_device, WiFiClientSecure *_client, PubSubClient *_mqttClient) { this->device = _device; this->client = _client; this->mqttClient = _mqttClient; this->mqttClient->setClient(*(this->client)); this->mqttClient->setStream(buffer); } CloudIoTCoreMQTTClient::CloudIoTCoreMQTTClient(CloudIoTCoreDevice *_device) { this->device = _device; this->client = new WiFiClientSecure(); this->mqttClient = new PubSubClient(); this->mqttClient->setClient(*(this->client)); this->mqttClient->setStream(buffer); } CloudIoTCoreMQTTClient::CloudIoTCoreMQTTClient(const char *project_id, const char *location, const char *registry_id, const char *device_id, const char *private_key) { this->device = new CloudIoTCoreDevice( project_id, location, registry_id, device_id, private_key); this->client = new WiFiClientSecure(); this->mqttClient = new PubSubClient(); this->mqttClient->setClient(*(this->client)); this->mqttClient->setStream(buffer); } void CloudIoTCoreMQTTClient::connect() { mqttClient->setServer(GOOGLE_APIS_MQTT_HOST, GOOGLE_APIS_MQTT_PORT); mqttClient->setCallback(callback); this->mqttClient->setStream(buffer); } #ifndef ESP8266 void CloudIoTCoreMQTTClient::connectSecure(const char *root_cert) { this->lastRootCert = root_cert; // For reinitializing WiFiClient later client->setCACert(root_cert); this->connect(); } #endif void CloudIoTCoreMQTTClient::setJwtExpSecs(int jwt_in_secs) { this->jwtExpSeconds = jwt_in_secs; } String CloudIoTCoreMQTTClient::getJWT() { // Refresh credential if it's expired. if (this->mqttIss == 0 || ((time(nullptr) - this->mqttIss) > this->jwtExpSeconds)) { this->mqttIss = time(nullptr); jwt = device->createJWT(this->mqttIss, this->jwtExpSeconds); if(this->debugLog) Serial.println(String("JWT now:\n") + String(jwt)); } return jwt; } int CloudIoTCoreMQTTClient::backoff(bool shouldDelay) { backOffCount++; int currDelay = (backOffCount * backOffCount * minBackoff) + random(minJitter,maxJitter); if (currDelay > maxBackoff) { currDelay = maxBackoff; } if (debugLog) Serial.printf("Waiting: %ld\n", currDelay); if (shouldDelay){ delay(currDelay); } return currDelay; } bool CloudIoTCoreMQTTClient::connected() { return this->mqttClient->connected(); } void CloudIoTCoreMQTTClient::setSkipReinit(bool isSkip){ this->skipReInit = isSkip; } PubSubClient* CloudIoTCoreMQTTClient::getMqttClient(){ return this->mqttClient; } int CloudIoTCoreMQTTClient::mqttConnect() { // For now, will not loop here until connected so that // caller can have control back. if (!client->connected()) { if (debugLog) { Serial.println("MQTT connecting ..."); } String pass = this->getJWT(); const char *user = "unused"; String clientId = device->getClientId(); if (debugLog) { Serial.println(clientId.c_str()); Serial.println(pass.c_str()); } if (mqttClient->connect(clientId.c_str(), user, pass.c_str())) { if (debugLog) { Serial.println("connected"); } backOffCount = 0; lastState = 0; if (configCallback != NULL) { String configTopic = device->getConfigTopic(); mqttClient->setCallback(callback); mqttClient->setStream(buffer); mqttClient->subscribe(configTopic.c_str(), 0); } return 0; // STATE_CONNECTED for client } else { // In case we want to encapsulate destroying client // if (!this->skipReInit) { } backoff(true); lastState = mqttClient->state(); return mqttClient->state(); } } } int CloudIoTCoreMQTTClient::loop() { if (!this->connected()) { this->mqttConnect(); } // TODO: if (lastState == 0) this->mqttClient->loop(); delay(10); return lastState; } void CloudIoTCoreMQTTClient::debugEnable(bool isEnable) { this->debugLog = isEnable; } void CloudIoTCoreMQTTClient::publishTelemetry(String binaryData) { this->publishTelemetry(binaryData.c_str()); } void CloudIoTCoreMQTTClient::publishTelemetry(const char *binaryData) { String topic = device->getEventsTopic(); mqttClient->publish(topic.c_str(), binaryData); } void CloudIoTCoreMQTTClient::publishState(String binaryData) { this->publishState(binaryData.c_str()); } void CloudIoTCoreMQTTClient::publishState(const char *binaryData) { String topic = device->getStateTopic(); mqttClient->publish(topic.c_str(), binaryData); } void CloudIoTCoreMQTTClient::setConfigCallback( CONFIG_CALLBACK_SIGNATURE_PARAM) { configCallback = configCallbackParam; } #endif
/* * File: TaskPort.cpp * * Copyright (C) 2021, Albert Krzymowski * */ #include "TaskPort.h" namespace IA20 { namespace IOT { namespace Tools { /*************************************************************************/ // TaskPort::TaskPort(){ // IA20_TRACER; // } // /*************************************************************************/ // TaskPort::~TaskPort() throw(){ // IA20_TRACER; // } /*************************************************************************/ } } }
#pragma once #include "distconv/base.hpp" #include <cooperative_groups.h> namespace distconv { namespace tensor { enum class HaloTraversalOpGroup {THREAD, WARP, BLOCK}; namespace internal { template <int ND, typename DataType, typename OpType> __global__ typename std::enable_if<OpType::group == HaloTraversalOpGroup::THREAD, void>::type traverse_halo_generic_kernel(DataType *tensor, Array<ND> shape, int dim, Side side, bool inner, int halo_width, size_t num_halo_points, OpType op) { const size_t num_threads = blockDim.x * gridDim.x; const bool fwd_halo = side == Side::RHS; for (size_t packed_offset = threadIdx.x + blockIdx.x * blockDim.x; packed_offset < num_halo_points; packed_offset +=num_threads) { size_t tensor_offset = 0; size_t dim_offset = 1; size_t offset = packed_offset; #pragma unroll for (int i = 0; i < ND; ++i) { int i_dim = i == dim ? halo_width : shape[i]; int idx = offset % i_dim; if (i == dim) { if (fwd_halo) { if (inner) { idx += shape[i] - halo_width * 2; } else { idx += shape[i] - halo_width; } } else { if (inner) { idx += halo_width; } } } tensor_offset += idx * dim_offset; offset /= i_dim; dim_offset *= shape[i]; } op(tensor[tensor_offset], packed_offset); } } template <int ND, typename DataType, typename OpType> __global__ typename std::enable_if<OpType::group == HaloTraversalOpGroup::BLOCK, void>::type traverse_halo_generic_kernel(DataType *tensor, Array<ND> shape, int dim, Side side, bool inner, int halo_width, size_t num_halo_points, OpType op) { // TODO: This should not be called as it is not yet supported. } template <typename DataType, typename OpType> void traverse_halo_generic(DataType *tensor, const Shape &shape, int dim, Side side, bool inner, int halo_width, size_t num_halo_points, OpType op, const int nd, const dim3 &grid_dims, const dim3 &block_dims, cudaStream_t s) { #define CALL_KERNEL(ND) \ traverse_halo_generic_kernel<ND, DataType, OpType> \ <<<grid_dims, block_dims, 0, s>>>( \ tensor, Array<ND>(shape), dim, side, inner, halo_width, \ num_halo_points, op) switch (nd) { case 1: CALL_KERNEL(1); break; case 2: CALL_KERNEL(2); break; case 3: CALL_KERNEL(3); break; case 4: CALL_KERNEL(4); break; case 5: CALL_KERNEL(5); break; case 6: CALL_KERNEL(6); break; default: throw std::exception(); } #undef CALL_KERNEL } // ND: 4, 5 // Traverse halo at dimension 0 template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::THREAD, void>::type traverse_halo_opt_dim0_apply(DataType *tensor, size_t tensor_offset, size_t packed_offset, int x_len, int y_len, int halo_width, OpType op) { for (int y = threadIdx.y; y < y_len; y += blockDim.y) { op(tensor[tensor_offset+y*x_len+threadIdx.x], packed_offset + y * halo_width + threadIdx.x); } } template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::BLOCK, void>::type traverse_halo_opt_dim0_apply(DataType *tensor, size_t tensor_offset, size_t packed_offset, int x_len, int y_len, int halo_width, OpType op) { for (int y = 0; y < y_len; y += blockDim.y) { auto tensor_idx = min(y + threadIdx.y, y_len - 1); op(tensor[tensor_offset+tensor_idx*x_len+threadIdx.x], packed_offset + y * halo_width, threadIdx.y * blockDim.x + threadIdx.x, min(blockDim.y, y_len - y) * blockDim.x); } } template <int ND, typename DataType, typename OpType, bool inner, Side side> __device__ static void traverse_halo_opt_dim0(DataType *tensor, Array<ND> shape, int halo_width, OpType op) { constexpr int dim = 0; auto sample_idx = blockIdx.y; auto ch_offset = ND == 5 ? shape[1] * shape[2]: shape[1]; auto sample_offset = ch_offset * shape[-2]; int packed_halo_idx = threadIdx.x; int halo_idx = threadIdx.x; if (side == Side::RHS) { if (inner) { halo_idx += (int)(shape[dim]) - halo_width * 2; } else { halo_idx += (int)(shape[dim]) - halo_width; } } else { if (inner) { halo_idx += halo_width; } } size_t offset_common = sample_idx * sample_offset + blockIdx.x * ch_offset; ch_offset *= gridDim.x; for (int ch_idx = blockIdx.x; ch_idx < shape[-2]; ch_idx += gridDim.x) { if (ND == 5) { for (int z = 0; z < shape[2]; ++z) { for (int y = threadIdx.y; y < shape[1]; y += blockDim.y) { // TODO #if 0 size_t packed_offset = (offset_common + y) * halo_width + packed_halo_idx; size_t tensor_offset = (offset_common + y) * shape[0] + halo_idx; op(tensor[tensor_offset], packed_offset); #endif } offset_common += shape[1]; } } else { size_t packed_offset = offset_common * halo_width + packed_halo_idx - threadIdx.x; size_t tensor_offset = offset_common * shape[0] + halo_idx - threadIdx.x; traverse_halo_opt_dim0_apply(tensor, tensor_offset, packed_offset, shape[0], shape[1], halo_width, op); } offset_common += ch_offset; } } // ND: 4, 5 // Traverse halo at dimension 1 with a known halo width template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::THREAD, void>::type traverse_halo_opt_dim1_apply(DataType * __restrict__ tensor, size_t tensor_offset, size_t packed_offset, int len, OpType op) { for (int x = threadIdx.x; x < len; x += blockDim.x) { op(tensor[tensor_offset+x], packed_offset + x); } } template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::BLOCK, void>::type traverse_halo_opt_dim1_apply(DataType * __restrict__ tensor, size_t tensor_offset, size_t packed_offset, int len, OpType op) { for (int x = 0; x < len; x += blockDim.x) { // avoid reading beyond array boundary auto tensor_idx = min(x + threadIdx.x, len - 1); op(tensor[tensor_offset+tensor_idx], packed_offset + x, threadIdx.x, min(blockDim.x, len - x)); } } template <typename DataType, typename OpType, int halo_width> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::THREAD, void>::type traverse_halo_opt_dim1_5d_apply(DataType * __restrict__ tensor, size_t tensor_offset_common, size_t packed_offset_common, int x_len, int y_len, int z_len, int halo_tensor_base, OpType op) { packed_offset_common += x_len * threadIdx.y; tensor_offset_common += x_len * y_len * threadIdx.y; for (int y = threadIdx.y; y < z_len; y += blockDim.y) { int z_block_len = min(blockDim.y, z_len - (y - threadIdx.y)); #pragma unroll for (int hw = 0; hw < halo_width; ++hw) { size_t packed_offset = packed_offset_common + x_len * z_block_len * hw; int halo_idx = hw + halo_tensor_base; size_t tensor_offset = tensor_offset_common + x_len * halo_idx; for (int x = threadIdx.x; x < x_len; x += blockDim.x) { op(tensor[tensor_offset+x], packed_offset + x); } } packed_offset_common += halo_width * x_len * blockDim.y; tensor_offset_common += x_len * y_len * blockDim.y; } } template <typename DataType, typename OpType, int halo_width> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::BLOCK, void>::type traverse_halo_opt_dim1_5d_apply(DataType * __restrict__ tensor, size_t tensor_offset_common, size_t packed_offset_common, int x_len, int y_len, int z_len, int halo_tensor_base, OpType op) { // Note that the traversal below assumes that the X dimension is // completely covered by a single thread block, i.e., blockDim.x == x_len. int tid = threadIdx.x + threadIdx.y * blockDim.x; for (int z = 0; z < z_len; z += blockDim.y) { int z_thread = min(z + threadIdx.y, z_len - 1); int z_block_len = min(blockDim.y, z_len - z); #pragma unroll for (int hw = 0; hw < halo_width; ++hw) { size_t packed_offset = packed_offset_common + x_len * z_block_len * hw + z * x_len * halo_width; int halo_idx = hw + halo_tensor_base; size_t tensor_offset = tensor_offset_common + x_len * halo_idx + z_thread * x_len * y_len; for (int x = 0; x < x_len; x += blockDim.x) { // avoid reading beyond array boundary auto x_thread = min(x + threadIdx.x, x_len - 1); op(tensor[tensor_offset+x_thread], packed_offset + x, tid, min(blockDim.x, x_len - x) * z_block_len); } } } } template <int ND, typename DataType, typename OpType, bool inner, Side side, int halo_width> __device__ static void traverse_halo_opt_dim1(DataType * __restrict__ tensor, const Array<ND> &shape, OpType op) { constexpr int dim = 1; auto sample_idx = blockIdx.y; auto ch_offset = ND == 5 ? shape[0] * shape[2]: shape[0]; const auto sample_offset = ch_offset * shape[-2]; int halo_tensor_base = 0; if (side == Side::RHS) { if (inner) { halo_tensor_base += (int)(shape[dim]) - halo_width * 2; } else { halo_tensor_base += (int)(shape[dim]) - halo_width; } } else { if (inner) { halo_tensor_base += halo_width; } } size_t offset_common = sample_idx * sample_offset + blockIdx.x * ch_offset; // The loop below traverses the channel dimension by gridDim.x // blocks, so the channel offset needs to be multiplied by the // number of blocks. ch_offset *= gridDim.x; for (int ch_idx = blockIdx.x; ch_idx < shape[-2]; ch_idx += gridDim.x) { const size_t packed_offset_common = offset_common * halo_width; const size_t tensor_offset_common = offset_common * shape[1]; if (ND == 5) { traverse_halo_opt_dim1_5d_apply<DataType, OpType, halo_width>( tensor, tensor_offset_common, packed_offset_common, shape[0], shape[1], shape[2], halo_tensor_base, op); } else { #pragma unroll for (int hw = 0; hw < halo_width; ++hw) { int halo_idx = hw + halo_tensor_base; size_t packed_offset = packed_offset_common + shape[0] * hw; size_t tensor_offset = tensor_offset_common + shape[0] * halo_idx; traverse_halo_opt_dim1_apply(tensor, tensor_offset, packed_offset, shape[0], op); } } offset_common += ch_offset; } } // ND: 5 // Traverse halo at dimension 1 with a known halo width template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::THREAD, void>::type traverse_halo_opt_dim2_apply(DataType * __restrict__ tensor, size_t tensor_offset_common, size_t packed_offset_common, int x_len, int y_len, OpType op) { for (int y = threadIdx.y; y < y_len; y += blockDim.y) { size_t packed_offset = packed_offset_common + x_len * y; size_t tensor_offset = tensor_offset_common + x_len * y; for (int x = threadIdx.x; x < x_len; x += blockDim.x) { op(tensor[tensor_offset+x], packed_offset + x); } } } template <typename DataType, typename OpType> __device__ static typename std::enable_if<OpType::group == HaloTraversalOpGroup::BLOCK, void>::type traverse_halo_opt_dim2_apply(DataType * __restrict__ tensor, size_t tensor_offset_common, size_t packed_offset_common, int x_len, int y_len, OpType op) { int tid = threadIdx.x + threadIdx.y * blockDim.x; for (int y = 0; y < y_len; y += blockDim.y) { for (int x = 0; x < x_len; x += blockDim.x) { // avoid reading beyond array boundary auto tensor_idx = min(x + threadIdx.x, x_len - 1) + min(y + threadIdx.y, y_len - 1) * x_len; op(tensor[tensor_offset_common+tensor_idx], packed_offset_common + x + y * x_len, tid, min(blockDim.x, x_len - x) * min(blockDim.y, y_len - y)); } } } // ND: 5 // Traverse halo at dimension 1 with a known halo width template <int ND, typename DataType, typename OpType, bool inner, Side side, int halo_width> __device__ static void traverse_halo_opt_dim2(DataType * __restrict__ tensor, const Array<ND> &shape, OpType op) { constexpr int dim = 2; auto sample_idx = blockIdx.y; auto ch_offset = shape[0] * shape[1]; auto sample_offset = ch_offset * shape[-2]; int halo_idx = 0; if (side == Side::RHS) { if (inner) { halo_idx += (int)(shape[dim]) - halo_width * 2; } else { halo_idx += (int)(shape[dim]) - halo_width; } } else { if (inner) { halo_idx += halo_width; } } size_t offset_common = sample_idx * sample_offset + blockIdx.x * ch_offset; ch_offset *= gridDim.x; for (int ch_idx = blockIdx.x; ch_idx < shape[-2]; ch_idx += gridDim.x) { size_t packed_offset_common = offset_common * halo_width; size_t tensor_offset_common = offset_common * shape[2]; tensor_offset_common += shape[0] * shape[1] * halo_idx; #pragma unroll for (int hw = 0; hw < halo_width; ++hw) { traverse_halo_opt_dim2_apply(tensor, tensor_offset_common, packed_offset_common, shape[0], shape[1], op); packed_offset_common += shape[0] * shape[1]; tensor_offset_common += shape[0] * shape[1]; } offset_common += ch_offset; } } template <typename OpType> __device__ static typename std::enable_if<OpType::has_pre_grid, void>::type traverse_halo_pre(OpType op) { if (gridDim.x * gridDim.y * gridDim.z == 1) { if (threadIdx.x == 0 && threadIdx.y == 0) { op.pre(); } __syncthreads(); } else { if (threadIdx.x == 0 && threadIdx.y == 0 && blockIdx.x == 0 && blockIdx.y == 0) { op.pre(); } cooperative_groups::this_grid().sync(); } } template <typename OpType> __device__ static typename std::enable_if<!OpType::has_pre_grid, void>::type traverse_halo_pre(OpType op) {} template <typename OpType> __device__ static typename std::enable_if<OpType::has_post_grid, void>::type traverse_halo_post(OpType op) { if (gridDim.x * gridDim.y * gridDim.z == 1) { __syncthreads(); if (threadIdx.x == 0 && threadIdx.y == 0) { op.post(); } } else { cooperative_groups::this_grid().sync(); if (threadIdx.x == 0 && threadIdx.y == 0 && blockIdx.x == 0 && blockIdx.y == 0) { op.post(); } } } template <typename OpType> __device__ static typename std::enable_if<!OpType::has_post_grid, void>::type traverse_halo_post(OpType op) {} // Traversal with a known halo dimension template <int ND, typename DataType, typename OpType, bool inner, Side side, int dim, int halo_width> __global__ static void traverse_halo_opt(DataType * __restrict__ tensor, Array<ND> shape, OpType op) { traverse_halo_pre(op); if (dim == 0) { traverse_halo_opt_dim0<ND, DataType, OpType, inner, side> (tensor, shape, halo_width, op); } else if (dim == 1) { traverse_halo_opt_dim1<ND, DataType, OpType, inner, side, halo_width>( tensor, shape, op); } else if (dim == 2) { traverse_halo_opt_dim2<ND, DataType, OpType, inner, side, halo_width>( tensor, shape, op); } traverse_halo_post(op); } // Specialization with halo width template <int ND, typename DataType, typename OpType, bool inner, Side side, int dim> inline void traverse_halo_opt(DataType *tensor, Array<ND> shape, int halo_width, OpType op, cudaStream_t s, dim3 gsize, dim3 bsize) { #define CALL(HW) \ if ((OpType::has_post_grid || OpType::has_pre_grid) && num_blocks > 1) { \ void *args[3] = {&tensor, &shape, &op}; \ DISTCONV_CHECK_CUDA(cudaLaunchCooperativeKernel( \ (const void *)(traverse_halo_opt<ND, DataType, OpType, inner, \ side, dim, HW>), \ gsize, bsize, (void **)args, 0, s)); \ } else { \ traverse_halo_opt<ND, DataType, OpType, inner, side, dim, HW> \ <<<gsize, bsize, 0, s>>>(tensor, shape, op); \ auto err = cudaGetLastError(); \ if (err != cudaSuccess) { \ util::MPIPrintStreamError() \ << "Lauch error: " \ << gsize.x << "x" << gsize.y << "x" << gsize.z \ << ", " << bsize.x << "x" << bsize.y << "x" << bsize.z; \ DISTCONV_CHECK_CUDA(err); \ } \ } int num_blocks = gsize.x * gsize.y * gsize.z; switch (halo_width) { case 1: CALL(1); break; case 2: CALL(2); break; case 3: CALL(3); break; case 4: CALL(4); break; // Disable larger halo width to reduce compilation time #if 0 case 5: CALL(5); break; case 6: CALL(6); break; case 7: CALL(7); break; #endif default: // In order to make the performance more consistent, make it // fail if the halo width is not included in the above cases. //traverse_halo_opt<ND, DataType, OpType, inner, side, dim> //<<<gsize, bsize, 0, s>>>(tensor, shape, halo_width, op); util::MPIRootPrintStreamError() << "Unsupported halo size: " << halo_width; throw std::exception(); } #undef CALL } inline int get_max_block_dimension() { int dim = 512; // default auto env = std::getenv("DISTCONV_HALO_TRAVERSAL_MAX_BLOCK_SIZE"); if (env) { dim = std::stoi(std::string(env)); } return dim; } // ND: 4, 5 // Use 2-way vector type if possible template <int ND, typename DataType, typename OpType, bool inner, Side side, int dim> inline void traverse_halo_opt(DataType *tensor, Array<ND> shape, int halo_width, OpType op, cudaStream_t s) { int vector_width = 1; if (dim >= 1) { if (shape[0] % 4 == 0) { // vector2 seems better than vector4. vector_width = 2; } else if (shape[0] % 2 == 0) { vector_width = 2; } shape[0] /= vector_width; } else if (dim == 0) { if (halo_width % 4 == 0 && shape[0] % 4 == 0) { // vector2 seems better than vector4. vector_width = 2; } else if (halo_width % 2 == 0 && shape[0] % 2 == 0) { vector_width = 2; } halo_width /= vector_width; shape[0] /= vector_width; } else { util::MPIRootPrintStreamError() << "Invalid dimension"; throw std::exception(); } dim3 bsize(1); size_t max_dim = get_max_block_dimension(); if (dim == 0) { bsize.x = halo_width; bsize.y = std::min(shape[1], max_dim / bsize.x); } else if (dim == 1) { // The block-based traverse_halo_opt_dim1_5d_apply assumes one // thread block completely covers the x dimension. if (ND == 5) assert_always(shape[0] <= max_dim); bsize.x = std::min(shape[0], max_dim); if (ND == 5) bsize.y = std::min(shape[2], max_dim / bsize.x); } else if (dim == 2) { bsize.x = std::min(shape[0], max_dim); if (ND == 5) bsize.y = std::min(shape[1], max_dim / bsize.x); } constexpr int max_channel_per_block = 512; dim3 gsize(util::ceil(int(shape[-2]), max_channel_per_block), shape[-1]); // Compiling for additional vector width makes compilation time // further longer assert_always(vector_width == 2 || vector_width == 1); if (vector_width == 2) { using VecType = typename util::GetVectorType<DataType, 2>::type; traverse_halo_opt<ND, VecType, OpType, inner, side, dim>( (VecType*)tensor, shape, halo_width, op, s, gsize, bsize); } else { traverse_halo_opt<ND, DataType, OpType, inner, side, dim>( tensor, shape, halo_width, op, s, gsize, bsize); } } // ND: 4, 5 // Specialization with dimension template <int ND, typename DataType, typename OpType, bool inner, Side side> inline void traverse_halo_opt(DataType *tensor, Array<ND> shape, int dim, int halo_width, OpType op, cudaStream_t s) { if (dim == 0) { traverse_halo_opt<ND, DataType, OpType, inner, side, 0>( tensor, shape, halo_width, op, s); } else if (dim == 1) { traverse_halo_opt<ND, DataType, OpType, inner, side, 1>( tensor, shape, halo_width, op, s); } else { assert_eq(dim, 2); traverse_halo_opt<ND, DataType, OpType, inner, side, 2>( tensor, shape, halo_width, op, s); } } // ND: 4, 5 // Specialization with direction template <int ND, typename DataType, typename OpType, bool inner> inline void traverse_halo_opt(DataType *tensor, Array<ND> shape, int dim, Side side, int halo_width, OpType op, cudaStream_t s) { if (side == Side::RHS) { traverse_halo_opt<ND, DataType, OpType, inner, Side::RHS>( tensor, shape, dim, halo_width, op, s); } else { traverse_halo_opt<ND, DataType, OpType, inner, Side::LHS>( tensor, shape, dim, halo_width, op, s); } } // ND: 4, 5 // Specialization with inner/outer template <int ND, typename DataType, typename OpType> inline void traverse_halo_opt(DataType *tensor, Array<ND> shape, int dim, Side side, int halo_width, bool inner, OpType op, cudaStream_t s) { if (inner) { traverse_halo_opt<ND, DataType, OpType, true>( tensor, shape, dim, side, halo_width, op, s); } else { traverse_halo_opt<ND, DataType, OpType, false>( tensor, shape, dim, side, halo_width, op, s); } } } // namespace internal template <typename Tensor, typename OpType> void TraverseHalo(Tensor &tensor, int dim, Side side, int halo_width, bool inner, OpType op, cudaStream_t s) { // ConstDataType is const DataType if the operation only reads the tensor. using ConstDataType = typename std::conditional< OpType::modifies_tensor, typename Tensor::data_type, typename std::add_const<typename Tensor::data_type>::type>::type; const int num_dims = tensor.get_num_dims(); int available_halo_width = tensor.get_halo_width(dim); assert_always(halo_width <= available_halo_width); if (inner) { assert_always(tensor.get_local_shape()[dim] >= (size_t)halo_width); } if (halo_width == 0) { // No halo region attached return; } if (num_dims == 4 && (dim == 0 || dim == 1)) { internal::traverse_halo_opt<4, ConstDataType, OpType>( static_cast<ConstDataType*>(tensor.get_buffer()), tensor.get_local_real_shape(), dim, side, halo_width, inner, op, s); } else if (num_dims == 5 && (dim == 0 || dim ==1 || dim == 2)) { internal::traverse_halo_opt<5, ConstDataType, OpType>( static_cast<ConstDataType*>(tensor.get_buffer()), tensor.get_local_real_shape(), dim, side, halo_width, inner, op, s); } else { auto local_real_shape = tensor.get_local_real_shape(); local_real_shape[dim] = halo_width; auto num_halo_points = local_real_shape.get_size(); int block_size = 256; int grid_size = (num_halo_points + block_size - 1) / block_size; // Block-based operation not supported assert_always(OpType::group == HaloTraversalOpGroup::THREAD); internal::traverse_halo_generic<ConstDataType, OpType>( static_cast<ConstDataType*>(tensor.get_buffer()), tensor.get_local_real_shape(), dim, side, inner, halo_width, num_halo_points, op, num_dims, grid_size, block_size, s); } } template <typename Tensor, typename OpType> void TraverseHalo(Tensor &tensor, int dim, Side side, bool inner, OpType op, cudaStream_t s) { TraverseHalo(tensor, dim, side, tensor.get_distribution().get_overlap()[dim], inner, op, s); return; } template <typename Tensor, typename OpType> void TraverseHalo(Tensor &tensor, int dim, int width_rhs, int width_lhs, bool inner, OpType op, cudaStream_t s) { TraverseHalo(tensor, dim, width_rhs, Side::RHS, inner, op, s); TraverseHalo(tensor, dim, width_lhs, Side::LHS, inner, op, s); } template <typename Tensor, typename OpType> void TraverseHalo(Tensor &tensor, int dim, bool inner, OpType op, cudaStream_t s) { TraverseHalo(tensor, dim, Side::RHS, inner, op, s); TraverseHalo(tensor, dim, Side::LHS, inner, op, s); } } // namespace tensor } // namespace distconv
// -*- C++ -*- // FILE: direct_follow // (C) 2005 Frank R. Schaefer // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // 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 GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ////////////////////////////////////////////////////////////////////////////////////// #include<iostream> #include<GetPot> using namespace std; void print_help(const string); int main(int argc, char** argv) { GetPot cl(argc, argv); if( cl.size() == 1 || cl.search(2, "--help", "-h") ) { print_help(cl[0]); exit(0); } cout << "Strings following -U:\n"; vector<string> tmp0 = cl.string_tails("-U"); for(vector<string>::const_iterator it = tmp0.begin(); it != tmp0.end(); it++) cout << " '" << *it << "'\n"; cout << "Integers following -V:\n"; vector<int> tmp1 = cl.int_tails("-V"); for(vector<int>::const_iterator it = tmp1.begin(); it != tmp1.end(); it++) { cout << " '" << *it << "'\n"; } cout << "Doubles following -NUM:\n"; vector<double> tmp2 = cl.double_tails("-NUM"); for(vector<double>::const_iterator it = tmp2.begin(); it != tmp2.end(); it++) cout << " '" << *it << "'\n"; } void print_help(const string Application) { cout << endl; cout << "Example to use string_tails(), integer_tails() and double_tails() -functions:" << endl << endl; cout << "USAGE:" << endl; cout << "--help, -h get some help about this program." << endl; cout << endl; cout << "Write one, none or more of the following arguments:\n\n"; cout << " -Ustring specify user name as string" << endl; cout << " -Vx specify a value given as x" << endl; cout << " -NUMx specify number given as x" << endl; cout << endl; cout << "You can use as many argument of any type as you want." << endl; cout << endl; exit(0); }
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/redis/v20180412/model/EnableReplicaReadonlyResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Redis::V20180412::Model; using namespace std; EnableReplicaReadonlyResponse::EnableReplicaReadonlyResponse() : m_statusHasBeenSet(false) { } CoreInternalOutcome EnableReplicaReadonlyResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Core::Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Core::Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("Status") && !rsp["Status"].IsNull()) { if (!rsp["Status"].IsString()) { return CoreInternalOutcome(Core::Error("response `Status` IsString=false incorrectly").SetRequestId(requestId)); } m_status = string(rsp["Status"].GetString()); m_statusHasBeenSet = true; } return CoreInternalOutcome(true); } string EnableReplicaReadonlyResponse::ToJsonString() const { rapidjson::Document value; value.SetObject(); rapidjson::Document::AllocatorType& allocator = value.GetAllocator(); if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator); } rapidjson::Value iKey(rapidjson::kStringType); string key = "RequestId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator); rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); value.Accept(writer); return buffer.GetString(); } string EnableReplicaReadonlyResponse::GetStatus() const { return m_status; } bool EnableReplicaReadonlyResponse::StatusHasBeenSet() const { return m_statusHasBeenSet; }
// Copyright 2018-2021, NVIDIA CORPORATION & AFFILIATES. 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 NVIDIA CORPORATION 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 ``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 "src/core/model.h" #include <chrono> #include <future> #include "src/core/constants.h" #include "src/core/filesystem.h" #include "src/core/infer_request.h" #include "src/core/logging.h" #include "src/core/model_config_utils.h" namespace nvidia { namespace inferenceserver { Status Model::GetInput( const std::string& name, const inference::ModelInput** input) const { const auto itr = input_map_.find(name); if (itr == input_map_.end()) { return Status( Status::Code::INVALID_ARG, "unexpected inference input '" + name + "' for model '" + Name() + "'"); } *input = &itr->second; return Status::Success; } Status Model::GetOutput( const std::string& name, const inference::ModelOutput** output) const { const auto itr = output_map_.find(name); if (itr == output_map_.end()) { return Status( Status::Code::INVALID_ARG, "unexpected inference output '" + name + "' for model '" + Name() + "'"); } *output = &itr->second; return Status::Success; } Status Model::SetModelConfig(const inference::ModelConfig& config) { config_ = config; return Status::Success; } Status Model::SetScheduler(std::unique_ptr<Scheduler> scheduler) { if (scheduler_ != nullptr) { return Status( Status::Code::INTERNAL, "Attempt to change scheduler not allowed"); } scheduler_ = std::move(scheduler); return Status::Success; } Status Model::Init() { RETURN_IF_ERROR(ValidateModelConfig(config_, min_compute_capability_)); RETURN_IF_ERROR(ValidateModelIOConfig(config_)); // Initialize the input map for (const auto& io : config_.input()) { input_map_.insert(std::make_pair(io.name(), io)); } // Initialize the output map and label provider for each output label_provider_ = std::make_shared<LabelProvider>(); for (const auto& io : config_.output()) { output_map_.insert(std::make_pair(io.name(), io)); if (!io.label_filename().empty()) { const auto label_path = JoinPath({model_dir_, io.label_filename()}); RETURN_IF_ERROR(label_provider_->AddLabels(io.name(), label_path)); } } if (config_.has_dynamic_batching()) { default_priority_level_ = config_.dynamic_batching().default_priority_level(); max_priority_level_ = config_.dynamic_batching().priority_levels(); } else if (config_.has_ensemble_scheduling()) { // For ensemble, allow any priority level to pass through default_priority_level_ = 0; max_priority_level_ = UINT32_MAX; } else { default_priority_level_ = 0; max_priority_level_ = 0; } return Status::Success; } }} // namespace nvidia::inferenceserver
// 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 "chrome/browser/download/download_item_model.h" #include "base/i18n/number_formatting.h" #include "base/i18n/rtl.h" #include "base/metrics/field_trial.h" #include "base/strings/string16.h" #include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "base/supports_user_data.h" #include "base/time/time.h" #include "chrome/browser/download/chrome_download_manager_delegate.h" #include "chrome/browser/download/download_crx_util.h" #include "chrome/browser/download/download_service.h" #include "chrome/browser/download/download_service_factory.h" #include "chrome/browser/download/download_stats.h" #include "chrome/browser/safe_browsing/download_feedback_service.h" #include "content/public/browser/download_danger_type.h" #include "content/public/browser/download_interrupt_reasons.h" #include "content/public/browser/download_item.h" #include "grit/chromium_strings.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/l10n/time_format.h" #include "ui/base/text/bytes_formatting.h" #include "ui/gfx/text_elider.h" using base::TimeDelta; using content::DownloadItem; namespace { // Per DownloadItem data used by DownloadItemModel. The model doesn't keep any // state since there could be multiple models associated with a single // DownloadItem, and the lifetime of the model is shorter than the DownloadItem. class DownloadItemModelData : public base::SupportsUserData::Data { public: // Get the DownloadItemModelData object for |download|. Returns NULL if // there's no model data. static const DownloadItemModelData* Get(const DownloadItem* download); // Get the DownloadItemModelData object for |download|. Creates a model data // object if not found. Always returns a non-NULL pointer, unless OOM. static DownloadItemModelData* GetOrCreate(DownloadItem* download); bool should_show_in_shelf() const { return should_show_in_shelf_; } void set_should_show_in_shelf(bool should_show_in_shelf) { should_show_in_shelf_ = should_show_in_shelf; } bool should_notify_ui() const { return should_notify_ui_; } void set_should_notify_ui(bool should_notify_ui) { should_notify_ui_ = should_notify_ui; } bool should_prefer_opening_in_browser() const { return should_prefer_opening_in_browser_; } void set_should_prefer_opening_in_browser(bool preference) { should_prefer_opening_in_browser_ = preference; } private: DownloadItemModelData(); virtual ~DownloadItemModelData() {} static const char kKey[]; // Whether the download should be displayed in the download shelf. True by // default. bool should_show_in_shelf_; // Whether the UI should be notified when the download is ready to be // presented. bool should_notify_ui_; // Whether the download should be opened in the browser vs. the system handler // for the file type. bool should_prefer_opening_in_browser_; }; // static const char DownloadItemModelData::kKey[] = "DownloadItemModelData key"; // static const DownloadItemModelData* DownloadItemModelData::Get( const DownloadItem* download) { return static_cast<const DownloadItemModelData*>(download->GetUserData(kKey)); } // static DownloadItemModelData* DownloadItemModelData::GetOrCreate( DownloadItem* download) { DownloadItemModelData* data = static_cast<DownloadItemModelData*>(download->GetUserData(kKey)); if (data == NULL) { data = new DownloadItemModelData(); download->SetUserData(kKey, data); } return data; } DownloadItemModelData::DownloadItemModelData() : should_show_in_shelf_(true), should_notify_ui_(false), should_prefer_opening_in_browser_(false) { } string16 InterruptReasonStatusMessage(int reason) { int string_id = 0; switch (reason) { case content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_ACCESS_DENIED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_DISK_FULL; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_PATH_TOO_LONG; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_LARGE; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_VIRUS; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_TEMPORARY_PROBLEM; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_BLOCKED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SECURITY_CHECK_FAILED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_FILE_TOO_SHORT; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_ERROR; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_TIMEOUT; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NETWORK_DISCONNECTED; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_DOWN; break; case content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SERVER_PROBLEM; break; case content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_NO_FILE; break; case content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED: string_id = IDS_DOWNLOAD_STATUS_CANCELLED; break; case content::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_SHUTDOWN; break; case content::DOWNLOAD_INTERRUPT_REASON_CRASH: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS_CRASH; break; default: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS; break; } return l10n_util::GetStringUTF16(string_id); } string16 InterruptReasonMessage(int reason) { int string_id = 0; string16 status_text; switch (reason) { case content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_ACCESS_DENIED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_DISK_FULL; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_PATH_TOO_LONG; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_LARGE: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_FILE_TOO_LARGE; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_VIRUS_INFECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_VIRUS; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_TEMPORARY_PROBLEM; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_BLOCKED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_SECURITY_CHECK_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SECURITY_CHECK_FAILED; break; case content::DOWNLOAD_INTERRUPT_REASON_FILE_TOO_SHORT: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_FILE_TOO_SHORT; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_ERROR; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_TIMEOUT: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_TIMEOUT; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_DISCONNECTED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NETWORK_DISCONNECTED; break; case content::DOWNLOAD_INTERRUPT_REASON_NETWORK_SERVER_DOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SERVER_DOWN; break; case content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SERVER_PROBLEM; break; case content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_NO_FILE; break; case content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED: string_id = IDS_DOWNLOAD_STATUS_CANCELLED; break; case content::DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_SHUTDOWN; break; case content::DOWNLOAD_INTERRUPT_REASON_CRASH: string_id = IDS_DOWNLOAD_INTERRUPTED_DESCRIPTION_CRASH; break; default: string_id = IDS_DOWNLOAD_INTERRUPTED_STATUS; break; } status_text = l10n_util::GetStringUTF16(string_id); return status_text; } } // namespace // ----------------------------------------------------------------------------- // DownloadItemModel DownloadItemModel::DownloadItemModel(DownloadItem* download) : download_(download) {} DownloadItemModel::~DownloadItemModel() {} string16 DownloadItemModel::GetInterruptReasonText() const { if (download_->GetState() != DownloadItem::INTERRUPTED || download_->GetLastReason() == content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) { return string16(); } return InterruptReasonMessage(download_->GetLastReason()); } string16 DownloadItemModel::GetStatusText() const { string16 status_text; switch (download_->GetState()) { case DownloadItem::IN_PROGRESS: status_text = GetInProgressStatusString(); break; case DownloadItem::COMPLETE: if (download_->GetFileExternallyRemoved()) { status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_REMOVED); } else { status_text.clear(); } break; case DownloadItem::CANCELLED: status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CANCELLED); break; case DownloadItem::INTERRUPTED: { content::DownloadInterruptReason reason = download_->GetLastReason(); if (reason != content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) { string16 interrupt_reason = InterruptReasonStatusMessage(reason); status_text = l10n_util::GetStringFUTF16( IDS_DOWNLOAD_STATUS_INTERRUPTED, interrupt_reason); } else { // Same as DownloadItem::CANCELLED. status_text = l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CANCELLED); } break; } default: NOTREACHED(); } return status_text; } string16 DownloadItemModel::GetTabProgressStatusText() const { int64 total = GetTotalBytes(); int64 size = download_->GetReceivedBytes(); string16 received_size = ui::FormatBytes(size); string16 amount = received_size; // Adjust both strings for the locale direction since we don't yet know which // string we'll end up using for constructing the final progress string. base::i18n::AdjustStringForLocaleDirection(&amount); if (total) { string16 total_text = ui::FormatBytes(total); base::i18n::AdjustStringForLocaleDirection(&total_text); base::i18n::AdjustStringForLocaleDirection(&received_size); amount = l10n_util::GetStringFUTF16( IDS_DOWNLOAD_TAB_PROGRESS_SIZE, received_size, total_text); } else { amount.assign(received_size); } int64 current_speed = download_->CurrentSpeed(); string16 speed_text = ui::FormatSpeed(current_speed); base::i18n::AdjustStringForLocaleDirection(&speed_text); base::TimeDelta remaining; string16 time_remaining; if (download_->IsPaused()) time_remaining = l10n_util::GetStringUTF16(IDS_DOWNLOAD_PROGRESS_PAUSED); else if (download_->TimeRemaining(&remaining)) time_remaining = ui::TimeFormat::TimeRemaining(remaining); if (time_remaining.empty()) { base::i18n::AdjustStringForLocaleDirection(&amount); return l10n_util::GetStringFUTF16( IDS_DOWNLOAD_TAB_PROGRESS_STATUS_TIME_UNKNOWN, speed_text, amount); } return l10n_util::GetStringFUTF16( IDS_DOWNLOAD_TAB_PROGRESS_STATUS, speed_text, amount, time_remaining); } string16 DownloadItemModel::GetTooltipText(const gfx::FontList& font_list, int max_width) const { string16 tooltip = gfx::ElideFilename( download_->GetFileNameToReportUser(), font_list, max_width); content::DownloadInterruptReason reason = download_->GetLastReason(); if (download_->GetState() == DownloadItem::INTERRUPTED && reason != content::DOWNLOAD_INTERRUPT_REASON_USER_CANCELED) { tooltip += ASCIIToUTF16("\n"); tooltip += gfx::ElideText(InterruptReasonStatusMessage(reason), font_list, max_width, gfx::ELIDE_AT_END); } return tooltip; } string16 DownloadItemModel::GetWarningText(const gfx::FontList& font_list, int base_width) const { // Should only be called if IsDangerous(). DCHECK(IsDangerous()); string16 elided_filename = gfx::ElideFilename(download_->GetFileNameToReportUser(), font_list, base_width); switch (download_->GetDangerType()) { case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: { return l10n_util::GetStringUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_URL); } case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: { if (download_crx_util::IsExtensionDownload(*download_)) { return l10n_util::GetStringUTF16( IDS_PROMPT_DANGEROUS_DOWNLOAD_EXTENSION); } else { return l10n_util::GetStringFUTF16(IDS_PROMPT_DANGEROUS_DOWNLOAD, elided_filename); } } case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: { return l10n_util::GetStringFUTF16(IDS_PROMPT_MALICIOUS_DOWNLOAD_CONTENT, elided_filename); } case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: { return l10n_util::GetStringFUTF16(IDS_PROMPT_UNCOMMON_DOWNLOAD_CONTENT, elided_filename); } case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: { return l10n_util::GetStringFUTF16( IDS_PROMPT_DOWNLOAD_CHANGES_SETTINGS, elided_filename); } case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: case content::DOWNLOAD_DANGER_TYPE_MAX: { break; } } NOTREACHED(); return string16(); } string16 DownloadItemModel::GetWarningConfirmButtonText() const { // Should only be called if IsDangerous() DCHECK(IsDangerous()); if (download_->GetDangerType() == content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE && download_crx_util::IsExtensionDownload(*download_)) { return l10n_util::GetStringUTF16(IDS_CONTINUE_EXTENSION_DOWNLOAD); } else { return l10n_util::GetStringUTF16(IDS_CONFIRM_DOWNLOAD); } } int64 DownloadItemModel::GetCompletedBytes() const { return download_->GetReceivedBytes(); } int64 DownloadItemModel::GetTotalBytes() const { return download_->AllDataSaved() ? download_->GetReceivedBytes() : download_->GetTotalBytes(); } // TODO(asanka,rdsmith): Once 'open' moves exclusively to the // ChromeDownloadManagerDelegate, we should calculate the percentage here // instead of calling into the DownloadItem. int DownloadItemModel::PercentComplete() const { return download_->PercentComplete(); } bool DownloadItemModel::IsDangerous() const { return download_->IsDangerous(); } bool DownloadItemModel::MightBeMalicious() const { if (!IsDangerous()) return false; switch (download_->GetDangerType()) { case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return true; case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: case content::DOWNLOAD_DANGER_TYPE_MAX: // We shouldn't get any of these due to the IsDangerous() test above. NOTREACHED(); // Fallthrough. case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: return false; } NOTREACHED(); return false; } // If you change this definition of malicious, also update // DownloadManagerImpl::NonMaliciousInProgressCount. bool DownloadItemModel::IsMalicious() const { if (!MightBeMalicious()) return false; switch (download_->GetDangerType()) { case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_URL: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_HOST: case content::DOWNLOAD_DANGER_TYPE_POTENTIALLY_UNWANTED: return true; case content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS: case content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT: case content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED: case content::DOWNLOAD_DANGER_TYPE_MAX: case content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE: // We shouldn't get any of these due to the MightBeMalicious() test above. NOTREACHED(); // Fallthrough. case content::DOWNLOAD_DANGER_TYPE_UNCOMMON_CONTENT: return false; } NOTREACHED(); return false; } bool DownloadItemModel::ShouldAllowDownloadFeedback() const { #if defined(FULL_SAFE_BROWSING) if (!IsDangerous()) return false; return safe_browsing::DownloadFeedbackService::IsEnabledForDownload( *download_); #else return false; #endif } bool DownloadItemModel::ShouldRemoveFromShelfWhenComplete() const { switch (download_->GetState()) { case DownloadItem::IN_PROGRESS: // If the download is dangerous or malicious, we should display a warning // on the shelf until the user accepts the download. if (IsDangerous()) return false; // If the download is an extension, temporary, or will be opened // automatically, then it should be removed from the shelf on completion. // TODO(asanka): The logic for deciding opening behavior should be in a // central location. http://crbug.com/167702 return (download_crx_util::IsExtensionDownload(*download_) || download_->IsTemporary() || download_->GetOpenWhenComplete() || download_->ShouldOpenFileBasedOnExtension()); case DownloadItem::COMPLETE: // If the download completed, then rely on GetAutoOpened() to check for // opening behavior. This should accurately reflect whether the download // was successfully opened. Extensions, for example, may fail to open. return download_->GetAutoOpened() || download_->IsTemporary(); case DownloadItem::CANCELLED: case DownloadItem::INTERRUPTED: // Interrupted or cancelled downloads should remain on the shelf. return false; case DownloadItem::MAX_DOWNLOAD_STATE: NOTREACHED(); } NOTREACHED(); return false; } bool DownloadItemModel::ShouldShowDownloadStartedAnimation() const { return !download_->IsSavePackageDownload() && !download_crx_util::IsExtensionDownload(*download_); } bool DownloadItemModel::ShouldShowInShelf() const { const DownloadItemModelData* data = DownloadItemModelData::Get(download_); return !data || data->should_show_in_shelf(); } void DownloadItemModel::SetShouldShowInShelf(bool should_show) { DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_); data->set_should_show_in_shelf(should_show); } bool DownloadItemModel::ShouldNotifyUI() const { const DownloadItemModelData* data = DownloadItemModelData::Get(download_); return data && data->should_notify_ui(); } void DownloadItemModel::SetShouldNotifyUI(bool should_notify) { DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_); data->set_should_notify_ui(should_notify); } bool DownloadItemModel::ShouldPreferOpeningInBrowser() const { const DownloadItemModelData* data = DownloadItemModelData::Get(download_); return data && data->should_prefer_opening_in_browser(); } void DownloadItemModel::SetShouldPreferOpeningInBrowser(bool preference) { DownloadItemModelData* data = DownloadItemModelData::GetOrCreate(download_); data->set_should_prefer_opening_in_browser(preference); } string16 DownloadItemModel::GetProgressSizesString() const { string16 size_ratio; int64 size = GetCompletedBytes(); int64 total = GetTotalBytes(); if (total > 0) { ui::DataUnits amount_units = ui::GetByteDisplayUnits(total); string16 simple_size = ui::FormatBytesWithUnits(size, amount_units, false); // In RTL locales, we render the text "size/total" in an RTL context. This // is problematic since a string such as "123/456 MB" is displayed // as "MB 123/456" because it ends with an LTR run. In order to solve this, // we mark the total string as an LTR string if the UI layout is // right-to-left so that the string "456 MB" is treated as an LTR run. string16 simple_total = base::i18n::GetDisplayStringInLTRDirectionality( ui::FormatBytesWithUnits(total, amount_units, true)); size_ratio = l10n_util::GetStringFUTF16(IDS_DOWNLOAD_STATUS_SIZES, simple_size, simple_total); } else { size_ratio = ui::FormatBytes(size); } return size_ratio; } string16 DownloadItemModel::GetInProgressStatusString() const { DCHECK_EQ(DownloadItem::IN_PROGRESS, download_->GetState()); TimeDelta time_remaining; // time_remaining is only known if the download isn't paused. bool time_remaining_known = (!download_->IsPaused() && download_->TimeRemaining(&time_remaining)); // Indication of progress. (E.g.:"100/200 MB" or "100MB") string16 size_ratio = GetProgressSizesString(); // The download is a CRX (app, extension, theme, ...) and it is being unpacked // and validated. if (download_->AllDataSaved() && download_crx_util::IsExtensionDownload(*download_)) { return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_CRX_INSTALL_RUNNING); } // A paused download: "100/120 MB, Paused" if (download_->IsPaused()) { return l10n_util::GetStringFUTF16( IDS_DOWNLOAD_STATUS_IN_PROGRESS, size_ratio, l10n_util::GetStringUTF16(IDS_DOWNLOAD_PROGRESS_PAUSED)); } // A download scheduled to be opened when complete: "Opening in 10 secs" if (download_->GetOpenWhenComplete()) { if (!time_remaining_known) return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_OPEN_WHEN_COMPLETE); return l10n_util::GetStringFUTF16( IDS_DOWNLOAD_STATUS_OPEN_IN, ui::TimeFormat::TimeRemainingShort(time_remaining)); } // In progress download with known time left: "100/120 MB, 10 secs left" if (time_remaining_known) { return l10n_util::GetStringFUTF16( IDS_DOWNLOAD_STATUS_IN_PROGRESS, size_ratio, ui::TimeFormat::TimeRemaining(time_remaining)); } // In progress download with no known time left and non-zero completed bytes: // "100/120 MB" or "100 MB" if (GetCompletedBytes() > 0) return size_ratio; // Instead of displaying "0 B" we say "Starting..." return l10n_util::GetStringUTF16(IDS_DOWNLOAD_STATUS_STARTING); } void DownloadItemModel::OpenUsingPlatformHandler() { DownloadService* download_service = DownloadServiceFactory::GetForBrowserContext( download_->GetBrowserContext()); if (!download_service) return; ChromeDownloadManagerDelegate* delegate = download_service->GetDownloadManagerDelegate(); if (!delegate) return; delegate->OpenDownloadUsingPlatformHandler(download_); RecordDownloadOpenMethod(DOWNLOAD_OPEN_METHOD_USER_PLATFORM); }
//////////////////////////////////////////////////////////////////////////// // Created : 25.09.2008 // Author : Dmitriy Iassenev // Copyright (C) GSC Game World - 2009 //////////////////////////////////////////////////////////////////////////// #include "pch.h" #include <xray/os_include.h> u64 windows_query_performance_counter () { u64 result; QueryPerformanceCounter ((PLARGE_INTEGER)&result); return (result); }
// <ReportConfigInspection> -*- C++ -*- /*! * \file ReportConfigInspection.hpp * * Collection of helper methods to inspect report / report trigger * configuration for a given simulation. */ #ifndef __REPORT_CONFIG_INSPECTION_H__ #define __REPORT_CONFIG_INSPECTION_H__ #include "sparta/app/ReportDescriptor.hpp" namespace sparta { namespace app { //! \brief Ask this descriptor if it has at least one trigger bool hasAnyReportTriggers(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any start trigger bool hasStartTrigger(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any update trigger bool hasUpdateTrigger(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any stop trigger bool hasStopTrigger(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any toggle trigger bool hasToggleTrigger(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any on-demand trigger bool hasOnDemandTrigger(const ReportDescriptor * rd); //! \brief Ask this descriptor if it has any *start* trigger //! that is configured to listen to a NotificationSource by //! the given name. bool hasNotifSourceStartTriggerNamed( const ReportDescriptor * rd, const std::string & notif_source_name); //! \brief Ask this descriptor if it has any *update* trigger //! that is configured to listen to a NotificationSource by //! the given name. bool hasNotifSourceUpdateTriggerNamed( const ReportDescriptor * rd, const std::string & notif_source_name); //! \brief Ask this descriptor if it has any *stop* trigger //! that is configured to listen to a NotificationSource by //! the given name. bool hasNotifSourceStopTriggerNamed( const ReportDescriptor * rd, const std::string & notif_source_name); //! \brief Ask this descriptor for its full trigger expression //! of the given type. Examples: //! \code //! auto start_expr = getTriggerExpression(rd, "start"); //! if (start_expr.isValid()) { //! std::cout << "Start trigger has expression: " //! << start_expr.getValue() << std::endl; //! } else { //! std::cout << "No start trigger found for report '" //! << rd->dest_file << "'" << std::endl; //! } //! //! auto update_expr = getTriggerExpression(rd, "update-cycles"); //! //... //! \endcode //! //! \note If valid, the returned string will have all whitespace //! characters removed from it. This ensures consistent returned //! strings for things like: //! trigger: | trigger: //! start: "notif.foobar >= 9" | start: "notif.foobar >= 9" //! //! Which are functionally identical. utils::ValidValue<std::string> getTriggerExpression( const ReportDescriptor * rd, const std::string & yaml_type); //! \brief Get the notif.THIS_NAME of the descriptor's start trigger. //! Example: //! \code //! //YAML file looked like this: //! // report: //! // ... //! // trigger: //! // start: notif.my_start_channel == 100 //! auto start_notif_name = getNotifSourceForStartTrigger(rd); //! sparta_assert(start_notif_name.isValid(), //! "Expected a notif-based start trigger"); //! std::cout << "Start trigger was driven by the NotificationSource named '" //! << start_notif_name.getValue() << std::endl; //! //! \note If valid, the returned string will have whitespace //! characters removed. More specifically, these strings are //! trimmed which removes whitespace from the outer edges of //! the string: //! " foobar " --> "foobar" //! //! There will be no whitespace left after trimming a notif //! source name. utils::ValidValue<std::string> getNotifSourceForStartTrigger( const ReportDescriptor * rd); //! \brief Get the notif.THIS_NAME of the descriptor's update trigger. //! See above for code example. //! \note See above for a note on whitespace removal. utils::ValidValue<std::string> getNotifSourceForUpdateTrigger( const ReportDescriptor * rd); //! \brief Get the notif.THIS_NAME of the descriptor's stop trigger. //! See above for code example. //! \note See above for a note on whitespace removal. utils::ValidValue<std::string> getNotifSourceForStopTrigger( const ReportDescriptor * rd); } // namespace app } // namespace sparta #endif
/** * Copyright (c) 2017-present, 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. */ #include <algorithm> #include <atomic> #include <cstdint> #include <iostream> #include <queue> #include <stdlib.h> #include <thread> #include <time.h> #include <vector> #include <gtest/gtest.h> #include "logdevice/common/SlidingWindowSingleEpoch.h" #include "logdevice/common/checks.h" using namespace facebook::logdevice; static int g_windowSize; // maximum # items in the window, must stay constant // for the duration of each inidividual test namespace { struct Stats { // number of successful calls to grow() on this thread uint64_t n_insertions = 0; uint64_t n_retired = 0; // the number of calls to retire() on this thread uint64_t n_reaped = 0; // the number of calls to deleter on this thread uint64_t n_reaped_reported = 0; // the number of reaped entries reported by // calls to retire() on this thread // maximum item id returned by grow() on this thread lsn_t right_edge_max = LSN_INVALID; uint64_t n_window_full = 0; // number of times grow() found the window full uint64_t n_window_empty = 0; // number of times the window got empty uint64_t n_retire_ooo = 0; // number of times retire() indicated that no // items were reaped (out-of-order retirement) uint64_t n_etoobig = 0; // number of times grow() failed with E::TOOBIG void aggregate(const Stats& r) { n_insertions += r.n_insertions; n_retired += r.n_retired; n_reaped += r.n_reaped; n_reaped_reported += r.n_reaped_reported; right_edge_max = std::max(right_edge_max, r.right_edge_max); n_window_full += r.n_window_full; n_window_empty += r.n_window_empty; n_retire_ooo += r.n_retire_ooo; n_etoobig += r.n_etoobig; } } __attribute__((__aligned__(64))); // Window item. class Item { public: explicit Item(uint32_t priority) : id_(LSN_INVALID), priority_(priority) {} bool operator==(const Item& other) const { return priority_ == other.priority_; } bool operator<(const Item& other) const { return priority_ < other.priority_; } bool operator<=(const Item& other) const { return priority_ <= other.priority_; } class Deleter { public: explicit Deleter(Stats* stats) : stats_(stats) { ld_check(stats); } void operator()(Item* it) { ASSERT_EQ( lsn_to_epoch(Item::Deleter::last_reaped), lsn_to_epoch(it->id_)); ++Item::Deleter::last_reaped; ASSERT_EQ(Item::Deleter::last_reaped, it->id_); stats_->n_reaped++; delete it; } static void initLastReaped(lsn_t initial) { Item::Deleter::last_reaped = initial - 1; } private: Stats* stats_; // per-thread stats to update // id of last Item that retire() passed to a Deleter on any thread. // Must monotonically increase without gaps. static lsn_t last_reaped; }; lsn_t id_; private: uint32_t priority_; // priority value that threads will use to decide // which item to retire() next } __attribute__((__aligned__(4))); lsn_t Item::Deleter::last_reaped; } // anonymous namespace /** * Start multiple threads that will all operate on the same * SlidingWindow. Each thread calls grow() a certain number of * times. After each grow() it may also call retire() on one of the * items it previously inserted and not yet retired, with some * probability. If grow() fails because the maximum window size is * reached, the thread calls retire() unconditionally. Deleter objects * verify that reaping is done in the strict ascending order with no * gaps. Some per-thread stats are maintained and logged to stdout at * the end of test. */ TEST(SlidingWindowTest, RandomRetirement) { const int n_threads = 24; // number of threads to run const int n_attempts = 128 * 1024; // calls to grow() per thread const epoch_t initial_epoch(1); // epoch where to start the window g_windowSize = 10001; // maximum # items in the window SlidingWindowSingleEpoch<Item, Item::Deleter> window( initial_epoch, g_windowSize); std::vector<std::thread> g_threads; std::vector<Stats> g_stats(n_threads, Stats()); lsn_t initial_lsn = compose_lsn(initial_epoch, ESN_MIN); Item::Deleter::initLastReaped(initial_lsn); for (int thread_id = 0; thread_id < n_threads; thread_id++) { g_threads.emplace_back(std::thread([=, &window, &g_stats] { struct drand48_data rnd; srand48_r(time(0), &rnd); // these constants indirectly control min and max number of retire() // calls per grow() const double retire_per_insertion_min = 32.0; const double retire_per_insertion_max = 256.0; // rate at which the number of retire() calls per grow() changes double retire_per_insertion_step = 0.0001; double retire_per_insertion = retire_per_insertion_min; Stats* stats = &g_stats[thread_id]; // items that have not yet been retired std::priority_queue<Item> active; for (int i = 0; i < n_attempts || !active.empty(); i++) { double retire_points = retire_per_insertion; if (i < n_attempts) { long priority; lrand48_r(&rnd, &priority); Item* it = new Item((uint32_t)priority); lsn_t lsn = window.grow(it); if (lsn != LSN_INVALID) { ASSERT_GT(lsn, stats->right_edge_max); stats->n_insertions++; stats->right_edge_max = lsn; it->id_ = lsn; active.push(*it); } else { ASSERT_EQ(facebook::logdevice::E::NOBUFS, err); stats->n_window_full++; // window size limit reached. Start aggressively retiring items, // gradually reducing aggressiveness. retire_per_insertion = retire_per_insertion_max; if (retire_per_insertion_step > 0) { retire_per_insertion_step = -retire_per_insertion_step; } delete it; } } else { // done with inserts, retire all remaining items asap retire_points = g_windowSize; } for (;;) { long r; lrand48_r(&rnd, &r); double p = (double)r / INT_MAX; if (p > retire_points) { // not enough retire points left break; } retire_points -= p; if (!active.empty()) { const Item& retire_item = active.top(); ld_check(retire_item.id_ != LSN_INVALID); stats->n_retired++; Item::Deleter deleter(stats); size_t n_reaped = window.retire(retire_item.id_, deleter); if (n_reaped == 0) { stats->n_retire_ooo++; } else { stats->n_reaped_reported += n_reaped; } active.pop(); } else { // don't have any more items to retire. Drop retirement rate // to min and start slowly increasing it. retire_per_insertion = retire_per_insertion_min; if (retire_per_insertion_step < 0) { retire_per_insertion_step = -retire_per_insertion_step; } } if (window.size() == 0) { ASSERT_TRUE(active.empty()); stats->n_window_empty++; break; } } retire_per_insertion += retire_per_insertion_step; if (retire_per_insertion < retire_per_insertion_min) { retire_per_insertion = retire_per_insertion_min; } else if (retire_per_insertion > retire_per_insertion_max) { retire_per_insertion = retire_per_insertion_max; } } // for i })); } for (std::thread& t : g_threads) { t.join(); } Stats totals; for (const Stats& s : g_stats) { totals.aggregate(s); } EXPECT_EQ(n_attempts * n_threads, totals.n_insertions + totals.n_window_full); EXPECT_EQ(totals.n_insertions, totals.n_retired); EXPECT_EQ(totals.n_insertions, totals.n_reaped); EXPECT_EQ(totals.n_insertions, totals.n_reaped_reported); std::cout << "SUMMARY: inserted, retired and reaped " << totals.n_insertions << " items on " << n_threads << " threads." << std::endl << " Window filled up " << totals.n_window_full << " time(s)" << std::endl << " Window went empty " << totals.n_window_empty << " time(s)" << std::endl << " The number of out-of-order retirements was " << totals.n_retire_ooo << std::endl; } /** * Creates a SlidingWindow with the max esn very close to ESN_MIN. * Start multiple threads that all operate on that SlidingWindow. Verifies * that grow() starts reporting E::TOOBIG in all threads after a certain * number of insertions. Verifies that all previously inserted items can * be retired and reaped. */ TEST(SlidingWindowTest, EsnExhaustion) { const int n_threads = 24; // number of threads to run const int n_attempts = 10000; // calls to grow() per thread const int esns_available = 15000; // number of ESNs remaining const esn_t initial_esn = ESN_MIN; const esn_t max_esn(esns_available); const lsn_t initial_lsn(compose_lsn(EPOCH_MIN, ESN_MIN)); g_windowSize = 10230; // maximum # items in the window SlidingWindowSingleEpoch<Item, Item::Deleter> window( EPOCH_MIN, g_windowSize, max_esn); std::vector<std::thread> g_threads; std::vector<Stats> g_stats(n_threads, Stats()); Item::Deleter::initLastReaped(initial_lsn); for (int thread_id = 0; thread_id < n_threads; thread_id++) { g_threads.emplace_back(std::thread([=, &window, &g_stats] { struct drand48_data rnd; srand48_r(time(0), &rnd); Stats* stats = &g_stats[thread_id]; std::queue<Item> active; for (int i = 0; i < n_attempts || !active.empty(); i++) { int retire = 2; if (i < n_attempts) { Item* it = new Item(0); lsn_t lsn = window.grow(it); if (lsn != LSN_INVALID) { ASSERT_GT(lsn, stats->right_edge_max); ASSERT_LT(lsn_to_esn(lsn).val_, ESN_MAX.val_); ASSERT_GE(lsn_to_esn(lsn), initial_esn); // must not wrap around ASSERT_EQ(0, stats->n_etoobig); // no successes after E::TOOBIG stats->n_insertions++; stats->right_edge_max = lsn; it->id_ = lsn; active.push(*it); } else if (err == facebook::logdevice::E::NOBUFS) { stats->n_window_full++; retire++; // retire an extra item delete it; } else { ASSERT_EQ(facebook::logdevice::E::TOOBIG, err); stats->n_etoobig++; delete it; } } else { // Done with insertions. Retire all remaining items. retire = active.size(); } // now retire some items for (int j = 0; j < retire && !active.empty(); j++) { const Item& retire_item = active.front(); ld_check(retire_item.id_ != LSN_INVALID); stats->n_retired++; Item::Deleter deleter(stats); size_t n_reaped = window.retire(retire_item.id_, deleter); if (n_reaped == 0) { stats->n_retire_ooo++; } else { stats->n_reaped_reported += n_reaped; } active.pop(); } } })); } for (std::thread& t : g_threads) { t.join(); } Stats totals; for (const Stats& s : g_stats) { totals.aggregate(s); } EXPECT_EQ(n_attempts * n_threads, totals.n_insertions + totals.n_window_full + totals.n_etoobig); EXPECT_EQ(totals.n_insertions, totals.n_retired); EXPECT_EQ(totals.n_insertions, totals.n_reaped); EXPECT_EQ(esns_available, lsn_to_esn(totals.right_edge_max).val_); EXPECT_EQ(esns_available, totals.n_insertions); std::cout << "SUMMARY: inserted, retired and reaped " << totals.n_insertions << " items on " << n_threads << " threads." << std::endl << " Window filled up " << totals.n_window_full << " time(s)" << std::endl << " Window went empty " << totals.n_window_empty << " time(s)" << std::endl << " The number of out-of-order retirements was " << totals.n_retire_ooo << std::endl << " The number of insertions failed with E::TOOBIG was " << totals.n_etoobig << std::endl << " Highest ESN assigned was " << lsn_to_esn(totals.right_edge_max).val_ << std::endl; } TEST(SlidingWindowTest, ConditionalInsert) { Stats stats; SlidingWindowSingleEpoch<Item, Item::Deleter> window(EPOCH_MIN, 1024); Item::Deleter::initLastReaped(compose_lsn(EPOCH_MIN, ESN_MIN)); Item* it = new Item(0); lsn_t lsn = window.grow(it, LSN_INVALID); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_NOT_READY, err); // the same for other lsns lsn = window.grow(it, compose_lsn(EPOCH_MIN, esn_t(1))); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_NOT_READY, err); // set the prev epoch tail but with wrong epoch int rv = window.set_prev_tail(compose_lsn(EPOCH_MIN, esn_t(1))); ASSERT_EQ(-1, rv); ASSERT_EQ(E::INVALID_PARAM, err); // set the prev epoch tail in the right way rv = window.set_prev_tail(LSN_INVALID); ASSERT_EQ(0, rv); // conditional append for the wrong lsn lsn = window.grow(it, compose_lsn(epoch_t(0), esn_t(1))); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_FAILED, err); // conditional append for the right lsn lsn = window.grow(it, LSN_INVALID); ASSERT_EQ(compose_lsn(EPOCH_MIN, ESN_MIN), lsn); it->id_ = lsn; it = new Item(0); // perform a conditional insert with a wrong prev_lsn lsn = window.grow(it, compose_lsn(EPOCH_MIN, esn_t(2))); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_FAILED, err); // perform a conditional insert with the right prev_lsn lsn = window.grow(it, compose_lsn(EPOCH_MIN, esn_t(1))); ASSERT_EQ(compose_lsn(EPOCH_MIN, esn_t(2)), lsn); it->id_ = lsn; Item::Deleter deleter(&stats); size_t n_reaped = window.retire(compose_lsn(EPOCH_MIN, esn_t(1)), deleter); ASSERT_EQ(1, n_reaped); n_reaped = window.retire(compose_lsn(EPOCH_MIN, esn_t(2)), deleter); ASSERT_EQ(1, n_reaped); } // the window can perform a conditonal insert after successful unconditonal // insert, even if the prev lsn remains unset TEST(SlidingWindowTest, ConditionalInsert2) { Stats stats; SlidingWindowSingleEpoch<Item, Item::Deleter> window(epoch_t(5), 1024); Item::Deleter::initLastReaped(compose_lsn(epoch_t(5), ESN_MIN)); Item* it = new Item(0); lsn_t lsn = window.grow(it, compose_lsn(epoch_t(4), esn_t(9))); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_NOT_READY, err); // perform an unconditional insert, should be successful lsn = window.grow(it); ASSERT_EQ(compose_lsn(epoch_t(5), ESN_MIN), lsn); it->id_ = lsn; it = new Item(0); // perform a conditional insert with a wrong prev_lsn lsn = window.grow(it, compose_lsn(epoch_t(5), esn_t(2))); ASSERT_EQ(LSN_INVALID, lsn); ASSERT_EQ(E::COND_WRITE_FAILED, err); // perform a conditional insert with the right prev_lsn lsn = window.grow(it, compose_lsn(epoch_t(5), esn_t(1))); ASSERT_EQ(compose_lsn(epoch_t(5), esn_t(2)), lsn); it->id_ = lsn; Item::Deleter deleter(&stats); size_t n_reaped = window.retire(compose_lsn(epoch_t(5), esn_t(2)), deleter); ASSERT_EQ(0, n_reaped); n_reaped = window.retire(compose_lsn(epoch_t(5), esn_t(1)), deleter); ASSERT_EQ(2, n_reaped); }
#include "image.h" #include <cassert> #include <cstdlib> int rawbmp2image(const data& file,int height,int width,image& i){ // if(file.len!=3*height*width) // return -1; if(i.len!=height*width) image_init(i,height,width); CastArray<RGB*> d(i.data,i.width); CastArray<unsigned char (*)[3]> d2((unsigned char(*)[3])file.head,width); for(int h=0;h<height;h++) for(int w=0;w<width;w++){ if(3*(w+h*width)<file.len){ d[h][w].r=d2[h][w][0]; d[h][w].g=d2[h][w][1]; d[h][w].b=d2[h][w][2]; }else{ d[h][w].r=0; d[h][w].g=0; d[h][w].b=0; } } return 0; } int image2rawbmp(const image& i,data& file){ /* typedef unsigned int uint; // assert(false); data_init(file,i.len*3/2); CastArray<RGB*> d(i.data,i.width); CastArray<unsigned char *> y((unsigned char*)file.head,i.width); */ return 0; } int bmp2image(const data& file,image& i){ int bpp; unsigned char *begin,*pos; unsigned char *parret; int offset; assert(file.len>=54); assert(file.head[0]=='B'); assert(file.head[1]=='M'); assert(*(long int*)(file.head+2)==file.len); offset=*(long int*)(file.head+10); assert(*(long int*)(file.head+14)==40); i.width=*(long int*)(file.head+18); i.height=*(long int*)(file.head+22); assert(*(short int*)(file.head+26)==1); bpp=*(short int*)(file.head+28); assert(*(long int*)(file.head+30)==0); // assert(*(long int*)(file.head+34)==file.len-offset); assert(file.len-offset==(i.width *bpp/8+(4-(i.width * bpp/8)%4)%4)*i.height); begin=(unsigned char*)file.head+offset; parret=(unsigned char*)file.head+54; i.len=i.width*i.height; i.data=(RGB*)malloc(i.width*i.height*sizeof(RGB)); assert(i.data!=NULL); // RGB (*dbuf)[i.width]; // dbuf=(RGB (*)[i.width])(i.data); // for(int h=i.height-1;h>=0;h--){ unsigned char ppos; for(int h=0;h<i.height;h++){ pos=begin+(i.width * bpp/8+(4-(i.width * bpp/8)%4)%4)*(i.height-h-1); for(int w=0;w<i.width;w++){ RGB rgb; switch(bpp){ case 8: ppos=*pos; rgb.b=*(parret+(ppos*4)); rgb.g=*(parret+(ppos*4)+1); rgb.r=*(parret+(ppos*4)+2); rgb.alpha=*(parret+(ppos*4)+3); pos++; break; case 16: unsigned short int p; p=*(unsigned short int*)pos; rgb.b=0x1f&p; rgb.g=(0x3e0&p)>>5; rgb.r=(0x7c00&p)>>10; *pos+=2; break; case 24: rgb.b=*pos++; rgb.g=*pos++; rgb.r=*pos++; break; case 32: rgb.b=*pos++; rgb.g=*pos++; rgb.r=*pos++; rgb.alpha=*pos++; break; default: return -1; } i.data[i.width*h+w]=rgb; // dbuf[h][w]=rgb; } } return 0; } int image2bmp(const image& im,data& file,int bpp,char** bmp_info,char** pos_data){ long int li=0; short int si=0; int pinfo,pdata; data_init(file); data_push(file,"BM",2); li=54+(im.width *bpp/8+(4-(im.width * bpp/8)%4)%4)*im.height; data_push(file,(char*)&li,4); data_push(file,(char*)&si,2); data_push(file,(char*)&si,2); li=54; data_push(file,(char*)&li,4); pinfo=file.len; li=40; data_push(file,(char*)&li,4); li=im.width; data_push(file,(char*)&li,4); li=im.height; data_push(file,(char*)&li,4); si=1; data_push(file,(char*)&si,2); si=bpp; data_push(file,(char*)&si,2); li=0; data_push(file,(char*)&li,4); li=(im.width *bpp/8+(4-(im.width * bpp/8)%4)%4)*im.height; data_push(file,(char*)&li,4); li=0; data_push(file,(char*)&li,4); data_push(file,(char*)&li,4); data_push(file,(char*)&li,4); data_push(file,(char*)&li,4); pdata=file.len; RGB* pos; int diff=(4-(im.width*(bpp/8))%4)%4; for(int h=im.height-1;h>=0;h--){ pos=im.data+im.width*h; for(int w=0;w<im.width;w++){ RGB rgb=pos[w]; switch(bpp){ case 24: data_push(file,(char*)&(rgb.b),1); data_push(file,(char*)&(rgb.g),1); data_push(file,(char*)&(rgb.r),1); break; case 32: data_push(file,(char*)&(rgb.b),1); data_push(file,(char*)&(rgb.g),1); data_push(file,(char*)&(rgb.r),1); data_push(file,(char*)&(rgb.alpha),1); break; default: return -1; } } for(int j=0;j<diff;j++){ char c=0; data_push(file,&c,1); } } if(bmp_info!=NULL) *bmp_info=file.head+pinfo; if(pos_data!=NULL) *pos_data=file.head+pdata; return 0; } #ifdef BMPCPP_MAIN int main(){ data file; image im; data_load(file,"/dev/stdin"); bmp2image(file,im); data_free(file); RGB (*dbuf)[im.width]; dbuf=(RGB (*)[im.width])(im.data); for(int i=0;i<im.height;i++){ for(int j=0;j<im.width;j++){ dbuf[i][j].r=255-dbuf[i][j].r; dbuf[i][j].g=255-dbuf[i][j].g; dbuf[i][j].b=255-dbuf[i][j].b; } } // std::reverse(i.data.begin(),i.data.end()); image2bmp(im,file); data_save(file,"/dev/stdout"); return 0; } #endif #ifdef BMPCPP_MAIN2 int main(){ data file; image_array im; data_load(file,"/dev/stdin"); bmp2image(file,im); data_free(file); for(int i=0;i<im.height;i++){ for(int j=0;j<im.width;j++){ im[i][j].r=255-im[i][j].r; im[i][j].g=255-im[i][j].g; im[i][j].b=255-im[i][j].b; } } // std::reverse(i.data.begin(),i.data.end()); image2bmp(im,file); data_save(file,"/dev/stdout"); return 0; } #endif
// // Copyright 2020 Google Inc. // // 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 "accessibility_label_not_punctuated_check.h" #include "string_utils.h" namespace gtx { bool AccessibilityLabelNotPunctuatedCheck::CheckElement( const UIElement &element, const Parameters &params, ErrorMessage *errorMessage) const { if (element.is_text_displaying_element()) { // This check is not applicable to text elements as accessibility labels can // hold static text that can be punctuated and formatted like a string. return true; } std::string accessibility_label = TrimWhitespace(element.ax_label()); // This check is not applicable for container elements that combine individual // labels joined with commas. if (accessibility_label.find(',') != std::string::npos) { return true; } return !EndsWithInvalidPunctuation(accessibility_label); } bool AccessibilityLabelNotPunctuatedCheck::EndsWithInvalidPunctuation( const std::string &str) const { return !str.empty() && str.back() == '.'; } } // namespace gtx
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #ifndef __OPENCV_PRECOMP_H__ #define __OPENCV_PRECOMP_H__ #include "opencv2/opencv_modules.hpp" #include "cvconfig.h" #include "opencv2/core/utility.hpp" #include "opencv2/core/core_c.h" #include "opencv2/core/cuda.hpp" #include "opencv2/core/opengl.hpp" #include "opencv2/core/private.hpp" #include "opencv2/core/private.cuda.hpp" #include "opencv2/core/ocl.hpp" #include <assert.h> #include <ctype.h> #include <float.h> #include <limits.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #ifdef HAVE_TEGRA_OPTIMIZATION #include "opencv2/core/core_tegra.hpp" #else #define GET_OPTIMIZED(func) (func) #endif namespace cv { typedef void (*BinaryFunc)(const uchar* src1, size_t step1, const uchar* src2, size_t step2, uchar* dst, size_t step, Size sz, void*); BinaryFunc getConvertFunc(int sdepth, int ddepth); BinaryFunc getCopyMaskFunc(size_t esz); /* default memory block for sparse array elements */ #define CV_SPARSE_MAT_BLOCK (1<<12) /* initial hash table size */ #define CV_SPARSE_HASH_SIZE0 (1<<10) /* maximal average node_count/hash_size ratio beyond which hash table is resized */ #define CV_SPARSE_HASH_RATIO 3 // -128.f ... 255.f extern const float g_8x32fTab[]; #define CV_8TO32F(x) cv::g_8x32fTab[(x)+128] extern const ushort g_8x16uSqrTab[]; #define CV_SQR_8U(x) cv::g_8x16uSqrTab[(x)+255] extern const char* g_HersheyGlyphs[]; extern const uchar g_Saturate8u[]; #define CV_FAST_CAST_8U(t) (assert(-256 <= (t) && (t) <= 512), cv::g_Saturate8u[(t)+256]) #define CV_MIN_8U(a,b) ((a) - CV_FAST_CAST_8U((a) - (b))) #define CV_MAX_8U(a,b) ((a) + CV_FAST_CAST_8U((b) - (a))) #if defined WIN32 || defined _WIN32 void deleteThreadAllocData(); #endif template<typename T1, typename T2=T1, typename T3=T1> struct OpAdd { typedef T1 type1; typedef T2 type2; typedef T3 rtype; T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a + b); } }; template<typename T1, typename T2=T1, typename T3=T1> struct OpSub { typedef T1 type1; typedef T2 type2; typedef T3 rtype; T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(a - b); } }; template<typename T1, typename T2=T1, typename T3=T1> struct OpRSub { typedef T1 type1; typedef T2 type2; typedef T3 rtype; T3 operator ()(const T1 a, const T2 b) const { return saturate_cast<T3>(b - a); } }; template<typename T> struct OpMin { typedef T type1; typedef T type2; typedef T rtype; T operator ()(const T a, const T b) const { return std::min(a, b); } }; template<typename T> struct OpMax { typedef T type1; typedef T type2; typedef T rtype; T operator ()(const T a, const T b) const { return std::max(a, b); } }; inline Size getContinuousSize( const Mat& m1, int widthScale=1 ) { return m1.isContinuous() ? Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows); } inline Size getContinuousSize( const Mat& m1, const Mat& m2, int widthScale=1 ) { return (m1.flags & m2.flags & Mat::CONTINUOUS_FLAG) != 0 ? Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows); } inline Size getContinuousSize( const Mat& m1, const Mat& m2, const Mat& m3, int widthScale=1 ) { return (m1.flags & m2.flags & m3.flags & Mat::CONTINUOUS_FLAG) != 0 ? Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows); } inline Size getContinuousSize( const Mat& m1, const Mat& m2, const Mat& m3, const Mat& m4, int widthScale=1 ) { return (m1.flags & m2.flags & m3.flags & m4.flags & Mat::CONTINUOUS_FLAG) != 0 ? Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows); } inline Size getContinuousSize( const Mat& m1, const Mat& m2, const Mat& m3, const Mat& m4, const Mat& m5, int widthScale=1 ) { return (m1.flags & m2.flags & m3.flags & m4.flags & m5.flags & Mat::CONTINUOUS_FLAG) != 0 ? Size(m1.cols*m1.rows*widthScale, 1) : Size(m1.cols*widthScale, m1.rows); } struct NoVec { size_t operator()(const void*, const void*, void*, size_t) const { return 0; } }; extern volatile bool USE_SSE2; extern volatile bool USE_SSE4_2; extern volatile bool USE_AVX; enum { BLOCK_SIZE = 1024 }; #if defined HAVE_IPP && (IPP_VERSION_MAJOR >= 7) #define ARITHM_USE_IPP 1 #define IF_IPP(then_call, else_call) then_call #else #define ARITHM_USE_IPP 0 #define IF_IPP(then_call, else_call) else_call #endif inline bool checkScalar(const Mat& sc, int atype, int sckind, int akind) { if( sc.dims > 2 || !sc.isContinuous() ) return false; Size sz = sc.size(); if(sz.width != 1 && sz.height != 1) return false; int cn = CV_MAT_CN(atype); if( akind == _InputArray::MATX && sckind != _InputArray::MATX ) return false; return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) || (sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4); } inline bool checkScalar(InputArray sc, int atype, int sckind, int akind) { if( sc.dims() > 2 || !sc.isContinuous() ) return false; Size sz = sc.size(); if(sz.width != 1 && sz.height != 1) return false; int cn = CV_MAT_CN(atype); if( akind == _InputArray::MATX && sckind != _InputArray::MATX ) return false; return sz == Size(1, 1) || sz == Size(1, cn) || sz == Size(cn, 1) || (sz == Size(1, 4) && sc.type() == CV_64F && cn <= 4); } void convertAndUnrollScalar( const Mat& sc, int buftype, uchar* scbuf, size_t blocksize ); struct CoreTLSData { CoreTLSData() : device(0), useOpenCL(-1) {} RNG rng; int device; ocl::Queue oclQueue; int useOpenCL; // 1 - use, 0 - do not use, -1 - auto/not initialized }; extern TLSData<CoreTLSData> coreTlsData; #if defined(BUILD_SHARED_LIBS) #if defined WIN32 || defined _WIN32 || defined WINCE #define CL_RUNTIME_EXPORT __declspec(dllexport) #elif defined __GNUC__ && __GNUC__ >= 4 #define CL_RUNTIME_EXPORT __attribute__ ((visibility ("default"))) #else #define CL_RUNTIME_EXPORT #endif #else #define CL_RUNTIME_EXPORT #endif extern bool __termination; // skip some cleanups, because process is terminating // (for example, if ExitProcess() was already called) } #endif /*_CXCORE_INTERNAL_H_*/
/* Copyright (C) 2013-2014 by Kristina Simpson <sweet.kristas@gmail.com> This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgement in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #pragma comment(lib, "opengl32") #pragma comment(lib, "glu32") #pragma comment(lib, "glew32") #include <numeric> #include <GL/glew.h> #include "asserts.hpp" #include "AttributeSetOGL.hpp" #include "BlendOGL.hpp" #include "CameraObject.hpp" #include "ColorScope.hpp" #include "CanvasOGL.hpp" #include "ClipScopeOGL.hpp" #include "DisplayDeviceOGL.hpp" #include "EffectsOGL.hpp" #include "FboOGL.hpp" #include "LightObject.hpp" #include "ModelMatrixScope.hpp" #include "ScissorOGL.hpp" #include "ShadersOGL.hpp" #include "StencilScopeOGL.hpp" #include "TextureOGL.hpp" #include "WindowManager.hpp" namespace KRE { namespace { static DisplayDeviceRegistrar<DisplayDeviceOpenGL> ogl_register("opengl"); CameraPtr& get_default_camera() { static CameraPtr res = nullptr; return res; } rect& get_current_viewport() { static rect res; return res; } bool& get_current_depth_enable() { static bool depth_enable = false; return depth_enable; } bool& get_current_depth_write() { static bool depth_write = false; return depth_write; } GLenum convert_drawing_mode(DrawMode dm) { switch(dm) { case DrawMode::POINTS: return GL_POINTS; case DrawMode::LINE_STRIP: return GL_LINE_STRIP; case DrawMode::LINE_LOOP: return GL_LINE_LOOP; case DrawMode::LINES: return GL_LINES; case DrawMode::TRIANGLE_STRIP: return GL_TRIANGLE_STRIP; case DrawMode::TRIANGLE_FAN: return GL_TRIANGLE_FAN; case DrawMode::TRIANGLES: return GL_TRIANGLES; case DrawMode::QUAD_STRIP: return GL_QUAD_STRIP; case DrawMode::QUADS: return GL_QUADS; case DrawMode::POLYGON: return GL_POLYGON; } ASSERT_LOG(false, "Unrecognised value for drawing mode."); return GL_NONE; } GLenum convert_index_type(IndexType it) { switch(it) { case IndexType::INDEX_NONE: break; case IndexType::INDEX_UCHAR: return GL_UNSIGNED_BYTE; case IndexType::INDEX_USHORT: return GL_UNSIGNED_SHORT; case IndexType::INDEX_ULONG: return GL_UNSIGNED_INT; } ASSERT_LOG(false, "Unrecognised value for index type."); return GL_NONE; } static const StencilSettings keep_stencil_settings(true, StencilFace::FRONT_AND_BACK, StencilFunc::EQUAL, 0xff, 0x01, 0x00, StencilOperation::KEEP, StencilOperation::KEEP, StencilOperation::KEEP); } DisplayDeviceOpenGL::DisplayDeviceOpenGL(WindowPtr wnd) : DisplayDevice(wnd), seperate_blend_equations_(false), have_render_to_texture_(false), npot_textures_(false), hardware_uniform_buffers_(false), major_version_(0), minor_version_(0), max_texture_units_(-1) { } DisplayDeviceOpenGL::~DisplayDeviceOpenGL() { } void DisplayDeviceOpenGL::init(int width, int height) { GLenum err = glewInit(); ASSERT_LOG(err == GLEW_OK, "Could not initialise GLEW: " << glewGetErrorString(err)); glViewport(0, 0, width, height); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int extension_count = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &extension_count); if(major_version_ >= 3) { // Get extensions for(int n = 0; n != extension_count; ++n) { std::string ext(reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, n))); extensions_.emplace(ext); } } else { glGetError(); std::string exts(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS))); if(glGetError() == GL_NONE) { for(auto& ext : Util::split(exts, " ")) { extensions_.emplace(ext); } } else { LOG_ERROR("Couldn't get the GL extension list. Extension count=" << extension_count); } } seperate_blend_equations_ = extensions_.find("GL_EXT_blend_equation_separate") != extensions_.end(); have_render_to_texture_ = extensions_.find("GL_EXT_framebuffer_object") != extensions_.end(); npot_textures_ = extensions_.find("GL_ARB_texture_non_power_of_two") != extensions_.end(); hardware_uniform_buffers_ = extensions_.find("GL_ARB_uniform_buffer_object") != extensions_.end(); glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &max_texture_units_); if((err = glGetError()) != GL_NONE) { LOG_ERROR("Failed query for GL_MAX_TEXTURE_IMAGE_UNITS: 0x" << std::hex << err); } glGetIntegerv(GL_MINOR_VERSION, &minor_version_); glGetIntegerv(GL_MAJOR_VERSION, &major_version_); if((err = glGetError()) != GL_NONE) { const char* version_str = reinterpret_cast<const char*>(glGetString(GL_VERSION)); std::stringstream ss(version_str); float vers; ss >> vers; float integral; minor_version_ = static_cast<int>(std::modf(vers, &integral) * 100.0f); major_version_ = static_cast<int>(integral); } glEnable(GL_POINT_SPRITE); } void DisplayDeviceOpenGL::printDeviceInfo() { if(minor_version_ == 0 && major_version_ == 0) { // fall-back to old glGetStrings method. const char* version_str = reinterpret_cast<const char*>(glGetString(GL_VERSION)); LOG_INFO("OpenGL version: " << version_str); } else { LOG_INFO("OpenGL version: " << major_version_ << "." << minor_version_); } if(max_texture_units_ > 0) { LOG_INFO("Maximum texture units: " << max_texture_units_); } else { LOG_INFO("Maximum texture units: <<unknown>>" ); } const int max_line_width = 101; std::vector<std::string> lines; for(auto& ext : extensions_) { if(lines.empty()) { lines.emplace_back(std::string()); } if(ext.size() + lines.back().size() + 1 > max_line_width) { lines.emplace_back("\n" + ext); } else { lines.back() += (lines.back().empty() ? "" : " ") + ext; } } LOG_INFO("OpenGL Extensions: \n" << std::accumulate(lines.begin(), lines.end(), std::string())); } int DisplayDeviceOpenGL::queryParameteri(DisplayDeviceParameters param) { switch (param) { case DisplayDeviceParameters::MAX_TEXTURE_UNITS: return max_texture_units_; default: break; } ASSERT_LOG(false, "Invalid Parameter requested: " << static_cast<int>(param)); return -1; } void DisplayDeviceOpenGL::clearTextures() { OpenGLTexture::handleClearTextures(); } void DisplayDeviceOpenGL::clear(ClearFlags clr) { glClear((clr & ClearFlags::COLOR ? GL_COLOR_BUFFER_BIT : 0) | (clr & ClearFlags::DEPTH ? GL_DEPTH_BUFFER_BIT : 0) | (clr & ClearFlags::STENCIL ? GL_STENCIL_BUFFER_BIT : 0)); } void DisplayDeviceOpenGL::setClearColor(float r, float g, float b, float a) const { glClearColor(r, g, b, a); } void DisplayDeviceOpenGL::setClearColor(const Color& color) const { glClearColor(float(color.r()), float(color.g()), float(color.b()), float(color.a())); } void DisplayDeviceOpenGL::swap() { // This is a no-action. } ShaderProgramPtr DisplayDeviceOpenGL::getDefaultShader() { return OpenGL::ShaderProgram::defaultSystemShader(); } CameraPtr DisplayDeviceOpenGL::setDefaultCamera(const CameraPtr& cam) { auto old_cam = get_default_camera(); get_default_camera() = cam; return old_cam; } CameraPtr DisplayDeviceOpenGL::getDefaultCamera() const { return get_default_camera(); } void DisplayDeviceOpenGL::render(const Renderable* r) const { if(!r->isEnabled()) { // Renderable item not enabled then early return. return; } StencilScopePtr stencil_scope; if(r->hasClipSettings()) { ModelManager2D mm(static_cast<int>(r->getPosition().x), static_cast<int>(r->getPosition().y)); auto clip_shape = r->getStencilMask(); bool cam_set = false; if(clip_shape->getCamera() == nullptr && r->getCamera() != nullptr) { cam_set = true; clip_shape->setCamera(r->getCamera()); } stencil_scope.reset(new StencilScopeOGL(r->getStencilSettings())); glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glDepthMask(GL_FALSE); glClear(GL_STENCIL_BUFFER_BIT); render(clip_shape.get()); stencil_scope->applyNewSettings(keep_stencil_settings); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_TRUE); if(cam_set) { clip_shape->setCamera(nullptr); } } auto shader = r->getShader(); shader->makeActive(); BlendEquationScopeOGL be_scope(*r); BlendModeScopeOGL bm_scope(*r); // apply lighting/depth check/depth write here. bool use_lighting = r->isLightingStateSet() ? r->useLighting() : false; // Set the depth enable. if(r->isDepthEnableStateSet()) { if(get_current_depth_enable() != r->isDepthEnabled()) { if(r->isDepthEnabled()) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } get_current_depth_enable() = r->isDepthEnabled(); } } else { // We assume that depth is disabled if not specified. if(get_current_depth_enable() == true) { glDisable(GL_DEPTH_TEST); get_current_depth_enable() = false; } } glm::mat4 pmat(1.0f); glm::mat4 vmat(1.0f); if(r->getCamera()) { // set camera here. pmat = r->getCamera()->getProjectionMat(); vmat = r->getCamera()->getViewMat(); } else if(get_default_camera() != nullptr) { pmat = get_default_camera()->getProjectionMat(); vmat = get_default_camera()->getViewMat(); } if(use_lighting) { for(auto lp : r->getLights()) { /// xxx need to set lights here. } } if(r->getRenderTarget()) { r->getRenderTarget()->apply(); } if(shader->getPUniform() != ShaderProgram::INVALID_UNIFORM) { shader->setUniformValue(shader->getPUniform(), glm::value_ptr(pmat)); } if(shader->getMvUniform() != ShaderProgram::INVALID_UNIFORM) { glm::mat4 mvmat = vmat; if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) { mvmat *= get_global_model_matrix() * r->getModelMatrix(); } else { mvmat *= r->getModelMatrix(); } shader->setUniformValue(shader->getMvUniform(), glm::value_ptr(mvmat)); } if(shader->getMvpUniform() != ShaderProgram::INVALID_UNIFORM) { glm::mat4 pvmat(1.0f); if(is_global_model_matrix_valid() && !r->ignoreGlobalModelMatrix()) { pvmat = pmat * vmat * get_global_model_matrix() * r->getModelMatrix(); } else { pvmat = pmat * vmat * r->getModelMatrix(); } shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(pvmat)); } if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM) { if(r->isColorSet()) { shader->setUniformValue(shader->getColorUniform(), r->getColor().asFloatVector()); } else { shader->setUniformValue(shader->getColorUniform(), ColorScope::getCurrentColor().asFloatVector()); } } shader->setUniformsForTexture(r->getTexture()); // XXX we should make this either or with setting the mvp/color uniforms above. auto uniform_draw_fn = shader->getUniformDrawFunction(); if(uniform_draw_fn) { uniform_draw_fn(shader); } // Loop through uniform render variables and set them. /*for(auto& urv : r->UniformRenderVariables()) { for(auto& rvd : urv->VariableDescritionList()) { auto rvdd = std::dynamic_pointer_cast<RenderVariableDeviceData>(rvd->GetDisplayData()); ASSERT_LOG(rvdd != nullptr, "Unable to cast DeviceData to RenderVariableDeviceData."); shader->SetUniformValue(rvdd->GetActiveMapIterator(), urv->Value()); } }*/ // Need to figure the interaction with shaders. /// XXX Need to create a mapping between attributes and the index value below. for(auto as : r->getAttributeSet()) { if(!as->isEnabled()) { continue; } //ASSERT_LOG(as->getCount() > 0, "No (or negative) number of vertices in attribute set. " << as->getCount()); if((!as->isMultiDrawEnabled() && as->getCount() <= 0) || (as->isMultiDrawEnabled() && as->getMultiDrawCount() <= 0)) { //LOG_WARN("No (or negative) number of vertices in attribute set. " << as->getCount()); continue; } GLenum draw_mode = convert_drawing_mode(as->getDrawMode()); // apply blend, if any, from attribute set. BlendEquationScopeOGL be_scope(*as); BlendModeScopeOGL bm_scope(*as); if(shader->getColorUniform() != ShaderProgram::INVALID_UNIFORM && as->isColorSet()) { shader->setUniformValue(shader->getColorUniform(), as->getColor().asFloatVector()); } for(auto& attr : as->getAttributes()) { if(attr->isEnabled()) { shader->applyAttribute(attr); } } if(as->isInstanced()) { if(as->isIndexed()) { as->bindIndex(); // XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset() glDrawElementsInstanced(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray(), as->getInstanceCount()); as->unbindIndex(); } else { glDrawArraysInstanced(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount()), as->getInstanceCount()); } } else { if(as->isIndexed()) { as->bindIndex(); // XXX as->GetIndexArray() should be as->GetIndexArray()+as->GetOffset() glDrawElements(draw_mode, static_cast<GLsizei>(as->getCount()), convert_index_type(as->getIndexType()), as->getIndexArray()); as->unbindIndex(); } else { if(as->isMultiDrawEnabled()) { glMultiDrawArrays(draw_mode, as->getMultiOffsetArray().data(), as->getMultiCountArray().data(), as->getMultiDrawCount()); } else { glDrawArrays(draw_mode, static_cast<GLint>(as->getOffset()), static_cast<GLsizei>(as->getCount())); } } } shader->cleanUpAfterDraw(); glBindBuffer(GL_ARRAY_BUFFER, 0); } if(r->getRenderTarget()) { r->getRenderTarget()->unapply(); } } ScissorPtr DisplayDeviceOpenGL::getScissor(const rect& r) { auto scissor = new ScissorOGL(r); return ScissorPtr(scissor); } TexturePtr DisplayDeviceOpenGL::handleCreateTexture(const SurfacePtr& surface, const variant& node) { std::vector<SurfacePtr> surfaces; if(surface != nullptr) { surfaces.emplace_back(surface); } return std::make_shared<OpenGLTexture>(node, surfaces); } TexturePtr DisplayDeviceOpenGL::handleCreateTexture(const SurfacePtr& surface, TextureType type, int mipmap_levels) { std::vector<SurfacePtr> surfaces(1, surface); return std::make_shared<OpenGLTexture>(surfaces, type, mipmap_levels); } TexturePtr DisplayDeviceOpenGL::handleCreateTexture1D(int width, PixelFormat::PF fmt) { return std::make_shared<OpenGLTexture>(1, width, 0, 0, fmt, TextureType::TEXTURE_1D); } TexturePtr DisplayDeviceOpenGL::handleCreateTexture2D(int width, int height, PixelFormat::PF fmt) { // XXX make a static function PixelFormat::isPlanar or such. const int count = fmt == PixelFormat::PF::PIXELFORMAT_YV12 ? 3 : 1; return std::make_shared<OpenGLTexture>(count, width, height, 0, fmt, TextureType::TEXTURE_2D); } TexturePtr DisplayDeviceOpenGL::handleCreateTexture3D(int width, int height, int depth, PixelFormat::PF fmt) { return std::make_shared<OpenGLTexture>(1, width, height, depth, fmt, TextureType::TEXTURE_3D); } TexturePtr DisplayDeviceOpenGL::handleCreateTextureArray(int count, int width, int height, PixelFormat::PF fmt, TextureType type) { return std::make_shared<OpenGLTexture>(count, width, height, 0, fmt, type); } TexturePtr DisplayDeviceOpenGL::handleCreateTextureArray(const std::vector<SurfacePtr>& surfaces, const variant& node) { return std::make_shared<OpenGLTexture>(node, surfaces); } RenderTargetPtr DisplayDeviceOpenGL::handleCreateRenderTarget(int width, int height, int color_plane_count, bool depth, bool stencil, bool use_multi_sampling, int multi_samples) { return std::make_shared<FboOpenGL>(width, height, color_plane_count, depth, stencil, use_multi_sampling, multi_samples); } RenderTargetPtr DisplayDeviceOpenGL::handleCreateRenderTarget(const variant& node) { return std::make_shared<FboOpenGL>(node); } AttributeSetPtr DisplayDeviceOpenGL::handleCreateAttributeSet(bool indexed, bool instanced) { return std::make_shared<AttributeSetOGL>(indexed, instanced); } HardwareAttributePtr DisplayDeviceOpenGL::handleCreateAttribute(AttributeBase* parent) { return std::make_shared<HardwareAttributeOGL>(parent); } CanvasPtr DisplayDeviceOpenGL::getCanvas() { return CanvasOGL::getInstance(); } ClipScopePtr DisplayDeviceOpenGL::createClipScope(const rect& r) { return ClipScopePtr(new ClipScopeOGL(r)); } ClipShapeScopePtr DisplayDeviceOpenGL::createClipShapeScope(const RenderablePtr& r) { return ClipShapeScopePtr(new ClipShapeScopeOGL(r)); } StencilScopePtr DisplayDeviceOpenGL::createStencilScope(const StencilSettings& settings) { auto ss = new StencilScopeOGL(settings); return StencilScopePtr(ss); } BlendEquationImplBasePtr DisplayDeviceOpenGL::getBlendEquationImpl() { return BlendEquationImplBasePtr(new BlendEquationImplOGL()); } void DisplayDeviceOpenGL::setViewPort(int x, int y, int width, int height) { rect new_vp(x, y, width, height); if(get_current_viewport() != new_vp && width != 0 && height != 0) { get_current_viewport() = new_vp; // N.B. glViewPort has the origin in the bottom-left corner. glViewport(x, y, width, height); } } void DisplayDeviceOpenGL::setViewPort(const rect& vp) { if(get_current_viewport() != vp && vp.w() != 0 && vp.h() != 0) { get_current_viewport() = vp; // N.B. glViewPort has the origin in the bottom-left corner. glViewport(vp.x(), vp.y(), vp.w(), vp.h()); } } const rect& DisplayDeviceOpenGL::getViewPort() const { return get_current_viewport(); } bool DisplayDeviceOpenGL::doCheckForFeature(DisplayDeviceCapabilties cap) { bool ret_val = false; switch(cap) { case DisplayDeviceCapabilties::NPOT_TEXTURES: return npot_textures_; case DisplayDeviceCapabilties::BLEND_EQUATION_SEPERATE: return seperate_blend_equations_; case DisplayDeviceCapabilties::RENDER_TO_TEXTURE: return have_render_to_texture_; case DisplayDeviceCapabilties::SHADERS: return true; case DisplayDeviceCapabilties::UNIFORM_BUFFERS: return hardware_uniform_buffers_; default: ASSERT_LOG(false, "Unknown value for DisplayDeviceCapabilties given."); } return ret_val; } void DisplayDeviceOpenGL::loadShadersFromVariant(const variant& node) { OpenGL::ShaderProgram::loadShadersFromVariant(node); } ShaderProgramPtr DisplayDeviceOpenGL::getShaderProgram(const std::string& name) { return OpenGL::ShaderProgram::factory(name); } ShaderProgramPtr DisplayDeviceOpenGL::getShaderProgram(const variant& node) { return OpenGL::ShaderProgram::factory(node); } ShaderProgramPtr DisplayDeviceOpenGL::createShader(const std::string& name, const std::vector<ShaderData>& shader_data, const std::vector<ActiveMapping>& uniform_map, const std::vector<ActiveMapping>& attribute_map) { return OpenGL::ShaderProgram::createShader(name, shader_data, uniform_map, attribute_map); } // XXX Need a way to deal with blits with Camera/Lighting. void DisplayDeviceOpenGL::doBlitTexture(const TexturePtr& tex, int dstx, int dsty, int dstw, int dsth, float rotation, int srcx, int srcy, int srcw, int srch) { ASSERT_LOG(false, "DisplayDevice::doBlitTexture deprecated"); ASSERT_LOG(!tex, "Texture passed in was not of expected type."); const float tx1 = float(srcx) / tex->width(); const float ty1 = float(srcy) / tex->height(); const float tx2 = srcw == 0 ? 1.0f : float(srcx + srcw) / tex->width(); const float ty2 = srch == 0 ? 1.0f : float(srcy + srch) / tex->height(); const float uv_coords[] = { tx1, ty1, tx2, ty1, tx1, ty2, tx2, ty2, }; const float vx1 = float(dstx); const float vy1 = float(dsty); const float vx2 = float(dstx + dstw); const float vy2 = float(dsty + dsth); const float vtx_coords[] = { vx1, vy1, vx2, vy1, vx1, vy2, vx2, vy2, }; // Apply blend mode from texture if there is any. BlendEquationScopeOGL be_scope(*tex); BlendModeScopeOGL bm_scope(*tex); glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), glm::radians(rotation), glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f)); glm::mat4 mvp = glm::ortho(0.0f, 800.0f, 600.0f, 0.0f) * model; auto shader = OpenGL::ShaderProgram::defaultSystemShader(); shader->makeActive(); getDefaultShader()->setUniformsForTexture(tex); shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp)); shader->setUniformValue(shader->getColorUniform(), glm::value_ptr(glm::vec4(1.0f,1.0f,1.0f,1.0f))); // XXX the following line are only temporary, obviously. //shader->setUniformValue(shader->getUniform("discard"), 0); glEnableVertexAttribArray(shader->getVertexAttribute()); glVertexAttribPointer(shader->getVertexAttribute(), 2, GL_FLOAT, GL_FALSE, 0, vtx_coords); glEnableVertexAttribArray(shader->getTexcoordAttribute()); glVertexAttribPointer(shader->getTexcoordAttribute(), 2, GL_FLOAT, GL_FALSE, 0, uv_coords); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(shader->getTexcoordAttribute()); glDisableVertexAttribArray(shader->getVertexAttribute()); } namespace { GLenum convert_read_format(ReadFormat fmt) { switch(fmt) { case ReadFormat::DEPTH: return GL_DEPTH_COMPONENT; case ReadFormat::STENCIL: return GL_STENCIL_INDEX; case ReadFormat::DEPTH_STENCIL: return GL_DEPTH_STENCIL; case ReadFormat::RED: return GL_RED; case ReadFormat::GREEN: return GL_GREEN; case ReadFormat::BLUE: return GL_BLUE; case ReadFormat::RG: return GL_RG; case ReadFormat::RGB: return GL_RGB; case ReadFormat::BGR: return GL_BGR; case ReadFormat::RGBA: return GL_RGBA; case ReadFormat::BGRA: return GL_BGRA; case ReadFormat::RED_INT: return GL_RED_INTEGER; case ReadFormat::GREEN_INT: return GL_GREEN_INTEGER; case ReadFormat::BLUE_INT: return GL_BLUE_INTEGER; case ReadFormat::RG_INT: return GL_RG_INTEGER; case ReadFormat::RGB_INT: return GL_RGB_INTEGER; case ReadFormat::BGR_INT: return GL_BGR_INTEGER; case ReadFormat::RGBA_INT: return GL_RGBA_INTEGER; case ReadFormat::BGRA_INT: return GL_BGRA_INTEGER; default: break; } ASSERT_LOG(false, "Unrecognised ReadFormat: " << static_cast<int>(fmt)); return GL_NONE; } GLenum convert_attr_format(AttrFormat type) { switch(type) { case AttrFormat::BOOL: return GL_BOOL; case AttrFormat::HALF_FLOAT: return GL_HALF_FLOAT; case AttrFormat::FLOAT: return GL_FLOAT; case AttrFormat::DOUBLE: return GL_DOUBLE; case AttrFormat::FIXED: return GL_FIXED; case AttrFormat::SHORT: return GL_SHORT; case AttrFormat::UNSIGNED_SHORT: return GL_UNSIGNED_SHORT; case AttrFormat::BYTE: return GL_BYTE; case AttrFormat::UNSIGNED_BYTE: return GL_UNSIGNED_BYTE; case AttrFormat::INT: return GL_INT; case AttrFormat::UNSIGNED_INT: return GL_UNSIGNED_INT; case AttrFormat::INT_2_10_10_10_REV: return GL_INT_2_10_10_10_REV; case AttrFormat::UNSIGNED_INT_2_10_10_10_REV: return GL_UNSIGNED_INT_2_10_10_10_REV; case AttrFormat::UNSIGNED_INT_10F_11F_11F_REV: return GL_UNSIGNED_INT_10F_11F_11F_REV; default: break; } ASSERT_LOG(false, "Unrecognised AttrFormat: " << static_cast<int>(type)); return GL_NONE; } } bool DisplayDeviceOpenGL::handleReadPixels(int x, int y, unsigned width, unsigned height, ReadFormat fmt, AttrFormat type, void* data, int stride) { ASSERT_LOG(width > 0 && height > 0, "Width or height was negative: " << width << " x " << height); LOG_DEBUG("row_pitch: " << stride); std::vector<uint8_t> new_data; new_data.resize(height * stride); //if(pixel_size != 4) { // glPixelStorei(GL_PACK_ALIGNMENT, 1); //} //glPixelStorei(GL_PACK_ALIGNMENT, 4); LOG_DEBUG("before read pixels"); glReadPixels(x, y, static_cast<int>(width), static_cast<int>(height), convert_read_format(fmt), convert_attr_format(type), &new_data[0]); LOG_DEBUG("after read pixels"); GLenum ok = glGetError(); if(ok != GL_NONE) { LOG_ERROR("Unable to read pixels error was: " << ok); return false; } LOG_DEBUG("before copy"); uint8_t* cp_data = reinterpret_cast<uint8_t*>(data); for(auto it = new_data.begin() + (height-1)*stride; it != new_data.begin(); it -= stride) { std::copy(it, it + stride, cp_data); cp_data += stride; } LOG_DEBUG("after copy"); return true; } EffectPtr DisplayDeviceOpenGL::createEffect(const variant& node) { ASSERT_LOG(node.has_key("type") && node["type"].is_string(), "Effects must have 'type' attribute as string: " << node.to_debug_string()); const std::string& type = node["type"].as_string(); if(type == "stipple") { return std::make_shared<OpenGL::StippleEffect>(node); } // XXX Add more effects here as and if needed. return EffectPtr(); } ShaderProgramPtr DisplayDeviceOpenGL::createGaussianShader(int radius) { return OpenGL::ShaderProgram::createGaussianShader(radius); } }
// Copyright 2019 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 "fuchsia/base/message_port.h" #include <stdint.h> #include <lib/fidl/cpp/binding.h> #include <lib/fit/function.h> #include <memory> #include <string> #include <utility> #include <vector> #include "base/bind.h" #include "base/check.h" #include "base/containers/circular_deque.h" #include "base/fuchsia/fuchsia_logging.h" #include "base/macros.h" #include "fuchsia/base/mem_buffer_util.h" namespace cr_fuchsia { namespace { using BlinkMessage = blink::WebMessagePort::Message; // Converts a fuchsia::web::WebMessage to a BlinkMessage. // An empty result indicates that conversion was successful. // Data validation errors are returned as a FrameError. absl::optional<fuchsia::web::FrameError> BlinkMessageFromFidl( fuchsia::web::WebMessage fidl_message, BlinkMessage* blink_message) { if (!fidl_message.has_data()) { return fuchsia::web::FrameError::NO_DATA_IN_MESSAGE; } std::u16string data_utf16; if (!cr_fuchsia::ReadUTF8FromVMOAsUTF16(fidl_message.data(), &data_utf16)) { return fuchsia::web::FrameError::BUFFER_NOT_UTF8; } blink_message->data = data_utf16; if (fidl_message.has_outgoing_transfer() && fidl_message.has_incoming_transfer()) { DLOG(WARNING) << "WebMessage may only have incoming or outgoing transfer."; return fuchsia::web::FrameError::INTERNAL_ERROR; } if (fidl_message.has_outgoing_transfer()) { for (fuchsia::web::OutgoingTransferable& transferrable : *fidl_message.mutable_outgoing_transfer()) { if (!transferrable.is_message_port()) return fuchsia::web::FrameError::INTERNAL_ERROR; blink_message->ports.push_back( BlinkMessagePortFromFidl(std::move(transferrable.message_port()))); } } else if (fidl_message.has_incoming_transfer()) { for (fuchsia::web::IncomingTransferable& transferrable : *fidl_message.mutable_incoming_transfer()) { if (!transferrable.is_message_port()) return fuchsia::web::FrameError::INTERNAL_ERROR; blink_message->ports.push_back( BlinkMessagePortFromFidl(std::move(transferrable.message_port()))); } } return absl::nullopt; } // Defines a MessagePortAdapter, which translates and routes messages between a // FIDL MessagePort and a blink::WebMessagePort. Every MessagePortAdapter has // exactly one FIDL MessagePort and one blink::WebMessagePort. // // MessagePortAdapter instances are self-managed; they destroy themselves when // the connection is terminated from either the Blink or FIDL side. class MessagePortAdapter : public blink::WebMessagePort::MessageReceiver { protected: explicit MessagePortAdapter(blink::WebMessagePort blink_port) : blink_port_(std::move(blink_port)) { blink_port_.SetReceiver(this, base::ThreadTaskRunnerHandle::Get()); } ~MessagePortAdapter() override = default; // Deletes |this|, implicitly disconnecting the FIDL and Blink ports. void Destroy() { delete this; } // Sends a message to |blink_port_|. void SendBlinkMessage(BlinkMessage message) { CHECK(blink_port_.PostMessage(std::move(message))); } // Called when a Blink message was received through |blink_port_|. virtual void DeliverMessageToFidl() = 0; // Returns the next messagefrom Blink, or an empty value if there // are no more messages in the incoming queue. absl::optional<fuchsia::web::WebMessage> GetNextBlinkMessage() { if (message_queue_.empty()) return absl::nullopt; return std::move(message_queue_.front()); } void OnDeliverMessageToFidlComplete() { DCHECK(!message_queue_.empty()); message_queue_.pop_front(); } private: // blink::WebMessagePort::MessageReceiver implementation: bool OnMessage(BlinkMessage message) override { absl::optional<fuchsia::web::WebMessage> message_converted = FidlWebMessageFromBlink(std::move(message), TransferableHostType::kLocal); if (!message_converted) { DLOG(ERROR) << "Couldn't decode WebMessage from blink::WebMessagePort."; Destroy(); return false; } message_queue_.emplace_back(std::move(*message_converted)); // Start draining the queue if it was empty beforehand. if (message_queue_.size() == 1u) DeliverMessageToFidl(); return true; } // blink::WebMessagePort::MessageReceiver implementation: void OnPipeError() override { Destroy(); } base::circular_deque<fuchsia::web::WebMessage> message_queue_; blink::WebMessagePort blink_port_; DISALLOW_COPY_AND_ASSIGN(MessagePortAdapter); }; // Binds a handle to a remote MessagePort to a blink::WebMessagePort. class FidlMessagePortClientAdapter : public MessagePortAdapter { public: FidlMessagePortClientAdapter( blink::WebMessagePort blink_port, fidl::InterfaceHandle<fuchsia::web::MessagePort> fidl_port) : MessagePortAdapter(std::move(blink_port)), port_(fidl_port.Bind()) { ReadMessageFromFidl(); port_.set_error_handler([this](zx_status_t status) { ZX_LOG_IF(ERROR, status != ZX_ERR_PEER_CLOSED && status != ZX_ERR_CANCELED, status) << " MessagePort disconnected."; Destroy(); }); } fidl::InterfaceRequest<fuchsia::web::MessagePort> NewRequest() { return port_.NewRequest(); } private: ~FidlMessagePortClientAdapter() override = default; void ReadMessageFromFidl() { port_->ReceiveMessage(fit::bind_member( this, &FidlMessagePortClientAdapter::OnMessageReceived)); } void OnMessageReceived(fuchsia::web::WebMessage message) { BlinkMessage blink_message; absl::optional<fuchsia::web::FrameError> result = BlinkMessageFromFidl(std::move(message), &blink_message); if (result) { LOG(WARNING) << "Received bad message, error: " << static_cast<int32_t>(*result); Destroy(); return; } SendBlinkMessage(std::move(blink_message)); ReadMessageFromFidl(); } void OnMessagePosted(fuchsia::web::MessagePort_PostMessage_Result result) { if (result.is_err()) { LOG(ERROR) << "PostMessage failed, reason: " << static_cast<int32_t>(result.err()); Destroy(); return; } DeliverMessageToFidl(); } // cr_fuchsia::MessagePortAdapter implementation. void DeliverMessageToFidl() override { absl::optional<fuchsia::web::WebMessage> message = GetNextBlinkMessage(); if (!message) return; port_->PostMessage( std::move(*message), fit::bind_member(this, &FidlMessagePortClientAdapter::OnMessagePosted)); OnDeliverMessageToFidlComplete(); } fuchsia::web::MessagePortPtr port_; DISALLOW_COPY_AND_ASSIGN(FidlMessagePortClientAdapter); }; // Binds a MessagePort FIDL service from a blink::WebMessagePort. class FidlMessagePortServerAdapter : public fuchsia::web::MessagePort, public MessagePortAdapter { public: explicit FidlMessagePortServerAdapter(blink::WebMessagePort blink_port) : cr_fuchsia::MessagePortAdapter(std::move(blink_port)), binding_(this) { binding_.set_error_handler([this](zx_status_t status) { ZX_LOG_IF(ERROR, status != ZX_ERR_PEER_CLOSED && status != ZX_ERR_CANCELED, status) << " MessagePort disconnected."; Destroy(); }); } FidlMessagePortServerAdapter( blink::WebMessagePort blink_port, fidl::InterfaceRequest<fuchsia::web::MessagePort> request) : FidlMessagePortServerAdapter(std::move(blink_port)) { binding_.Bind(std::move(request)); } fidl::InterfaceHandle<fuchsia::web::MessagePort> NewBinding() { return binding_.NewBinding(); } private: ~FidlMessagePortServerAdapter() override = default; // cr_fuchsia::MessagePortAdapter implementation. void DeliverMessageToFidl() override { // Do nothing if the client hasn't requested a read, or if there's nothing // to read. if (!pending_receive_message_callback_) return; absl::optional<fuchsia::web::WebMessage> message = GetNextBlinkMessage(); if (!message) return; pending_receive_message_callback_(std::move(*message)); pending_receive_message_callback_ = {}; OnDeliverMessageToFidlComplete(); } // fuchsia::web::MessagePort implementation. void PostMessage(fuchsia::web::WebMessage message, PostMessageCallback callback) override { BlinkMessage blink_message; absl::optional<fuchsia::web::FrameError> status = BlinkMessageFromFidl(std::move(message), &blink_message); if (status) { LOG(ERROR) << "Error when reading message from FIDL: " << static_cast<int32_t>(*status); Destroy(); return; } SendBlinkMessage(std::move(blink_message)); fuchsia::web::MessagePort_PostMessage_Result result; result.set_response(fuchsia::web::MessagePort_PostMessage_Response()); callback(std::move(result)); } void ReceiveMessage(ReceiveMessageCallback callback) override { if (pending_receive_message_callback_) { LOG(WARNING) << "ReceiveMessage called multiple times without acknowledgement."; Destroy(); return; } pending_receive_message_callback_ = std::move(callback); DeliverMessageToFidl(); } PostMessageCallback post_message_ack_; ReceiveMessageCallback pending_receive_message_callback_; fidl::Binding<fuchsia::web::MessagePort> binding_; DISALLOW_COPY_AND_ASSIGN(FidlMessagePortServerAdapter); }; fidl::InterfaceRequest<fuchsia::web::MessagePort> RemoteFidlMessagePortFromBlink(blink::WebMessagePort blink_port) { fidl::InterfaceHandle<fuchsia::web::MessagePort> fidl_handle; auto request = fidl_handle.NewRequest(); new FidlMessagePortClientAdapter(std::move(blink_port), std::move(fidl_handle)); return request; } } // namespace // Methods for constructing MessagePortAdapters for various port types and // origins. The adapters manage their own lifetimes and will self-delete when // either endpoint of their channels are disconnected. blink::WebMessagePort BlinkMessagePortFromFidl( fidl::InterfaceRequest<fuchsia::web::MessagePort> fidl_port) { auto port_pair = blink::WebMessagePort::CreatePair(); new FidlMessagePortServerAdapter(std::move(port_pair.first), std::move(fidl_port)); return std::move(port_pair.second); } blink::WebMessagePort BlinkMessagePortFromFidl( fidl::InterfaceHandle<fuchsia::web::MessagePort> fidl_port) { auto port_pair = blink::WebMessagePort::CreatePair(); new FidlMessagePortClientAdapter(std::move(port_pair.first), std::move(fidl_port)); return std::move(port_pair.second); } fidl::InterfaceHandle<fuchsia::web::MessagePort> FidlMessagePortFromBlink( blink::WebMessagePort blink_port) { auto* adapter = new FidlMessagePortServerAdapter(std::move(blink_port)); return adapter->NewBinding(); } absl::optional<fuchsia::web::WebMessage> FidlWebMessageFromBlink( BlinkMessage blink_message, TransferableHostType port_type) { fuchsia::web::WebMessage fidl_message; if (!blink_message.ports.empty()) { switch (port_type) { case TransferableHostType::kLocal: for (blink::WebMessagePort& port : blink_message.ports) { fuchsia::web::IncomingTransferable incoming; incoming.set_message_port(FidlMessagePortFromBlink(std::move(port))); fidl_message.mutable_incoming_transfer()->push_back( std::move(incoming)); } break; case TransferableHostType::kRemote: for (blink::WebMessagePort& port : blink_message.ports) { fuchsia::web::OutgoingTransferable outgoing; outgoing.set_message_port( RemoteFidlMessagePortFromBlink(std::move(port))); fidl_message.mutable_outgoing_transfer()->push_back( std::move(outgoing)); } break; } blink_message.ports.clear(); } std::u16string data_utf16 = std::move(blink_message.data); std::string data_utf8; if (!base::UTF16ToUTF8(data_utf16.data(), data_utf16.size(), &data_utf8)) return absl::nullopt; base::STLClearObject(&data_utf16); constexpr char kBufferVmoName[] = "cr-web-message-from-blink"; fuchsia::mem::Buffer data_buffer = cr_fuchsia::MemBufferFromString(data_utf8, kBufferVmoName); if (!data_buffer.vmo) return absl::nullopt; fidl_message.set_data(std::move(data_buffer)); return fidl_message; } } // namespace cr_fuchsia
#include <string> #include "core/compiler.h" #include "gtest/gtest.h" #include "tests/util/util.h" #include "torch/csrc/jit/ir/irparser.h" TEST(Converters, ATenSoftmax1DConvertsCorrectly) { const auto graph = R"IR( graph(%0 : Tensor): %1 : None = prim::Constant() %2 : int = prim::Constant[value=0]() %3 : Tensor = aten::softmax(%0, %2, %1) return (%3))IR"; auto g = std::make_shared<torch::jit::Graph>(); torch::jit::parseIR(graph, &*g); auto in = at::randint(0, 5, {5}, {at::kCUDA}); auto params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto jit_results = trtorch::tests::util::RunGraph(g, params, {in}); in = at::clone(in); params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto trt_results = trtorch::tests::util::RunGraphEngine(g, params, {in}); auto trt = trt_results[0].reshape_as(jit_results[0]); ASSERT_TRUE(trtorch::tests::util::almostEqual(jit_results[0], trt, 2e-6)); } TEST(Converters, ATenSoftmaxNDConvertsCorrectlySub3DIndex) { const auto graph = R"IR( graph(%0 : Tensor): %1 : None = prim::Constant() %2 : int = prim::Constant[value=1]() %3 : Tensor = aten::softmax(%0, %2, %1) return (%3))IR"; auto g = std::make_shared<torch::jit::Graph>(); torch::jit::parseIR(graph, &*g); auto in = at::randint(0, 5, {1, 2, 2, 2, 2}, {at::kCUDA}); auto params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto jit_results = trtorch::tests::util::RunGraph(g, params, {in}); in = at::clone(in); params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto trt_results = trtorch::tests::util::RunGraphEngine(g, params, {in}); auto trt = trt_results[0].reshape_as(jit_results[0]); ASSERT_TRUE(trtorch::tests::util::almostEqual(jit_results[0], trt, 2e-6)); } TEST(Converters, ATenSoftmaxNDConvertsCorrectlyAbove3DIndex) { const auto graph = R"IR( graph(%0 : Tensor): %1 : None = prim::Constant() %2 : int = prim::Constant[value=3]() %3 : Tensor = aten::softmax(%0, %2, %1) return (%3))IR"; auto g = std::make_shared<torch::jit::Graph>(); torch::jit::parseIR(graph, &*g); auto in = at::randint(0, 5, {1, 2, 2, 2, 2}, {at::kCUDA}); auto jit_in = at::clone(in); auto params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto jit_results = trtorch::tests::util::RunGraph(g, params, {jit_in}); auto trt_in = at::clone(in); params = trtorch::core::conversion::get_named_params(g->inputs(), {}); auto trt_results = trtorch::tests::util::RunGraphEngine(g, params, {trt_in}); auto trt = trt_results[0].reshape_as(jit_results[0]); ASSERT_TRUE(trtorch::tests::util::almostEqual(jit_results[0], trt, 2e-6)); }
/* * Copyright (c) 2017 * FZI Forschungszentrum Informatik, Karlsruhe, Germany (www.fzi.de) * KIT, Institute of Measurement and Control, Karlsruhe, Germany (www.mrt.kit.edu) * 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. */ #pragma once #include <memory> #include <automated_driving_msgs/MotionState.h> #include <util_automated_driving_msgs/util_automated_driving_msgs.hpp> #ifndef Q_MOC_RUN #include <OGRE/OgreColourValue.h> #include <OGRE/OgreSceneManager.h> #include <OGRE/OgreSceneNode.h> #include <util_rviz/util_rviz.hpp> #include <util_rviz/util_rvizshapes.hpp> #include <rviz/ogre_helpers/arrow.h> #include <rviz/ogre_helpers/movable_text.h> #endif namespace motion_state_rviz_plugin_ros { class MotionStateVisual { public: struct Parameters { bool arrowShow{true}; float arrowVMin{1}; float arrowVMax{10}; float arrowLength{1}; bool textShow{true}; std::string textContent = ""; float textFontSize{1}; float textVMin{1}; bool textShowDebug{false}; Ogre::ColourValue color{Ogre::ColourValue::Black}; }; MotionStateVisual(Ogre::SceneManager* scene_manager, Ogre::SceneNode* parent_node, const Parameters& p); virtual ~MotionStateVisual(); // Configure the visual to show the data in the message. void setVisible(const bool visible); // Set the pose of the coordinate frame the message refers to. void setFramePosition(const Ogre::Vector3& position); void setFrameOrientation(const Ogre::Quaternion& orientation); void setParams(const Parameters& p); void makeArrow(const automated_driving_msgs::MotionState& ms); void makeText(const automated_driving_msgs::MotionState& ms); void updateColor(); private: // objects implementing the actual arrow shape boost::shared_ptr<rviz::Arrow> velocity_arrow_; // objects implementing the Car boost::shared_ptr<rviz::SimpleCar> car_; // object implementing the text boost::shared_ptr<rviz::MovableText> movable_text_; // A SceneNode whose pose is set to match the coordinate frame of // the MotionState message header. Ogre::SceneNode* frame_node_; // The SceneManager, kept here only so the destructor can ask it to // destroy the ``frame_node_``. Ogre::SceneManager* scene_manager_; Parameters params_; }; } // namespace motion_state_rviz_plugin_ros
/* * Copyright (c) 2014, Ford Motor Company * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following * disclaimer in the documentation and/or other materials provided with the * distribution. * * Neither the name of the Ford Motor Company nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <string> #include "gmock/gmock.h" #include "smart_objects/smart_object.h" namespace test { namespace components { namespace smart_object_test { using namespace ns_smart_device_link::ns_smart_objects; TEST(test_SmartObjectInvalidTest, simple_type_can_be_set_in_constructor) { SmartObject objMap(SmartType_Map); ASSERT_EQ(SmartType_Map, objMap.getType()); SmartObject objArray(SmartType_Array); ASSERT_EQ(SmartType_Array, objArray.getType()); SmartObject objInt(SmartType_Integer); ASSERT_EQ(SmartType_Integer, objInt.getType()); SmartObject objDouble(SmartType_Double); ASSERT_EQ(SmartType_Double, objDouble.getType()); SmartObject objBoolean(SmartType_Boolean); ASSERT_EQ(SmartType_Boolean, objBoolean.getType()); SmartObject objChar(SmartType_Character); ASSERT_EQ(SmartType_Character, objChar.getType()); SmartObject objString(SmartType_String); ASSERT_EQ(SmartType_String, objString.getType()); SmartObject objBinary(SmartType_Binary); ASSERT_EQ(SmartType_Binary, objBinary.getType()); SmartObject objInvalid(SmartType_Invalid); ASSERT_EQ(SmartType_Invalid, objInvalid.getType()); SmartObject objNullConstructor(SmartType_Null); ASSERT_EQ(SmartType_Null, objNullConstructor.getType()); SmartObject objNullDefault; ASSERT_EQ(SmartType_Null, objNullDefault.getType()); } TEST(test_SmartObjectInvalidTest, invalid_object_remains_invalid) { SmartObject obj(SmartType_Invalid); ASSERT_EQ(SmartType_Invalid, obj.getType()); obj = 1; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_int_value, obj.asInt()); // ---- unsigned int ---- // obj = static_cast<unsigned int>(100); ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_unsigned_int_value, obj.asUInt()); // ---- DOUBLE ---- // obj = 3.14; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_double_value, obj.asDouble()); // ---- CHAR ---- // obj = 'a'; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_char_value, obj.asChar()); // ---- BOOL ---- // obj = true; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_bool_value, obj.asBool()); // ---- CHAR* ---- // obj = "Hello, world"; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_string_value, obj.asString()); // ---- STD::STRING ---- // obj = std::string("Hello, world"); ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_string_value, obj.asString()); // ---- BINARY ---- // ns_smart_device_link::ns_smart_objects::SmartBinary binaryData; binaryData.push_back('\0'); binaryData.push_back('a'); obj = binaryData; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_binary_value, obj.asBinary()); // ---- ARRAY ---- // obj[0] = 1; obj[1] = true; obj[2] = 'a'; obj[3] = 3.14; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_int_value, obj[0].asInt()); ASSERT_EQ(invalid_bool_value, obj[1].asBool()); ASSERT_EQ(invalid_char_value, obj[2].asChar()); ASSERT_EQ(invalid_double_value, obj[3].asDouble()); // ---- DEEP ARRAY ---- // obj[0] = 1; obj[1][0] = 3.14; obj[1][1][0] = true; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_int_value, obj[0].asInt()); ASSERT_EQ(invalid_double_value, obj[1][0].asDouble()); ASSERT_EQ(invalid_bool_value, obj[1][1][0].asBool()); // ---- MAP ---- // obj["name"] = "My name"; obj["count"] = 10; obj["isValid"] = true; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_string_value, obj["name"].asString()); ASSERT_EQ(invalid_int_value, obj["count"].asInt()); ASSERT_EQ(invalid_bool_value, obj["isValid"].asBool()); // ---- DEEP MAP ---- // obj["request"]["name"] = "My Request"; obj["request"]["id"] = 123; obj["response"]["name"] = "My Response"; obj["response"]["id"] = 456; obj["we"]["need"]["to"]["go"]["deeper"] = true; ASSERT_EQ(SmartType_Invalid, obj.getType()); ASSERT_EQ(invalid_string_value, obj["request"]["name"].asString()); ASSERT_EQ(invalid_int_value, obj["request"]["id"].asInt()); ASSERT_EQ(invalid_string_value, obj["response"]["name"].asString()); ASSERT_EQ(invalid_int_value, obj["response"]["id"].asInt()); ASSERT_EQ(invalid_bool_value, obj["we"]["need"]["to"]["go"]["deeper"].asBool()); } } // namespace smart_object_test } // namespace components } // namespace test
#include "Precomp.h" #include "VulkanRenderer.h" using namespace ::CainEngine::Graphics; using namespace ::CainEngine::Graphics::Vulkan; VulkanRenderer::VulkanRenderer() { VkWin32SurfaceCreateInfoKHR }
#include<iostream> using namespace std; /* Priority Queue is nothing but logical arrangements of queues accroding to priority power. Two types of PQ could be: 1. Limited Element Set Priority - when number of priorities are limited like in OS - Element will be added to its corresponding priority queue - if the highest priority queue get empty then we go to next - if all pqs are empty then list is empty 2. Element Prirority - When number of prirorities unknown and each element brings its own priority. Two Ways: I. A. Enqueue Element as it comes - O(1) B. Dequeue element - O(2n) - Search for highest priority element - O(n) + Remove and shift elements - O(n) II. A. Enqueue Element in decreasing order of priority : O(n) B. Dequeue Last Element - O(1) In this program we will implement 1. */ /* Number of Priorities = 3; */ class Queue { private: int front; int rear; int size; char* Q; public: Queue(int); ~Queue(); bool isFull(); bool isEmpty(); void enqueue(char); char dequeue(); void display(); }; Queue::Queue(int size) { this->size = size; this->front = -1; this->rear = -1; this->Q = new char[this->size]; } Queue::~Queue() { delete[] Q; } bool Queue::isEmpty() { if(this->front == this->rear) return true; else return false; } bool Queue::isFull() { if(this->rear == this->size-1) return true; else return false; } void Queue::display() { for(int i=this->front+1;i<=this->rear;i++) { cout << this->Q[i] << " "; } } void Queue::enqueue(char x) { if(isFull()) { cout << "Queue is full. Can't enqueue" << endl; } else { this->rear++; this->Q[this->rear] = x; } } char Queue::dequeue() { char x = 0; if(isEmpty()) { cout << "Queue is empty." << endl; } else { this->front++; x=this->Q[this->front]; } return x; } void enqueue_pq(Queue* q1, Queue* q2, Queue* q3, char x, int priority) { switch (priority) { case 1: q1->enqueue(x); break; case 2: q2->enqueue(x); break; case 3: q3->enqueue(x); break; default: cout << "Invalid priority supplied" << endl; break; } } char dequeue_pq(Queue* q1, Queue* q2, Queue* q3) { if(!q1->isEmpty()) { return q1->dequeue(); } if(!q2->isEmpty()) { return q2->dequeue(); } if(!q3->isEmpty()) { return q3->dequeue(); } cout << "Priority Queue is EMPTY." << endl; return '0'; } void display_pq(Queue* q1, Queue* q2, Queue* q3) { q1->display(); q2->display(); q3->display(); } int main() { /* Number of priorities=3 */ Queue q1(10); Queue q2(10); Queue q3(10); //Enqueueing in PQ enqueue_pq(&q1,&q2,&q3,'A', 1); enqueue_pq(&q1,&q2,&q3,'B', 1); enqueue_pq(&q1,&q2,&q3,'C', 2); enqueue_pq(&q1,&q2,&q3,'D', 3); cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; enqueue_pq(&q1,&q2,&q3,'E', 2); enqueue_pq(&q1,&q2,&q3,'F', 1); enqueue_pq(&q1,&q2,&q3,'G', 2); enqueue_pq(&q1,&q2,&q3,'H', 3); enqueue_pq(&q1,&q2,&q3,'I', 2); enqueue_pq(&q1,&q2,&q3,'J', 2); enqueue_pq(&q1,&q2,&q3,'K', 3); display_pq(&q1,&q2,&q3); cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; cout << "Dequeued: " << dequeue_pq(&q1,&q2,&q3) << endl; display_pq(&q1,&q2,&q3); return 0; }
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *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 Redis 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. */ #ifndef SNAPSHOT_HPP_ #define SNAPSHOT_HPP_ #include <string> #include <deque> #include "common.hpp" #include "buffer/buffer_helper.hpp" #include "context.hpp" #include "db/codec.hpp" #include "db/db_utils.hpp" #include "thread/thread_mutex_lock.hpp" namespace ardb { enum SnapshotType { REDIS_DUMP = 1, ARDB_DUMP, BACKUP_DUMP }; enum SnapshotState { SNAPSHOT_INVALID = 0, DUMP_START = 1, DUMPING, DUMP_SUCCESS, DUMP_FAIL, LOAD_START = 10, LODING, LOAD_SUCCESS, LOAD_FAIL }; class Snapshot; typedef int SnapshotRoutine(SnapshotState state, Snapshot* snapshot, void* cb); class ObjectIO { protected: DBWriter* m_dbwriter; virtual bool Read(void* buf, size_t buflen, bool cksm = true) = 0; virtual int Write(const void* buf, size_t buflen) = 0; int WriteType(uint8 type); int WriteKeyType(KeyType type); int WriteLen(uint64 len); int WriteMillisecondTime(uint64 ts); int WriteDouble(double v); int WriteLongLongAsStringObject(long long value); int WriteRawString(const std::string& str); int WriteRawString(const char *s, size_t len); int WriteLzfStringObject(const char *s, size_t len); int WriteTime(time_t t); int WriteStringObject(const Data& o); int ReadType(); time_t ReadTime(); int64 ReadMillisecondTime(); uint64_t ReadLen(int *isencoded); bool ReadInteger(int enctype, int64& v); bool ReadLzfStringObject(std::string& str); bool ReadString(std::string& str); int ReadDoubleValue(double& val, bool binary = false); int ReadBinaryDoubleValue(double& val); int ReadBinaryFloatValue(float& val); bool RedisLoadCheckModuleValue(char* name); bool RedisLoadObject(Context& ctx, int type, const std::string& key, int64 expiretime); void RedisLoadListZipList(Context& ctx, unsigned char* data, const std::string& key, ValueObject& meta_value); void RedisLoadHashZipList(Context& ctx, unsigned char* data, const std::string& key, ValueObject& meta_value); void RedisLoadZSetZipList(Context& ctx, unsigned char* data, const std::string& key, ValueObject& meta_value); void RedisLoadSetIntSet(Context& ctx, unsigned char* data, const std::string& key, ValueObject& meta_value); void RedisWriteMagicHeader(); int ArdbWriteMagicHeader(); int ArdbLoadChunk(Context& ctx, int type); int ArdbLoadBuffer(Context& ctx, Buffer& buffer); DBWriter& GetDBWriter(); public: ObjectIO() : m_dbwriter(NULL) { } void SetDBWriter(DBWriter* writer) { m_dbwriter = writer; } int ArdbSaveRawKeyValue(const Slice& key, const Slice& value, Buffer& buffer, int64 ttl); int ArdbFlushWriteBuffer(Buffer& buffer); virtual ~ObjectIO() { } }; class ObjectBuffer: public ObjectIO { private: Buffer m_buffer; bool Read(void* buf, size_t buflen, bool cksm); int Write(const void* buf, size_t buflen); public: ObjectBuffer(); ObjectBuffer(const std::string& content); bool RedisSave(Context& ctx, const std::string& key, std::string& content, uint64* ttl = NULL); bool RedisLoad(Context& ctx, const std::string& key, int64 ttl); bool CheckReadPayload(); Buffer& GetInternalBuffer() { return m_buffer; } bool ArdbLoad(Context& ctx); void Reset() { m_buffer.Clear(); } }; class SnapshotManager; class Snapshot: public ObjectIO { protected: FILE* m_read_fp; FILE* m_write_fp; std::string m_file_path; uint64 m_cksm; SnapshotRoutine* m_routine_cb; void *m_routine_cbdata; uint64 m_processed_bytes; uint64 m_file_size; SnapshotState m_state; uint64 m_routinetime; char* m_read_buf; int64 m_expected_data_size; int64 m_writed_data_size; Buffer m_write_buffer; uint64 m_cached_repl_offset; uint64 m_cached_repl_cksm; time_t m_save_time; SnapshotType m_type; const void* m_engine_snapshot; bool Read(void* buf, size_t buflen, bool cksm); int RedisLoad(); int RedisSave(); int ArdbSave(); int ArdbLoad(); int BackupSave(); int BackupLoad(); int DoSave(); int BeforeSave(SnapshotType type, const std::string& file, SnapshotRoutine* cb, void *data); int AfterSave(const std::string& fname, int err); int PrepareSave(SnapshotType type, const std::string& file, SnapshotRoutine* cb, void *data); void VerifyState(); friend class SnapshotManager; public: Snapshot(); SnapshotType GetType() { return m_type; } uint64 CachedReplOffset() { return m_cached_repl_offset; } uint64 CachedReplCksm() { return m_cached_repl_cksm; } const std::string& GetPath() { return m_file_path; } time_t SaveTime() { return m_save_time; } bool IsSaving(); bool IsReady(); void MarkDumpComplete(); void SetExpectedDataSize(int64 size); int64 DumpLeftDataSize(); int64 ProcessLeftDataSize(); int Write(const void* buf, size_t buflen); int OpenWriteFile(const std::string& file); int OpenReadFile(const std::string& file); int SetFilePath(const std::string& path); int Load(const std::string& file, SnapshotRoutine* cb, void *data); int Reload(SnapshotRoutine* cb, void *data); int Save(SnapshotType type, const std::string& file, SnapshotRoutine* cb, void *data); int BGSave(SnapshotType type, const std::string& file, SnapshotRoutine* cb = NULL, void *data = NULL); void Flush(); void Remove(); int Rename(const std::string& default_file = "dump.rdb"); void Close(); void SetRoutineCallback(SnapshotRoutine* cb, void *data); void* GetIteratorByNamespace(Context& ctx, const Data& ns); ~Snapshot(); static SnapshotType GetSnapshotType(const std::string& file); static SnapshotType GetSnapshotTypeByName(const std::string& name); static std::string GetSyncSnapshotPath(SnapshotType type, uint64 offset, uint64 cksm); }; class SnapshotManager { private: typedef std::deque<Snapshot*> SnapshotArray; ThreadMutexLock m_snapshots_lock; SnapshotArray m_snapshots; public: SnapshotManager(); void Init(); void Routine(); Snapshot* GetSyncSnapshot(SnapshotType type, SnapshotRoutine* cb, void *data); Snapshot* NewSnapshot(SnapshotType type, bool bgsave, SnapshotRoutine* cb, void *data); void AddSnapshot(const std::string& path); time_t LastSave(); int CurrentSaverNum(); time_t LastSaveCost(); int LastSaveErr(); time_t LastSaveStartUnixTime(); void PrintSnapshotInfo(std::string& str); }; extern SnapshotManager* g_snapshot_manager; } #endif /* RDB_HPP_ */
#include "hooks/hooks.H" #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <bm/bm.h> #include "libdft_api.h" #include "tagmap.h" #include "pin.H" #include "provlog.H" #include "dtracker.H" #include "osutils.H" /* tracks whether path existed before the execution of syscall */ static struct { std::string pathname; int existed_before_syscall; } exist_status; /* * open(2)/creat(2) handlers * * Signatures: * int open(const char *pathname, int flags); * int open(const char *pathname, int flags, mode_t mode); * int creat(const char *pathname, mode_t mode); */ #define DEF_SYSCALL_OPEN #include "hooks/syscall_args.h" template<> void pre_open_hook<libdft_tag_ewah>(syscall_ctx_t *ctx) { /* Check the status of the pathname we are about to open/create. */ exist_status.pathname = std::string(_PATHNAME); exist_status.existed_before_syscall = path_exists(exist_status.pathname); //std::cerr << exist_status.pathname << std::endl; //std::cerr << exist_status.existed_before_syscall << std::endl; } template<> void post_open_hook<libdft_tag_ewah>(syscall_ctx_t *ctx) { /* not successful; optimized branch */ if (unlikely(_FD < 0)) { LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n"); return; } /* Resolve fd to full pathname. Use this instead of syscall argument. */ const std::string fdn = fdname(_FD); if ( !in_dtracker_whitelist(fdn) && !path_isdir(fdn) ) { const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD]; fdset.insert(_FD); int created = ( exist_status.existed_before_syscall != 1 && (_FLAGS & O_CREAT) && exist_status.pathname == std::string(_PATHNAME) ); LOG("OK " _CALL_LOG_STR + "\n"); LOG("INFO mapped fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n"); PROVLOG::open(ufd, fdn, _FLAGS, created); } else { LOG("INFO ignoring fd" + decstr(_FD) + " (" + fdn + ")\n"); } /* reset the exist_status */ exist_status.existed_before_syscall = 0; } #define UNDEF_SYSCALL_OPEN #include "hooks/syscall_args.h" /* * close(2) handler - updates watched fds * * Signature: int close(int fd); */ #define DEF_SYSCALL_CLOSE #include "hooks/syscall_args.h" template<> void post_close_hook<libdft_tag_ewah>(syscall_ctx_t *ctx) { /* not successful; optimized branch */ if (unlikely(_RET_STATUS < 0)) { LOG("ERROR " _CALL_LOG_STR + " (" + strerror(errno) + ")\n"); return; } LOG("OK " _CALL_LOG_STR + "\n"); std::set<int>::iterator it = fdset.find(_FD); if (it == fdset.end()) return; const PROVLOG::ufd_t ufd = PROVLOG::ufdmap[_FD]; fdset.erase(it); PROVLOG::ufdmap.del(_FD); if (IS_STDFD(_FD)) stdcount[_FD] = 0; LOG("INFO removed mapping fd" + decstr(_FD) + ":ufd" + decstr(ufd) + "\n"); PROVLOG::close(ufd); } #define UNDEF_SYSCALL_CLOSE #include "hooks/syscall_args.h" /* vim: set noet ts=4 sts=4 sw=4 ai : */
/* * Copyright (c) 2003-2020 Rony Shapiro <ronys@pwsafe.org>. * All rights reserved. Use of the code is allowed under the * Artistic License 2.0 terms, as specified in the LICENSE file * distributed with this code, or available from * http://www.opensource.org/licenses/artistic-license-2.0.php */ /** \file * Implementation of CUTF8Conv */ #include "UTF8Conv.h" #include "Util.h" #include "os/debug.h" #include "os/utf8conv.h" CUTF8Conv::~CUTF8Conv() { if (m_utf8 != nullptr) { trashMemory(m_utf8, m_utf8MaxLen * sizeof(m_utf8[0])); delete[] m_utf8; } if (m_wc != nullptr) { trashMemory(m_wc, m_wcMaxLen); delete[] m_wc; } if (m_tmp != nullptr) { trashMemory(m_tmp, m_tmpMaxLen * sizeof(m_tmp[0])); delete[] m_tmp; } } bool CUTF8Conv::ToUTF8(const StringX &data, const unsigned char *&utf8, size_t &utf8Len) { // If we're not in Unicode, call MultiByteToWideChar to get from // current codepage to Unicode, and then WideCharToMultiByte to // get to UTF-8 encoding. if (data.empty()) { utf8Len = 0; return true; } wchar_t *wcPtr = const_cast<wchar_t *>(data.c_str()); size_t wcLen = data.length()+1; // first get needed utf8 buffer size size_t mbLen = pws_os::wcstombs(nullptr, 0, wcPtr, wcLen); if (mbLen == 0) { // uh-oh ASSERT(0); m_utf8Len = 0; return false; } // Allocate buffer (if previous allocation was smaller) if (mbLen > m_utf8MaxLen) { if (m_utf8 != nullptr) trashMemory(m_utf8, m_utf8MaxLen); delete[] m_utf8; m_utf8 = new unsigned char[mbLen]; m_utf8MaxLen = mbLen; } // Finally get result m_utf8Len = pws_os::wcstombs(reinterpret_cast<char *>(m_utf8), mbLen, wcPtr, wcLen); ASSERT(m_utf8Len != 0); m_utf8Len--; // remove unneeded null termination utf8 = m_utf8; utf8Len = m_utf8Len; return true; } // In following, char * is managed by caller. bool CUTF8Conv::FromUTF8(const unsigned char *utf8, size_t utf8Len, StringX &data) { // Call MultiByteToWideChar to get from UTF-8 to Unicode. // If we're not in Unicode, call WideCharToMultiByte to // get to current codepage. // // Due to a bug in pre-3.08 versions, data may be in ACP // instead of UTF-8. We try to detect and workaround this. if (utf8Len == 0 || (utf8Len == 1 && utf8[0] == '\0')) { data = _T(""); return true; } ASSERT(utf8 != nullptr); // first get needed wide char buffer size size_t wcLen = pws_os::mbstowcs(nullptr, 0, reinterpret_cast<const char *>(utf8), size_t(-1), !m_cp_acp); if (wcLen == 0) { // uh-oh // it seems that this always returns non-zero, even if encoding // broken. Therefore, we'll give a conservative value here, // and try to recover later pws_os::Trace0(_T("FromUTF8: Couldn't get buffer size - guessing!")); wcLen = sizeof(StringX::value_type) * (utf8Len + 1); } // Allocate buffer (if previous allocation was smaller) if (wcLen > m_wcMaxLen) { if (m_wc != nullptr) trashMemory(m_wc, m_wcMaxLen); delete[] m_wc; m_wc = new wchar_t[wcLen]; m_wcMaxLen = wcLen; } // next translate to buffer wcLen = pws_os::mbstowcs(m_wc, wcLen, reinterpret_cast<const char *>(utf8), size_t(-1), !m_cp_acp); #ifdef _WIN32 if (wcLen == 0) { DWORD errCode = GetLastError(); switch (errCode) { case ERROR_INSUFFICIENT_BUFFER: pws_os::Trace0(_T("INSUFFICIENT BUFFER")); break; case ERROR_INVALID_FLAGS: pws_os::Trace0(_T("INVALID FLAGS")); break; case ERROR_INVALID_PARAMETER: pws_os::Trace0(_T("INVALID PARAMETER")); break; case ERROR_NO_UNICODE_TRANSLATION: // try to recover pws_os::Trace0(_T("NO UNICODE TRANSLATION")); wcLen = MultiByteToWideChar(CP_ACP, // code page 0, // character-type options LPSTR(utf8), // string to map -1, // -1 means null-terminated m_wc, // output buffer static_cast<int>(wcLen)); // output buffer size if (wcLen > 0) { pws_os::Trace0(_T("FromUTF8: recovery succeeded!")); } break; default: ASSERT(0); } } ASSERT(wcLen != 0); #endif /* _WIN32 */ if (wcLen != 0) { m_wc[wcLen - 1] = TCHAR('\0'); data = m_wc; return true; } else return false; }
#ifdef PEGASUS_OS_FREEBSD #ifndef __UNIX_AUTHORIZATIONSUBJECT_PRIVATE_H #define __UNIX_AUTHORIZATIONSUBJECT_PRIVATE_H #endif #endif
#include <time.h> #include <iostream> using namespace std ; // iteration code is in a separate source file extern int iterate(int *data,int *indices,int length) ; // generate an array - and initialise it int *generate_data(int length) { int *data = new int[length] ; for ( int i = 0 ; i < length ; i++ ) { data[i] = 0 ; } return data ; } // generate an array of indices - 0 to length - 1 int *generate_indices_asc(int length) { int *indices = new int[length] ; for ( int i = 0 ; i < length ; i++ ) { indices[i] = i ; } return indices ; } // generate an array of indices - length - 1 down to 0 int *generate_indices_dsc(int length) { int *indices = new int[length] ; int last_index = length ; for ( int i = 0 ; i < length ; i++ ) { indices[i] = --last_index ; } return indices ; } // generate an array of indices - random numbers from 0 to length - 1 int *generate_indices_random(int length) { int *indices = new int[length] ; for ( int i = 0 ; i < length ; i++ ) { indices[i] = rand() % length ; } return indices ; } double real_time() { struct timespec realtime ; clock_gettime(CLOCK_REALTIME,&realtime) ; return realtime.tv_sec + realtime.tv_nsec / 1000000000.0 ; } // usage error void usage(string error) { cout << "usage: loop <data length> <number of iterations> asc|dsc|random" << endl ; cout << error << endl ; exit(-1) ; } // main program - generate data and iterate over it in a specified order int main(int argc,char **argv) { // we must have 4 parameters, executable is first argument if ( argc < 4 ) usage("there must be 3 parameters") ; // check length parameter is > 0 int length = stoi(argv[1]) ; if ( length <= 0 ) usage("data length must be > 0" ) ; // check iterations parameter is > 0 int iterations = stoi(argv[2]) ; if ( iterations <= 0 ) usage("number of iterations must be > 0" ) ; // check requested ordering string ordering = argv[3] ; // pointers to the data array and indices array int *data = generate_data(length) ; int *indices ; if ( ordering == "asc" ) { indices = generate_indices_asc(length) ; } else if ( ordering == "dsc" ) { indices = generate_indices_dsc(length) ; } else if ( ordering == "random" ) { indices = generate_indices_random(length) ; } else { usage("iteration ordering must be one of asc, dsc or random") ; } //cout << "Starting iterations\n" ; // record start time - in seconds double start = real_time() ; // iterate over data in specified order iterations number of times for ( int i = 0 ; i < iterations ; i++ ) { iterate(data,indices,length) ; } // record stop time - in seconds double stop = real_time() ; //cout << "Finished iterations\n" ; // report time taken and read rate in millions per second double time = stop - start ; int rate = (int) (length * (double) iterations / time / 1000000.0) ; cout << argv[0] << "," << iterations << "," << length << "," << ordering << "," << time << "," << rate << "," ; }
#include "core.hpp" #include "lbfgs.hpp" #include <cblas.h> #include <immintrin.h> template <class T> struct get_blas_int_type; template <class T> struct get_blas_int_type<float (*)(T, float const*, T, float const*, T)> { using type = T; }; using blas_int = typename get_blas_int_type<decltype(&cblas_sdot)>::type; LBFGS_EXPORT auto blas_dot(gsl::span<float const> a, gsl::span<float const> b) noexcept -> double { LBFGS_ASSERT(a.size() == b.size(), "incompatible dimensions"); LBFGS_ASSERT( a.size() <= static_cast<size_t>(std::numeric_limits<blas_int>::max()), "integer overflow"); return cblas_dsdot(static_cast<blas_int>(a.size()), a.data(), 1, b.data(), 1); } LBFGS_EXPORT auto blas_nrm2(gsl::span<float const> x) noexcept -> double { LBFGS_ASSERT( x.size() <= static_cast<size_t>(std::numeric_limits<blas_int>::max()), "integer overflow"); return static_cast<double>( cblas_snrm2(static_cast<blas_int>(x.size()), x.data(), 1)); } LBFGS_EXPORT auto blas_scal(float const a, gsl::span<float> x) noexcept -> void { LBFGS_ASSERT( x.size() <= static_cast<size_t>(std::numeric_limits<blas_int>::max()), "integer overflow"); cblas_sscal(static_cast<blas_int>(x.size()), a, x.data(), 1); } LBFGS_EXPORT auto blas_axpy(float const a, gsl::span<float const> x, gsl::span<float> y) noexcept -> void { LBFGS_ASSERT(x.size() == y.size(), "incompatible dimensions"); LBFGS_ASSERT( x.size() <= static_cast<size_t>(std::numeric_limits<blas_int>::max()), "integer overflow"); cblas_saxpy(static_cast<blas_int>(x.size()), a, x.data(), 1, y.data(), 1); } LBFGS_EXPORT auto custom_dot(gsl::span<float const> a, gsl::span<float const> b) noexcept -> double { return ::LBFGS_NAMESPACE::detail::dot(a, b); } LBFGS_EXPORT auto custom_nrm2(gsl::span<float const> a) noexcept -> double { return ::LBFGS_NAMESPACE::detail::nrm2(a); } LBFGS_EXPORT auto custom_scal(float const c, gsl::span<float> a) noexcept -> void { return ::LBFGS_NAMESPACE::detail::scal(c, a); } LBFGS_EXPORT auto custom_axpy(float a, gsl::span<float const> x, gsl::span<float> y) noexcept -> void { return ::LBFGS_NAMESPACE::detail::axpy(a, x, y); }
// Copyright (c) 2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "base58.h" #include "hash.h" #include "uint256.h" #include "chainparams.h" #include <assert.h> #include <stdint.h> #include <string.h> #include <vector> #include <string> #include <boost/variant/apply_visitor.hpp> #include <boost/variant/static_visitor.hpp> /* All alphanumeric characters except for "0", "I", "O", and "l" */ static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet) { CAutoBN_CTX pctx; vchRet.clear(); CBigNum bn58 = 58; CBigNum bn = 0; CBigNum bnChar; // Skip leading spaces. while (*psz && isspace(*psz)) psz++; // Skip and count leading '1's. int zeroes = 0; while (*psz == '1') { zeroes++; psz++; } // Convert big endian string to bignum for (const char* p = psz; *p; p++) { const char* p1 = strchr(pszBase58, *p); if (p1 == NULL) { while (isspace(*p)) p++; if (*p != '\0') return false; break; } bnChar.setulong(p1 - pszBase58); if (!BN_mul(&bn, &bn, &bn58, pctx)) throw bignum_error("DecodeBase58 : BN_mul failed"); bn += bnChar; } // Get bignum as little endian data std::vector<unsigned char> vchTmp = bn.getvch(); // Trim off sign byte if present if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80) vchTmp.erase(vchTmp.end()-1); // Restore leading zeros int nLeadingZeros = 0; for (const char* p = psz; *p == pszBase58[0]; p++) nLeadingZeros++; vchRet.assign(nLeadingZeros + vchTmp.size(), 0); // Convert little endian data to big endian reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size()); return true; // Allocate enough space in big-endian base256 representation. std::vector<unsigned char> b256(strlen(psz) * 733 / 1000 + 1); // log(58) / log(256), rounded up. // Process the characters. while (*psz && !isspace(*psz)) { // Decode base58 character const char *ch = strchr(pszBase58, *psz); if (ch == NULL) return false; // Apply "b256 = b256 * 58 + ch". int carry = ch - pszBase58; for (std::vector<unsigned char>::reverse_iterator it = b256.rbegin(); it != b256.rend(); it++) { carry += 58 * (*it); *it = carry % 256; carry /= 256; } assert(carry == 0); psz++; } // Skip trailing spaces. while (isspace(*psz)) psz++; if (*psz != 0) return false; // Skip leading zeroes in b256. std::vector<unsigned char>::iterator it = b256.begin(); while (it != b256.end() && *it == 0) it++; // Copy result into output vector. vchRet.reserve(zeroes + (b256.end() - it)); vchRet.assign(zeroes, 0x00); while (it != b256.end()) vchRet.push_back(*(it++)); return true; } std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend) { // Skip & count leading zeroes. int zeroes = 0; while (pbegin != pend && *pbegin == 0) { pbegin++; zeroes++; } // Allocate enough space in big-endian base58 representation. std::vector<unsigned char> b58((pend - pbegin) * 138 / 100 + 1); // log(256) / log(58), rounded up. // Process the bytes. while (pbegin != pend) { int carry = *pbegin; // Apply "b58 = b58 * 256 + ch". for (std::vector<unsigned char>::reverse_iterator it = b58.rbegin(); it != b58.rend(); it++) { carry += 256 * (*it); *it = carry % 58; carry /= 58; } assert(carry == 0); pbegin++; } // Skip leading zeroes in base58 result. std::vector<unsigned char>::iterator it = b58.begin(); while (it != b58.end() && *it == 0) it++; // Translate the result into a string. std::string str; str.reserve(zeroes + (b58.end() - it)); str.assign(zeroes, '1'); while (it != b58.end()) str += pszBase58[*(it++)]; return str; } std::string EncodeBase58(const std::vector<unsigned char>& vch) { return EncodeBase58(&vch[0], &vch[0] + vch.size()); } bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58(str.c_str(), vchRet); } std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn) { // add 4-byte hash check to the end std::vector<unsigned char> vch(vchIn); uint256 hash = Hash(vch.begin(), vch.end()); vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4); return EncodeBase58(vch); } bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet) { if (!DecodeBase58(psz, vchRet) || (vchRet.size() < 4)) { vchRet.clear(); return false; } // re-calculate the checksum, insure it matches the included 4-byte checksum uint256 hash = Hash(vchRet.begin(), vchRet.end()-4); if (memcmp(&hash, &vchRet.end()[-4], 4) != 0) { vchRet.clear(); return false; } vchRet.resize(vchRet.size()-4); return true; } bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet) { return DecodeBase58Check(str.c_str(), vchRet); } CBase58Data::CBase58Data() { vchVersion.clear(); vchData.clear(); } void CBase58Data::SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize) { vchVersion = vchVersionIn; vchData.resize(nSize); if (!vchData.empty()) memcpy(&vchData[0], pdata, nSize); } void CBase58Data::SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend) { SetData(vchVersionIn, (void*)pbegin, pend - pbegin); } bool CBase58Data::SetString(const char* psz, unsigned int nVersionBytes) { std::vector<unsigned char> vchTemp; bool rc58 = DecodeBase58Check(psz, vchTemp); if ((!rc58) || (vchTemp.size() < nVersionBytes)) { vchData.clear(); vchVersion.clear(); return false; } vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes); vchData.resize(vchTemp.size() - nVersionBytes); if (!vchData.empty()) memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size()); memory_cleanse(&vchTemp[0], vchData.size()); return true; } bool CBase58Data::SetString(const std::string& str) { return SetString(str.c_str()); } std::string CBase58Data::ToString() const { std::vector<unsigned char> vch = vchVersion; vch.insert(vch.end(), vchData.begin(), vchData.end()); return EncodeBase58Check(vch); } int CBase58Data::CompareTo(const CBase58Data& b58) const { if (vchVersion < b58.vchVersion) return -1; if (vchVersion > b58.vchVersion) return 1; if (vchData < b58.vchData) return -1; if (vchData > b58.vchData) return 1; return 0; } namespace { class CMyceAddressVisitor : public boost::static_visitor<bool> { private: CMyceAddress *addr; public: CMyceAddressVisitor(CMyceAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const { return addr->Set(id); } bool operator()(const CScriptID &id) const { return addr->Set(id); } bool operator()(const CNoDestination &no) const { return false; } bool operator()(const CStealthAddress &stxAddr) const { return false; } }; class CBitcoinAddressVisitor : public boost::static_visitor<bool> { private: CBitcoinAddress *addr; public: CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const { return addr->Set(id); } bool operator()(const CScriptID &id) const { return addr->Set(id); } bool operator()(const CNoDestination &no) const { return false; } bool operator()(const CStealthAddress &stxAddr) const { return false; } }; }; bool CMyceAddress::Set(const CKeyID &id) { SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20); return true; } bool CMyceAddress::Set(const CScriptID &id) { SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20); return true; } bool CMyceAddress::Set(const CTxDestination &dest) { return boost::apply_visitor(CMyceAddressVisitor(this), dest); } bool CMyceAddress::IsValid() const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) || vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); return fCorrectSize && fKnownVersion; } CTxDestination CMyceAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS)) return CScriptID(id); else return CNoDestination(); } bool CMyceAddress::GetKeyID(CKeyID &keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CMyceAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS); } void CMyceSecret::SetKey(const CKey& vchSecret) { assert(vchSecret.IsValid()); SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size()); if (vchSecret.IsCompressed()) vchData.push_back(1); } CKey CMyceSecret::GetKey() { CKey ret; ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1); return ret; } bool CMyceSecret::IsValid() const { bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1); bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY); return fExpectedFormat && fCorrectVersion; } bool CMyceSecret::SetString(const char* pszSecret) { return CBase58Data::SetString(pszSecret) && IsValid(); } bool CMyceSecret::SetString(const std::string& strSecret) { return SetString(strSecret.c_str()); } /** base58-encoded Bitcoin addresses. * Public-key-hash-addresses have version 0 (or 111 testnet). * The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key. * Script-hash-addresses have version 5 (or 196 testnet). * The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script. */ CChainParams::Base58Type pubkey_address = (CChainParams::Base58Type)0; CChainParams::Base58Type script_address = (CChainParams::Base58Type)5; bool CBitcoinAddress::Set(const CKeyID &id) { SetData(Params().Base58Prefix(pubkey_address), &id, 20); return true; } bool CBitcoinAddress::Set(const CScriptID &id) { SetData(Params().Base58Prefix(script_address), &id, 20); return true; } bool CBitcoinAddress::Set(const CTxDestination &dest) { return boost::apply_visitor(CBitcoinAddressVisitor(this), dest); } bool CBitcoinAddress::IsValid() const { bool fCorrectSize = vchData.size() == 20; bool fKnownVersion = vchVersion == Params().Base58Prefix(pubkey_address) || vchVersion == Params().Base58Prefix(script_address); return fCorrectSize && fKnownVersion; } CTxDestination CBitcoinAddress::Get() const { if (!IsValid()) return CNoDestination(); uint160 id; memcpy(&id, &vchData[0], 20); if (vchVersion == Params().Base58Prefix(pubkey_address)) return CKeyID(id); else if (vchVersion == Params().Base58Prefix(script_address)) return CScriptID(id); else return CNoDestination(); } bool CBitcoinAddress::GetKeyID(CKeyID &keyID) const { if (!IsValid() || vchVersion != Params().Base58Prefix(pubkey_address)) return false; uint160 id; memcpy(&id, &vchData[0], 20); keyID = CKeyID(id); return true; } bool CBitcoinAddress::IsScript() const { return IsValid() && vchVersion == Params().Base58Prefix(script_address); }
// ============================================================================ // Include files // ============================================================================ // STD & STL: // ============================================================================ #include <limits> // ============================================================================ // Ostap // ============================================================================ #include "Ostap/StatusCode.h" #include "Ostap/PDFs3D.h" #include "Ostap/Iterator.h" // ============================================================================ // ROOT // ============================================================================ #include "RooArgSet.h" #include "RooRealVar.h" // ============================================================================ // Local // ============================================================================ #include "local_roofit.h" // ============================================================================ /** @file * Implementation file for namespace Ostap::Models * @author Vanya BELYAEV Ivan.Belyaev@cern.ch * @date 2017-11-21 */ // ============================================================================ // generic polinomial // ============================================================================ Ostap::Models::Poly3DPositive::Poly3DPositive ( const char* name , const char* title , RooRealVar& x , RooRealVar& y , RooRealVar& z , const unsigned short nX , const unsigned short nY , const unsigned short nZ , RooArgList& phis ) : RooAbsPdf ( name , title ) , m_x ( "x" , "Observable-X" , this , x ) , m_y ( "y" , "Observable-Y" , this , y ) , m_z ( "z" , "Observable-Z" , this , z ) , m_phis ( "phis" , "Coefficients" , this ) // , m_positive ( nX , nY , nZ , x.getMin() , x.getMax() , y.getMin() , y.getMax() , z.getMin() , z.getMax() ) { // ::copy_real ( phis , m_phis , "Invalid phi-parameter!" , "Ostap::Models::Poly3DPositive" ) ; // Ostap::Assert ( ::size ( m_phis ) == m_positive.npars () , "Widths/#channels mismatch" , "Ostap::Models::Poly3DPositive" ) ; // setPars () ; // } // ============================================================================ // copy constructor // ============================================================================ Ostap::Models::Poly3DPositive::Poly3DPositive ( const Ostap::Models::Poly3DPositive& right , const char* name ) : RooAbsPdf ( right , name ) // , m_x ( "x" , this , right.m_x ) , m_y ( "y" , this , right.m_y ) , m_z ( "z" , this , right.m_z ) , m_phis ( "phis" , this , right.m_phis ) // , m_positive ( right.m_positive ) { setPars () ; } // ============================================================================ // destructor // ============================================================================ Ostap::Models::Poly3DPositive::~Poly3DPositive(){} // ============================================================================ // clone // ============================================================================ Ostap::Models::Poly3DPositive* Ostap::Models::Poly3DPositive::clone( const char* name ) const { return new Ostap::Models::Poly3DPositive(*this,name) ; } // ============================================================================ void Ostap::Models::Poly3DPositive::setPars () const { ::set_pars ( m_phis , m_positive ) ; } // ============================================================================ // the actual evaluation of function // ============================================================================ Double_t Ostap::Models::Poly3DPositive::evaluate() const { setPars () ; return m_positive ( m_x , m_y , m_z ) ; } // ============================================================================ Int_t Ostap::Models::Poly3DPositive::getAnalyticalIntegral ( RooArgSet& allVars , RooArgSet& analVars , const char* /* rangename */ ) const { // ========================================================================== if ( matchArgs ( allVars , analVars , m_x , m_y , m_z ) ) { return 1 ; } else if ( matchArgs ( allVars , analVars , m_x , m_y ) ) { return 2 ; } else if ( matchArgs ( allVars , analVars , m_x , m_z ) ) { return 3 ; } else if ( matchArgs ( allVars , analVars , m_y , m_z ) ) { return 4 ; } else if ( matchArgs ( allVars , analVars , m_x ) ) { return 5 ; } else if ( matchArgs ( allVars , analVars , m_y ) ) { return 6 ; } else if ( matchArgs ( allVars , analVars , m_z ) ) { return 7 ; } // ========================================================================== return 0 ; } // ============================================================================ Double_t Ostap::Models::Poly3DPositive::analyticalIntegral ( Int_t code , const char* rangeName ) const { assert ( 1 <= code && code <=7 ) ; // return // 3D-integral 1 == code ? m_positive.integral ( m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 2D-integrals 2 == code ? m_positive.integrateXY ( m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 3 == code ? m_positive.integrateXZ ( m_y , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 4 == code ? m_positive.integrateYZ ( m_x , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 1D-integrals 5 == code ? m_positive.integrateX ( m_y , m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) ) : 6 == code ? m_positive.integrateY ( m_x , m_z , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 7 == code ? m_positive.integrateZ ( m_x , m_y , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 0.0 ; } // ============================================================================ // ============================================================================ // symmetric polinomial // ============================================================================ Ostap::Models::Poly3DSymPositive::Poly3DSymPositive ( const char* name , const char* title , RooRealVar& x , RooRealVar& y , RooRealVar& z , const unsigned short n , RooArgList& phis ) : RooAbsPdf ( name , title ) , m_x ( "x" , "Observable-X" , this , x ) , m_y ( "y" , "Observable-Y" , this , y ) , m_z ( "z" , "Observable-Z" , this , z ) , m_phis ( "phis" , "Coefficients" , this ) // , m_positive ( n , std::min ( x.getMin() , std::min ( y.getMin() , z.getMin() ) ) , std::max ( x.getMax() , std::max ( y.getMax() , z.getMax() ) ) ) { // ::copy_real ( phis , m_phis , "Invalid phi-parameter!" , "Ostap::Models::Poly3DSymPositive" ) ; // Ostap::Assert ( ::size ( m_phis ) == m_positive.npars () , "Widths/#channels mismatch" , "Ostap::Models::Poly3DSymPositive" ) ; // setPars () ; // } // ============================================================================ // copy constructor // ============================================================================ Ostap::Models::Poly3DSymPositive::Poly3DSymPositive ( const Ostap::Models::Poly3DSymPositive& right , const char* name ) : RooAbsPdf ( right , name ) // , m_x ( "x" , this , right.m_x ) , m_y ( "y" , this , right.m_y ) , m_z ( "z" , this , right.m_z ) , m_phis ( "phis" , this , right.m_phis ) // , m_positive ( right.m_positive ) { setPars () ; } // ============================================================================ // destructor // ============================================================================ Ostap::Models::Poly3DSymPositive::~Poly3DSymPositive(){} // ============================================================================ // clone // ============================================================================ Ostap::Models::Poly3DSymPositive* Ostap::Models::Poly3DSymPositive::clone( const char* name ) const { return new Ostap::Models::Poly3DSymPositive(*this,name) ; } // ============================================================================ void Ostap::Models::Poly3DSymPositive::setPars () const { ::set_pars ( m_phis , m_positive ) ; } // ============================================================================ // the actual evaluation of function // ============================================================================ Double_t Ostap::Models::Poly3DSymPositive::evaluate() const { setPars () ; return m_positive ( m_x , m_y , m_z ) ; } // ============================================================================ Int_t Ostap::Models::Poly3DSymPositive::getAnalyticalIntegral ( RooArgSet& allVars , RooArgSet& analVars , const char* /* rangename */ ) const { // ========================================================================== if ( matchArgs ( allVars , analVars , m_x , m_y , m_z ) ) { return 1 ; } else if ( matchArgs ( allVars , analVars , m_x , m_y ) ) { return 2 ; } else if ( matchArgs ( allVars , analVars , m_x , m_z ) ) { return 3 ; } else if ( matchArgs ( allVars , analVars , m_y , m_z ) ) { return 4 ; } else if ( matchArgs ( allVars , analVars , m_x ) ) { return 5 ; } else if ( matchArgs ( allVars , analVars , m_y ) ) { return 6 ; } else if ( matchArgs ( allVars , analVars , m_z ) ) { return 7 ; } // ========================================================================== return 0 ; } // ============================================================================ Double_t Ostap::Models::Poly3DSymPositive::analyticalIntegral ( Int_t code , const char* rangeName ) const { assert ( 1 <= code && code <=7 ) ; // return // 3D-integral 1 == code ? m_positive.integral ( m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 2D-integrals 2 == code ? m_positive.integrateXY ( m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 3 == code ? m_positive.integrateXZ ( m_y , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 4 == code ? m_positive.integrateYZ ( m_x , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 1D-integrals 5 == code ? m_positive.integrateX ( m_y , m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) ) : 6 == code ? m_positive.integrateY ( m_x , m_z , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 7 == code ? m_positive.integrateZ ( m_x , m_y , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 0.0 ; } // ============================================================================ // ============================================================================ // mixed symmetry polinomial // ============================================================================ Ostap::Models::Poly3DMixPositive::Poly3DMixPositive ( const char* name , const char* title , RooRealVar& x , RooRealVar& y , RooRealVar& z , const unsigned short n , const unsigned short nz , RooArgList& phis ) : RooAbsPdf ( name , title ) , m_x ( "x" , "Observable-X" , this , x ) , m_y ( "y" , "Observable-Y" , this , y ) , m_z ( "z" , "Observable-Z" , this , z ) , m_phis ( "phis" , "Coefficients" , this ) // , m_positive ( n , nz , std::min ( x.getMin() , y.getMin() ) , std::max ( x.getMax() , y.getMax() ) , z.getMin() , z.getMax() ) { // ::copy_real ( phis , m_phis , "Invalid phi-parameter!" , "Ostap::Models::Poly2DMixPositive" ) ; // Ostap::Assert ( ::size ( m_phis ) == m_positive.npars () , "Widths/#channels mismatch" , "Ostap::Models::Poly3DMixPositive" ) ; // setPars () ; // } // ============================================================================ // copy constructor // ============================================================================ Ostap::Models::Poly3DMixPositive::Poly3DMixPositive ( const Ostap::Models::Poly3DMixPositive& right , const char* name ) : RooAbsPdf ( right , name ) // , m_x ( "x" , this , right.m_x ) , m_y ( "y" , this , right.m_y ) , m_z ( "z" , this , right.m_z ) , m_phis ( "phis" , this , right.m_phis ) // , m_positive ( right.m_positive ) { setPars () ; } // ============================================================================ // destructor // ============================================================================ Ostap::Models::Poly3DMixPositive::~Poly3DMixPositive(){} // ============================================================================ // clone // ============================================================================ Ostap::Models::Poly3DMixPositive* Ostap::Models::Poly3DMixPositive::clone( const char* name ) const { return new Ostap::Models::Poly3DMixPositive(*this,name) ; } // ============================================================================ void Ostap::Models::Poly3DMixPositive::setPars () const { ::set_pars ( m_phis , m_positive ) ; } // ============================================================================ // the actual evaluation of function // ============================================================================ Double_t Ostap::Models::Poly3DMixPositive::evaluate() const { setPars () ; return m_positive ( m_x , m_y , m_z ) ; } // ============================================================================ Int_t Ostap::Models::Poly3DMixPositive::getAnalyticalIntegral ( RooArgSet& allVars , RooArgSet& analVars , const char* /* rangename */ ) const { // ========================================================================== if ( matchArgs ( allVars , analVars , m_x , m_y , m_z ) ) { return 1 ; } else if ( matchArgs ( allVars , analVars , m_x , m_y ) ) { return 2 ; } else if ( matchArgs ( allVars , analVars , m_x , m_z ) ) { return 3 ; } else if ( matchArgs ( allVars , analVars , m_y , m_z ) ) { return 4 ; } else if ( matchArgs ( allVars , analVars , m_x ) ) { return 5 ; } else if ( matchArgs ( allVars , analVars , m_y ) ) { return 6 ; } else if ( matchArgs ( allVars , analVars , m_z ) ) { return 7 ; } // ========================================================================== return 0 ; } // ============================================================================ Double_t Ostap::Models::Poly3DMixPositive::analyticalIntegral ( Int_t code , const char* rangeName ) const { assert ( 1 <= code && code <=7 ) ; // return // 3D-integral 1 == code ? m_positive.integral ( m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 2D-integrals 2 == code ? m_positive.integrateXY ( m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 3 == code ? m_positive.integrateXZ ( m_y , m_x.min ( rangeName ) , m_x.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 4 == code ? m_positive.integrateYZ ( m_x , m_y.min ( rangeName ) , m_y.max ( rangeName ) , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : // 1D-integrals 5 == code ? m_positive.integrateX ( m_y , m_z , m_x.min ( rangeName ) , m_x.max ( rangeName ) ) : 6 == code ? m_positive.integrateY ( m_x , m_z , m_y.min ( rangeName ) , m_y.max ( rangeName ) ) : 7 == code ? m_positive.integrateZ ( m_x , m_y , m_z.min ( rangeName ) , m_z.max ( rangeName ) ) : 0.0 ; } // ============================================================================ // ============================================================================ ClassImp(Ostap::Models::Poly3DPositive ) ClassImp(Ostap::Models::Poly3DSymPositive ) ClassImp(Ostap::Models::Poly3DMixPositive ) // ============================================================================ // The END // ============================================================================
// Copyright 2014 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "simulation/Topologies.h" #include "lib/catch.hpp" #include "overlay/StellarXDR.h" #include "main/Application.h" #include "overlay/LoopbackPeer.h" #include "util/make_unique.h" #include "crypto/SHA.h" #include "main/test.h" #include "util/Logging.h" #include "util/types.h" #include "herder/Herder.h" #include "transactions/TransactionFrame.h" using namespace stellar; typedef std::unique_ptr<Application> appPtr; // Simulation tests. Some of the tests in this suite are long. // They are marked with [long][hide]. Run the day-to-day tests with // // --test // or // --test [simulation]~[long] // void printStats(int& nLedgers, std::chrono::system_clock::time_point tBegin, Simulation::pointer sim) { auto t = std::chrono::duration_cast<std::chrono::seconds>( std::chrono::system_clock::now() - tBegin); LOG(INFO) << "Time spent closing " << nLedgers << " ledgers with " << sim->getNodes().size() << " nodes : " << t.count() << " seconds"; LOG(INFO) << sim->metricsSummary("scp"); } #include "lib/util/lrucache.hpp" TEST_CASE("3 nodes. 2 running. threshold 2", "[simulation][core3]") { Simulation::Mode mode = Simulation::OVER_LOOPBACK; SECTION("Over loopback") { mode = Simulation::OVER_LOOPBACK; } SECTION("Over tcp") { mode = Simulation::OVER_TCP; } { Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); Simulation::pointer simulation = std::make_shared<Simulation>(mode, networkID); std::vector<SecretKey> keys; for (int i = 0; i < 3; i++) { keys.push_back( SecretKey::fromSeed(sha256("NODE_SEED_" + std::to_string(i)))); } SCPQuorumSet qSet; qSet.threshold = 2; for (auto& k : keys) { qSet.validators.push_back(k.getPublicKey()); } simulation->addNode(keys[0], qSet, simulation->getClock()); simulation->addNode(keys[1], qSet, simulation->getClock()); simulation->addPendingConnection(keys[0].getPublicKey(), keys[1].getPublicKey()); auto tBegin = std::chrono::system_clock::now(); LOG(INFO) << "#######################################################"; simulation->startAllNodes(); int nLedgers = 10; simulation->crankUntil( [&simulation, nLedgers]() { return simulation->haveAllExternalized(nLedgers + 1, 5); }, 2 * nLedgers * Herder::EXP_LEDGER_TIMESPAN_SECONDS, true); // printStats(nLedgers, tBegin, simulation); REQUIRE(simulation->haveAllExternalized(nLedgers + 1, 5)); } LOG(DEBUG) << "done with core3 test"; } TEST_CASE("core topology: 4 ledgers at scales 2..4", "[simulation]") { Simulation::Mode mode = Simulation::OVER_LOOPBACK; SECTION("Over loopback") { mode = Simulation::OVER_LOOPBACK; } SECTION("Over tcp") { mode = Simulation::OVER_TCP; } Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); for (int size = 2; size <= 4; size++) { auto tBegin = std::chrono::system_clock::now(); Simulation::pointer sim = Topologies::core(size, 1.0, mode, networkID); sim->startAllNodes(); int nLedgers = 4; sim->crankUntil( [&sim, nLedgers]() { return sim->haveAllExternalized(nLedgers + 1, nLedgers); }, 2 * nLedgers * Herder::EXP_LEDGER_TIMESPAN_SECONDS, true); REQUIRE(sim->haveAllExternalized(nLedgers + 1, 5)); // printStats(nLedgers, tBegin, sim); } } static void hierarchicalTopoTest(int nLedgers, int nBranches, Simulation::Mode mode, Hash const& networkID) { auto tBegin = std::chrono::system_clock::now(); Simulation::pointer sim = Topologies::hierarchicalQuorum(nBranches, mode, networkID); sim->startAllNodes(); sim->crankUntil( [&sim, nLedgers]() { return sim->haveAllExternalized(nLedgers + 1, 5); }, 20 * nLedgers * Herder::EXP_LEDGER_TIMESPAN_SECONDS, true); REQUIRE(sim->haveAllExternalized(nLedgers + 1, 5)); // printStats(nLedgers, tBegin, sim); } TEST_CASE("hierarchical topology scales 1..3", "[simulation]") { Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); Simulation::Mode mode = Simulation::OVER_LOOPBACK; auto test = [&]() { int const nLedgers = 4; for (int nBranches = 1; nBranches <= 3; nBranches += 2) { hierarchicalTopoTest(nLedgers, nBranches, mode, networkID); } }; SECTION("Over loopback") { LOG(DEBUG) << "OVER_LOOPBACK"; mode = Simulation::OVER_LOOPBACK; test(); } SECTION("Over tcp") { LOG(DEBUG) << "OVER_TCP"; mode = Simulation::OVER_TCP; test(); } } static void hierarchicalSimplifiedTest(int nLedgers, int nbCore, int nbOuterNodes, Simulation::Mode mode, Hash const& networkID) { auto tBegin = std::chrono::system_clock::now(); Simulation::pointer sim = Topologies::hierarchicalQuorumSimplified( nbCore, nbOuterNodes, mode, networkID); sim->startAllNodes(); sim->crankUntil( [&sim, nLedgers]() { return sim->haveAllExternalized(nLedgers + 1, 3); }, 20 * nLedgers * Herder::EXP_LEDGER_TIMESPAN_SECONDS, true); REQUIRE(sim->haveAllExternalized(nLedgers + 1, 3)); // printStats(nLedgers, tBegin, sim); } TEST_CASE("core-nodes with outer nodes", "[simulation]") { Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); Simulation::Mode mode = Simulation::OVER_LOOPBACK; SECTION("Over loopback") { mode = Simulation::OVER_LOOPBACK; hierarchicalSimplifiedTest(4, 5, 10, mode, networkID); } SECTION("Over tcp") { mode = Simulation::OVER_TCP; hierarchicalSimplifiedTest(4, 5, 10, mode, networkID); } } TEST_CASE("cycle4 topology", "[simulation]") { Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); Simulation::pointer simulation = Topologies::cycle4(networkID); simulation->startAllNodes(); simulation->crankUntil( [&simulation]() { return simulation->haveAllExternalized(2, 4); }, std::chrono::seconds(20), true); // Still transiently does not work (quorum retrieval) REQUIRE(simulation->haveAllExternalized(2, 4)); } TEST_CASE("Stress test on 2 nodes 3 accounts 10 random transactions 10tx/sec", "[stress100][simulation][stress][long][hide]") { Hash networkID = sha256(getTestConfig().NETWORK_PASSPHRASE); Simulation::pointer simulation = Topologies::pair(Simulation::OVER_LOOPBACK, networkID); simulation->startAllNodes(); simulation->crankUntil( [&]() { return simulation->haveAllExternalized(3, 1); }, 2 * Herder::EXP_LEDGER_TIMESPAN_SECONDS, false); simulation->executeAll(simulation->accountCreationTransactions(3)); try { simulation->crankUntil( [&]() { // we need to wait 2 rounds in case the tx don't propagate // to the second node in time and the second node gets the // nomination return simulation->haveAllExternalized(5, 2) && simulation->accountsOutOfSyncWithDb().empty(); }, 3 * Herder::EXP_LEDGER_TIMESPAN_SECONDS, false); auto crankingTime = simulation->executeStressTest( 10, 10, [&simulation](size_t i) { return simulation->createRandomTransaction(0.5); }); simulation->crankUntil( [&]() { return simulation->accountsOutOfSyncWithDb().empty(); }, std::chrono::seconds(60), true); } catch (...) { auto problems = simulation->accountsOutOfSyncWithDb(); REQUIRE(problems.empty()); } LOG(INFO) << simulation->metricsSummary("database"); } TEST_CASE("Auto-calibrated single node load test", "[autoload][hide]") { Config cfg = #ifdef USE_POSTGRES !force_sqlite ? getTestConfig(0, Config::TESTDB_POSTGRESQL) : #endif getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE); cfg.RUN_STANDALONE = false; cfg.PARANOID_MODE = false; cfg.DESIRED_MAX_TX_PER_LEDGER = 10000; VirtualClock clock(VirtualClock::REAL_TIME); Application::pointer appPtr = Application::create(clock, cfg); appPtr->start(); // force maxTxSetSize to avoid throwing txSets on the floor during the first // ledger close appPtr->getLedgerManager().getCurrentLedgerHeader().maxTxSetSize = cfg.DESIRED_MAX_TX_PER_LEDGER; appPtr->generateLoad(100000, 100000, 10, true); auto& io = clock.getIOService(); asio::io_service::work mainWork(io); auto& complete = appPtr->getMetrics().NewMeter({"loadgen", "run", "complete"}, "run"); while (!io.stopped() && complete.count() == 0) { clock.crank(); } }
// Copyright (c) 2018 The Open-Transactions developers // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "stdafx.hpp" #include "opentxs/core/AccountList.hpp" #include "opentxs/api/Core.hpp" #include "opentxs/api/Wallet.hpp" #include "opentxs/core/util/Assert.hpp" #include "opentxs/core/util/Common.hpp" #include "opentxs/core/util/Tag.hpp" #include "opentxs/core/Account.hpp" #include "opentxs/core/Contract.hpp" #include "opentxs/core/Helpers.hpp" #include "opentxs/core/Identifier.hpp" #include "opentxs/core/Log.hpp" #include "opentxs/core/Message.hpp" #include "opentxs/core/String.hpp" #include <irrxml/irrXML.hpp> #include <sys/types.h> #include <cstdint> #include <cstdlib> #include <cstring> #include <map> #include <memory> #include <ostream> #include <string> #include <utility> using namespace irr; using namespace io; #define OT_METHOD "opentxs::AccountList::" namespace opentxs { AccountList::AccountList(const api::Core& core) : api_(core) , acctType_(Account::voucher) , mapAcctIDs_{} { } AccountList::AccountList(const api::Core& core, Account::AccountType acctType) : api_(core) , acctType_(acctType) , mapAcctIDs_{} { } void AccountList::Serialize(Tag& parent) const { String acctType; TranslateAccountTypeToString(acctType_, acctType); std::uint32_t sizeMapAcctIDs = mapAcctIDs_.size(); TagPtr pTag(new Tag("accountList")); pTag->add_attribute("type", acctType.Get()); pTag->add_attribute("count", formatUint(sizeMapAcctIDs)); for (auto& it : mapAcctIDs_) { std::string instrumentDefinitionID = it.first; std::string accountId = it.second; OT_ASSERT( (instrumentDefinitionID.size() > 0) && (accountId.size() > 0)); TagPtr pTagEntry(new Tag("accountEntry")); pTagEntry->add_attribute( "instrumentDefinitionID", instrumentDefinitionID); pTagEntry->add_attribute("accountID", accountId); pTag->add_tag(pTagEntry); } parent.add_tag(pTag); } std::int32_t AccountList::ReadFromXMLNode( irr::io::IrrXMLReader*& xml, const String& acctType, const String& acctCount) { if (!acctType.Exists()) { otErr << "AccountList::ReadFromXMLNode: Failed: Empty accountList " "'type' attribute.\n"; return -1; } acctType_ = TranslateAccountTypeStringToEnum(acctType); if (Account::err_acct == acctType_) { otErr << "AccountList::ReadFromXMLNode: Failed: accountList 'type' " "attribute contains unknown value.\n"; return -1; } // Load up the account IDs. std::int32_t count = acctCount.Exists() ? atoi(acctCount.Get()) : 0; if (count > 0) { while (count-- > 0) { if (!Contract::SkipToElement(xml)) { otOut << "AccountList::ReadFromXMLNode: Failure: Unable to find " "expected element.\n"; return -1; } if ((xml->getNodeType() == EXN_ELEMENT) && (!strcmp("accountEntry", xml->getNodeName()))) { String instrumentDefinitionID = xml->getAttributeValue( "instrumentDefinitionID"); // Instrument Definition ID of // this account. String accountID = xml->getAttributeValue( "accountID"); // Account ID for this account. if (!instrumentDefinitionID.Exists() || !accountID.Exists()) { otErr << "Error loading accountEntry: Either the " "instrumentDefinitionID (" << instrumentDefinitionID << "), or the accountID (" << accountID << ") was EMPTY.\n"; return -1; } mapAcctIDs_.insert(std::make_pair( instrumentDefinitionID.Get(), accountID.Get())); } else { otErr << "Expected accountEntry element in accountList.\n"; return -1; } } } if (!Contract::SkipAfterLoadingField(xml)) // </accountList> { otOut << "*** AccountList::ReadFromXMLNode: Bad data? Expected " "EXN_ELEMENT_END here, but " "didn't get it. Returning false.\n"; return -1; } return 1; } void AccountList::Release_AcctList() { mapAcctIDs_.clear(); } void AccountList::Release() { Release_AcctList(); } ExclusiveAccount AccountList::GetOrRegisterAccount( const Nym& serverNym, const Identifier& accountOwnerId, const Identifier& instrumentDefinitionID, const Identifier& notaryID, bool& wasAcctCreated, std::int64_t stashTransNum) { ExclusiveAccount account{}; wasAcctCreated = false; if (Account::stash == acctType_) { if (1 > stashTransNum) { otErr << OT_METHOD << __FUNCTION__ << ": Failed attempt to " "create stash account without cron item #."; return {}; } } // First, we'll see if there's already an account ID available for the // requested instrument definition ID. String acctTypeString; TranslateAccountTypeToString(acctType_, acctTypeString); auto acctIDsIt = mapAcctIDs_.find(instrumentDefinitionID.str()); // Account ID *IS* already there for this instrument definition if (mapAcctIDs_.end() != acctIDsIt) { const auto& accountID = acctIDsIt->second; account = api_.Wallet().mutable_Account(Identifier::Factory(accountID)); if (account) { otLog3 << OT_METHOD << __FUNCTION__ << "Successfully loaded " << acctTypeString << " account ID: " << accountID << " Instrument Definition ID: " << instrumentDefinitionID.str() << std::endl; return account; } } // Not found. There's no account ID yet for that instrument definition ID. // That means we can create it. account = api_.Wallet().CreateAccount( accountOwnerId, notaryID, instrumentDefinitionID, serverNym, acctType_, stashTransNum); if (false == bool(account)) { otErr << OT_METHOD << __FUNCTION__ << ": Failed trying to generate" << acctTypeString << " account with instrument definition ID: " << instrumentDefinitionID.str() << std::endl; } else { String acctIDString; account.get().GetIdentifier(acctIDString); otOut << "Successfully created " << acctTypeString << " account ID: " << acctIDString << " Instrument Definition ID: " << instrumentDefinitionID.str() << std::endl; mapAcctIDs_[instrumentDefinitionID.str()] = acctIDString.Get(); wasAcctCreated = true; } return account; } AccountList::~AccountList() { Release_AcctList(); } } // namespace opentxs
#include <bts/rpc/rpc_client.hpp> #include <bts/net/stcp_socket.hpp> #include <bts/blockchain/address.hpp> #include <bts/blockchain/transaction.hpp> #include <bts/blockchain/block.hpp> #include <bts/utilities/key_conversion.hpp> #include <bts/utilities/padding_ostream.hpp> #include <fc/reflect/variant.hpp> #include <fc/network/tcp_socket.hpp> #include <fc/rpc/json_connection.hpp> #include <fc/thread/thread.hpp> #include <fc/crypto/base58.hpp> #include <fc/crypto/digest.hpp> #include <fc/thread/future.hpp> #include <bts/rpc_stubs/common_api_rpc_client.hpp> namespace bts { namespace rpc { namespace detail { class rpc_client_impl : public bts::rpc_stubs::common_api_rpc_client { public: fc::rpc::json_connection_ptr _json_connection; fc::future<void> _json_exec_loop_complete; virtual fc::rpc::json_connection_ptr get_json_connection() const override { return _json_connection; } void connect_to(const fc::ip::endpoint& remote_endpoint, const blockchain::public_key_type& remote_public_key); bool login(const std::string& username, const std::string& password); }; void rpc_client_impl::connect_to(const fc::ip::endpoint& remote_endpoint, const bts::blockchain::public_key_type& remote_public_key) { fc::buffered_istream_ptr buffered_istream; fc::buffered_ostream_ptr buffered_ostream; if( remote_public_key != bts::blockchain::public_key_type() ) { net::stcp_socket_ptr socket = std::make_shared<bts::net::stcp_socket>(); try { socket->connect_to(remote_endpoint); } catch ( const fc::exception& e ) { elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) ); throw; } std::vector<char> packed_signature(80, ' '); FC_ASSERT( socket->readsome(packed_signature.data(), packed_signature.size()) == 80, "Unexpected number of bytes read from RPC socket" ); fc::ecc::compact_signature signature; signature = fc::raw::unpack<fc::ecc::compact_signature>(packed_signature); wdump((signature)); FC_ASSERT(blockchain::public_key_type(fc::ecc::public_key(signature, fc::digest(socket->get_shared_secret()))) == remote_public_key, "Unable to establish secure connection with server."); buffered_istream = std::make_shared<fc::buffered_istream>(socket); buffered_ostream = std::make_shared<utilities::padding_ostream<>>(socket); } else { fc::tcp_socket_ptr socket = std::make_shared<fc::tcp_socket>(); try { socket->connect_to(remote_endpoint); } catch ( const fc::exception& e ) { elog( "fatal: error opening RPC socket to endpoint ${endpoint}: ${e}", ("endpoint", remote_endpoint)("e", e.to_detail_string() ) ); throw; } buffered_istream = std::make_shared<fc::buffered_istream>(socket); buffered_ostream = std::make_shared<fc::buffered_ostream>(socket); } _json_connection = std::make_shared<fc::rpc::json_connection>(std::move(buffered_istream), std::move(buffered_ostream)); _json_exec_loop_complete = fc::async([=](){ _json_connection->exec(); }, "json exec loop"); } bool rpc_client_impl::login(const std::string& username, const std::string& password) { return _json_connection->call<bool>("login", username, password); } } // end namespace detail rpc_client::rpc_client() : my(new detail::rpc_client_impl) { } rpc_client::~rpc_client() { try { my->_json_exec_loop_complete.cancel_and_wait("~rpc_client()"); } catch (const fc::exception& e) { wlog("Caught exception ${e} while canceling json_connection exec loop", ("e", e)); } } void rpc_client::connect_to(const fc::ip::endpoint& remote_endpoint, const bts::blockchain::public_key_type& remote_public_key) { my->connect_to(remote_endpoint, remote_public_key); } bool rpc_client::login(const std::string& username, const std::string& password) { return my->login(username, password); } fc::rpc::json_connection_ptr rpc_client::get_json_connection() const { return my->_json_connection; } void rpc_client::reset_json_connection() { my->_json_connection->close(); auto ptr_copy = my->_json_connection; fc::schedule([ptr_copy] { /* Do nothing; just let ptr_copy go out of scope */ }, fc::time_point::now() + fc::seconds(1), __FUNCTION__); my->_json_connection.reset(); } } } // bts::rpc
// ===================================================================================== // // Filename: gemma_impl.cpp // // Description: // // Version: 1.0 // Created: 05/20/2018 05:53:23 PM // Revision: none // Compiler: g++ // // Author: Baoxing Song (songbx.me), songbaoxing168@163.com // Company: unemployed // // ===================================================================================== /************************************************************************* * * * This is a re impelmentation of the GEMMA method * Xiang Zhou and Matthew Stephens (2012). * Genome-wide efficient mixed-model analysis for association studies. Nature Genetics 44, 821–824. * * I ever read the source code of GEMMA, but I did copy any piece of code * ************************************************************************/ // // Created by song on 5/20/18. // This file implemented the algorithm in the pater ogf gemma published on nature genetics // #include "gemma_impl.h" // the euqations have nothing with lambda value begin //void _get_UtW_( const Eigen_result & eigen_L, const My_matrix<double> & W, const int & n, const int & q, My_matrix<double> & UtW){ // int i, j, k; // for ( i=0; i<n; ++i ) { // for (j = 0; j < q; ++j) { // UtW.get_matrix()[i][j] = 0.0; // } // } // for ( i=0; i<n; ++i ) { // for (j = 0; j < q; ++j) { // for ( k=0; k<n; ++k ){ // UtW.get_matrix()[i][j] += (eigen_L.get_eigen_vectors().get_matrix()[k][i] * W.get_matrix()[k][j]); // } // } // } //} // //void _get_Uty_( const Eigen_result & eigen_L, const My_Vector<double> & y, const size_t & n, My_Vector<double> & Uty){ // // this function has been compared with gemma, it should be correct // int i, j; // for ( i=0; i<n; ++i ){ // Uty.get_array()[i]=0.0; // for ( j=0; j<n; ++j ){ // Uty.get_array()[i]+=eigen_L.get_eigen_vectors().get_matrix()[j][i]*y.get_array()[j]; // } // } //} // the equations have nothing with lambda value end void get_lambda_theta_p_1_( const double & lambda, const Eigen_result & eigen_L, My_Vector<double> & lambda_theta_p_1, const int & n){ for ( int i=0; i<n; ++i ){ lambda_theta_p_1.get_array()[i]=(lambda*eigen_L.get_eigen_values().get_array()[i]+1.0); } } // the equation on the second page of online method void _get_yTH_1_y_s_(const My_Vector<double> & Uty, const int & n, My_Vector<double> & lambda_theta_p_1, double & yTH_1_y, double & yTH_1H_1H_1_y ){ yTH_1_y=0.0; yTH_1H_1H_1_y=0.0; double temp1; for( int i=0; i<n; ++i ){ temp1 = Uty.get_array()[i]*Uty.get_array()[i]; yTH_1_y += (temp1/lambda_theta_p_1.get_array()[i]); yTH_1H_1H_1_y += (temp1/pow(lambda_theta_p_1.get_array()[i], 3.0)); } } // _get_yTPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxy, ypw, wpw ) void _get_yTPxy_(const int & n, const My_Vector<double> & y, const My_matrix<double> & UtW, const My_Vector<double> & Uty, const Eigen_result & eigen_L, const double & lambda, const int & q, const My_Vector<double> & lambda_theta_p_1, double & yTPxy, My_matrix<double> & ypw, double *** wpw ) { yTPxy=0.0; int i, j, k, l; //for aTPiPib begin // for the wpw term in the function begin k=-1;// put k=0 part out of for loop is good for auto vectorization // here i is the index of a, j is the index of b and k is the index of P for( i=0; i<q; ++i ){ // since the index could not be -1, so here we use k+1 as the third index, attention, this only affect the third index for( j=0; j<q; ++j ){ wpw[i][j][k+1] = 0.0; for( l=0; l<n; ++l ) { wpw[i][j][k+1] += UtW.get_matrix()[l][i]*UtW.get_matrix()[l][j]/lambda_theta_p_1.get_array()[l]; // todo check, there maybe something wrong with the indeX here } } } for( k=0; k<q; ++k ){ for( i=0; i<q; ++i ){ for( j=0; j<q; ++j ){ wpw[i][j][k+1] = wpw[i][j][k+1-1] - wpw[i][k][k+1-1]*wpw[j][k][k+1-1]/wpw[k][k][k+1-1]; } } } // for the wpw term in the function end // this here we have a==b==y, // for the ypw term in the function begin k=-1; // j is the index of b and k is the index of P for( j=0; j<q; ++j ){ ypw.get_matrix()[j][k+1] = 0.0; for( l=0; l<n; ++l ) { ypw.get_matrix()[j][k+1] += Uty.get_array()[l]*UtW.get_matrix()[l][j]/lambda_theta_p_1.get_array()[l]; } } for( k=0; k < q; ++k ){ for( j=0; j<q; ++j ){ ypw.get_matrix()[j][k+1] = ypw.get_matrix()[j][k+1-1] - ypw.get_matrix()[k][k+1-1]*wpw[j][k][k+1-1]/wpw[k][k][k+1-1]; } } // for the ypw term in the function end k=-1; for( l=0; l<n; ++l ) { yTPxy += Uty.get_array()[l] * Uty.get_array()[l] / lambda_theta_p_1.get_array()[l]; } for( k=0; k < q; ++k ){ yTPxy = yTPxy - ypw.get_matrix()[k][k+1-1]*ypw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]; } } void _get_yTPxPxy_(const int & n, const My_Vector<double> & y, const My_matrix<double> & UtW, const My_Vector<double> & Uty, const Eigen_result & eigen_L, const double & lambda, const int & q, const My_Vector<double> & lambda_theta_p_1, double & yTPxPxy, const My_matrix<double> & ypw, My_matrix<double> & yppw, double *** wpw, double *** wppw ) { int i, j, k, l; yTPxPxy=0; //for aTPiPib begin // for the wppw term in the function begin k=-1;// put k=0 part out of for loop is good for auto vectorization // here i is the index of a, j is the index of b and k is the index of P for( i=0; i<q; ++i ){ for( j=0; j<q; ++j ){ wppw[i][j][k+1] = 0.0; for( l=0; l<n; ++l ) { wppw[i][j][k+1] += UtW.get_matrix()[l][i]*UtW.get_matrix()[l][j]/pow(lambda_theta_p_1.get_array()[l], 2); } } } for( k=0; k < q; ++k ){ for( i=0; i<q; ++i ){ for( j=0; j<q; ++j ){ wppw[i][j][k+1] = wppw[i][j][k+1-1] + wpw[i][k][k+1-1]*wpw[j][k][k+1-1]* wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1],2)- wpw[i][k][k+1-1]*wppw[j][k][k+1-1]/wpw[k][k][k+1-1]- wpw[j][k][k+1-1]*wppw[i][k][k+1-1]/wpw[k][k][k+1-1]; } } } // for the wppw term in the function end // this here we have a==b==y // for the yppw term in the function begin k=-1; // j is the index of b and k is the index of P for( j=0; j<q; ++j ){ yppw.get_matrix()[j][k+1] = 0.0; for( l=0; l<n; ++l ) { yppw.get_matrix()[j][k+1] += Uty.get_array()[l]*UtW.get_matrix()[l][j]/pow(lambda_theta_p_1.get_array()[l], 2); } } for( k=0; k < q; ++k ){ for( j=0; j<q; ++j ){ yppw.get_matrix()[j][k+1] = yppw.get_matrix()[j][k+1-1] + ypw.get_matrix()[k][k+1-1]*wpw[j][k][k+1-1]* wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1],2)- ypw.get_matrix()[k][k+1-1]*wppw[j][k][k+1-1]/wpw[k][k][k+1-1]- wpw[j][k][k+1-1]*yppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]; } } // for the yppw term in the function end k=-1; for( j=0; j<n; ++j ) { yTPxPxy += Uty.get_array()[j] * Uty.get_array()[j] / pow(lambda_theta_p_1.get_array()[j], 2); } for( k=0; k < q; ++k ){ yTPxPxy = yTPxPxy + ypw.get_matrix()[k][k+1-1]*ypw.get_matrix()[k][k+1-1]* wppw[k][k][k+1-1]/pow((wpw[k][k][k+1-1]), 2) - 2*(ypw.get_matrix()[k][k+1-1]*yppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]); } //for aTPiPib end } void _get_yTPxPxPxy_(const int & n, const My_Vector<double> & y, const My_matrix<double> & UtW, const My_Vector<double> & Uty, const Eigen_result & eigen_L, const double & lambda, const int & q, const My_Vector<double> & lambda_theta_p_1, double & yTPxPxPxy, const My_matrix<double> & ypw, const My_matrix<double> & yppw, My_matrix<double> & ypppw, double *** wpw, double *** wppw, double *** wpppw) { yTPxPxPxy=0.0; int i, j, k, l; //for aTPiPiPib begin // for the wpppw term in the function begin k=-1;// put k=0 part out of for loop is good for auto vectorization // here i is the index of a, j is the index of b and k is the index of P for( i=0; i<q; ++i ){ for( j=0; j<q; ++j ){ wpppw[i][j][k+1] = 0.0; for( l=0; l<n; ++l ) { wpppw[i][j][k+1] += UtW.get_matrix()[l][i]*UtW.get_matrix()[l][j]/pow(lambda_theta_p_1.get_array()[l], 3); } } } for( k=0; k < q; ++k ){ for( i=0; i<q; ++i ){ for( j=0; j<q; ++j ){ wpppw[i][j][k+1] = wpppw[i][j][k+1-1] - wpw[i][k][k+1-1]*wpw[j][k][k+1-1]* pow(wppw[k][k][k+1-1],2)/pow(wpw[k][k][k+1-1],3)- wpw[i][k][k+1-1]*wpppw[j][k][k+1-1]/wpw[k][k][k+1-1]- wpw[j][k][k+1-1]*wpppw[i][k][k+1-1]/wpw[k][k][k+1-1]- wppw[i][k][k+1-1]*wppw[j][k][k+1-1]/wpw[k][k][k+1-1]+ wpw[i][k][k+1-1]*wppw[j][k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ wpw[j][k][k+1-1]*wppw[i][k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ wpw[i][k][k+1-1]*wpw[j][k][k+1-1]*wpppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2); } } } // for the wpppw term in the function end // this here we have a==b==y // for the ypppw term in the function begin k=-1; // j is the index of b and k is the index of P for( j=0; j<q; ++j ){ ypppw.get_matrix()[j][k+1] = 0.0; for( l=0; l<n; ++l ) { ypppw.get_matrix()[j][k+1] += Uty.get_array()[l]*UtW.get_matrix()[l][j]/pow(lambda_theta_p_1.get_array()[l], 3); } } for( k=0; k < q; ++k ){ for( j=0; j<q; ++j ){ ypppw.get_matrix()[j][k+1] = ypppw.get_matrix()[j][k+1-1] - ypw.get_matrix()[k][k+1-1]*wpw[j][k][k+1-1] *pow(wppw[k][k][k+1-1], 2)/pow(wpw[k][k][k+1-1], 3)- ypw.get_matrix()[k][k+1-1]*wpppw[j][k][k+1-1]/wpw[k][k][k+1-1]- wpw[j][k][k+1-1]*ypppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]- yppw.get_matrix()[k][k+1-1]*wppw[j][k][k+1-1]/wpw[k][k][k+1-1]+ ypw.get_matrix()[k][k+1-1]*wppw[j][k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ wpw[j][k][k+1-1]*yppw.get_matrix()[k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ ypw.get_matrix()[k][k+1-1]*wpw[j][k][k+1-1]*wpppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2); } } // for the ypppw term in the function end k=-1; for( j=0; j<n; ++j ) { yTPxPxPxy += Uty.get_array()[j] * Uty.get_array()[j] / pow(lambda_theta_p_1.get_array()[j], 3); } for( k=0; k < q; ++k ){ yTPxPxPxy = yTPxPxPxy - pow(ypw.get_matrix()[k][k+1-1], 2) * pow(wppw[k][k][k+1-1], 2)/pow(wpw[k][k][k+1-1], 3)- ypw.get_matrix()[k][k+1-1]*ypppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]- ypw.get_matrix()[k][k+1-1]*ypppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]- yppw.get_matrix()[k][k+1-1]*yppw.get_matrix()[k][k+1-1]/wpw[k][k][k+1-1]+ ypw.get_matrix()[k][k+1-1]*yppw.get_matrix()[k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ ypw.get_matrix()[k][k+1-1]*yppw.get_matrix()[k][k+1-1]*wppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2)+ ypw.get_matrix()[k][k+1-1]*ypw.get_matrix()[k][k+1-1]*wpppw[k][k][k+1-1]/pow(wpw[k][k][k+1-1], 2); } //for aTPiPib end } // the euqation on the second page of online method double _get_log_det_H_(const My_Vector<double> & lambda_theta_p_1, const int & n){ double result = 0.0; for( int i=0; i<n; ++i ){ if( lambda_theta_p_1.get_array()[i]<0 ){ result += log(-lambda_theta_p_1.get_array()[i]); //try to avoid to use if for avx }else if( lambda_theta_p_1.get_array()[i]>0 ) { result += log(lambda_theta_p_1.get_array()[i]); //try to avoid to use if for avx } } return result; } // the eqaution on the second page of online method void _get_trace_H_1_s_(const My_Vector<double> & lambda_theta_p_1, const int & n, double & trace_H_1, double & trace_H_1_H_1){ trace_H_1 = 0.0; trace_H_1_H_1 = 0.0; for( int i=0; i<n; ++i ){ trace_H_1 += 1.0/lambda_theta_p_1.get_array()[i]; trace_H_1_H_1 += 1.0/pow(lambda_theta_p_1.get_array()[i], 2); } } // the first equation of 3.1.4 on page 5 of supplementary document // this one rely on the result from _get_trace_H_1_ double _get_trace_H_1_G_( const double & lambda, const int & n, const double & trace_H_1){ return (n-trace_H_1)/lambda; } // the second equation of 3.1.4 on page 5 of supplementary document // this one rely on the result from _get_trace_H_1_ and _get_trace_H_1_H_1_ double _get_trace_H_1_G_H_1_G_(const double & lambda, const int & n, const double & trace_H_1, const double & trace_H_1_H_1){ return (n+trace_H_1_H_1-2.0*trace_H_1)/pow(lambda, 2); } void _get_trace_Px_s_( const double & trace_H_1, const double & trace_H_1_H_1, const My_Vector<double> & lambda_theta_p_1, const My_matrix<double> & UtW, const int & n, const int & q, double *** wpw, double *** wppw, double *** wpppw, double & trace_P, double & trace_PP){ int k=0; trace_P = trace_H_1 - wppw[k][k][k+1-1]/wpw[k][k][k+1-1]; trace_PP = trace_H_1_H_1 + pow(wppw[k][k][k+1-1], 2)/pow(wpw[k][k][k+1-1], 2)-2*wpppw[k][k][k+1-1]/wpw[k][k][k+1-1]; for( k=1; k < q; ++k ){ trace_P = trace_P - wppw[k][k][k+1-1]/wpw[k][k][k+1-1]; trace_PP = trace_PP + pow(wppw[k][k][k+1-1], 2)/pow(wpw[k][k][k+1-1], 2)-2*wpppw[k][k][k+1-1]/wpw[k][k][k+1-1]; } } // the third equation of 3.1.4 on page 5 of supplementary document double _get_trace_Px_G_(const double & lambda, const int & p, const double & trace_Px){ return (p-trace_Px)/lambda; } // the fourth equation of 3.1.4 on page 5 of supplementary document double _get_trace_Px_G_Px_G_(const double & lambda, const int & p, const double & trace_Px, const double & trace_Px_Px){ return (p+trace_Px_Px-2*trace_Px)/pow(lambda,2); } double get_det_WTH_1W_( const int & n, const int & q, const My_matrix<double> & UtW, double *** wpw, const My_Vector<double> & lambda_theta_p_1){ // todo check, there maybe something wrong double WTH_1W = 0.0; int i, j = 0; for( i=0; i<n; ++i ){ WTH_1W += UtW.get_matrix()[i][0]*UtW.get_matrix()[i][0]/lambda_theta_p_1.get_array()[i]; } WTH_1W = WTH_1W * wpw[j][j][j+1-1]; for( j=1; j<q; ++j ){ WTH_1W = WTH_1W * wpw[j][j][j+1-1]; } return WTH_1W; } // the fifth equation of 3.1.4 on page 5 of supplementary document // rely one the function get_ytPxy and get_ytPxPxy double get_ytPxGPxy( const double & ytPxy, const double & ytPxPxy, const double & lambda){ return (ytPxy-ytPxPxy)/lambda; } // the sixth equation of 3.1.4 on page 5 of supplementary document // rely one the function get_ytPxy, get_ytPxPxy and get_ytPxPxPxy double get_yTPxGPxGPxy( const double & ytPxy, const double & ytPxPxPxy, const double & ytPxPxy, const double & lambda ){ return (ytPxy+ytPxPxPxy-2*ytPxPxy)/pow(lambda, 2); } // simplified log-likelihoods (eq. 3 from gemma paper) double _sll_( const int & n, const double & log_det_H, const double & ytPxy){ return 0.5*n*log((double)n/(2*M_PI)) - 0.5*n - 0.5*log_det_H-0.5*n*log(ytPxy); } // simplified log-restricted likelihoods (eq. 4 from gemma paper) // could not be used, since the function to calculate det_WTW is not implemented double _srll_( const int & p, const double & log_det_H, const double & det_WTW, const double & det_WTH_1_W, const double & ytPxy){ return 0.5*(p)*log((double)p/(2*M_PI))-0.5*p+0.5*log(det_WTW)-0.5*log_det_H-0.5*log(det_WTH_1_W) - 0.5*p*log(ytPxy); } // simplified log-restricted likelihoods (eq. 4 from gemma paper) // this is a simplified function, since det_WTH_1_W is not affected by lambda value. It could be only used for newton optimization double _srll_simple_( const int & p, const double & det_h, const double & det_WTH_1_W, const double & ytPxy){ return -0.5*log(det_h)-0.5*log(det_WTH_1_W) - 0.5*p*log(ytPxy); } // (eq. 5 from gemma paper) double _dsll_(const double & trace_H_1_G, const int & n, const double & ytPxGPxy, const double & ytPxy){ return -0.5*trace_H_1_G+0.5*n*ytPxGPxy/ytPxy; } // (eq. 7 from gemma paper) double _dsrll_(const double & trace_Px_G, const int & p, const double & ytPxGPxy, const double & ytPxy){ return -0.5/trace_Px_G + 0.5*p*ytPxGPxy/ytPxy; } // (eq. 6 from gemma paper) double _ddsll_( const double & trace_H_1_G_H_1_G, const int & n, const double & yTPxGPxGPxy, const double & ytPxy, const double & ytPxGPxy ){ return 0.5*trace_H_1_G_H_1_G-0.5*n*(2*yTPxGPxGPxy*ytPxy-pow(ytPxGPxy,2))/pow(ytPxy, 2); } // (eq. 8 from gemma paper) double _ddsrll_(const double & trace_Px_G_Px_G, const int & p, const double & yTPxGPxGPxy, const double & ytPxy, const double & ytPxGPxy){ return 0.5*trace_Px_G_Px_G - 0.5*p*(2*yTPxGPxGPxy*ytPxy-pow(ytPxGPxy, 2)) / pow(ytPxy,2); } // this is an implementation of the euqation 2.6 from publication: //Generalized Newton Raphson’s method free from second derivative, Journal of Nonlinear Science and Applications 9(5):2823-2831 · April 2016 DOI: 10.22436/jnsa.009.05.77 // however this is not the original publication, so do not cite this paper for publication purpose int newton_raphson_ll( double & new_lambda, const double & eps, const int & js, const int & n, const int & q, const Eigen_result & eigen_L, const My_Vector<double> & y, const My_matrix<double> & UtW, const My_Vector<double> & Uty, double *** wpw, double *** wppw, double *** wpppw, My_matrix<double> & ypw, My_matrix<double> & yppw, My_matrix<double> & ypppw ){ // js maximum number of iteration int k=1, l=js; double y0, y1, y2, d, u, x0=new_lambda, x1=new_lambda; My_Vector<double> lambda_theta_p_1(n); double trace_H_1; double trace_H_1_H_1; get_lambda_theta_p_1_( x1, eigen_L, lambda_theta_p_1, n); double log_det_H = _get_log_det_H_(lambda_theta_p_1, n); double yTH_1_y; double yTH_1H_1H_1_y; _get_yTH_1_y_s_(Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); double yTPxy; double yTPxPxy; double yTPxPxPxy; _get_yTPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxy, ypw, wpw ); //there maybe something wrong with this function. Because yTPxy should not be negative //std::cout << "line 404 _get_yTPxy_ " << yTPxy << std::endl; _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); double trace_H_1_G = _get_trace_H_1_G_( x1, n, trace_H_1); double trace_H_1_G_H_1_G = _get_trace_H_1_G_H_1_G_(x1, n, trace_H_1, trace_H_1_H_1); double ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxPxy, x1); double yTPxGPxGPxy = get_yTPxGPxGPxy(yTPxy, yTPxPxPxy, yTPxPxy, x1); y0=_sll_(n, log_det_H, yTPxy); y1=_dsll_(trace_H_1_G, n, ytPxGPxy, yTPxy); y2=_ddsll_(trace_H_1_G_H_1_G, n, yTPxGPxGPxy, yTPxy, ytPxGPxy); d=eps+1.0; while( (d>=eps) && (l!=0) ){ x0=x1; if( fabs(y1)+1.0 == 1.0 ){ std::cout << "error" << std::endl; return -1; } x1 = x0 - y1/y2; get_lambda_theta_p_1_( x1, eigen_L, lambda_theta_p_1, n); log_det_H = _get_log_det_H_(lambda_theta_p_1, n); _get_yTH_1_y_s_(Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxy, ypw, wpw ); _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); trace_H_1_G = _get_trace_H_1_G_( x1, n, trace_H_1); trace_H_1_G_H_1_G = _get_trace_H_1_G_H_1_G_(x1, n, trace_H_1, trace_H_1_H_1); ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxPxy, x1); yTPxGPxGPxy = get_yTPxGPxGPxy(yTPxy, yTPxPxPxy, yTPxPxy, x1); y1=_dsll_(trace_H_1_G, n, ytPxGPxy, yTPxy); y2=_ddsll_(trace_H_1_G_H_1_G, n, yTPxGPxGPxy, yTPxy, ytPxGPxy); d=fabs(x1-x0); --l; } new_lambda=x0; k=js-l; return k; } int newton_raphson_reml( double & new_lambda, const double & eps, const int & js, const int & n, const Eigen_result & eigen_L, const My_Vector<double> & y, const int & q, const int & p, double *** wpw, double *** wppw, double *** wpppw, const My_matrix<double> & UtW, const My_Vector<double> & Uty, My_matrix<double> & ypw, My_matrix<double> & yppw, My_matrix<double> & ypppw){ // js maximum number of iteration int k=1,l=js; double y1, y2, d, x0, x1=new_lambda, u; x0=new_lambda; My_Vector<double> lambda_theta_p_1(n); double trace_H_1; double trace_H_1_H_1; get_lambda_theta_p_1_( x1, eigen_L, lambda_theta_p_1, n); double yTH_1_y; double yTH_1H_1H_1_y; _get_yTH_1_y_s_(Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); double yTPxy; double yTPxPxy; double yTPxPxPxy; _get_yTPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxy, ypw, wpw ); _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); double ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxPxy, x1); double yTPxGPxGPxy = get_yTPxGPxGPxy(yTPxy, yTPxPxPxy, yTPxPxy, x1); double trace_P; double trace_PP; _get_trace_Px_s_( trace_H_1, trace_H_1_H_1, lambda_theta_p_1, UtW, n, q, wpw, wppw, wpppw, trace_P, trace_PP); double trace_Px_G = _get_trace_Px_G_(x1, p, trace_P); double trace_Px_G_Px_G = _get_trace_Px_G_Px_G_(x1, p, trace_P, trace_PP); y1=_dsrll_(trace_Px_G, p, ytPxGPxy, yTPxy); y2=_ddsrll_(trace_Px_G_Px_G, p, yTPxGPxGPxy, yTPxy, ytPxGPxy); d=eps+1.0; while( (d>=eps) && (l!=0) ){ x0=x1; if( fabs(y2)+1.0 == 1.0 ){ std::cout << "error" << std::endl; return -1; } x1 = x0 - y1/y2; get_lambda_theta_p_1_( x1, eigen_L, lambda_theta_p_1, n); _get_yTH_1_y_s_(Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxy, ypw, wpw ); _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x1, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxy, x1); yTPxGPxGPxy = get_yTPxGPxGPxy(yTPxy, yTPxPxPxy, yTPxPxy, x1); _get_trace_Px_s_( trace_H_1, trace_H_1_H_1, lambda_theta_p_1, UtW, n, q, wpw, wppw, wpppw, trace_P, trace_PP); trace_Px_G = _get_trace_Px_G_(x1, p, trace_P); trace_Px_G_Px_G = _get_trace_Px_G_Px_G_(x1, p, trace_P, trace_PP); y1=_dsrll_(trace_Px_G, p, ytPxGPxy, yTPxy); y2=_ddsrll_(trace_Px_G_Px_G, p, yTPxGPxGPxy, yTPxy, ytPxGPxy); d=fabs(x1-x0); // u=fabs(y0); // if( u>d ){ // d=u; // } --l; } new_lambda=x0; k=js-l; return k; } double gemma_estimates ( const My_Vector<double> & y, const My_Vector<double> & Uty, const My_matrix<double> & x, const My_matrix<double> & w, const Eigen_result & eigen_L, const int & ngrids, const double & llim, const double &ulim, const double & eps, const std::string & method, const int & maxiter ){ double lambda; return gemma_estimates ( y, Uty, x, w, eigen_L, ngrids, llim, ulim, eps, method, maxiter, lambda ); } double gemma_estimates ( const My_Vector<double> & y, const My_Vector<double> & Uty, const My_matrix<double> & w, const Eigen_result & eigen_L, const int & ngrids, const double & llim, const double &ulim, const double & eps, const std::string & method, const int & maxiter ){ My_matrix<double> x(y.get_length(), 0); double lambda; return gemma_estimates ( y, Uty, x, w, eigen_L, ngrids, llim, ulim, eps, method, maxiter, lambda ); } double gemma_estimates ( const My_Vector<double> & y, const My_Vector<double> & Uty, const My_matrix<double> & w, const Eigen_result & eigen_L, const int & ngrids, const double & llim, const double &ulim, const double & eps, const std::string & method, const int & maxiter, double & lambda ){ My_matrix<double> x(y.get_length(), 0); return gemma_estimates ( y, Uty, x, w, eigen_L, ngrids, llim, ulim, eps, method, maxiter, lambda ); } double gemma_estimates ( const My_Vector<double> & y, const My_Vector<double> & Uty, const My_matrix<double> & x, const My_matrix<double> & w, const Eigen_result & eigen_L, const int & ngrids, const double & llim, const double &ulim, const double & eps, const std::string & method, const int & maxiter, double & lambda ){ assert( y.get_length()==w.get_num_row() ); int i, j; int n = y.get_length(); int c = w.get_num_column(); int cx = x.get_num_column(); int q = c + cx; int p = n - q; // in the gemma paper the cx == 1, so in their function they have n-c-1 in the equation (4) int m = ngrids+1; My_matrix<double> W(x.get_num_row(), q); if( x.get_num_column()>0 ){ append_two_matrix( w, x, W); } else { W.value_copy(w); } My_matrix<double> UtW(n, q); trmul( eigen_L.get_eigen_vectors(), W, UtW); My_Vector<double> log_lambdas(m); // the space for deltas to search My_Vector<double> lambdas(m); for ( i=0; i < m; ++i ){ log_lambdas.get_array()[i] = (double(i) / ngrids)*(ulim - llim) + llim; lambdas.get_array()[i] = pow(10, log_lambdas.get_array()[i]); } double x0; double log_det_H; double trace_H_1; double trace_H_1_H_1; double trace_H_1_G; double yTH_1_y; double yTPxPxPxy; double yTH_1H_1H_1_y; double yTPxy; double yTPxPxy; double ytPxGPxy; double trace_P; double trace_PP; double trace_Px_G; double det_WTH_1_W; My_matrix<double> P(n, n); My_Vector<double> lls(m); My_Vector<double> dlls(m); //matrix for lambda estimation begin double *** wpw = new double** [q]; for( i=0; i<q; ++i ){ wpw[i]= new double* [q]; for( j=0; j<q; ++j ){ wpw[i][j] = new double[q+1]; } } double *** wppw = new double** [q]; for( i=0; i<q; ++i ){ wppw[i]= new double* [q]; for( j=0; j<q; ++j ){ wppw[i][j] = new double[q+1]; } } double *** wpppw = new double** [q]; for( i=0; i<q; ++i ){ wpppw[i]= new double* [q]; for( j=0; j<q; ++j ){ wpppw[i][j] = new double[q+1]; } } My_matrix<double> ypw(q, q+1); My_matrix<double> yppw(q, q+1); My_matrix<double> ypppw(q, q+1); //matrix for lambda estimation end My_Vector<double> lambda_theta_p_1(n); if (method.compare("REML") == 0){ for( i=0; i<m; ++i ){ x0 = lambdas.get_array()[i]; get_lambda_theta_p_1_( x0, eigen_L, lambda_theta_p_1, n); log_det_H = _get_log_det_H_(lambda_theta_p_1, n); _get_yTH_1_y_s_( Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxy, ypw, wpw ); _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxy, x0); _get_trace_Px_s_( trace_H_1, trace_H_1_H_1, lambda_theta_p_1, UtW, n, q, wpw, wppw, wpppw, trace_P, trace_PP); trace_Px_G = _get_trace_Px_G_(x0, p, trace_P); det_WTH_1_W = get_det_WTH_1W_( n, q, UtW, wpw, lambda_theta_p_1 ); lls.get_array()[i] =_srll_simple_(p, log_det_H, det_WTH_1_W, yTPxy); dlls.get_array()[i]=_dsrll_(trace_Px_G, p, ytPxGPxy, yTPxy); } }else if (method.compare("ML") == 0){ for( i=0; i<m; ++i ){ x0 = lambdas.get_array()[i]; get_lambda_theta_p_1_( x0, eigen_L, lambda_theta_p_1, n); log_det_H = _get_log_det_H_(lambda_theta_p_1, n); _get_yTH_1_y_s_(Uty, n, lambda_theta_p_1, yTH_1_y, yTH_1H_1H_1_y ); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxy, ypw, wpw ); _get_yTPxPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxPxy, ypw, yppw, wpw, wppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); trace_H_1_G = _get_trace_H_1_G_( x0, n, trace_H_1); ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxPxy, x0); _get_yTPxPxPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxPxPxy, ypw, yppw, ypppw, wpw, wppw, wpppw ); _get_trace_H_1_s_(lambda_theta_p_1, n, trace_H_1, trace_H_1_H_1); double trace_H_1_G = _get_trace_H_1_G_( x0, n, trace_H_1); double trace_H_1_G_H_1_G = _get_trace_H_1_G_H_1_G_(x0, n, trace_H_1, trace_H_1_H_1); double ytPxGPxy = get_ytPxGPxy( yTPxy, yTPxPxy, x0); double yTPxGPxGPxy = get_yTPxGPxGPxy(yTPxy, yTPxPxPxy, yTPxPxy, x0); lls.get_array()[i] = _sll_( n, log_det_H, yTPxy); dlls.get_array()[i] = _dsll_( trace_H_1_G, n, ytPxGPxy, yTPxy); } } int max_ll_i = argmax(lls); double max_ll = lls.get_array()[max_ll_i]; double last_dll = dlls.get_array()[0]; std::map<int, double> zero_intervals; for ( i =0; i<m; ++i ){ if ( dlls.get_array()[i]<0 && last_dll>0 ){ zero_intervals[i] = lls.get_array()[i]; } last_dll = dlls.get_array()[i]; } double opt_lambda; double opt_ll; if (zero_intervals.size() > 0){ opt_ll = -DBL_MAX; int opt_i; for(std::map<int, double>::iterator it=zero_intervals.begin();it!=zero_intervals.end();++it){ if( it->second > opt_ll ){ opt_ll = it->second; opt_i = it->first; } } // if( (opt_i) <0 ){ opt_lambda = lambdas.get_array()[opt_i]; // }else{ // opt_lambda = lambdas.get_array()[opt_i - 1]; // } double new_opt_lambda = opt_lambda; if (method.compare("REML") == 0) { newton_raphson_reml( new_opt_lambda , eps, maxiter, n, eigen_L, y, q, p, wpw, wppw, wpppw, UtW, Uty, ypw, yppw, ypppw); }else if (method.compare("ML") == 0){ newton_raphson_ll( new_opt_lambda, eps, maxiter, n, q, eigen_L, y, UtW, Uty, wpw, wppw, wpppw, ypw, yppw, ypppw); } if (opt_i > 1 && lambdas.get_array()[opt_i - 1] - eps < new_opt_lambda && new_opt_lambda < lambdas.get_array()[opt_i] + eps){ opt_lambda = new_opt_lambda; }else if (opt_i == 1 && 0.0 < new_opt_lambda && new_opt_lambda < lambdas.get_array()[opt_i] + eps){ opt_lambda = new_opt_lambda; }else if(opt_i == m - 1 && new_opt_lambda > lambdas.get_array()[opt_i - 1] - eps ){ opt_lambda = new_opt_lambda; } get_lambda_theta_p_1_( opt_lambda, eigen_L, lambda_theta_p_1, n); log_det_H = _get_log_det_H_(lambda_theta_p_1, n); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxy, ypw, wpw ); opt_ll = _sll_( n, log_det_H, yTPxy); if (opt_ll < max_ll || std::isnan(opt_ll) ){ opt_lambda = lambdas.get_array()[max_ll_i]; } } else { opt_lambda = lambdas.get_array()[max_ll_i]; } // no matter use ml or reml to optimize the parameters, always use the ml function to get the likelyhood get_lambda_theta_p_1_( opt_lambda, eigen_L, lambda_theta_p_1, n); log_det_H = _get_log_det_H_(lambda_theta_p_1, n); _get_yTPxy_( n, y, UtW, Uty, eigen_L, x0, q, lambda_theta_p_1, yTPxy, ypw, wpw ); opt_ll = _sll_( n, log_det_H, yTPxy); for ( i=0; i<q; ++i ){ for ( j=0; j<q; ++j ){ delete [] wpw[i][j]; delete [] wppw[i][j]; delete [] wpppw[i][j]; } delete [] wpw[i]; delete [] wppw[i]; delete [] wpppw[i]; } delete [] wpw; delete [] wppw; delete [] wpppw; lambda = opt_lambda; // std::cout << "752 opt_lambda " << opt_lambda << std::endl; return opt_ll; // this function should return beta and likelihood for p-value computing } void CalcLmmVgVe(const My_Vector<double> & y, const Eigen_result & eigen_L, const My_matrix<double> &UtW, const My_Vector<double> & Uty, const double & lambda, double &vg, double &ve) { int q = UtW.get_num_column(); int n = UtW.get_num_row(); double yTPxy; My_matrix<double> ypw(q, q+1); int i, j; double *** wpw = new double** [q]; for( i=0; i<q; ++i ){ wpw[i]= new double* [q]; for( j=0; j<q; ++j ){ wpw[i][j] = new double[q+1]; } } My_Vector<double> lambda_theta_p_1(n); get_lambda_theta_p_1_( lambda, eigen_L, lambda_theta_p_1, n); _get_yTPxy_( n, y, UtW, Uty, eigen_L, lambda, q, lambda_theta_p_1, yTPxy, ypw, wpw ); ve = yTPxy / (double)(n - q); vg = ve * lambda; } /* * get_lambda_theta_p_1_ * _get_yTH_1_y_s_ * * get_lambda_theta_p_1_ * _get_yTPxy_s_ * * get_lambda_theta_p_1_ * _get_det_H_ * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * double _get_trace_H_1_G_ * * get_lambda_theta_p_1_ * _get_yTPxy_s_ * double get_det_WTH_1W_ * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * double _get_trace_H_1_G_H_1_G_ * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * _get_yTPxy_s_ * void _get_trace_Px_s_ * double _get_trace_Px_G_ * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * _get_yTPxy_s_ * void _get_trace_Px_s_ * double _get_trace_Px_G_Px_G_ * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * _get_yTPxy_s_ * double get_ytPxGPxy * * get_lambda_theta_p_1_ * void _get_trace_H_1_s_ * _get_yTPxy_s_ * double get_yTPxGPxGPxy * */ /*My_Vector<double> & get_a_t_h_1_b( My_matrix<double> & a, My_matrix<double> & b, const Eigen_result & eigen_L, const double & lamda, My_Vector<double> & result ){ My_matrix UTa(a.get_num_row(), a.get_num_column()); trmul(a, eigen_L.get_eigen_vectors(), UTa); My_matrix UTb(b.get_num_row(), b.get_num_column()); trmul(b, eigen_L.get_eigen_vectors(), UTb); int j; for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j]=0; } double lamda_p_theta_1; for( int i=0; i<a.get_num_row(); ++i ){ lamda_p_theta_1 = 1/(lamda*eigen_L.get_eigen_values().get_array()[i]+1); for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j] = UTa.get_matrix()[i][j]*UTb.get_matrix()[i][j]*lamda_p_theta_1; } } return result; } My_Vector<double> & get_a_t_h_1_h_1_b( My_matrix<double> & a, My_matrix<double> & b, const Eigen_result & eigen_L, const double & lamda, My_Vector<double> & result ){ My_matrix UTa(a.get_num_row(), a.get_num_column()); trmul(a, eigen_L.get_eigen_vectors(), UTa); My_matrix UTb(b.get_num_row(), b.get_num_column()); trmul(b, eigen_L.get_eigen_vectors(), UTb); int j; for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j]=0; } double lamda_p_theta_2; for( int i=0; i<a.get_num_row(); ++i ){ lamda_p_theta_2 = 2/(lamda*eigen_L.get_eigen_values().get_array()[i]+1); for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j] = UTa.get_matrix()[i][j]*UTb.get_matrix()[i][j]*lamda_p_theta_2; } } return result; } My_Vector<double> & get_a_t_h_1_h_1_h_1_b( My_matrix<double> & a, My_matrix<double> & b, const Eigen_result & eigen_L, const double & lamda, My_Vector<double> & result ){ My_matrix UTa(a.get_num_row(), a.get_num_column()); trmul(a, eigen_L.get_eigen_vectors(), UTa); My_matrix UTb(b.get_num_row(), b.get_num_column()); trmul(b, eigen_L.get_eigen_vectors(), UTb); int j; for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j]=0; } double lamda_p_theta_3; for( int i=0; i<a.get_num_row(); ++i ){ lamda_p_theta_3 = 3/(lamda*eigen_L.get_eigen_values().get_array()[i]+1); for( j=0; j<a.get_num_column(); ++j ){ result.get_array()[j] = UTa.get_matrix()[i][j]*UTb.get_matrix()[i][j]*lamda_p_theta_3; } } return result; } My_matrix<double> & get_Pi(int i, My_matrix<double> & H1, const My_matrix<double> & W, const My_matrix<double> & Wt, My_matrix<double> & Pi, const int & n){ // i = #covariants + independent variants if( -1 == i ){ return H1; }else{ My_matrix<double> Pi_1(n, n); get_Pi(i-1, H1, W, Wt, Pi_1, n); int j, z, is; My_Vector<double> wiTPi_1(n); for( j=0; j<n; ++j ){ wiTPi_1.get_array()[j]=0; for( z=0; z<n; ++z ){ wiTPi_1.get_array()[j] += Wt.get_matrix()[i][z]*Pi_1.get_matrix()[j][z]; } } double wiTPi_1_wi_1_1 = 0.0; for( j=0; j<n; ++j ){ wiTPi_1_wi_1_1 += wiTPi_1.get_array()[j]*W.get_matrix()[j][i]; } wiTPi_1_wi_1_1=1/wiTPi_1_wi_1_1; My_Vector<double> Pi_1_wi(W.get_num_row()); for( j=0; j<n; ++j ){ Pi_1_wi.get_array()[j]=0; for( z=0; z<n; ++z ){ Pi_1_wi.get_array()[j] += Pi_1.get_matrix()[j][z]*W.get_matrix()[j][i]; } } for( j=0; j<n; ++j ){ for( z=0; z<n; ++z ){ Pi.get_matrix()[j][z] = Pi_1.get_matrix()[j][z] - Pi_1_wi.get_array()[j] * wiTPi_1_wi_1_1 * wiTPi_1.get_array()[z]; } } return Pi; } } // this function is somehow complex, should be careful for debuging double get_det_W_T_h_1_W( int i, My_matrix<double> & W, const My_matrix<double> & H1, const int & n, const My_matrix<double> * P ){ if( i==1 ){ double witpi_1wi=0.0; My_Vector witpi_1(n); int j, z; for(j=0; j<n; ++j){ witpi_1.get_array()[j]=0; for(z=0; z<n; ++z){ witpi_1.get_array()[j] += W.get_matrix()[z][i] * P[i-1].get_matrix()[j][z]; } witpi_1wi += witpi_1.get_array()[j] * W.get_matrix()[j][i]; } My_Vector<double> wi1t_h1(n); for( j=0; j<n; ++j ){ wi1t_h1.get_array()[j] = 0; for(z=0; z<n; ++z){ wi1t_h1.get_array()[j] += W.get_matrix()[z][0] * H1.get_matrix()[j][z]; } } double wi1t_h1_wi1(0.0); for( j=0; j<W.get_num_row(); ++j ){ wi1t_h1_wi1 += wi1t_h1.get_array()[j]*W.get_matrix()[j][0]; } return witpi_1wi * wi1t_h1_wi1; }else{ double witpi_1wi=0.0; My_Vector witpi_1(n); int j, z; for(j=0; j<n; ++j){ witpi_1.get_array()[j]=0; for(z=0; z<n; ++z){ witpi_1.get_array()[j] += W.get_matrix()[z][i] * P[i-1].get_matrix()[j][z]; } witpi_1wi += witpi_1.get_array()[j] * W.get_matrix()[j][i]; } int next_i = i - 1; return witpi_1wi * get_det_W_T_h_1_W( next_i, W, H1, n, P ); } } */ /* // the euqation on the online method part of calculation of the basic quantities double _get_aTh_1b( const My_Vector<double> & va, const My_Vector<double> & vb, const int & n, const Eigen_result & eigen_L, const double & lambda ){ double result = 0.0; for( int i=0; i<n; ++i ){ result += (va.get_array()[i]*vb.get_array()[i])/(lambda*eigen_L.get_eigen_values().get_array()[i]+1); } return result; } // the euqation on the online method part of calculation of the basic quantities double _get_aTh_1h_1b( const My_Vector<double> & va, const My_Vector<double> & vb, const int & n, const Eigen_result & eigen_L, const double & lambda ){ double result = 0.0; for( int i=0; i<n; ++i ){ result += (va.get_array()[i]*vb.get_array()[i])/pow((lambda*eigen_L.get_eigen_values().get_array()[i]+1),2); } return result; } // the euqation on the online method part of calculation of the basic quantities double _get_aTh_1h_1h_1b( const My_Vector<double> & va, const My_Vector<double> & vb, const int & n, const Eigen_result & eigen_L, const double & lambda ){ double result = 0.0; for( int i=0; i<n; ++i ){ result += (va.get_array()[i]*vb.get_array()[i])/pow((lambda*eigen_L.get_eigen_values().get_array()[i]+1),3); } return result; } */ /*// the third equation of 3.1.5 on page 6 of supplementary document void _set_aTPibs( const int & q, const double & aTh_1b, const double & aTh_1Wi, const double & bTh_1Wi, const double & WiTh_1Wi, const My_Vector<double> & aTPi_1Wi, const My_Vector<double> & bTPi_1Wi, const My_Vector<double> & WiTPi_1Wi, My_Vector<double> & aTPib){//todo aTPib.get_array()[0] = aTh_1b - aTh_1Wi*bTh_1Wi*WiTh_1Wi; for( int i=1; i<q; ++i ){ aTPib.get_array()[i] = aTPi_1Wi.get_array()[i-1] - aTPi_1Wi.get_array()[i]*bTPi_1Wi.get_array()[i]/WiTPi_1Wi.get_array()[i]; } } // the forth equation of 3.1.5 on page 6 of supplementary document void _set_atPiPib( const int & q, const double & aTh_1h_1b, const double & aTH_1Wi, const double & bTH_1Wi, const double & WiTh_1Wi, const double & WiTH_1H_1Wi, const double & bTH_1H_1Wi, const double & WiTH_1Wi, const double & aTH_1H_1Wi, const My_Vector<double> & aTPi_1Wi, const My_Vector<double> & bTPi_1Wi, const My_Vector<double> & WiTPi_1Wi, const My_Vector<double> & aTPi_1Pi_1Wi, const My_Vector<double> & bTPi_1Pi_1Wi, const My_Vector<double> & WiTPi_1Pi_1Wi, My_Vector<double> & aTPiPib){//todo aTPiPib.get_array()[0] = aTh_1h_1b + aTH_1Wi*bTH_1Wi*WiTH_1H_1Wi/pow(WiTh_1Wi, 2)- aTH_1Wi*bTH_1H_1Wi/WiTH_1Wi- bTH_1Wi*aTH_1H_1Wi/WiTH_1Wi; for( int i=1; i<q; ++i ){ aTPiPib.get_array()[i] = aTPiPib.get_array()[i-1] + aTPi_1Wi.get_array()[i-1]*bTPi_1Wi.get_array()[i-1]* WiTPi_1Pi_1Wi.get_array()[i-1]/pow(WiTPi_1Wi.get_array()[i-1], 2)- aTPi_1Wi.get_array()[i-1]*bTPi_1Pi_1Wi.get_array()[i-1]/WiTPi_1Wi.get_array()[i-1]- bTPi_1Wi.get_array()[i-1]*aTPi_1Pi_1Wi.get_array()[i-1]/WiTPi_1Wi.get_array()[i-1]; } } void _set_atPiPiPib( const int & q, const double & aTh_1h_1h_1b, const double & bTH_1H_1H_1Wi, const double & aTH_1H_1H_1Wi, const double & aTH_1Wi, const double & bTH_1Wi, const double & WiTH_1H_1H_1Wi, const double & WiTh_1Wi, const double & WiTH_1H_1Wi, const double & bTH_1H_1Wi, const double & WiTH_1Wi, const double & aTH_1H_1Wi, const My_Vector<double> & aTPi_1Wi, const My_Vector<double> & bTPi_1Wi, const My_Vector<double> & WiTPi_1Wi, const My_Vector<double> & aTPi_1Pi_1Wi, const My_Vector<double> & bTPi_1Pi_1Wi, const My_Vector<double> & WiTPi_1Pi_1Wi, const My_Vector<double> & bTPi_1Pi_1Pi_1Wi, const My_Vector<double> & aTPi_1Pi_1Pi_1Wi, const My_Vector<double> & WiTPi_1Pi_1Pi_1Wi, My_Vector<double> & atPiPiPib){//todo atPiPiPib.get_array()[0] = aTh_1h_1h_1b - aTH_1Wi*bTH_1Wi*pow(WiTH_1H_1Wi,2)/pow(WiTh_1Wi, 3) - aTH_1Wi*bTH_1H_1H_1Wi/WiTH_1Wi - bTH_1Wi*aTH_1H_1H_1Wi/WiTH_1Wi - aTH_1H_1Wi*bTH_1H_1Wi/WiTH_1Wi + aTH_1Wi*bTH_1H_1Wi*WiTH_1H_1Wi/pow(WiTH_1Wi, 2) + bTH_1Wi*aTH_1H_1Wi*WiTH_1H_1Wi/pow(WiTH_1Wi, 2) + aTH_1Wi*bTH_1Wi*WiTH_1H_1H_1Wi/pow(WiTH_1Wi, 2); for( int i=1; i<q; ++i ){ atPiPiPib.get_array()[i] = atPiPiPib.get_array()[i-1] - aTPi_1Wi.get_array()[i]*bTPi_1Wi.get_array()[i]*pow(WiTPi_1Pi_1Wi.get_array()[i],2)/pow(WiTPi_1Wi.get_array()[i], 3) - aTPi_1Wi.get_array()[i]*bTPi_1Pi_1Pi_1Wi.get_array()[i]/WiTPi_1Wi.get_array()[i] - bTPi_1Wi.get_array()[i]*aTPi_1Pi_1Pi_1Wi.get_array()[i]/WiTPi_1Wi.get_array()[i] - aTPi_1Pi_1Wi.get_array()[i]*bTPi_1Pi_1Wi.get_array()[i]/WiTPi_1Wi.get_array()[i] + aTPi_1Wi.get_array()[i]*bTPi_1Pi_1Wi.get_array()[i]*WiTPi_1Pi_1Wi.get_array()[i]/pow(WiTPi_1Wi.get_array()[i], 2) + bTPi_1Wi.get_array()[i]*aTPi_1Pi_1Wi.get_array()[i]*WiTPi_1Pi_1Wi.get_array()[i]/pow(WiTPi_1Wi.get_array()[i], 2) + aTPi_1Wi.get_array()[i]*bTPi_1Wi.get_array()[i]*WiTPi_1Pi_1Pi_1Wi.get_array()[i]/pow(WiTPi_1Wi.get_array()[i], 2); } } // the first equation of 3.1.5 on page 6 of supplementary document void _setTracePis( const int & q, const double & trace_H_1, My_Vector<double> & TracePis, My_Vector<double> & WiTPi_1wi, My_Vector<double> & WiTPi_1Pi_1wi){ //todo set WiTPi_1Pi_1wi and WiTPi_1wi TracePis.get_array()[0] = trace_H_1 - WiTPi_1Pi_1wi.get_array()[0]/WiTPi_1wi.get_array()[0]; for( int i=1; i<q; ++i ){ TracePis.get_array()[i]=0; TracePis.get_array()[i] = TracePis.get_array()[i-1]-WiTPi_1Pi_1wi.get_array()[i]/WiTPi_1wi.get_array()[i]; } } // the second equation of 3.1.5 on page 6 of supplementary document void _setTracePiPis( const int & q, const double & trace_H_1_H_1, My_Vector<double> & TracePiPis, My_Vector<double> & WiTPi_1wi, My_Vector<double> & WiTPi_1Pi_1wi, My_Vector<double> & WiTPi_1Pi_1Pi_1wi){ //todo set WiTPi_1Pi_1wi and WiTPi_1wi double PP0 = trace_H_1_H_1; TracePiPis.get_array()[0] = PP0 + pow(WiTPi_1Pi_1wi.get_array()[0], 2)/pow(WiTPi_1wi.get_array()[0],2) -2.0*WiTPi_1Pi_1Pi_1wi.get_array()[0]/WiTPi_1wi.get_array()[0]; for( int i=1; i<q; ++i ){ TracePiPis.get_array()[i]=0; TracePiPis.get_array()[i] = TracePiPis.get_array()[i-1]+pow(WiTPi_1Pi_1wi.get_array()[i], 2)/pow(WiTPi_1wi.get_array()[i],2) -2.0*WiTPi_1Pi_1Pi_1wi.get_array()[i]/WiTPi_1wi.get_array()[i]; } } */ //double _get_trace_PxH_(const int & n, const int & c){ // return double(n-c-1); //} // //// todo is there any special way to to this???? //double get_trace_Pi( const My_matrix<double> & Pi, const int & n ){ // double result=0.0; // for( int i=0; i<n; ++i ){ // result += Pi.get_matrix()[i][i]; // } // return result; //} // //// todo is there any special way to to this???? //double get_trace_Pi_Pi( const My_matrix<double> & Pi, const int & n ){ // double result=0.0; // for( int i=0; i<n; ++i ){ // result += Pi.get_matrix()[i][i]*Pi.get_matrix()[i][i]; // } // return result; //} //// this function will generate the result of ytPx //double _get_ytPxy_( const My_Vector<double> & y, My_Vector<double> & ytPx, const My_matrix<double> & Pi, const int & n ){ // int i, j; // for( i=0; i<n; ++i ){ // ytPx.get_array()[i]=0; // for( j=0; j<n; ++j ) { // ytPx.get_array()[i] += y.get_array()[j] * Pi.get_matrix()[i][j]; // } // } // double result=0.0; // for( i=0; i<n; ++i ){ // result += ytPx.get_array()[i] * y.get_array()[i]; // } // return result; //} // //// this function rely on get_ytPxy, you should run get_ytPxy to get the value of ytPx //double get_ytPxPxy(const My_Vector<double> & y, const My_Vector<double> & ytPx, const My_matrix<double> & P, const int & n, My_Vector<double> & ytPxPx ){ // int i, j; // for( i=0; i<n; ++i ){ // ytPxPx.get_array()[i]=0; // for( j=0; j<n; ++j ) { // ytPxPx.get_array()[i] += ytPx.get_array()[j] * P.get_matrix()[i][j]; // } // } // // double result=0.0; // for( i=0; i<n; ++i ){ // result += ytPxPx.get_array()[i] * y.get_array()[i]; // } // return result; //} // //// this function rely on get_ytPxPxy, you shoudl run get_ytPxPxy to get the value of ytPxPx //double get_ytPxPxPxy(const My_Vector<double> & y, const My_matrix<double> & P, const int & n, const My_Vector<double> & ytPxPx ){ // My_Vector<double> ytPxPxPx(n); // int i, j; // for( i=0; i<n; ++i ){ // ytPxPxPx.get_array()[i]=0; // for( j=0; j<n; ++j ) { // ytPxPxPx.get_array()[i] += ytPxPx.get_array()[j] * P.get_matrix()[i][j]; // } // } // // double result=0.0; // for( i=0; i<n; ++i ){ // result += ytPxPxPx.get_array()[i] * y.get_array()[i]; // } // return result; //}
#include "Time.h" float Time::deltaTime; float Time::scaleTime = 1; float Time::time; bool Time::running = false; bool Time::paused = false; Timer Time::gameTimer; void Time::Start() { running = true; gameTimer.Start(); time = 0; } void Time::PreUpdate(float dt) { deltaTime = running ? dt : 0; if (running) time = gameTimer.ReadSec(); } void Time::Update() { } void Time::Play() { running = true; } void Time::Pause() { paused = true; gameTimer.Stop(); } void Time::Resume() { paused = false; gameTimer.Resume(); } void Time::Stop() { running = false; gameTimer.Stop(); }
//===--- SILGenBridging.cpp - SILGen for bridging to Clang ASTs -----------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "ArgumentScope.h" #include "Callee.h" #include "RValue.h" #include "ResultPlan.h" #include "SILGenFunction.h" #include "Scope.h" #include "swift/AST/DiagnosticsSIL.h" #include "swift/AST/ExistentialLayout.h" #include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/GenericEnvironment.h" #include "swift/AST/ParameterList.h" #include "swift/AST/ProtocolConformance.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILUndef.h" #include "swift/SIL/TypeLowering.h" using namespace swift; using namespace Lowering; /// Convert to the given formal type, assuming that the lowered type of /// the source type is the same as its formal type. This is a reasonable /// assumption for a wide variety of types. static ManagedValue emitUnabstractedCast(SILGenFunction &SGF, SILLocation loc, ManagedValue value, CanType sourceFormalType, CanType targetFormalType) { if (value.getType() == SGF.getLoweredType(targetFormalType)) return value; return SGF.emitTransformedValue(loc, value, AbstractionPattern(sourceFormalType), sourceFormalType, AbstractionPattern(targetFormalType), targetFormalType); } static bool shouldBridgeThroughError(SILGenModule &SGM, CanType type, CanType targetType) { // Never use this logic if the target type is AnyObject. if (targetType->isEqual(SGM.getASTContext().getAnyObjectType())) return false; auto errorProtocol = SGM.getASTContext().getErrorDecl(); if (!errorProtocol) return false; // Existential types are convertible to Error if they are, or imply, Error. if (type.isExistentialType()) { auto layout = type->getExistentialLayout(); for (auto proto : layout.getProtocols()) { if (proto->getDecl() == errorProtocol || proto->getDecl()->inheritsFrom(errorProtocol)) { return true; } } // They're also convertible to Error if they have a class bound that // conforms to Error. if (auto cls = layout.superclass) { type = cls->getCanonicalType(); // Otherwise, they are not convertible to Error. } else { return false; } } auto optConf = SGM.SwiftModule->lookupConformance(type, errorProtocol); return optConf.hasValue(); } /// Bridge the given Swift value to its corresponding Objective-C /// object, using the appropriate witness for the /// _ObjectiveCBridgeable._bridgeToObjectiveC requirement. static Optional<ManagedValue> emitBridgeNativeToObjectiveC(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftValue, CanType swiftValueType, CanType bridgedType, ProtocolConformance *conformance) { // Find the _bridgeToObjectiveC requirement. auto requirement = SGF.SGM.getBridgeToObjectiveCRequirement(loc); if (!requirement) return None; // Retrieve the _bridgeToObjectiveC witness. auto witness = conformance->getWitnessDecl(requirement, nullptr); assert(witness); // Determine the type we're bridging to. auto objcTypeReq = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); if (!objcTypeReq) return None; Type objcType = conformance->getTypeWitness(objcTypeReq, nullptr); assert(objcType); // Create a reference to the witness. SILDeclRef witnessConstant(witness); auto witnessRef = SGF.emitGlobalFunctionRef(loc, witnessConstant); // Determine the substitutions. auto witnessFnTy = witnessRef->getType(); // Compute the substitutions. // FIXME: Figure out the right SubstitutionMap stuff if the witness // has generic parameters of its own. assert(!cast<FuncDecl>(witness)->isGeneric() && "Generic witnesses not supported"); auto *dc = cast<FuncDecl>(witness)->getDeclContext(); auto *genericSig = dc->getGenericSignatureOfContext(); auto typeSubMap = swiftValueType->getContextSubstitutionMap( SGF.SGM.SwiftModule, dc); // Substitute into the witness function type. witnessFnTy = witnessFnTy.substGenericArgs(SGF.SGM.M, typeSubMap); // We might have to re-abstract the 'self' value if it is an // Optional. AbstractionPattern origSelfType(witness->getInterfaceType()); origSelfType = origSelfType.getFunctionInputType(); swiftValue = SGF.emitSubstToOrigValue(loc, swiftValue, origSelfType, swiftValueType, SGFContext()); // The witness may be more abstract than the concrete value we're bridging, // for instance, if the value is a concrete instantiation of a generic type. // // Note that we assume that we don't ever have to reabstract the parameter. // This is safe for now, since only nominal types currently can conform to // protocols. SILFunctionConventions witnessConv(witnessFnTy.castTo<SILFunctionType>(), SGF.SGM.M); if (witnessConv.isSILIndirect(witnessConv.getParameters()[0]) && !swiftValue.getType().isAddress()) { auto tmp = SGF.emitTemporaryAllocation(loc, swiftValue.getType()); SGF.B.createStoreBorrowOrTrivial(loc, swiftValue.borrow(SGF, loc), tmp); swiftValue = ManagedValue::forUnmanaged(tmp); } SmallVector<Substitution, 4> subs; if (genericSig) genericSig->getSubstitutions(typeSubMap, subs); // Call the witness. SILType resultTy = SGF.getLoweredType(objcType); SILValue bridgedValue = SGF.B.createApply(loc, witnessRef, witnessFnTy, resultTy, subs, swiftValue.borrow(SGF, loc).getValue()); auto bridgedMV = SGF.emitManagedRValueWithCleanup(bridgedValue); // The Objective-C value doesn't necessarily match the desired type. bridgedMV = emitUnabstractedCast(SGF, loc, bridgedMV, objcType->getCanonicalType(), bridgedType); return bridgedMV; } /// Bridge the given Objective-C object to its corresponding Swift /// value, using the appropriate witness for the /// _ObjectiveCBridgeable._unconditionallyBridgeFromObjectiveC requirement. static Optional<ManagedValue> emitBridgeObjectiveCToNative(SILGenFunction &SGF, SILLocation loc, ManagedValue objcValue, CanType bridgedType, ProtocolConformance *conformance) { // Find the _unconditionallyBridgeFromObjectiveC requirement. auto requirement = SGF.SGM.getUnconditionallyBridgeFromObjectiveCRequirement(loc); if (!requirement) return None; // Find the _ObjectiveCType requirement. auto objcTypeRequirement = SGF.SGM.getBridgedObjectiveCTypeRequirement(loc); if (!objcTypeRequirement) return None; // Retrieve the _unconditionallyBridgeFromObjectiveC witness. auto witness = conformance->getWitnessDeclRef(requirement, nullptr); assert(witness); // Retrieve the _ObjectiveCType witness. auto objcType = conformance->getTypeWitness(objcTypeRequirement, nullptr); assert(objcType); // Create a reference to the witness. SILDeclRef witnessConstant(witness.getDecl()); auto witnessRef = SGF.emitGlobalFunctionRef(loc, witnessConstant); // Determine the substitutions. auto witnessFnTy = witnessRef->getType().castTo<SILFunctionType>(); CanType swiftValueType = conformance->getType()->getCanonicalType(); auto genericSig = witnessFnTy->getGenericSignature(); SubstitutionMap typeSubMap; if (genericSig) typeSubMap = genericSig->getSubstitutionMap(witness.getSubstitutions()); // Substitute into the witness function type. witnessFnTy = witnessFnTy->substGenericArgs(SGF.SGM.M, typeSubMap); // The witness takes an _ObjectiveCType?, so convert to that type. CanType desiredValueType = OptionalType::get(objcType)->getCanonicalType(); objcValue = emitUnabstractedCast(SGF, loc, objcValue, bridgedType, desiredValueType); // Call the witness. auto metatypeParam = witnessFnTy->getParameters()[1]; assert(isa<MetatypeType>(metatypeParam.getType()) && cast<MetatypeType>(metatypeParam.getType()).getInstanceType() == swiftValueType); SILValue metatypeValue = SGF.B.createMetatype(loc, metatypeParam.getSILStorageType()); auto witnessCI = SGF.getConstantInfo(witnessConstant); CanType formalResultTy = witnessCI.LoweredType.getResult(); auto subs = witness.getSubstitutions(); // Set up the generic signature, since formalResultTy is an interface type. GenericContextScope genericContextScope(SGF.SGM.Types, genericSig); CalleeTypeInfo calleeTypeInfo( witnessFnTy, AbstractionPattern(genericSig, formalResultTy), swiftValueType); SGFContext context; ResultPlanPtr resultPlan = ResultPlanBuilder::computeResultPlan(SGF, calleeTypeInfo, loc, context); ArgumentScope argScope(SGF, loc); RValue result = SGF.emitApply(std::move(resultPlan), std::move(argScope), loc, ManagedValue::forUnmanaged(witnessRef), subs, {objcValue, ManagedValue::forUnmanaged(metatypeValue)}, calleeTypeInfo, ApplyOptions::None, context); return std::move(result).getAsSingleValue(SGF, loc); } static ManagedValue emitBridgeBoolToObjCBool(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftBool) { // func _convertBoolToObjCBool(Bool) -> ObjCBool SILValue boolToObjCBoolFn = SGF.emitGlobalFunctionRef(loc, SGF.SGM.getBoolToObjCBoolFn()); SILType resultTy =SGF.getLoweredLoadableType(SGF.SGM.Types.getObjCBoolType()); SILValue result = SGF.B.createApply(loc, boolToObjCBoolFn, boolToObjCBoolFn->getType(), resultTy, {}, swiftBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitBridgeBoolToDarwinBoolean(SILGenFunction &SGF, SILLocation loc, ManagedValue swiftBool) { // func _convertBoolToDarwinBoolean(Bool) -> DarwinBoolean SILValue boolToDarwinBooleanFn = SGF.emitGlobalFunctionRef(loc, SGF.SGM.getBoolToDarwinBooleanFn()); SILType resultTy = SGF.getLoweredLoadableType(SGF.SGM.Types.getDarwinBooleanType()); SILValue result = SGF.B.createApply(loc, boolToDarwinBooleanFn, boolToDarwinBooleanFn->getType(), resultTy, {}, swiftBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitBridgeForeignBoolToBool(SILGenFunction &SGF, SILLocation loc, ManagedValue foreignBool, SILDeclRef bridgingFnRef) { // func _convertObjCBoolToBool(ObjCBool) -> Bool SILValue bridgingFn = SGF.emitGlobalFunctionRef(loc, bridgingFnRef); SILType resultTy = SGF.getLoweredLoadableType(SGF.SGM.Types.getBoolType()); SILValue result = SGF.B.createApply(loc, bridgingFn, bridgingFn->getType(), resultTy, {}, foreignBool.forward(SGF)); return SGF.emitManagedRValueWithCleanup(result); } static ManagedValue emitManagedParameter(SILGenFunction &SGF, SILLocation loc, SILParameterInfo param, SILValue value) { const TypeLowering &valueTL = SGF.getTypeLowering(value->getType()); switch (param.getConvention()) { case ParameterConvention::Direct_Owned: // Consume owned parameters at +1. return SGF.emitManagedRValueWithCleanup(value, valueTL); case ParameterConvention::Direct_Guaranteed: // If we have a guaranteed parameter, the object should not need to be // retained or have a cleanup. return ManagedValue::forUnmanaged(value); case ParameterConvention::Direct_Unowned: // We need to independently retain the value. return SGF.emitManagedRetain(loc, value, valueTL); case ParameterConvention::Indirect_Inout: return ManagedValue::forLValue(value); case ParameterConvention::Indirect_In_Guaranteed: if (valueTL.isLoadable()) { return SGF.B.createLoadBorrow(loc, ManagedValue::forUnmanaged(value)); } else { return ManagedValue::forUnmanaged(value); } case ParameterConvention::Indirect_In: if (valueTL.isLoadable()) { return SGF.emitLoad(loc, value, valueTL, SGFContext(), IsTake); } else { return SGF.emitManagedRValueWithCleanup(value, valueTL); } case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_InoutAliasable: llvm_unreachable("unexpected convention"); } llvm_unreachable("bad convention"); } static void expandTupleTypes(CanType type, SmallVectorImpl<CanType> &results) { if (auto tuple = dyn_cast<TupleType>(type)) { for (auto eltType : tuple.getElementTypes()) expandTupleTypes(eltType, results); } else { results.push_back(type); } } /// Recursively expand all the tuples in the given parameter list. /// Callers assume that the resulting array will line up with the /// SILFunctionType's parameter list, which is true as along as there /// aren't any indirectly-passed tuples; we should be safe from that /// here in the bridging code. static SmallVector<CanType, 8> expandTupleTypes(AnyFunctionType::CanParamArrayRef params) { SmallVector<CanType, 8> results; for (auto param : params) expandTupleTypes(param.getType(), results); return results; } static CanAnyFunctionType getBridgedBlockType(SILGenModule &SGM, CanAnyFunctionType blockType) { return SGM.Types.getBridgedFunctionType(AbstractionPattern(blockType), blockType, blockType->getExtInfo()); } static void buildFuncToBlockInvokeBody(SILGenFunction &SGF, SILLocation loc, CanAnyFunctionType formalFuncType, CanAnyFunctionType formalBlockType, CanSILFunctionType funcTy, CanSILFunctionType blockTy, CanSILBlockStorageType blockStorageTy) { Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); SILBasicBlock *entry = &*SGF.F.begin(); SILFunctionConventions blockConv(blockTy, SGF.SGM.M); SILFunctionConventions funcConv(funcTy, SGF.SGM.M); // Make sure we lower the component types of the formal block type. formalBlockType = getBridgedBlockType(SGF.SGM, formalBlockType); // Set up the indirect result. SILType blockResultTy = blockTy->getAllResultsType(); SILValue indirectResult; if (blockTy->getNumResults() != 0) { auto result = blockTy->getSingleResult(); if (result.getConvention() == ResultConvention::Indirect) { indirectResult = entry->createFunctionArgument(blockResultTy); } } // Get the captured native function value out of the block. auto storageAddrTy = SILType::getPrimitiveAddressType(blockStorageTy); auto storage = entry->createFunctionArgument(storageAddrTy); auto capture = SGF.B.createProjectBlockStorage(loc, storage); auto &funcTL = SGF.getTypeLowering(funcTy); auto fn = SGF.emitLoad(loc, capture, funcTL, SGFContext(), IsNotTake); // Collect the block arguments, which may have nonstandard conventions. assert(blockTy->getParameters().size() == funcTy->getParameters().size() && "block and function types don't match"); auto nativeParamTypes = expandTupleTypes(formalFuncType.getParams()); auto bridgedParamTypes = expandTupleTypes(formalBlockType.getParams()); SmallVector<ManagedValue, 4> args; for (unsigned i : indices(funcTy->getParameters())) { auto &param = blockTy->getParameters()[i]; SILType paramTy = blockConv.getSILType(param); SILValue v = entry->createFunctionArgument(paramTy); ManagedValue mv; // If the parameter is a block, we need to copy it to ensure it lives on // the heap. The adapted closure value might outlive the block's original // scope. if (SGF.getSILType(param).isBlockPointerCompatible()) { // We still need to consume the original block if it was owned. switch (param.getConvention()) { case ParameterConvention::Direct_Owned: SGF.emitManagedRValueWithCleanup(v); break; case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: break; case ParameterConvention::Indirect_In: case ParameterConvention::Indirect_In_Constant: case ParameterConvention::Indirect_In_Guaranteed: case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: llvm_unreachable("indirect params to blocks not supported"); } SILValue blockCopy = SGF.B.createCopyBlock(loc, v); mv = SGF.emitManagedRValueWithCleanup(blockCopy); } else { mv = emitManagedParameter(SGF, loc, param, v); } CanType formalBridgedType = bridgedParamTypes[i]; CanType formalNativeType = nativeParamTypes[i]; SILType loweredNativeTy = funcTy->getParameters()[i].getSILStorageType(); args.push_back(SGF.emitBridgedToNativeValue(loc, mv, formalBridgedType, formalNativeType, loweredNativeTy)); } auto init = indirectResult ? SGF.useBufferAsTemporary(indirectResult, SGF.getTypeLowering(indirectResult->getType())) : nullptr; CanType formalNativeResultType = formalFuncType.getResult(); CanType formalBridgedResultType = formalBlockType.getResult(); bool canEmitIntoInit = (indirectResult && indirectResult->getType() == SGF.getLoweredType(formalNativeResultType).getAddressType()); // Call the native function. SGFContext C(canEmitIntoInit ? init.get() : nullptr); ManagedValue result = SGF.emitMonomorphicApply(loc, fn, args, formalNativeResultType, formalNativeResultType, ApplyOptions::None, None, None, C) .getAsSingleValue(SGF, loc); // Bridge the result back to ObjC. if (!canEmitIntoInit) { result = SGF.emitNativeToBridgedValue(loc, result, formalNativeResultType, formalBridgedResultType, blockResultTy, SGFContext(init.get())); } SILValue resultVal; // If we have an indirect result, make sure the result is there. if (indirectResult) { if (!result.isInContext()) { init->copyOrInitValueInto(SGF, loc, result, /*isInit*/ true); init->finishInitialization(SGF); } init->getManagedAddress().forward(SGF); resultVal = SGF.B.createTuple(loc, {}); } else { // Otherwise, return the result at +1. resultVal = result.forward(SGF); } scope.pop(); SGF.B.createReturn(loc, resultVal); } /// Bridge a native function to a block with a thunk. ManagedValue SILGenFunction::emitFuncToBlock(SILLocation loc, ManagedValue fn, CanAnyFunctionType funcType, CanAnyFunctionType blockType, CanSILFunctionType loweredBlockTy){ auto loweredFuncTy = fn.getType().castTo<SILFunctionType>(); // Build the invoke function signature. The block will capture the original // function value. auto fnInterfaceTy = cast<SILFunctionType>( loweredFuncTy->mapTypeOutOfContext()->getCanonicalType()); auto blockInterfaceTy = cast<SILFunctionType>( loweredBlockTy->mapTypeOutOfContext()->getCanonicalType()); assert(!blockInterfaceTy->isCoroutine()); auto storageTy = SILBlockStorageType::get(loweredFuncTy); auto storageInterfaceTy = SILBlockStorageType::get(fnInterfaceTy); // Build the invoke function type. SmallVector<SILParameterInfo, 4> params; params.push_back(SILParameterInfo(storageInterfaceTy, ParameterConvention::Indirect_InoutAliasable)); std::copy(blockInterfaceTy->getParameters().begin(), blockInterfaceTy->getParameters().end(), std::back_inserter(params)); auto extInfo = SILFunctionType::ExtInfo() .withRepresentation(SILFunctionType::Representation::CFunctionPointer); CanGenericSignature genericSig; GenericEnvironment *genericEnv = nullptr; SubstitutionList subs; if (funcType->hasArchetype() || blockType->hasArchetype()) { genericSig = F.getLoweredFunctionType()->getGenericSignature(); genericEnv = F.getGenericEnvironment(); subs = F.getForwardingSubstitutions(); // The block invoke function must be pseudogeneric. This should be OK for now // since a bridgeable function's parameters and returns should all be // trivially representable in ObjC so not need to exercise the type metadata. // // Ultimately we may need to capture generic parameters in block storage, but // that will require a redesign of the interface to support dependent-layout // context. Currently we don't capture anything directly into a block but a // Swift closure, but that's totally dumb. if (genericSig) extInfo = extInfo.withIsPseudogeneric(); } auto invokeTy = SILFunctionType::get( genericSig, extInfo, SILCoroutineKind::None, ParameterConvention::Direct_Unowned, params, /*yields*/ {}, blockInterfaceTy->getResults(), blockInterfaceTy->getOptionalErrorResult(), getASTContext()); // Create the invoke function. Borrow the mangling scheme from reabstraction // thunks, which is what we are in spirit. auto thunk = SGM.getOrCreateReabstractionThunk(invokeTy, loweredFuncTy, loweredBlockTy, F.isSerialized()); // Build it if necessary. if (thunk->empty()) { thunk->setGenericEnvironment(genericEnv); SILGenFunction thunkSGF(SGM, *thunk); auto loc = RegularLocation::getAutoGeneratedLocation(); buildFuncToBlockInvokeBody(thunkSGF, loc, funcType, blockType, loweredFuncTy, loweredBlockTy, storageTy); } // Form the block on the stack. auto storageAddrTy = SILType::getPrimitiveAddressType(storageTy); auto storage = emitTemporaryAllocation(loc, storageAddrTy); auto capture = B.createProjectBlockStorage(loc, storage); B.createStore(loc, fn, capture, StoreOwnershipQualifier::Init); auto invokeFn = B.createFunctionRef(loc, thunk); auto stackBlock = B.createInitBlockStorageHeader(loc, storage, invokeFn, SILType::getPrimitiveObjectType(loweredBlockTy), subs); // Copy the block so we have an independent heap object we can hand off. auto heapBlock = B.createCopyBlock(loc, stackBlock); return emitManagedRValueWithCleanup(heapBlock); } static ManagedValue emitNativeToCBridgedNonoptionalValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType nativeType, CanType bridgedType, SILType loweredBridgedTy, SGFContext C) { assert(loweredBridgedTy.isObject()); if (v.getType().getObjectType() == loweredBridgedTy) return v; // If the input is a native type with a bridged mapping, convert it. #define BRIDGE_TYPE(BridgedModule,BridgedType, NativeModule,NativeType,Opt) \ if (nativeType == SGF.SGM.Types.get##NativeType##Type() \ && bridgedType == SGF.SGM.Types.get##BridgedType##Type()) { \ return emitBridge##NativeType##To##BridgedType(SGF, loc, v); \ } #include "swift/SIL/BridgedTypes.def" // Bridge thick to Objective-C metatypes. if (auto bridgedMetaTy = dyn_cast<AnyMetatypeType>(bridgedType)) { if (bridgedMetaTy->hasRepresentation() && bridgedMetaTy->getRepresentation() == MetatypeRepresentation::ObjC) { SILValue native = SGF.B.emitThickToObjCMetatype(loc, v.getValue(), loweredBridgedTy); // *NOTE*: ObjCMetatypes are trivial types. They only gain ARC semantics // when they are converted to an object via objc_metatype_to_object. assert(!v.hasCleanup() && "Metatypes are trivial and thus should not have cleanups"); return ManagedValue::forUnmanaged(native); } } // Bridge native functions to blocks. auto bridgedFTy = dyn_cast<AnyFunctionType>(bridgedType); if (bridgedFTy && bridgedFTy->getRepresentation() == AnyFunctionType::Representation::Block) { auto nativeFTy = cast<AnyFunctionType>(nativeType); if (nativeFTy->getRepresentation() != AnyFunctionType::Representation::Block) return SGF.emitFuncToBlock(loc, v, nativeFTy, bridgedFTy, loweredBridgedTy.castTo<SILFunctionType>()); } // If the native type conforms to _ObjectiveCBridgeable, use its // _bridgeToObjectiveC witness. if (auto conformance = SGF.SGM.getConformanceToObjectiveCBridgeable(loc, nativeType)) { if (auto result = emitBridgeNativeToObjectiveC(SGF, loc, v, nativeType, bridgedType, conformance)) return *result; assert(SGF.SGM.getASTContext().Diags.hadAnyError() && "Bridging code should have complained"); return SGF.emitUndef(loc, bridgedType); } // Bridge Error, or types that conform to it, to NSError. if (shouldBridgeThroughError(SGF.SGM, nativeType, bridgedType)) { auto errorTy = SGF.SGM.Types.getNSErrorType(); auto error = SGF.emitNativeToBridgedError(loc, v, nativeType, errorTy); if (errorTy != bridgedType) { error = emitUnabstractedCast(SGF, loc, error, errorTy, bridgedType); } return error; } // Fall back to dynamic Any-to-id bridging. // The destination type should be AnyObject in this case. assert(bridgedType->isEqual(SGF.getASTContext().getAnyObjectType())); // Blocks bridge to id with a cast under ObjCInterop. if (auto nativeFnType = dyn_cast<AnyFunctionType>(nativeType)) { if (nativeFnType->getRepresentation() == FunctionTypeRepresentation::Block && SGF.getASTContext().LangOpts.EnableObjCInterop) { return SGF.B.createBlockToAnyObject(loc, v, loweredBridgedTy); } } // If the input argument is known to be an existential, save the runtime // some work by opening it. if (nativeType->isExistentialType()) { auto openedType = ArchetypeType::getOpened(nativeType); auto openedExistential = SGF.emitOpenExistential( loc, v, openedType, SGF.getLoweredType(openedType), AccessKind::Read); v = SGF.manageOpaqueValue(openedExistential, loc, SGFContext()); nativeType = openedType; } // Call into the stdlib intrinsic. if (auto bridgeAnything = SGF.getASTContext().getBridgeAnythingToObjectiveC(nullptr)) { auto *genericSig = bridgeAnything->getGenericSignature(); auto subMap = genericSig->getSubstitutionMap( [&](SubstitutableType *t) -> Type { return nativeType; }, MakeAbstractConformanceForGenericType()); // The intrinsic takes a T; reabstract to the generic abstraction // pattern. v = SGF.emitSubstToOrigValue(loc, v, AbstractionPattern::getOpaque(), nativeType); // Put the value into memory if necessary. assert(v.getType().isTrivial(SGF.SGM.M) || v.hasCleanup()); SILModuleConventions silConv(SGF.SGM.M); // bridgeAnything always takes an indirect argument as @in. // Since we don't have the SIL type here, check the current SIL stage/mode // to determine the convention. if (v.getType().isObject() && silConv.useLoweredAddresses()) { auto tmp = SGF.emitTemporaryAllocation(loc, v.getType()); v.forwardInto(SGF, loc, tmp); v = SGF.emitManagedBufferWithCleanup(tmp); } return SGF.emitApplyOfLibraryIntrinsic(loc, bridgeAnything, subMap, v, C) .getAsSingleValue(SGF, loc); } // Shouldn't get here unless the standard library is busted. return SGF.emitUndef(loc, loweredBridgedTy); } static ManagedValue emitNativeToCBridgedValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType nativeType, CanType bridgedType, SILType loweredBridgedTy, SGFContext C = SGFContext()) { SILType loweredNativeTy = v.getType(); if (loweredNativeTy.getObjectType() == loweredBridgedTy.getObjectType()) return v; CanType bridgedObjectType = bridgedType.getOptionalObjectType(); CanType nativeObjectType = nativeType.getOptionalObjectType(); // Check for optional-to-optional conversions. if (bridgedObjectType && nativeObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, ManagedValue v, SILType loweredBridgedObjectTy, SGFContext C) { return emitNativeToCBridgedValue(SGF, loc, v, nativeObjectType, bridgedObjectType, loweredBridgedObjectTy, C); }; return SGF.emitOptionalToOptional(loc, v, loweredBridgedTy, helper, C); } // Check if we need to wrap the bridged result in an optional. if (bridgedObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { auto loweredBridgedObjectTy = loweredBridgedTy.getOptionalObjectType(); return emitNativeToCBridgedValue(SGF, loc, v, nativeType, bridgedObjectType, loweredBridgedObjectTy, C); }; return SGF.emitOptionalSome(loc, loweredBridgedTy, helper, C); } return emitNativeToCBridgedNonoptionalValue(SGF, loc, v, nativeType, bridgedType, loweredBridgedTy, C); } ManagedValue SILGenFunction::emitNativeToBridgedValue(SILLocation loc, ManagedValue v, CanType nativeTy, CanType bridgedTy, SILType loweredBridgedTy, SGFContext C) { loweredBridgedTy = loweredBridgedTy.getObjectType(); return emitNativeToCBridgedValue(*this, loc, v, nativeTy, bridgedTy, loweredBridgedTy, C); } static void buildBlockToFuncThunkBody(SILGenFunction &SGF, SILLocation loc, CanAnyFunctionType formalBlockTy, CanAnyFunctionType formalFuncTy, CanSILFunctionType blockTy, CanSILFunctionType funcTy) { // Collect the native arguments, which should all be +1. Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); // Make sure we lower the component types of the formal block type. formalBlockTy = getBridgedBlockType(SGF.SGM, formalBlockTy); assert(blockTy->getNumParameters() == funcTy->getNumParameters() && "block and function types don't match"); SmallVector<ManagedValue, 4> args; SILBasicBlock *entry = &*SGF.F.begin(); SILFunctionConventions fnConv(funcTy, SGF.SGM.M); // Set up the indirect result slot. SILValue indirectResult; if (funcTy->getNumResults() != 0) { auto result = funcTy->getSingleResult(); if (result.getConvention() == ResultConvention::Indirect) { SILType resultTy = fnConv.getSILType(result); indirectResult = entry->createFunctionArgument(resultTy); } } auto formalBlockParams = expandTupleTypes(formalBlockTy.getParams()); auto formalFuncParams = expandTupleTypes(formalFuncTy.getParams()); assert(formalBlockParams.size() == blockTy->getNumParameters()); assert(formalFuncParams.size() == funcTy->getNumParameters()); // Create the arguments for the call. for (unsigned i : indices(funcTy->getParameters())) { auto &param = funcTy->getParameters()[i]; CanType formalBlockParamTy = formalBlockParams[i]; CanType formalFuncParamTy = formalFuncParams[i]; auto paramTy = fnConv.getSILType(param); SILValue v = entry->createFunctionArgument(paramTy); // First get the managed parameter for this function. auto mv = emitManagedParameter(SGF, loc, param, v); SILType loweredBlockArgTy = blockTy->getParameters()[i].getSILStorageType(); // Then bridge the native value to its bridged variant. mv = SGF.emitNativeToBridgedValue(loc, mv, formalFuncParamTy, formalBlockParamTy, loweredBlockArgTy); // Finally change ownership if we need to. We do not need to care about the // case of a +1 parameter being passed to a +0 function since +1 parameters // can be "instantaneously" borrowed at the call site. if (blockTy->getParameters()[i].isConsumed()) { mv = mv.ensurePlusOne(SGF, loc); } args.push_back(mv); } // Add the block argument. SILValue blockV = entry->createFunctionArgument(SILType::getPrimitiveObjectType(blockTy)); ManagedValue block = ManagedValue::forUnmanaged(blockV); CanType formalResultType = formalFuncTy.getResult(); auto init = indirectResult ? SGF.useBufferAsTemporary(indirectResult, SGF.getTypeLowering(indirectResult->getType())) : nullptr; // Call the block. ManagedValue result = SGF.emitMonomorphicApply(loc, block, args, formalBlockTy.getResult(), formalResultType, ApplyOptions::None, /*override CC*/ SILFunctionTypeRepresentation::Block, /*foreign error*/ None, SGFContext(init.get())) .getAsSingleValue(SGF, loc); SILValue r; // If we have an indirect result, make sure the result is there. if (indirectResult) { if (!result.isInContext()) { init->copyOrInitValueInto(SGF, loc, result, /*isInit*/ true); init->finishInitialization(SGF); } init->getManagedAddress().forward(SGF); r = SGF.B.createTuple(loc, fnConv.getSILResultType(), ArrayRef<SILValue>()); // Otherwise, return the result at +1. } else { r = result.forward(SGF); } scope.pop(); SGF.B.createReturn(loc, r); // Finally, verify the thunk for SIL invariants. SGF.F.verify(); } /// Bridge a native function to a block with a thunk. ManagedValue SILGenFunction::emitBlockToFunc(SILLocation loc, ManagedValue block, CanAnyFunctionType blockType, CanAnyFunctionType funcType, CanSILFunctionType loweredFuncTy) { // Declare the thunk. auto loweredBlockTy = block.getType().castTo<SILFunctionType>(); SubstitutionMap contextSubs, interfaceSubs; GenericEnvironment *genericEnv = nullptr; // These two are not used here -- but really, bridging thunks // should be emitted using the formal AST type, not the lowered // type CanType inputSubstType, outputSubstType; auto loweredFuncTyWithoutNoEscape = adjustFunctionType( loweredFuncTy, loweredFuncTy->getExtInfo().withNoEscape(false), loweredFuncTy->getWitnessMethodConformanceOrNone()); auto thunkTy = buildThunkType(loweredBlockTy, loweredFuncTyWithoutNoEscape, inputSubstType, outputSubstType, genericEnv, interfaceSubs); auto thunk = SGM.getOrCreateReabstractionThunk(thunkTy, loweredBlockTy, loweredFuncTyWithoutNoEscape, F.isSerialized()); // Build it if necessary. if (thunk->empty()) { SILGenFunction thunkSGF(SGM, *thunk); thunk->setGenericEnvironment(genericEnv); auto loc = RegularLocation::getAutoGeneratedLocation(); buildBlockToFuncThunkBody(thunkSGF, loc, blockType, funcType, loweredBlockTy, loweredFuncTyWithoutNoEscape); } CanSILFunctionType substFnTy = thunkTy; SmallVector<Substitution, 4> subs; if (auto genericSig = thunkTy->getGenericSignature()) { genericSig->getSubstitutions(interfaceSubs, subs); substFnTy = thunkTy->substGenericArgs(F.getModule(), interfaceSubs); } // Create it in the current function. auto thunkValue = B.createFunctionRef(loc, thunk); ManagedValue thunkedFn = B.createPartialApply( loc, thunkValue, SILType::getPrimitiveObjectType(substFnTy), subs, block, SILType::getPrimitiveObjectType(loweredFuncTyWithoutNoEscape)); if (!loweredFuncTy->isNoEscape()) { return thunkedFn; } // Handle the escaping to noescape conversion. assert(loweredFuncTy->isNoEscape()); return B.createConvertEscapeToNoEscape( loc, thunkedFn, SILType::getPrimitiveObjectType(loweredFuncTy), false); } static ManagedValue emitCBridgedToNativeValue(SILGenFunction &SGF, SILLocation loc, ManagedValue v, CanType bridgedType, CanType nativeType, SILType loweredNativeTy, bool isCallResult, SGFContext C) { assert(loweredNativeTy.isObject()); SILType loweredBridgedTy = v.getType(); if (loweredNativeTy == loweredBridgedTy.getObjectType()) return v; if (auto nativeObjectType = nativeType.getOptionalObjectType()) { auto bridgedObjectType = bridgedType.getOptionalObjectType(); // Optional injection. if (!bridgedObjectType) { auto helper = [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { auto loweredNativeObjectTy = loweredNativeTy.getOptionalObjectType(); return emitCBridgedToNativeValue(SGF, loc, v, bridgedType, nativeObjectType, loweredNativeObjectTy, isCallResult, C); }; return SGF.emitOptionalSome(loc, loweredNativeTy, helper, C); } // Optional-to-optional. auto helper = [=](SILGenFunction &SGF, SILLocation loc, ManagedValue v, SILType loweredNativeObjectTy, SGFContext C) { return emitCBridgedToNativeValue(SGF, loc, v, bridgedObjectType, nativeObjectType, loweredNativeObjectTy, isCallResult, C); }; return SGF.emitOptionalToOptional(loc, v, loweredNativeTy, helper, C); } // Bridge Bool to ObjCBool or DarwinBoolean when requested. if (nativeType == SGF.SGM.Types.getBoolType()) { if (bridgedType == SGF.SGM.Types.getObjCBoolType()) { return emitBridgeForeignBoolToBool(SGF, loc, v, SGF.SGM.getObjCBoolToBoolFn()); } if (bridgedType == SGF.SGM.Types.getDarwinBooleanType()) { return emitBridgeForeignBoolToBool(SGF, loc, v, SGF.SGM.getDarwinBooleanToBoolFn()); } } // Bridge Objective-C to thick metatypes. if (isa<AnyMetatypeType>(nativeType)) { auto bridgedMetaTy = cast<AnyMetatypeType>(bridgedType); if (bridgedMetaTy->hasRepresentation() && bridgedMetaTy->getRepresentation() == MetatypeRepresentation::ObjC) { SILValue native = SGF.B.emitObjCToThickMetatype(loc, v.getValue(), loweredNativeTy); // *NOTE*: ObjCMetatypes are trivial types. They only gain ARC semantics // when they are converted to an object via objc_metatype_to_object. assert(!v.hasCleanup() && "Metatypes are trivial and should not have " "cleanups"); return ManagedValue::forUnmanaged(native); } } // Bridge blocks back into native function types. if (auto nativeFTy = dyn_cast<AnyFunctionType>(nativeType)) { auto bridgedFTy = cast<AnyFunctionType>(bridgedType); if (bridgedFTy->getRepresentation() == AnyFunctionType::Representation::Block && nativeFTy->getRepresentation() != AnyFunctionType::Representation::Block) { return SGF.emitBlockToFunc(loc, v, bridgedFTy, nativeFTy, loweredNativeTy.castTo<SILFunctionType>()); } } // Bridge via _ObjectiveCBridgeable. if (auto conformance = SGF.SGM.getConformanceToObjectiveCBridgeable(loc, nativeType)) { if (auto result = emitBridgeObjectiveCToNative(SGF, loc, v, bridgedType, conformance)) return *result; assert(SGF.SGM.getASTContext().Diags.hadAnyError() && "Bridging code should have complained"); return SGF.emitUndef(loc, nativeType); } // id-to-Any bridging. if (nativeType->isAny()) { // If this is not a call result, use the normal erasure logic. if (!isCallResult) { return SGF.emitTransformedValue(loc, v, bridgedType, nativeType, C); } // Otherwise, we use more complicated logic that handles results that // were unexpetedly null. assert(bridgedType.isAnyClassReferenceType()); // Convert to AnyObject if necessary. CanType anyObjectTy = SGF.getASTContext().getAnyObjectType()->getCanonicalType(); if (bridgedType != anyObjectTy) { v = SGF.emitTransformedValue(loc, v, bridgedType, anyObjectTy); } // TODO: Ever need to handle +0 values here? assert(v.hasCleanup()); // Use a runtime call to bridge the AnyObject to Any. We do this instead of // a simple AnyObject-to-Any upcast because the ObjC API may have returned // a null object in spite of its annotation. // Bitcast to Optional. This provides a barrier to the optimizer to prevent // it from attempting to eliminate null checks. auto optionalBridgedTy = SILType::getOptionalType(loweredBridgedTy); auto optionalMV = SGF.B.createUncheckedBitCast(loc, v, optionalBridgedTy); return SGF.emitApplyOfLibraryIntrinsic(loc, SGF.getASTContext().getBridgeAnyObjectToAny(nullptr), SubstitutionMap(), optionalMV, C) .getAsSingleValue(SGF, loc); } // Bridge NSError to Error. if (bridgedType == SGF.SGM.Types.getNSErrorType()) return SGF.emitBridgedToNativeError(loc, v); return v; } ManagedValue SILGenFunction::emitBridgedToNativeValue(SILLocation loc, ManagedValue v, CanType bridgedType, CanType nativeType, SILType loweredNativeTy, SGFContext C, bool isCallResult) { loweredNativeTy = loweredNativeTy.getObjectType(); return emitCBridgedToNativeValue(*this, loc, v, bridgedType, nativeType, loweredNativeTy, isCallResult, C); } /// Bridge a possibly-optional foreign error type to Error. ManagedValue SILGenFunction::emitBridgedToNativeError(SILLocation loc, ManagedValue bridgedError) { // If the incoming error is non-optional, just do an existential erasure. CanType bridgedErrorTy = bridgedError.getType().getSwiftRValueType(); if (!bridgedErrorTy.getOptionalObjectType()) { auto nativeErrorTy = SILType::getExceptionType(getASTContext()); auto conformance = SGM.getNSErrorConformanceToError(); if (!conformance) return emitUndef(loc, nativeErrorTy); ProtocolConformanceRef conformanceArray[] = { ProtocolConformanceRef(conformance) }; auto conformances = getASTContext().AllocateCopy(conformanceArray); return B.createInitExistentialRef(loc, nativeErrorTy, bridgedErrorTy, bridgedError, conformances); } // Otherwise, we need to call a runtime function to potential substitute // a standard error for a nil NSError. auto bridgeFn = emitGlobalFunctionRef(loc, SGM.getNSErrorToErrorFn()); auto bridgeFnType = bridgeFn->getType().castTo<SILFunctionType>(); SILFunctionConventions bridgeFnConv(bridgeFnType, SGM.M); assert(bridgeFnType->getNumResults() == 1); assert(bridgeFnType->getResults()[0].getConvention() == ResultConvention::Owned); auto nativeErrorType = bridgeFnConv.getSILType(bridgeFnType->getResults()[0]); SILValue arg; if (SGM.M.getOptions().EnableGuaranteedNormalArguments) { assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Guaranteed); arg = bridgedError.getValue(); } else { assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Owned); arg = bridgedError.forward(*this); } SILValue nativeError = B.createApply(loc, bridgeFn, bridgeFn->getType(), nativeErrorType, {}, arg); return emitManagedRValueWithCleanup(nativeError); } /// Bridge Error to a foreign error type. ManagedValue SILGenFunction::emitNativeToBridgedError(SILLocation loc, ManagedValue nativeError, CanType nativeType, CanType bridgedErrorType){ // Handle injections into optional. if (auto bridgedObjectType = bridgedErrorType.getOptionalObjectType()) { auto loweredBridgedOptionalTy = SILType::getPrimitiveObjectType(bridgedErrorType); return emitOptionalSome( loc, loweredBridgedOptionalTy, [&](SILGenFunction &SGF, SILLocation loc, SGFContext C) { SILType loweredBridgedObjectTy = loweredBridgedOptionalTy.getOptionalObjectType(); return emitNativeToBridgedValue(loc, nativeError, nativeType, bridgedObjectType, loweredBridgedObjectTy); }); } assert(bridgedErrorType == SGM.Types.getNSErrorType() && "only handling NSError for now"); // The native error might just be a value of a type that conforms to // Error. This should be a subtyping or erasure conversion of the sort // that we can do automatically. // FIXME: maybe we should use a different entrypoint for this case, to // avoid the code size and performance overhead of forming the box? nativeError = emitUnabstractedCast(*this, loc, nativeError, nativeType, getASTContext().getExceptionType()); auto bridgeFn = emitGlobalFunctionRef(loc, SGM.getErrorToNSErrorFn()); auto bridgeFnType = bridgeFn->getType().castTo<SILFunctionType>(); SILFunctionConventions bridgeFnConv(bridgeFnType, SGM.M); assert(bridgeFnType->getNumResults() == 1); assert(bridgeFnType->getResults()[0].getConvention() == ResultConvention::Owned); auto loweredBridgedErrorType = bridgeFnConv.getSILType(bridgeFnType->getResults()[0]); SILValue arg; if (SGM.M.getOptions().EnableGuaranteedNormalArguments) { assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Guaranteed); arg = nativeError.getValue(); } else { assert(bridgeFnType->getParameters()[0].getConvention() == ParameterConvention::Direct_Owned); arg = nativeError.forward(*this); } SILValue bridgedError = B.createApply(loc, bridgeFn, bridgeFn->getType(), loweredBridgedErrorType, {}, arg); return emitManagedRValueWithCleanup(bridgedError); } //===----------------------------------------------------------------------===// // ObjC method thunks //===----------------------------------------------------------------------===// static SILValue emitBridgeReturnValue(SILGenFunction &SGF, SILLocation loc, SILValue result, CanType formalNativeTy, CanType formalBridgedTy, SILType loweredBridgedTy) { Scope scope(SGF.Cleanups, CleanupLocation::get(loc)); ManagedValue native = SGF.emitManagedRValueWithCleanup(result); ManagedValue bridged = SGF.emitNativeToBridgedValue(loc, native, formalNativeTy, formalBridgedTy, loweredBridgedTy); return bridged.forward(SGF); } /// Take an argument at +0 and bring it to +1. static SILValue emitObjCUnconsumedArgument(SILGenFunction &SGF, SILLocation loc, SILValue arg) { auto &lowering = SGF.getTypeLowering(arg->getType()); // If address-only, make a +1 copy and operate on that. if (lowering.isAddressOnly()) { auto tmp = SGF.emitTemporaryAllocation(loc, arg->getType().getObjectType()); SGF.B.createCopyAddr(loc, arg, tmp, IsNotTake, IsInitialization); return tmp; } return lowering.emitCopyValue(SGF.B, loc, arg); } static CanAnyFunctionType substGenericArgs(CanAnyFunctionType fnType, const SubstitutionList &subs) { if (auto genericFnType = dyn_cast<GenericFunctionType>(fnType)) { return cast<FunctionType>(genericFnType->substGenericArgs(subs) ->getCanonicalType()); } return fnType; } /// Bridge argument types and adjust retain count conventions for an ObjC thunk. static SILFunctionType *emitObjCThunkArguments(SILGenFunction &SGF, SILLocation loc, SILDeclRef thunk, SmallVectorImpl<SILValue> &args, SILValue &foreignErrorSlot, Optional<ForeignErrorConvention> &foreignError, CanType &nativeFormalResultTy, CanType &bridgedFormalResultTy) { SILDeclRef native = thunk.asForeign(false); auto subs = SGF.F.getForwardingSubstitutions(); auto objcInfo = SGF.SGM.Types.getConstantInfo(thunk); auto objcFnTy = objcInfo.SILFnType->substGenericArgs(SGF.SGM.M, subs); auto objcFormalFnTy = substGenericArgs(objcInfo.LoweredType, subs); auto swiftInfo = SGF.SGM.Types.getConstantInfo(native); auto swiftFnTy = swiftInfo.SILFnType->substGenericArgs(SGF.SGM.M, subs); auto swiftFormalFnTy = substGenericArgs(swiftInfo.LoweredType, subs); SILFunctionConventions swiftConv(swiftFnTy, SGF.SGM.M); // We must have the same context archetypes as the unthunked function. assert(objcInfo.GenericEnv == swiftInfo.GenericEnv); SmallVector<ManagedValue, 8> bridgedArgs; bridgedArgs.reserve(objcFnTy->getParameters().size()); SILFunction *orig = SGF.SGM.getFunction(native, NotForDefinition); // Find the foreign error convention if we have one. if (orig->getLoweredFunctionType()->hasErrorResult()) { auto func = cast<AbstractFunctionDecl>(thunk.getDecl()); foreignError = func->getForeignErrorConvention(); assert(foreignError && "couldn't find foreign error convention!"); } // We don't know what to do with indirect results from the Objective-C side. assert(objcFnTy->getNumIndirectFormalResults() == 0 && "Objective-C methods cannot have indirect results"); auto bridgedFormalTypes = expandTupleTypes(objcFormalFnTy.getParams()); bridgedFormalResultTy = objcFormalFnTy.getResult(); auto nativeFormalTypes = expandTupleTypes(swiftFormalFnTy.getParams()); nativeFormalResultTy = swiftFormalFnTy.getResult(); // Emit the other arguments, taking ownership of arguments if necessary. auto inputs = objcFnTy->getParameters(); auto nativeInputs = swiftFnTy->getParameters(); assert(nativeInputs.size() == bridgedFormalTypes.size()); assert(nativeInputs.size() == nativeFormalTypes.size()); assert(inputs.size() == nativeInputs.size() + unsigned(foreignError.hasValue())); for (unsigned i = 0, e = inputs.size(); i < e; ++i) { SILType argTy = SGF.getSILType(inputs[i]); SILValue arg = SGF.F.begin()->createFunctionArgument(argTy); // If this parameter is the foreign error slot, pull it out. // It does not correspond to a native argument. if (foreignError && i == foreignError->getErrorParameterIndex()) { foreignErrorSlot = arg; continue; } // If the argument is a block, copy it. if (argTy.isBlockPointerCompatible()) { auto copy = SGF.B.createCopyBlock(loc, arg); // If the argument is consumed, we're still responsible for releasing the // original. if (inputs[i].isConsumed()) SGF.emitManagedRValueWithCleanup(arg); arg = copy; } // Convert the argument to +1 if necessary. else if (!inputs[i].isConsumed()) { arg = emitObjCUnconsumedArgument(SGF, loc, arg); } auto managedArg = SGF.emitManagedRValueWithCleanup(arg); bridgedArgs.push_back(managedArg); } assert(bridgedArgs.size() + unsigned(foreignError.hasValue()) == objcFnTy->getParameters().size() && "objc inputs don't match number of arguments?!"); assert(bridgedArgs.size() == swiftFnTy->getParameters().size() && "swift inputs don't match number of arguments?!"); assert((foreignErrorSlot || !foreignError) && "didn't find foreign error slot"); // Bridge the input types. // FIXME: We really want alloc_stacks to outlive this scope, because // bridging id-to-Any requires allocating an Any which gets passed to // the native entry point. // Scope scope(gen.Cleanups, CleanupLocation::get(loc)); assert(bridgedArgs.size() == nativeInputs.size()); for (unsigned i = 0, size = bridgedArgs.size(); i < size; ++i) { // Consider the bridged values to be "call results" since they're coming // from potentially nil-unsound ObjC callers. ManagedValue native = SGF.emitBridgedToNativeValue(loc, bridgedArgs[i], bridgedFormalTypes[i], nativeFormalTypes[i], swiftFnTy->getParameters()[i].getSILStorageType(), SGFContext(), /*isCallResult*/ true); SILValue argValue; if (nativeInputs[i].isConsumed()) { argValue = native.forward(SGF); } else if (nativeInputs[i].isGuaranteed()) { argValue = native.borrow(SGF, loc).getUnmanagedValue(); } else { argValue = native.getValue(); } args.push_back(argValue); } return objcFnTy; } void SILGenFunction::emitNativeToForeignThunk(SILDeclRef thunk) { assert(thunk.isForeign); SILDeclRef native = thunk.asForeign(false); auto nativeInfo = getConstantInfo(native); auto subs = F.getForwardingSubstitutions(); auto substTy = nativeInfo.SILFnType->substGenericArgs(SGM.M, subs); SILType substSILTy = SILType::getPrimitiveObjectType(substTy); SILFunctionConventions substConv(substTy, SGM.M); // Use the same generic environment as the native entry point. F.setGenericEnvironment(nativeInfo.GenericEnv); auto loc = thunk.getAsRegularLocation(); loc.markAutoGenerated(); Scope scope(Cleanups, CleanupLocation::get(loc)); // If we are bridging a Swift method with an Any return value, create a // stack allocation to hold the result, since Any is address-only. SmallVector<SILValue, 4> args; if (substConv.hasIndirectSILResults()) { args.push_back( emitTemporaryAllocation(loc, substConv.getSingleSILResultType())); } // If the '@objc' was inferred due to deprecated rules, // emit a Builtin.swift3ImplicitObjCEntrypoint(). // // However, don't do so for 'dynamic' members, which must use Objective-C // dispatch and therefore create many false positives. if (thunk.hasDecl()) { auto decl = thunk.getDecl(); // For an accessor, look at the storage declaration's attributes. if (auto accessor = dyn_cast<AccessorDecl>(decl)) { decl = accessor->getStorage(); } if (auto attr = decl->getAttrs().getAttribute<ObjCAttr>()) { // If @objc was inferred based on the Swift 3 @objc inference rules, but // we aren't compiling in Swift 3 compatibility mode, emit a call to // Builtin.swift3ImplicitObjCEntrypoint() to enable runtime logging of // the uses of such entrypoints. if (attr->isSwift3Inferred() && !decl->getAttrs().hasAttribute<DynamicAttr>() && !getASTContext().LangOpts.isSwiftVersion3()) { // Get the starting source location of the declaration so we can say // exactly where to stick '@objc'. SourceLoc objcInsertionLoc = decl->getAttributeInsertionLoc(/*modifier*/ false); auto objcInsertionLocArgs = emitSourceLocationArgs(objcInsertionLoc, loc); B.createBuiltin(loc, getASTContext().getIdentifier("swift3ImplicitObjCEntrypoint"), getModule().Types.getEmptyTupleType(), { }, { objcInsertionLocArgs.filenameStartPointer.forward(*this), objcInsertionLocArgs.filenameLength.forward(*this), objcInsertionLocArgs.line.forward(*this), objcInsertionLocArgs.column.forward(*this) }); } } } // Now, enter a cleanup used for bridging the arguments. Note that if we // have an indirect result, it must be outside of this scope, otherwise // we will deallocate it too early. Scope argScope(Cleanups, CleanupLocation::get(loc)); // Bridge the arguments. Optional<ForeignErrorConvention> foreignError; SILValue foreignErrorSlot; CanType nativeFormalResultType, bridgedFormalResultType; auto objcFnTy = emitObjCThunkArguments(*this, loc, thunk, args, foreignErrorSlot, foreignError, nativeFormalResultType, bridgedFormalResultType); SILFunctionConventions objcConv(CanSILFunctionType(objcFnTy), SGM.M); SILFunctionConventions nativeConv(CanSILFunctionType(nativeInfo.SILFnType), SGM.M); auto swiftResultTy = F.mapTypeIntoContext(nativeConv.getSILResultType()); auto objcResultTy = objcConv.getSILResultType(); // Call the native entry point. SILValue nativeFn = emitGlobalFunctionRef(loc, native, nativeInfo); SILValue result; assert(foreignError.hasValue() == substTy->hasErrorResult()); if (!substTy->hasErrorResult()) { // Create the apply. result = B.createApply(loc, nativeFn, substSILTy, swiftResultTy, subs, args); if (substConv.hasIndirectSILResults()) { assert(substTy->getNumResults() == 1); result = args[0]; } // Leave the argument cleanup scope immediately. This isn't really // necessary; it just limits lifetimes a little bit more. argScope.pop(); // Now bridge the return value. result = emitBridgeReturnValue(*this, loc, result, nativeFormalResultType, bridgedFormalResultType, objcResultTy); } else { SILBasicBlock *contBB = createBasicBlock(); SILBasicBlock *errorBB = createBasicBlock(); SILBasicBlock *normalBB = createBasicBlock(); B.createTryApply(loc, nativeFn, substSILTy, subs, args, normalBB, errorBB); // Emit the non-error destination. { B.emitBlock(normalBB); SILValue nativeResult = normalBB->createPHIArgument(swiftResultTy, ValueOwnershipKind::Owned); if (substConv.hasIndirectSILResults()) { assert(substTy->getNumResults() == 1); nativeResult = args[0]; } // In this branch, the eventual return value is mostly created // by bridging the native return value, but we may need to // adjust it slightly. SILValue bridgedResult = emitBridgeReturnValueForForeignError(loc, nativeResult, nativeFormalResultType, bridgedFormalResultType, objcResultTy, foreignErrorSlot, *foreignError); B.createBranch(loc, contBB, bridgedResult); } // Emit the error destination. { B.emitBlock(errorBB); SILValue nativeError = errorBB->createPHIArgument( substConv.getSILErrorType(), ValueOwnershipKind::Owned); // In this branch, the eventual return value is mostly invented. // Store the native error in the appropriate location and return. SILValue bridgedResult = emitBridgeErrorForForeignError(loc, nativeError, objcResultTy, foreignErrorSlot, *foreignError); B.createBranch(loc, contBB, bridgedResult); } // Emit the join block. B.emitBlock(contBB); result = contBB->createPHIArgument(objcResultTy, ValueOwnershipKind::Owned); // Leave the scope now. argScope.pop(); } scope.pop(); B.createReturn(loc, result); } static SILValue getThunkedForeignFunctionRef(SILGenFunction &SGF, SILLocation loc, SILDeclRef foreign, ArrayRef<ManagedValue> args, SubstitutionList subs, const SILConstantInfo &foreignCI) { assert(!foreign.isCurried && "should not thunk calling convention when curried"); assert(foreign.isForeign); // Produce an objc_method when thunking ObjC methods. if (foreignCI.SILFnType->getRepresentation() == SILFunctionTypeRepresentation::ObjCMethod) { SILValue thisArg = args.back().getValue(); return SGF.B.createObjCMethod(loc, thisArg, foreign, foreignCI.getSILType()); } // Otherwise, emit a function_ref. return SGF.emitGlobalFunctionRef(loc, foreign); } /// Generate code to emit a thunk with native conventions that calls a /// function with foreign conventions. void SILGenFunction::emitForeignToNativeThunk(SILDeclRef thunk) { assert(!thunk.isForeign && "foreign-to-native thunks only"); // Wrap the function in its original form. auto fd = cast<AbstractFunctionDecl>(thunk.getDecl()); auto nativeCI = getConstantInfo(thunk); auto nativeFnTy = F.getLoweredFunctionType(); assert(nativeFnTy == nativeCI.SILFnType); // Use the same generic environment as the native entry point. F.setGenericEnvironment(nativeCI.GenericEnv); SILDeclRef foreignDeclRef = thunk.asForeign(true); SILConstantInfo foreignCI = getConstantInfo(foreignDeclRef); auto foreignFnTy = foreignCI.SILFnType; // Find the foreign error convention and 'self' parameter index. Optional<ForeignErrorConvention> foreignError; if (nativeFnTy->hasErrorResult()) { foreignError = fd->getForeignErrorConvention(); assert(foreignError && "couldn't find foreign error convention!"); } ImportAsMemberStatus memberStatus = fd->getImportAsMemberStatus(); // Forward the arguments. auto forwardedParameters = fd->getParameterLists(); // For allocating constructors, 'self' is a metatype, not the 'self' value // formally present in the constructor body. Type allocatorSelfType; if (thunk.kind == SILDeclRef::Kind::Allocator) { allocatorSelfType = forwardedParameters[0] ->getInterfaceType(getASTContext()) ->getWithoutSpecifierType(); if (F.getGenericEnvironment()) allocatorSelfType = F.getGenericEnvironment() ->mapTypeIntoContext(allocatorSelfType); forwardedParameters = forwardedParameters.slice(1); } SmallVector<SILValue, 8> params; // Introduce indirect returns if necessary. // TODO: Handle exploded results? We don't currently need to since the only // bridged indirect type is Any. SILValue indirectResult; SILFunctionConventions nativeConv(nativeFnTy, SGM.M); if (nativeConv.hasIndirectSILResults()) { assert(nativeConv.getNumIndirectSILResults() == 1 && "bridged exploded result?!"); indirectResult = F.begin()->createFunctionArgument(nativeConv.getSingleSILResultType()); } for (auto *paramList : reversed(forwardedParameters)) bindParametersForForwarding(paramList, params); if (allocatorSelfType) { auto selfMetatype = CanMetatypeType::get(allocatorSelfType->getCanonicalType()); auto selfArg = F.begin()->createFunctionArgument( getLoweredLoadableType(selfMetatype), fd->getImplicitSelfDecl()); params.push_back(selfArg); } // Set up the throw destination if necessary. CleanupLocation cleanupLoc(fd); if (foreignError) { prepareRethrowEpilog(cleanupLoc); } SILValue result; { Scope scope(Cleanups, fd); // Bridge all the arguments. SmallVector<ManagedValue, 8> args; unsigned foreignArgIndex = 0; // A helper function to add a function error argument in the // appropriate position. auto maybeAddForeignErrorArg = [&] { if (foreignError && foreignArgIndex == foreignError->getErrorParameterIndex()) { args.push_back(ManagedValue()); foreignArgIndex++; } }; { auto foreignFormalParams = expandTupleTypes(foreignCI.LoweredType.getParams()); auto nativeFormalParams = expandTupleTypes(nativeCI.LoweredType.getParams()); for (unsigned nativeParamIndex : indices(params)) { // Bring the parameter to +1. auto paramValue = params[nativeParamIndex]; auto thunkParam = nativeFnTy->getParameters()[nativeParamIndex]; // TODO: Could avoid a retain if the bridged parameter is also +0 and // doesn't require a bridging conversion. ManagedValue param; switch (thunkParam.getConvention()) { case ParameterConvention::Direct_Owned: param = emitManagedRValueWithCleanup(paramValue); break; case ParameterConvention::Direct_Guaranteed: case ParameterConvention::Direct_Unowned: param = emitManagedRetain(fd, paramValue); break; case ParameterConvention::Indirect_Inout: case ParameterConvention::Indirect_InoutAliasable: param = ManagedValue::forLValue(paramValue); break; case ParameterConvention::Indirect_In: param = emitManagedRValueWithCleanup(paramValue); break; case ParameterConvention::Indirect_In_Guaranteed: { auto tmp = emitTemporaryAllocation(fd, paramValue->getType()); B.createCopyAddr(fd, paramValue, tmp, IsNotTake, IsInitialization); param = emitManagedRValueWithCleanup(tmp); break; } case ParameterConvention::Indirect_In_Constant: llvm_unreachable("unsupported convention"); } maybeAddForeignErrorArg(); bool isSelf = nativeParamIndex == params.size() - 1; if (memberStatus.isInstance()) { // Leave space for `self` to be filled in later. if (foreignArgIndex == memberStatus.getSelfIndex()) { args.push_back({}); foreignArgIndex++; } // Use the `self` space we skipped earlier if it's time. if (isSelf) { foreignArgIndex = memberStatus.getSelfIndex(); } } else if (memberStatus.isStatic() && isSelf) { // Lose a static `self` parameter. break; } CanType nativeFormalType = F.mapTypeIntoContext(nativeFormalParams[nativeParamIndex]) ->getCanonicalType(); CanType foreignFormalType = F.mapTypeIntoContext(foreignFormalParams[nativeParamIndex]) ->getCanonicalType(); auto foreignParam = foreignFnTy->getParameters()[foreignArgIndex++]; SILType foreignLoweredTy = F.mapTypeIntoContext(foreignParam.getSILStorageType()); auto bridged = emitNativeToBridgedValue(fd, param, nativeFormalType, foreignFormalType, foreignLoweredTy); // Handle C pointer arguments imported as indirect `self` arguments. if (foreignParam.getConvention() == ParameterConvention::Indirect_In) { auto temp = emitTemporaryAllocation(fd, bridged.getType()); bridged.forwardInto(*this, fd, temp); bridged = emitManagedBufferWithCleanup(temp); } if (memberStatus.isInstance() && isSelf) { // Fill in the `self` space. args[memberStatus.getSelfIndex()] = bridged; } else { args.push_back(bridged); } } } maybeAddForeignErrorArg(); // Call the original. auto subs = getForwardingSubstitutions(); auto fn = getThunkedForeignFunctionRef(*this, fd, foreignDeclRef, args, subs, foreignCI); auto fnType = fn->getType().castTo<SILFunctionType>(); fnType = fnType->substGenericArgs(SGM.M, subs); CanType nativeFormalResultType = fd->mapTypeIntoContext(nativeCI.LoweredType.getResult()) ->getCanonicalType(); CanType bridgedFormalResultType = fd->mapTypeIntoContext(foreignCI.LoweredType.getResult()) ->getCanonicalType(); CalleeTypeInfo calleeTypeInfo( fnType, AbstractionPattern(nativeFnTy->getGenericSignature(), bridgedFormalResultType), nativeFormalResultType, foreignError, ImportAsMemberStatus()); auto init = indirectResult ? useBufferAsTemporary(indirectResult, getTypeLowering(indirectResult->getType())) : nullptr; SGFContext context(init.get()); ResultPlanPtr resultPlan = ResultPlanBuilder::computeResultPlan( *this, calleeTypeInfo, fd, context); ArgumentScope argScope(*this, fd); ManagedValue resultMV = emitApply(std::move(resultPlan), std::move(argScope), fd, ManagedValue::forUnmanaged(fn), subs, args, calleeTypeInfo, ApplyOptions::None, context) .getAsSingleValue(*this, fd); if (indirectResult) { if (!resultMV.isInContext()) { init->copyOrInitValueInto(*this, fd, resultMV, /*isInit*/ true); init->finishInitialization(*this); } init->getManagedAddress().forward(*this); result = emitEmptyTuple(fd); } else { result = resultMV.forward(*this); } } B.createReturn(ImplicitReturnLocation::getImplicitReturnLoc(fd), result); // Emit the throw destination. emitRethrowEpilog(fd); }
/* --------------------------------------------------------------------------- Open Asset Import Library (assimp) --------------------------------------------------------------------------- Copyright (c) 2006-2020, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. 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. --------------------------------------------------------------------------- */ /** @file B3DImporter.cpp * @brief Implementation of the b3d importer class */ #ifndef ASSIMP_BUILD_NO_B3D_IMPORTER // internal headers #include "AssetLib/B3D/B3DImporter.h" #include "PostProcessing/ConvertToLHProcess.h" #include "PostProcessing/TextureTransform.h" #include <assimp/StringUtils.h> #include <assimp/anim.h> #include <assimp/importerdesc.h> #include <assimp/scene.h> #include <assimp/DefaultLogger.hpp> #include <assimp/IOSystem.hpp> #include <memory> using namespace Assimp; using namespace std; static const aiImporterDesc desc = { "BlitzBasic 3D Importer", "", "", "http://www.blitzbasic.com/", aiImporterFlags_SupportBinaryFlavour, 0, 0, 0, 0, "b3d" }; #ifdef _MSC_VER #pragma warning(disable : 4018) #endif //#define DEBUG_B3D template <typename T> void DeleteAllBarePointers(std::vector<T> &x) { for (auto p : x) { delete p; } } B3DImporter::~B3DImporter() { } // ------------------------------------------------------------------------------------------------ bool B3DImporter::CanRead(const std::string &pFile, IOSystem * /*pIOHandler*/, bool /*checkSig*/) const { size_t pos = pFile.find_last_of('.'); if (pos == string::npos) { return false; } string ext = pFile.substr(pos + 1); if (ext.size() != 3) { return false; } return (ext[0] == 'b' || ext[0] == 'B') && (ext[1] == '3') && (ext[2] == 'd' || ext[2] == 'D'); } // ------------------------------------------------------------------------------------------------ // Loader meta information const aiImporterDesc *B3DImporter::GetInfo() const { return &desc; } // ------------------------------------------------------------------------------------------------ void B3DImporter::InternReadFile(const std::string &pFile, aiScene *pScene, IOSystem *pIOHandler) { std::unique_ptr<IOStream> file(pIOHandler->Open(pFile)); // Check whether we can read from the file if (file.get() == nullptr) { throw DeadlyImportError("Failed to open B3D file " + pFile + "."); } // check whether the .b3d file is large enough to contain // at least one chunk. size_t fileSize = file->FileSize(); if (fileSize < 8) { throw DeadlyImportError("B3D File is too small."); } _pos = 0; _buf.resize(fileSize); file->Read(&_buf[0], 1, fileSize); _stack.clear(); ReadBB3D(pScene); } // ------------------------------------------------------------------------------------------------ AI_WONT_RETURN void B3DImporter::Oops() { throw DeadlyImportError("B3D Importer - INTERNAL ERROR"); } // ------------------------------------------------------------------------------------------------ AI_WONT_RETURN void B3DImporter::Fail(string str) { #ifdef DEBUG_B3D ASSIMP_LOG_ERROR_F("Error in B3D file data: ", str); #endif throw DeadlyImportError("B3D Importer - error in B3D file data: " + str); } // ------------------------------------------------------------------------------------------------ int B3DImporter::ReadByte() { if (_pos > _buf.size()) { Fail("EOF"); } return _buf[_pos++]; } // ------------------------------------------------------------------------------------------------ int B3DImporter::ReadInt() { if (_pos + 4 > _buf.size()) { Fail("EOF"); } int n; memcpy(&n, &_buf[_pos], 4); _pos += 4; return n; } // ------------------------------------------------------------------------------------------------ float B3DImporter::ReadFloat() { if (_pos + 4 > _buf.size()) { Fail("EOF"); } float n; memcpy(&n, &_buf[_pos], 4); _pos += 4; return n; } // ------------------------------------------------------------------------------------------------ aiVector2D B3DImporter::ReadVec2() { float x = ReadFloat(); float y = ReadFloat(); return aiVector2D(x, y); } // ------------------------------------------------------------------------------------------------ aiVector3D B3DImporter::ReadVec3() { float x = ReadFloat(); float y = ReadFloat(); float z = ReadFloat(); return aiVector3D(x, y, z); } // ------------------------------------------------------------------------------------------------ aiQuaternion B3DImporter::ReadQuat() { // (aramis_acg) Fix to adapt the loader to changed quat orientation float w = -ReadFloat(); float x = ReadFloat(); float y = ReadFloat(); float z = ReadFloat(); return aiQuaternion(w, x, y, z); } // ------------------------------------------------------------------------------------------------ string B3DImporter::ReadString() { if (_pos > _buf.size()) { Fail("EOF"); } string str; while (_pos < _buf.size()) { char c = (char)ReadByte(); if (!c) { return str; } str += c; } return string(); } // ------------------------------------------------------------------------------------------------ string B3DImporter::ReadChunk() { string tag; for (int i = 0; i < 4; ++i) { tag += char(ReadByte()); } #ifdef DEBUG_B3D ASSIMP_LOG_DEBUG_F("ReadChunk: ", tag); #endif unsigned sz = (unsigned)ReadInt(); _stack.push_back(_pos + sz); return tag; } // ------------------------------------------------------------------------------------------------ void B3DImporter::ExitChunk() { _pos = _stack.back(); _stack.pop_back(); } // ------------------------------------------------------------------------------------------------ size_t B3DImporter::ChunkSize() { return _stack.back() - _pos; } // ------------------------------------------------------------------------------------------------ template <class T> T *B3DImporter::to_array(const vector<T> &v) { if (v.empty()) { return 0; } T *p = new T[v.size()]; for (size_t i = 0; i < v.size(); ++i) { p[i] = v[i]; } return p; } // ------------------------------------------------------------------------------------------------ template <class T> T **unique_to_array(vector<std::unique_ptr<T>> &v) { if (v.empty()) { return 0; } T **p = new T *[v.size()]; for (size_t i = 0; i < v.size(); ++i) { p[i] = v[i].release(); } return p; } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadTEXS() { while (ChunkSize()) { string name = ReadString(); /*int flags=*/ReadInt(); /*int blend=*/ReadInt(); /*aiVector2D pos=*/ReadVec2(); /*aiVector2D scale=*/ReadVec2(); /*float rot=*/ReadFloat(); _textures.push_back(name); } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadBRUS() { int n_texs = ReadInt(); if (n_texs < 0 || n_texs > 8) { Fail("Bad texture count"); } while (ChunkSize()) { string name = ReadString(); aiVector3D color = ReadVec3(); float alpha = ReadFloat(); float shiny = ReadFloat(); /*int blend=**/ ReadInt(); int fx = ReadInt(); std::unique_ptr<aiMaterial> mat(new aiMaterial); // Name aiString ainame(name); mat->AddProperty(&ainame, AI_MATKEY_NAME); // Diffuse color mat->AddProperty(&color, 1, AI_MATKEY_COLOR_DIFFUSE); // Opacity mat->AddProperty(&alpha, 1, AI_MATKEY_OPACITY); // Specular color aiColor3D speccolor(shiny, shiny, shiny); mat->AddProperty(&speccolor, 1, AI_MATKEY_COLOR_SPECULAR); // Specular power float specpow = shiny * 128; mat->AddProperty(&specpow, 1, AI_MATKEY_SHININESS); // Double sided if (fx & 0x10) { int i = 1; mat->AddProperty(&i, 1, AI_MATKEY_TWOSIDED); } //Textures for (int i = 0; i < n_texs; ++i) { int texid = ReadInt(); if (texid < -1 || (texid >= 0 && texid >= static_cast<int>(_textures.size()))) { Fail("Bad texture id"); } if (i == 0 && texid >= 0) { aiString texname(_textures[texid]); mat->AddProperty(&texname, AI_MATKEY_TEXTURE_DIFFUSE(0)); } } _materials.emplace_back(std::move(mat)); } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadVRTS() { _vflags = ReadInt(); _tcsets = ReadInt(); _tcsize = ReadInt(); if (_tcsets < 0 || _tcsets > 4 || _tcsize < 0 || _tcsize > 4) { Fail("Bad texcoord data"); } int sz = 12 + (_vflags & 1 ? 12 : 0) + (_vflags & 2 ? 16 : 0) + (_tcsets * _tcsize * 4); size_t n_verts = ChunkSize() / sz; int v0 = static_cast<int>(_vertices.size()); _vertices.resize(v0 + n_verts); for (unsigned int i = 0; i < n_verts; ++i) { Vertex &v = _vertices[v0 + i]; memset(v.bones, 0, sizeof(v.bones)); memset(v.weights, 0, sizeof(v.weights)); v.vertex = ReadVec3(); if (_vflags & 1) { v.normal = ReadVec3(); } if (_vflags & 2) { ReadQuat(); //skip v 4bytes... } for (int j = 0; j < _tcsets; ++j) { float t[4] = { 0, 0, 0, 0 }; for (int k = 0; k < _tcsize; ++k) { t[k] = ReadFloat(); } t[1] = 1 - t[1]; if (!j) { v.texcoords = aiVector3D(t[0], t[1], t[2]); } } } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadTRIS(int v0) { int matid = ReadInt(); if (matid == -1) { matid = 0; } else if (matid < 0 || matid >= (int)_materials.size()) { #ifdef DEBUG_B3D ASSIMP_LOG_ERROR_F("material id=", matid); #endif Fail("Bad material id"); } std::unique_ptr<aiMesh> mesh(new aiMesh); mesh->mMaterialIndex = matid; mesh->mNumFaces = 0; mesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE; size_t n_tris = ChunkSize() / 12; aiFace *face = mesh->mFaces = new aiFace[n_tris]; for (unsigned int i = 0; i < n_tris; ++i) { int i0 = ReadInt() + v0; int i1 = ReadInt() + v0; int i2 = ReadInt() + v0; if (i0 < 0 || i0 >= (int)_vertices.size() || i1 < 0 || i1 >= (int)_vertices.size() || i2 < 0 || i2 >= (int)_vertices.size()) { #ifdef DEBUG_B3D ASSIMP_LOG_ERROR_F("Bad triangle index: i0=", i0, ", i1=", i1, ", i2=", i2); #endif Fail("Bad triangle index"); continue; } face->mNumIndices = 3; face->mIndices = new unsigned[3]; face->mIndices[0] = i0; face->mIndices[1] = i1; face->mIndices[2] = i2; ++mesh->mNumFaces; ++face; } _meshes.emplace_back(std::move(mesh)); } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadMESH() { /*int matid=*/ReadInt(); int v0 = static_cast<int>(_vertices.size()); while (ChunkSize()) { string t = ReadChunk(); if (t == "VRTS") { ReadVRTS(); } else if (t == "TRIS") { ReadTRIS(v0); } ExitChunk(); } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadBONE(int id) { while (ChunkSize()) { int vertex = ReadInt(); float weight = ReadFloat(); if (vertex < 0 || vertex >= (int)_vertices.size()) { Fail("Bad vertex index"); } Vertex &v = _vertices[vertex]; for (int i = 0; i < 4; ++i) { if (!v.weights[i]) { v.bones[i] = static_cast<unsigned char>(id); v.weights[i] = weight; break; } } } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadKEYS(aiNodeAnim *nodeAnim) { vector<aiVectorKey> trans, scale; vector<aiQuatKey> rot; int flags = ReadInt(); while (ChunkSize()) { int frame = ReadInt(); if (flags & 1) { trans.push_back(aiVectorKey(frame, ReadVec3())); } if (flags & 2) { scale.push_back(aiVectorKey(frame, ReadVec3())); } if (flags & 4) { rot.push_back(aiQuatKey(frame, ReadQuat())); } } if (flags & 1) { nodeAnim->mNumPositionKeys = static_cast<unsigned int>(trans.size()); nodeAnim->mPositionKeys = to_array(trans); } if (flags & 2) { nodeAnim->mNumScalingKeys = static_cast<unsigned int>(scale.size()); nodeAnim->mScalingKeys = to_array(scale); } if (flags & 4) { nodeAnim->mNumRotationKeys = static_cast<unsigned int>(rot.size()); nodeAnim->mRotationKeys = to_array(rot); } } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadANIM() { /*int flags=*/ReadInt(); int frames = ReadInt(); float fps = ReadFloat(); std::unique_ptr<aiAnimation> anim(new aiAnimation); anim->mDuration = frames; anim->mTicksPerSecond = fps; _animations.emplace_back(std::move(anim)); } // ------------------------------------------------------------------------------------------------ aiNode *B3DImporter::ReadNODE(aiNode *parent) { string name = ReadString(); aiVector3D t = ReadVec3(); aiVector3D s = ReadVec3(); aiQuaternion r = ReadQuat(); aiMatrix4x4 trans, scale, rot; aiMatrix4x4::Translation(t, trans); aiMatrix4x4::Scaling(s, scale); rot = aiMatrix4x4(r.GetMatrix()); aiMatrix4x4 tform = trans * rot * scale; int nodeid = static_cast<int>(_nodes.size()); aiNode *node = new aiNode(name); _nodes.push_back(node); node->mParent = parent; node->mTransformation = tform; std::unique_ptr<aiNodeAnim> nodeAnim; vector<unsigned> meshes; vector<aiNode *> children; while (ChunkSize()) { const string chunk = ReadChunk(); if (chunk == "MESH") { unsigned int n = static_cast<unsigned int>(_meshes.size()); ReadMESH(); for (unsigned int i = n; i < static_cast<unsigned int>(_meshes.size()); ++i) { meshes.push_back(i); } } else if (chunk == "BONE") { ReadBONE(nodeid); } else if (chunk == "ANIM") { ReadANIM(); } else if (chunk == "KEYS") { if (!nodeAnim) { nodeAnim.reset(new aiNodeAnim); nodeAnim->mNodeName = node->mName; } ReadKEYS(nodeAnim.get()); } else if (chunk == "NODE") { aiNode *child = ReadNODE(node); children.push_back(child); } ExitChunk(); } if (nodeAnim) { _nodeAnims.emplace_back(std::move(nodeAnim)); } node->mNumMeshes = static_cast<unsigned int>(meshes.size()); node->mMeshes = to_array(meshes); node->mNumChildren = static_cast<unsigned int>(children.size()); node->mChildren = to_array(children); return node; } // ------------------------------------------------------------------------------------------------ void B3DImporter::ReadBB3D(aiScene *scene) { _textures.clear(); _materials.clear(); _vertices.clear(); _meshes.clear(); DeleteAllBarePointers(_nodes); _nodes.clear(); _nodeAnims.clear(); _animations.clear(); string t = ReadChunk(); if (t == "BB3D") { int version = ReadInt(); if (!DefaultLogger::isNullLogger()) { char dmp[128]; ai_snprintf(dmp, 128, "B3D file format version: %i", version); ASSIMP_LOG_INFO(dmp); } while (ChunkSize()) { const string chunk = ReadChunk(); if (chunk == "TEXS") { ReadTEXS(); } else if (chunk == "BRUS") { ReadBRUS(); } else if (chunk == "NODE") { ReadNODE(0); } ExitChunk(); } } ExitChunk(); if (!_nodes.size()) { Fail("No nodes"); } if (!_meshes.size()) { Fail("No meshes"); } // Fix nodes/meshes/bones for (size_t i = 0; i < _nodes.size(); ++i) { aiNode *node = _nodes[i]; for (size_t j = 0; j < node->mNumMeshes; ++j) { aiMesh *mesh = _meshes[node->mMeshes[j]].get(); int n_tris = mesh->mNumFaces; int n_verts = mesh->mNumVertices = n_tris * 3; aiVector3D *mv = mesh->mVertices = new aiVector3D[n_verts], *mn = 0, *mc = 0; if (_vflags & 1) { mn = mesh->mNormals = new aiVector3D[n_verts]; } if (_tcsets) { mc = mesh->mTextureCoords[0] = new aiVector3D[n_verts]; } aiFace *face = mesh->mFaces; vector<vector<aiVertexWeight>> vweights(_nodes.size()); for (int vertIdx = 0; vertIdx < n_verts; vertIdx += 3) { for (int faceIndex = 0; faceIndex < 3; ++faceIndex) { Vertex &v = _vertices[face->mIndices[faceIndex]]; *mv++ = v.vertex; if (mn) *mn++ = v.normal; if (mc) *mc++ = v.texcoords; face->mIndices[faceIndex] = vertIdx + faceIndex; for (int k = 0; k < 4; ++k) { if (!v.weights[k]) break; int bone = v.bones[k]; float weight = v.weights[k]; vweights[bone].push_back(aiVertexWeight(vertIdx + faceIndex, weight)); } } ++face; } vector<aiBone *> bones; for (size_t weightIndx = 0; weightIndx < vweights.size(); ++weightIndx) { vector<aiVertexWeight> &weights = vweights[weightIndx]; if (!weights.size()) { continue; } aiBone *bone = new aiBone; bones.push_back(bone); aiNode *bnode = _nodes[weightIndx]; bone->mName = bnode->mName; bone->mNumWeights = static_cast<unsigned int>(weights.size()); bone->mWeights = to_array(weights); aiMatrix4x4 mat = bnode->mTransformation; while (bnode->mParent) { bnode = bnode->mParent; mat = bnode->mTransformation * mat; } bone->mOffsetMatrix = mat.Inverse(); } mesh->mNumBones = static_cast<unsigned int>(bones.size()); mesh->mBones = to_array(bones); } } //nodes scene->mRootNode = _nodes[0]; _nodes.clear(); // node ownership now belongs to scene //material if (!_materials.size()) { _materials.emplace_back(std::unique_ptr<aiMaterial>(new aiMaterial)); } scene->mNumMaterials = static_cast<unsigned int>(_materials.size()); scene->mMaterials = unique_to_array(_materials); //meshes scene->mNumMeshes = static_cast<unsigned int>(_meshes.size()); scene->mMeshes = unique_to_array(_meshes); //animations if (_animations.size() == 1 && _nodeAnims.size()) { aiAnimation *anim = _animations.back().get(); anim->mNumChannels = static_cast<unsigned int>(_nodeAnims.size()); anim->mChannels = unique_to_array(_nodeAnims); scene->mNumAnimations = static_cast<unsigned int>(_animations.size()); scene->mAnimations = unique_to_array(_animations); } // convert to RH MakeLeftHandedProcess makeleft; makeleft.Execute(scene); FlipWindingOrderProcess flip; flip.Execute(scene); } #endif // !! ASSIMP_BUILD_NO_B3D_IMPORTER
/* * * Copyright 2015, 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 "test/cpp/qps/usage_timer.h" #include <grpc/support/time.h> #include <sys/resource.h> #include <sys/time.h> UsageTimer::UsageTimer() : start_(Sample()) {} double UsageTimer::Now() { auto ts = gpr_now(GPR_CLOCK_REALTIME); return ts.tv_sec + 1e-9 * ts.tv_nsec; } static double time_double(struct timeval* tv) { return tv->tv_sec + 1e-6 * tv->tv_usec; } UsageTimer::Result UsageTimer::Sample() { struct rusage usage; struct timeval tv; gettimeofday(&tv, NULL); getrusage(RUSAGE_SELF, &usage); Result r; r.wall = time_double(&tv); r.user = time_double(&usage.ru_utime); r.system = time_double(&usage.ru_stime); return r; } UsageTimer::Result UsageTimer::Mark() const { Result s = Sample(); Result r; r.wall = s.wall - start_.wall; r.user = s.user - start_.user; r.system = s.system - start_.system; return r; }
// ctcbin/nnet2-ctc-latgen-faster.cc // Copyright 2009-2012 Microsoft Corporation // Johns Hopkins University (author: Daniel Povey) // 2014 Guoguo Chen // 2016 LingoChamp Feiteng // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "fstext/kaldi-fst-io.h" #include "nnet2/am-nnet.h" #include "decoder/decoder-wrappers.h" #include "ctc/ctc-decodable-am-nnet.h" #include "ctc/ctc-decoder-wrappers.h" #include "ctc/ctc-nnet-example.h" #include "base/timer.h" int main(int argc, char *argv[]) { try { using namespace kaldi; using namespace kaldi::ctc; typedef kaldi::int32 int32; using fst::SymbolTable; using fst::VectorFst; using fst::StdArc; const char *usage = "Generate lattices using neural net model.\n" "Usage: nnet-latgen-faster [options] <nnet-in> <fst-in|fsts-rspecifier> <features-rspecifier>" " <lattice-wspecifier> [ <words-wspecifier> [<alignments-wspecifier>] ]\n"; ParseOptions po(usage); Timer timer; bool allow_partial = true; BaseFloat blank_threshold = 0.98; BaseFloat acoustic_scale = 1.0; int32 frame_subsampling_factor = 0, frame_shift = 0; LatticeFasterDecoderConfig config; std::string use_gpu = "yes"; std::string word_syms_filename; config.Register(&po); po.Register("acoustic-scale", &acoustic_scale, "Scaling factor for acoustic likelihoods"); po.Register("word-symbol-table", &word_syms_filename, "Symbol table for words [for debug output]"); po.Register("allow-partial", &allow_partial, "If true, produce output even if end state was not reached."); po.Register("blank-threshold", &blank_threshold, "If blank prob bigger than blank_threshold, skip this frame(faster), set 1.0 to avoid skip any frame."); po.Register("use-gpu", &use_gpu, "yes|no|optional|wait, only has effect if compiled with CUDA"); po.Register("frame-shift", &frame_shift, "Allows you to shift time values " "in the supervision data (excluding iVector data) - useful in " "augmenting data. Note, the outputs will remain at the closest " "exact multiples of the frame subsampling factor"); po.Register("frame-subsampling-factor", &frame_subsampling_factor, "the frame subsampling factor"); po.Read(argc, argv); if (po.NumArgs() < 4 || po.NumArgs() > 6) { po.PrintUsage(); exit(1); } #if HAVE_CUDA==1 CuDevice::Instantiate().SelectGpuId(use_gpu); #endif std::string model_in_filename = po.GetArg(1), fst_in_str = po.GetArg(2), feature_rspecifier = po.GetArg(3), lattice_wspecifier = po.GetArg(4), words_wspecifier = po.GetOptArg(5), alignment_wspecifier = po.GetOptArg(6); CtcTransitionModel trans_model; AmNnet am_nnet; { bool binary_read; Input ki(model_in_filename, &binary_read); trans_model.Read(ki.Stream(), binary_read); am_nnet.Read(ki.Stream(), binary_read); } bool determinize = config.determinize_lattice; CompactLatticeWriter compact_lattice_writer; LatticeWriter lattice_writer; if (! (determinize ? compact_lattice_writer.Open(lattice_wspecifier) : lattice_writer.Open(lattice_wspecifier))) KALDI_ERR << "Could not open table for writing lattices: " << lattice_wspecifier; Int32VectorWriter words_writer(words_wspecifier); Int32VectorWriter alignment_writer(alignment_wspecifier); fst::SymbolTable *word_syms = NULL; if (word_syms_filename != "") if (!(word_syms = fst::SymbolTable::ReadText(word_syms_filename))) KALDI_ERR << "Could not read symbol table from file " << word_syms_filename; double tot_like = 0.0; kaldi::int64 frame_count = 0; int num_success = 0, num_fail = 0; if (ClassifyRspecifier(fst_in_str, NULL, NULL) == kNoRspecifier) { SequentialBaseFloatCuMatrixReader feature_reader(feature_rspecifier); // Input FST is just one FST, not a table of FSTs. VectorFst<StdArc> *decode_fst = fst::ReadFstKaldi(fst_in_str); { LatticeFasterDecoder decoder(*decode_fst, config); for (; !feature_reader.Done(); feature_reader.Next()) { std::string utt = feature_reader.Key(); const CuMatrix<BaseFloat> &features (feature_reader.Value()); if (features.NumRows() == 0) { KALDI_WARN << "Zero-length utterance: " << utt; num_fail++; continue; } bool pad_input = true; CuMatrix<BaseFloat> feats; if (frame_subsampling_factor > 1) { Matrix<BaseFloat> features_cpu(features); FrameSubsamplingShiftFeatureTimes(frame_subsampling_factor, frame_shift, features_cpu); feats.Resize(features_cpu.NumRows(), features_cpu.NumCols(), kUndefined, kStrideEqualNumCols); feats.CopyFromMat(features_cpu); } else { feats.Resize(features.NumRows(), features.NumCols(), kUndefined, kStrideEqualNumCols); feats.CopyFromMat(features); } CtcDecodableAmNnet nnet_decodable(trans_model, am_nnet, feats, pad_input, acoustic_scale, blank_threshold); double like; if (DecodeUtteranceLatticeFasterCtc( decoder, nnet_decodable, trans_model, word_syms, utt, acoustic_scale, determinize, allow_partial, &alignment_writer, &words_writer, &compact_lattice_writer, &lattice_writer, &like)) { tot_like += like; frame_count += features.NumRows(); num_success++; } else num_fail++; } } delete decode_fst; // delete this only after decoder goes out of scope. } else { // We have different FSTs for different utterances. SequentialTableReader<fst::VectorFstHolder> fst_reader(fst_in_str); RandomAccessBaseFloatCuMatrixReader feature_reader(feature_rspecifier); for (; !fst_reader.Done(); fst_reader.Next()) { std::string utt = fst_reader.Key(); if (!feature_reader.HasKey(utt)) { KALDI_WARN << "Not decoding utterance " << utt << " because no features available."; num_fail++; continue; } const CuMatrix<BaseFloat> &features = feature_reader.Value(utt); if (features.NumRows() == 0) { KALDI_WARN << "Zero-length utterance: " << utt; num_fail++; continue; } LatticeFasterDecoder decoder(fst_reader.Value(), config); bool pad_input = true; CuMatrix<BaseFloat> feats; if (frame_subsampling_factor > 1) { Matrix<BaseFloat> features_cpu(features); FrameSubsamplingShiftFeatureTimes(frame_subsampling_factor, frame_shift, features_cpu); feats.Resize(features_cpu.NumRows(), features_cpu.NumCols(), kUndefined, kStrideEqualNumCols); feats.CopyFromMat(features_cpu); } else { feats.Resize(features.NumRows(), features.NumCols(), kUndefined, kStrideEqualNumCols); feats.CopyFromMat(features); } CtcDecodableAmNnet nnet_decodable(trans_model, am_nnet, feats, pad_input, acoustic_scale); double like; if (DecodeUtteranceLatticeFasterCtc( decoder, nnet_decodable, trans_model, word_syms, utt, acoustic_scale, determinize, allow_partial, &alignment_writer, &words_writer, &compact_lattice_writer, &lattice_writer, &like)) { tot_like += like; frame_count += features.NumRows(); num_success++; } else num_fail++; } } #if HAVE_CUDA==1 CuDevice::Instantiate().PrintProfile(); #endif double elapsed = timer.Elapsed(); KALDI_LOG << "Time taken "<< elapsed << "s: real-time factor assuming 100 frames/sec is " << (elapsed*100.0/frame_count); KALDI_LOG << "Done " << num_success << " utterances, failed for " << num_fail; KALDI_LOG << "Overall log-likelihood per frame is " << (tot_like/frame_count) << " over " << frame_count<<" frames."; delete word_syms; if (num_success != 0) return 0; else return 1; } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
/* @Copyright:LintCode @Author: qili @Problem: http://www.lintcode.com/problem/cosine-similarity @Language: C++ @Datetime: 16-07-26 07:25 */ class Solution { public: /** * @param A: An integer array. * @param B: An integer array. * @return: Cosine similarity. */ double cosineSimilarity(vector<int> A, vector<int> B) { if (A.size() != B.size() || A.size() == 0) return 2.0; int len = A.size(); double m = 0, d1 = 0, d2 = 0; for (int i = 0; i < len; ++i) { m += (double)A[i] * B[i]; d1 += (double)A[i] * A[i]; d2 += (double)B[i] * B[i]; } if (d1 == 0.0 || d2 == 0.0) return 2.0; d1 = std::sqrt(d1); d2 = std::sqrt(d2); return m / d1 / d2; } };
/** global.hpp **/ #ifndef GLOBAL_HPP #define GLOBAL_HPP #ifdef _WIN32 #define DLL #endif #ifdef DLL #ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #define DLL_CALL __stdcall #else #define DLL_EXPORT #define DLL_CALL #endif typedef const bool cbool; typedef const char cchar; typedef const signed char cschar; typedef signed char schar; typedef const unsigned char cuchar; typedef unsigned char uchar; typedef const short cshort; typedef const unsigned short cushort; typedef unsigned short ushort; typedef const int cint; typedef const unsigned int cuint; typedef unsigned int uint; typedef const long clong; typedef const unsigned long culong; typedef unsigned long ulong; typedef const float cfloat; typedef const double cdouble; typedef const long double cldouble; typedef long double ldouble; typedef const void cvoid; #endif
/* $Id: UIKeyboardHandlerNormal.cpp 69500 2017-10-28 15:14:05Z vboxsync $ */ /** @file * VBox Qt GUI - UIKeyboardHandlerNormal class implementation. */ /* * Copyright (C) 2010-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Qt includes: */ # ifndef VBOX_WS_MAC # include <QMainWindow> # include <QMenuBar> # include <QKeyEvent> # include <QTimer> # endif /* !VBOX_WS_MAC */ /* GUI includes: */ # include "UIKeyboardHandlerNormal.h" # ifndef VBOX_WS_MAC # include "UIMachineLogic.h" # include "UIMachineWindow.h" # include "UIShortcutPool.h" # endif /* !VBOX_WS_MAC */ #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Namespaces: */ #ifndef VBOX_WS_MAC using namespace UIExtraDataDefs; #endif /* !VBOX_WS_MAC */ UIKeyboardHandlerNormal::UIKeyboardHandlerNormal(UIMachineLogic* pMachineLogic) : UIKeyboardHandler(pMachineLogic) { } UIKeyboardHandlerNormal::~UIKeyboardHandlerNormal() { } #ifndef VBOX_WS_MAC bool UIKeyboardHandlerNormal::eventFilter(QObject *pWatchedObject, QEvent *pEvent) { /* Check if pWatchedObject object is view: */ if (UIMachineView *pWatchedView = isItListenedView(pWatchedObject)) { /* Get corresponding screen index: */ ulong uScreenId = m_views.key(pWatchedView); NOREF(uScreenId); /* Handle view events: */ switch (pEvent->type()) { /* We don't want this on the Mac, cause there the menu-bar isn't within the * window and popping up a menu there looks really ugly. */ case QEvent::KeyPress: { /* Get key-event: */ QKeyEvent *pKeyEvent = static_cast<QKeyEvent*>(pEvent); /* Process Host+Home as menu-bar activator: */ if (isHostKeyPressed() && QKeySequence(pKeyEvent->key()) == gShortcutPool->shortcut(GUI_Input_MachineShortcuts, QString("PopupMenu")).sequence()) { /* Trying to get menu-bar: */ QMenuBar *pMenuBar = qobject_cast<QMainWindow*>(m_windows[uScreenId])->menuBar(); /* If menu-bar is present and have actions: */ if (pMenuBar && !pMenuBar->actions().isEmpty()) { /* Is menu-bar visible? */ if (pMenuBar->isVisible()) { /* If 'active' action is NOT chosen: */ if (!pMenuBar->activeAction()) /* Set first menu-bar action as 'active': */ pMenuBar->setActiveAction(pMenuBar->actions()[0]); /* If 'active' action is chosen: */ if (pMenuBar->activeAction()) { /* Activate 'active' menu-bar action: */ pMenuBar->activeAction()->activate(QAction::Trigger); #ifdef VBOX_WS_WIN /* Windows host needs separate 'focus set' * to let menubar operate while popped up: */ pMenuBar->setFocus(); #endif /* VBOX_WS_WIN */ } } else { /* Post request to show popup-menu: */ QTimer::singleShot(0, m_pMachineLogic, SLOT(sltInvokePopupMenu())); } /* Filter-out this event: */ return true; } } break; } default: break; } } /* Else just propagate to base-class: */ return UIKeyboardHandler::eventFilter(pWatchedObject, pEvent); } #endif /* !VBOX_WS_MAC */
#include <SDL2/SDL.h> #include <SDL2/SDL_mixer.h> #include <iostream> using namespace std; #include "./menu.h" #include "../util/util.h" void start_page(SDL_Window* gWindow, SDL_Surface* gScreenSurface){ SDL_Surface* start_page = NULL; start_page = LoadSurface("source/picture/word/start.bmp"); // show picture SDL_BlitScaled(start_page, NULL, gScreenSurface, NULL); SDL_UpdateWindowSurface(gWindow); // play music Mix_Music* music = NULL; music = LoadMusic("source/music/m1.wav"); Mix_PlayMusic(music, -1); // check touch SDL_Event e; do{ SDL_PollEvent(&e); } while( e.type != SDL_KEYDOWN && e.type != SDL_MOUSEBUTTONDOWN ); // go to menu page Mix_FreeMusic(music); SDL_FreeSurface(start_page); } bool end_page(SDL_Window* gWindow, SDL_Surface* gScreenSurface, int end){ SDL_Surface* page = NULL; if(end == win){ cout << "win" << endl; page = LoadSurface("source/picture/word/win.bmp"); } else{ cout << "dead" << endl; page = LoadSurface("source/picture/word/loss.bmp"); } SDL_BlitScaled(page, NULL, gScreenSurface, NULL); SDL_UpdateWindowSurface(gWindow); SDL_Delay(1500); SDL_Event e; SDL_PollEvent(&e); do{ SDL_PollEvent(&e); if (e.type == SDL_QUIT) return true; } while( e.key.keysym.scancode != SDL_SCANCODE_Q && e.key.keysym.scancode != SDL_SCANCODE_R ); if(e.key.keysym.scancode == SDL_SCANCODE_Q){ return true; } return false; }
#undef NDEBUG #include"Bitcoin/Tx.hpp" #include"Bitcoin/TxId.hpp" #include"Util/Str.hpp" #include<assert.h> #include<sstream> #include<iostream> namespace { Bitcoin::Tx test_tx(char const* hextx, char const* hextxid) { auto tx_bytes = Util::Str::hexread(hextx); auto tx_s = std::string(tx_bytes.begin(), tx_bytes.end()); auto is = std::istringstream(std::move(tx_s)); auto tx = Bitcoin::Tx(); is >> tx; assert(tx.get_txid() == Bitcoin::TxId(hextxid)); auto os = std::ostringstream(); os << tx; tx_s = os.str(); assert(Util::Str::hexdump(&tx_s[0], tx_s.size()) == hextx); auto tx_2 = Bitcoin::Tx(hextx); assert(tx == tx_2); assert(std::string(tx) == hextx); return tx; } } int main() { auto tx = Bitcoin::Tx(); /* Random onchain tx. */ tx = test_tx( "02000000000101385e378e72018e7e902980145fdbbfd16e6b0526bb63c656d5c1af3e63a6292e000000001716001471b2a7fc4fd6d6f4ee0d80db24a7bee788ba6442feffffff02636a9902000000001976a9143b9cdf5afe5640861cb96cdb3af5eca4216e303388ac431663720000000017a91471c7ff853df638d8bc076ba0841dcc30749ed74f870247304402204e4c50c34727caf658ecf0455d67d320078a5861e7bbe1fd207bbd720a40f7bd0220234067858406eb86cec3b0ff1d10612dc2bfc1a1d63782aeb0d9aea688d2c7f20121027ee675512d19023e72ba3c75ba5738e0e56979d6916da9bba8ddf4cc331942d0eae80900" , "31e394b1c76d6162b95487e6719a0d4a4b585a0a22c96980978a5c6ee2c06197" ); /* Details below were extracted from blockstream.info. */ assert(tx.nVersion == 2); assert(tx.inputs.size() == 1); assert(tx.inputs[0].prevTxid == Bitcoin::TxId("2e29a6633eafc1d556c663bb26056b6ed1bfdb5f148029907e8e01728e375e38")); assert(tx.inputs[0].prevOut == 0); assert(tx.inputs[0].scriptSig == Util::Str::hexread("16001471b2a7fc4fd6d6f4ee0d80db24a7bee788ba6442")); assert(tx.inputs[0].witness.witnesses.size() == 2); assert(tx.inputs[0].witness.witnesses[0] == Util::Str::hexread("304402204e4c50c34727caf658ecf0455d67d320078a5861e7bbe1fd207bbd720a40f7bd0220234067858406eb86cec3b0ff1d10612dc2bfc1a1d63782aeb0d9aea688d2c7f201")); assert(tx.inputs[0].witness.witnesses[1] == Util::Str::hexread("027ee675512d19023e72ba3c75ba5738e0e56979d6916da9bba8ddf4cc331942d0")); assert(tx.inputs[0].nSequence == 0xfffffffe); assert(tx.outputs.size() == 2); assert(tx.outputs[0].amount == Ln::Amount::sat(43608675)); assert(tx.outputs[0].scriptPubKey == Util::Str::hexread("76a9143b9cdf5afe5640861cb96cdb3af5eca4216e303388ac")); assert(tx.outputs[1].amount == Ln::Amount::sat(1919096387)); assert(tx.outputs[1].scriptPubKey == Util::Str::hexread("a91471c7ff853df638d8bc076ba0841dcc30749ed74f87")); assert(tx.nLockTime == 649450); /* Truncation. */ auto flag = false; try { tx = Bitcoin::Tx("02000000000101385e378e72018e7e902980145fdbbfd16e6b0526bb63c656d5c1af3e63a6292e000000001716001471b2a7fc4fd6d6f4ee0d80db24a7bee788ba6442feffffff02636a9902000000001976a9143b9cdf5afe5640861cb96cdb3af5eca4216e303388ac431663720000000017a91471c7ff853df638d8bc076ba0841dcc30749ed74f870247304402204e4c50c34727caf658ecf0455d67d320078a5861e7bbe1fd207bbd720a40f7bd0220234067858406eb86cec3b0ff1d10612dc2bfc1a1d63782aeb0d9aea688d2c7f20121027ee675512d19023e72ba3c75ba5738e0e56979d6916da9bba8ddf4cc331942d0eae809"); } catch (...) { flag = true; } assert(flag); /* Too long. */ flag = false; try { tx = Bitcoin::Tx("02000000000101385e378e72018e7e902980145fdbbfd16e6b0526bb63c656d5c1af3e63a6292e000000001716001471b2a7fc4fd6d6f4ee0d80db24a7bee788ba6442feffffff02636a9902000000001976a9143b9cdf5afe5640861cb96cdb3af5eca4216e303388ac431663720000000017a91471c7ff853df638d8bc076ba0841dcc30749ed74f870247304402204e4c50c34727caf658ecf0455d67d320078a5861e7bbe1fd207bbd720a40f7bd0220234067858406eb86cec3b0ff1d10612dc2bfc1a1d63782aeb0d9aea688d2c7f20121027ee675512d19023e72ba3c75ba5738e0e56979d6916da9bba8ddf4cc331942d0eae80900ff"); } catch (...) { flag = true; } assert(flag); return 0; }
#include <limits> #include <cmath> #include <itkImageToHistogramFilter.h> #include <itkMaskedImageToHistogramFilter.h> #include <itkHistogram.h> #include <itkExtractImageFilter.h> #include <itkImageRegionConstIterator.h> #include <itkChangeInformationImageFilter.h> #include <itkMinimumMaximumImageCalculator.h> #include <itkMinimumMaximumImageFilter.h> #include <itkMaskImageFilter.h> #include <itkExceptionObject.h> #include <mitkImageStatisticsCalculator.h> #include <mitkImage.h> #include <mitkHistogramStatisticsCalculator.h> #include <mitkImageAccessByItk.h> #include <mitkImageToItk.h> #include <mitkExtendedStatisticsImageFilter.h> #include <mitkExtendedLabelStatisticsImageFilter.h> #include <mitkImageTimeSelector.h> #include <mitkMinMaxImageFilterWithIndex.h> #include <mitkMinMaxLabelmageFilterWithIndex.h> #include <mitkitkMaskImageFilter.h> #include <mitkImageCast.h> #include <mitkMaskUtilities.h> #include "itkImageFileWriter.h" namespace mitk { void ImageStatisticsCalculator::SetInputImage(mitk::Image::Pointer image) { if (image != m_Image) { m_Image = image; m_StatisticsByTimeStep.resize(m_Image->GetTimeSteps()); m_StatisticsUpdateTimePerTimeStep.resize(m_Image->GetTimeSteps()); std::fill(m_StatisticsUpdateTimePerTimeStep.begin(), m_StatisticsUpdateTimePerTimeStep.end(), 0); this->Modified(); } } void ImageStatisticsCalculator::SetMask(mitk::MaskGenerator::Pointer mask) { if (mask != m_MaskGenerator) { m_MaskGenerator = mask; this->Modified(); } } void ImageStatisticsCalculator::SetSecondaryMask(mitk::MaskGenerator::Pointer mask) { if (mask != m_SecondaryMaskGenerator) { m_SecondaryMaskGenerator = mask; this->Modified(); } } void ImageStatisticsCalculator::SetNBinsForHistogramStatistics(unsigned int nBins) { if (nBins != m_nBinsForHistogramStatistics) { m_nBinsForHistogramStatistics = nBins; this->Modified(); this->m_UseBinSizeOverNBins = false; } if (m_UseBinSizeOverNBins) { this->Modified(); this->m_UseBinSizeOverNBins = false; } } unsigned int ImageStatisticsCalculator::GetNBinsForHistogramStatistics() const { return m_nBinsForHistogramStatistics; } void ImageStatisticsCalculator::SetBinSizeForHistogramStatistics(double binSize) { if (binSize != m_binSizeForHistogramStatistics) { m_binSizeForHistogramStatistics = binSize; this->Modified(); this->m_UseBinSizeOverNBins = true; } if (!m_UseBinSizeOverNBins) { this->Modified(); this->m_UseBinSizeOverNBins = true; } } double ImageStatisticsCalculator::GetBinSizeForHistogramStatistics() const { return m_binSizeForHistogramStatistics; } ImageStatisticsCalculator::StatisticsContainer::Pointer ImageStatisticsCalculator::GetStatistics(unsigned int timeStep, unsigned int label) { if (timeStep >= m_StatisticsByTimeStep.size()) { mitkThrow() << "invalid timeStep in ImageStatisticsCalculator_v2::GetStatistics"; } if (m_Image.IsNull()) { mitkThrow() << "no image"; } if (!m_Image->IsInitialized()) { mitkThrow() << "Image not initialized!"; } if (IsUpdateRequired(timeStep)) { if (m_MaskGenerator.IsNotNull()) { m_MaskGenerator->SetTimeStep(timeStep); m_InternalMask = m_MaskGenerator->GetMask(); if (m_MaskGenerator->GetReferenceImage().IsNotNull()) { m_InternalImageForStatistics = m_MaskGenerator->GetReferenceImage(); } else { m_InternalImageForStatistics = m_Image; } } else { m_InternalImageForStatistics = m_Image; } if (m_SecondaryMaskGenerator.IsNotNull()) { m_SecondaryMaskGenerator->SetTimeStep(timeStep); m_SecondaryMask = m_SecondaryMaskGenerator->GetMask(); } ImageTimeSelector::Pointer imgTimeSel = ImageTimeSelector::New(); imgTimeSel->SetInput(m_InternalImageForStatistics); imgTimeSel->SetTimeNr(timeStep); imgTimeSel->UpdateLargestPossibleRegion(); m_ImageTimeSlice = imgTimeSel->GetOutput(); // Calculate statistics with/without mask if (m_MaskGenerator.IsNull() && m_SecondaryMaskGenerator.IsNull()) { // 1) calculate statistics unmasked: AccessByItk_1(m_ImageTimeSlice, InternalCalculateStatisticsUnmasked, timeStep) } else { // 2) calculate statistics masked AccessByItk_1(m_ImageTimeSlice, InternalCalculateStatisticsMasked, timeStep) } //this->Modified(); } m_StatisticsUpdateTimePerTimeStep[timeStep] = m_StatisticsByTimeStep[timeStep][m_StatisticsByTimeStep[timeStep].size()-1]->GetMTime(); for (auto it = m_StatisticsByTimeStep[timeStep].begin(); it != m_StatisticsByTimeStep[timeStep].end(); ++it) { StatisticsContainer::Pointer statCont = *it; if (statCont->GetLabel() == label) { return statCont->Clone(); } } // these lines will ony be executed if the requested label could not be found! MITK_WARN << "Invalid label: " << label << " in time step: " << timeStep; return StatisticsContainer::New(); } template < typename TPixel, unsigned int VImageDimension > void ImageStatisticsCalculator::InternalCalculateStatisticsUnmasked( typename itk::Image< TPixel, VImageDimension >* image, unsigned int timeStep) { typedef typename itk::Image< TPixel, VImageDimension > ImageType; typedef typename itk::ExtendedStatisticsImageFilter<ImageType> ImageStatisticsFilterType; typedef typename itk::MinMaxImageFilterWithIndex<ImageType> MinMaxFilterType; StatisticsContainer::Pointer statisticsResult = StatisticsContainer::New(); typename ImageStatisticsFilterType::Pointer statisticsFilter = ImageStatisticsFilterType::New(); statisticsFilter->SetInput(image); statisticsFilter->SetCoordinateTolerance(0.001); statisticsFilter->SetDirectionTolerance(0.001); // TODO: this is single threaded. Implement our own image filter that does this multi threaded // typename itk::MinimumMaximumImageCalculator<ImageType>::Pointer imgMinMaxFilter = itk::MinimumMaximumImageCalculator<ImageType>::New(); // imgMinMaxFilter->SetImage(image); // imgMinMaxFilter->Compute(); vnl_vector<int> minIndex, maxIndex; typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New(); minMaxFilter->SetInput(image); minMaxFilter->UpdateLargestPossibleRegion(); typename ImageType::PixelType minval = minMaxFilter->GetMin(); typename ImageType::PixelType maxval = minMaxFilter->GetMax(); typename ImageType::IndexType tmpMinIndex = minMaxFilter->GetMinIndex(); typename ImageType::IndexType tmpMaxIndex = minMaxFilter->GetMaxIndex(); // typename ImageType::IndexType tmpMinIndex = imgMinMaxFilter->GetIndexOfMinimum(); // typename ImageType::IndexType tmpMaxIndex = imgMinMaxFilter->GetIndexOfMaximum(); minIndex.set_size(tmpMaxIndex.GetIndexDimension()); maxIndex.set_size(tmpMaxIndex.GetIndexDimension()); for (unsigned int i=0; i < tmpMaxIndex.GetIndexDimension(); i++) { minIndex[i] = tmpMinIndex[i]; maxIndex[i] = tmpMaxIndex[i]; } statisticsResult->SetMinIndex(minIndex); statisticsResult->SetMaxIndex(maxIndex); //convert m_binSize in m_nBins if necessary unsigned int nBinsForHistogram; if (m_UseBinSizeOverNBins) { nBinsForHistogram = std::max(static_cast<double>(std::ceil(maxval - minval)) / m_binSizeForHistogramStatistics, 10.); // do not allow less than 10 bins } else { nBinsForHistogram = m_nBinsForHistogramStatistics; } statisticsFilter->SetHistogramParameters(nBinsForHistogram, minval, maxval); try { statisticsFilter->Update(); } catch (const itk::ExceptionObject& e) { mitkThrow() << "Image statistics calculation failed due to following ITK Exception: \n " << e.what(); } // no mask, therefore just one label = the whole image m_StatisticsByTimeStep[timeStep].resize(1); statisticsResult->SetLabel(1); statisticsResult->SetN(image->GetLargestPossibleRegion().GetNumberOfPixels()); statisticsResult->SetMean(statisticsFilter->GetMean()); statisticsResult->SetMin(statisticsFilter->GetMinimum()); statisticsResult->SetMax(statisticsFilter->GetMaximum()); statisticsResult->SetVariance(statisticsFilter->GetVariance()); statisticsResult->SetStd(statisticsFilter->GetSigma()); statisticsResult->SetSkewness(statisticsFilter->GetSkewness()); statisticsResult->SetKurtosis(statisticsFilter->GetKurtosis()); statisticsResult->SetRMS(std::sqrt(std::pow(statisticsFilter->GetMean(), 2.) + statisticsFilter->GetVariance())); // variance = sigma^2 statisticsResult->SetMPP(statisticsFilter->GetMPP()); statisticsResult->SetEntropy(statisticsFilter->GetEntropy()); statisticsResult->SetMedian(statisticsFilter->GetMedian()); statisticsResult->SetUniformity(statisticsFilter->GetUniformity()); statisticsResult->SetUPP(statisticsFilter->GetUPP()); statisticsResult->SetHistogram(statisticsFilter->GetHistogram()); m_StatisticsByTimeStep[timeStep][0] = statisticsResult; } template < typename TPixel, unsigned int VImageDimension > void ImageStatisticsCalculator::InternalCalculateStatisticsMasked( typename itk::Image< TPixel, VImageDimension >* image, unsigned int timeStep) { typedef itk::Image< TPixel, VImageDimension > ImageType; typedef itk::Image< MaskPixelType, VImageDimension > MaskType; typedef typename MaskType::PixelType LabelPixelType; typedef itk::ExtendedLabelStatisticsImageFilter< ImageType, MaskType > ImageStatisticsFilterType; typedef MaskUtilities< TPixel, VImageDimension > MaskUtilType; typedef typename itk::MinMaxLabelImageFilterWithIndex<ImageType, MaskType> MinMaxLabelFilterType; typedef typename ImageType::PixelType InputImgPixelType; // workaround: if m_SecondaryMaskGenerator ist not null but m_MaskGenerator is! (this is the case if we request a 'ignore zuero valued pixels' // mask in the gui but do not define a primary mask) bool swapMasks = false; if (m_SecondaryMask.IsNotNull() && m_InternalMask.IsNull()) { m_InternalMask = m_SecondaryMask; m_SecondaryMask = nullptr; swapMasks = true; } // maskImage has to have the same dimension as image typename MaskType::Pointer maskImage = MaskType::New(); try { // try to access the pixel values directly (no copying or casting). Only works if mask pixels are of pixelType unsigned short maskImage = ImageToItkImage< MaskPixelType, VImageDimension >(m_InternalMask); } catch (const itk::ExceptionObject &) { // if the pixel type of the mask is not short, then we have to make a copy of m_InternalMask (and cast the values) CastToItkImage(m_InternalMask, maskImage); } // if we have a secondary mask (say a ignoreZeroPixelMask) we need to combine the masks (corresponds to AND) if (m_SecondaryMask.IsNotNull()) { // dirty workaround for a bug when pf mask + any other mask is used in conjunction. We need a proper fix for this (Fabian Isensee is responsible and probably working on it!) if (m_InternalMask->GetDimension() == 2 && (m_SecondaryMask->GetDimension() == 3 || m_SecondaryMask->GetDimension() == 4)) { mitk::Image::Pointer old_img = m_SecondaryMaskGenerator->GetReferenceImage(); m_SecondaryMaskGenerator->SetInputImage(m_MaskGenerator->GetReferenceImage()); m_SecondaryMask = m_SecondaryMaskGenerator->GetMask(); m_SecondaryMaskGenerator->SetInputImage(old_img); } typename MaskType::Pointer secondaryMaskImage = MaskType::New(); secondaryMaskImage = ImageToItkImage< MaskPixelType, VImageDimension >(m_SecondaryMask); // secondary mask should be a ignore zero value pixel mask derived from image. it has to be cropped to the mask region (which may be planar or simply smaller) typename MaskUtilities<MaskPixelType, VImageDimension>::Pointer secondaryMaskMaskUtil = MaskUtilities<MaskPixelType, VImageDimension>::New(); secondaryMaskMaskUtil->SetImage(secondaryMaskImage.GetPointer()); secondaryMaskMaskUtil->SetMask(maskImage.GetPointer()); typename MaskType::Pointer adaptedSecondaryMaskImage = secondaryMaskMaskUtil->ExtractMaskImageRegion(); typename itk::MaskImageFilter2<MaskType, MaskType, MaskType>::Pointer maskFilter = itk::MaskImageFilter2<MaskType, MaskType, MaskType>::New(); maskFilter->SetInput1(maskImage); maskFilter->SetInput2(adaptedSecondaryMaskImage); maskFilter->SetMaskingValue(1); // all pixels of maskImage where secondaryMaskImage==1 will be kept, all the others are set to 0 maskFilter->UpdateLargestPossibleRegion(); maskImage = maskFilter->GetOutput(); } typename MaskUtilType::Pointer maskUtil = MaskUtilType::New(); maskUtil->SetImage(image); maskUtil->SetMask(maskImage.GetPointer()); // if mask is smaller than image, extract the image region where the mask is typename ImageType::Pointer adaptedImage = ImageType::New(); adaptedImage = maskUtil->ExtractMaskImageRegion(); // this also checks mask sanity // find min, max, minindex and maxindex typename MinMaxLabelFilterType::Pointer minMaxFilter = MinMaxLabelFilterType::New(); minMaxFilter->SetInput(adaptedImage); minMaxFilter->SetLabelInput(maskImage); minMaxFilter->UpdateLargestPossibleRegion(); // set histogram parameters for each label individually (min/max may be different for each label) typedef typename std::map<LabelPixelType, InputImgPixelType> MapType; typedef typename std::pair<LabelPixelType, InputImgPixelType> PairType; std::vector<LabelPixelType> relevantLabels = minMaxFilter->GetRelevantLabels(); MapType minVals; MapType maxVals; std::map<LabelPixelType, unsigned int> nBins; for (LabelPixelType label:relevantLabels) { minVals.insert(PairType(label, minMaxFilter->GetMin(label))); maxVals.insert(PairType(label, minMaxFilter->GetMax(label))); unsigned int nBinsForHistogram; if (m_UseBinSizeOverNBins) { nBinsForHistogram = std::max(static_cast<double>(std::ceil(minMaxFilter->GetMax(label) - minMaxFilter->GetMin(label))) / m_binSizeForHistogramStatistics, 10.); // do not allow less than 10 bins } else { nBinsForHistogram = m_nBinsForHistogramStatistics; } nBins.insert(typename std::pair<LabelPixelType, unsigned int>(label, nBinsForHistogram)); } typename ImageStatisticsFilterType::Pointer imageStatisticsFilter = ImageStatisticsFilterType::New(); imageStatisticsFilter->SetDirectionTolerance(0.001); imageStatisticsFilter->SetCoordinateTolerance(0.001); imageStatisticsFilter->SetInput(adaptedImage); imageStatisticsFilter->SetLabelInput(maskImage); imageStatisticsFilter->SetHistogramParametersForLabels(nBins, minVals, maxVals); imageStatisticsFilter->Update(); std::list<int> labels = imageStatisticsFilter->GetRelevantLabels(); auto it = labels.begin(); m_StatisticsByTimeStep[timeStep].resize(0); while(it != labels.end()) { StatisticsContainer::Pointer statisticsResult = StatisticsContainer::New(); // find min, max, minindex and maxindex // make sure to only look in the masked region, use a masker for this vnl_vector<int> minIndex, maxIndex; mitk::Point3D worldCoordinateMin; mitk::Point3D worldCoordinateMax; mitk::Point3D indexCoordinateMin; mitk::Point3D indexCoordinateMax; m_InternalImageForStatistics->GetGeometry()->IndexToWorld(minMaxFilter->GetMinIndex(*it), worldCoordinateMin); m_InternalImageForStatistics->GetGeometry()->IndexToWorld(minMaxFilter->GetMaxIndex(*it), worldCoordinateMax); m_Image->GetGeometry()->WorldToIndex(worldCoordinateMin, indexCoordinateMin); m_Image->GetGeometry()->WorldToIndex(worldCoordinateMax, indexCoordinateMax); minIndex.set_size(3); maxIndex.set_size(3); //for (unsigned int i=0; i < tmpMaxIndex.GetIndexDimension(); i++) for (unsigned int i=0; i < 3; i++) { minIndex[i] = indexCoordinateMin[i]; maxIndex[i] = indexCoordinateMax[i]; } statisticsResult->SetMinIndex(minIndex); statisticsResult->SetMaxIndex(maxIndex); assert(std::abs(minMaxFilter->GetMax(*it) - imageStatisticsFilter->GetMaximum(*it)) < mitk::eps); assert(std::abs(minMaxFilter->GetMin(*it) - imageStatisticsFilter->GetMinimum(*it)) < mitk::eps); statisticsResult->SetN(imageStatisticsFilter->GetSum(*it) / (double) imageStatisticsFilter->GetMean(*it)); statisticsResult->SetMean(imageStatisticsFilter->GetMean(*it)); statisticsResult->SetMin(imageStatisticsFilter->GetMinimum(*it)); statisticsResult->SetMax(imageStatisticsFilter->GetMaximum(*it)); statisticsResult->SetVariance(imageStatisticsFilter->GetVariance(*it)); statisticsResult->SetStd(imageStatisticsFilter->GetSigma(*it)); statisticsResult->SetSkewness(imageStatisticsFilter->GetSkewness(*it)); statisticsResult->SetKurtosis(imageStatisticsFilter->GetKurtosis(*it)); statisticsResult->SetRMS(std::sqrt(std::pow(imageStatisticsFilter->GetMean(*it), 2.) + imageStatisticsFilter->GetVariance(*it))); // variance = sigma^2 statisticsResult->SetMPP(imageStatisticsFilter->GetMPP(*it)); statisticsResult->SetLabel(*it); statisticsResult->SetEntropy(imageStatisticsFilter->GetEntropy(*it)); statisticsResult->SetMedian(imageStatisticsFilter->GetMedian(*it)); statisticsResult->SetUniformity(imageStatisticsFilter->GetUniformity(*it)); statisticsResult->SetUPP(imageStatisticsFilter->GetUPP(*it)); statisticsResult->SetHistogram(imageStatisticsFilter->GetHistogram(*it)); m_StatisticsByTimeStep[timeStep].push_back(statisticsResult); ++it; } // swap maskGenerators back if (swapMasks) { m_SecondaryMask = m_InternalMask; m_InternalMask = nullptr; } } bool ImageStatisticsCalculator::IsUpdateRequired(unsigned int timeStep) const { unsigned long thisClassTimeStamp = this->GetMTime(); unsigned long inputImageTimeStamp = m_Image->GetMTime(); unsigned long statisticsTimeStamp = m_StatisticsUpdateTimePerTimeStep[timeStep]; if (thisClassTimeStamp > statisticsTimeStamp) // inputs have changed { return true; } if (inputImageTimeStamp > statisticsTimeStamp) // image has changed { return true; } if (m_MaskGenerator.IsNotNull()) { unsigned long maskGeneratorTimeStamp = m_MaskGenerator->GetMTime(); if (maskGeneratorTimeStamp > statisticsTimeStamp) // there is a mask generator and it has changed { return true; } } if (m_SecondaryMaskGenerator.IsNotNull()) { unsigned long maskGeneratorTimeStamp = m_SecondaryMaskGenerator->GetMTime(); if (maskGeneratorTimeStamp > statisticsTimeStamp) // there is a secondary mask generator and it has changed { return true; } } return false; } ImageStatisticsCalculator::StatisticsContainer::StatisticsContainer(): m_N(0), m_Mean(nan("")), m_Min(nan("")), m_Max(nan("")), m_Std(nan("")), m_Variance(nan("")), m_Skewness(nan("")), m_Kurtosis(nan("")), m_RMS(nan("")), m_MPP(nan("")), m_Median(nan("")), m_Uniformity(nan("")), m_UPP(nan("")), m_Entropy(nan("")), m_Label(0) { m_minIndex.set_size(0); m_maxIndex.set_size(0); } ImageStatisticsCalculator::statisticsMapType ImageStatisticsCalculator::StatisticsContainer::GetStatisticsAsMap() { ImageStatisticsCalculator::statisticsMapType statisticsAsMap; statisticsAsMap["N"] = m_N; statisticsAsMap["Mean"] = m_Mean; statisticsAsMap["Min"] = m_Min; statisticsAsMap["Max"] = m_Max; statisticsAsMap["StandardDeviation"] = m_Std; statisticsAsMap["Variance"] = m_Variance; statisticsAsMap["Skewness"] = m_Skewness; statisticsAsMap["Kurtosis"] = m_Kurtosis; statisticsAsMap["RMS"] = m_RMS; statisticsAsMap["MPP"] = m_MPP; statisticsAsMap["Median"] = m_Median; statisticsAsMap["Uniformity"] = m_Uniformity; statisticsAsMap["UPP"] = m_UPP; statisticsAsMap["Entropy"] = m_Entropy; statisticsAsMap["Label"] = m_Label; return statisticsAsMap; } void ImageStatisticsCalculator::StatisticsContainer::Reset() { m_N = 0; m_Mean = nan(""); m_Min = nan(""); m_Max = nan(""); m_Std = nan(""); m_Variance = nan(""); m_Skewness = nan(""); m_Kurtosis = nan(""); m_RMS = nan(""); m_MPP = nan(""); m_Median = nan(""); m_Uniformity = nan(""); m_UPP = nan(""); m_Entropy = nan(""); m_Histogram = HistogramType::New(); m_minIndex.set_size(0); m_maxIndex.set_size(0); m_Label = 0; } void ImageStatisticsCalculator::StatisticsContainer::Print() { ImageStatisticsCalculator::statisticsMapType statMap = this->GetStatisticsAsMap(); // print all map key value pairs // const auto& val:statMap for (auto it = statMap.begin(); it != statMap.end(); ++it) { std::cout << it->first << ": " << it->second << std::endl; } // print the min and max index std::cout << "Min Index:" << std::endl; for (auto it = this->GetMinIndex().begin(); it != this->GetMinIndex().end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; // print the min and max index std::cout << "Max Index:" << std::endl; for (auto it = this->GetMaxIndex().begin(); it != this->GetMaxIndex().end(); ++it) { std::cout << *it << " "; } std::cout << std::endl; } std::string ImageStatisticsCalculator::StatisticsContainer::GetAsString() { std::string res = ""; ImageStatisticsCalculator::statisticsMapType statMap = this->GetStatisticsAsMap(); // print all map key value pairs // const auto& val:statMap for (auto it = statMap.begin(); it != statMap.end(); ++it) { res += std::string(it->first) + ": " + std::to_string(it->second) + "\n"; } // print the min and max index res += "Min Index:" + std::string("\n"); for (auto it = this->GetMinIndex().begin(); it != this->GetMinIndex().end(); it++) { res += std::to_string(*it) + std::string(" "); } res += "\n"; // print the min and max index res += "Max Index:" + std::string("\n"); for (auto it = this->GetMaxIndex().begin(); it != this->GetMaxIndex().end(); it++) { res += std::to_string(*it) + " "; } res += "\n"; return res; } }