text
stringlengths
5
1.04M
/* * COPYRIGHT AND LICENSE Copyright (c) 2015 Peter J. Gadomski <pete.gadomski@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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. All advertising materials mentioning features or use of this software must display the following acknowledgement: This product includes software developed by the San Diego Supercomputer Center. 4. Neither the names of the Centers nor the names of the contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 <gtest/gtest.h> #include <points2grid/InCoreInterp.hpp> namespace points2grid { TEST(Issue7, TwoPointCloud) { InCoreInterp interp(1e4, 1e4, 1, 1, 1e4, 0, 10, 0, 10, 3); interp.init(); interp.update(0, 0, 10); interp.update(10, 10, 0); interp.calculate_grid_values(); GridPoint point = interp.get_grid_point(0, 0); EXPECT_EQ(2U, point.count); EXPECT_EQ(5, point.Zmean); EXPECT_EQ(0, point.Zmin); EXPECT_EQ(10, point.Zmax); } }
// Copyright Antony Polukhin, 2013-2020. // Distributed under the Boost Software License, Version 1.0. // (See the accompanying file LICENSE_1_0.txt // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.) #include <boost/config.hpp> #ifdef BOOST_MSVC # pragma warning(disable: 4512) // generic_stringize.cpp(37) : warning C4512: 'stringize_functor' : assignment operator could not be generated #endif //[lexical_cast_stringize /*` In this example we'll make a `stringize` method that accepts a sequence, converts each element of the sequence into string and appends that string to the result. Example is based on the example from the [@http://www.packtpub.com/boost-cplusplus-application-development-cookbook/book Boost C++ Application Development Cookbook] by Antony Polukhin, ISBN 9781849514880. Step 1: Making a functor that converts any type to a string and remembers result: */ #include <boost/lexical_cast.hpp> struct stringize_functor { private: std::string& result; public: explicit stringize_functor(std::string& res) : result(res) {} template <class T> void operator()(const T& v) const { result += boost::lexical_cast<std::string>(v); } }; //` Step 2: Applying `stringize_functor` to each element in sequence: #include <boost/fusion/include/for_each.hpp> template <class Sequence> std::string stringize(const Sequence& seq) { std::string result; boost::fusion::for_each(seq, stringize_functor(result)); return result; } //` Step 3: Using the `stringize` with different types: #include <boost/fusion/adapted/boost_tuple.hpp> #include <boost/fusion/adapted/std_pair.hpp> int main() { boost::tuple<char, int, char, int> decim('-', 10, 'e', 5); if (stringize(decim) != "-10e5") { return 1; } std::pair<int, std::string> value_and_type(270, "Kelvin"); if (stringize(value_and_type) != "270Kelvin") { return 2; } return 0; } //] [/lexical_cast_stringize]
//#include "stdafx.h" #include "Batisseur.h" using namespace std; int Batisseur::deplacement(int plateau[5][5][3], int couleur) { int x, y,i,j; std::string buffer; bool bouge = false; x = posXY[0]; y = posXY[1]; i = posXY[0]; j = posXY[1]; while (bouge == false) { cin>>buffer; if ((buffer == "6") && (y<4) && (plateau[i][j++][0]-nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[1] =++ y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } j = posXY[1]; if ((buffer == "4") && (y>0) && ((plateau[i][--j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[1] = --y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } j = posXY[1]; if ((buffer == "8") && (x>0) && ((plateau[--i][j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] = --x; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; if ((buffer == "2") && (x<4) && ((plateau[++i][j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] = ++x; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; if ((buffer == "1") && (y>0) && (x<4) && ((plateau[++i][--j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] = ++ x; posXY[1] = -- y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; j = posXY[1]; if ((buffer == "3") && (y<4) && (x<4) && ((plateau[++i][++j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] = ++x; posXY[1] = ++y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; j = posXY[1]; if ((buffer == "7") && (y>0) && (x>0) && ((plateau[--i][--j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] =-- x; posXY[1] =-- y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; j = posXY[1]; if ((buffer == "9") && (y<4) && (x>0) && ((plateau[--i][++j][0]) - nvcase<2) && (plateau[i][j][1] == 0)) { plateau[x][y][1] = 0; plateau[x][y][2] = 0; posXY[0] = --x; posXY[1] = ++y; nvcase = plateau[x][y][0]; plateau[x][y][1] = 1; plateau[x][y][2] = couleur; bouge = true; } i = posXY[0]; j = posXY[1]; if ((buffer == "5") ) { return 5; } if (nvcase == 3) { return 2; } if (buffer == "3€") { return 2; } } return 1; } int Batisseur::construire(int plateau[5][5][3]) { int buffer, x, y,i,j; bool construit = false; x=posXY[0]; y=posXY[1]; cout << "construis" << endl; while (construit == false) { cin >> buffer; i = posXY[0]; j = posXY[1]; if ((buffer == 6) && (y < 4) && ((plateau[i][++j][0]) < 4) && (plateau[i][j][1] == 0)){ plateau[x][++y][0] ++; construit = true; } j = posXY[1]; if ((buffer == 4) && (y>0) && ((plateau[i][--j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[x][--y][0] ++; construit = true; } j = posXY[1]; if ((buffer == 8) && (x>0) && ((plateau[--i][j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[--x][y][0] ++; construit = true; } i = posXY[0]; if ((buffer == 2) && (x<4) && ((plateau[++i][j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[++x][y][0] ++; construit = true; } i = posXY[0]; if ((buffer == 1) && (y>0) && (x<4) && ((plateau[++i][--j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[++x][--y][0] ++; construit = true; } i = posXY[0]; j = posXY[1]; if ((buffer == 3) && (y<4) && (x<4) && ((plateau[++i][++j][0])< 4) && (plateau[i][j][1] == 0)) { plateau[++x][++y][0] ++; construit = true; } i = posXY[0]; j = posXY[1]; if ((buffer == 7) && (y>0) && (x>0) && ((plateau[--i][--j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[--x][--y][0] ++; construit = true; } i = posXY[0]; j = posXY[1]; if ((buffer == 9) && (y<4) && (x>0) && ((plateau[--i][++j][0]) < 4) && (plateau[i][j][1] == 0)) { plateau[--x][++y][0] ++; construit = true; } } return 0; } void Batisseur::placementstart(int plateau[5][5][3],int couleur) { int x,y; bool good=false; while (good == false) { cout << "ou voulez vous placer votre batisseur ?" << endl; cout << "ligne" << endl; cin >> x; cout << "colonne" << endl; cin >> y; if ((plateau[--x][--y][1] == 0) && (++x>0 && x<6) && (++y>0 && y<6)) { x--; y--; plateau[x][y][1] = 1; posXY[0] = x; posXY[1] = y; plateau[x][y][2] = couleur; good = true; } else { cout << "placement incorecte" << endl; } } } Batisseur::Batisseur() { nvcase = 0; posXY[0]=-66; posXY[1]=-66; } Batisseur::~Batisseur(){}
/** @file UniformTraits.hpp Copyright 2016 Computational Topology Group, University of Kaiserslautern 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. Author(s): C.Garth, T.Biedert */ #ifndef _UNIFORMTRAITS_HPP_ #define _UNIFORMTRAITS_HPP_ #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <vector> namespace ugl { // ------------------------------------------------------------------------- /** * Traits for getting the size and a data pointer of different possible input * data to UniformSet. */ template<typename T> struct uniform_traits { }; // --- basic types --------------------------------------------------------- template<typename T> struct basic_uniform_traits { static const GLvoid* data( const T& t ) { return &t; } static GLsizei size( const T& /*t*/ ) { return 1; } }; template<> struct uniform_traits<int> : public basic_uniform_traits<int> { static GLenum type() { return GL_INT; } }; template<> struct uniform_traits<unsigned int> : public basic_uniform_traits<unsigned int> { static GLenum type() { return GL_UNSIGNED_INT; } }; template<> struct uniform_traits<float> : public basic_uniform_traits<float> { static GLenum type() { return GL_FLOAT; } }; template<> struct uniform_traits<double> : public basic_uniform_traits<double> { static GLenum type() { return GL_DOUBLE; } }; template<> struct uniform_traits<bool> : public basic_uniform_traits<bool> { static GLenum type() { return GL_BOOL; } }; // --- glm types ----------------------------------------------------------- template<typename T> struct glm_uniform_traits_base { static const GLvoid* data( const T& m ) { return glm::value_ptr( m ); } static GLsizei size( const T& /*t*/ ) { return 1; } }; template<> struct uniform_traits<glm::vec2> : glm_uniform_traits_base<glm::vec2> { static GLenum type() { return GL_FLOAT_VEC2; } }; template<> struct uniform_traits<glm::vec3> : glm_uniform_traits_base<glm::vec3> { static GLenum type() { return GL_FLOAT_VEC3; } }; template<> struct uniform_traits<glm::vec4> : glm_uniform_traits_base<glm::vec4> { static GLenum type() { return GL_FLOAT_VEC4; } }; template<> struct uniform_traits<glm::ivec2> : glm_uniform_traits_base<glm::ivec2> { static GLenum type() { return GL_INT_VEC2; } }; template<> struct uniform_traits<glm::ivec3> : glm_uniform_traits_base<glm::ivec3> { static GLenum type() { return GL_INT_VEC3; } }; template<> struct uniform_traits<glm::ivec4> : glm_uniform_traits_base<glm::ivec4> { static GLenum type() { return GL_INT_VEC4; } }; template<> struct uniform_traits<glm::uvec2> : glm_uniform_traits_base<glm::uvec2> { static GLenum type() { return GL_INT_VEC2; } }; template<> struct uniform_traits<glm::uvec3> : glm_uniform_traits_base<glm::uvec3> { static GLenum type() { return GL_INT_VEC3; } }; template<> struct uniform_traits<glm::uvec4> : glm_uniform_traits_base<glm::uvec4> { static GLenum type() { return GL_INT_VEC4; } }; template<> struct uniform_traits<glm::mat3> : glm_uniform_traits_base<glm::mat3> { static GLenum type() { return GL_FLOAT_MAT3; } }; template<> struct uniform_traits<glm::mat4> : glm_uniform_traits_base<glm::mat4> { static GLenum type() { return GL_FLOAT_MAT4; } }; // --- STL vector ---------------------------------------------------------- template<typename U> struct uniform_traits< std::vector<U> > { static const GLvoid* data( const std::vector<U>& vector ) { return vector.data(); } static GLsizei size( const std::vector<U>& vector ) { GLsizei out = 0; for( const U& element : vector ) out += uniform_traits<U>::size( element ); return out; } static GLenum type() { return uniform_traits<U>::type(); } }; } // namespace ugl #endif // _UNIFORMTRAITS_HPP_
// 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. // #ifndef SIM_SLAB_LANDING_DEFAULT_HXX #define SIM_SLAB_LANDING_DEFAULT_HXX #ifndef XSD_USE_CHAR #define XSD_USE_CHAR #endif #ifndef XSD_CXX_TREE_USE_CHAR #define XSD_CXX_TREE_USE_CHAR #endif // Begin prologue. // // // End prologue. #include <xsd/cxx/config.hxx> #if (XSD_INT_VERSION != 4000000L) #error XSD runtime version mismatch #endif #include <xsd/cxx/pre.hxx> #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/types.hxx> #include <xsd/cxx/xml/error-handler.hxx> #include <xsd/cxx/xml/dom/auto-ptr.hxx> #include <xsd/cxx/tree/parsing.hxx> #include <xsd/cxx/tree/parsing/byte.hxx> #include <xsd/cxx/tree/parsing/unsigned-byte.hxx> #include <xsd/cxx/tree/parsing/short.hxx> #include <xsd/cxx/tree/parsing/unsigned-short.hxx> #include <xsd/cxx/tree/parsing/int.hxx> #include <xsd/cxx/tree/parsing/unsigned-int.hxx> #include <xsd/cxx/tree/parsing/long.hxx> #include <xsd/cxx/tree/parsing/unsigned-long.hxx> #include <xsd/cxx/tree/parsing/boolean.hxx> #include <xsd/cxx/tree/parsing/float.hxx> #include <xsd/cxx/tree/parsing/double.hxx> #include <xsd/cxx/tree/parsing/decimal.hxx> namespace xml_schema { // anyType and anySimpleType. // typedef ::xsd::cxx::tree::type type; typedef ::xsd::cxx::tree::simple_type< char, type > simple_type; typedef ::xsd::cxx::tree::type container; // 8-bit // typedef signed char byte; typedef unsigned char unsigned_byte; // 16-bit // typedef short short_; typedef unsigned short unsigned_short; // 32-bit // typedef int int_; typedef unsigned int unsigned_int; // 64-bit // typedef long long long_; typedef unsigned long long unsigned_long; // Supposed to be arbitrary-length integral types. // typedef long long integer; typedef long long non_positive_integer; typedef unsigned long long non_negative_integer; typedef unsigned long long positive_integer; typedef long long negative_integer; // Boolean. // typedef bool boolean; // Floating-point types. // typedef float float_; typedef double double_; typedef double decimal; // String types. // typedef ::xsd::cxx::tree::string< char, simple_type > string; typedef ::xsd::cxx::tree::normalized_string< char, string > normalized_string; typedef ::xsd::cxx::tree::token< char, normalized_string > token; typedef ::xsd::cxx::tree::name< char, token > name; typedef ::xsd::cxx::tree::nmtoken< char, token > nmtoken; typedef ::xsd::cxx::tree::nmtokens< char, simple_type, nmtoken > nmtokens; typedef ::xsd::cxx::tree::ncname< char, name > ncname; typedef ::xsd::cxx::tree::language< char, token > language; // ID/IDREF. // typedef ::xsd::cxx::tree::id< char, ncname > id; typedef ::xsd::cxx::tree::idref< char, ncname, type > idref; typedef ::xsd::cxx::tree::idrefs< char, simple_type, idref > idrefs; // URI. // typedef ::xsd::cxx::tree::uri< char, simple_type > uri; // Qualified name. // typedef ::xsd::cxx::tree::qname< char, simple_type, uri, ncname > qname; // Binary. // typedef ::xsd::cxx::tree::buffer< char > buffer; typedef ::xsd::cxx::tree::base64_binary< char, simple_type > base64_binary; typedef ::xsd::cxx::tree::hex_binary< char, simple_type > hex_binary; // Date/time. // typedef ::xsd::cxx::tree::time_zone time_zone; typedef ::xsd::cxx::tree::date< char, simple_type > date; typedef ::xsd::cxx::tree::date_time< char, simple_type > date_time; typedef ::xsd::cxx::tree::duration< char, simple_type > duration; typedef ::xsd::cxx::tree::gday< char, simple_type > gday; typedef ::xsd::cxx::tree::gmonth< char, simple_type > gmonth; typedef ::xsd::cxx::tree::gmonth_day< char, simple_type > gmonth_day; typedef ::xsd::cxx::tree::gyear< char, simple_type > gyear; typedef ::xsd::cxx::tree::gyear_month< char, simple_type > gyear_month; typedef ::xsd::cxx::tree::time< char, simple_type > time; // Entity. // typedef ::xsd::cxx::tree::entity< char, ncname > entity; typedef ::xsd::cxx::tree::entities< char, simple_type, entity > entities; typedef ::xsd::cxx::tree::content_order content_order; // Flags and properties. // typedef ::xsd::cxx::tree::flags flags; typedef ::xsd::cxx::tree::properties< char > properties; // Parsing/serialization diagnostics. // typedef ::xsd::cxx::tree::severity severity; typedef ::xsd::cxx::tree::error< char > error; typedef ::xsd::cxx::tree::diagnostics< char > diagnostics; // Exceptions. // typedef ::xsd::cxx::tree::exception< char > exception; typedef ::xsd::cxx::tree::bounds< char > bounds; typedef ::xsd::cxx::tree::duplicate_id< char > duplicate_id; typedef ::xsd::cxx::tree::parsing< char > parsing; typedef ::xsd::cxx::tree::expected_element< char > expected_element; typedef ::xsd::cxx::tree::unexpected_element< char > unexpected_element; typedef ::xsd::cxx::tree::expected_attribute< char > expected_attribute; typedef ::xsd::cxx::tree::unexpected_enumerator< char > unexpected_enumerator; typedef ::xsd::cxx::tree::expected_text_content< char > expected_text_content; typedef ::xsd::cxx::tree::no_prefix_mapping< char > no_prefix_mapping; typedef ::xsd::cxx::tree::no_type_info< char > no_type_info; typedef ::xsd::cxx::tree::not_derived< char > not_derived; // Error handler callback interface. // typedef ::xsd::cxx::xml::error_handler< char > error_handler; // DOM interaction. // namespace dom { // Automatic pointer for DOMDocument. // using ::xsd::cxx::xml::dom::auto_ptr; #ifndef XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA #define XSD_CXX_TREE_TREE_NODE_KEY__XML_SCHEMA // DOM user data key for back pointers to tree nodes. // const XMLCh* const tree_node_key = ::xsd::cxx::tree::user_data_keys::node; #endif } } // Forward declarations. // namespace schema { namespace simxml { namespace BuildingModel { class SimSlab_Landing_Default; } } } #include <memory> // ::std::auto_ptr #include <limits> // std::numeric_limits #include <algorithm> // std::binary_search #include <xsd/cxx/xml/char-utf8.hxx> #include <xsd/cxx/tree/exceptions.hxx> #include <xsd/cxx/tree/elements.hxx> #include <xsd/cxx/tree/containers.hxx> #include <xsd/cxx/tree/list.hxx> #include <xsd/cxx/xml/dom/parsing-header.hxx> #include "simslab_landing.hxx" namespace schema { namespace simxml { namespace BuildingModel { class SimSlab_Landing_Default: public ::schema::simxml::BuildingModel::SimSlab_Landing { public: // Constructors. // SimSlab_Landing_Default (); SimSlab_Landing_Default (const RefId_type&); SimSlab_Landing_Default (const ::xercesc::DOMElement& e, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); SimSlab_Landing_Default (const SimSlab_Landing_Default& x, ::xml_schema::flags f = 0, ::xml_schema::container* c = 0); virtual SimSlab_Landing_Default* _clone (::xml_schema::flags f = 0, ::xml_schema::container* c = 0) const; virtual ~SimSlab_Landing_Default (); }; } } } #include <iosfwd> #include <xercesc/sax/InputSource.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMErrorHandler.hpp> namespace schema { namespace simxml { namespace BuildingModel { } } } #include <xsd/cxx/post.hxx> // Begin epilogue. // // // End epilogue. #endif // SIM_SLAB_LANDING_DEFAULT_HXX
// 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 "ash/display/display_controller.h" #include "ash/display/display_manager.h" #include "ash/screen_ash.h" #include "ash/shell.h" #include "ash/shell_window_ids.h" #include "ash/system/tray/system_tray.h" #include "ash/test/ash_test_base.h" #include "ash/wm/coordinate_conversion.h" #include "ash/wm/property_util.h" #include "ash/wm/window_cycle_controller.h" #include "ash/wm/window_properties.h" #include "ash/wm/window_util.h" #include "base/strings/string_util.h" #include "ui/aura/client/activation_client.h" #include "ui/aura/client/capture_client.h" #include "ui/aura/client/focus_client.h" #include "ui/aura/root_window.h" #include "ui/aura/test/event_generator.h" #include "ui/aura/test/test_windows.h" #include "ui/aura/test/window_test_api.h" #include "ui/aura/window.h" #include "ui/base/cursor/cursor.h" #include "ui/base/events/event_handler.h" #include "ui/gfx/display.h" #include "ui/gfx/screen.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_delegate.h" namespace ash { namespace { void SetSecondaryDisplayLayout(DisplayLayout::Position position) { DisplayController* display_controller = Shell::GetInstance()->display_controller(); DisplayLayout layout = display_controller->GetCurrentDisplayLayout(); layout.position = position; display_controller->SetLayoutForCurrentDisplays(layout); } class ModalWidgetDelegate : public views::WidgetDelegateView { public: ModalWidgetDelegate() {} virtual ~ModalWidgetDelegate() {} // Overridden from views::WidgetDelegate: virtual views::View* GetContentsView() OVERRIDE { return this; } virtual ui::ModalType GetModalType() const OVERRIDE { return ui::MODAL_TYPE_SYSTEM; } private: DISALLOW_COPY_AND_ASSIGN(ModalWidgetDelegate); }; internal::DisplayManager* GetDisplayManager() { return Shell::GetInstance()->display_manager(); } // An event handler which moves the target window to the secondary root window // at pre-handle phase of a mouse release event. class MoveWindowByClickEventHandler : public ui::EventHandler { public: explicit MoveWindowByClickEventHandler(aura::Window* target) : target_(target) {} virtual ~MoveWindowByClickEventHandler() {} private: // ui::EventHandler overrides: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if (event->type() == ui::ET_MOUSE_RELEASED) { Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); DCHECK_LT(1u, root_windows.size()); root_windows[1]->AddChild(target_); } } aura::Window* target_; DISALLOW_COPY_AND_ASSIGN(MoveWindowByClickEventHandler); }; // An event handler which records the event's locations. class EventLocationRecordingEventHandler : public ui::EventHandler { public: explicit EventLocationRecordingEventHandler() { reset(); } virtual ~EventLocationRecordingEventHandler() {} std::string GetLocationsAndReset() { std::string result = location_.ToString() + " " + root_location_.ToString(); reset(); return result; } private: // ui::EventHandler overrides: virtual void OnMouseEvent(ui::MouseEvent* event) OVERRIDE { if (event->type() == ui::ET_MOUSE_MOVED || event->type() == ui::ET_MOUSE_DRAGGED) { location_ = event->location(); root_location_ = event->root_location(); } } void reset() { location_.SetPoint(-999, -999); root_location_.SetPoint(-999, -999); } gfx::Point root_location_; gfx::Point location_; DISALLOW_COPY_AND_ASSIGN(EventLocationRecordingEventHandler); }; } // namespace class ExtendedDesktopTest : public test::AshTestBase { public: views::Widget* CreateTestWidget(const gfx::Rect& bounds) { return CreateTestWidgetWithParentAndContext( NULL, CurrentContext(), bounds, false); } views::Widget* CreateTestWidgetWithParent(views::Widget* parent, const gfx::Rect& bounds, bool child) { CHECK(parent); return CreateTestWidgetWithParentAndContext(parent, NULL, bounds, child); } views::Widget* CreateTestWidgetWithParentAndContext(views::Widget* parent, gfx::NativeView context, const gfx::Rect& bounds, bool child) { views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW); if (parent) params.parent = parent->GetNativeView(); params.context = context; params.bounds = bounds; params.child = child; views::Widget* widget = new views::Widget; widget->Init(params); widget->Show(); return widget; } }; // Test conditions that root windows in extended desktop mode // must satisfy. TEST_F(ExtendedDesktopTest, Basic) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); // All root windows must have the root window controller. ASSERT_EQ(2U, root_windows.size()); for (Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { EXPECT_TRUE(GetRootWindowController(*iter) != NULL); } // Make sure root windows share the same controllers. EXPECT_EQ(aura::client::GetFocusClient(root_windows[0]), aura::client::GetFocusClient(root_windows[1])); EXPECT_EQ(aura::client::GetActivationClient(root_windows[0]), aura::client::GetActivationClient(root_windows[1])); EXPECT_EQ(aura::client::GetCaptureClient(root_windows[0]), aura::client::GetCaptureClient(root_windows[1])); } TEST_F(ExtendedDesktopTest, Activation) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); views::Widget* widget_on_1st = CreateTestWidget(gfx::Rect(10, 10, 100, 100)); views::Widget* widget_on_2nd = CreateTestWidget(gfx::Rect(1200, 10, 100, 100)); EXPECT_EQ(root_windows[0], widget_on_1st->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], widget_on_2nd->GetNativeView()->GetRootWindow()); EXPECT_EQ(widget_on_2nd->GetNativeView(), aura::client::GetFocusClient(root_windows[0])->GetFocusedWindow()); EXPECT_TRUE(wm::IsActiveWindow(widget_on_2nd->GetNativeView())); aura::test::EventGenerator& event_generator(GetEventGenerator()); // Clicking a window changes the active window and active root window. event_generator.MoveMouseToCenterOf(widget_on_1st->GetNativeView()); event_generator.ClickLeftButton(); EXPECT_EQ(widget_on_1st->GetNativeView(), aura::client::GetFocusClient(root_windows[0])->GetFocusedWindow()); EXPECT_TRUE(wm::IsActiveWindow(widget_on_1st->GetNativeView())); event_generator.MoveMouseToCenterOf(widget_on_2nd->GetNativeView()); event_generator.ClickLeftButton(); EXPECT_EQ(widget_on_2nd->GetNativeView(), aura::client::GetFocusClient(root_windows[0])->GetFocusedWindow()); EXPECT_TRUE(wm::IsActiveWindow(widget_on_2nd->GetNativeView())); } TEST_F(ExtendedDesktopTest, SystemModal) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); views::Widget* widget_on_1st = CreateTestWidget(gfx::Rect(10, 10, 100, 100)); EXPECT_TRUE(wm::IsActiveWindow(widget_on_1st->GetNativeView())); EXPECT_EQ(root_windows[0], widget_on_1st->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[0], Shell::GetActiveRootWindow()); // Open system modal. Make sure it's on 2nd root window and active. views::Widget* modal_widget = views::Widget::CreateWindowWithContextAndBounds( new ModalWidgetDelegate(), CurrentContext(), gfx::Rect(1200, 100, 100, 100)); modal_widget->Show(); EXPECT_TRUE(wm::IsActiveWindow(modal_widget->GetNativeView())); EXPECT_EQ(root_windows[1], modal_widget->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], Shell::GetActiveRootWindow()); aura::test::EventGenerator& event_generator(GetEventGenerator()); // Clicking a widget on widget_on_1st display should not change activation. event_generator.MoveMouseToCenterOf(widget_on_1st->GetNativeView()); event_generator.ClickLeftButton(); EXPECT_TRUE(wm::IsActiveWindow(modal_widget->GetNativeView())); EXPECT_EQ(root_windows[1], Shell::GetActiveRootWindow()); // Close system modal and so clicking a widget should work now. modal_widget->Close(); event_generator.MoveMouseToCenterOf(widget_on_1st->GetNativeView()); event_generator.ClickLeftButton(); EXPECT_TRUE(wm::IsActiveWindow(widget_on_1st->GetNativeView())); EXPECT_EQ(root_windows[0], Shell::GetActiveRootWindow()); } TEST_F(ExtendedDesktopTest, TestCursor) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); EXPECT_EQ(ui::kCursorPointer, root_windows[0]->last_cursor().native_type()); EXPECT_EQ(ui::kCursorPointer, root_windows[1]->last_cursor().native_type()); Shell::GetInstance()->cursor_manager()->SetCursor(ui::kCursorCopy); EXPECT_EQ(ui::kCursorCopy, root_windows[0]->last_cursor().native_type()); EXPECT_EQ(ui::kCursorCopy, root_windows[1]->last_cursor().native_type()); } TEST_F(ExtendedDesktopTest, TestCursorLocation) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); aura::test::WindowTestApi root_window0_test_api(root_windows[0]); aura::test::WindowTestApi root_window1_test_api(root_windows[1]); root_windows[0]->MoveCursorTo(gfx::Point(10, 10)); EXPECT_EQ("10,10", Shell::GetScreen()->GetCursorScreenPoint().ToString()); EXPECT_TRUE(root_window0_test_api.ContainsMouse()); EXPECT_FALSE(root_window1_test_api.ContainsMouse()); root_windows[1]->MoveCursorTo(gfx::Point(10, 20)); EXPECT_EQ("1010,20", Shell::GetScreen()->GetCursorScreenPoint().ToString()); EXPECT_FALSE(root_window0_test_api.ContainsMouse()); EXPECT_TRUE(root_window1_test_api.ContainsMouse()); root_windows[0]->MoveCursorTo(gfx::Point(20, 10)); EXPECT_EQ("20,10", Shell::GetScreen()->GetCursorScreenPoint().ToString()); EXPECT_TRUE(root_window0_test_api.ContainsMouse()); EXPECT_FALSE(root_window1_test_api.ContainsMouse()); } TEST_F(ExtendedDesktopTest, CycleWindows) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("700x500,500x500"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); WindowCycleController* controller = Shell::GetInstance()->window_cycle_controller(); views::Widget* d1_w1 = CreateTestWidget(gfx::Rect(10, 10, 100, 100)); EXPECT_EQ(root_windows[0], d1_w1->GetNativeView()->GetRootWindow()); views::Widget* d2_w1 = CreateTestWidget(gfx::Rect(800, 10, 100, 100)); EXPECT_EQ(root_windows[1], d2_w1->GetNativeView()->GetRootWindow()); EXPECT_TRUE(wm::IsActiveWindow(d2_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::FORWARD, false); EXPECT_TRUE(wm::IsActiveWindow(d1_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::FORWARD, false); EXPECT_TRUE(wm::IsActiveWindow(d2_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::BACKWARD, false); EXPECT_TRUE(wm::IsActiveWindow(d1_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::BACKWARD, false); EXPECT_TRUE(wm::IsActiveWindow(d2_w1->GetNativeView())); // Cycle through all windows across root windows. views::Widget* d1_w2 = CreateTestWidget(gfx::Rect(10, 200, 100, 100)); EXPECT_EQ(root_windows[0], d1_w2->GetNativeView()->GetRootWindow()); views::Widget* d2_w2 = CreateTestWidget(gfx::Rect(800, 200, 100, 100)); EXPECT_EQ(root_windows[1], d2_w2->GetNativeView()->GetRootWindow()); controller->HandleCycleWindow(WindowCycleController::FORWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d1_w2->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::FORWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d2_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::FORWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d1_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::FORWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d2_w2->GetNativeView())); // Backwards controller->HandleCycleWindow(WindowCycleController::BACKWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d1_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::BACKWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d2_w1->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::BACKWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d1_w2->GetNativeView())); controller->HandleCycleWindow(WindowCycleController::BACKWARD, true); EXPECT_TRUE(wm::IsActiveWindow(d2_w2->GetNativeView())); } TEST_F(ExtendedDesktopTest, GetRootWindowAt) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("700x500,500x500"); SetSecondaryDisplayLayout(DisplayLayout::LEFT); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); EXPECT_EQ(root_windows[1], wm::GetRootWindowAt(gfx::Point(-400, 100))); EXPECT_EQ(root_windows[1], wm::GetRootWindowAt(gfx::Point(-1, 100))); EXPECT_EQ(root_windows[0], wm::GetRootWindowAt(gfx::Point(0, 300))); EXPECT_EQ(root_windows[0], wm::GetRootWindowAt(gfx::Point(700,300))); // Zero origin. EXPECT_EQ(root_windows[0], wm::GetRootWindowAt(gfx::Point(0, 0))); // Out of range point should return the primary root window EXPECT_EQ(root_windows[0], wm::GetRootWindowAt(gfx::Point(-600, 0))); EXPECT_EQ(root_windows[0], wm::GetRootWindowAt(gfx::Point(701, 100))); } TEST_F(ExtendedDesktopTest, GetRootWindowMatching) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("700x500,500x500"); SetSecondaryDisplayLayout(DisplayLayout::LEFT); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); // Containing rect. EXPECT_EQ(root_windows[1], wm::GetRootWindowMatching(gfx::Rect(-300, 10, 50, 50))); EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(100, 10, 50, 50))); // Intersecting rect. EXPECT_EQ(root_windows[1], wm::GetRootWindowMatching(gfx::Rect(-200, 0, 300, 300))); EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(-100, 0, 300, 300))); // Zero origin. EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(0, 0, 0, 0))); EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(0, 0, 1, 1))); // Empty rect. EXPECT_EQ(root_windows[1], wm::GetRootWindowMatching(gfx::Rect(-400, 100, 0, 0))); EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(100, 100, 0, 0))); // Out of range rect should return the primary root window. EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(-600, -300, 50, 50))); EXPECT_EQ(root_windows[0], wm::GetRootWindowMatching(gfx::Rect(0, 1000, 50, 50))); } TEST_F(ExtendedDesktopTest, Capture) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); aura::test::EventCountDelegate r1_d1; aura::test::EventCountDelegate r1_d2; aura::test::EventCountDelegate r2_d1; scoped_ptr<aura::Window> r1_w1(aura::test::CreateTestWindowWithDelegate( &r1_d1, 0, gfx::Rect(10, 10, 100, 100), root_windows[0])); scoped_ptr<aura::Window> r1_w2(aura::test::CreateTestWindowWithDelegate( &r1_d2, 0, gfx::Rect(10, 100, 100, 100), root_windows[0])); scoped_ptr<aura::Window> r2_w1(aura::test::CreateTestWindowWithDelegate( &r2_d1, 0, gfx::Rect(10, 10, 100, 100), root_windows[1])); r1_w1->SetCapture(); EXPECT_EQ(r1_w1.get(), aura::client::GetCaptureWindow(r2_w1->GetRootWindow())); aura::test::EventGenerator generator2(root_windows[1]); generator2.MoveMouseToCenterOf(r2_w1.get()); generator2.ClickLeftButton(); EXPECT_EQ("0 0 0", r2_d1.GetMouseMotionCountsAndReset()); EXPECT_EQ("0 0", r2_d1.GetMouseButtonCountsAndReset()); // The mouse is outside. On chromeos, the mouse is warped to the // dest root window, but it's not implemented on Win yet, so // no mouse move event on Win. EXPECT_EQ("1 1 0", r1_d1.GetMouseMotionCountsAndReset()); EXPECT_EQ("1 1", r1_d1.GetMouseButtonCountsAndReset()); // Emulate passive grab. (15,15) on 1st display is (-985,15) on 2nd // display. generator2.MoveMouseTo(-985, 15); EXPECT_EQ("0 1 0", r1_d1.GetMouseMotionCountsAndReset()); r1_w2->SetCapture(); EXPECT_EQ(r1_w2.get(), aura::client::GetCaptureWindow(r2_w1->GetRootWindow())); generator2.MoveMouseBy(10, 10); generator2.ClickLeftButton(); EXPECT_EQ("0 0 0", r2_d1.GetMouseMotionCountsAndReset()); EXPECT_EQ("0 0", r2_d1.GetMouseButtonCountsAndReset()); // mouse is already entered. EXPECT_EQ("0 1 0", r1_d2.GetMouseMotionCountsAndReset()); EXPECT_EQ("1 1", r1_d2.GetMouseButtonCountsAndReset()); r1_w2->ReleaseCapture(); EXPECT_EQ(NULL, aura::client::GetCaptureWindow(r2_w1->GetRootWindow())); generator2.MoveMouseTo(15, 15); generator2.ClickLeftButton(); EXPECT_EQ("1 1 0", r2_d1.GetMouseMotionCountsAndReset()); EXPECT_EQ("1 1", r2_d1.GetMouseButtonCountsAndReset()); // Make sure the mouse_moved_handler_ is properly reset. EXPECT_EQ("0 0 0", r1_d2.GetMouseMotionCountsAndReset()); EXPECT_EQ("0 0", r1_d2.GetMouseButtonCountsAndReset()); } TEST_F(ExtendedDesktopTest, MoveWindow) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); views::Widget* d1 = CreateTestWidget(gfx::Rect(10, 10, 100, 100)); EXPECT_EQ(root_windows[0], d1->GetNativeView()->GetRootWindow()); d1->SetBounds(gfx::Rect(1010, 10, 100, 100)); EXPECT_EQ("1010,10 100x100", d1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(root_windows[1], d1->GetNativeView()->GetRootWindow()); d1->SetBounds(gfx::Rect(10, 10, 100, 100)); EXPECT_EQ("10,10 100x100", d1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(root_windows[0], d1->GetNativeView()->GetRootWindow()); // Make sure the bounds which doesn't fit to the root window // works correctly. d1->SetBounds(gfx::Rect(1560, 30, 100, 100)); EXPECT_EQ(root_windows[1], d1->GetNativeView()->GetRootWindow()); EXPECT_EQ("1560,30 100x100", d1->GetWindowBoundsInScreen().ToString()); // Setting outside of root windows will be moved to primary root window. // TODO(oshima): This one probably should pick the closest root window. d1->SetBounds(gfx::Rect(200, 10, 100, 100)); EXPECT_EQ(root_windows[0], d1->GetNativeView()->GetRootWindow()); } // Verifies if the mouse event arrives to the window even when the window // moves to another root in a pre-target handler. See: crbug.com/157583 TEST_F(ExtendedDesktopTest, MoveWindowByMouseClick) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); aura::test::EventCountDelegate delegate; scoped_ptr<aura::Window> window(aura::test::CreateTestWindowWithDelegate( &delegate, 0, gfx::Rect(10, 10, 100, 100), root_windows[0])); MoveWindowByClickEventHandler event_handler(window.get()); window->AddPreTargetHandler(&event_handler); aura::test::EventGenerator& event_generator(GetEventGenerator()); event_generator.MoveMouseToCenterOf(window.get()); event_generator.ClickLeftButton(); // Both mouse pressed and released arrive at the window and its delegate. EXPECT_EQ("1 1", delegate.GetMouseButtonCountsAndReset()); // Also event_handler moves the window to another root at mouse release. EXPECT_EQ(root_windows[1], window->GetRootWindow()); } TEST_F(ExtendedDesktopTest, MoveWindowToDisplay) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x1000,1000x1000"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); gfx::Display display0 = Shell::GetScreen()->GetDisplayMatching( root_windows[0]->GetBoundsInScreen()); gfx::Display display1 = Shell::GetScreen()->GetDisplayMatching( root_windows[1]->GetBoundsInScreen()); EXPECT_NE(display0.id(), display1.id()); views::Widget* d1 = CreateTestWidget(gfx::Rect(10, 10, 1000, 100)); EXPECT_EQ(root_windows[0], d1->GetNativeView()->GetRootWindow()); // Move the window where the window spans both root windows. Since the second // parameter is |display1|, the window should be shown on the secondary root. d1->GetNativeWindow()->SetBoundsInScreen(gfx::Rect(500, 10, 1000, 100), display1); EXPECT_EQ("500,10 1000x100", d1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(root_windows[1], d1->GetNativeView()->GetRootWindow()); // Move to the primary root. d1->GetNativeWindow()->SetBoundsInScreen(gfx::Rect(500, 10, 1000, 100), display0); EXPECT_EQ("500,10 1000x100", d1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ(root_windows[0], d1->GetNativeView()->GetRootWindow()); } TEST_F(ExtendedDesktopTest, MoveWindowWithTransient) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); views::Widget* w1 = CreateTestWidget(gfx::Rect(10, 10, 100, 100)); views::Widget* w1_t1 = CreateTestWidgetWithParent( w1, gfx::Rect(50, 50, 50, 50), false /* transient */); // Transient child of the transient child. views::Widget* w1_t11 = CreateTestWidgetWithParent( w1_t1, gfx::Rect(1200, 70, 30, 30), false /* transient */); views::Widget* w11 = CreateTestWidgetWithParent( w1, gfx::Rect(10, 10, 40, 40), true /* child */); views::Widget* w11_t1 = CreateTestWidgetWithParent( w1, gfx::Rect(1300, 100, 80, 80), false /* transient */); EXPECT_EQ(root_windows[0], w1->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[0], w11->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[0], w1_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[0], w1_t11->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[0], w11_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ("50,50 50x50", w1_t1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ("1200,70 30x30", w1_t11->GetWindowBoundsInScreen().ToString()); EXPECT_EQ("20,20 40x40", w11->GetWindowBoundsInScreen().ToString()); EXPECT_EQ("1300,100 80x80", w11_t1->GetWindowBoundsInScreen().ToString()); w1->SetBounds(gfx::Rect(1100,10,100,100)); EXPECT_EQ(root_windows[1], w1_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], w1_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], w1_t11->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], w11->GetNativeView()->GetRootWindow()); EXPECT_EQ(root_windows[1], w11_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ("1110,20 40x40", w11->GetWindowBoundsInScreen().ToString()); // Transient window's screen bounds stays the same. EXPECT_EQ("50,50 50x50", w1_t1->GetWindowBoundsInScreen().ToString()); EXPECT_EQ("1200,70 30x30", w1_t11->GetWindowBoundsInScreen().ToString()); EXPECT_EQ("1300,100 80x80", w11_t1->GetWindowBoundsInScreen().ToString()); // Transient window doesn't move between root window unless // its transient parent moves. w1_t1->SetBounds(gfx::Rect(10, 50, 50, 50)); EXPECT_EQ(root_windows[1], w1_t1->GetNativeView()->GetRootWindow()); EXPECT_EQ("10,50 50x50", w1_t1->GetWindowBoundsInScreen().ToString()); } namespace internal { // Test if the Window::ConvertPointToTarget works across root windows. // TODO(oshima): Move multiple display suport and this test to aura. TEST_F(ExtendedDesktopTest, ConvertPoint) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("1000x600,600x400"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); gfx::Display& display_1 = GetDisplayManager()->FindDisplayForRootWindow(root_windows[0]); EXPECT_EQ("0,0", display_1.bounds().origin().ToString()); gfx::Display& display_2 = GetDisplayManager()->FindDisplayForRootWindow(root_windows[1]); EXPECT_EQ("1000,0", display_2.bounds().origin().ToString()); aura::Window* d1 = CreateTestWidget(gfx::Rect(10, 10, 100, 100))->GetNativeView(); aura::Window* d2 = CreateTestWidget(gfx::Rect(1020, 20, 100, 100))->GetNativeView(); EXPECT_EQ(root_windows[0], d1->GetRootWindow()); EXPECT_EQ(root_windows[1], d2->GetRootWindow()); // Convert point in the Root2's window to the Root1's window Coord. gfx::Point p(0, 0); aura::Window::ConvertPointToTarget(root_windows[1], root_windows[0], &p); EXPECT_EQ("1000,0", p.ToString()); p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(d2, d1, &p); EXPECT_EQ("1010,10", p.ToString()); // Convert point in the Root1's window to the Root2's window Coord. p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(root_windows[0], root_windows[1], &p); EXPECT_EQ("-1000,0", p.ToString()); p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(d1, d2, &p); EXPECT_EQ("-1010,-10", p.ToString()); // Move the 2nd display to the bottom and test again. SetSecondaryDisplayLayout(DisplayLayout::BOTTOM); display_2 = GetDisplayManager()->FindDisplayForRootWindow(root_windows[1]); EXPECT_EQ("0,600", display_2.bounds().origin().ToString()); // Convert point in Root2's window to Root1's window Coord. p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(root_windows[1], root_windows[0], &p); EXPECT_EQ("0,600", p.ToString()); p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(d2, d1, &p); EXPECT_EQ("10,610", p.ToString()); // Convert point in Root1's window to Root2's window Coord. p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(root_windows[0], root_windows[1], &p); EXPECT_EQ("0,-600", p.ToString()); p.SetPoint(0, 0); aura::Window::ConvertPointToTarget(d1, d2, &p); EXPECT_EQ("-10,-610", p.ToString()); } TEST_F(ExtendedDesktopTest, OpenSystemTray) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("500x600,600x400"); SystemTray* tray = ash::Shell::GetInstance()->GetPrimarySystemTray(); ASSERT_FALSE(tray->HasSystemBubble()); aura::test::EventGenerator& event_generator(GetEventGenerator()); // Opens the tray by a dummy click event and makes sure that adding/removing // displays doesn't break anything. event_generator.MoveMouseToCenterOf(tray->GetWidget()->GetNativeWindow()); event_generator.ClickLeftButton(); EXPECT_TRUE(tray->HasSystemBubble()); UpdateDisplay("500x600"); EXPECT_TRUE(tray->HasSystemBubble()); UpdateDisplay("500x600,600x400"); EXPECT_TRUE(tray->HasSystemBubble()); // Closes the tray and again makes sure that adding/removing displays doesn't // break anything. event_generator.ClickLeftButton(); RunAllPendingInMessageLoop(); EXPECT_FALSE(tray->HasSystemBubble()); UpdateDisplay("500x600"); EXPECT_FALSE(tray->HasSystemBubble()); UpdateDisplay("500x600,600x400"); EXPECT_FALSE(tray->HasSystemBubble()); } TEST_F(ExtendedDesktopTest, StayInSameRootWindow) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("100x100,200x200"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); views::Widget* w1 = CreateTestWidget(gfx::Rect(10, 10, 50, 50)); EXPECT_EQ(root_windows[0], w1->GetNativeView()->GetRootWindow()); w1->SetBounds(gfx::Rect(150, 10, 50, 50)); EXPECT_EQ(root_windows[1], w1->GetNativeView()->GetRootWindow()); // The widget stays in the same root if kStayInSameRootWindowKey is set to // true. w1->GetNativeView()->SetProperty(internal::kStayInSameRootWindowKey, true); w1->SetBounds(gfx::Rect(10, 10, 50, 50)); EXPECT_EQ(root_windows[1], w1->GetNativeView()->GetRootWindow()); // The widget should now move to the 1st root window without the property. w1->GetNativeView()->ClearProperty(internal::kStayInSameRootWindowKey); w1->SetBounds(gfx::Rect(10, 10, 50, 50)); EXPECT_EQ(root_windows[0], w1->GetNativeView()->GetRootWindow()); } TEST_F(ExtendedDesktopTest, KeyEventsOnLockScreen) { if (!SupportsMultipleDisplays()) return; UpdateDisplay("100x100,200x200"); Shell::RootWindowList root_windows = Shell::GetAllRootWindows(); // Create normal windows on both displays. views::Widget* widget1 = CreateTestWidget( Shell::GetScreen()->GetPrimaryDisplay().bounds()); widget1->Show(); EXPECT_EQ(root_windows[0], widget1->GetNativeView()->GetRootWindow()); views::Widget* widget2 = CreateTestWidget( ScreenAsh::GetSecondaryDisplay().bounds()); widget2->Show(); EXPECT_EQ(root_windows[1], widget2->GetNativeView()->GetRootWindow()); // Create a LockScreen window. views::Widget* lock_widget = CreateTestWidget( Shell::GetScreen()->GetPrimaryDisplay().bounds()); views::Textfield* textfield = new views::Textfield; lock_widget->client_view()->AddChildView(textfield); ash::Shell::GetContainer( Shell::GetPrimaryRootWindow(), ash::internal::kShellWindowId_LockScreenContainer)-> AddChild(lock_widget->GetNativeView()); lock_widget->Show(); textfield->RequestFocus(); aura::client::FocusClient* focus_client = aura::client::GetFocusClient(root_windows[0]); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); // The lock window should get events on both root windows. aura::test::EventGenerator& event_generator(GetEventGenerator()); event_generator.set_current_root_window(root_windows[0]); event_generator.PressKey(ui::VKEY_A, 0); event_generator.ReleaseKey(ui::VKEY_A, 0); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); EXPECT_EQ("a", UTF16ToASCII(textfield->text())); event_generator.set_current_root_window(root_windows[1]); event_generator.PressKey(ui::VKEY_B, 0); event_generator.ReleaseKey(ui::VKEY_B, 0); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); EXPECT_EQ("ab", UTF16ToASCII(textfield->text())); // Deleting 2nd display. The lock window still should get the events. UpdateDisplay("100x100"); event_generator.PressKey(ui::VKEY_C, 0); event_generator.ReleaseKey(ui::VKEY_C, 0); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); EXPECT_EQ("abc", UTF16ToASCII(textfield->text())); // Creating 2nd display again, and lock window still should get events // on both root windows. UpdateDisplay("100x100,200x200"); root_windows = Shell::GetAllRootWindows(); event_generator.set_current_root_window(root_windows[0]); event_generator.PressKey(ui::VKEY_D, 0); event_generator.ReleaseKey(ui::VKEY_D, 0); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); EXPECT_EQ("abcd", UTF16ToASCII(textfield->text())); event_generator.set_current_root_window(root_windows[1]); event_generator.PressKey(ui::VKEY_E, 0); event_generator.ReleaseKey(ui::VKEY_E, 0); EXPECT_EQ(lock_widget->GetNativeView(), focus_client->GetFocusedWindow()); EXPECT_EQ("abcde", UTF16ToASCII(textfield->text())); } TEST_F(ExtendedDesktopTest, PassiveGrab) { if (!SupportsMultipleDisplays()) return; EventLocationRecordingEventHandler event_handler; ash::Shell::GetInstance()->AddPreTargetHandler(&event_handler); UpdateDisplay("300x300,200x200"); views::Widget* widget = CreateTestWidget(gfx::Rect(50, 50, 200, 200)); widget->Show(); ASSERT_EQ("50,50 200x200", widget->GetWindowBoundsInScreen().ToString()); aura::test::EventGenerator& generator(GetEventGenerator()); generator.MoveMouseTo(150, 150); EXPECT_EQ("100,100 150,150", event_handler.GetLocationsAndReset()); generator.PressLeftButton(); generator.MoveMouseTo(400, 150); EXPECT_EQ("350,100 400,150", event_handler.GetLocationsAndReset()); generator.ReleaseLeftButton(); EXPECT_EQ("-999,-999 -999,-999", event_handler.GetLocationsAndReset()); generator.MoveMouseTo(400, 150); EXPECT_EQ("100,150 100,150", event_handler.GetLocationsAndReset()); ash::Shell::GetInstance()->RemovePreTargetHandler(&event_handler); } } // namespace internal } // namespace ash
/* * Copyright 2012 Open Source Robotics Foundation * * 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. * */ #ifndef _GAZEBO_HH_ #define _GAZEBO_HH_ #include <gazebo/gazebo_core.hh> #include <string> namespace gazebo { void print_version(); void add_plugin(const std::string &_filename); bool load(int _argc = 0, char **_argv = 0); bool init(); void run(); void stop(); void fini(); /// \brief Find a file in the gazebo search paths std::string find_file(const std::string &_file); } #endif
/*ckwg +29 * Copyright 2011-2013 by Kitware, 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 name of Kitware, Inc. nor the names of any 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 AUTHORS 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 <sprokit/pipeline/pipeline.h> #include <sprokit/pipeline/scheduler.h> #include <sprokit/python/util/python_exceptions.h> #include <sprokit/python/util/python_gil.h> #include <boost/python/class.hpp> #include <boost/python/module.hpp> #include <boost/python/override.hpp> #include <boost/python/pure_virtual.hpp> /** * \file scheduler.cxx * * \brief Python bindings for \link sprokit::scheduler\endlink. */ using namespace boost::python; class wrap_scheduler : public sprokit::scheduler , public wrapper<sprokit::scheduler> { public: wrap_scheduler(sprokit::pipeline_t const& pipe, sprokit::config_t const& config); ~wrap_scheduler(); void _start(); void _wait(); void _pause(); void _resume(); void _stop(); sprokit::pipeline_t _pipeline() const; override get_pure_override(char const* name) const; }; BOOST_PYTHON_MODULE(scheduler) { class_<wrap_scheduler, boost::noncopyable>("PythonScheduler" , "The base class for Python schedulers." , no_init) .def(init<sprokit::pipeline_t, sprokit::config_t>()) .def("start", &sprokit::scheduler::start , "Start the execution of the pipeline.") .def("wait", &sprokit::scheduler::wait , "Wait until the pipeline execution is complete.") .def("pause", &sprokit::scheduler::pause , "Pause execution.") .def("resume", &sprokit::scheduler::resume , "Resume execution.") .def("stop", &sprokit::scheduler::stop , "Stop the execution of the pipeline.") .def("pipeline", &wrap_scheduler::_pipeline , "The pipeline the scheduler is to run.") .def("_start", pure_virtual(&wrap_scheduler::_start) , "Implementation of starting the pipeline.") .def("_wait", pure_virtual(&wrap_scheduler::_wait) , "Implementation of waiting until execution is complete.") .def("_pause", pure_virtual(&wrap_scheduler::_pause) , "Implementation of pausing execution.") .def("_resume", pure_virtual(&wrap_scheduler::_resume) , "Implementation of resuming execution.") .def("_stop", pure_virtual(&wrap_scheduler::_stop) , "Implementation of stopping the pipeline.") ; } wrap_scheduler ::wrap_scheduler(sprokit::pipeline_t const& pipe, sprokit::config_t const& config) : sprokit::scheduler(pipe, config) { } wrap_scheduler ::~wrap_scheduler() { shutdown(); } void wrap_scheduler ::_start() { sprokit::python::python_gil const gil; (void)gil; SPROKIT_PYTHON_HANDLE_EXCEPTION(get_pure_override("_start")()) } void wrap_scheduler ::_wait() { sprokit::python::python_gil const gil; (void)gil; SPROKIT_PYTHON_HANDLE_EXCEPTION(get_pure_override("_wait")()) } void wrap_scheduler ::_pause() { sprokit::python::python_gil const gil; (void)gil; SPROKIT_PYTHON_HANDLE_EXCEPTION(get_pure_override("_pause")()) } void wrap_scheduler ::_resume() { sprokit::python::python_gil const gil; (void)gil; SPROKIT_PYTHON_HANDLE_EXCEPTION(get_pure_override("_resume")()) } void wrap_scheduler ::_stop() { sprokit::python::python_gil const gil; (void)gil; SPROKIT_PYTHON_HANDLE_EXCEPTION(get_pure_override("_stop")()) } sprokit::pipeline_t wrap_scheduler ::_pipeline() const { return pipeline(); } override wrap_scheduler ::get_pure_override(char const* method) const { override const o = get_override(method); if (!o) { std::ostringstream sstr; sstr << method << " is not implemented"; throw std::runtime_error(sstr.str().c_str()); } return o; }
#ifndef PYTHONIC_BUILTIN_STR_RSTRIP_HPP #define PYTHONIC_BUILTIN_STR_RSTRIP_HPP #include "pythonic/include/__builtin__/str/rstrip.hpp" #include "pythonic/types/str.hpp" #include "pythonic/utils/functor.hpp" namespace pythonic { namespace __builtin__ { namespace str { types::str rstrip(types::str const &self, types::str const &to_del) { return {self.begin(), self.begin() + self.find_last_not_of(to_del) + 1}; } DEFINE_FUNCTOR(pythonic::__builtin__::str, rstrip); } } } #endif
# include "rrdb.server.impl.h" # include <algorithm> # include <dsn/cpp/utils.h> # include <rocksdb/utilities/checkpoint.h> # ifdef __TITLE__ # undef __TITLE__ # endif #define __TITLE__ "rrdb.server.impl" namespace dsn { namespace apps { static std::string chkpt_get_dir_name(::dsn::replication::decree d, rocksdb::SequenceNumber seq) { char buffer[256]; sprintf(buffer, "checkpoint.%" PRId64 ".%" PRIu64 "", d, seq); return std::string(buffer); } static bool chkpt_init_from_dir(const char* name, ::dsn::replication::decree& d, rocksdb::SequenceNumber& seq) { return 2 == sscanf(name, "checkpoint.%" PRId64 ".%" PRIu64 "", &d, &seq) && std::string(name) == chkpt_get_dir_name(d, seq); } rrdb_service_impl::rrdb_service_impl(::dsn::replication::replica* replica) : rrdb_service(replica), _max_checkpoint_count(3) { _is_open = false; _last_seq = 0; _is_catchup = false; _last_durable_seq = 0; _is_checkpointing = false; // init db options _db_opts.write_buffer_size = (size_t)dsn_config_get_value_uint64("replication", "rocksdb_write_buffer_size", 134217728, "rocksdb options.write_buffer_size, default 128MB" ); _db_opts.max_write_buffer_number = (int)dsn_config_get_value_uint64("replication", "rocksdb_max_write_buffer_number", 3, "rocksdb options.max_write_buffer_number, default 3" ); _db_opts.max_background_compactions = (int)dsn_config_get_value_uint64("replication", "rocksdb_max_background_compactions", 20, "rocksdb options.max_background_compactions, default 20" ); _db_opts.num_levels = dsn_config_get_value_uint64("replication", "rocksdb_num_levels", 6, "rocksdb options.num_levels, default 6" ); _db_opts.target_file_size_base = dsn_config_get_value_uint64("replication", "rocksdb_target_file_size_base", 67108864, "rocksdb options.write_buffer_size, default 64MB" ); _db_opts.max_bytes_for_level_base = dsn_config_get_value_uint64("replication", "rocksdb_max_bytes_for_level_base", 10485760, "rocksdb options.max_bytes_for_level_base, default 10MB" ); _db_opts.max_grandparent_overlap_factor = (int)dsn_config_get_value_uint64("replication", "rocksdb_max_grandparent_overlap_factor", 10, "rocksdb options.max_grandparent_overlap_factor, default 10" ); _db_opts.level0_file_num_compaction_trigger = (int)dsn_config_get_value_uint64("replication", "rocksdb_level0_file_num_compaction_trigger", 4, "rocksdb options.level0_file_num_compaction_trigger, 4" ); _db_opts.level0_slowdown_writes_trigger = (int)dsn_config_get_value_uint64("replication", "rocksdb_level0_slowdown_writes_trigger", 8, "rocksdb options.level0_slowdown_writes_trigger, default 8" ); _db_opts.level0_stop_writes_trigger = (int)dsn_config_get_value_uint64("replication", "rocksdb_level0_stop_writes_trigger", 12, "rocksdb options.level0_stop_writes_trigger, default 12" ); // disable write ahead logging as replication handles logging instead now _wt_opts.disableWAL = true; } rrdb_service_impl::checkpoint_info rrdb_service_impl::parse_checkpoints() { std::vector<std::string> dirs; utils::filesystem::get_subdirectories(data_dir(), dirs, false); utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.clear(); for (auto& d : dirs) { checkpoint_info ci; std::string d1 = d.substr(data_dir().length() + 1); if (chkpt_init_from_dir(d1.c_str(), ci.d, ci.seq)) { _checkpoints.push_back(ci); } else if (d1.find("checkpoint") != std::string::npos) { dwarn("invalid checkpoint directory %s, remove ...", d.c_str() ); utils::filesystem::remove_path(d); } } std::sort(_checkpoints.begin(), _checkpoints.end()); return _checkpoints.size() > 0 ? *_checkpoints.rbegin() : checkpoint_info(); } void rrdb_service_impl::gc_checkpoints() { while (true) { checkpoint_info del_d; { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); if (_checkpoints.size() <= _max_checkpoint_count) break; del_d = *_checkpoints.begin(); _checkpoints.erase(_checkpoints.begin()); } auto old_cpt = chkpt_get_dir_name(del_d.d, del_d.seq); auto old_cpt_dir = utils::filesystem::path_combine(data_dir(), old_cpt); if (utils::filesystem::directory_exists(old_cpt_dir)) { if (utils::filesystem::remove_path(old_cpt_dir)) { ddebug("%s: checkpoint %s removed by garbage collection", data_dir().c_str(), old_cpt_dir.c_str()); } else { derror("%s: remove checkpoint %s failed by garbage collection", data_dir().c_str(), old_cpt_dir.c_str()); { // put back if remove failed utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.push_back(del_d); std::sort(_checkpoints.begin(), _checkpoints.end()); } break; } } else { dwarn("%s: checkpoint %s does not exist, garbage collection ignored", data_dir().c_str(), old_cpt_dir.c_str()); } } } void rrdb_service_impl::write_batch() { dassert(_batch.Count() > 0, ""); auto opts = _wt_opts; opts.given_sequence_number = _last_seq + 1; opts.given_decree = last_committed_decree() + 1; auto status = _db->Write(opts, &_batch); if (status.ok()) { _last_seq += _batch.Count(); check_last_seq(); } else { derror("%s failed, status = %s", __FUNCTION__, status.ToString().c_str()); set_physical_error(status.code()); } for (auto& r : _batch_repliers) { r(status.code()); } _batch_repliers.clear(); _batch.Clear(); } void rrdb_service_impl::check_last_seq() { dassert(_last_seq == _db->GetLatestSequenceNumber(), "_last_seq mismatch DB::GetLatestSequenceNumber(): %" PRIu64 " vs %" PRIu64 "", _last_seq, _db->GetLatestSequenceNumber() ); } void rrdb_service_impl::catchup_one() { dbg_dassert(_last_durable_seq < _last_seq, "incorrect seq values in catch-up: %" PRIu64 " vs %" PRIu64 "", _last_durable_seq, _last_seq ); if (++_last_durable_seq == _last_seq) { _is_catchup = false; ddebug("catch up done, last_seq = %" PRIu64 "", _last_seq); } } void rrdb_service_impl::on_put(const update_request& update, ::dsn::rpc_replier<int>& reply) { dassert(_is_open, "rrdb service %s is not ready", data_dir().c_str()); if (_is_catchup) { dassert(reply.is_empty(), "catchup only happens during initialization"); catchup_one(); return; } rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); _batch.Put(skey, svalue); _batch_repliers.push_back(reply); if (get_current_batch_state() != BS_BATCH) { write_batch(); } } void rrdb_service_impl::on_remove(const ::dsn::blob& key, ::dsn::rpc_replier<int>& reply) { dassert(_is_open, "rrdb service %s is not ready", data_dir().c_str()); if (_is_catchup) { dassert(reply.is_empty(), "catchup only happens during initialization"); catchup_one(); return; } rocksdb::Slice skey(key.data(), key.length()); _batch.Delete(skey); _batch_repliers.push_back(reply); if (get_current_batch_state() != BS_BATCH) { write_batch(); } } void rrdb_service_impl::on_merge(const update_request& update, ::dsn::rpc_replier<int>& reply) { dassert(_is_open, "rrdb service %s is not ready", data_dir().c_str()); if (_is_catchup) { dassert(reply.is_empty(), "catchup only happens during initialization"); catchup_one(); return; } rocksdb::Slice skey(update.key.data(), update.key.length()); rocksdb::Slice svalue(update.value.data(), update.value.length()); _batch.Merge(skey, svalue); _batch_repliers.push_back(reply); if (get_current_batch_state() != BS_BATCH) { write_batch(); } } void rrdb_service_impl::on_get(const ::dsn::blob& key, ::dsn::rpc_replier<read_response>& reply) { dassert(_is_open, "rrdb service %s is not ready", data_dir().c_str()); read_response resp; rocksdb::Slice skey(key.data(), key.length()); rocksdb::Status status = _db->Get(_rd_opts, skey, &resp.value); if (!status.ok() && !status.IsNotFound()) { derror("%s failed, status = %s", __FUNCTION__, status.ToString().c_str()); } resp.error = status.code(); reply(resp); } ::dsn::error_code rrdb_service_impl::open(bool create_new) { dassert(!_is_open, "rrdb service %s is already opened", data_dir().c_str()); rocksdb::Options opts = _db_opts; opts.create_if_missing = create_new; opts.error_if_exists = create_new; rrdb_service_impl::checkpoint_info last_checkpoint; if (create_new) { auto& dir = data_dir(); if (!utils::filesystem::remove_path(dir)) { derror("remove old directory %s failed", dir.c_str()); return ERR_FILE_OPERATION_FAILED; } if (!utils::filesystem::create_directory(dir)) { derror("create new directory %s failed", dir.c_str()); return ERR_FILE_OPERATION_FAILED; } } else { last_checkpoint = parse_checkpoints(); gc_checkpoints(); } auto path = utils::filesystem::path_combine(data_dir(), "rdb"); auto status = rocksdb::DB::Open(opts, path, &_db); if (status.ok()) { // load from checkpoints // set last_durable_decree/last_durable_seq/last_commit_decree to the last checkpoint _last_durable_decree = last_checkpoint.d; _last_durable_seq = last_checkpoint.seq; init_last_commit_decree(last_checkpoint.d); // however, // because rocksdb may persist the state on disk even without explicit flush(), // it is possible that the _last_seq is larger than _last_durable_seq // i.e., _last_durable_seq is not the ground-truth, // in this case, the db enters a catch-up mode, where the write ops are ignored // but only _last_durable_seq is increased until it equals to _last_seq. _last_seq = _db->GetLatestSequenceNumber(); if (_last_seq > _last_durable_seq) { _is_catchup = true; } ddebug("open app %s: last_committed/durable_decree = <%" PRId64 ", %" PRId64 ">, " "last_seq = %" PRIu64 ", last_durable_seq = %" PRIu64 ", is_catch_up = %s", data_dir().c_str(), last_committed_decree(), last_durable_decree(), _last_seq, _last_durable_seq, _is_catchup ? "true" : "false" ); _is_open = true; return ERR_OK; } else { derror("open rocksdb %s failed, status = %s", path.c_str(), status.ToString().c_str() ); return ERR_LOCAL_APP_FAILURE; } } ::dsn::error_code rrdb_service_impl::close(bool clear_state) { if (!_is_open) { dassert(_db == nullptr, ""); dassert(!clear_state, "should not be here if do clear"); return ERR_OK; } _is_open = false; delete _db; _db = nullptr; _batch.Clear(); _batch_repliers.clear(); _last_seq = 0; _is_catchup = false; _last_durable_seq = 0; _is_checkpointing = false; { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.clear(); } reset_states(); if (clear_state) { if (!utils::filesystem::remove_path(data_dir())) { return ERR_FILE_OPERATION_FAILED; } } return ERR_OK; } ::dsn::error_code rrdb_service_impl::checkpoint() { if (!_is_open || _is_catchup|| _is_checkpointing) return ERR_WRONG_TIMING; if (_last_durable_decree == last_committed_decree()) return ERR_NO_NEED_OPERATE; _is_checkpointing = true; rocksdb::Checkpoint* chkpt = nullptr; auto status = rocksdb::Checkpoint::Create(_db, &chkpt); if (!status.ok()) { derror("%s: create Checkpoint object failed, status = %s", data_dir().c_str(), status.ToString().c_str() ); _is_checkpointing = false; return ERR_LOCAL_APP_FAILURE; } checkpoint_info ci; ci.d = last_committed_decree(); ci.seq = _last_seq; check_last_seq(); auto dir = chkpt_get_dir_name(ci.d, ci.seq); auto chkpt_dir = utils::filesystem::path_combine(data_dir(), dir); if (utils::filesystem::directory_exists(chkpt_dir)) { dwarn("%s: checkpoint directory %s already exist, remove it first", data_dir().c_str(), chkpt_dir.c_str() ); if (!utils::filesystem::remove_path(chkpt_dir)) { derror("%s: remove old checkpoint directory %s failed", data_dir().c_str(), chkpt_dir.c_str() ); _is_checkpointing = false; return ERR_FILE_OPERATION_FAILED; } } status = chkpt->CreateCheckpoint(chkpt_dir); delete chkpt; chkpt = nullptr; if (!status.ok()) { derror("%s: create checkpoint failed, status = %s", data_dir().c_str(), status.ToString().c_str() ); utils::filesystem::remove_path(chkpt_dir); _is_checkpointing = false; return ERR_LOCAL_APP_FAILURE; } { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.push_back(ci); std::sort(_checkpoints.begin(), _checkpoints.end()); _last_durable_decree = _checkpoints.back().d; } ddebug("%s: create checkpoint %s succeed", data_dir().c_str(), chkpt_dir.c_str() ); gc_checkpoints(); _is_checkpointing = false; return ERR_OK; } // Must be thread safe. ::dsn::error_code rrdb_service_impl::checkpoint_async() { if (!_is_open || _is_catchup || _is_checkpointing) return ERR_WRONG_TIMING; if (_last_durable_decree == last_committed_decree()) return ERR_NO_NEED_OPERATE; _is_checkpointing = true; rocksdb::Checkpoint* chkpt = nullptr; auto status = rocksdb::Checkpoint::Create(_db, &chkpt); if (!status.ok()) { derror("%s: create Checkpoint object failed, status = %s", data_dir().c_str(), status.ToString().c_str() ); _is_checkpointing = false; return ERR_LOCAL_APP_FAILURE; } rocksdb::SequenceNumber sequence = 0; uint64_t decree = 0; { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); if (!_checkpoints.empty()) { auto& ci = _checkpoints.back(); sequence = ci.seq; decree = ci.d; } } char buf[256]; sprintf(buf, "checkpoint.tmp.%" PRIu64 "", dsn_now_us()); std::string tmp_dir = utils::filesystem::path_combine(data_dir(), buf); if (utils::filesystem::directory_exists(tmp_dir)) { dwarn("%s: tmp directory %s already exist, remove it first", data_dir().c_str(), tmp_dir.c_str() ); if (!utils::filesystem::remove_path(tmp_dir)) { derror("%s: remove old tmp directory %s failed", data_dir().c_str(), tmp_dir.c_str() ); _is_checkpointing = false; return ERR_FILE_OPERATION_FAILED; } } status = chkpt->CreateCheckpointQuick(tmp_dir, &sequence, &decree); delete chkpt; chkpt = nullptr; if (!status.ok()) { derror("%s: async create checkpoint failed, status = %s", data_dir().c_str(), status.ToString().c_str() ); utils::filesystem::remove_path(tmp_dir); _is_checkpointing = false; return status.IsTryAgain() ? ERR_TRY_AGAIN : ERR_LOCAL_APP_FAILURE; } checkpoint_info ci; ci.seq = sequence; ci.d = decree; auto dir = chkpt_get_dir_name(ci.d, ci.seq); auto chkpt_dir = utils::filesystem::path_combine(data_dir(), dir); if (utils::filesystem::directory_exists(chkpt_dir)) { dwarn("%s: checkpoint directory %s already exist, remove it first", data_dir().c_str(), chkpt_dir.c_str() ); if (!utils::filesystem::remove_path(chkpt_dir)) { derror("%s: remove old checkpoint directory %s failed", data_dir().c_str(), chkpt_dir.c_str() ); utils::filesystem::remove_path(tmp_dir); _is_checkpointing = false; return ERR_FILE_OPERATION_FAILED; } } if (!utils::filesystem::rename_path(tmp_dir, chkpt_dir)) { derror("%s: rename checkpoint directory from %s to %s failed", data_dir().c_str(), tmp_dir.c_str(), chkpt_dir.c_str() ); utils::filesystem::remove_path(tmp_dir); _is_checkpointing = false; return ERR_FILE_OPERATION_FAILED; } { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.push_back(ci); std::sort(_checkpoints.begin(), _checkpoints.end()); _last_durable_decree = _checkpoints.back().d; } ddebug("%s: async create checkpoint %s succeed", data_dir().c_str(), chkpt_dir.c_str() ); gc_checkpoints(); _is_checkpointing = false; return ERR_OK; } ::dsn::error_code rrdb_service_impl::get_checkpoint( ::dsn::replication::decree start, const blob& learn_req, /*out*/ ::dsn::replication::learn_state& state) { dassert(_is_open, "rrdb service %s is not ready", data_dir().c_str()); checkpoint_info ci; { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); if (_checkpoints.size() > 0) ci = *_checkpoints.rbegin(); } if (ci.d == 0) { derror("%s: no checkpoint found", data_dir().c_str()); return ERR_OBJECT_NOT_FOUND; } auto dir = chkpt_get_dir_name(ci.d, ci.seq); auto chkpt_dir = utils::filesystem::path_combine(data_dir(), dir); auto succ = utils::filesystem::get_subfiles(chkpt_dir, state.files, true); if (!succ) { derror("%s: list files in checkpoint dir %s failed", data_dir().c_str(), chkpt_dir.c_str()); return ERR_FILE_OPERATION_FAILED; } // attach checkpoint info binary_writer writer; writer.write_pod(ci); state.meta.push_back(writer.get_buffer()); state.from_decree_excluded = 0; state.to_decree_included = ci.d; ddebug("%s: get checkpoint succeed, from_decree_excluded = 0, to_decree_included = %" PRId64, data_dir().c_str(), state.to_decree_included); return ERR_OK; } ::dsn::error_code rrdb_service_impl::apply_checkpoint( ::dsn::replication::learn_state& state, ::dsn::replication::chkpt_apply_mode mode) { ::dsn::error_code err; checkpoint_info ci; dassert(state.meta.size() >= 1, "the learned state does not have checkpint meta info"); binary_reader reader(state.meta[0]); reader.read_pod(ci); if (mode == dsn::replication::CHKPT_COPY) { dassert(state.to_decree_included > last_durable_decree() && ci.d == state.to_decree_included, ""); auto dir = chkpt_get_dir_name(ci.d, ci.seq); auto chkpt_dir = utils::filesystem::path_combine(data_dir(), dir); auto old_dir = utils::filesystem::remove_file_name(state.files[0]); auto succ = utils::filesystem::rename_path(old_dir, chkpt_dir); if (succ) { utils::auto_lock<utils::ex_lock_nr> l(_checkpoints_lock); _checkpoints.push_back(ci); _last_durable_decree = ci.d; err = ERR_OK; } else { err = ERR_FILE_OPERATION_FAILED; } return err; } if (_is_open) { err = close(true); if (err != ERR_OK) { derror("close rocksdb %s failed, err = %s", data_dir().c_str(), err.to_string()); return err; } } // clear data dir if (!utils::filesystem::remove_path(data_dir())) { derror("clear data directory %s failed", data_dir().c_str()); return ERR_FILE_OPERATION_FAILED; } // reopen the db with the new checkpoint files if (state.files.size() > 0) { // create data dir if (!utils::filesystem::create_directory(data_dir())) { derror("create data directory %s failed", data_dir().c_str()); return ERR_FILE_OPERATION_FAILED; } // move learned files from learn_dir to data_dir/rdb std::string learn_dir = utils::filesystem::remove_file_name(*state.files.rbegin()); std::string new_dir = utils::filesystem::path_combine(data_dir(), "rdb"); if (!utils::filesystem::rename_path(learn_dir, new_dir)) { derror("rename %s to %s failed", learn_dir.c_str(), new_dir.c_str()); return ERR_FILE_OPERATION_FAILED; } err = open(false); } else { dwarn("%s: apply empty checkpoint, create new rocksdb", data_dir().c_str()); err = open(true); } if (err != ERR_OK) { derror("open rocksdb %s failed, err = %s", data_dir().c_str(), err.to_string()); return err; } // because there is no checkpoint in the new db dassert(_is_open, ""); dassert(last_committed_decree() == 0, ""); dassert(last_durable_decree() == 0, ""); dassert(ci.seq == _last_seq, "seq numbers from loaded data and attached meta info do not match: %" PRId64 " vs %" PRId64 "", ci.seq, _last_seq ); // set last_commit_decree to last checkpoint init_last_commit_decree(ci.d); _is_catchup = false; // checkpoint immediately if need if (last_committed_decree() != last_durable_decree()) { err = checkpoint(); if (err != ERR_OK) { derror("%s: checkpoint failed, err = %s", data_dir().c_str(), err.to_string()); return err; } dassert(last_committed_decree() == last_durable_decree(), "commit and durable decree mismatch after checkpoint: %" PRId64 " vs %" PRId64, last_committed_decree(), last_durable_decree() ); } ddebug("%s: apply checkpoint succeed, last_committed_decree = %" PRId64, data_dir().c_str(), last_committed_decree()); return ERR_OK; } } }
// Copyright 2020 Juan Marcelo Portillo. All Rights Reserved. #include "Gizmos/ScaleGizmo.h" #include "Components/BoxComponent.h" #include "Components/SphereComponent.h" AScaleGizmo::AScaleGizmo() { XY_PlaneBox = CreateDefaultSubobject<UBoxComponent>(TEXT("XY Plane")); YZ_PlaneBox = CreateDefaultSubobject<UBoxComponent>(TEXT("YZ Plane")); XZ_PlaneBox = CreateDefaultSubobject<UBoxComponent>(TEXT("XZ Plane")); XYZ_Sphere = CreateDefaultSubobject<USphereComponent>(TEXT("XYZ Sphere")); XY_PlaneBox->SetupAttachment(ScalingScene); YZ_PlaneBox->SetupAttachment(ScalingScene); XZ_PlaneBox->SetupAttachment(ScalingScene); XYZ_Sphere->SetupAttachment(ScalingScene); RegisterDomainComponent(XY_PlaneBox, ETransformationDomain::TD_XY_Plane); RegisterDomainComponent(YZ_PlaneBox, ETransformationDomain::TD_YZ_Plane); RegisterDomainComponent(XZ_PlaneBox, ETransformationDomain::TD_XZ_Plane); RegisterDomainComponent(XYZ_Sphere, ETransformationDomain::TD_XYZ); ScalingFactor = 0.05f; } void AScaleGizmo::UpdateGizmoSpace(ESpaceType SpaceType) { //Force to always be Local SetActorRelativeRotation(FQuat(EForceInit::ForceInit)); } FTransform AScaleGizmo::GetDeltaTransform(const FVector& LookingVector , const FVector& RayStartPoint, const FVector& RayEndPoint , ETransformationDomain Domain) { FTransform deltaTransform; deltaTransform.SetScale3D(FVector::ZeroVector); if (AreRaysValid()) { const float Cos45Deg = 0.707; // the opposite direction of the Normal that is most perpendicular to the Looking Vector // will be the one we choose to be the normal to the Domain! (needs to be calculated for axis. For planes, it's straightforward) FVector planeNormal; FVector targetDirection(0.f); //we have two vectors for each direction, one world and one local // world is to calculate the scale direction (e.g. for X scale it would have to be multiplied by 1.f, 0.f, 0.f) // local is to calculate the direction of the mouse and calculate how much it moved! FVector forwardVector = GetActorForwardVector(); FVector rightVector = GetActorRightVector(); FVector upVector = GetActorUpVector();; switch (Domain) { case ETransformationDomain::TD_X_Axis: { targetDirection = forwardVector; if (FMath::Abs(FVector::DotProduct(LookingVector, rightVector)) > Cos45Deg) planeNormal = rightVector; else planeNormal = upVector; break; } case ETransformationDomain::TD_Y_Axis: { targetDirection = rightVector; if (FMath::Abs(FVector::DotProduct(LookingVector, forwardVector)) > Cos45Deg) planeNormal = forwardVector; else planeNormal = upVector; break; } case ETransformationDomain::TD_Z_Axis: { targetDirection = upVector; if (FMath::Abs(FVector::DotProduct(LookingVector, forwardVector)) > Cos45Deg) planeNormal = forwardVector; else planeNormal = rightVector; break; } case ETransformationDomain::TD_XY_Plane: targetDirection = forwardVector + rightVector; planeNormal = upVector; break; case ETransformationDomain::TD_YZ_Plane: targetDirection = rightVector + upVector; planeNormal = forwardVector; break; case ETransformationDomain::TD_XZ_Plane: targetDirection = forwardVector + upVector; planeNormal = rightVector; break; case ETransformationDomain::TD_XYZ: targetDirection = forwardVector + rightVector + upVector; planeNormal = LookingVector; break; } FPlane plane; plane.X = planeNormal.X; plane.Y = planeNormal.Y; plane.Z = planeNormal.Z; plane.W = FVector::PointPlaneDist(GetActorLocation(), FVector::ZeroVector, planeNormal); FVector deltaLocation = FMath::LinePlaneIntersection(RayStartPoint, RayEndPoint, plane) - FMath::LinePlaneIntersection(PreviousRayStartPoint, PreviousRayEndPoint, plane); deltaLocation = deltaLocation.ProjectOnTo(targetDirection); deltaTransform.SetScale3D(deltaLocation * ScalingFactor); } UpdateRays(RayStartPoint, RayEndPoint); return deltaTransform; } FTransform AScaleGizmo::GetSnappedTransform(FTransform& outCurrentAccumulatedTransform , const FTransform& DeltaTransform , ETransformationDomain Domain , float SnappingValue) const { if (SnappingValue == 0.f) return DeltaTransform; FTransform result = DeltaTransform; FVector addedScale = outCurrentAccumulatedTransform.GetScale3D() + DeltaTransform.GetScale3D(); float domains = 1.f; switch (Domain) { case ETransformationDomain::TD_XY_Plane: case ETransformationDomain::TD_YZ_Plane: case ETransformationDomain::TD_XZ_Plane: domains = 2.f; break; case ETransformationDomain::TD_XYZ: domains = 3.f; break; } FVector snappedScale = addedScale.GetSafeNormal() * FMath::GridSnap(addedScale.Size(), FMath::Sqrt(FMath::Square(SnappingValue) * domains)); result.SetScale3D(snappedScale); outCurrentAccumulatedTransform.SetScale3D(addedScale - snappedScale); return result; } FTransform AScaleGizmo::GetSnappedTransformPerComponent(const FTransform& OldComponentTransform , const FTransform& NewComponentTransform, ETransformationDomain Domain , float SnappingValue) const { FTransform result= NewComponentTransform; FVector newScale = NewComponentTransform.GetScale3D(); if (!newScale.Equals(OldComponentTransform.GetScale3D(), 0.0001f)) { FVector domainScale; switch (Domain) { case ETransformationDomain::TD_X_Axis: domainScale = FVector(1.f, 0.f, 0.f); break; case ETransformationDomain::TD_Y_Axis: domainScale = FVector(0.f, 1.f, 0.f); break; case ETransformationDomain::TD_Z_Axis: domainScale = FVector(0.f, 0.f, 1.f); break; case ETransformationDomain::TD_XY_Plane: domainScale = FVector(1.f, 1.f, 0.f); break; case ETransformationDomain::TD_YZ_Plane: domainScale = FVector(0.f, 1.f, 1.f); break; case ETransformationDomain::TD_XZ_Plane: domainScale = FVector(1.f, 0.f, 1.f); break; case ETransformationDomain::TD_XYZ: domainScale = FVector(1.f, 1.f, 1.f); break; } FVector domainInverseScale = FVector::OneVector - domainScale; newScale = newScale.GridSnap(SnappingValue); FVector scale = (newScale * domainScale) + (NewComponentTransform.GetScale3D() * domainInverseScale); result.SetScale3D(scale); } return result; }
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "receiverequestdialog.h" #include "ui_receiverequestdialog.h" #include "bitcoinunits.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include "walletmodel.h" #include <QClipboard> #include <QDrag> #include <QMenu> #include <QMimeData> #include <QMouseEvent> #include <QPixmap> // #define USE_QRCODE #if defined(HAVE_CONFIG_H) #include "config/dapscoin-config.h" /* for USE_QRCODE */ #endif #ifdef USE_QRCODE #include <qrencode.h> #endif QRImageWidget::QRImageWidget(QWidget* parent) : QLabel(parent), contextMenu(0) { contextMenu = new QMenu(this); contextMenu->setAttribute(Qt::WA_DeleteOnClose); QAction* saveImageAction = new QAction(tr("&Save Image..."), this); connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage())); contextMenu->addAction(saveImageAction); QAction* copyImageAction = new QAction(tr("&Copy Image"), this); connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage())); contextMenu->addAction(copyImageAction); } QImage QRImageWidget::exportImage() { if (!pixmap()) return QImage(); return pixmap()->toImage().scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE); } void QRImageWidget::mousePressEvent(QMouseEvent* event) { if (event->button() == Qt::LeftButton && pixmap()) { event->accept(); QMimeData* mimeData = new QMimeData; mimeData->setImageData(exportImage()); QDrag* drag = new QDrag(this); drag->setMimeData(mimeData); drag->exec(); } else { QLabel::mousePressEvent(event); } } void QRImageWidget::saveImage() { if (!pixmap()) return; QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL); if (!fn.isEmpty()) { exportImage().save(fn); } } void QRImageWidget::copyImage() { if (!pixmap()) return; QApplication::clipboard()->setImage(exportImage()); } void QRImageWidget::contextMenuEvent(QContextMenuEvent* event) { if (!pixmap()) return; contextMenu->exec(event->globalPos()); } ReceiveRequestDialog::ReceiveRequestDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::ReceiveRequestDialog), model(0) { ui->setupUi(this); #ifndef USE_QRCODE ui->btnSaveAs->setVisible(false); ui->lblQRCode->setVisible(false); #endif connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage())); } ReceiveRequestDialog::~ReceiveRequestDialog() { delete ui; } void ReceiveRequestDialog::setModel(OptionsModel* model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update())); // update the display unit if necessary update(); } void ReceiveRequestDialog::setInfo(const SendCoinsRecipient& info) { this->info = info; update(); } void ReceiveRequestDialog::update() { if (!model) return; QString target = info.label; if (target.isEmpty()) target = info.address; setWindowTitle(tr("Request payment to %1").arg(target)); QString uri = GUIUtil::formatBitcoinURI(info); ui->btnSaveAs->setEnabled(false); QString html; html += "<html><font face='verdana, arial, helvetica, sans-serif'>"; html += "<b>" + tr("Payment information") + "</b><br>"; html += "<b>" + tr("URI") + "</b>: "; html += "<a style=\"color:#5B4C7C;\" href=\"" + uri + "\">" + GUIUtil::HtmlEscape(uri) + "</a><br>"; html += "<b>" + tr("Address") + "</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>"; if (info.amount) html += "<b>" + tr("Amount") + "</b>: " + BitcoinUnits::formatWithUnit(model->getDisplayUnit(), info.amount) + "<br>"; if (!info.label.isEmpty()) html += "<b>" + tr("Label") + "</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>"; if (!info.message.isEmpty()) html += "<b>" + tr("Message") + "</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>"; ui->outUri->setText(html); #ifdef USE_QRCODE ui->lblQRCode->setText(""); if (!uri.isEmpty()) { // limit URI length if (uri.length() > MAX_URI_LENGTH) { ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); } else { QRcode* code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char* p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->btnSaveAs->setEnabled(true); } } #endif } void ReceiveRequestDialog::on_btnCopyURI_clicked() { GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(info)); } void ReceiveRequestDialog::on_btnCopyAddress_clicked() { GUIUtil::setClipboard(info.address); }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2017-2019 The Kron Core developers // Distributed under the MIT software license, see the accompanying #if defined(HAVE_CONFIG_H) #include "config/Kron-config.h" #endif #include "chainparamsbase.h" #include "clientversion.h" #include "fs.h" #include "rpc/client.h" #include "rpc/protocol.h" #include "util.h" #include "utilstrencodings.h" #include <stdio.h> #include <event2/buffer.h> #include <event2/keyvalq_struct.h> #include "support/events.h" #include <univalue.h> static const char DEFAULT_RPCCONNECT[] = "127.0.0.1"; static const int DEFAULT_HTTP_CLIENT_TIMEOUT=900; static const bool DEFAULT_NAMED=false; static const int CONTINUE_EXECUTION=-1; std::string HelpMessageCli() { const auto defaultBaseParams = CreateBaseChainParams(CBaseChainParams::MAIN); const auto testnetBaseParams = CreateBaseChainParams(CBaseChainParams::TESTNET); std::string strUsage; strUsage += HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("This help message")); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), Kron_CONF_FILENAME)); strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); strUsage += HelpMessageOpt("-getinfo", _("Get general information from the remote server. Note that unlike server-side RPC calls, the results of -getinfo is the result of multiple non-atomic requests. Some entries in the result may represent results from different states (e.g. wallet balance may be as of a different block from the chain state reported)")); AppendParamsHelpMessages(strUsage); strUsage += HelpMessageOpt("-named", strprintf(_("Pass named instead of positional arguments (default: %s)"), DEFAULT_NAMED)); strUsage += HelpMessageOpt("-rpcconnect=<ip>", strprintf(_("Send commands to node running on <ip> (default: %s)"), DEFAULT_RPCCONNECT)); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Connect to JSON-RPC on <port> (default: %u or testnet: %u)"), defaultBaseParams->RPCPort(), testnetBaseParams->RPCPort())); strUsage += HelpMessageOpt("-rpcwait", _("Wait for RPC server to start")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcclienttimeout=<n>", strprintf(_("Timeout in seconds during HTTP requests, or 0 for no timeout. (default: %d)"), DEFAULT_HTTP_CLIENT_TIMEOUT)); strUsage += HelpMessageOpt("-stdinrpcpass", strprintf(_("Read RPC password from standard input as a single line. When combined with -stdin, the first line from standard input is used for the RPC password."))); strUsage += HelpMessageOpt("-stdin", _("Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases). When combined with -stdinrpcpass, the first line from standard input is used for the RPC password.")); strUsage += HelpMessageOpt("-rpcwallet=<walletname>", _("Send RPC for non-default wallet on RPC server (argument is wallet filename in Krond directory, required if Krond/-Qt runs with multiple wallets)")); return strUsage; } ////////////////////////////////////////////////////////////////////////////// // // Start // // // Exception thrown on connection error. This error is used to determine // when to wait if -rpcwait is given. // class CConnectionFailed : public std::runtime_error { public: explicit inline CConnectionFailed(const std::string& msg) : std::runtime_error(msg) {} }; // // This function returns either one of EXIT_ codes when it's expected to stop the process or // CONTINUE_EXECUTION when it's expected to continue further. // static int AppInitRPC(int argc, char* argv[]) { // // Parameters // gArgs.ParseParameters(argc, argv); if (argc<2 || gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) { std::string strUsage = strprintf(_("%s RPC client version"), _(PACKAGE_NAME)) + " " + FormatFullVersion() + "\n"; if (!gArgs.IsArgSet("-version")) { strUsage += "\n" + _("Usage:") + "\n" + " Kron-cli [options] <command> [params] " + strprintf(_("Send command to %s"), _(PACKAGE_NAME)) + "\n" + " Kron-cli [options] -named <command> [name=value] ... " + strprintf(_("Send command to %s (with named arguments)"), _(PACKAGE_NAME)) + "\n" + " Kron-cli [options] help " + _("List commands") + "\n" + " Kron-cli [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessageCli(); } fprintf(stdout, "%s", strUsage.c_str()); if (argc < 2) { fprintf(stderr, "Error: too few parameters\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return EXIT_FAILURE; } try { gArgs.ReadConfigFile(gArgs.GetArg("-conf", Kron_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return EXIT_FAILURE; } // Check for -testnet or -regtest parameter (BaseParams() calls are only valid after this clause) try { SelectBaseParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return EXIT_FAILURE; } if (gArgs.GetBoolArg("-rpcssl", false)) { fprintf(stderr, "Error: SSL mode for RPC (-rpcssl) is no longer supported.\n"); return EXIT_FAILURE; } return CONTINUE_EXECUTION; } /** Reply structure for request_done to fill in */ struct HTTPReply { HTTPReply(): status(0), error(-1) {} int status; int error; std::string body; }; const char *http_errorstring(int code) { switch(code) { #if LIBEVENT_VERSION_NUMBER >= 0x02010300 case EVREQ_HTTP_TIMEOUT: return "timeout reached"; case EVREQ_HTTP_EOF: return "EOF reached"; case EVREQ_HTTP_INVALID_HEADER: return "error while reading header, or invalid header"; case EVREQ_HTTP_BUFFER_ERROR: return "error encountered while reading or writing"; case EVREQ_HTTP_REQUEST_CANCEL: return "request was canceled"; case EVREQ_HTTP_DATA_TOO_LONG: return "response body is larger than allowed"; #endif default: return "unknown"; } } static void http_request_done(struct evhttp_request *req, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); if (req == nullptr) { /* If req is nullptr, it means an error occurred while connecting: the * error code will have been passed to http_error_cb. */ reply->status = 0; return; } reply->status = evhttp_request_get_response_code(req); struct evbuffer *buf = evhttp_request_get_input_buffer(req); if (buf) { size_t size = evbuffer_get_length(buf); const char *data = (const char*)evbuffer_pullup(buf, size); if (data) reply->body = std::string(data, size); evbuffer_drain(buf, size); } } #if LIBEVENT_VERSION_NUMBER >= 0x02010300 static void http_error_cb(enum evhttp_request_error err, void *ctx) { HTTPReply *reply = static_cast<HTTPReply*>(ctx); reply->error = err; } #endif /** Class that handles the conversion from a command-line to a JSON-RPC request, * as well as converting back to a JSON object that can be shown as result. */ class BaseRequestHandler { public: virtual ~BaseRequestHandler() {} virtual UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) = 0; virtual UniValue ProcessReply(const UniValue &batch_in) = 0; }; /** Process getinfo requests */ class GetinfoRequestHandler: public BaseRequestHandler { public: const int ID_NETWORKINFO = 0; const int ID_BLOCKCHAININFO = 1; const int ID_WALLETINFO = 2; /** Create a simulated `getinfo` request. */ UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override { UniValue result(UniValue::VARR); result.push_back(JSONRPCRequestObj("getnetworkinfo", NullUniValue, ID_NETWORKINFO)); result.push_back(JSONRPCRequestObj("getblockchaininfo", NullUniValue, ID_BLOCKCHAININFO)); result.push_back(JSONRPCRequestObj("getwalletinfo", NullUniValue, ID_WALLETINFO)); return result; } /** Collect values from the batch and form a simulated `getinfo` reply. */ UniValue ProcessReply(const UniValue &batch_in) override { UniValue result(UniValue::VOBJ); std::vector<UniValue> batch = JSONRPCProcessBatchReply(batch_in, 3); // Errors in getnetworkinfo() and getblockchaininfo() are fatal, pass them on // getwalletinfo() is allowed to fail in case there is no wallet. if (!batch[ID_NETWORKINFO]["error"].isNull()) { return batch[ID_NETWORKINFO]; } if (!batch[ID_BLOCKCHAININFO]["error"].isNull()) { return batch[ID_BLOCKCHAININFO]; } result.pushKV("version", batch[ID_NETWORKINFO]["result"]["version"]); result.pushKV("protocolversion", batch[ID_NETWORKINFO]["result"]["protocolversion"]); if (!batch[ID_WALLETINFO].isNull()) { result.pushKV("walletversion", batch[ID_WALLETINFO]["result"]["walletversion"]); result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]); } result.pushKV("blocks", batch[ID_BLOCKCHAININFO]["result"]["blocks"]); result.pushKV("timeoffset", batch[ID_NETWORKINFO]["result"]["timeoffset"]); result.pushKV("connections", batch[ID_NETWORKINFO]["result"]["connections"]); result.pushKV("proxy", batch[ID_NETWORKINFO]["result"]["networks"][0]["proxy"]); result.pushKV("difficulty", batch[ID_BLOCKCHAININFO]["result"]["difficulty"]); result.pushKV("testnet", UniValue(batch[ID_BLOCKCHAININFO]["result"]["chain"].get_str() == "test")); if (!batch[ID_WALLETINFO].isNull()) { result.pushKV("walletversion", batch[ID_WALLETINFO]["result"]["walletversion"]); result.pushKV("balance", batch[ID_WALLETINFO]["result"]["balance"]); result.pushKV("keypoololdest", batch[ID_WALLETINFO]["result"]["keypoololdest"]); result.pushKV("keypoolsize", batch[ID_WALLETINFO]["result"]["keypoolsize"]); if (!batch[ID_WALLETINFO]["result"]["unlocked_until"].isNull()) { result.pushKV("unlocked_until", batch[ID_WALLETINFO]["result"]["unlocked_until"]); } result.pushKV("paytxfee", batch[ID_WALLETINFO]["result"]["paytxfee"]); } result.pushKV("relayfee", batch[ID_NETWORKINFO]["result"]["relayfee"]); result.pushKV("warnings", batch[ID_NETWORKINFO]["result"]["warnings"]); return JSONRPCReplyObj(result, NullUniValue, 1); } }; /** Process default single requests */ class DefaultRequestHandler: public BaseRequestHandler { public: UniValue PrepareRequest(const std::string& method, const std::vector<std::string>& args) override { UniValue params; if(gArgs.GetBoolArg("-named", DEFAULT_NAMED)) { params = RPCConvertNamedValues(method, args); } else { params = RPCConvertValues(method, args); } return JSONRPCRequestObj(method, params, 1); } UniValue ProcessReply(const UniValue &reply) override { return reply.get_obj(); } }; static UniValue CallRPC(BaseRequestHandler *rh, const std::string& strMethod, const std::vector<std::string>& args) { std::string host; // In preference order, we choose the following for the port: // 1. -rpcport // 2. port in -rpcconnect (ie following : in ipv4 or ]: in ipv6) // 3. default port for chain int port = BaseParams().RPCPort(); SplitHostPort(gArgs.GetArg("-rpcconnect", DEFAULT_RPCCONNECT), port, host); port = gArgs.GetArg("-rpcport", port); // Obtain event base raii_event_base base = obtain_event_base(); // Synchronously look up hostname raii_evhttp_connection evcon = obtain_evhttp_connection_base(base.get(), host, port); evhttp_connection_set_timeout(evcon.get(), gArgs.GetArg("-rpcclienttimeout", DEFAULT_HTTP_CLIENT_TIMEOUT)); HTTPReply response; raii_evhttp_request req = obtain_evhttp_request(http_request_done, (void*)&response); if (req == nullptr) throw std::runtime_error("create http request failed"); #if LIBEVENT_VERSION_NUMBER >= 0x02010300 evhttp_request_set_error_cb(req.get(), http_error_cb); #endif // Get credentials std::string strRPCUserColonPass; if (gArgs.GetArg("-rpcpassword", "") == "") { // Try fall back to cookie-based authentication if no password is provided if (!GetAuthCookie(&strRPCUserColonPass)) { throw std::runtime_error(strprintf( _("Could not locate RPC credentials. No authentication cookie could be found, and RPC password is not set. See -rpcpassword and -stdinrpcpass. Configuration file: (%s)"), GetConfigFile(gArgs.GetArg("-conf", Kron_CONF_FILENAME)).string().c_str())); } } else { strRPCUserColonPass = gArgs.GetArg("-rpcuser", "") + ":" + gArgs.GetArg("-rpcpassword", ""); } struct evkeyvalq* output_headers = evhttp_request_get_output_headers(req.get()); assert(output_headers); evhttp_add_header(output_headers, "Host", host.c_str()); evhttp_add_header(output_headers, "Connection", "close"); evhttp_add_header(output_headers, "Authorization", (std::string("Basic ") + EncodeBase64(strRPCUserColonPass)).c_str()); // Attach request data std::string strRequest = rh->PrepareRequest(strMethod, args).write() + "\n"; struct evbuffer* output_buffer = evhttp_request_get_output_buffer(req.get()); assert(output_buffer); evbuffer_add(output_buffer, strRequest.data(), strRequest.size()); // check if we should use a special wallet endpoint std::string endpoint = "/"; std::string walletName = gArgs.GetArg("-rpcwallet", ""); if (!walletName.empty()) { char *encodedURI = evhttp_uriencode(walletName.c_str(), walletName.size(), false); if (encodedURI) { endpoint = "/wallet/"+ std::string(encodedURI); free(encodedURI); } else { throw CConnectionFailed("uri-encode failed"); } } int r = evhttp_make_request(evcon.get(), req.get(), EVHTTP_REQ_POST, endpoint.c_str()); req.release(); // ownership moved to evcon in above call if (r != 0) { throw CConnectionFailed("send http request failed"); } event_base_dispatch(base.get()); if (response.status == 0) throw CConnectionFailed(strprintf("couldn't connect to server: %s (code %d)\n(make sure server is running and you are connecting to the correct RPC port)", http_errorstring(response.error), response.error)); else if (response.status == HTTP_UNAUTHORIZED) throw std::runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); else if (response.status >= 400 && response.status != HTTP_BAD_REQUEST && response.status != HTTP_NOT_FOUND && response.status != HTTP_INTERNAL_SERVER_ERROR) throw std::runtime_error(strprintf("server returned HTTP error %d", response.status)); else if (response.body.empty()) throw std::runtime_error("no response from server"); // Parse reply UniValue valReply(UniValue::VSTR); if (!valReply.read(response.body)) throw std::runtime_error("couldn't parse reply from server"); const UniValue reply = rh->ProcessReply(valReply); if (reply.empty()) throw std::runtime_error("expected reply to have result, error and id properties"); return reply; } int CommandLineRPC(int argc, char *argv[]) { std::string strPrint; int nRet = 0; try { // Skip switches while (argc > 1 && IsSwitchChar(argv[1][0])) { argc--; argv++; } std::string rpcPass; if (gArgs.GetBoolArg("-stdinrpcpass", false)) { if (!std::getline(std::cin, rpcPass)) { throw std::runtime_error("-stdinrpcpass specified but failed to read from standard input"); } gArgs.ForceSetArg("-rpcpassword", rpcPass); } std::vector<std::string> args = std::vector<std::string>(&argv[1], &argv[argc]); if (gArgs.GetBoolArg("-stdin", false)) { // Read one arg per line from stdin and append std::string line; while (std::getline(std::cin, line)) { args.push_back(line); } } std::unique_ptr<BaseRequestHandler> rh; std::string method; if (gArgs.GetBoolArg("-getinfo", false)) { rh.reset(new GetinfoRequestHandler()); method = ""; } else { rh.reset(new DefaultRequestHandler()); if (args.size() < 1) { throw std::runtime_error("too few parameters (need at least command)"); } method = args[0]; args.erase(args.begin()); // Remove trailing method name from arguments vector } // Execute and handle connection failures with -rpcwait const bool fWait = gArgs.GetBoolArg("-rpcwait", false); do { try { const UniValue reply = CallRPC(rh.get(), method, args); // Parse reply const UniValue& result = find_value(reply, "result"); const UniValue& error = find_value(reply, "error"); if (!error.isNull()) { // Error int code = error["code"].get_int(); if (fWait && code == RPC_IN_WARMUP) throw CConnectionFailed("server in warmup"); strPrint = "error: " + error.write(); nRet = abs(code); if (error.isObject()) { UniValue errCode = find_value(error, "code"); UniValue errMsg = find_value(error, "message"); strPrint = errCode.isNull() ? "" : "error code: "+errCode.getValStr()+"\n"; if (errMsg.isStr()) strPrint += "error message:\n"+errMsg.get_str(); if (errCode.isNum() && errCode.get_int() == RPC_WALLET_NOT_SPECIFIED) { strPrint += "\nTry adding \"-rpcwallet=<filename>\" option to Kron-cli command line."; } } } else { // Result if (result.isNull()) strPrint = ""; else if (result.isStr()) strPrint = result.get_str(); else strPrint = result.write(2); } // Connection succeeded, no need to retry. break; } catch (const CConnectionFailed&) { if (fWait) MilliSleep(1000); else throw; } } while (fWait); } catch (const boost::thread_interrupted&) { throw; } catch (const std::exception& e) { strPrint = std::string("error: ") + e.what(); nRet = EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRPC()"); throw; } if (strPrint != "") { fprintf((nRet == 0 ? stdout : stderr), "%s\n", strPrint.c_str()); } return nRet; } int main(int argc, char* argv[]) { SetupEnvironment(); if (!SetupNetworking()) { fprintf(stderr, "Error: Initializing networking failed\n"); return EXIT_FAILURE; } try { int ret = AppInitRPC(argc, argv); if (ret != CONTINUE_EXECUTION) return ret; } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInitRPC()"); return EXIT_FAILURE; } catch (...) { PrintExceptionContinue(nullptr, "AppInitRPC()"); return EXIT_FAILURE; } int ret = EXIT_FAILURE; try { ret = CommandLineRPC(argc, argv); } catch (const std::exception& e) { PrintExceptionContinue(&e, "CommandLineRPC()"); } catch (...) { PrintExceptionContinue(nullptr, "CommandLineRPC()"); } return ret; }
#include "pokemondlg.h" #include "ui_pokemondlg.h" #include <QVBoxLayout> PokemonDlg::PokemonDlg(const QString &detail, bool myPokemonTable, QWidget *parent) : QDialog(parent), ui(new Ui::PokemonDlg) { ui->setupUi(this); // ui setWindowTitle(tr("精灵详情")); table = new QTableWidget(this); table->setColumnCount(1); table->setRowCount(9); table->setVerticalHeaderLabels({tr("精灵ID"), tr("名字"), tr("种族"), tr("攻击力"), tr("防御力"), tr("生命值"), tr("速度"), tr("等级"), tr("经验")}); table->horizontalHeader()->hide(); table->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch); // data auto details = detail.split(' '); for (int i = 0; i < 9; ++i) { auto t = new QTableWidgetItem(details[i]); if (i != 1) { // only pokemon name can be changed t->setFlags(t->flags() ^ Qt::ItemIsEnabled); t->setBackgroundColor(QColor("#eff0f1")); } else { if (myPokemonTable) { t->setToolTip(tr("双击以更改精灵名称")); } else { // can not change other players' pokemons' name t->setFlags(t->flags() ^ Qt::ItemIsEditable); t->setBackgroundColor(QColor("#eff0f1")); } } table->setItem(i, 0, t); } connect(table, &QTableWidget::cellChanged, this, [this, detail] { emit pokemonChangeName(detail[0], table->item(1, 0)->text()); }); // img lbImg = new QLabel(this); // name // if (details[2] == "Bulbasaur") if (details[2] == "妙蛙种子") { lbImg->setPixmap(QPixmap(":/img/img/bulbasaur.png")); setWindowIcon(QIcon(":/img/img/bulbasaur.png")); } // else if (details[2] == "Charmander") else if (details[2] == "小火龙") { lbImg->setPixmap(QPixmap(":/img/img/charmander.png")); setWindowIcon(QIcon(":/img/img/charmander.png")); } // else if (details[2] == "Squirtle") else if (details[2] == "杰尼龟") { lbImg->setPixmap(QPixmap(":/img/img/squirtle.png")); setWindowIcon(QIcon(":/img/img/squirtle.png")); } // else if (details[2] == "Pidgey") else if (details[2] == "波波") { lbImg->setPixmap(QPixmap(":/img/img/pidgey.png")); setWindowIcon(QIcon(":/img/img/pidgey.png")); } // layout QVBoxLayout *layout = new QVBoxLayout(this); layout->addWidget(lbImg, 0, Qt::AlignCenter); layout->addWidget(table, 0, Qt::AlignHCenter); setLayout(layout); setFixedSize(340, 670); // can not resize window // memory setAttribute(Qt::WA_DeleteOnClose); // setup ui after data filling setWindowFlags(windowFlags() ^ Qt::WindowContextHelpButtonHint); show(); } PokemonDlg::~PokemonDlg() { delete ui; }
// // Created by cody on 8/7/17. // #include <iostream> int main() { std::cout << "Enter two numbers:" << std::endl; int v1 = 0, v2 = 0; std::cin >> v1 >> v2; std::cout << "The sum of " << v1 << " and " << v2 << " is " << v1 + v2 << std::endl; return 0; }
https://github.com/Yashwanth-Chennu Problem Statement:https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/is-zoo-f6f309e7/submissions/ Solution: #include <bits/stdc++.h> using namespace std; int main(){ string zoo; cin >> zoo; int len = zoo.size(); if(len > 20) cout << "No"; else{ int zc = 0, oc = 0; for(int i = 0; i < len; i++){ if(zoo[i] == 'z') zc++; if(zoo[i] == 'o') oc++; } if(2*zc == oc) cout <<"Yes"; else cout <<"No"; } return 0; }
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. #include "vm/object_graph.h" #include "vm/dart.h" #include "vm/dart_api_state.h" #include "vm/growable_array.h" #include "vm/isolate.h" #include "vm/native_symbol.h" #include "vm/object.h" #include "vm/object_store.h" #include "vm/profiler.h" #include "vm/raw_object.h" #include "vm/raw_object_fields.h" #include "vm/reusable_handles.h" #include "vm/visitor.h" namespace dart { #if !defined(PRODUCT) static bool IsUserClass(intptr_t cid) { if (cid == kContextCid) return true; if (cid == kTypeArgumentsCid) return false; return cid >= kInstanceCid; } // The state of a pre-order, depth-first traversal of an object graph. // When a node is visited, *all* its children are pushed to the stack at once. // We insert a sentinel between the node and its children on the stack, to // remember that the node has been visited. The node is kept on the stack while // its children are processed, to give the visitor a complete chain of parents. // // TODO(koda): Potential optimizations: // - Use tag bits for compact Node and sentinel representations. class ObjectGraph::Stack : public ObjectPointerVisitor { public: explicit Stack(IsolateGroup* isolate_group) : ObjectPointerVisitor(isolate_group), include_vm_objects_(true), data_(kInitialCapacity) { object_ids_ = new WeakTable(); } ~Stack() { delete object_ids_; object_ids_ = nullptr; } virtual bool trace_values_through_fields() const { return true; } // Marks and pushes. Used to initialize this stack with roots. // We can use ObjectIdTable normally used by serializers because it // won't be in use while handling a service request (ObjectGraph's only use). virtual void VisitPointers(ObjectPtr* first, ObjectPtr* last) { for (ObjectPtr* current = first; current <= last; ++current) { if ((*current)->IsHeapObject() && !(*current)->untag()->InVMIsolateHeap() && object_ids_->GetValueExclusive(*current) == 0) { // not visited yet if (!include_vm_objects_ && !IsUserClass((*current)->GetClassId())) { continue; } object_ids_->SetValueExclusive(*current, 1); Node node; node.ptr = current; node.obj = *current; node.gc_root_type = gc_root_type(); data_.Add(node); } } } // Traverses the object graph from the current state. void TraverseGraph(ObjectGraph::Visitor* visitor) { while (!data_.is_empty()) { Node node = data_.Last(); if (node.ptr == kSentinel) { data_.RemoveLast(); // The node below the sentinel has already been visited. data_.RemoveLast(); continue; } ObjectPtr obj = node.obj; ASSERT(obj->IsHeapObject()); Node sentinel; sentinel.ptr = kSentinel; data_.Add(sentinel); StackIterator it(this, data_.length() - 2); visitor->gc_root_type = node.gc_root_type; Visitor::Direction direction = visitor->VisitObject(&it); if (direction == ObjectGraph::Visitor::kAbort) { break; } if (direction == ObjectGraph::Visitor::kProceed) { set_gc_root_type(node.gc_root_type); obj->untag()->VisitPointers(this); clear_gc_root_type(); } } } virtual bool visit_weak_persistent_handles() const { return visit_weak_persistent_handles_; } void set_visit_weak_persistent_handles(bool value) { visit_weak_persistent_handles_ = value; } bool include_vm_objects_; private: struct Node { ObjectPtr* ptr; // kSentinel for the sentinel node. ObjectPtr obj; const char* gc_root_type; }; bool visit_weak_persistent_handles_ = false; static ObjectPtr* const kSentinel; static const intptr_t kInitialCapacity = 1024; static const intptr_t kNoParent = -1; intptr_t Parent(intptr_t index) const { // The parent is just below the next sentinel. for (intptr_t i = index; i >= 1; --i) { if (data_[i].ptr == kSentinel) { return i - 1; } } return kNoParent; } // During the iteration of the heap we are already at a safepoint, so there is // no need to let the GC know about [object_ids_] (i.e. GC cannot run while we // use [object_ids]). WeakTable* object_ids_ = nullptr; GrowableArray<Node> data_; friend class StackIterator; DISALLOW_COPY_AND_ASSIGN(Stack); }; ObjectPtr* const ObjectGraph::Stack::kSentinel = NULL; ObjectPtr ObjectGraph::StackIterator::Get() const { return stack_->data_[index_].obj; } bool ObjectGraph::StackIterator::MoveToParent() { intptr_t parent = stack_->Parent(index_); if (parent == Stack::kNoParent) { return false; } else { index_ = parent; return true; } } intptr_t ObjectGraph::StackIterator::OffsetFromParentInWords() const { intptr_t parent_index = stack_->Parent(index_); if (parent_index == Stack::kNoParent) { return -1; } Stack::Node parent = stack_->data_[parent_index]; uword parent_start = UntaggedObject::ToAddr(parent.obj); Stack::Node child = stack_->data_[index_]; ASSERT(child.obj == *child.ptr); uword child_ptr_addr = reinterpret_cast<uword>(child.ptr); intptr_t offset = child_ptr_addr - parent_start; if (offset > 0 && offset < parent.obj->untag()->HeapSize()) { ASSERT(Utils::IsAligned(offset, kWordSize)); return offset >> kWordSizeLog2; } else { // Some internal VM objects visit pointers not contained within the parent. // For instance, UntaggedCode::VisitCodePointers visits pointers in // instructions. ASSERT(!parent.obj->IsDartInstance()); return -1; } } static void IterateUserFields(ObjectPointerVisitor* visitor) { visitor->set_gc_root_type("user global"); Thread* thread = Thread::Current(); // Scope to prevent handles create here from appearing as stack references. HANDLESCOPE(thread); Zone* zone = thread->zone(); const GrowableObjectArray& libraries = GrowableObjectArray::Handle( zone, thread->isolate_group()->object_store()->libraries()); Library& library = Library::Handle(zone); Object& entry = Object::Handle(zone); Class& cls = Class::Handle(zone); Array& fields = Array::Handle(zone); Field& field = Field::Handle(zone); for (intptr_t i = 0; i < libraries.Length(); i++) { library ^= libraries.At(i); DictionaryIterator entries(library); while (entries.HasNext()) { entry = entries.GetNext(); if (entry.IsClass()) { cls ^= entry.ptr(); fields = cls.fields(); for (intptr_t j = 0; j < fields.Length(); j++) { field ^= fields.At(j); ObjectPtr ptr = field.ptr(); visitor->VisitPointer(&ptr); } } else if (entry.IsField()) { field ^= entry.ptr(); ObjectPtr ptr = field.ptr(); visitor->VisitPointer(&ptr); } } } visitor->clear_gc_root_type(); } ObjectGraph::ObjectGraph(Thread* thread) : ThreadStackResource(thread) { // The VM isolate has all its objects pre-marked, so iterating over it // would be a no-op. ASSERT(thread->isolate() != Dart::vm_isolate()); } ObjectGraph::~ObjectGraph() {} void ObjectGraph::IterateObjects(ObjectGraph::Visitor* visitor) { Stack stack(isolate_group()); stack.set_visit_weak_persistent_handles( visitor->visit_weak_persistent_handles()); isolate_group()->VisitObjectPointers(&stack, ValidationPolicy::kDontValidateFrames); stack.TraverseGraph(visitor); } void ObjectGraph::IterateUserObjects(ObjectGraph::Visitor* visitor) { Stack stack(isolate_group()); stack.set_visit_weak_persistent_handles( visitor->visit_weak_persistent_handles()); IterateUserFields(&stack); stack.include_vm_objects_ = false; stack.TraverseGraph(visitor); } void ObjectGraph::IterateObjectsFrom(const Object& root, ObjectGraph::Visitor* visitor) { Stack stack(isolate_group()); stack.set_visit_weak_persistent_handles( visitor->visit_weak_persistent_handles()); ObjectPtr root_raw = root.ptr(); stack.VisitPointer(&root_raw); stack.TraverseGraph(visitor); } class InstanceAccumulator : public ObjectVisitor { public: InstanceAccumulator(ObjectGraph::Stack* stack, intptr_t class_id) : stack_(stack), class_id_(class_id) {} void VisitObject(ObjectPtr obj) { if (obj->GetClassId() == class_id_) { ObjectPtr rawobj = obj; stack_->VisitPointer(&rawobj); } } private: ObjectGraph::Stack* stack_; const intptr_t class_id_; DISALLOW_COPY_AND_ASSIGN(InstanceAccumulator); }; void ObjectGraph::IterateObjectsFrom(intptr_t class_id, HeapIterationScope* iteration, ObjectGraph::Visitor* visitor) { Stack stack(isolate_group()); InstanceAccumulator accumulator(&stack, class_id); iteration->IterateObjectsNoImagePages(&accumulator); stack.TraverseGraph(visitor); } class SizeVisitor : public ObjectGraph::Visitor { public: SizeVisitor() : size_(0) {} intptr_t size() const { return size_; } virtual bool ShouldSkip(ObjectPtr obj) const { return false; } virtual Direction VisitObject(ObjectGraph::StackIterator* it) { ObjectPtr obj = it->Get(); if (ShouldSkip(obj)) { return kBacktrack; } size_ += obj->untag()->HeapSize(); return kProceed; } private: intptr_t size_; }; class SizeExcludingObjectVisitor : public SizeVisitor { public: explicit SizeExcludingObjectVisitor(const Object& skip) : skip_(skip) {} virtual bool ShouldSkip(ObjectPtr obj) const { return obj == skip_.ptr(); } private: const Object& skip_; }; class SizeExcludingClassVisitor : public SizeVisitor { public: explicit SizeExcludingClassVisitor(intptr_t skip) : skip_(skip) {} virtual bool ShouldSkip(ObjectPtr obj) const { return obj->GetClassId() == skip_; } private: const intptr_t skip_; }; intptr_t ObjectGraph::SizeRetainedByInstance(const Object& obj) { HeapIterationScope iteration_scope(Thread::Current(), true); SizeVisitor total; IterateObjects(&total); intptr_t size_total = total.size(); SizeExcludingObjectVisitor excluding_obj(obj); IterateObjects(&excluding_obj); intptr_t size_excluding_obj = excluding_obj.size(); return size_total - size_excluding_obj; } intptr_t ObjectGraph::SizeReachableByInstance(const Object& obj) { HeapIterationScope iteration_scope(Thread::Current(), true); SizeVisitor total; IterateObjectsFrom(obj, &total); return total.size(); } intptr_t ObjectGraph::SizeRetainedByClass(intptr_t class_id) { HeapIterationScope iteration_scope(Thread::Current(), true); SizeVisitor total; IterateObjects(&total); intptr_t size_total = total.size(); SizeExcludingClassVisitor excluding_class(class_id); IterateObjects(&excluding_class); intptr_t size_excluding_class = excluding_class.size(); return size_total - size_excluding_class; } intptr_t ObjectGraph::SizeReachableByClass(intptr_t class_id) { HeapIterationScope iteration_scope(Thread::Current(), true); SizeVisitor total; IterateObjectsFrom(class_id, &iteration_scope, &total); return total.size(); } class RetainingPathVisitor : public ObjectGraph::Visitor { public: // We cannot use a GrowableObjectArray, since we must not trigger GC. RetainingPathVisitor(ObjectPtr obj, const Array& path) : thread_(Thread::Current()), obj_(obj), path_(path), length_(0) {} intptr_t length() const { return length_; } virtual bool visit_weak_persistent_handles() const { return true; } bool ShouldSkip(ObjectPtr obj) { // A retaining path through ICData is never the only retaining path, // and it is less informative than its alternatives. intptr_t cid = obj->GetClassId(); switch (cid) { case kICDataCid: return true; default: return false; } } bool ShouldStop(ObjectPtr obj) { // A static field is considered a root from a language point of view. if (obj->IsField()) { const Field& field = Field::Handle(static_cast<FieldPtr>(obj)); return field.is_static(); } return false; } void StartList() { was_last_array_ = false; } intptr_t HideNDescendant(ObjectPtr obj) { // A GrowableObjectArray overwrites its internal storage. // Keeping both of them in the list is redundant. if (was_last_array_ && obj->IsGrowableObjectArray()) { was_last_array_ = false; return 1; } // A LinkedHasMap overwrites its internal storage. // Keeping both of them in the list is redundant. if (was_last_array_ && obj->IsLinkedHashMap()) { was_last_array_ = false; return 1; } was_last_array_ = obj->IsArray(); return 0; } virtual Direction VisitObject(ObjectGraph::StackIterator* it) { if (it->Get() != obj_) { if (ShouldSkip(it->Get())) { return kBacktrack; } else { return kProceed; } } else { HANDLESCOPE(thread_); Object& current = Object::Handle(); Smi& offset_from_parent = Smi::Handle(); StartList(); do { // We collapse the backingstore of some internal objects. length_ -= HideNDescendant(it->Get()); intptr_t obj_index = length_ * 2; intptr_t offset_index = obj_index + 1; if (!path_.IsNull() && offset_index < path_.Length()) { current = it->Get(); path_.SetAt(obj_index, current); offset_from_parent = Smi::New(it->OffsetFromParentInWords()); path_.SetAt(offset_index, offset_from_parent); } ++length_; } while (!ShouldStop(it->Get()) && it->MoveToParent()); return kAbort; } } private: Thread* thread_; ObjectPtr obj_; const Array& path_; intptr_t length_; bool was_last_array_; }; ObjectGraph::RetainingPathResult ObjectGraph::RetainingPath(Object* obj, const Array& path) { HeapIterationScope iteration_scope(Thread::Current(), true); // To break the trivial path, the handle 'obj' is temporarily cleared during // the search, but restored before returning. ObjectPtr raw = obj->ptr(); *obj = Object::null(); RetainingPathVisitor visitor(raw, path); IterateUserObjects(&visitor); if (visitor.length() == 0) { IterateObjects(&visitor); } *obj = raw; return {visitor.length(), visitor.gc_root_type}; } class InboundReferencesVisitor : public ObjectVisitor, public ObjectPointerVisitor { public: // We cannot use a GrowableObjectArray, since we must not trigger GC. InboundReferencesVisitor(Isolate* isolate, ObjectPtr target, const Array& references, Object* scratch) : ObjectPointerVisitor(isolate->group()), source_(nullptr), target_(target), references_(references), scratch_(scratch), length_(0) { ASSERT(Thread::Current()->no_safepoint_scope_depth() != 0); } virtual bool trace_values_through_fields() const { return true; } intptr_t length() const { return length_; } virtual void VisitObject(ObjectPtr raw_obj) { source_ = raw_obj; raw_obj->untag()->VisitPointers(this); } virtual void VisitPointers(ObjectPtr* first, ObjectPtr* last) { for (ObjectPtr* current_ptr = first; current_ptr <= last; current_ptr++) { ObjectPtr current_obj = *current_ptr; if (current_obj == target_) { intptr_t obj_index = length_ * 2; intptr_t offset_index = obj_index + 1; if (!references_.IsNull() && offset_index < references_.Length()) { *scratch_ = source_; references_.SetAt(obj_index, *scratch_); *scratch_ = Smi::New(0); uword source_start = UntaggedObject::ToAddr(source_); uword current_ptr_addr = reinterpret_cast<uword>(current_ptr); intptr_t offset = current_ptr_addr - source_start; if (offset > 0 && offset < source_->untag()->HeapSize()) { ASSERT(Utils::IsAligned(offset, kWordSize)); *scratch_ = Smi::New(offset >> kWordSizeLog2); } else { // Some internal VM objects visit pointers not contained within the // parent. For instance, UntaggedCode::VisitCodePointers visits // pointers in instructions. ASSERT(!source_->IsDartInstance()); *scratch_ = Smi::New(-1); } references_.SetAt(offset_index, *scratch_); } ++length_; } } } private: ObjectPtr source_; ObjectPtr target_; const Array& references_; Object* scratch_; intptr_t length_; }; intptr_t ObjectGraph::InboundReferences(Object* obj, const Array& references) { Object& scratch = Object::Handle(); HeapIterationScope iteration(Thread::Current()); NoSafepointScope no_safepoint; InboundReferencesVisitor visitor(isolate(), obj->ptr(), references, &scratch); iteration.IterateObjects(&visitor); return visitor.length(); } // Each OldPage is divided into blocks of size kBlockSize. Each object belongs // to the block containing its header word. // When generating a heap snapshot, we assign objects sequential ids in heap // iteration order. A bitvector is computed that indicates the number of objects // in each block, so the id of any object in the block can be found be adding // the number of bits set before the object to the block's first id. // Compare ForwardingBlock used for heap compaction. class CountingBlock { public: void Clear() { base_count_ = 0; count_bitvector_ = 0; } intptr_t Lookup(uword addr) const { uword block_offset = addr & ~kBlockMask; intptr_t bitvector_shift = block_offset >> kObjectAlignmentLog2; ASSERT(bitvector_shift < kBitsPerWord); uword preceding_bitmask = (static_cast<uword>(1) << bitvector_shift) - 1; return base_count_ + Utils::CountOneBitsWord(count_bitvector_ & preceding_bitmask); } void Record(uword old_addr, intptr_t id) { if (base_count_ == 0) { ASSERT(count_bitvector_ == 0); base_count_ = id; // First object in the block. } uword block_offset = old_addr & ~kBlockMask; intptr_t bitvector_shift = block_offset >> kObjectAlignmentLog2; ASSERT(bitvector_shift < kBitsPerWord); count_bitvector_ |= static_cast<uword>(1) << bitvector_shift; } private: intptr_t base_count_; uword count_bitvector_; COMPILE_ASSERT(kBitVectorWordsPerBlock == 1); DISALLOW_COPY_AND_ASSIGN(CountingBlock); }; class CountingPage { public: void Clear() { for (intptr_t i = 0; i < kBlocksPerPage; i++) { blocks_[i].Clear(); } } intptr_t Lookup(uword addr) { return BlockFor(addr)->Lookup(addr); } void Record(uword addr, intptr_t id) { return BlockFor(addr)->Record(addr, id); } CountingBlock* BlockFor(uword addr) { intptr_t page_offset = addr & ~kOldPageMask; intptr_t block_number = page_offset / kBlockSize; ASSERT(block_number >= 0); ASSERT(block_number <= kBlocksPerPage); return &blocks_[block_number]; } private: CountingBlock blocks_[kBlocksPerPage]; DISALLOW_ALLOCATION(); DISALLOW_IMPLICIT_CONSTRUCTORS(CountingPage); }; void HeapSnapshotWriter::EnsureAvailable(intptr_t needed) { intptr_t available = capacity_ - size_; if (available >= needed) { return; } if (buffer_ != nullptr) { Flush(); } ASSERT(buffer_ == nullptr); intptr_t chunk_size = kPreferredChunkSize; if (chunk_size < needed + kMetadataReservation) { chunk_size = needed + kMetadataReservation; } buffer_ = reinterpret_cast<uint8_t*>(malloc(chunk_size)); size_ = kMetadataReservation; capacity_ = chunk_size; } void HeapSnapshotWriter::Flush(bool last) { if (size_ == 0 && !last) { return; } JSONStream js; { JSONObject jsobj(&js); jsobj.AddProperty("jsonrpc", "2.0"); jsobj.AddProperty("method", "streamNotify"); { JSONObject params(&jsobj, "params"); params.AddProperty("streamId", Service::heapsnapshot_stream.id()); { JSONObject event(&params, "event"); event.AddProperty("type", "Event"); event.AddProperty("kind", "HeapSnapshot"); event.AddProperty("isolate", thread()->isolate()); event.AddPropertyTimeMillis("timestamp", OS::GetCurrentTimeMillis()); event.AddProperty("last", last); } } } Service::SendEventWithData(Service::heapsnapshot_stream.id(), "HeapSnapshot", kMetadataReservation, js.buffer()->buffer(), js.buffer()->length(), buffer_, size_); buffer_ = nullptr; size_ = 0; capacity_ = 0; } void HeapSnapshotWriter::SetupCountingPages() { for (intptr_t i = 0; i < kMaxImagePages; i++) { image_page_ranges_[i].base = 0; image_page_ranges_[i].size = 0; } intptr_t next_offset = 0; OldPage* image_page = Dart::vm_isolate_group()->heap()->old_space()->image_pages_; while (image_page != NULL) { RELEASE_ASSERT(next_offset <= kMaxImagePages); image_page_ranges_[next_offset].base = image_page->object_start(); image_page_ranges_[next_offset].size = image_page->object_end() - image_page->object_start(); image_page = image_page->next(); next_offset++; } image_page = isolate_group()->heap()->old_space()->image_pages_; while (image_page != NULL) { RELEASE_ASSERT(next_offset <= kMaxImagePages); image_page_ranges_[next_offset].base = image_page->object_start(); image_page_ranges_[next_offset].size = image_page->object_end() - image_page->object_start(); image_page = image_page->next(); next_offset++; } OldPage* page = isolate_group()->heap()->old_space()->pages_; while (page != NULL) { page->forwarding_page(); CountingPage* counting_page = reinterpret_cast<CountingPage*>(page->forwarding_page()); ASSERT(counting_page != NULL); counting_page->Clear(); page = page->next(); } } bool HeapSnapshotWriter::OnImagePage(ObjectPtr obj) const { const uword addr = UntaggedObject::ToAddr(obj); for (intptr_t i = 0; i < kMaxImagePages; i++) { if ((addr - image_page_ranges_[i].base) < image_page_ranges_[i].size) { return true; } } return false; } CountingPage* HeapSnapshotWriter::FindCountingPage(ObjectPtr obj) const { if (obj->IsOldObject() && !OnImagePage(obj)) { // On a regular or large page. OldPage* page = OldPage::Of(obj); return reinterpret_cast<CountingPage*>(page->forwarding_page()); } // On an image page or in new space. return nullptr; } void HeapSnapshotWriter::AssignObjectId(ObjectPtr obj) { ASSERT(obj->IsHeapObject()); CountingPage* counting_page = FindCountingPage(obj); if (counting_page != nullptr) { // Likely: object on an ordinary page. counting_page->Record(UntaggedObject::ToAddr(obj), ++object_count_); } else { // Unlikely: new space object, or object on a large or image page. thread()->heap()->SetObjectId(obj, ++object_count_); } } intptr_t HeapSnapshotWriter::GetObjectId(ObjectPtr obj) const { if (!obj->IsHeapObject()) { return 0; } if (FLAG_write_protect_code && obj->IsInstructions() && !OnImagePage(obj)) { // A non-writable alias mapping may exist for instruction pages. obj = OldPage::ToWritable(obj); } CountingPage* counting_page = FindCountingPage(obj); intptr_t id; if (counting_page != nullptr) { // Likely: object on an ordinary page. id = counting_page->Lookup(UntaggedObject::ToAddr(obj)); } else { // Unlikely: new space object, or object on a large or image page. id = thread()->heap()->GetObjectId(obj); } ASSERT(id != 0); return id; } void HeapSnapshotWriter::ClearObjectIds() { thread()->heap()->ResetObjectIdTable(); } void HeapSnapshotWriter::CountReferences(intptr_t count) { reference_count_ += count; } void HeapSnapshotWriter::CountExternalProperty() { external_property_count_ += 1; } class Pass1Visitor : public ObjectVisitor, public ObjectPointerVisitor, public HandleVisitor { public: explicit Pass1Visitor(HeapSnapshotWriter* writer) : ObjectVisitor(), ObjectPointerVisitor(IsolateGroup::Current()), HandleVisitor(Thread::Current()), writer_(writer) {} virtual bool trace_values_through_fields() const { return true; } void VisitObject(ObjectPtr obj) { if (obj->IsPseudoObject()) return; writer_->AssignObjectId(obj); obj->untag()->VisitPointers(this); } void VisitPointers(ObjectPtr* from, ObjectPtr* to) { intptr_t count = to - from + 1; ASSERT(count >= 0); writer_->CountReferences(count); } void VisitHandle(uword addr) { FinalizablePersistentHandle* weak_persistent_handle = reinterpret_cast<FinalizablePersistentHandle*>(addr); if (!weak_persistent_handle->ptr()->IsHeapObject()) { return; // Free handle. } writer_->CountExternalProperty(); } private: HeapSnapshotWriter* const writer_; DISALLOW_COPY_AND_ASSIGN(Pass1Visitor); }; enum NonReferenceDataTags { kNoData = 0, kNullData, kBoolData, kIntData, kDoubleData, kLatin1Data, kUTF16Data, kLengthData, kNameData, }; static const intptr_t kMaxStringElements = 128; class Pass2Visitor : public ObjectVisitor, public ObjectPointerVisitor, public HandleVisitor { public: explicit Pass2Visitor(HeapSnapshotWriter* writer) : ObjectVisitor(), ObjectPointerVisitor(IsolateGroup::Current()), HandleVisitor(Thread::Current()), isolate_(thread()->isolate()), writer_(writer) {} virtual bool trace_values_through_fields() const { return true; } void VisitObject(ObjectPtr obj) { if (obj->IsPseudoObject()) return; intptr_t cid = obj->GetClassId(); writer_->WriteUnsigned(cid); writer_->WriteUnsigned(discount_sizes_ ? 0 : obj->untag()->HeapSize()); if (cid == kNullCid) { writer_->WriteUnsigned(kNullData); } else if (cid == kBoolCid) { writer_->WriteUnsigned(kBoolData); writer_->WriteUnsigned( static_cast<uintptr_t>(static_cast<BoolPtr>(obj)->untag()->value_)); } else if (cid == kSmiCid) { UNREACHABLE(); } else if (cid == kMintCid) { writer_->WriteUnsigned(kIntData); writer_->WriteSigned(static_cast<MintPtr>(obj)->untag()->value_); } else if (cid == kDoubleCid) { writer_->WriteUnsigned(kDoubleData); writer_->WriteBytes(&(static_cast<DoublePtr>(obj)->untag()->value_), sizeof(double)); } else if (cid == kOneByteStringCid) { OneByteStringPtr str = static_cast<OneByteStringPtr>(obj); intptr_t len = Smi::Value(str->untag()->length_); intptr_t trunc_len = Utils::Minimum(len, kMaxStringElements); writer_->WriteUnsigned(kLatin1Data); writer_->WriteUnsigned(len); writer_->WriteUnsigned(trunc_len); writer_->WriteBytes(&str->untag()->data()[0], trunc_len); } else if (cid == kExternalOneByteStringCid) { ExternalOneByteStringPtr str = static_cast<ExternalOneByteStringPtr>(obj); intptr_t len = Smi::Value(str->untag()->length_); intptr_t trunc_len = Utils::Minimum(len, kMaxStringElements); writer_->WriteUnsigned(kLatin1Data); writer_->WriteUnsigned(len); writer_->WriteUnsigned(trunc_len); writer_->WriteBytes(&str->untag()->external_data_[0], trunc_len); } else if (cid == kTwoByteStringCid) { TwoByteStringPtr str = static_cast<TwoByteStringPtr>(obj); intptr_t len = Smi::Value(str->untag()->length_); intptr_t trunc_len = Utils::Minimum(len, kMaxStringElements); writer_->WriteUnsigned(kUTF16Data); writer_->WriteUnsigned(len); writer_->WriteUnsigned(trunc_len); writer_->WriteBytes(&str->untag()->data()[0], trunc_len * 2); } else if (cid == kExternalTwoByteStringCid) { ExternalTwoByteStringPtr str = static_cast<ExternalTwoByteStringPtr>(obj); intptr_t len = Smi::Value(str->untag()->length_); intptr_t trunc_len = Utils::Minimum(len, kMaxStringElements); writer_->WriteUnsigned(kUTF16Data); writer_->WriteUnsigned(len); writer_->WriteUnsigned(trunc_len); writer_->WriteBytes(&str->untag()->external_data_[0], trunc_len * 2); } else if (cid == kArrayCid || cid == kImmutableArrayCid) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned( Smi::Value(static_cast<ArrayPtr>(obj)->untag()->length_)); } else if (cid == kGrowableObjectArrayCid) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned(Smi::Value( static_cast<GrowableObjectArrayPtr>(obj)->untag()->length_)); } else if (cid == kLinkedHashMapCid) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned( Smi::Value(static_cast<LinkedHashMapPtr>(obj)->untag()->used_data_)); } else if (cid == kObjectPoolCid) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned(static_cast<ObjectPoolPtr>(obj)->untag()->length_); } else if (IsTypedDataClassId(cid)) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned( Smi::Value(static_cast<TypedDataPtr>(obj)->untag()->length_)); } else if (IsExternalTypedDataClassId(cid)) { writer_->WriteUnsigned(kLengthData); writer_->WriteUnsigned( Smi::Value(static_cast<ExternalTypedDataPtr>(obj)->untag()->length_)); } else if (cid == kFunctionCid) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<FunctionPtr>(obj)->untag()->name_); } else if (cid == kCodeCid) { ObjectPtr owner = static_cast<CodePtr>(obj)->untag()->owner_; if (owner->IsFunction()) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<FunctionPtr>(owner)->untag()->name_); } else if (owner->IsClass()) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<ClassPtr>(owner)->untag()->name_); } else { writer_->WriteUnsigned(kNoData); } } else if (cid == kFieldCid) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<FieldPtr>(obj)->untag()->name_); } else if (cid == kClassCid) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<ClassPtr>(obj)->untag()->name_); } else if (cid == kLibraryCid) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<LibraryPtr>(obj)->untag()->url_); } else if (cid == kScriptCid) { writer_->WriteUnsigned(kNameData); ScrubAndWriteUtf8(static_cast<ScriptPtr>(obj)->untag()->url_); } else { writer_->WriteUnsigned(kNoData); } DoCount(); obj->untag()->VisitPointersPrecise(isolate_, this); DoWrite(); obj->untag()->VisitPointersPrecise(isolate_, this); } void ScrubAndWriteUtf8(StringPtr str) { if (str == String::null()) { writer_->WriteUtf8("null"); } else { String handle; handle = str; char* value = handle.ToMallocCString(); writer_->ScrubAndWriteUtf8(value); free(value); } } void set_discount_sizes(bool value) { discount_sizes_ = value; } void DoCount() { writing_ = false; counted_ = 0; written_ = 0; } void DoWrite() { writing_ = true; writer_->WriteUnsigned(counted_); } void VisitPointers(ObjectPtr* from, ObjectPtr* to) { if (writing_) { for (ObjectPtr* ptr = from; ptr <= to; ptr++) { ObjectPtr target = *ptr; written_++; total_++; writer_->WriteUnsigned(writer_->GetObjectId(target)); } } else { intptr_t count = to - from + 1; ASSERT(count >= 0); counted_ += count; } } void VisitHandle(uword addr) { FinalizablePersistentHandle* weak_persistent_handle = reinterpret_cast<FinalizablePersistentHandle*>(addr); if (!weak_persistent_handle->ptr()->IsHeapObject()) { return; // Free handle. } writer_->WriteUnsigned(writer_->GetObjectId(weak_persistent_handle->ptr())); writer_->WriteUnsigned(weak_persistent_handle->external_size()); // Attempt to include a native symbol name. auto const name = NativeSymbolResolver::LookupSymbolName( reinterpret_cast<uword>(weak_persistent_handle->callback()), nullptr); writer_->WriteUtf8((name == nullptr) ? "Unknown native function" : name); if (name != nullptr) { NativeSymbolResolver::FreeSymbolName(name); } } private: // TODO(dartbug.com/36097): Once the shared class table contains more // information than just the size (i.e. includes an immutable class // descriptor), we can remove this dependency on the current isolate. Isolate* isolate_; HeapSnapshotWriter* const writer_; bool writing_ = false; intptr_t counted_ = 0; intptr_t written_ = 0; intptr_t total_ = 0; bool discount_sizes_ = false; DISALLOW_COPY_AND_ASSIGN(Pass2Visitor); }; class Pass3Visitor : public ObjectVisitor { public: explicit Pass3Visitor(HeapSnapshotWriter* writer) : ObjectVisitor(), isolate_(Isolate::Current()), writer_(writer) {} void VisitObject(ObjectPtr obj) { if (obj->IsPseudoObject()) { return; } writer_->WriteUnsigned(GetHash(obj)); } private: uint32_t GetHash(ObjectPtr obj) { if (!obj->IsHeapObject()) return 0; intptr_t cid = obj->GetClassId(); uint32_t hash = 0; switch (cid) { case kForwardingCorpse: case kFreeListElement: case kSmiCid: UNREACHABLE(); case kArrayCid: case kBoolCid: case kCodeSourceMapCid: case kCompressedStackMapsCid: case kDoubleCid: case kExternalOneByteStringCid: case kExternalTwoByteStringCid: case kGrowableObjectArrayCid: case kImmutableArrayCid: case kInstructionsCid: case kInstructionsSectionCid: case kLinkedHashMapCid: case kMintCid: case kNeverCid: case kNullCid: case kObjectPoolCid: case kOneByteStringCid: case kPcDescriptorsCid: case kTwoByteStringCid: case kVoidCid: // Don't provide hash codes for objects with the above CIDs in order // to try and avoid having to initialize identity hash codes for common // primitives and types that don't have hash codes. break; default: { hash = GetHashHelper(obj); } } return hash; } uint32_t GetHashHelper(ObjectPtr obj) { uint32_t hash; #if defined(HASH_IN_OBJECT_HEADER) hash = Object::GetCachedHash(obj); if (hash == 0) { ASSERT( !isolate_->group()->heap()->old_space()->IsObjectFromImagePages(obj)); hash = isolate_->random()->NextUInt32(); Object::SetCachedHash(obj, hash); hash = Object::GetCachedHash(obj); } #else Heap* heap = isolate_->group()->heap(); hash = heap->GetHash(obj); if (hash == 0) { ASSERT(!heap->old_space()->IsObjectFromImagePages(obj)); heap->SetHash(obj, isolate_->random()->NextUInt32()); hash = heap->GetHash(obj); } #endif return hash; } // TODO(dartbug.com/36097): Once the shared class table contains more // information than just the size (i.e. includes an immutable class // descriptor), we can remove this dependency on the current isolate. Isolate* isolate_; HeapSnapshotWriter* const writer_; DISALLOW_COPY_AND_ASSIGN(Pass3Visitor); }; void HeapSnapshotWriter::Write() { HeapIterationScope iteration(thread()); WriteBytes("dartheap", 8); // Magic value. WriteUnsigned(0); // Flags. WriteUtf8(isolate()->name()); Heap* H = thread()->heap(); { intptr_t used = H->TotalUsedInWords() << kWordSizeLog2; intptr_t capacity = H->TotalCapacityInWords() << kWordSizeLog2; intptr_t external = H->TotalExternalInWords() << kWordSizeLog2; intptr_t image = H->old_space()->ImageInWords() << kWordSizeLog2; WriteUnsigned(used + image); WriteUnsigned(capacity + image); WriteUnsigned(external); } { HANDLESCOPE(thread()); ClassTable* class_table = isolate_group()->class_table(); class_count_ = class_table->NumCids() - 1; Class& cls = Class::Handle(); Library& lib = Library::Handle(); String& str = String::Handle(); Array& fields = Array::Handle(); Field& field = Field::Handle(); WriteUnsigned(class_count_); for (intptr_t cid = 1; cid <= class_count_; cid++) { if (!class_table->HasValidClassAt(cid)) { WriteUnsigned(0); // Flags WriteUtf8(""); // Name WriteUtf8(""); // Library name WriteUtf8(""); // Library uri WriteUtf8(""); // Reserved WriteUnsigned(0); // Field count } else { cls = class_table->At(cid); WriteUnsigned(0); // Flags str = cls.Name(); ScrubAndWriteUtf8(const_cast<char*>(str.ToCString())); lib = cls.library(); if (lib.IsNull()) { WriteUtf8(""); WriteUtf8(""); } else { str = lib.name(); ScrubAndWriteUtf8(const_cast<char*>(str.ToCString())); str = lib.url(); ScrubAndWriteUtf8(const_cast<char*>(str.ToCString())); } WriteUtf8(""); // Reserved intptr_t field_count = 0; intptr_t min_offset = kIntptrMax; for (intptr_t j = 0; OffsetsTable::offsets_table[j].class_id != -1; j++) { if (OffsetsTable::offsets_table[j].class_id == cid) { field_count++; intptr_t offset = OffsetsTable::offsets_table[j].offset; min_offset = Utils::Minimum(min_offset, offset); } } if (cls.is_finalized()) { do { fields = cls.fields(); if (!fields.IsNull()) { for (intptr_t i = 0; i < fields.Length(); i++) { field ^= fields.At(i); if (field.is_instance()) { field_count++; } } } cls = cls.SuperClass(); } while (!cls.IsNull()); cls = class_table->At(cid); } WriteUnsigned(field_count); for (intptr_t j = 0; OffsetsTable::offsets_table[j].class_id != -1; j++) { if (OffsetsTable::offsets_table[j].class_id == cid) { intptr_t flags = 1; // Strong. WriteUnsigned(flags); intptr_t offset = OffsetsTable::offsets_table[j].offset; intptr_t index = (offset - min_offset) / kWordSize; ASSERT(index >= 0); WriteUnsigned(index); WriteUtf8(OffsetsTable::offsets_table[j].field_name); WriteUtf8(""); // Reserved } } if (cls.is_finalized()) { do { fields = cls.fields(); if (!fields.IsNull()) { for (intptr_t i = 0; i < fields.Length(); i++) { field ^= fields.At(i); if (field.is_instance()) { intptr_t flags = 1; // Strong. WriteUnsigned(flags); intptr_t index = field.HostOffset() / kWordSize - 1; ASSERT(index >= 0); WriteUnsigned(index); str = field.name(); ScrubAndWriteUtf8(const_cast<char*>(str.ToCString())); WriteUtf8(""); // Reserved } } } cls = cls.SuperClass(); } while (!cls.IsNull()); cls = class_table->At(cid); } } } } SetupCountingPages(); { Pass1Visitor visitor(this); // Root "object". ++object_count_; isolate()->VisitObjectPointers(&visitor, ValidationPolicy::kDontValidateFrames); // Heap objects. iteration.IterateVMIsolateObjects(&visitor); iteration.IterateObjects(&visitor); // External properties. isolate()->group()->VisitWeakPersistentHandles(&visitor); } { Pass2Visitor visitor(this); WriteUnsigned(reference_count_); WriteUnsigned(object_count_); // Root "object". WriteUnsigned(0); // cid WriteUnsigned(0); // shallowSize WriteUnsigned(kNoData); visitor.DoCount(); isolate()->VisitObjectPointers(&visitor, ValidationPolicy::kDontValidateFrames); visitor.DoWrite(); isolate()->VisitObjectPointers(&visitor, ValidationPolicy::kDontValidateFrames); // Heap objects. visitor.set_discount_sizes(true); iteration.IterateVMIsolateObjects(&visitor); visitor.set_discount_sizes(false); iteration.IterateObjects(&visitor); // External properties. WriteUnsigned(external_property_count_); isolate()->group()->VisitWeakPersistentHandles(&visitor); } { // Identity hash codes Pass3Visitor visitor(this); // Handle root object. WriteUnsigned(0); // Handle visit rest of the objects. iteration.IterateVMIsolateObjects(&visitor); iteration.IterateObjects(&visitor); } ClearObjectIds(); Flush(true); } CountObjectsVisitor::CountObjectsVisitor(Thread* thread, intptr_t class_count) : ObjectVisitor(), HandleVisitor(thread), new_count_(new intptr_t[class_count]), new_size_(new intptr_t[class_count]), new_external_size_(new intptr_t[class_count]), old_count_(new intptr_t[class_count]), old_size_(new intptr_t[class_count]), old_external_size_(new intptr_t[class_count]) { memset(new_count_.get(), 0, class_count * sizeof(intptr_t)); memset(new_size_.get(), 0, class_count * sizeof(intptr_t)); memset(new_external_size_.get(), 0, class_count * sizeof(intptr_t)); memset(old_count_.get(), 0, class_count * sizeof(intptr_t)); memset(old_size_.get(), 0, class_count * sizeof(intptr_t)); memset(old_external_size_.get(), 0, class_count * sizeof(intptr_t)); } void CountObjectsVisitor::VisitObject(ObjectPtr obj) { intptr_t cid = obj->GetClassId(); intptr_t size = obj->untag()->HeapSize(); if (obj->IsNewObject()) { new_count_[cid] += 1; new_size_[cid] += size; } else { old_count_[cid] += 1; old_size_[cid] += size; } } void CountObjectsVisitor::VisitHandle(uword addr) { FinalizablePersistentHandle* handle = reinterpret_cast<FinalizablePersistentHandle*>(addr); ObjectPtr obj = handle->ptr(); if (!obj->IsHeapObject()) { return; } intptr_t cid = obj->GetClassId(); intptr_t size = handle->external_size(); if (obj->IsNewObject()) { new_external_size_[cid] += size; } else { old_external_size_[cid] += size; } } #endif // !defined(PRODUCT) } // namespace dart
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/core/subgraph_bridge_registry.h" #include "lite/kernels/npu/bridges/graph.h" #include "lite/kernels/npu/bridges/utility.h" namespace paddle { namespace lite { namespace subgraph { namespace npu { void CvtXYShape(std::vector<int64_t>* x_shape, std::vector<int64_t>* y_shape, int axis) { int x_shape_size = x_shape->size(); int y_shape_size = y_shape->size(); CHECK_GE(x_shape_size, y_shape_size); // only support: // 1. same shape // 2. (n,c,h,w) * (1,c,1,1) // 3. (n,c,h,w) * (n,c,1,1) // 4. (n,c,h,w) * (1,c,h,1) // 5. (n,c,h,w) * (1,c,h,w) // 6. (n,c,h,w) * (n,c,1,w) if (*x_shape == *y_shape) { *x_shape = CvtShape(*x_shape); *y_shape = CvtShape(*y_shape); return; } if (y_shape_size == 1) { for (int i = 0; i < 4 - x_shape_size; i++) { x_shape->push_back(1); } int64_t n = x_shape->at(0); int64_t c = x_shape->at(1); int64_t h = x_shape->at(2); int64_t w = x_shape->at(3); if (axis == 0) { *x_shape = std::vector<int64_t>{1, n, c * h * w, 1}; } else if (axis == 2) { *x_shape = std::vector<int64_t>{n * c, h, w, 1}; } else if (axis == 3) { *x_shape = std::vector<int64_t>{n * c * h, w, 1, 1}; } *y_shape = std::vector<int64_t>{1, y_shape->at(0), 1, 1}; return; } if (y_shape_size == 2) { for (int i = 0; i < 4 - x_shape_size; i++) { x_shape->push_back(1); } int64_t n = x_shape->at(0); int64_t c = x_shape->at(1); int64_t h = x_shape->at(2); int64_t w = x_shape->at(3); if (axis == 0) { y_shape->insert(y_shape->end(), 2, 1); } else if (axis == 1) { y_shape->insert(y_shape->begin(), 1); y_shape->insert(y_shape->end(), 1); } else if (axis == 2) { *x_shape = std::vector<int64_t>{n * c, h, w, 1}; y_shape->insert(y_shape->begin(), 1); y_shape->insert(y_shape->end(), 1); } return; } if (y_shape_size == 3) { y_shape->insert(y_shape->begin(), 1); int64_t n = x_shape->at(0); int64_t c = x_shape->at(1); int64_t h = x_shape->at(2); int64_t w = x_shape->at(3); if (axis == 0) { *x_shape = std::vector<int64_t>{1, n * c * h, w, 1}; *y_shape = std::vector<int64_t>{1, n * c * h, 1, 1}; } return; } } int ElementwiseConverter(void* ctx, OpLite* op, KernelBase* kernel) { CHECK(ctx != nullptr); CHECK(op != nullptr); auto graph = static_cast<Graph*>(ctx); auto op_info = op->op_info(); auto op_type = op_info->Type(); auto scope = op->scope(); VLOG(3) << "[NPU] Converting " + op_type + "..."; // Get input and output vars and op attributes auto x_name = op_info->Input("X").front(); auto x = scope->FindTensor(x_name); auto x_dims = x->dims(); auto y_name = op_info->Input("Y").front(); auto y = scope->FindTensor(y_name); auto y_dims = y->dims(); auto out_name = op_info->Output("Out").front(); auto out = scope->FindTensor(out_name); auto out_dims = out->dims(); auto axis = op_info->GetAttr<int>("axis"); if (axis < 0) { axis = x_dims.size() - y_dims.size(); } auto x_new_shape = x_dims.Vectorize(); auto y_new_shape = y_dims.Vectorize(); CvtXYShape(&x_new_shape, &y_new_shape, axis); // X node std::shared_ptr<Node> x_node = nullptr; if (graph->Has(x_name)) { x_node = graph->Get(x_name); auto reshaped_x_node = graph->Add<ge::op::Reshape>(x_name + "/reshape"); auto reshaped_x_op = reshaped_x_node->data<ge::op::Reshape>(); reshaped_x_op->set_input_tensor(*x_node->data()); reshaped_x_op->set_attr_shape( ge::AttrValue::LIST_INT(x_new_shape.begin(), x_new_shape.end())); reshaped_x_op->set_attr_axis(0); x_node = reshaped_x_node; } else { x_node = graph->Add(x_name, *x, x_new_shape); } // Y node std::shared_ptr<Node> y_node = nullptr; if (graph->Has(y_name)) { y_node = graph->Get(y_name); auto reshaped_y_node = graph->Add<ge::op::Reshape>(y_name + "/reshape"); auto reshaped_y_op = reshaped_y_node->data<ge::op::Reshape>(); reshaped_y_op->set_input_tensor(*y_node->data()); reshaped_y_op->set_attr_shape( ge::AttrValue::LIST_INT(y_new_shape.begin(), y_new_shape.end())); reshaped_y_op->set_attr_axis(0); y_node = reshaped_y_node; } else { y_node = graph->Add(y_name, *y, y_new_shape); } // Elementwise node std::shared_ptr<Node> elt_node = nullptr; if (op_type == "elementwise_add" || op_type == "fusion_elementwise_add_activation") { elt_node = graph->Add<ge::op::Add>(out_name); auto elt_op = elt_node->data<ge::op::Add>(); elt_op->set_input_x1(*x_node->data()); elt_op->set_input_x2(*y_node->data()); } else if (op_type == "elementwise_sub" || op_type == "fusion_elementwise_sub_activation") { elt_node = graph->Add<ge::op::Sub>(out_name); auto elt_op = elt_node->data<ge::op::Sub>(); elt_op->set_input_x1(*x_node->data()); elt_op->set_input_x2(*y_node->data()); } else if (op_type == "elementwise_mul" || op_type == "fusion_elementwise_mul_activation") { elt_node = graph->Add<ge::op::Mul>(out_name); auto elt_op = elt_node->data<ge::op::Mul>(); elt_op->set_input_x(*x_node->data()); elt_op->set_input_y(*y_node->data()); } else if (op_type == "elementwise_div" || op_type == "fusion_elementwise_div_activation") { elt_node = graph->Add<ge::op::RealDiv>(out_name); auto elt_op = elt_node->data<ge::op::RealDiv>(); elt_op->set_input_x1(*x_node->data()); elt_op->set_input_x2(*y_node->data()); } else { LOG(WARNING) << "[NPU] Unsupported op type: " << op_type; return FAILED; } auto out_shape = out_dims.Vectorize(); if (out_shape != x_new_shape) { auto reshaped_elt_node = graph->Add<ge::op::Reshape>(out_name); auto reshaped_elt_op = reshaped_elt_node->data<ge::op::Reshape>(); reshaped_elt_op->set_input_tensor(*elt_node->data()); reshaped_elt_op->set_attr_shape( ge::AttrValue::LIST_INT(out_shape.begin(), out_shape.end())); reshaped_elt_op->set_attr_axis(0); elt_node = reshaped_elt_node; } // Act node if (op_type == "fusion_elementwise_add_activation" || op_type == "fusion_elementwise_sub_activation" || op_type == "fusion_elementwise_mul_activation" || op_type == "fusion_elementwise_div_activation") { auto act_type = op_info->GetAttr<std::string>("act_type"); auto act_node = graph->Add<ge::op::Activation>(out_name); auto act_op = act_node->data<ge::op::Activation>(); act_op->set_input_x(*elt_node->data()); // TODO(hong19860320) set the coef value for act Ops, such as leaky_relu, // clipped_relu etc. act_op->set_attr_mode(CvtActMode(act_type)); } return REBUILD_WHEN_SHAPE_CHANGED; } } // namespace npu } // namespace subgraph } // namespace lite } // namespace paddle REGISTER_SUBGRAPH_BRIDGE(elementwise_add, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(elementwise_sub, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(elementwise_mul, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(elementwise_div, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(fusion_elementwise_add_activation, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(fusion_elementwise_sub_activation, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(fusion_elementwise_mul_activation, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE(fusion_elementwise_div_activation, kNPU, paddle::lite::subgraph::npu::ElementwiseConverter);
#include "t3_hosvd_test.hpp" #include "vmmlib/t3_hosvd.hpp" #include <sstream> namespace vmml { bool t3_hosvd_test::run() { bool global_ok = true; bool ok = false; double precision = 0.001; // hosvd test data after lathauwer et al. 2000a tensor3< 3, 3, 3, double > t3_data_hosvd; double data_hosvd[] = { 0.9073, 1.7842, 2.1236, 0.8924, 1.7753, -0.6631, 2.1488, 4.2495, 1.8260, 0.7158, 1.6970, -0.0704, -0.4898, -1.5077, 1.9103, 0.3054, 0.3207, 2.1335, -0.3698, 0.0151, 1.4429, 2.4288, 4.0337, -1.7495, 2.3753, 4.7146, -0.2716 }; t3_data_hosvd.set(data_hosvd, data_hosvd + 27); //prepare control data matrix< 3, 3, double > u1_hosvd; matrix< 3, 3, double > u2_hosvd; matrix< 3, 3, double > u3_hosvd; matrix< 3, 3, double > u1_hosvd_check; matrix< 3, 3, double > u2_hosvd_check; matrix< 3, 3, double > u3_hosvd_check; double data_u1_hosvd[] = { -0.1122204303093513, 0.7738508263292329, -0.6233469929427331, -0.5770542482332139, -0.5614452683822977, -0.5931168562830853, -0.8089591890924934, 0.293145201565186, 0.5095595364450776}; u1_hosvd_check.set( data_u1_hosvd, data_u1_hosvd + 9); double data_u2_hosvd[] = { -0.4624061014026708, 0.01022823125054092, 0.8866092604248326, -0.8866395226347692, -0.01338403108646822, -0.4622674816746957, 0.007138227200902682, -0.9998581154330659, 0.01525761170912346 }; u2_hosvd_check.set( data_u2_hosvd, data_u2_hosvd + 9); double data_u3_hosvd[] = { -0.6208224807897551, -0.498575577624314, -0.6049808598151153, 0.05741499780009954, -0.7985513947597073, 0.5991820991609654, -0.7818458705996144, 0.3372507425105363, 0.5243843736253236 }; u3_hosvd_check.set( data_u3_hosvd, data_u3_hosvd + 9); ///hosvd t3_hosvd< 3, 3, 3, 3, 3, 3, double >::hosvd( t3_data_hosvd, u1_hosvd, u2_hosvd, u3_hosvd ); if ( u1_hosvd.equals( u1_hosvd_check, precision ) && u2_hosvd.equals( u2_hosvd_check, precision ) && u3_hosvd.equals( u3_hosvd_check, precision )) { log( "HOSVD (3x3x3) compute factor matrices U1, U2, U3", true ); } else { std::stringstream error; error << "HOSVD (3x3x3): " << std::endl << "U1 should be: " << std::endl << u1_hosvd_check << std::endl << "U1 is: " << std::endl << u1_hosvd << std::endl << "U2 should be: " << std::endl << u2_hosvd_check << std::endl << "U2 is: " << std::endl << u2_hosvd << std::endl << "U3 should be: " << std::endl << u3_hosvd_check << std::endl << "U3 is: " << std::endl << u3_hosvd << std::endl; log_error( error.str() ); } //hosvd with test data from Lathauwer et al. 2000b (non-cubic) matrix< 3, 3, double > u1_2; matrix< 2, 2, double > u2_2; matrix< 2, 2, double > u3_2; matrix< 3, 3, double > u1_2_check; matrix< 2, 2, double > u2_2_check; matrix< 2, 2, double > u3_2_check; double data_u1_2[] = {-0.246452, 0.499323, 0.830625, 0.521727, -0.653918, 0.547898, 0.816738, 0.56839, -0.0993512}; u1_2_check.set( data_u1_2, data_u1_2 + 9); double data_u2_2[] = {0.171472, 0.985189, 0.985189, -0.171472}; u2_2_check.set( data_u2_2, data_u2_2 + 4); double data_u3_2[] = {-0.510464, 0.859899, 0.859899, 0.510464}; u3_2_check.set( data_u3_2, data_u3_2 + 4); double data_2[] = { 0, 1, 2, 3, 4, 5, -1, 4, -2, -5, 3, -6}; tensor3< 3, 2, 2, double > t3_data_2; t3_data_2.set(data_2, data_2 + 12); ///hosvd t3_hosvd< 3, 2, 2, 3, 2, 2, double >::hosvd( t3_data_2, u1_2, u2_2, u3_2 ); TEST(u1_2.equals( u1_2_check, precision ) && u2_2.equals( u2_2_check, precision ) && u3_2.equals( u3_2_check, precision )); if ( ok ) { log( "HOSVD (3x2x2) compute factor matrices U1, U2, U3", ok ); } else { std::stringstream error; error << "HOSVD (3x2x2): " << std::endl << "U1 should be: " << std::endl << u1_2_check << std::endl << "U1 is: " << std::endl << u1_2 << std::endl << "U2 should be: " << std::endl << u2_2_check << std::endl << "U2 is: " << std::endl << u2_2 << std::endl << "U3 should be: " << std::endl << u3_2_check << std::endl << "U3 is: " << std::endl << u3_2 << std::endl; log_error( error.str() ); } //hoeigs test u1_hosvd.zero(); u2_hosvd.zero(); u3_hosvd.zero(); matrix<3, 3, double> u1_hoeigs_check; matrix<3, 3, double> u2_hoeigs_check; matrix<3, 3, double> u3_hoeigs_check; double data_u1_hoeigs[] = { 0.1122204363, 0.7738507986, -0.623347044, 0.5770543218, -0.5614452958, -0.5931168199, 0.8089591861, 0.2931452692, 0.5095595717}; u1_hoeigs_check.set( data_u1_hoeigs, data_u1_hoeigs + 9); double data_u2_hoeigs[] = { -0.4624060392, -0.01022823341, 0.8866092563, -0.886639595, 0.01338403113, -0.4622673988, 0.007138226647, 0.9998582006, 0.01525761187 }; u2_hoeigs_check.set( data_u2_hoeigs, data_u2_hoeigs + 9); double data_u3_hoeigs[] = { 0.6208223701, 0.4985756576, 0.6049809456, -0.05741500854, 0.7985514402, -0.5991820693, 0.7818458676, -0.3372507095, -0.524384439 }; u3_hoeigs_check.set( data_u3_hoeigs, data_u3_hoeigs + 9); t3_hosvd< 3, 3, 3, 3, 3, 3, double >::hoeigs( t3_data_hosvd, u1_hosvd, u2_hosvd, u3_hosvd ); TEST(u1_hosvd.equals( u1_hoeigs_check, precision ) && u2_hosvd.equals( u2_hoeigs_check, precision ) && u3_hosvd.equals( u3_hoeigs_check, precision )); if (ok) { log( "HOEIGS compute factor matrices U1, U2, U3", true ); } else { std::stringstream error; error << "HOEIGS: " << std::endl << "U1 should be: " << std::endl << u1_hoeigs_check << std::endl << "U1 is: " << std::endl << u1_hosvd << std::endl << "U2 should be: " << std::endl << u2_hoeigs_check << std::endl << "U2 is: " << std::endl << u2_hosvd << std::endl << "U3 should be: " << std::endl << u3_hoeigs_check << std::endl << "U3 is: " << std::endl << u3_hosvd << std::endl; log_error( error.str() ); } return global_ok; } } //end vmml namespace
/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/test/RouteScaleGenerators.h" #include "fboss/agent/test/ResourceLibUtil.h" #include "fboss/agent/state/Port.h" #include "fboss/agent/state/SwitchState.h" #include "fboss/agent/test/EcmpSetupHelper.h" namespace facebook::fboss::utility { /* * RSW distribution was discussed here * https://fb.workplace.com/groups/266410803370065/permalink/3170120682999048/ * There are 2 changes to this distritbution here. * i) We found /128 did not factor in pod local RSW loopbacks. So /128 should * have been 49 instead of 1. To give some room, I have doubled them to be 100. * ii) We increased static routes for ILA/IP per task from 384 to 1024 as part * of S185053, so upping the scale limits here too. */ RSWRouteScaleGenerator::RSWRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, // v6 distribution { {46, 96}, {54, 624}, {66, 96}, {57, 16}, {59, 96}, {60, 96}, {64, 3718}, {127, 128}, {128, 100}, }, // v4 distribution { {19, 80}, {24, 592}, {26, 1}, {31, 128}, {32, 2176}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId) {} FSWRouteScaleGenerator::FSWRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, // v6 distribution { {48, 100}, {52, 200}, {56, 100}, {64, 3550}, {80, 300}, {96, 200}, {112, 100}, {127, 100}, {128, 3350}, }, // v4 distribution { {15, 200}, {24, 2000}, {26, 1000}, {28, 200}, {31, 100}, {32, 4500}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId) {} THAlpmRouteScaleGenerator::THAlpmRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, // v6 distribution { {48, 200}, {52, 200}, {56, 200}, {64, 10000}, {80, 200}, {96, 200}, {112, 200}, {120, 200}, {128, 10000}, }, // v4 distribution { {15, 400}, {24, 400}, {26, 400}, {28, 400}, {30, 400}, {32, 10000}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId) {} HgridDuRouteScaleGenerator::HgridDuRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, // v6 distribution { {37, 8}, {47, 8}, {46, 768}, {52, 256}, {54, 1}, {56, 768}, {57, 2}, {59, 768}, {60, 768}, {64, 16344}, {127, 128}, {128, 1}, }, // v4 distribution { {19, 1}, {24, 99}, {26, 96}, {27, 384}, {31, 128}, {32, 16721}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId) {} HgridUuRouteScaleGenerator::HgridUuRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, // v6 distribution { {127, 128}, {128, 1226}, {24, 1}, {37, 37}, {44, 18}, {46, 1048}, {47, 8}, {48, 25}, {52, 304}, {54, 16}, {56, 768}, {57, 136}, {59, 770}, {60, 783}, {61, 28}, {62, 240}, {63, 2091}, {64, 23393}, }, // v4 distribution { {19, 8}, {21, 1}, {24, 152}, {27, 416}, {31, 128}, {32, 16625}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId) {} TurboFSWRouteScaleGenerator::TurboFSWRouteScaleGenerator( const std::shared_ptr<SwitchState>& startingState, bool isStandaloneRibEnabled, unsigned int chunkSize, unsigned int ecmpWidth, RouterID routerId) : RouteDistributionGenerator( startingState, { // ip2ip routes. There may not be any in turbo fabric // adding few just to test the code. {46, 12}, {56, 12}, {64, 12}, {128, 11}, }, // v4 distribution { {26, 11}, {32, 11}, }, isStandaloneRibEnabled, chunkSize, ecmpWidth, routerId), // V6 Routes per label path v6PrefixLabelDistributionSpec_({ // mapping from prefix len to // {numlabelledRoutes, numRoutesPerLabel, startingLabel} // // 11 pods within mesh + 84 pods outside mesh {46, {95, 8, 100}}, // 11 interpod + 1 spine = 12 ECMP paths share routes // 11 pods within mesh + 84 pods outside mesh {56, {95, 8, 100}}, // 11 interpod + 1 spine = 12 ECMP paths share routes // 11 pods within mesh + 3750 VIP routes {64, {3761, 376, 200}}, // 10 spine ECMP NHs in link failure cases. // In steady state, the routes will resolve // over a single ECMP NH {128, {11, 1, 300}}, // 11 spines }), // V4 Routes per label path // 11 /26 for interpod + 3750 VIP routes v4PrefixLabelDistributionSpec_( {{26, {11, 1, 500}}, {32, {3761, 376, 600}}}) { boost::container::flat_set<PortDescriptor> allPorts; for (auto port : *startingState->getPorts()) { if (!port->isEnabled()) { continue; } allPorts.insert(PortDescriptor(port->getID())); } CHECK_GE(allPorts.size(), ecmpWidth); size_t unlabeledPortsSize = ecmpWidth - 32; for (auto i = 0; i < ecmpWidth; i++) { auto iPortId = *(allPorts.begin() + i); if (i < unlabeledPortsSize) { unlabeledPorts_.insert(iPortId); } else { labeledPorts_.insert(iPortId); } } } template <typename AddrT> void TurboFSWRouteScaleGenerator::genIp2MplsRouteDistribution( const MaskLen2PrefixLabelDistribution& labelDistributionSpec, const boost::container::flat_set<PortDescriptor>& labeledPorts) const { using PrefixT = RoutePrefix<AddrT>; std::vector<PrefixT> prefixes; EcmpSetupTargetedPorts<AddrT> ecmpHelper(startingState()); for (const auto& prefixLabelDistribution : labelDistributionSpec) { uint8_t prefixSize = prefixLabelDistribution.first; uint32_t numRoutes = prefixLabelDistribution.second.totalPrefixes; uint32_t chunkSize = prefixLabelDistribution.second.chunkSize; uint32_t labelForChunk = prefixLabelDistribution.second.startingLabel; auto prefixGenerator = PrefixGenerator<AddrT>(prefixSize); while (numRoutes) { int label = labelForChunk; for (auto j = 0; j < chunkSize && numRoutes > 0; ++j, numRoutes--) { const auto cidrNetwork = getNewPrefix( prefixGenerator, startingState(), getRouterID(), isStandaloneRibEnabled()); if constexpr (std::is_same<folly::IPAddressV6, AddrT>::value) { prefixes.emplace_back( RoutePrefix<AddrT>{cidrNetwork.first.asV6(), cidrNetwork.second}); } else { prefixes.emplace_back( RoutePrefix<AddrT>{cidrNetwork.first.asV4(), cidrNetwork.second}); } } // b19 is always 1, b18 identifies IP version if constexpr (std::is_same<folly::IPAddressV6, AddrT>::value) { label = 0x3 << 18 | ((0xff & label) << 10); } else { label = 0x2 << 18 | ((0xff & label) << 10); } std::map<PortDescriptor, LabelForwardingAction::LabelStack> labels{}; for (auto i = 0; i < labeledPorts.size(); i++) { auto labeledPort = *(labeledPorts.begin() + i); LabelForwardingAction::LabelStack stack{ label + static_cast<int>(labeledPort.phyPortID())}; labels.emplace(labeledPort, stack); } RouteChunk routeChunk; for (auto& prefix : prefixes) { Route route; route.prefix = prefix.toCidrNetwork(); // create ucmp with 1:3 weight distribution for labelled paths for (auto port : unlabeledPorts_) { UnresolvedNextHop nhop(ecmpHelper.ip(port), ECMP_WEIGHT); route.nhops.push_back(nhop); } for (auto port : labeledPorts_) { UnresolvedNextHop nhop( ecmpHelper.ip(port), 3, LabelForwardingAction( LabelForwardingAction::LabelForwardingType::PUSH, labels.find(port)->second)); route.nhops.push_back(nhop); } routeChunk.push_back(route); } generatedRouteChunks_->push_back(routeChunk); labelForChunk++; prefixes.clear(); } } } void TurboFSWRouteScaleGenerator::genRoutes() const { if (generatedRouteChunks_) { return; } // Add ip2ip routes RouteDistributionGenerator::genRoutes(); // Add v6 labelled routes genIp2MplsRouteDistribution<folly::IPAddressV6>( v6PrefixLabelDistributionSpec_, labeledPorts_); // Add v4 labelled routes genIp2MplsRouteDistribution<folly::IPAddressV4>( v4PrefixLabelDistributionSpec_, labeledPorts_); } std::shared_ptr<SwitchState> TurboFSWRouteScaleGenerator::resolveNextHops( std::shared_ptr<SwitchState> in) const { auto ecmpHelper4 = EcmpSetupTargetedPorts4(in); auto ecmpHelper6 = EcmpSetupTargetedPorts6(in); auto nhopsResolvedState = ecmpHelper6.resolveNextHops(in, unlabeledPorts_); nhopsResolvedState = ecmpHelper6.resolveNextHops(nhopsResolvedState, labeledPorts_); nhopsResolvedState = ecmpHelper4.resolveNextHops(nhopsResolvedState, unlabeledPorts_); nhopsResolvedState = ecmpHelper4.resolveNextHops(nhopsResolvedState, labeledPorts_); return nhopsResolvedState; } bool TurboFSWRouteScaleGenerator::isSupported(PlatformMode mode) const { return ( mode == PlatformMode::MINIPACK || mode == PlatformMode::YAMP || mode == PlatformMode::FUJI || mode == PlatformMode::ELBERT); } } // namespace facebook::fboss::utility
class Solution { public: int minMoves2(vector<int>& nums) { const int inf = 1e9; sort(nums.begin(), nums.end()); int mid = 0; long long ans = 0, _min = 0; int len = nums.size(); if (len % 2) { mid = nums[len / 2]; for (auto& v : nums) ans += abs(v - mid); } else { mid = nums[(len / 2) - 1] + nums[len / 2]; mid /= 2; for (auto& v : nums) ans += abs(v - mid); mid++; for (auto& v : nums) _min += abs(v - mid); ans = min(ans, _min); } return ans; } };
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/codegen/assembler-inl.h" #include "src/compiler/backend/instruction-selector-impl.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties.h" namespace v8 { namespace internal { namespace compiler { enum ImmediateMode { kArithmeticImm, // 12 bit unsigned immediate shifted left 0 or 12 bits kShift32Imm, // 0 - 31 kShift64Imm, // 0 - 63 kLogical32Imm, kLogical64Imm, kLoadStoreImm8, // signed 8 bit or 12 bit unsigned scaled by access size kLoadStoreImm16, kLoadStoreImm32, kLoadStoreImm64, kNoImmediate }; // Adds Arm64-specific methods for generating operands. class Arm64OperandGenerator final : public OperandGenerator { public: explicit Arm64OperandGenerator(InstructionSelector* selector) : OperandGenerator(selector) {} InstructionOperand UseOperand(Node* node, ImmediateMode mode) { if (CanBeImmediate(node, mode)) { return UseImmediate(node); } return UseRegister(node); } // Use the zero register if the node has the immediate value zero, otherwise // assign a register. InstructionOperand UseRegisterOrImmediateZero(Node* node) { if ((IsIntegerConstant(node) && (GetIntegerConstantValue(node) == 0)) || (IsFloatConstant(node) && (bit_cast<int64_t>(GetFloatConstantValue(node)) == 0))) { return UseImmediate(node); } return UseRegister(node); } // Use the provided node if it has the required value, or create a // TempImmediate otherwise. InstructionOperand UseImmediateOrTemp(Node* node, int32_t value) { if (GetIntegerConstantValue(node) == value) { return UseImmediate(node); } return TempImmediate(value); } bool IsIntegerConstant(Node* node) { return (node->opcode() == IrOpcode::kInt32Constant) || (node->opcode() == IrOpcode::kInt64Constant); } int64_t GetIntegerConstantValue(Node* node) { if (node->opcode() == IrOpcode::kInt32Constant) { return OpParameter<int32_t>(node->op()); } DCHECK_EQ(IrOpcode::kInt64Constant, node->opcode()); return OpParameter<int64_t>(node->op()); } bool IsFloatConstant(Node* node) { return (node->opcode() == IrOpcode::kFloat32Constant) || (node->opcode() == IrOpcode::kFloat64Constant); } double GetFloatConstantValue(Node* node) { if (node->opcode() == IrOpcode::kFloat32Constant) { return OpParameter<float>(node->op()); } DCHECK_EQ(IrOpcode::kFloat64Constant, node->opcode()); return OpParameter<double>(node->op()); } bool CanBeImmediate(Node* node, ImmediateMode mode) { return IsIntegerConstant(node) && CanBeImmediate(GetIntegerConstantValue(node), mode); } bool CanBeImmediate(int64_t value, ImmediateMode mode) { unsigned ignored; switch (mode) { case kLogical32Imm: // TODO(dcarney): some unencodable values can be handled by // switching instructions. return Assembler::IsImmLogical(static_cast<uint64_t>(value), 32, &ignored, &ignored, &ignored); case kLogical64Imm: return Assembler::IsImmLogical(static_cast<uint64_t>(value), 64, &ignored, &ignored, &ignored); case kArithmeticImm: return Assembler::IsImmAddSub(value); case kLoadStoreImm8: return IsLoadStoreImmediate(value, 0); case kLoadStoreImm16: return IsLoadStoreImmediate(value, 1); case kLoadStoreImm32: return IsLoadStoreImmediate(value, 2); case kLoadStoreImm64: return IsLoadStoreImmediate(value, 3); case kNoImmediate: return false; case kShift32Imm: // Fall through. case kShift64Imm: // Shift operations only observe the bottom 5 or 6 bits of the value. // All possible shifts can be encoded by discarding bits which have no // effect. return true; } return false; } bool CanBeLoadStoreShiftImmediate(Node* node, MachineRepresentation rep) { // TODO(arm64): Load and Store on 128 bit Q registers is not supported yet. DCHECK_GT(MachineRepresentation::kSimd128, rep); return IsIntegerConstant(node) && (GetIntegerConstantValue(node) == ElementSizeLog2Of(rep)); } private: bool IsLoadStoreImmediate(int64_t value, unsigned size) { return Assembler::IsImmLSScaled(value, size) || Assembler::IsImmLSUnscaled(value); } }; namespace { void VisitRR(InstructionSelector* selector, ArchOpcode opcode, Node* node) { Arm64OperandGenerator g(selector); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0))); } void VisitRRR(InstructionSelector* selector, ArchOpcode opcode, Node* node) { Arm64OperandGenerator g(selector); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1))); } void VisitSimdShiftRRR(InstructionSelector* selector, ArchOpcode opcode, Node* node) { Arm64OperandGenerator g(selector); InstructionOperand temps[] = {g.TempSimd128Register(), g.TempRegister()}; selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)), arraysize(temps), temps); } void VisitRRI(InstructionSelector* selector, ArchOpcode opcode, Node* node) { Arm64OperandGenerator g(selector); int32_t imm = OpParameter<int32_t>(node->op()); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseImmediate(imm)); } void VisitRRO(InstructionSelector* selector, ArchOpcode opcode, Node* node, ImmediateMode operand_mode) { Arm64OperandGenerator g(selector); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseOperand(node->InputAt(1), operand_mode)); } void VisitRRIR(InstructionSelector* selector, ArchOpcode opcode, Node* node) { Arm64OperandGenerator g(selector); int32_t imm = OpParameter<int32_t>(node->op()); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseImmediate(imm), g.UseRegister(node->InputAt(1))); } struct ExtendingLoadMatcher { ExtendingLoadMatcher(Node* node, InstructionSelector* selector) : matches_(false), selector_(selector), base_(nullptr), immediate_(0) { Initialize(node); } bool Matches() const { return matches_; } Node* base() const { DCHECK(Matches()); return base_; } int64_t immediate() const { DCHECK(Matches()); return immediate_; } ArchOpcode opcode() const { DCHECK(Matches()); return opcode_; } private: bool matches_; InstructionSelector* selector_; Node* base_; int64_t immediate_; ArchOpcode opcode_; void Initialize(Node* node) { Int64BinopMatcher m(node); // When loading a 64-bit value and shifting by 32, we should // just load and sign-extend the interesting 4 bytes instead. // This happens, for example, when we're loading and untagging SMIs. DCHECK(m.IsWord64Sar()); if (m.left().IsLoad() && m.right().Is(32) && selector_->CanCover(m.node(), m.left().node())) { Arm64OperandGenerator g(selector_); Node* load = m.left().node(); Node* offset = load->InputAt(1); base_ = load->InputAt(0); opcode_ = kArm64Ldrsw; if (g.IsIntegerConstant(offset)) { immediate_ = g.GetIntegerConstantValue(offset) + 4; matches_ = g.CanBeImmediate(immediate_, kLoadStoreImm32); } } } }; bool TryMatchExtendingLoad(InstructionSelector* selector, Node* node) { ExtendingLoadMatcher m(node, selector); return m.Matches(); } bool TryEmitExtendingLoad(InstructionSelector* selector, Node* node) { ExtendingLoadMatcher m(node, selector); Arm64OperandGenerator g(selector); if (m.Matches()) { InstructionOperand inputs[2]; inputs[0] = g.UseRegister(m.base()); InstructionCode opcode = m.opcode() | AddressingModeField::encode(kMode_MRI); DCHECK(is_int32(m.immediate())); inputs[1] = g.TempImmediate(static_cast<int32_t>(m.immediate())); InstructionOperand outputs[] = {g.DefineAsRegister(node)}; selector->Emit(opcode, arraysize(outputs), outputs, arraysize(inputs), inputs); return true; } return false; } bool TryMatchAnyShift(InstructionSelector* selector, Node* node, Node* input_node, InstructionCode* opcode, bool try_ror) { Arm64OperandGenerator g(selector); if (!selector->CanCover(node, input_node)) return false; if (input_node->InputCount() != 2) return false; if (!g.IsIntegerConstant(input_node->InputAt(1))) return false; switch (input_node->opcode()) { case IrOpcode::kWord32Shl: case IrOpcode::kWord64Shl: *opcode |= AddressingModeField::encode(kMode_Operand2_R_LSL_I); return true; case IrOpcode::kWord32Shr: case IrOpcode::kWord64Shr: *opcode |= AddressingModeField::encode(kMode_Operand2_R_LSR_I); return true; case IrOpcode::kWord32Sar: *opcode |= AddressingModeField::encode(kMode_Operand2_R_ASR_I); return true; case IrOpcode::kWord64Sar: if (TryMatchExtendingLoad(selector, input_node)) return false; *opcode |= AddressingModeField::encode(kMode_Operand2_R_ASR_I); return true; case IrOpcode::kWord32Ror: case IrOpcode::kWord64Ror: if (try_ror) { *opcode |= AddressingModeField::encode(kMode_Operand2_R_ROR_I); return true; } return false; default: return false; } } bool TryMatchAnyExtend(Arm64OperandGenerator* g, InstructionSelector* selector, Node* node, Node* left_node, Node* right_node, InstructionOperand* left_op, InstructionOperand* right_op, InstructionCode* opcode) { if (!selector->CanCover(node, right_node)) return false; NodeMatcher nm(right_node); if (nm.IsWord32And()) { Int32BinopMatcher mright(right_node); if (mright.right().Is(0xFF) || mright.right().Is(0xFFFF)) { int32_t mask = mright.right().Value(); *left_op = g->UseRegister(left_node); *right_op = g->UseRegister(mright.left().node()); *opcode |= AddressingModeField::encode( (mask == 0xFF) ? kMode_Operand2_R_UXTB : kMode_Operand2_R_UXTH); return true; } } else if (nm.IsWord32Sar()) { Int32BinopMatcher mright(right_node); if (selector->CanCover(mright.node(), mright.left().node()) && mright.left().IsWord32Shl()) { Int32BinopMatcher mleft_of_right(mright.left().node()); if ((mright.right().Is(16) && mleft_of_right.right().Is(16)) || (mright.right().Is(24) && mleft_of_right.right().Is(24))) { int32_t shift = mright.right().Value(); *left_op = g->UseRegister(left_node); *right_op = g->UseRegister(mleft_of_right.left().node()); *opcode |= AddressingModeField::encode( (shift == 24) ? kMode_Operand2_R_SXTB : kMode_Operand2_R_SXTH); return true; } } } return false; } bool TryMatchLoadStoreShift(Arm64OperandGenerator* g, InstructionSelector* selector, MachineRepresentation rep, Node* node, Node* index, InstructionOperand* index_op, InstructionOperand* shift_immediate_op) { if (!selector->CanCover(node, index)) return false; if (index->InputCount() != 2) return false; Node* left = index->InputAt(0); Node* right = index->InputAt(1); switch (index->opcode()) { case IrOpcode::kWord32Shl: case IrOpcode::kWord64Shl: if (!g->CanBeLoadStoreShiftImmediate(right, rep)) { return false; } *index_op = g->UseRegister(left); *shift_immediate_op = g->UseImmediate(right); return true; default: return false; } } // Bitfields describing binary operator properties: // CanCommuteField is true if we can switch the two operands, potentially // requiring commuting the flags continuation condition. using CanCommuteField = BitField8<bool, 1, 1>; // MustCommuteCondField is true when we need to commute the flags continuation // condition in order to switch the operands. using MustCommuteCondField = BitField8<bool, 2, 1>; // IsComparisonField is true when the operation is a comparison and has no other // result other than the condition. using IsComparisonField = BitField8<bool, 3, 1>; // IsAddSubField is true when an instruction is encoded as ADD or SUB. using IsAddSubField = BitField8<bool, 4, 1>; // Get properties of a binary operator. uint8_t GetBinopProperties(InstructionCode opcode) { uint8_t result = 0; switch (opcode) { case kArm64Cmp32: case kArm64Cmp: // We can commute CMP by switching the inputs and commuting // the flags continuation. result = CanCommuteField::update(result, true); result = MustCommuteCondField::update(result, true); result = IsComparisonField::update(result, true); // The CMP and CMN instructions are encoded as SUB or ADD // with zero output register, and therefore support the same // operand modes. result = IsAddSubField::update(result, true); break; case kArm64Cmn32: case kArm64Cmn: result = CanCommuteField::update(result, true); result = IsComparisonField::update(result, true); result = IsAddSubField::update(result, true); break; case kArm64Add32: case kArm64Add: result = CanCommuteField::update(result, true); result = IsAddSubField::update(result, true); break; case kArm64Sub32: case kArm64Sub: result = IsAddSubField::update(result, true); break; case kArm64Tst32: case kArm64Tst: result = CanCommuteField::update(result, true); result = IsComparisonField::update(result, true); break; case kArm64And32: case kArm64And: case kArm64Or32: case kArm64Or: case kArm64Eor32: case kArm64Eor: result = CanCommuteField::update(result, true); break; default: UNREACHABLE(); } DCHECK_IMPLIES(MustCommuteCondField::decode(result), CanCommuteField::decode(result)); return result; } // Shared routine for multiple binary operations. template <typename Matcher> void VisitBinop(InstructionSelector* selector, Node* node, InstructionCode opcode, ImmediateMode operand_mode, FlagsContinuation* cont) { Arm64OperandGenerator g(selector); InstructionOperand inputs[3]; size_t input_count = 0; InstructionOperand outputs[1]; size_t output_count = 0; Node* left_node = node->InputAt(0); Node* right_node = node->InputAt(1); uint8_t properties = GetBinopProperties(opcode); bool can_commute = CanCommuteField::decode(properties); bool must_commute_cond = MustCommuteCondField::decode(properties); bool is_add_sub = IsAddSubField::decode(properties); if (g.CanBeImmediate(right_node, operand_mode)) { inputs[input_count++] = g.UseRegister(left_node); inputs[input_count++] = g.UseImmediate(right_node); } else if (can_commute && g.CanBeImmediate(left_node, operand_mode)) { if (must_commute_cond) cont->Commute(); inputs[input_count++] = g.UseRegister(right_node); inputs[input_count++] = g.UseImmediate(left_node); } else if (is_add_sub && TryMatchAnyExtend(&g, selector, node, left_node, right_node, &inputs[0], &inputs[1], &opcode)) { input_count += 2; } else if (is_add_sub && can_commute && TryMatchAnyExtend(&g, selector, node, right_node, left_node, &inputs[0], &inputs[1], &opcode)) { if (must_commute_cond) cont->Commute(); input_count += 2; } else if (TryMatchAnyShift(selector, node, right_node, &opcode, !is_add_sub)) { Matcher m_shift(right_node); inputs[input_count++] = g.UseRegisterOrImmediateZero(left_node); inputs[input_count++] = g.UseRegister(m_shift.left().node()); // We only need at most the last 6 bits of the shift. inputs[input_count++] = g.UseImmediate(static_cast<int>(m_shift.right().Value() & 0x3F)); } else if (can_commute && TryMatchAnyShift(selector, node, left_node, &opcode, !is_add_sub)) { if (must_commute_cond) cont->Commute(); Matcher m_shift(left_node); inputs[input_count++] = g.UseRegisterOrImmediateZero(right_node); inputs[input_count++] = g.UseRegister(m_shift.left().node()); // We only need at most the last 6 bits of the shift. inputs[input_count++] = g.UseImmediate(static_cast<int>(m_shift.right().Value() & 0x3F)); } else { inputs[input_count++] = g.UseRegisterOrImmediateZero(left_node); inputs[input_count++] = g.UseRegister(right_node); } if (!IsComparisonField::decode(properties)) { outputs[output_count++] = g.DefineAsRegister(node); } DCHECK_NE(0u, input_count); DCHECK((output_count != 0) || IsComparisonField::decode(properties)); DCHECK_GE(arraysize(inputs), input_count); DCHECK_GE(arraysize(outputs), output_count); selector->EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, cont); } // Shared routine for multiple binary operations. template <typename Matcher> void VisitBinop(InstructionSelector* selector, Node* node, ArchOpcode opcode, ImmediateMode operand_mode) { FlagsContinuation cont; VisitBinop<Matcher>(selector, node, opcode, operand_mode, &cont); } template <typename Matcher> void VisitAddSub(InstructionSelector* selector, Node* node, ArchOpcode opcode, ArchOpcode negate_opcode) { Arm64OperandGenerator g(selector); Matcher m(node); if (m.right().HasValue() && (m.right().Value() < 0) && (m.right().Value() > std::numeric_limits<int>::min()) && g.CanBeImmediate(-m.right().Value(), kArithmeticImm)) { selector->Emit(negate_opcode, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.TempImmediate(static_cast<int32_t>(-m.right().Value()))); } else { VisitBinop<Matcher>(selector, node, opcode, kArithmeticImm); } } // For multiplications by immediate of the form x * (2^k + 1), where k > 0, // return the value of k, otherwise return zero. This is used to reduce the // multiplication to addition with left shift: x + (x << k). template <typename Matcher> int32_t LeftShiftForReducedMultiply(Matcher* m) { DCHECK(m->IsInt32Mul() || m->IsInt64Mul()); if (m->right().HasValue() && m->right().Value() >= 3) { uint64_t value_minus_one = m->right().Value() - 1; if (base::bits::IsPowerOfTwo(value_minus_one)) { return WhichPowerOf2(value_minus_one); } } return 0; } } // namespace void InstructionSelector::VisitStackSlot(Node* node) { StackSlotRepresentation rep = StackSlotRepresentationOf(node->op()); int slot = frame_->AllocateSpillSlot(rep.size()); OperandGenerator g(this); Emit(kArchStackSlot, g.DefineAsRegister(node), sequence()->AddImmediate(Constant(slot)), 0, nullptr); } void InstructionSelector::VisitAbortCSAAssert(Node* node) { Arm64OperandGenerator g(this); Emit(kArchAbortCSAAssert, g.NoOutput(), g.UseFixed(node->InputAt(0), x1)); } void EmitLoad(InstructionSelector* selector, Node* node, InstructionCode opcode, ImmediateMode immediate_mode, MachineRepresentation rep, Node* output = nullptr) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); InstructionOperand inputs[3]; size_t input_count = 0; InstructionOperand outputs[1]; // If output is not nullptr, use that as the output register. This // is used when we merge a conversion into the load. outputs[0] = g.DefineAsRegister(output == nullptr ? node : output); ExternalReferenceMatcher m(base); if (m.HasValue() && g.IsIntegerConstant(index) && selector->CanAddressRelativeToRootsRegister(m.Value())) { ptrdiff_t const delta = g.GetIntegerConstantValue(index) + TurboAssemblerBase::RootRegisterOffsetForExternalReference( selector->isolate(), m.Value()); input_count = 1; // Check that the delta is a 32-bit integer due to the limitations of // immediate operands. if (is_int32(delta)) { inputs[0] = g.UseImmediate(static_cast<int32_t>(delta)); opcode |= AddressingModeField::encode(kMode_Root); selector->Emit(opcode, arraysize(outputs), outputs, input_count, inputs); return; } } inputs[0] = g.UseRegister(base); if (g.CanBeImmediate(index, immediate_mode)) { input_count = 2; inputs[1] = g.UseImmediate(index); opcode |= AddressingModeField::encode(kMode_MRI); } else if (TryMatchLoadStoreShift(&g, selector, rep, node, index, &inputs[1], &inputs[2])) { input_count = 3; opcode |= AddressingModeField::encode(kMode_Operand2_R_LSL_I); } else { input_count = 2; inputs[1] = g.UseRegister(index); opcode |= AddressingModeField::encode(kMode_MRR); } selector->Emit(opcode, arraysize(outputs), outputs, input_count, inputs); } void InstructionSelector::VisitLoad(Node* node) { InstructionCode opcode = kArchNop; ImmediateMode immediate_mode = kNoImmediate; LoadRepresentation load_rep = LoadRepresentationOf(node->op()); MachineRepresentation rep = load_rep.representation(); switch (rep) { case MachineRepresentation::kFloat32: opcode = kArm64LdrS; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kFloat64: opcode = kArm64LdrD; immediate_mode = kLoadStoreImm64; break; case MachineRepresentation::kBit: // Fall through. case MachineRepresentation::kWord8: opcode = load_rep.IsSigned() ? kArm64Ldrsb : kArm64Ldrb; immediate_mode = kLoadStoreImm8; break; case MachineRepresentation::kWord16: opcode = load_rep.IsSigned() ? kArm64Ldrsh : kArm64Ldrh; immediate_mode = kLoadStoreImm16; break; case MachineRepresentation::kWord32: opcode = kArm64LdrW; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kCompressedSigned: // Fall through. case MachineRepresentation::kCompressedPointer: // Fall through. case MachineRepresentation::kCompressed: #ifdef V8_COMPRESS_POINTERS opcode = kArm64LdrW; immediate_mode = kLoadStoreImm32; break; #else UNREACHABLE(); #endif #ifdef V8_COMPRESS_POINTERS case MachineRepresentation::kTaggedSigned: opcode = kArm64LdrDecompressTaggedSigned; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kTaggedPointer: opcode = kArm64LdrDecompressTaggedPointer; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kTagged: opcode = kArm64LdrDecompressAnyTagged; immediate_mode = kLoadStoreImm32; break; #else case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: // Fall through. #endif case MachineRepresentation::kWord64: opcode = kArm64Ldr; immediate_mode = kLoadStoreImm64; break; case MachineRepresentation::kSimd128: opcode = kArm64LdrQ; immediate_mode = kNoImmediate; break; case MachineRepresentation::kNone: UNREACHABLE(); } if (node->opcode() == IrOpcode::kPoisonedLoad) { CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison); opcode |= MiscField::encode(kMemoryAccessPoisoned); } EmitLoad(this, node, opcode, immediate_mode, rep); } void InstructionSelector::VisitPoisonedLoad(Node* node) { VisitLoad(node); } void InstructionSelector::VisitProtectedLoad(Node* node) { // TODO(eholk) UNIMPLEMENTED(); } void InstructionSelector::VisitStore(Node* node) { Arm64OperandGenerator g(this); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); StoreRepresentation store_rep = StoreRepresentationOf(node->op()); WriteBarrierKind write_barrier_kind = store_rep.write_barrier_kind(); MachineRepresentation rep = store_rep.representation(); // TODO(arm64): I guess this could be done in a better way. if (write_barrier_kind != kNoWriteBarrier && V8_LIKELY(!FLAG_disable_write_barriers)) { DCHECK(CanBeTaggedOrCompressedPointer(rep)); AddressingMode addressing_mode; InstructionOperand inputs[3]; size_t input_count = 0; inputs[input_count++] = g.UseUniqueRegister(base); // OutOfLineRecordWrite uses the index in an add or sub instruction, but we // can trust the assembler to generate extra instructions if the index does // not fit into add or sub. So here only check the immediate for a store. if (g.CanBeImmediate(index, COMPRESS_POINTERS_BOOL ? kLoadStoreImm32 : kLoadStoreImm64)) { inputs[input_count++] = g.UseImmediate(index); addressing_mode = kMode_MRI; } else { inputs[input_count++] = g.UseUniqueRegister(index); addressing_mode = kMode_MRR; } inputs[input_count++] = g.UseUniqueRegister(value); RecordWriteMode record_write_mode = WriteBarrierKindToRecordWriteMode(write_barrier_kind); InstructionCode code = kArchStoreWithWriteBarrier; code |= AddressingModeField::encode(addressing_mode); code |= MiscField::encode(static_cast<int>(record_write_mode)); Emit(code, 0, nullptr, input_count, inputs); } else { InstructionOperand inputs[4]; size_t input_count = 0; InstructionCode opcode = kArchNop; ImmediateMode immediate_mode = kNoImmediate; switch (rep) { case MachineRepresentation::kFloat32: opcode = kArm64StrS; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kFloat64: opcode = kArm64StrD; immediate_mode = kLoadStoreImm64; break; case MachineRepresentation::kBit: // Fall through. case MachineRepresentation::kWord8: opcode = kArm64Strb; immediate_mode = kLoadStoreImm8; break; case MachineRepresentation::kWord16: opcode = kArm64Strh; immediate_mode = kLoadStoreImm16; break; case MachineRepresentation::kWord32: opcode = kArm64StrW; immediate_mode = kLoadStoreImm32; break; case MachineRepresentation::kCompressedSigned: // Fall through. case MachineRepresentation::kCompressedPointer: // Fall through. case MachineRepresentation::kCompressed: #ifdef V8_COMPRESS_POINTERS opcode = kArm64StrCompressTagged; immediate_mode = kLoadStoreImm32; break; #else UNREACHABLE(); #endif case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: opcode = kArm64StrCompressTagged; immediate_mode = COMPRESS_POINTERS_BOOL ? kLoadStoreImm32 : kLoadStoreImm64; break; case MachineRepresentation::kWord64: opcode = kArm64Str; immediate_mode = kLoadStoreImm64; break; case MachineRepresentation::kSimd128: opcode = kArm64StrQ; immediate_mode = kNoImmediate; break; case MachineRepresentation::kNone: UNREACHABLE(); } inputs[0] = g.UseRegisterOrImmediateZero(value); inputs[1] = g.UseRegister(base); if (g.CanBeImmediate(index, immediate_mode)) { input_count = 3; inputs[2] = g.UseImmediate(index); opcode |= AddressingModeField::encode(kMode_MRI); } else if (TryMatchLoadStoreShift(&g, this, rep, node, index, &inputs[2], &inputs[3])) { input_count = 4; opcode |= AddressingModeField::encode(kMode_Operand2_R_LSL_I); } else { input_count = 3; inputs[2] = g.UseRegister(index); opcode |= AddressingModeField::encode(kMode_MRR); } Emit(opcode, 0, nullptr, input_count, inputs); } } void InstructionSelector::VisitProtectedStore(Node* node) { // TODO(eholk) UNIMPLEMENTED(); } void InstructionSelector::VisitSimd128ReverseBytes(Node* node) { UNREACHABLE(); } // Architecture supports unaligned access, therefore VisitLoad is used instead void InstructionSelector::VisitUnalignedLoad(Node* node) { UNREACHABLE(); } // Architecture supports unaligned access, therefore VisitStore is used instead void InstructionSelector::VisitUnalignedStore(Node* node) { UNREACHABLE(); } template <typename Matcher> static void VisitLogical(InstructionSelector* selector, Node* node, Matcher* m, ArchOpcode opcode, bool left_can_cover, bool right_can_cover, ImmediateMode imm_mode) { Arm64OperandGenerator g(selector); // Map instruction to equivalent operation with inverted right input. ArchOpcode inv_opcode = opcode; switch (opcode) { case kArm64And32: inv_opcode = kArm64Bic32; break; case kArm64And: inv_opcode = kArm64Bic; break; case kArm64Or32: inv_opcode = kArm64Orn32; break; case kArm64Or: inv_opcode = kArm64Orn; break; case kArm64Eor32: inv_opcode = kArm64Eon32; break; case kArm64Eor: inv_opcode = kArm64Eon; break; default: UNREACHABLE(); } // Select Logical(y, ~x) for Logical(Xor(x, -1), y). if ((m->left().IsWord32Xor() || m->left().IsWord64Xor()) && left_can_cover) { Matcher mleft(m->left().node()); if (mleft.right().Is(-1)) { // TODO(all): support shifted operand on right. selector->Emit(inv_opcode, g.DefineAsRegister(node), g.UseRegister(m->right().node()), g.UseRegister(mleft.left().node())); return; } } // Select Logical(x, ~y) for Logical(x, Xor(y, -1)). if ((m->right().IsWord32Xor() || m->right().IsWord64Xor()) && right_can_cover) { Matcher mright(m->right().node()); if (mright.right().Is(-1)) { // TODO(all): support shifted operand on right. selector->Emit(inv_opcode, g.DefineAsRegister(node), g.UseRegister(m->left().node()), g.UseRegister(mright.left().node())); return; } } if (m->IsWord32Xor() && m->right().Is(-1)) { selector->Emit(kArm64Not32, g.DefineAsRegister(node), g.UseRegister(m->left().node())); } else if (m->IsWord64Xor() && m->right().Is(-1)) { selector->Emit(kArm64Not, g.DefineAsRegister(node), g.UseRegister(m->left().node())); } else { VisitBinop<Matcher>(selector, node, opcode, imm_mode); } } void InstructionSelector::VisitWord32And(Node* node) { Arm64OperandGenerator g(this); Int32BinopMatcher m(node); if (m.left().IsWord32Shr() && CanCover(node, m.left().node()) && m.right().HasValue()) { uint32_t mask = m.right().Value(); uint32_t mask_width = base::bits::CountPopulation(mask); uint32_t mask_msb = base::bits::CountLeadingZeros32(mask); if ((mask_width != 0) && (mask_width != 32) && (mask_msb + mask_width == 32)) { // The mask must be contiguous, and occupy the least-significant bits. DCHECK_EQ(0u, base::bits::CountTrailingZeros32(mask)); // Select Ubfx for And(Shr(x, imm), mask) where the mask is in the least // significant bits. Int32BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue()) { // Any shift value can match; int32 shifts use `value % 32`. uint32_t lsb = mleft.right().Value() & 0x1F; // Ubfx cannot extract bits past the register size, however since // shifting the original value would have introduced some zeros we can // still use ubfx with a smaller mask and the remaining bits will be // zeros. if (lsb + mask_width > 32) mask_width = 32 - lsb; Emit(kArm64Ubfx32, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediateOrTemp(mleft.right().node(), lsb), g.TempImmediate(mask_width)); return; } // Other cases fall through to the normal And operation. } } VisitLogical<Int32BinopMatcher>( this, node, &m, kArm64And32, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical32Imm); } void InstructionSelector::VisitWord64And(Node* node) { Arm64OperandGenerator g(this); Int64BinopMatcher m(node); if (m.left().IsWord64Shr() && CanCover(node, m.left().node()) && m.right().HasValue()) { uint64_t mask = m.right().Value(); uint64_t mask_width = base::bits::CountPopulation(mask); uint64_t mask_msb = base::bits::CountLeadingZeros64(mask); if ((mask_width != 0) && (mask_width != 64) && (mask_msb + mask_width == 64)) { // The mask must be contiguous, and occupy the least-significant bits. DCHECK_EQ(0u, base::bits::CountTrailingZeros64(mask)); // Select Ubfx for And(Shr(x, imm), mask) where the mask is in the least // significant bits. Int64BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue()) { // Any shift value can match; int64 shifts use `value % 64`. uint32_t lsb = static_cast<uint32_t>(mleft.right().Value() & 0x3F); // Ubfx cannot extract bits past the register size, however since // shifting the original value would have introduced some zeros we can // still use ubfx with a smaller mask and the remaining bits will be // zeros. if (lsb + mask_width > 64) mask_width = 64 - lsb; Emit(kArm64Ubfx, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediateOrTemp(mleft.right().node(), lsb), g.TempImmediate(static_cast<int32_t>(mask_width))); return; } // Other cases fall through to the normal And operation. } } VisitLogical<Int64BinopMatcher>( this, node, &m, kArm64And, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical64Imm); } void InstructionSelector::VisitWord32Or(Node* node) { Int32BinopMatcher m(node); VisitLogical<Int32BinopMatcher>( this, node, &m, kArm64Or32, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical32Imm); } void InstructionSelector::VisitWord64Or(Node* node) { Int64BinopMatcher m(node); VisitLogical<Int64BinopMatcher>( this, node, &m, kArm64Or, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical64Imm); } void InstructionSelector::VisitWord32Xor(Node* node) { Int32BinopMatcher m(node); VisitLogical<Int32BinopMatcher>( this, node, &m, kArm64Eor32, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical32Imm); } void InstructionSelector::VisitWord64Xor(Node* node) { Int64BinopMatcher m(node); VisitLogical<Int64BinopMatcher>( this, node, &m, kArm64Eor, CanCover(node, m.left().node()), CanCover(node, m.right().node()), kLogical64Imm); } void InstructionSelector::VisitWord32Shl(Node* node) { Int32BinopMatcher m(node); if (m.left().IsWord32And() && CanCover(node, m.left().node()) && m.right().IsInRange(1, 31)) { Arm64OperandGenerator g(this); Int32BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue()) { uint32_t mask = mleft.right().Value(); uint32_t mask_width = base::bits::CountPopulation(mask); uint32_t mask_msb = base::bits::CountLeadingZeros32(mask); if ((mask_width != 0) && (mask_msb + mask_width == 32)) { uint32_t shift = m.right().Value(); DCHECK_EQ(0u, base::bits::CountTrailingZeros32(mask)); DCHECK_NE(0u, shift); if ((shift + mask_width) >= 32) { // If the mask is contiguous and reaches or extends beyond the top // bit, only the shift is needed. Emit(kArm64Lsl32, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediate(m.right().node())); return; } else { // Select Ubfiz for Shl(And(x, mask), imm) where the mask is // contiguous, and the shift immediate non-zero. Emit(kArm64Ubfiz32, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediate(m.right().node()), g.TempImmediate(mask_width)); return; } } } } VisitRRO(this, kArm64Lsl32, node, kShift32Imm); } void InstructionSelector::VisitWord64Shl(Node* node) { Arm64OperandGenerator g(this); Int64BinopMatcher m(node); if ((m.left().IsChangeInt32ToInt64() || m.left().IsChangeUint32ToUint64()) && m.right().IsInRange(32, 63) && CanCover(node, m.left().node())) { // There's no need to sign/zero-extend to 64-bit if we shift out the upper // 32 bits anyway. Emit(kArm64Lsl, g.DefineAsRegister(node), g.UseRegister(m.left().node()->InputAt(0)), g.UseImmediate(m.right().node())); return; } VisitRRO(this, kArm64Lsl, node, kShift64Imm); } void InstructionSelector::VisitStackPointerGreaterThan( Node* node, FlagsContinuation* cont) { Node* const value = node->InputAt(0); InstructionCode opcode = kArchStackPointerGreaterThan; Arm64OperandGenerator g(this); EmitWithContinuation(opcode, g.UseRegister(value), cont); } namespace { bool TryEmitBitfieldExtract32(InstructionSelector* selector, Node* node) { Arm64OperandGenerator g(selector); Int32BinopMatcher m(node); if (selector->CanCover(node, m.left().node()) && m.left().IsWord32Shl()) { // Select Ubfx or Sbfx for (x << (K & 0x1F)) OP (K & 0x1F), where // OP is >>> or >> and (K & 0x1F) != 0. Int32BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue() && m.right().HasValue() && (mleft.right().Value() & 0x1F) != 0 && (mleft.right().Value() & 0x1F) == (m.right().Value() & 0x1F)) { DCHECK(m.IsWord32Shr() || m.IsWord32Sar()); ArchOpcode opcode = m.IsWord32Sar() ? kArm64Sbfx32 : kArm64Ubfx32; int right_val = m.right().Value() & 0x1F; DCHECK_NE(right_val, 0); selector->Emit(opcode, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.TempImmediate(0), g.TempImmediate(32 - right_val)); return true; } } return false; } } // namespace void InstructionSelector::VisitWord32Shr(Node* node) { Int32BinopMatcher m(node); if (m.left().IsWord32And() && m.right().HasValue()) { uint32_t lsb = m.right().Value() & 0x1F; Int32BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue() && mleft.right().Value() != 0) { // Select Ubfx for Shr(And(x, mask), imm) where the result of the mask is // shifted into the least-significant bits. uint32_t mask = static_cast<uint32_t>(mleft.right().Value() >> lsb) << lsb; unsigned mask_width = base::bits::CountPopulation(mask); unsigned mask_msb = base::bits::CountLeadingZeros32(mask); if ((mask_msb + mask_width + lsb) == 32) { Arm64OperandGenerator g(this); DCHECK_EQ(lsb, base::bits::CountTrailingZeros32(mask)); Emit(kArm64Ubfx32, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediateOrTemp(m.right().node(), lsb), g.TempImmediate(mask_width)); return; } } } else if (TryEmitBitfieldExtract32(this, node)) { return; } if (m.left().IsUint32MulHigh() && m.right().HasValue() && CanCover(node, node->InputAt(0))) { // Combine this shift with the multiply and shift that would be generated // by Uint32MulHigh. Arm64OperandGenerator g(this); Node* left = m.left().node(); int shift = m.right().Value() & 0x1F; InstructionOperand const smull_operand = g.TempRegister(); Emit(kArm64Umull, smull_operand, g.UseRegister(left->InputAt(0)), g.UseRegister(left->InputAt(1))); Emit(kArm64Lsr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32 + shift)); return; } VisitRRO(this, kArm64Lsr32, node, kShift32Imm); } void InstructionSelector::VisitWord64Shr(Node* node) { Int64BinopMatcher m(node); if (m.left().IsWord64And() && m.right().HasValue()) { uint32_t lsb = m.right().Value() & 0x3F; Int64BinopMatcher mleft(m.left().node()); if (mleft.right().HasValue() && mleft.right().Value() != 0) { // Select Ubfx for Shr(And(x, mask), imm) where the result of the mask is // shifted into the least-significant bits. uint64_t mask = static_cast<uint64_t>(mleft.right().Value() >> lsb) << lsb; unsigned mask_width = base::bits::CountPopulation(mask); unsigned mask_msb = base::bits::CountLeadingZeros64(mask); if ((mask_msb + mask_width + lsb) == 64) { Arm64OperandGenerator g(this); DCHECK_EQ(lsb, base::bits::CountTrailingZeros64(mask)); Emit(kArm64Ubfx, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseImmediateOrTemp(m.right().node(), lsb), g.TempImmediate(mask_width)); return; } } } VisitRRO(this, kArm64Lsr, node, kShift64Imm); } void InstructionSelector::VisitWord32Sar(Node* node) { if (TryEmitBitfieldExtract32(this, node)) { return; } Int32BinopMatcher m(node); if (m.left().IsInt32MulHigh() && m.right().HasValue() && CanCover(node, node->InputAt(0))) { // Combine this shift with the multiply and shift that would be generated // by Int32MulHigh. Arm64OperandGenerator g(this); Node* left = m.left().node(); int shift = m.right().Value() & 0x1F; InstructionOperand const smull_operand = g.TempRegister(); Emit(kArm64Smull, smull_operand, g.UseRegister(left->InputAt(0)), g.UseRegister(left->InputAt(1))); Emit(kArm64Asr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32 + shift)); return; } if (m.left().IsInt32Add() && m.right().HasValue() && CanCover(node, node->InputAt(0))) { Node* add_node = m.left().node(); Int32BinopMatcher madd_node(add_node); if (madd_node.left().IsInt32MulHigh() && CanCover(add_node, madd_node.left().node())) { // Combine the shift that would be generated by Int32MulHigh with the add // on the left of this Sar operation. We do it here, as the result of the // add potentially has 33 bits, so we have to ensure the result is // truncated by being the input to this 32-bit Sar operation. Arm64OperandGenerator g(this); Node* mul_node = madd_node.left().node(); InstructionOperand const smull_operand = g.TempRegister(); Emit(kArm64Smull, smull_operand, g.UseRegister(mul_node->InputAt(0)), g.UseRegister(mul_node->InputAt(1))); InstructionOperand const add_operand = g.TempRegister(); Emit(kArm64Add | AddressingModeField::encode(kMode_Operand2_R_ASR_I), add_operand, g.UseRegister(add_node->InputAt(1)), smull_operand, g.TempImmediate(32)); Emit(kArm64Asr32, g.DefineAsRegister(node), add_operand, g.UseImmediate(node->InputAt(1))); return; } } VisitRRO(this, kArm64Asr32, node, kShift32Imm); } void InstructionSelector::VisitWord64Sar(Node* node) { if (TryEmitExtendingLoad(this, node)) return; VisitRRO(this, kArm64Asr, node, kShift64Imm); } void InstructionSelector::VisitWord32Ror(Node* node) { VisitRRO(this, kArm64Ror32, node, kShift32Imm); } void InstructionSelector::VisitWord64Ror(Node* node) { VisitRRO(this, kArm64Ror, node, kShift64Imm); } #define RR_OP_LIST(V) \ V(Word64Clz, kArm64Clz) \ V(Word32Clz, kArm64Clz32) \ V(Word32ReverseBits, kArm64Rbit32) \ V(Word64ReverseBits, kArm64Rbit) \ V(Word32ReverseBytes, kArm64Rev32) \ V(Word64ReverseBytes, kArm64Rev) \ V(ChangeFloat32ToFloat64, kArm64Float32ToFloat64) \ V(RoundInt32ToFloat32, kArm64Int32ToFloat32) \ V(RoundUint32ToFloat32, kArm64Uint32ToFloat32) \ V(ChangeInt32ToFloat64, kArm64Int32ToFloat64) \ V(ChangeInt64ToFloat64, kArm64Int64ToFloat64) \ V(ChangeUint32ToFloat64, kArm64Uint32ToFloat64) \ V(TruncateFloat32ToInt32, kArm64Float32ToInt32) \ V(ChangeFloat64ToInt32, kArm64Float64ToInt32) \ V(ChangeFloat64ToInt64, kArm64Float64ToInt64) \ V(TruncateFloat32ToUint32, kArm64Float32ToUint32) \ V(ChangeFloat64ToUint32, kArm64Float64ToUint32) \ V(ChangeFloat64ToUint64, kArm64Float64ToUint64) \ V(TruncateFloat64ToInt64, kArm64Float64ToInt64) \ V(TruncateFloat64ToUint32, kArm64Float64ToUint32) \ V(TruncateFloat64ToFloat32, kArm64Float64ToFloat32) \ V(TruncateFloat64ToWord32, kArchTruncateDoubleToI) \ V(RoundFloat64ToInt32, kArm64Float64ToInt32) \ V(RoundInt64ToFloat32, kArm64Int64ToFloat32) \ V(RoundInt64ToFloat64, kArm64Int64ToFloat64) \ V(RoundUint64ToFloat32, kArm64Uint64ToFloat32) \ V(RoundUint64ToFloat64, kArm64Uint64ToFloat64) \ V(BitcastFloat32ToInt32, kArm64Float64ExtractLowWord32) \ V(BitcastFloat64ToInt64, kArm64U64MoveFloat64) \ V(BitcastInt32ToFloat32, kArm64Float64MoveU64) \ V(BitcastInt64ToFloat64, kArm64Float64MoveU64) \ V(Float32Abs, kArm64Float32Abs) \ V(Float64Abs, kArm64Float64Abs) \ V(Float32Sqrt, kArm64Float32Sqrt) \ V(Float64Sqrt, kArm64Float64Sqrt) \ V(Float32RoundDown, kArm64Float32RoundDown) \ V(Float64RoundDown, kArm64Float64RoundDown) \ V(Float32RoundUp, kArm64Float32RoundUp) \ V(Float64RoundUp, kArm64Float64RoundUp) \ V(Float32RoundTruncate, kArm64Float32RoundTruncate) \ V(Float64RoundTruncate, kArm64Float64RoundTruncate) \ V(Float64RoundTiesAway, kArm64Float64RoundTiesAway) \ V(Float32RoundTiesEven, kArm64Float32RoundTiesEven) \ V(Float64RoundTiesEven, kArm64Float64RoundTiesEven) \ V(Float64ExtractLowWord32, kArm64Float64ExtractLowWord32) \ V(Float64ExtractHighWord32, kArm64Float64ExtractHighWord32) \ V(Float64SilenceNaN, kArm64Float64SilenceNaN) #define RRR_OP_LIST(V) \ V(Int32Div, kArm64Idiv32) \ V(Int64Div, kArm64Idiv) \ V(Uint32Div, kArm64Udiv32) \ V(Uint64Div, kArm64Udiv) \ V(Int32Mod, kArm64Imod32) \ V(Int64Mod, kArm64Imod) \ V(Uint32Mod, kArm64Umod32) \ V(Uint64Mod, kArm64Umod) \ V(Float32Add, kArm64Float32Add) \ V(Float64Add, kArm64Float64Add) \ V(Float32Sub, kArm64Float32Sub) \ V(Float64Sub, kArm64Float64Sub) \ V(Float32Div, kArm64Float32Div) \ V(Float64Div, kArm64Float64Div) \ V(Float32Max, kArm64Float32Max) \ V(Float64Max, kArm64Float64Max) \ V(Float32Min, kArm64Float32Min) \ V(Float64Min, kArm64Float64Min) #define RR_VISITOR(Name, opcode) \ void InstructionSelector::Visit##Name(Node* node) { \ VisitRR(this, opcode, node); \ } RR_OP_LIST(RR_VISITOR) #undef RR_VISITOR #undef RR_OP_LIST #define RRR_VISITOR(Name, opcode) \ void InstructionSelector::Visit##Name(Node* node) { \ VisitRRR(this, opcode, node); \ } RRR_OP_LIST(RRR_VISITOR) #undef RRR_VISITOR #undef RRR_OP_LIST void InstructionSelector::VisitWord32Ctz(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitWord64Ctz(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitWord32Popcnt(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitWord64Popcnt(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitInt32Add(Node* node) { Arm64OperandGenerator g(this); Int32BinopMatcher m(node); // Select Madd(x, y, z) for Add(Mul(x, y), z). if (m.left().IsInt32Mul() && CanCover(node, m.left().node())) { Int32BinopMatcher mleft(m.left().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mleft) == 0) { Emit(kArm64Madd32, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node())); return; } } // Select Madd(x, y, z) for Add(z, Mul(x, y)). if (m.right().IsInt32Mul() && CanCover(node, m.right().node())) { Int32BinopMatcher mright(m.right().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mright) == 0) { Emit(kArm64Madd32, g.DefineAsRegister(node), g.UseRegister(mright.left().node()), g.UseRegister(mright.right().node()), g.UseRegister(m.left().node())); return; } } VisitAddSub<Int32BinopMatcher>(this, node, kArm64Add32, kArm64Sub32); } void InstructionSelector::VisitInt64Add(Node* node) { Arm64OperandGenerator g(this); Int64BinopMatcher m(node); // Select Madd(x, y, z) for Add(Mul(x, y), z). if (m.left().IsInt64Mul() && CanCover(node, m.left().node())) { Int64BinopMatcher mleft(m.left().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mleft) == 0) { Emit(kArm64Madd, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node())); return; } } // Select Madd(x, y, z) for Add(z, Mul(x, y)). if (m.right().IsInt64Mul() && CanCover(node, m.right().node())) { Int64BinopMatcher mright(m.right().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mright) == 0) { Emit(kArm64Madd, g.DefineAsRegister(node), g.UseRegister(mright.left().node()), g.UseRegister(mright.right().node()), g.UseRegister(m.left().node())); return; } } VisitAddSub<Int64BinopMatcher>(this, node, kArm64Add, kArm64Sub); } void InstructionSelector::VisitInt32Sub(Node* node) { Arm64OperandGenerator g(this); Int32BinopMatcher m(node); // Select Msub(x, y, a) for Sub(a, Mul(x, y)). if (m.right().IsInt32Mul() && CanCover(node, m.right().node())) { Int32BinopMatcher mright(m.right().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mright) == 0) { Emit(kArm64Msub32, g.DefineAsRegister(node), g.UseRegister(mright.left().node()), g.UseRegister(mright.right().node()), g.UseRegister(m.left().node())); return; } } VisitAddSub<Int32BinopMatcher>(this, node, kArm64Sub32, kArm64Add32); } void InstructionSelector::VisitInt64Sub(Node* node) { Arm64OperandGenerator g(this); Int64BinopMatcher m(node); // Select Msub(x, y, a) for Sub(a, Mul(x, y)). if (m.right().IsInt64Mul() && CanCover(node, m.right().node())) { Int64BinopMatcher mright(m.right().node()); // Check multiply can't be later reduced to addition with shift. if (LeftShiftForReducedMultiply(&mright) == 0) { Emit(kArm64Msub, g.DefineAsRegister(node), g.UseRegister(mright.left().node()), g.UseRegister(mright.right().node()), g.UseRegister(m.left().node())); return; } } VisitAddSub<Int64BinopMatcher>(this, node, kArm64Sub, kArm64Add); } namespace { void EmitInt32MulWithOverflow(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { Arm64OperandGenerator g(selector); Int32BinopMatcher m(node); InstructionOperand result = g.DefineAsRegister(node); InstructionOperand left = g.UseRegister(m.left().node()); InstructionOperand right = g.UseRegister(m.right().node()); selector->Emit(kArm64Smull, result, left, right); InstructionCode opcode = kArm64Cmp | AddressingModeField::encode(kMode_Operand2_R_SXTW); selector->EmitWithContinuation(opcode, result, result, cont); } } // namespace void InstructionSelector::VisitInt32Mul(Node* node) { Arm64OperandGenerator g(this); Int32BinopMatcher m(node); // First, try to reduce the multiplication to addition with left shift. // x * (2^k + 1) -> x + (x << k) int32_t shift = LeftShiftForReducedMultiply(&m); if (shift > 0) { Emit(kArm64Add32 | AddressingModeField::encode(kMode_Operand2_R_LSL_I), g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(m.left().node()), g.TempImmediate(shift)); return; } if (m.left().IsInt32Sub() && CanCover(node, m.left().node())) { Int32BinopMatcher mleft(m.left().node()); // Select Mneg(x, y) for Mul(Sub(0, x), y). if (mleft.left().Is(0)) { Emit(kArm64Mneg32, g.DefineAsRegister(node), g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node())); return; } } if (m.right().IsInt32Sub() && CanCover(node, m.right().node())) { Int32BinopMatcher mright(m.right().node()); // Select Mneg(x, y) for Mul(x, Sub(0, y)). if (mright.left().Is(0)) { Emit(kArm64Mneg32, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(mright.right().node())); return; } } VisitRRR(this, kArm64Mul32, node); } void InstructionSelector::VisitInt64Mul(Node* node) { Arm64OperandGenerator g(this); Int64BinopMatcher m(node); // First, try to reduce the multiplication to addition with left shift. // x * (2^k + 1) -> x + (x << k) int32_t shift = LeftShiftForReducedMultiply(&m); if (shift > 0) { Emit(kArm64Add | AddressingModeField::encode(kMode_Operand2_R_LSL_I), g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(m.left().node()), g.TempImmediate(shift)); return; } if (m.left().IsInt64Sub() && CanCover(node, m.left().node())) { Int64BinopMatcher mleft(m.left().node()); // Select Mneg(x, y) for Mul(Sub(0, x), y). if (mleft.left().Is(0)) { Emit(kArm64Mneg, g.DefineAsRegister(node), g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node())); return; } } if (m.right().IsInt64Sub() && CanCover(node, m.right().node())) { Int64BinopMatcher mright(m.right().node()); // Select Mneg(x, y) for Mul(x, Sub(0, y)). if (mright.left().Is(0)) { Emit(kArm64Mneg, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(mright.right().node())); return; } } VisitRRR(this, kArm64Mul, node); } void InstructionSelector::VisitInt32MulHigh(Node* node) { Arm64OperandGenerator g(this); InstructionOperand const smull_operand = g.TempRegister(); Emit(kArm64Smull, smull_operand, g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1))); Emit(kArm64Asr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32)); } void InstructionSelector::VisitUint32MulHigh(Node* node) { Arm64OperandGenerator g(this); InstructionOperand const smull_operand = g.TempRegister(); Emit(kArm64Umull, smull_operand, g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1))); Emit(kArm64Lsr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32)); } void InstructionSelector::VisitTryTruncateFloat32ToInt64(Node* node) { Arm64OperandGenerator g(this); InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))}; InstructionOperand outputs[2]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); Node* success_output = NodeProperties::FindProjection(node, 1); if (success_output) { outputs[output_count++] = g.DefineAsRegister(success_output); } Emit(kArm64Float32ToInt64, output_count, outputs, 1, inputs); } void InstructionSelector::VisitTryTruncateFloat64ToInt64(Node* node) { Arm64OperandGenerator g(this); InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))}; InstructionOperand outputs[2]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); Node* success_output = NodeProperties::FindProjection(node, 1); if (success_output) { outputs[output_count++] = g.DefineAsRegister(success_output); } Emit(kArm64Float64ToInt64, output_count, outputs, 1, inputs); } void InstructionSelector::VisitTryTruncateFloat32ToUint64(Node* node) { Arm64OperandGenerator g(this); InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))}; InstructionOperand outputs[2]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); Node* success_output = NodeProperties::FindProjection(node, 1); if (success_output) { outputs[output_count++] = g.DefineAsRegister(success_output); } Emit(kArm64Float32ToUint64, output_count, outputs, 1, inputs); } void InstructionSelector::VisitTryTruncateFloat64ToUint64(Node* node) { Arm64OperandGenerator g(this); InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))}; InstructionOperand outputs[2]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); Node* success_output = NodeProperties::FindProjection(node, 1); if (success_output) { outputs[output_count++] = g.DefineAsRegister(success_output); } Emit(kArm64Float64ToUint64, output_count, outputs, 1, inputs); } void InstructionSelector::VisitChangeInt32ToInt64(Node* node) { Node* value = node->InputAt(0); if (value->opcode() == IrOpcode::kLoad && CanCover(node, value)) { // Generate sign-extending load. LoadRepresentation load_rep = LoadRepresentationOf(value->op()); MachineRepresentation rep = load_rep.representation(); InstructionCode opcode = kArchNop; ImmediateMode immediate_mode = kNoImmediate; switch (rep) { case MachineRepresentation::kBit: // Fall through. case MachineRepresentation::kWord8: opcode = load_rep.IsSigned() ? kArm64Ldrsb : kArm64Ldrb; immediate_mode = kLoadStoreImm8; break; case MachineRepresentation::kWord16: opcode = load_rep.IsSigned() ? kArm64Ldrsh : kArm64Ldrh; immediate_mode = kLoadStoreImm16; break; case MachineRepresentation::kWord32: opcode = kArm64Ldrsw; immediate_mode = kLoadStoreImm32; break; default: UNREACHABLE(); return; } EmitLoad(this, value, opcode, immediate_mode, rep, node); return; } if (value->opcode() == IrOpcode::kWord32Sar && CanCover(node, value)) { Int32BinopMatcher m(value); if (m.right().HasValue()) { Arm64OperandGenerator g(this); // Mask the shift amount, to keep the same semantics as Word32Sar. int right = m.right().Value() & 0x1F; Emit(kArm64Sbfx, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.TempImmediate(right), g.TempImmediate(32 - right)); return; } } VisitRR(this, kArm64Sxtw, node); } void InstructionSelector::VisitChangeUint32ToUint64(Node* node) { Arm64OperandGenerator g(this); Node* value = node->InputAt(0); switch (value->opcode()) { case IrOpcode::kWord32And: case IrOpcode::kWord32Or: case IrOpcode::kWord32Xor: case IrOpcode::kWord32Shl: case IrOpcode::kWord32Shr: case IrOpcode::kWord32Sar: case IrOpcode::kWord32Ror: case IrOpcode::kWord32Equal: case IrOpcode::kInt32Add: case IrOpcode::kInt32AddWithOverflow: case IrOpcode::kInt32Sub: case IrOpcode::kInt32SubWithOverflow: case IrOpcode::kInt32Mul: case IrOpcode::kInt32MulHigh: case IrOpcode::kInt32Div: case IrOpcode::kInt32Mod: case IrOpcode::kInt32LessThan: case IrOpcode::kInt32LessThanOrEqual: case IrOpcode::kUint32Div: case IrOpcode::kUint32LessThan: case IrOpcode::kUint32LessThanOrEqual: case IrOpcode::kUint32Mod: case IrOpcode::kUint32MulHigh: { // 32-bit operations will write their result in a W register (implicitly // clearing the top 32-bit of the corresponding X register) so the // zero-extension is a no-op. EmitIdentity(node); return; } case IrOpcode::kLoad: { // As for the operations above, a 32-bit load will implicitly clear the // top 32 bits of the destination register. LoadRepresentation load_rep = LoadRepresentationOf(value->op()); switch (load_rep.representation()) { case MachineRepresentation::kWord8: case MachineRepresentation::kWord16: case MachineRepresentation::kWord32: EmitIdentity(node); return; default: break; } break; } default: break; } Emit(kArm64Mov32, g.DefineAsRegister(node), g.UseRegister(value)); } void InstructionSelector::VisitChangeTaggedToCompressed(Node* node) { // The top 32 bits in the 64-bit register will be undefined, and // must not be used by a dependent node. EmitIdentity(node); } void InstructionSelector::VisitChangeTaggedPointerToCompressedPointer( Node* node) { // The top 32 bits in the 64-bit register will be undefined, and // must not be used by a dependent node. EmitIdentity(node); } void InstructionSelector::VisitChangeTaggedSignedToCompressedSigned( Node* node) { // The top 32 bits in the 64-bit register will be undefined, and // must not be used by a dependent node. EmitIdentity(node); } void InstructionSelector::VisitChangeCompressedToTagged(Node* node) { Arm64OperandGenerator g(this); Node* const value = node->InputAt(0); if ((value->opcode() == IrOpcode::kLoad || value->opcode() == IrOpcode::kPoisonedLoad) && CanCover(node, value)) { DCHECK_EQ(LoadRepresentationOf(value->op()).representation(), MachineRepresentation::kCompressed); InstructionCode opcode = kArm64LdrDecompressAnyTagged; if (value->opcode() == IrOpcode::kPoisonedLoad) { CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison); opcode |= MiscField::encode(kMemoryAccessPoisoned); } ImmediateMode immediate_mode = kLoadStoreImm32; MachineRepresentation rep = MachineRepresentation::kCompressed; EmitLoad(this, value, opcode, immediate_mode, rep, node); } else { Emit(kArm64DecompressAny, g.DefineAsRegister(node), g.UseRegister(value)); } } void InstructionSelector::VisitChangeCompressedPointerToTaggedPointer( Node* node) { Arm64OperandGenerator g(this); Node* const value = node->InputAt(0); if ((value->opcode() == IrOpcode::kLoad || value->opcode() == IrOpcode::kPoisonedLoad) && CanCover(node, value)) { DCHECK_EQ(LoadRepresentationOf(value->op()).representation(), MachineRepresentation::kCompressedPointer); InstructionCode opcode = kArm64LdrDecompressTaggedPointer; if (value->opcode() == IrOpcode::kPoisonedLoad) { CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison); opcode |= MiscField::encode(kMemoryAccessPoisoned); } ImmediateMode immediate_mode = kLoadStoreImm32; MachineRepresentation rep = MachineRepresentation::kCompressedPointer; EmitLoad(this, value, opcode, immediate_mode, rep, node); } else { Emit(kArm64DecompressPointer, g.DefineAsRegister(node), g.UseRegister(value)); } } void InstructionSelector::VisitChangeCompressedSignedToTaggedSigned( Node* node) { Arm64OperandGenerator g(this); Node* const value = node->InputAt(0); if ((value->opcode() == IrOpcode::kLoad || value->opcode() == IrOpcode::kPoisonedLoad) && CanCover(node, value)) { DCHECK_EQ(LoadRepresentationOf(value->op()).representation(), MachineRepresentation::kCompressedSigned); InstructionCode opcode = kArm64LdrDecompressTaggedSigned; if (value->opcode() == IrOpcode::kPoisonedLoad) { CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison); opcode |= MiscField::encode(kMemoryAccessPoisoned); } ImmediateMode immediate_mode = kLoadStoreImm32; MachineRepresentation rep = MachineRepresentation::kCompressedSigned; EmitLoad(this, value, opcode, immediate_mode, rep, node); } else { Emit(kArm64DecompressSigned, g.DefineAsRegister(node), g.UseRegister(value)); } } void InstructionSelector::VisitTruncateInt64ToInt32(Node* node) { Arm64OperandGenerator g(this); // The top 32 bits in the 64-bit register will be undefined, and // must not be used by a dependent node. EmitIdentity(node); } void InstructionSelector::VisitFloat64Mod(Node* node) { Arm64OperandGenerator g(this); Emit(kArm64Float64Mod, g.DefineAsFixed(node, d0), g.UseFixed(node->InputAt(0), d0), g.UseFixed(node->InputAt(1), d1)) ->MarkAsCall(); } void InstructionSelector::VisitFloat64Ieee754Binop(Node* node, InstructionCode opcode) { Arm64OperandGenerator g(this); Emit(opcode, g.DefineAsFixed(node, d0), g.UseFixed(node->InputAt(0), d0), g.UseFixed(node->InputAt(1), d1)) ->MarkAsCall(); } void InstructionSelector::VisitFloat64Ieee754Unop(Node* node, InstructionCode opcode) { Arm64OperandGenerator g(this); Emit(opcode, g.DefineAsFixed(node, d0), g.UseFixed(node->InputAt(0), d0)) ->MarkAsCall(); } void InstructionSelector::EmitPrepareArguments( ZoneVector<PushParameter>* arguments, const CallDescriptor* call_descriptor, Node* node) { Arm64OperandGenerator g(this); // `arguments` includes alignment "holes". This means that slots bigger than // kSystemPointerSize, e.g. Simd128, will span across multiple arguments. int claim_count = static_cast<int>(arguments->size()); bool needs_padding = claim_count % 2 != 0; int slot = claim_count - 1; claim_count = RoundUp(claim_count, 2); // Bump the stack pointer. if (claim_count > 0) { // TODO(titzer): claim and poke probably take small immediates. // TODO(titzer): it would be better to bump the sp here only // and emit paired stores with increment for non c frames. Emit(kArm64Claim, g.NoOutput(), g.TempImmediate(claim_count)); if (needs_padding) { Emit(kArm64Poke, g.NoOutput(), g.UseImmediate(0), g.TempImmediate(claim_count - 1)); } } // Poke the arguments into the stack. while (slot >= 0) { PushParameter input0 = (*arguments)[slot]; PushParameter input1 = slot > 0 ? (*arguments)[slot - 1] : PushParameter(); // Emit a poke-pair if consecutive parameters have the same type. // TODO(arm): Support consecutive Simd128 parameters. if (input0.node != nullptr && input1.node != nullptr && input0.location.GetType() == input1.location.GetType()) { Emit(kArm64PokePair, g.NoOutput(), g.UseRegister(input0.node), g.UseRegister(input1.node), g.TempImmediate(slot)); slot -= 2; } else if (input0.node != nullptr) { Emit(kArm64Poke, g.NoOutput(), g.UseRegister(input0.node), g.TempImmediate(slot)); slot--; } else { // Skip any alignment holes in pushed nodes. slot--; } } } void InstructionSelector::EmitPrepareResults( ZoneVector<PushParameter>* results, const CallDescriptor* call_descriptor, Node* node) { Arm64OperandGenerator g(this); int reverse_slot = 0; for (PushParameter output : *results) { if (!output.location.IsCallerFrameSlot()) continue; reverse_slot += output.location.GetSizeInPointers(); // Skip any alignment holes in nodes. if (output.node == nullptr) continue; DCHECK(!call_descriptor->IsCFunctionCall()); if (output.location.GetType() == MachineType::Float32()) { MarkAsFloat32(output.node); } else if (output.location.GetType() == MachineType::Float64()) { MarkAsFloat64(output.node); } Emit(kArm64Peek, g.DefineAsRegister(output.node), g.UseImmediate(reverse_slot)); } } bool InstructionSelector::IsTailCallAddressImmediate() { return false; } int InstructionSelector::GetTempsCountForTailCallFromJSFunction() { return 3; } namespace { // Shared routine for multiple compare operations. void VisitCompare(InstructionSelector* selector, InstructionCode opcode, InstructionOperand left, InstructionOperand right, FlagsContinuation* cont) { selector->EmitWithContinuation(opcode, left, right, cont); } // This function checks whether we can convert: // ((a <op> b) cmp 0), b.<cond> // to: // (a <ops> b), b.<cond'> // where <ops> is the flag setting version of <op>. // We only generate conditions <cond'> that are a combination of the N // and Z flags. This avoids the need to make this function dependent on // the flag-setting operation. bool CanUseFlagSettingBinop(FlagsCondition cond) { switch (cond) { case kEqual: case kNotEqual: case kSignedLessThan: case kSignedGreaterThanOrEqual: case kUnsignedLessThanOrEqual: // x <= 0 -> x == 0 case kUnsignedGreaterThan: // x > 0 -> x != 0 return true; default: return false; } } // Map <cond> to <cond'> so that the following transformation is possible: // ((a <op> b) cmp 0), b.<cond> // to: // (a <ops> b), b.<cond'> // where <ops> is the flag setting version of <op>. FlagsCondition MapForFlagSettingBinop(FlagsCondition cond) { DCHECK(CanUseFlagSettingBinop(cond)); switch (cond) { case kEqual: case kNotEqual: return cond; case kSignedLessThan: return kNegative; case kSignedGreaterThanOrEqual: return kPositiveOrZero; case kUnsignedLessThanOrEqual: // x <= 0 -> x == 0 return kEqual; case kUnsignedGreaterThan: // x > 0 -> x != 0 return kNotEqual; default: UNREACHABLE(); } } // This function checks if we can perform the transformation: // ((a <op> b) cmp 0), b.<cond> // to: // (a <ops> b), b.<cond'> // where <ops> is the flag setting version of <op>, and if so, // updates {node}, {opcode} and {cont} accordingly. void MaybeReplaceCmpZeroWithFlagSettingBinop(InstructionSelector* selector, Node** node, Node* binop, ArchOpcode* opcode, FlagsCondition cond, FlagsContinuation* cont, ImmediateMode* immediate_mode) { ArchOpcode binop_opcode; ArchOpcode no_output_opcode; ImmediateMode binop_immediate_mode; switch (binop->opcode()) { case IrOpcode::kInt32Add: binop_opcode = kArm64Add32; no_output_opcode = kArm64Cmn32; binop_immediate_mode = kArithmeticImm; break; case IrOpcode::kWord32And: binop_opcode = kArm64And32; no_output_opcode = kArm64Tst32; binop_immediate_mode = kLogical32Imm; break; default: UNREACHABLE(); } if (selector->CanCover(*node, binop)) { // The comparison is the only user of the add or and, so we can generate // a cmn or tst instead. cont->Overwrite(MapForFlagSettingBinop(cond)); *opcode = no_output_opcode; *node = binop; *immediate_mode = binop_immediate_mode; } else if (selector->IsOnlyUserOfNodeInSameBlock(*node, binop)) { // We can also handle the case where the add and the compare are in the // same basic block, and the compare is the only use of add in this basic // block (the add has users in other basic blocks). cont->Overwrite(MapForFlagSettingBinop(cond)); *opcode = binop_opcode; *node = binop; *immediate_mode = binop_immediate_mode; } } // Map {cond} to kEqual or kNotEqual, so that we can select // either TBZ or TBNZ when generating code for: // (x cmp 0), b.{cond} FlagsCondition MapForTbz(FlagsCondition cond) { switch (cond) { case kSignedLessThan: // generate TBNZ return kNotEqual; case kSignedGreaterThanOrEqual: // generate TBZ return kEqual; default: UNREACHABLE(); } } // Map {cond} to kEqual or kNotEqual, so that we can select // either CBZ or CBNZ when generating code for: // (x cmp 0), b.{cond} FlagsCondition MapForCbz(FlagsCondition cond) { switch (cond) { case kEqual: // generate CBZ case kNotEqual: // generate CBNZ return cond; case kUnsignedLessThanOrEqual: // generate CBZ return kEqual; case kUnsignedGreaterThan: // generate CBNZ return kNotEqual; default: UNREACHABLE(); } } void EmitBranchOrDeoptimize(InstructionSelector* selector, InstructionCode opcode, InstructionOperand value, FlagsContinuation* cont) { DCHECK(cont->IsBranch() || cont->IsDeoptimize()); selector->EmitWithContinuation(opcode, value, cont); } template <int N> struct CbzOrTbzMatchTrait {}; template <> struct CbzOrTbzMatchTrait<32> { using IntegralType = uint32_t; using BinopMatcher = Int32BinopMatcher; static constexpr IrOpcode::Value kAndOpcode = IrOpcode::kWord32And; static constexpr ArchOpcode kTestAndBranchOpcode = kArm64TestAndBranch32; static constexpr ArchOpcode kCompareAndBranchOpcode = kArm64CompareAndBranch32; static constexpr unsigned kSignBit = kWSignBit; }; template <> struct CbzOrTbzMatchTrait<64> { using IntegralType = uint64_t; using BinopMatcher = Int64BinopMatcher; static constexpr IrOpcode::Value kAndOpcode = IrOpcode::kWord64And; static constexpr ArchOpcode kTestAndBranchOpcode = kArm64TestAndBranch; static constexpr ArchOpcode kCompareAndBranchOpcode = kArm64CompareAndBranch; static constexpr unsigned kSignBit = kXSignBit; }; // Try to emit TBZ, TBNZ, CBZ or CBNZ for certain comparisons of {node} // against {value}, depending on the condition. template <int N> bool TryEmitCbzOrTbz(InstructionSelector* selector, Node* node, typename CbzOrTbzMatchTrait<N>::IntegralType value, Node* user, FlagsCondition cond, FlagsContinuation* cont) { // Branch poisoning requires flags to be set, so when it's enabled for // a particular branch, we shouldn't be applying the cbz/tbz optimization. DCHECK(!cont->IsPoisoned()); // Only handle branches and deoptimisations. if (!cont->IsBranch() && !cont->IsDeoptimize()) return false; switch (cond) { case kSignedLessThan: case kSignedGreaterThanOrEqual: { // Here we handle sign tests, aka. comparisons with zero. if (value != 0) return false; // We don't generate TBZ/TBNZ for deoptimisations, as they have a // shorter range than conditional branches and generating them for // deoptimisations results in more veneers. if (cont->IsDeoptimize()) return false; Arm64OperandGenerator g(selector); cont->Overwrite(MapForTbz(cond)); if (N == 32) { Int32Matcher m(node); if (m.IsFloat64ExtractHighWord32() && selector->CanCover(user, node)) { // SignedLessThan(Float64ExtractHighWord32(x), 0) and // SignedGreaterThanOrEqual(Float64ExtractHighWord32(x), 0) // essentially check the sign bit of a 64-bit floating point value. InstructionOperand temp = g.TempRegister(); selector->Emit(kArm64U64MoveFloat64, temp, g.UseRegister(node->InputAt(0))); selector->EmitWithContinuation(kArm64TestAndBranch, temp, g.TempImmediate(kDSignBit), cont); return true; } } selector->EmitWithContinuation( CbzOrTbzMatchTrait<N>::kTestAndBranchOpcode, g.UseRegister(node), g.TempImmediate(CbzOrTbzMatchTrait<N>::kSignBit), cont); return true; } case kEqual: case kNotEqual: { if (node->opcode() == CbzOrTbzMatchTrait<N>::kAndOpcode) { // Emit a tbz/tbnz if we are comparing with a single-bit mask: // Branch(WordEqual(WordAnd(x, 1 << N), 1 << N), true, false) typename CbzOrTbzMatchTrait<N>::BinopMatcher m_and(node); if (cont->IsBranch() && base::bits::IsPowerOfTwo(value) && m_and.right().Is(value) && selector->CanCover(user, node)) { Arm64OperandGenerator g(selector); // In the code generator, Equal refers to a bit being cleared. We want // the opposite here so negate the condition. cont->Negate(); selector->EmitWithContinuation( CbzOrTbzMatchTrait<N>::kTestAndBranchOpcode, g.UseRegister(m_and.left().node()), g.TempImmediate(base::bits::CountTrailingZeros(value)), cont); return true; } } V8_FALLTHROUGH; } case kUnsignedLessThanOrEqual: case kUnsignedGreaterThan: { if (value != 0) return false; Arm64OperandGenerator g(selector); cont->Overwrite(MapForCbz(cond)); EmitBranchOrDeoptimize(selector, CbzOrTbzMatchTrait<N>::kCompareAndBranchOpcode, g.UseRegister(node), cont); return true; } default: return false; } } // Shared routine for multiple word compare operations. void VisitWordCompare(InstructionSelector* selector, Node* node, InstructionCode opcode, FlagsContinuation* cont, ImmediateMode immediate_mode) { Arm64OperandGenerator g(selector); Node* left = node->InputAt(0); Node* right = node->InputAt(1); // If one of the two inputs is an immediate, make sure it's on the right. if (!g.CanBeImmediate(right, immediate_mode) && g.CanBeImmediate(left, immediate_mode)) { cont->Commute(); std::swap(left, right); } if (opcode == kArm64Cmp && !cont->IsPoisoned()) { Int64Matcher m(right); if (m.HasValue()) { if (TryEmitCbzOrTbz<64>(selector, left, m.Value(), node, cont->condition(), cont)) { return; } } } VisitCompare(selector, opcode, g.UseRegister(left), g.UseOperand(right, immediate_mode), cont); } void VisitWord32Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { Int32BinopMatcher m(node); FlagsCondition cond = cont->condition(); if (!cont->IsPoisoned()) { if (m.right().HasValue()) { if (TryEmitCbzOrTbz<32>(selector, m.left().node(), m.right().Value(), node, cond, cont)) { return; } } else if (m.left().HasValue()) { FlagsCondition commuted_cond = CommuteFlagsCondition(cond); if (TryEmitCbzOrTbz<32>(selector, m.right().node(), m.left().Value(), node, commuted_cond, cont)) { return; } } } ArchOpcode opcode = kArm64Cmp32; ImmediateMode immediate_mode = kArithmeticImm; if (m.right().Is(0) && (m.left().IsInt32Add() || m.left().IsWord32And())) { // Emit flag setting add/and instructions for comparisons against zero. if (CanUseFlagSettingBinop(cond)) { Node* binop = m.left().node(); MaybeReplaceCmpZeroWithFlagSettingBinop(selector, &node, binop, &opcode, cond, cont, &immediate_mode); } } else if (m.left().Is(0) && (m.right().IsInt32Add() || m.right().IsWord32And())) { // Same as above, but we need to commute the condition before we // continue with the rest of the checks. FlagsCondition commuted_cond = CommuteFlagsCondition(cond); if (CanUseFlagSettingBinop(commuted_cond)) { Node* binop = m.right().node(); MaybeReplaceCmpZeroWithFlagSettingBinop(selector, &node, binop, &opcode, commuted_cond, cont, &immediate_mode); } } else if (m.right().IsInt32Sub() && (cond == kEqual || cond == kNotEqual)) { // Select negated compare for comparisons with negated right input. // Only do this for kEqual and kNotEqual, which do not depend on the // C and V flags, as those flags will be different with CMN when the // right-hand side of the original subtraction is INT_MIN. Node* sub = m.right().node(); Int32BinopMatcher msub(sub); if (msub.left().Is(0)) { bool can_cover = selector->CanCover(node, sub); node->ReplaceInput(1, msub.right().node()); // Even if the comparison node covers the subtraction, after the input // replacement above, the node still won't cover the input to the // subtraction; the subtraction still uses it. // In order to get shifted operations to work, we must remove the rhs // input to the subtraction, as TryMatchAnyShift requires this node to // cover the input shift. We do this by setting it to the lhs input, // as we know it's zero, and the result of the subtraction isn't used by // any other node. if (can_cover) sub->ReplaceInput(1, msub.left().node()); opcode = kArm64Cmn32; } } VisitBinop<Int32BinopMatcher>(selector, node, opcode, immediate_mode, cont); } void VisitWordTest(InstructionSelector* selector, Node* node, InstructionCode opcode, FlagsContinuation* cont) { Arm64OperandGenerator g(selector); VisitCompare(selector, opcode, g.UseRegister(node), g.UseRegister(node), cont); } void VisitWord32Test(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { VisitWordTest(selector, node, kArm64Tst32, cont); } void VisitWord64Test(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { VisitWordTest(selector, node, kArm64Tst, cont); } template <typename Matcher> struct TestAndBranchMatcher { TestAndBranchMatcher(Node* node, FlagsContinuation* cont) : matches_(false), cont_(cont), matcher_(node) { Initialize(); } bool Matches() const { return matches_; } unsigned bit() const { DCHECK(Matches()); return base::bits::CountTrailingZeros(matcher_.right().Value()); } Node* input() const { DCHECK(Matches()); return matcher_.left().node(); } private: bool matches_; FlagsContinuation* cont_; Matcher matcher_; void Initialize() { if (cont_->IsBranch() && !cont_->IsPoisoned() && matcher_.right().HasValue() && base::bits::IsPowerOfTwo(matcher_.right().Value())) { // If the mask has only one bit set, we can use tbz/tbnz. DCHECK((cont_->condition() == kEqual) || (cont_->condition() == kNotEqual)); matches_ = true; } else { matches_ = false; } } }; // Shared routine for multiple float32 compare operations. void VisitFloat32Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { Arm64OperandGenerator g(selector); Float32BinopMatcher m(node); if (m.right().Is(0.0f)) { VisitCompare(selector, kArm64Float32Cmp, g.UseRegister(m.left().node()), g.UseImmediate(m.right().node()), cont); } else if (m.left().Is(0.0f)) { cont->Commute(); VisitCompare(selector, kArm64Float32Cmp, g.UseRegister(m.right().node()), g.UseImmediate(m.left().node()), cont); } else { VisitCompare(selector, kArm64Float32Cmp, g.UseRegister(m.left().node()), g.UseRegister(m.right().node()), cont); } } // Shared routine for multiple float64 compare operations. void VisitFloat64Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { Arm64OperandGenerator g(selector); Float64BinopMatcher m(node); if (m.right().Is(0.0)) { VisitCompare(selector, kArm64Float64Cmp, g.UseRegister(m.left().node()), g.UseImmediate(m.right().node()), cont); } else if (m.left().Is(0.0)) { cont->Commute(); VisitCompare(selector, kArm64Float64Cmp, g.UseRegister(m.right().node()), g.UseImmediate(m.left().node()), cont); } else { VisitCompare(selector, kArm64Float64Cmp, g.UseRegister(m.left().node()), g.UseRegister(m.right().node()), cont); } } void VisitAtomicExchange(InstructionSelector* selector, Node* node, ArchOpcode opcode) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); InstructionOperand inputs[] = {g.UseRegister(base), g.UseRegister(index), g.UseUniqueRegister(value)}; InstructionOperand outputs[] = {g.DefineAsRegister(node)}; InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()}; InstructionCode code = opcode | AddressingModeField::encode(kMode_MRR); selector->Emit(code, arraysize(outputs), outputs, arraysize(inputs), inputs, arraysize(temps), temps); } void VisitAtomicCompareExchange(InstructionSelector* selector, Node* node, ArchOpcode opcode) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* old_value = node->InputAt(2); Node* new_value = node->InputAt(3); InstructionOperand inputs[] = {g.UseRegister(base), g.UseRegister(index), g.UseUniqueRegister(old_value), g.UseUniqueRegister(new_value)}; InstructionOperand outputs[] = {g.DefineAsRegister(node)}; InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()}; InstructionCode code = opcode | AddressingModeField::encode(kMode_MRR); selector->Emit(code, arraysize(outputs), outputs, arraysize(inputs), inputs, arraysize(temps), temps); } void VisitAtomicLoad(InstructionSelector* selector, Node* node, ArchOpcode opcode) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); InstructionOperand inputs[] = {g.UseRegister(base), g.UseRegister(index)}; InstructionOperand outputs[] = {g.DefineAsRegister(node)}; InstructionOperand temps[] = {g.TempRegister()}; InstructionCode code = opcode | AddressingModeField::encode(kMode_MRR); selector->Emit(code, arraysize(outputs), outputs, arraysize(inputs), inputs, arraysize(temps), temps); } void VisitAtomicStore(InstructionSelector* selector, Node* node, ArchOpcode opcode) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); InstructionOperand inputs[] = {g.UseRegister(base), g.UseRegister(index), g.UseUniqueRegister(value)}; InstructionOperand temps[] = {g.TempRegister()}; InstructionCode code = opcode | AddressingModeField::encode(kMode_MRR); selector->Emit(code, 0, nullptr, arraysize(inputs), inputs, arraysize(temps), temps); } void VisitAtomicBinop(InstructionSelector* selector, Node* node, ArchOpcode opcode) { Arm64OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); AddressingMode addressing_mode = kMode_MRR; InstructionOperand inputs[] = {g.UseRegister(base), g.UseRegister(index), g.UseUniqueRegister(value)}; InstructionOperand outputs[] = {g.DefineAsRegister(node)}; InstructionOperand temps[] = {g.TempRegister(), g.TempRegister(), g.TempRegister()}; InstructionCode code = opcode | AddressingModeField::encode(addressing_mode); selector->Emit(code, arraysize(outputs), outputs, arraysize(inputs), inputs, arraysize(temps), temps); } } // namespace void InstructionSelector::VisitWordCompareZero(Node* user, Node* value, FlagsContinuation* cont) { Arm64OperandGenerator g(this); // Try to combine with comparisons against 0 by simply inverting the branch. while (value->opcode() == IrOpcode::kWord32Equal && CanCover(user, value)) { Int32BinopMatcher m(value); if (!m.right().Is(0)) break; user = value; value = m.left().node(); cont->Negate(); } // Try to match bit checks to create TBZ/TBNZ instructions. // Unlike the switch below, CanCover check is not needed here. // If there are several uses of the given operation, we will generate a TBZ // instruction for each. This is useful even if there are other uses of the // arithmetic result, because it moves dependencies further back. switch (value->opcode()) { case IrOpcode::kWord64Equal: { Int64BinopMatcher m(value); if (m.right().Is(0)) { Node* const left = m.left().node(); if (left->opcode() == IrOpcode::kWord64And) { // Attempt to merge the Word64Equal(Word64And(x, y), 0) comparison // into a tbz/tbnz instruction. TestAndBranchMatcher<Uint64BinopMatcher> tbm(left, cont); if (tbm.Matches()) { Arm64OperandGenerator gen(this); cont->OverwriteAndNegateIfEqual(kEqual); this->EmitWithContinuation(kArm64TestAndBranch, gen.UseRegister(tbm.input()), gen.TempImmediate(tbm.bit()), cont); return; } } } break; } case IrOpcode::kWord32And: { TestAndBranchMatcher<Uint32BinopMatcher> tbm(value, cont); if (tbm.Matches()) { Arm64OperandGenerator gen(this); this->EmitWithContinuation(kArm64TestAndBranch32, gen.UseRegister(tbm.input()), gen.TempImmediate(tbm.bit()), cont); return; } break; } case IrOpcode::kWord64And: { TestAndBranchMatcher<Uint64BinopMatcher> tbm(value, cont); if (tbm.Matches()) { Arm64OperandGenerator gen(this); this->EmitWithContinuation(kArm64TestAndBranch, gen.UseRegister(tbm.input()), gen.TempImmediate(tbm.bit()), cont); return; } break; } default: break; } if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kWord32Equal: cont->OverwriteAndNegateIfEqual(kEqual); return VisitWord32Compare(this, value, cont); case IrOpcode::kInt32LessThan: cont->OverwriteAndNegateIfEqual(kSignedLessThan); return VisitWord32Compare(this, value, cont); case IrOpcode::kInt32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual); return VisitWord32Compare(this, value, cont); case IrOpcode::kUint32LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitWord32Compare(this, value, cont); case IrOpcode::kUint32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitWord32Compare(this, value, cont); case IrOpcode::kWord64Equal: { cont->OverwriteAndNegateIfEqual(kEqual); Int64BinopMatcher m(value); if (m.right().Is(0)) { Node* const left = m.left().node(); if (CanCover(value, left) && left->opcode() == IrOpcode::kWord64And) { return VisitWordCompare(this, left, kArm64Tst, cont, kLogical64Imm); } } return VisitWordCompare(this, value, kArm64Cmp, cont, kArithmeticImm); } case IrOpcode::kInt64LessThan: cont->OverwriteAndNegateIfEqual(kSignedLessThan); return VisitWordCompare(this, value, kArm64Cmp, cont, kArithmeticImm); case IrOpcode::kInt64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual); return VisitWordCompare(this, value, kArm64Cmp, cont, kArithmeticImm); case IrOpcode::kUint64LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitWordCompare(this, value, kArm64Cmp, cont, kArithmeticImm); case IrOpcode::kUint64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitWordCompare(this, value, kArm64Cmp, cont, kArithmeticImm); case IrOpcode::kFloat32Equal: cont->OverwriteAndNegateIfEqual(kEqual); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat32LessThan: cont->OverwriteAndNegateIfEqual(kFloatLessThan); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kFloatLessThanOrEqual); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat64Equal: cont->OverwriteAndNegateIfEqual(kEqual); return VisitFloat64Compare(this, value, cont); case IrOpcode::kFloat64LessThan: cont->OverwriteAndNegateIfEqual(kFloatLessThan); return VisitFloat64Compare(this, value, cont); case IrOpcode::kFloat64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kFloatLessThanOrEqual); return VisitFloat64Compare(this, value, cont); case IrOpcode::kProjection: // Check if this is the overflow output projection of an // <Operation>WithOverflow node. if (ProjectionIndexOf(value->op()) == 1u) { // We cannot combine the <Operation>WithOverflow with this branch // unless the 0th projection (the use of the actual value of the // <Operation> is either nullptr, which means there's no use of the // actual value, or was already defined, which means it is scheduled // *AFTER* this branch). Node* const node = value->InputAt(0); Node* const result = NodeProperties::FindProjection(node, 0); if (result == nullptr || IsDefined(result)) { switch (node->opcode()) { case IrOpcode::kInt32AddWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32, kArithmeticImm, cont); case IrOpcode::kInt32SubWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32, kArithmeticImm, cont); case IrOpcode::kInt32MulWithOverflow: // ARM64 doesn't set the overflow flag for multiplication, so we // need to test on kNotEqual. Here is the code sequence used: // smull result, left, right // cmp result.X(), Operand(result, SXTW) cont->OverwriteAndNegateIfEqual(kNotEqual); return EmitInt32MulWithOverflow(this, node, cont); case IrOpcode::kInt64AddWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitBinop<Int64BinopMatcher>(this, node, kArm64Add, kArithmeticImm, cont); case IrOpcode::kInt64SubWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitBinop<Int64BinopMatcher>(this, node, kArm64Sub, kArithmeticImm, cont); default: break; } } } break; case IrOpcode::kInt32Add: return VisitWordCompare(this, value, kArm64Cmn32, cont, kArithmeticImm); case IrOpcode::kInt32Sub: return VisitWord32Compare(this, value, cont); case IrOpcode::kWord32And: return VisitWordCompare(this, value, kArm64Tst32, cont, kLogical32Imm); case IrOpcode::kWord64And: return VisitWordCompare(this, value, kArm64Tst, cont, kLogical64Imm); case IrOpcode::kStackPointerGreaterThan: cont->OverwriteAndNegateIfEqual(kStackPointerGreaterThanCondition); return VisitStackPointerGreaterThan(value, cont); default: break; } } // Branch could not be combined with a compare, compare against 0 and branch. if (!cont->IsPoisoned() && cont->IsBranch()) { Emit(cont->Encode(kArm64CompareAndBranch32), g.NoOutput(), g.UseRegister(value), g.Label(cont->true_block()), g.Label(cont->false_block())); } else { EmitWithContinuation(cont->Encode(kArm64Tst32), g.UseRegister(value), g.UseRegister(value), cont); } } void InstructionSelector::VisitSwitch(Node* node, const SwitchInfo& sw) { Arm64OperandGenerator g(this); InstructionOperand value_operand = g.UseRegister(node->InputAt(0)); // Emit either ArchTableSwitch or ArchLookupSwitch. if (enable_switch_jump_table_ == kEnableSwitchJumpTable) { static const size_t kMaxTableSwitchValueRange = 2 << 16; size_t table_space_cost = 4 + sw.value_range(); size_t table_time_cost = 3; size_t lookup_space_cost = 3 + 2 * sw.case_count(); size_t lookup_time_cost = sw.case_count(); if (sw.case_count() > 4 && table_space_cost + 3 * table_time_cost <= lookup_space_cost + 3 * lookup_time_cost && sw.min_value() > std::numeric_limits<int32_t>::min() && sw.value_range() <= kMaxTableSwitchValueRange) { InstructionOperand index_operand = value_operand; if (sw.min_value()) { index_operand = g.TempRegister(); Emit(kArm64Sub32, index_operand, value_operand, g.TempImmediate(sw.min_value())); } // Generate a table lookup. return EmitTableSwitch(sw, index_operand); } } // Generate a tree of conditional jumps. return EmitBinarySearchSwitch(sw, value_operand); } void InstructionSelector::VisitWord32Equal(Node* const node) { Node* const user = node; FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); Int32BinopMatcher m(user); if (m.right().Is(0)) { Node* const value = m.left().node(); if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kInt32Add: case IrOpcode::kWord32And: return VisitWord32Compare(this, node, &cont); case IrOpcode::kInt32Sub: return VisitWordCompare(this, value, kArm64Cmp32, &cont, kArithmeticImm); case IrOpcode::kWord32Equal: { // Word32Equal(Word32Equal(x, y), 0) => Word32Compare(x, y, ne). Int32BinopMatcher mequal(value); node->ReplaceInput(0, mequal.left().node()); node->ReplaceInput(1, mequal.right().node()); cont.Negate(); // {node} still does not cover its new operands, because {mequal} is // still using them. // Since we won't generate any more code for {mequal}, set its // operands to zero to make sure {node} can cover them. // This improves pattern matching in VisitWord32Compare. mequal.node()->ReplaceInput(0, m.right().node()); mequal.node()->ReplaceInput(1, m.right().node()); return VisitWord32Compare(this, node, &cont); } default: break; } return VisitWord32Test(this, value, &cont); } } VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitInt32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitInt32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThanOrEqual, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitUint32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitUint32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitWord64Equal(Node* const node) { Node* const user = node; FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); Int64BinopMatcher m(user); if (m.right().Is(0)) { Node* const value = m.left().node(); if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kWord64And: return VisitWordCompare(this, value, kArm64Tst, &cont, kLogical64Imm); default: break; } return VisitWord64Test(this, value, &cont); } } VisitWordCompare(this, node, kArm64Cmp, &cont, kArithmeticImm); } void InstructionSelector::VisitInt32AddWithOverflow(Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); return VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32, kArithmeticImm, &cont); } FlagsContinuation cont; VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32, kArithmeticImm, &cont); } void InstructionSelector::VisitInt32SubWithOverflow(Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); return VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32, kArithmeticImm, &cont); } FlagsContinuation cont; VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32, kArithmeticImm, &cont); } void InstructionSelector::VisitInt32MulWithOverflow(Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { // ARM64 doesn't set the overflow flag for multiplication, so we need to // test on kNotEqual. Here is the code sequence used: // smull result, left, right // cmp result.X(), Operand(result, SXTW) FlagsContinuation cont = FlagsContinuation::ForSet(kNotEqual, ovf); return EmitInt32MulWithOverflow(this, node, &cont); } FlagsContinuation cont; EmitInt32MulWithOverflow(this, node, &cont); } void InstructionSelector::VisitInt64AddWithOverflow(Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); return VisitBinop<Int64BinopMatcher>(this, node, kArm64Add, kArithmeticImm, &cont); } FlagsContinuation cont; VisitBinop<Int64BinopMatcher>(this, node, kArm64Add, kArithmeticImm, &cont); } void InstructionSelector::VisitInt64SubWithOverflow(Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); return VisitBinop<Int64BinopMatcher>(this, node, kArm64Sub, kArithmeticImm, &cont); } FlagsContinuation cont; VisitBinop<Int64BinopMatcher>(this, node, kArm64Sub, kArithmeticImm, &cont); } void InstructionSelector::VisitInt64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node); VisitWordCompare(this, node, kArm64Cmp, &cont, kArithmeticImm); } void InstructionSelector::VisitInt64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThanOrEqual, node); VisitWordCompare(this, node, kArm64Cmp, &cont, kArithmeticImm); } void InstructionSelector::VisitUint64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitWordCompare(this, node, kArm64Cmp, &cont, kArithmeticImm); } void InstructionSelector::VisitUint64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitWordCompare(this, node, kArm64Cmp, &cont, kArithmeticImm); } void InstructionSelector::VisitFloat32Neg(Node* node) { Arm64OperandGenerator g(this); Node* in = node->InputAt(0); if (in->opcode() == IrOpcode::kFloat32Mul && CanCover(node, in)) { Float32BinopMatcher m(in); Emit(kArm64Float32Fnmul, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(m.right().node())); return; } VisitRR(this, kArm64Float32Neg, node); } void InstructionSelector::VisitFloat32Mul(Node* node) { Arm64OperandGenerator g(this); Float32BinopMatcher m(node); if (m.left().IsFloat32Neg() && CanCover(node, m.left().node())) { Emit(kArm64Float32Fnmul, g.DefineAsRegister(node), g.UseRegister(m.left().node()->InputAt(0)), g.UseRegister(m.right().node())); return; } if (m.right().IsFloat32Neg() && CanCover(node, m.right().node())) { Emit(kArm64Float32Fnmul, g.DefineAsRegister(node), g.UseRegister(m.right().node()->InputAt(0)), g.UseRegister(m.left().node())); return; } return VisitRRR(this, kArm64Float32Mul, node); } void InstructionSelector::VisitFloat32Equal(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kFloatLessThan, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kFloatLessThanOrEqual, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat64Equal(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::VisitFloat64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kFloatLessThan, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::VisitFloat64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kFloatLessThanOrEqual, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::VisitFloat64InsertLowWord32(Node* node) { Arm64OperandGenerator g(this); Node* left = node->InputAt(0); Node* right = node->InputAt(1); if (left->opcode() == IrOpcode::kFloat64InsertHighWord32 && CanCover(node, left)) { Node* right_of_left = left->InputAt(1); Emit(kArm64Bfi, g.DefineSameAsFirst(right), g.UseRegister(right), g.UseRegister(right_of_left), g.TempImmediate(32), g.TempImmediate(32)); Emit(kArm64Float64MoveU64, g.DefineAsRegister(node), g.UseRegister(right)); return; } Emit(kArm64Float64InsertLowWord32, g.DefineSameAsFirst(node), g.UseRegister(left), g.UseRegister(right)); } void InstructionSelector::VisitFloat64InsertHighWord32(Node* node) { Arm64OperandGenerator g(this); Node* left = node->InputAt(0); Node* right = node->InputAt(1); if (left->opcode() == IrOpcode::kFloat64InsertLowWord32 && CanCover(node, left)) { Node* right_of_left = left->InputAt(1); Emit(kArm64Bfi, g.DefineSameAsFirst(left), g.UseRegister(right_of_left), g.UseRegister(right), g.TempImmediate(32), g.TempImmediate(32)); Emit(kArm64Float64MoveU64, g.DefineAsRegister(node), g.UseRegister(left)); return; } Emit(kArm64Float64InsertHighWord32, g.DefineSameAsFirst(node), g.UseRegister(left), g.UseRegister(right)); } void InstructionSelector::VisitFloat64Neg(Node* node) { Arm64OperandGenerator g(this); Node* in = node->InputAt(0); if (in->opcode() == IrOpcode::kFloat64Mul && CanCover(node, in)) { Float64BinopMatcher m(in); Emit(kArm64Float64Fnmul, g.DefineAsRegister(node), g.UseRegister(m.left().node()), g.UseRegister(m.right().node())); return; } VisitRR(this, kArm64Float64Neg, node); } void InstructionSelector::VisitFloat64Mul(Node* node) { Arm64OperandGenerator g(this); Float64BinopMatcher m(node); if (m.left().IsFloat64Neg() && CanCover(node, m.left().node())) { Emit(kArm64Float64Fnmul, g.DefineAsRegister(node), g.UseRegister(m.left().node()->InputAt(0)), g.UseRegister(m.right().node())); return; } if (m.right().IsFloat64Neg() && CanCover(node, m.right().node())) { Emit(kArm64Float64Fnmul, g.DefineAsRegister(node), g.UseRegister(m.right().node()->InputAt(0)), g.UseRegister(m.left().node())); return; } return VisitRRR(this, kArm64Float64Mul, node); } void InstructionSelector::VisitMemoryBarrier(Node* node) { Arm64OperandGenerator g(this); Emit(kArm64DmbIsh, g.NoOutput()); } void InstructionSelector::VisitWord32AtomicLoad(Node* node) { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); ArchOpcode opcode = kArchNop; switch (load_rep.representation()) { case MachineRepresentation::kWord8: opcode = load_rep.IsSigned() ? kWord32AtomicLoadInt8 : kWord32AtomicLoadUint8; break; case MachineRepresentation::kWord16: opcode = load_rep.IsSigned() ? kWord32AtomicLoadInt16 : kWord32AtomicLoadUint16; break; case MachineRepresentation::kWord32: opcode = kWord32AtomicLoadWord32; break; default: UNREACHABLE(); } VisitAtomicLoad(this, node, opcode); } void InstructionSelector::VisitWord64AtomicLoad(Node* node) { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); ArchOpcode opcode = kArchNop; switch (load_rep.representation()) { case MachineRepresentation::kWord8: opcode = kArm64Word64AtomicLoadUint8; break; case MachineRepresentation::kWord16: opcode = kArm64Word64AtomicLoadUint16; break; case MachineRepresentation::kWord32: opcode = kArm64Word64AtomicLoadUint32; break; case MachineRepresentation::kWord64: opcode = kArm64Word64AtomicLoadUint64; break; default: UNREACHABLE(); } VisitAtomicLoad(this, node, opcode); } void InstructionSelector::VisitWord32AtomicStore(Node* node) { MachineRepresentation rep = AtomicStoreRepresentationOf(node->op()); ArchOpcode opcode = kArchNop; switch (rep) { case MachineRepresentation::kWord8: opcode = kWord32AtomicStoreWord8; break; case MachineRepresentation::kWord16: opcode = kWord32AtomicStoreWord16; break; case MachineRepresentation::kWord32: opcode = kWord32AtomicStoreWord32; break; default: UNREACHABLE(); } VisitAtomicStore(this, node, opcode); } void InstructionSelector::VisitWord64AtomicStore(Node* node) { MachineRepresentation rep = AtomicStoreRepresentationOf(node->op()); ArchOpcode opcode = kArchNop; switch (rep) { case MachineRepresentation::kWord8: opcode = kArm64Word64AtomicStoreWord8; break; case MachineRepresentation::kWord16: opcode = kArm64Word64AtomicStoreWord16; break; case MachineRepresentation::kWord32: opcode = kArm64Word64AtomicStoreWord32; break; case MachineRepresentation::kWord64: opcode = kArm64Word64AtomicStoreWord64; break; default: UNREACHABLE(); } VisitAtomicStore(this, node, opcode); } void InstructionSelector::VisitWord32AtomicExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Int8()) { opcode = kWord32AtomicExchangeInt8; } else if (type == MachineType::Uint8()) { opcode = kWord32AtomicExchangeUint8; } else if (type == MachineType::Int16()) { opcode = kWord32AtomicExchangeInt16; } else if (type == MachineType::Uint16()) { opcode = kWord32AtomicExchangeUint16; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = kWord32AtomicExchangeWord32; } else { UNREACHABLE(); return; } VisitAtomicExchange(this, node, opcode); } void InstructionSelector::VisitWord64AtomicExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Uint8()) { opcode = kArm64Word64AtomicExchangeUint8; } else if (type == MachineType::Uint16()) { opcode = kArm64Word64AtomicExchangeUint16; } else if (type == MachineType::Uint32()) { opcode = kArm64Word64AtomicExchangeUint32; } else if (type == MachineType::Uint64()) { opcode = kArm64Word64AtomicExchangeUint64; } else { UNREACHABLE(); return; } VisitAtomicExchange(this, node, opcode); } void InstructionSelector::VisitWord32AtomicCompareExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Int8()) { opcode = kWord32AtomicCompareExchangeInt8; } else if (type == MachineType::Uint8()) { opcode = kWord32AtomicCompareExchangeUint8; } else if (type == MachineType::Int16()) { opcode = kWord32AtomicCompareExchangeInt16; } else if (type == MachineType::Uint16()) { opcode = kWord32AtomicCompareExchangeUint16; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = kWord32AtomicCompareExchangeWord32; } else { UNREACHABLE(); return; } VisitAtomicCompareExchange(this, node, opcode); } void InstructionSelector::VisitWord64AtomicCompareExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Uint8()) { opcode = kArm64Word64AtomicCompareExchangeUint8; } else if (type == MachineType::Uint16()) { opcode = kArm64Word64AtomicCompareExchangeUint16; } else if (type == MachineType::Uint32()) { opcode = kArm64Word64AtomicCompareExchangeUint32; } else if (type == MachineType::Uint64()) { opcode = kArm64Word64AtomicCompareExchangeUint64; } else { UNREACHABLE(); return; } VisitAtomicCompareExchange(this, node, opcode); } void InstructionSelector::VisitWord32AtomicBinaryOperation( Node* node, ArchOpcode int8_op, ArchOpcode uint8_op, ArchOpcode int16_op, ArchOpcode uint16_op, ArchOpcode word32_op) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Int8()) { opcode = int8_op; } else if (type == MachineType::Uint8()) { opcode = uint8_op; } else if (type == MachineType::Int16()) { opcode = int16_op; } else if (type == MachineType::Uint16()) { opcode = uint16_op; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = word32_op; } else { UNREACHABLE(); return; } VisitAtomicBinop(this, node, opcode); } #define VISIT_ATOMIC_BINOP(op) \ void InstructionSelector::VisitWord32Atomic##op(Node* node) { \ VisitWord32AtomicBinaryOperation( \ node, kWord32Atomic##op##Int8, kWord32Atomic##op##Uint8, \ kWord32Atomic##op##Int16, kWord32Atomic##op##Uint16, \ kWord32Atomic##op##Word32); \ } VISIT_ATOMIC_BINOP(Add) VISIT_ATOMIC_BINOP(Sub) VISIT_ATOMIC_BINOP(And) VISIT_ATOMIC_BINOP(Or) VISIT_ATOMIC_BINOP(Xor) #undef VISIT_ATOMIC_BINOP void InstructionSelector::VisitWord64AtomicBinaryOperation( Node* node, ArchOpcode uint8_op, ArchOpcode uint16_op, ArchOpcode uint32_op, ArchOpcode uint64_op) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Uint8()) { opcode = uint8_op; } else if (type == MachineType::Uint16()) { opcode = uint16_op; } else if (type == MachineType::Uint32()) { opcode = uint32_op; } else if (type == MachineType::Uint64()) { opcode = uint64_op; } else { UNREACHABLE(); return; } VisitAtomicBinop(this, node, opcode); } #define VISIT_ATOMIC_BINOP(op) \ void InstructionSelector::VisitWord64Atomic##op(Node* node) { \ VisitWord64AtomicBinaryOperation( \ node, kArm64Word64Atomic##op##Uint8, kArm64Word64Atomic##op##Uint16, \ kArm64Word64Atomic##op##Uint32, kArm64Word64Atomic##op##Uint64); \ } VISIT_ATOMIC_BINOP(Add) VISIT_ATOMIC_BINOP(Sub) VISIT_ATOMIC_BINOP(And) VISIT_ATOMIC_BINOP(Or) VISIT_ATOMIC_BINOP(Xor) #undef VISIT_ATOMIC_BINOP void InstructionSelector::VisitInt32AbsWithOverflow(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitInt64AbsWithOverflow(Node* node) { UNREACHABLE(); } #define SIMD_TYPE_LIST(V) \ V(F64x2) \ V(F32x4) \ V(I64x2) \ V(I32x4) \ V(I16x8) \ V(I8x16) #define SIMD_UNOP_LIST(V) \ V(F64x2Abs, kArm64F64x2Abs) \ V(F64x2Neg, kArm64F64x2Neg) \ V(F64x2Sqrt, kArm64F64x2Sqrt) \ V(F32x4SConvertI32x4, kArm64F32x4SConvertI32x4) \ V(F32x4UConvertI32x4, kArm64F32x4UConvertI32x4) \ V(F32x4Abs, kArm64F32x4Abs) \ V(F32x4Neg, kArm64F32x4Neg) \ V(F32x4Sqrt, kArm64F32x4Sqrt) \ V(F32x4RecipApprox, kArm64F32x4RecipApprox) \ V(F32x4RecipSqrtApprox, kArm64F32x4RecipSqrtApprox) \ V(I64x2Neg, kArm64I64x2Neg) \ V(I32x4SConvertF32x4, kArm64I32x4SConvertF32x4) \ V(I32x4SConvertI16x8Low, kArm64I32x4SConvertI16x8Low) \ V(I32x4SConvertI16x8High, kArm64I32x4SConvertI16x8High) \ V(I32x4Neg, kArm64I32x4Neg) \ V(I32x4UConvertF32x4, kArm64I32x4UConvertF32x4) \ V(I32x4UConvertI16x8Low, kArm64I32x4UConvertI16x8Low) \ V(I32x4UConvertI16x8High, kArm64I32x4UConvertI16x8High) \ V(I16x8SConvertI8x16Low, kArm64I16x8SConvertI8x16Low) \ V(I16x8SConvertI8x16High, kArm64I16x8SConvertI8x16High) \ V(I16x8Neg, kArm64I16x8Neg) \ V(I16x8UConvertI8x16Low, kArm64I16x8UConvertI8x16Low) \ V(I16x8UConvertI8x16High, kArm64I16x8UConvertI8x16High) \ V(I8x16Neg, kArm64I8x16Neg) \ V(S128Not, kArm64S128Not) \ V(S1x2AnyTrue, kArm64S1x2AnyTrue) \ V(S1x2AllTrue, kArm64S1x2AllTrue) \ V(S1x4AnyTrue, kArm64S1x4AnyTrue) \ V(S1x4AllTrue, kArm64S1x4AllTrue) \ V(S1x8AnyTrue, kArm64S1x8AnyTrue) \ V(S1x8AllTrue, kArm64S1x8AllTrue) \ V(S1x16AnyTrue, kArm64S1x16AnyTrue) \ V(S1x16AllTrue, kArm64S1x16AllTrue) #define SIMD_SHIFT_OP_LIST(V) \ V(I64x2Shl) \ V(I64x2ShrS) \ V(I64x2ShrU) \ V(I32x4Shl) \ V(I32x4ShrS) \ V(I32x4ShrU) \ V(I16x8Shl) \ V(I16x8ShrS) \ V(I16x8ShrU) \ V(I8x16Shl) \ V(I8x16ShrS) \ V(I8x16ShrU) #define SIMD_BINOP_LIST(V) \ V(F64x2Add, kArm64F64x2Add) \ V(F64x2Sub, kArm64F64x2Sub) \ V(F64x2Mul, kArm64F64x2Mul) \ V(F64x2Div, kArm64F64x2Div) \ V(F64x2Min, kArm64F64x2Min) \ V(F64x2Max, kArm64F64x2Max) \ V(F64x2Eq, kArm64F64x2Eq) \ V(F64x2Ne, kArm64F64x2Ne) \ V(F64x2Lt, kArm64F64x2Lt) \ V(F64x2Le, kArm64F64x2Le) \ V(F32x4Add, kArm64F32x4Add) \ V(F32x4AddHoriz, kArm64F32x4AddHoriz) \ V(F32x4Sub, kArm64F32x4Sub) \ V(F32x4Mul, kArm64F32x4Mul) \ V(F32x4Div, kArm64F32x4Div) \ V(F32x4Min, kArm64F32x4Min) \ V(F32x4Max, kArm64F32x4Max) \ V(F32x4Eq, kArm64F32x4Eq) \ V(F32x4Ne, kArm64F32x4Ne) \ V(F32x4Lt, kArm64F32x4Lt) \ V(F32x4Le, kArm64F32x4Le) \ V(I64x2Add, kArm64I64x2Add) \ V(I64x2Sub, kArm64I64x2Sub) \ V(I64x2Eq, kArm64I64x2Eq) \ V(I64x2Ne, kArm64I64x2Ne) \ V(I64x2GtS, kArm64I64x2GtS) \ V(I64x2GeS, kArm64I64x2GeS) \ V(I64x2GtU, kArm64I64x2GtU) \ V(I64x2GeU, kArm64I64x2GeU) \ V(I32x4Add, kArm64I32x4Add) \ V(I32x4AddHoriz, kArm64I32x4AddHoriz) \ V(I32x4Sub, kArm64I32x4Sub) \ V(I32x4Mul, kArm64I32x4Mul) \ V(I32x4MinS, kArm64I32x4MinS) \ V(I32x4MaxS, kArm64I32x4MaxS) \ V(I32x4Eq, kArm64I32x4Eq) \ V(I32x4Ne, kArm64I32x4Ne) \ V(I32x4GtS, kArm64I32x4GtS) \ V(I32x4GeS, kArm64I32x4GeS) \ V(I32x4MinU, kArm64I32x4MinU) \ V(I32x4MaxU, kArm64I32x4MaxU) \ V(I32x4GtU, kArm64I32x4GtU) \ V(I32x4GeU, kArm64I32x4GeU) \ V(I16x8SConvertI32x4, kArm64I16x8SConvertI32x4) \ V(I16x8Add, kArm64I16x8Add) \ V(I16x8AddSaturateS, kArm64I16x8AddSaturateS) \ V(I16x8AddHoriz, kArm64I16x8AddHoriz) \ V(I16x8Sub, kArm64I16x8Sub) \ V(I16x8SubSaturateS, kArm64I16x8SubSaturateS) \ V(I16x8Mul, kArm64I16x8Mul) \ V(I16x8MinS, kArm64I16x8MinS) \ V(I16x8MaxS, kArm64I16x8MaxS) \ V(I16x8Eq, kArm64I16x8Eq) \ V(I16x8Ne, kArm64I16x8Ne) \ V(I16x8GtS, kArm64I16x8GtS) \ V(I16x8GeS, kArm64I16x8GeS) \ V(I16x8UConvertI32x4, kArm64I16x8UConvertI32x4) \ V(I16x8AddSaturateU, kArm64I16x8AddSaturateU) \ V(I16x8SubSaturateU, kArm64I16x8SubSaturateU) \ V(I16x8MinU, kArm64I16x8MinU) \ V(I16x8MaxU, kArm64I16x8MaxU) \ V(I16x8GtU, kArm64I16x8GtU) \ V(I16x8GeU, kArm64I16x8GeU) \ V(I8x16SConvertI16x8, kArm64I8x16SConvertI16x8) \ V(I8x16Add, kArm64I8x16Add) \ V(I8x16AddSaturateS, kArm64I8x16AddSaturateS) \ V(I8x16Sub, kArm64I8x16Sub) \ V(I8x16SubSaturateS, kArm64I8x16SubSaturateS) \ V(I8x16Mul, kArm64I8x16Mul) \ V(I8x16MinS, kArm64I8x16MinS) \ V(I8x16MaxS, kArm64I8x16MaxS) \ V(I8x16Eq, kArm64I8x16Eq) \ V(I8x16Ne, kArm64I8x16Ne) \ V(I8x16GtS, kArm64I8x16GtS) \ V(I8x16GeS, kArm64I8x16GeS) \ V(I8x16UConvertI16x8, kArm64I8x16UConvertI16x8) \ V(I8x16AddSaturateU, kArm64I8x16AddSaturateU) \ V(I8x16SubSaturateU, kArm64I8x16SubSaturateU) \ V(I8x16MinU, kArm64I8x16MinU) \ V(I8x16MaxU, kArm64I8x16MaxU) \ V(I8x16GtU, kArm64I8x16GtU) \ V(I8x16GeU, kArm64I8x16GeU) \ V(S128And, kArm64S128And) \ V(S128Or, kArm64S128Or) \ V(S128Xor, kArm64S128Xor) void InstructionSelector::VisitS128Zero(Node* node) { Arm64OperandGenerator g(this); Emit(kArm64S128Zero, g.DefineAsRegister(node)); } #define SIMD_VISIT_SPLAT(Type) \ void InstructionSelector::Visit##Type##Splat(Node* node) { \ VisitRR(this, kArm64##Type##Splat, node); \ } SIMD_TYPE_LIST(SIMD_VISIT_SPLAT) #undef SIMD_VISIT_SPLAT #define SIMD_VISIT_EXTRACT_LANE(Type) \ void InstructionSelector::Visit##Type##ExtractLane(Node* node) { \ VisitRRI(this, kArm64##Type##ExtractLane, node); \ } SIMD_TYPE_LIST(SIMD_VISIT_EXTRACT_LANE) #undef SIMD_VISIT_EXTRACT_LANE #define SIMD_VISIT_REPLACE_LANE(Type) \ void InstructionSelector::Visit##Type##ReplaceLane(Node* node) { \ VisitRRIR(this, kArm64##Type##ReplaceLane, node); \ } SIMD_TYPE_LIST(SIMD_VISIT_REPLACE_LANE) #undef SIMD_VISIT_REPLACE_LANE #undef SIMD_TYPE_LIST #define SIMD_VISIT_UNOP(Name, instruction) \ void InstructionSelector::Visit##Name(Node* node) { \ VisitRR(this, instruction, node); \ } SIMD_UNOP_LIST(SIMD_VISIT_UNOP) #undef SIMD_VISIT_UNOP #undef SIMD_UNOP_LIST #define SIMD_VISIT_SHIFT_OP(Name) \ void InstructionSelector::Visit##Name(Node* node) { \ VisitSimdShiftRRR(this, kArm64##Name, node); \ } SIMD_SHIFT_OP_LIST(SIMD_VISIT_SHIFT_OP) #undef SIMD_VISIT_SHIFT_OP #undef SIMD_SHIFT_OP_LIST #define SIMD_VISIT_BINOP(Name, instruction) \ void InstructionSelector::Visit##Name(Node* node) { \ VisitRRR(this, instruction, node); \ } SIMD_BINOP_LIST(SIMD_VISIT_BINOP) #undef SIMD_VISIT_BINOP #undef SIMD_BINOP_LIST void InstructionSelector::VisitI64x2Mul(Node* node) { Arm64OperandGenerator g(this); InstructionOperand temps[] = {g.TempSimd128Register()}; Emit(kArm64I64x2Mul, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)), arraysize(temps), temps); } void InstructionSelector::VisitS128Select(Node* node) { Arm64OperandGenerator g(this); Emit(kArm64S128Select, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)), g.UseRegister(node->InputAt(2))); } #define VISIT_SIMD_QFMOP(op) \ void InstructionSelector::Visit##op(Node* node) { \ Arm64OperandGenerator g(this); \ Emit(kArm64##op, g.DefineSameAsFirst(node), \ g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(1)), \ g.UseRegister(node->InputAt(2))); \ } VISIT_SIMD_QFMOP(F64x2Qfma) VISIT_SIMD_QFMOP(F64x2Qfms) VISIT_SIMD_QFMOP(F32x4Qfma) VISIT_SIMD_QFMOP(F32x4Qfms) #undef VISIT_SIMD_QFMOP namespace { struct ShuffleEntry { uint8_t shuffle[kSimd128Size]; ArchOpcode opcode; }; static const ShuffleEntry arch_shuffles[] = { {{0, 1, 2, 3, 16, 17, 18, 19, 4, 5, 6, 7, 20, 21, 22, 23}, kArm64S32x4ZipLeft}, {{8, 9, 10, 11, 24, 25, 26, 27, 12, 13, 14, 15, 28, 29, 30, 31}, kArm64S32x4ZipRight}, {{0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27}, kArm64S32x4UnzipLeft}, {{4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31}, kArm64S32x4UnzipRight}, {{0, 1, 2, 3, 16, 17, 18, 19, 8, 9, 10, 11, 24, 25, 26, 27}, kArm64S32x4TransposeLeft}, {{4, 5, 6, 7, 20, 21, 22, 23, 12, 13, 14, 15, 21, 22, 23, 24}, kArm64S32x4TransposeRight}, {{4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11}, kArm64S32x2Reverse}, {{0, 1, 16, 17, 2, 3, 18, 19, 4, 5, 20, 21, 6, 7, 22, 23}, kArm64S16x8ZipLeft}, {{8, 9, 24, 25, 10, 11, 26, 27, 12, 13, 28, 29, 14, 15, 30, 31}, kArm64S16x8ZipRight}, {{0, 1, 4, 5, 8, 9, 12, 13, 16, 17, 20, 21, 24, 25, 28, 29}, kArm64S16x8UnzipLeft}, {{2, 3, 6, 7, 10, 11, 14, 15, 18, 19, 22, 23, 26, 27, 30, 31}, kArm64S16x8UnzipRight}, {{0, 1, 16, 17, 4, 5, 20, 21, 8, 9, 24, 25, 12, 13, 28, 29}, kArm64S16x8TransposeLeft}, {{2, 3, 18, 19, 6, 7, 22, 23, 10, 11, 26, 27, 14, 15, 30, 31}, kArm64S16x8TransposeRight}, {{6, 7, 4, 5, 2, 3, 0, 1, 14, 15, 12, 13, 10, 11, 8, 9}, kArm64S16x4Reverse}, {{2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13}, kArm64S16x2Reverse}, {{0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23}, kArm64S8x16ZipLeft}, {{8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31}, kArm64S8x16ZipRight}, {{0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30}, kArm64S8x16UnzipLeft}, {{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31}, kArm64S8x16UnzipRight}, {{0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30}, kArm64S8x16TransposeLeft}, {{1, 17, 3, 19, 5, 21, 7, 23, 9, 25, 11, 27, 13, 29, 15, 31}, kArm64S8x16TransposeRight}, {{7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8}, kArm64S8x8Reverse}, {{3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12}, kArm64S8x4Reverse}, {{1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14}, kArm64S8x2Reverse}}; bool TryMatchArchShuffle(const uint8_t* shuffle, const ShuffleEntry* table, size_t num_entries, bool is_swizzle, ArchOpcode* opcode) { uint8_t mask = is_swizzle ? kSimd128Size - 1 : 2 * kSimd128Size - 1; for (size_t i = 0; i < num_entries; i++) { const ShuffleEntry& entry = table[i]; int j = 0; for (; j < kSimd128Size; j++) { if ((entry.shuffle[j] & mask) != (shuffle[j] & mask)) { break; } } if (j == kSimd128Size) { *opcode = entry.opcode; return true; } } return false; } void ArrangeShuffleTable(Arm64OperandGenerator* g, Node* input0, Node* input1, InstructionOperand* src0, InstructionOperand* src1) { if (input0 == input1) { // Unary, any q-register can be the table. *src0 = *src1 = g->UseRegister(input0); } else { // Binary, table registers must be consecutive. *src0 = g->UseFixed(input0, fp_fixed1); *src1 = g->UseFixed(input1, fp_fixed2); } } } // namespace void InstructionSelector::VisitS8x16Shuffle(Node* node) { uint8_t shuffle[kSimd128Size]; bool is_swizzle; CanonicalizeShuffle(node, shuffle, &is_swizzle); uint8_t shuffle32x4[4]; Arm64OperandGenerator g(this); ArchOpcode opcode; if (TryMatchArchShuffle(shuffle, arch_shuffles, arraysize(arch_shuffles), is_swizzle, &opcode)) { VisitRRR(this, opcode, node); return; } Node* input0 = node->InputAt(0); Node* input1 = node->InputAt(1); uint8_t offset; if (TryMatchConcat(shuffle, &offset)) { Emit(kArm64S8x16Concat, g.DefineAsRegister(node), g.UseRegister(input0), g.UseRegister(input1), g.UseImmediate(offset)); return; } int index = 0; if (TryMatch32x4Shuffle(shuffle, shuffle32x4)) { if (TryMatchDup<4>(shuffle, &index)) { DCHECK_GT(4, index); Emit(kArm64S128Dup, g.DefineAsRegister(node), g.UseRegister(input0), g.UseImmediate(4), g.UseImmediate(index % 4)); } else if (TryMatchIdentity(shuffle)) { EmitIdentity(node); } else { Emit(kArm64S32x4Shuffle, g.DefineAsRegister(node), g.UseRegister(input0), g.UseRegister(input1), g.UseImmediate(Pack4Lanes(shuffle32x4))); } return; } if (TryMatchDup<8>(shuffle, &index)) { DCHECK_GT(8, index); Emit(kArm64S128Dup, g.DefineAsRegister(node), g.UseRegister(input0), g.UseImmediate(8), g.UseImmediate(index % 8)); return; } if (TryMatchDup<16>(shuffle, &index)) { DCHECK_GT(16, index); Emit(kArm64S128Dup, g.DefineAsRegister(node), g.UseRegister(input0), g.UseImmediate(16), g.UseImmediate(index % 16)); return; } // Code generator uses vtbl, arrange sources to form a valid lookup table. InstructionOperand src0, src1; ArrangeShuffleTable(&g, input0, input1, &src0, &src1); Emit(kArm64S8x16Shuffle, g.DefineAsRegister(node), src0, src1, g.UseImmediate(Pack4Lanes(shuffle)), g.UseImmediate(Pack4Lanes(shuffle + 4)), g.UseImmediate(Pack4Lanes(shuffle + 8)), g.UseImmediate(Pack4Lanes(shuffle + 12))); } void InstructionSelector::VisitSignExtendWord8ToInt32(Node* node) { VisitRR(this, kArm64Sxtb32, node); } void InstructionSelector::VisitSignExtendWord16ToInt32(Node* node) { VisitRR(this, kArm64Sxth32, node); } void InstructionSelector::VisitSignExtendWord8ToInt64(Node* node) { VisitRR(this, kArm64Sxtb, node); } void InstructionSelector::VisitSignExtendWord16ToInt64(Node* node) { VisitRR(this, kArm64Sxth, node); } void InstructionSelector::VisitSignExtendWord32ToInt64(Node* node) { VisitRR(this, kArm64Sxtw, node); } // static MachineOperatorBuilder::Flags InstructionSelector::SupportedMachineOperatorFlags() { return MachineOperatorBuilder::kFloat32RoundDown | MachineOperatorBuilder::kFloat64RoundDown | MachineOperatorBuilder::kFloat32RoundUp | MachineOperatorBuilder::kFloat64RoundUp | MachineOperatorBuilder::kFloat32RoundTruncate | MachineOperatorBuilder::kFloat64RoundTruncate | MachineOperatorBuilder::kFloat64RoundTiesAway | MachineOperatorBuilder::kFloat32RoundTiesEven | MachineOperatorBuilder::kFloat64RoundTiesEven | MachineOperatorBuilder::kWord32ShiftIsSafe | MachineOperatorBuilder::kInt32DivIsSafe | MachineOperatorBuilder::kUint32DivIsSafe | MachineOperatorBuilder::kWord32ReverseBits | MachineOperatorBuilder::kWord64ReverseBits; } // static MachineOperatorBuilder::AlignmentRequirements InstructionSelector::AlignmentRequirements() { return MachineOperatorBuilder::AlignmentRequirements:: FullUnalignedAccessSupport(); } } // namespace compiler } // namespace internal } // namespace v8
#include <boost/log/sinks/syslog_backend.hpp>
//+--------------------------------------------------------------------------- // // Microsoft Forms // Copyright (C) Microsoft Corporation, 1996 // // File: baseprot.cxx // // Contents: Implementation of a base class for pluggable protocols // // History: 02-12-97 AnandRa Created // //---------------------------------------------------------------------------- #include "headers.hxx" #ifndef X_UWININET_H_ #define X_UWININET_H_ #include "uwininet.h" #endif #ifndef X_BASEPROT_HXX_ #define X_BASEPROT_HXX_ #include "baseprot.hxx" #endif //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::QueryInterface // // Synopsis: per IPrivateUnknown // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::QueryInterface(REFIID riid, void **ppv) { *ppv = NULL; if (riid == IID_IInternetProtocolInfo) { *ppv = (IInternetProtocolInfo *)this; } else { RRETURN(super::QueryInterface(riid, ppv)); } Assert(*ppv); ((IUnknown *)*ppv)->AddRef(); return S_OK; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::ParseUrl // // Synopsis: per IInternetProtocolInfo // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::ParseUrl( LPCWSTR pwzUrl, PARSEACTION ParseAction, DWORD dwFlags, LPWSTR pwzResult, DWORD cchResult, DWORD * pcchResult, DWORD dwReserved) { CStr cstr; HRESULT hr = INET_E_DEFAULT_ACTION; if (!pcchResult || !pwzResult) { hr = E_POINTER; goto Cleanup; } if (ParseAction == PARSE_DOMAIN) { BSTR bstrTemp; hr = THR(UnwrapSpecialUrl(pwzUrl, cstr)); if (hr) goto Cleanup; *pcchResult = cstr.Length() + 1; if (cstr.Length() + 1 > cchResult) { // Not enough room hr = S_FALSE; goto Cleanup; } cstr.AllocBSTR(&bstrTemp); #ifdef WIN16 Assert(0); #else UrlGetPartW(bstrTemp, pwzResult, pcchResult, URL_PART_HOSTNAME, 0); #endif SysFreeString(bstrTemp); } Cleanup: RRETURN2(hr, INET_E_DEFAULT_ACTION, S_FALSE); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::CombineUrl // // Synopsis: per IInternetProtocolInfo // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::CombineUrl( LPCWSTR pwzBaseUrl, LPCWSTR pwzRelativeUrl, DWORD dwFlags, LPWSTR pwzResult, DWORD cchResult, DWORD * pcchResult, DWORD dwReserved) { HRESULT hr = INET_E_DEFAULT_ACTION; // get the correct base url for navigating to a non-pluggable protocol from a // pluggable protocol. We get here from CoInternetCombineUrl if the base url is // a pluggable protocol. So, search for the last embedded \1 to extract the true // base url and if present, call the API again to combine the non-pluggable // protocol url properly. if not prest, just tell urlmon to do the default thing. if (pwzBaseUrl) { TCHAR *pchSrc = _tcsrchr(pwzBaseUrl, _T('\1')); if (pchSrc) { hr = THR(CoInternetCombineUrl( ++pchSrc, pwzRelativeUrl, URL_ESCAPE_SPACES_ONLY, pwzResult, cchResult, pcchResult, 0)); } } RRETURN1(hr, INET_E_DEFAULT_ACTION); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::CompareUrl // // Synopsis: per IInternetProtocolInfo // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::CompareUrl( LPCWSTR pwzUrl1, LPCWSTR pwzUrl2, DWORD dwFlags) { RRETURN(E_NOTIMPL); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::QueryInfo // // Synopsis: per IInternetProtocolInfo // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::QueryInfo( LPCWSTR pwzUrl, QUERYOPTION QueryOption, DWORD dwQueryFlags, LPVOID pvBuffer, DWORD cbBuffer, DWORD * pcbBuffer, DWORD dwReserved) { HRESULT hr = INET_E_DEFAULT_ACTION; switch (QueryOption) { case QUERY_USES_NETWORK: { if (!pvBuffer || cbBuffer < sizeof(DWORD)) return E_FAIL; if (pcbBuffer) { *pcbBuffer = sizeof(DWORD); } *(DWORD *)pvBuffer = FALSE; hr = S_OK; } break; case QUERY_IS_SECURE: { if (!pvBuffer || cbBuffer < sizeof(DWORD)) return E_FAIL; if (pcbBuffer) { *pcbBuffer = sizeof(DWORD); } *(DWORD *)pvBuffer = HasSecureContext(pwzUrl); hr = S_OK; } break; } RRETURN1(hr, INET_E_DEFAULT_ACTION); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocolCF::UnwrapSpecialUrl // // Synopsis: Helper to unwrap a url by lopping off any stuff after \1 // //---------------------------------------------------------------------------- HRESULT CBaseProtocolCF::UnwrapSpecialUrl(LPCWSTR pchUrl, CStr &cstrUnwrappedUrl) { TCHAR * pchSpecial = NULL; HRESULT hr = S_OK; TCHAR ach[pdlUrlLen]; DWORD dwSize; hr = THR(CoInternetParseUrl( pchUrl, PARSE_ENCODE, 0, ach, ARRAY_SIZE(ach), &dwSize, 0)); if (hr) goto Cleanup; pchSpecial = _tcsrchr(ach, _T('\1')); if (pchSpecial) { hr = THR(cstrUnwrappedUrl.Set(pchSpecial + 1)); if (hr) goto Cleanup; } else { hr = THR(cstrUnwrappedUrl.Set(ach)); if (hr) goto Cleanup; } Cleanup: RRETURN(hr); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::CBaseProtocol // // Synopsis: ctor // //---------------------------------------------------------------------------- CBaseProtocol::CBaseProtocol(IUnknown *pUnkOuter) : super() { _pUnkOuter = pUnkOuter ? pUnkOuter : PunkInner(); _bscf = BSCF_FIRSTDATANOTIFICATION; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::~CBaseProtocol // // Synopsis: dtor // //---------------------------------------------------------------------------- CBaseProtocol::~CBaseProtocol() { } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Passivate // // Synopsis: 1st stage dtor // //---------------------------------------------------------------------------- void CBaseProtocol::Passivate() { ClearInterface(&_pStm); super::Passivate(); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::PrivateQueryInterface // // Synopsis: per IPrivateUnknown // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::PrivateQueryInterface(REFIID riid, void **ppv) { *ppv = NULL; if (riid == IID_IUnknown) { *ppv = PunkInner(); } else if (riid == IID_IInternetProtocol || riid == IID_IInternetProtocolRoot) { *ppv = (IInternetProtocol *)this; } else if (riid == IID_IServiceProvider) { *ppv = (IServiceProvider *)this; } else { RRETURN(E_NOINTERFACE); } Assert(*ppv); ((IUnknown *)*ppv)->AddRef(); return S_OK; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Start // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Start( LPCWSTR pchUrl, IInternetProtocolSink *pTrans, IInternetBindInfo *pOIBindInfo, DWORD grfSTI, HANDLE_PTR dwReserved) { HRESULT hr = NOERROR; PROTOCOLDATA protdata; TCHAR ach[pdlUrlLen]; DWORD dwSize; Assert(!_pProtSink && pOIBindInfo && pTrans && !_cstrURL); if ( !(grfSTI & PI_PARSE_URL)) { ReplaceInterface(&_pProtSink, pTrans); ReplaceInterface(&_pOIBindInfo, pOIBindInfo); } _bindinfo.cbSize = sizeof(BINDINFO); hr = THR(pOIBindInfo->GetBindInfo(&_grfBindF, &_bindinfo)); // // First get the basic url. Unescape it first. // hr = THR(CoInternetParseUrl(pchUrl, PARSE_ENCODE, 0, ach, ARRAY_SIZE(ach), &dwSize, 0)); if (hr) goto Cleanup; hr = THR(_cstrURL.Set(ach)); if (hr) goto Cleanup; // // Now append any extra data if needed. // if (_bindinfo.szExtraInfo) { hr = THR(_cstrURL.Append(_bindinfo.szExtraInfo)); if (hr) goto Cleanup; } _grfSTI = grfSTI; // // Always go async and return E_PENDING now. // Perform script execution when we get the Continue. // hr = E_PENDING; protdata.grfFlags = PI_FORCE_ASYNC; protdata.dwState = BIND_ASYNC; protdata.pData = NULL; protdata.cbData = 0; _pProtSink->Switch(&protdata); Cleanup: RRETURN(hr); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Continue // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Continue(PROTOCOLDATA *pStateInfoIn) { HRESULT hr = E_FAIL; Assert(!pStateInfoIn->pData && !pStateInfoIn->cbData && pStateInfoIn->dwState == BIND_ASYNC); if (pStateInfoIn->dwState == BIND_ASYNC) { hr = THR(ParseAndBind()); } RRETURN(hr); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Abort // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Abort(HRESULT hrReason, DWORD dwOptions) { _fAborted = TRUE; RRETURN(_pProtSink->ReportResult(E_ABORT, 0, 0)); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Terminate // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Terminate(DWORD dwOptions) { ClearInterface(&_pOIBindInfo); ClearInterface(&_pProtSink); ReleaseBindInfo(&_bindinfo); return S_OK; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Suspend // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Suspend() { RRETURN(E_NOTIMPL); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Resume // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Resume() { RRETURN(E_NOTIMPL); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Read // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Read(void *pv,ULONG cb,ULONG *pcbRead) { HRESULT hr = S_OK; if (!_pStm) { hr = E_FAIL; } else { hr = THR(_pStm->Read(pv, cb, pcbRead)); } RRETURN1(hr, S_FALSE); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::Seek // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::Seek( LARGE_INTEGER dlibMove, DWORD dwOrigin, ULARGE_INTEGER *plibNewPosition) { HRESULT hr = S_OK; if (!_pStm) { hr = E_FAIL; } else { hr = THR(_pStm->Seek(dlibMove, dwOrigin, plibNewPosition)); } RRETURN(hr); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::LockRequest // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::LockRequest(DWORD dwOptions) { return S_OK; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::UnlockRequest // // Synopsis: per IInternetProtocol // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::UnlockRequest() { return S_OK; } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::QueryService // // Synopsis: per IServiceProvider // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::QueryService(REFGUID rsid, REFIID riid, void ** ppv) { HRESULT hr = S_OK; IServiceProvider * pSP = NULL; *ppv = NULL; hr = THR_NOTRACE(_pProtSink->QueryInterface( IID_IServiceProvider, (void **)&pSP)); if (hr) goto Cleanup; hr = THR_NOTRACE(pSP->QueryService(rsid, riid, ppv)); if (hr) goto Cleanup; Cleanup: ReleaseInterface(pSP); RRETURN(hr); } //+--------------------------------------------------------------------------- // // Method: CBaseProtocol::ParseAndBind // // Synopsis: Actually perform the binding. // Derived classes should just implement this one method // //---------------------------------------------------------------------------- HRESULT CBaseProtocol::ParseAndBind() { if (_pProtSink) { _pProtSink->ReportResult(E_UNEXPECTED, 0, 0); } return S_OK; } //+--------------------------------------------------------------------------- // // Method: HasSecureContext // // Synopsis: Scans a \1-style URL to see if it should be treated as secure // //---------------------------------------------------------------------------- BOOL HasSecureContext(const TCHAR *pchUrl) { TCHAR *pchSpecial; TCHAR *pchNext; TCHAR ach[pdlUrlLen]; DWORD dwSize; if (! THR(CoInternetParseUrl( pchUrl, PARSE_ENCODE, 0, ach, ARRAY_SIZE(ach), &dwSize, 0))) { // 1. scan for \1\1 - if present, we have mixed security somewhere along the way pchSpecial = ach; for (;;) { pchNext = _tcschr(pchSpecial, _T('\1')); if (!pchNext) break; pchSpecial = pchNext + 1; // Mixed security or missing context: not secure if (*pchSpecial == _T('\1') || *pchSpecial == _T('\0')) return FALSE; } // Last context is https: secure if (pchSpecial && URL_SCHEME_HTTPS == GetUrlScheme(pchSpecial)) return TRUE; } return FALSE; }
/* * Copyright (C) 2021 Patrick Mours * License: https://github.com/crosire/reshade#license */ #pragma once #include "reshade_api_resource.hpp" namespace reshade { namespace api { /// <summary> /// A list of flags that represent the available shader stages in the render pipeline. /// </summary> enum class shader_stage : uint32_t { vertex = 0x1, hull = 0x2, domain = 0x4, geometry = 0x8, pixel = 0x10, compute = 0x20, all = 0x7FFFFFFF, all_compute = compute, all_graphics = vertex | hull | domain | geometry | pixel, }; RESHADE_DEFINE_ENUM_FLAG_OPERATORS(shader_stage); /// <summary> /// The available shader source formats. /// <para>Support for these varies between render APIs (e.g. D3D accepts DXBC, but no GLSL, the reverse of which is true for OpenGL).</para> /// </summary> enum class shader_format : uint32_t { /// <summary> /// DirectX Bytecode /// </summary> dxbc, /// <summary> /// DirectX Intermediate Language /// </summary> /// <remarks>https://github.com/Microsoft/DirectXShaderCompiler/blob/master/docs/DXIL.rst</remarks> dxil, /// <summary> /// SPIR-V /// </summary> /// <remarks>https://www.khronos.org/spir/</remarks> spirv, /// <summary> /// High-level shader language /// </summary> /// <remarks>https://docs.microsoft.com/windows/win32/direct3dhlsl</remarks> hlsl, /// <summary> /// OpenGL Shading Language /// </summary> /// <remarks>https://www.khronos.org/opengl/wiki/OpenGL_Shading_Language</remarks> glsl }; /// <summary> /// A list of all possible render pipeline states that can be set dynamically independent of pipeline state objects. /// <para>Support for these varies between render APIs (e.g. modern APIs like D3D12 and Vulkan support much less dynamic states than D3D9).</para> /// </summary> enum class dynamic_state : uint32_t { unknown = 0, alpha_test_enable = 15, alpha_reference_value = 24, alpha_func = 25, srgb_write_enable = 194, primitive_topology = 1000, sample_mask = 162, // Blend state alpha_to_coverage_enable = 1003, blend_enable = 27, logic_op_enable = 1004, color_blend_op = 171, src_color_blend_factor = 19, dst_color_blend_factor = 20, alpha_blend_op = 209, src_alpha_blend_factor = 207, dst_alpha_blend_factor = 208, logic_op = 1005, blend_constant = 193, render_target_write_mask = 168, // Rasterizer state fill_mode = 8, cull_mode = 22, front_counter_clockwise = 1001, depth_bias = 195, depth_bias_clamp = 1002, depth_bias_slope_scaled = 175, depth_clip_enable = 136, scissor_enable = 174, multisample_enable = 161, antialiased_line_enable = 176, // Depth-stencil state depth_enable = 7, depth_write_mask = 14, depth_func = 23, stencil_enable = 52, stencil_read_mask = 58, stencil_write_mask = 59, stencil_reference_value = 57, front_stencil_func = 56, front_stencil_pass_op = 55, front_stencil_fail_op = 53, front_stencil_depth_fail_op = 54, back_stencil_func = 189, back_stencil_pass_op = 188, back_stencil_fail_op = 186, back_stencil_depth_fail_op = 187, }; /// <summary> /// A list of flags that represent the available pipeline stages in the render pipeline. /// </summary> enum class pipeline_stage : uint32_t { /// <summary>The vertex shader stage.</summary> /// <seealso cref="shader_stage::vertex"/> /// <seealso cref="pipeline_desc::graphics::vertex_shader"/> vertex_shader = 0x00000008, /// <summary>The hull shader stage.</summary> /// <seealso cref="shader_stage::hull"/> /// <seealso cref="pipeline_desc::graphics::hull_shader"/> hull_shader = 0x00000010, /// <summary>The domain shader stage.</summary> /// <seealso cref="shader_stage::domain"/> /// <seealso cref="pipeline_desc::graphics::domain_shader"/> domain_shader = 0x00000020, /// <summary>The geometry shader stage.</summary> /// <seealso cref="shader_stage::geometry"/> /// <seealso cref="pipeline_desc::graphics::geometry_shader"/> geometry_shader = 0x00000040, /// <summary>The pixel shader stage.</summary> /// <seealso cref="shader_stage::pixel"/> /// <seealso cref="pipeline_desc::graphics::pixel_shader"/> pixel_shader = 0x00000080, /// <summary>The compute shader stage.</summary> /// <seealso cref="shader_stage::compute"/> /// <seealso cref="pipeline_desc::compute::shader"/> compute_shader = 0x00000800, /// <summary> /// The pipeline stage where vertex and index buffers are consumed. /// </summary> /// <seealso cref="pipeline_desc::graphics::input_layout"/> input_assembler = 0x00000004, /// <summary> /// The pipeline stage where rasterization happens and early depth and stencil tests are performed. /// </summary> /// <seealso cref="pipeline_desc::graphics::rasterizer_state"/> rasterizer = 0x00000100, /// <summary> /// The pipeline stage where late depth and stencil tests are performed. /// </summary> /// <seealso cref="pipeline_desc::graphics::depth_stencil_state"/> depth_stencil = 0x00000200, /// <summary> /// The pipeline stage where the final color values are output from the pipeline and written to the render targets. /// </summary> /// <seealso cref="pipeline_desc::graphics::blend_state"/> output_merger = 0x00000400, /// <summary> /// All operations performed by all supported commands (compute, graphics, ...). /// </summary> all = 0x00010000, /// <summary> /// Combination of all pipeline stages for compute. /// </summary> all_compute = 0x00000800, /// <summary> /// Combination of all pipeline stages for graphics. /// </summary> all_graphics = 0x00008000, /// <summary> /// Combination of all supported shader stages by all supported commands (compute, graphics, ...). /// </summary> all_shader_stages = vertex_shader | hull_shader | domain_shader | geometry_shader | pixel_shader | compute_shader, }; RESHADE_DEFINE_ENUM_FLAG_OPERATORS(pipeline_stage); /// <summary> /// The fill mode to use when rendering triangles. /// </summary> enum class fill_mode : uint32_t { solid = 0, wireframe = 1, point = 2 }; /// <summary> /// Indicates triangles facing a particular direction are not drawn. /// This is compatible with 'VkCullModeFlags'. /// </summary> enum class cull_mode : uint32_t { none = 0, front = 1, back = 2, front_and_back = front | back }; RESHADE_DEFINE_ENUM_FLAG_OPERATORS(cull_mode); /// <summary> /// The available logic operations. /// This is compatible with 'VkLogicOp'. /// </summary> enum class logic_op : uint32_t { clear = 0, bitwise_and = 1, bitwise_and_reverse = 2, bitwise_and_inverted = 4, copy = 3, copy_inverted = 12, noop = 5, bitwise_or = 7, bitwise_or_reverse = 11, bitwise_or_inverted = 13, bitwise_xor = 6, bitwise_nor = 8, equivalent = 9, invert = 10, bitwise_nand = 14, set = 15 }; /// <summary> /// The available color or alpha blending operations. /// This is compatible with 'VkBlendOp'. /// </summary> enum class blend_op : uint32_t { add = 0, subtract = 1, rev_subtract = 2, min = 3, max = 4 }; /// <summary> /// The available blend factors used in blending operations. /// This is compatible with 'VkBlendFactor'. /// </summary> enum class blend_factor : uint32_t { zero = 0, one = 1, src_color = 2, inv_src_color = 3, dst_color = 4, inv_dst_color = 5, src_alpha = 6, inv_src_alpha = 7, dst_alpha = 8, inv_dst_alpha = 9, constant_color = 10, inv_constant_color = 11, constant_alpha = 12, inv_constant_alpha = 13, src_alpha_sat = 14, src1_color = 15, inv_src1_color = 16, src1_alpha = 17, inv_src1_alpha = 18 }; /// <summary> /// The available stencil operations that can be performed during depth-stencil testing. /// This is compatible with 'VkStencilOp'. /// </summary> enum class stencil_op : uint32_t { keep = 0, zero = 1, replace = 2, incr_sat = 3, decr_sat = 4, invert = 5, incr = 6, decr = 7 }; /// <summary> /// Specifies how the pipeline interprets vertex data that is bound to the vertex input stage and subsequently renders it. /// This is compatible with 'D3D_PRIMITIVE_TOPOLOGY'. /// </summary> enum class primitive_topology : uint32_t { undefined = 0, point_list = 1, line_list = 2, line_strip = 3, triangle_list = 4, triangle_strip = 5, triangle_fan = 6, line_list_adj = 10, line_strip_adj = 11, triangle_list_adj = 12, triangle_strip_adj = 13, patch_list_01_cp = 33, patch_list_02_cp, patch_list_03_cp, patch_list_04_cp, patch_list_05_cp, patch_list_06_cp, patch_list_07_cp, patch_list_08_cp, patch_list_09_cp, patch_list_10_cp, patch_list_11_cp, patch_list_12_cp, patch_list_13_cp, patch_list_14_cp, patch_list_15_cp, patch_list_16_cp, patch_list_17_cp, patch_list_18_cp, patch_list_19_cp, patch_list_20_cp, patch_list_21_cp, patch_list_22_cp, patch_list_23_cp, patch_list_24_cp, patch_list_25_cp, patch_list_26_cp, patch_list_27_cp, patch_list_28_cp, patch_list_29_cp, patch_list_30_cp, patch_list_31_cp, patch_list_32_cp }; /// <summary> /// The available query types. /// </summary> enum class query_type { occlusion = 0, binary_occlusion = 1, timestamp = 2, pipeline_statistics = 3 }; /// <summary> /// The render pass attachment types that can be cleared by <see cref="command_list_impl::clear_attachments"/>. /// This is compatible with 'VkImageAspectFlags'. /// </summary> enum class attachment_type { color = 0x1, depth = 0x2, stencil = 0x4 }; RESHADE_DEFINE_ENUM_FLAG_OPERATORS(attachment_type); /// <summary> /// The available descriptor types. /// This is mostly compatible with 'VkDescriptorType'. /// </summary> enum class descriptor_type { sampler = 0, sampler_with_resource_view = 1, shader_resource_view = 2, unordered_access_view = 3, constant_buffer = 6, shader_storage_buffer = 7 }; /// <summary> /// The available pipeline layout parameter types. /// </summary> enum class pipeline_layout_param_type { descriptor_set = 0, push_constants = 1, push_descriptors = 2, }; /// <summary> /// The available indirect command types. /// </summary> enum class indirect_command { unknown, draw, draw_indexed, dispatch }; /// <summary> /// An opaque handle to a pipeline state object. /// <para>In D3D9, D3D10, D3D11 or D3D12 this is a pointer to a 'IDirect3D(...)Shader', 'ID3D10(...)(Shader/State)', 'ID3D11(...)(Shader/State)' or 'ID3D12PipelineState' object, in Vulkan a 'VkPipeline' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(pipeline); /// <summary> /// An opaque handle to a pipeline layout object. /// <para>In D3D12 this is a pointer to a 'ID3D12RootSignature' object, in Vulkan a 'VkPipelineLayout' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(pipeline_layout); /// <summary> /// An opaque handle to a descriptor set layout. /// <para>In Vulkan this is a 'VkDescriptorSetLayout' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(descriptor_set_layout); /// <summary> /// An opaque handle to a query pool. /// <para>In D3D12 this is a pointer to a 'ID3D12QueryHeap' object, in Vulkan a 'VkQueryPool' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(query_pool); /// <summary> /// An opaque handle to a render pass. /// <para>In Vulkan this is a 'VkRenderPass' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(render_pass); /// <summary> /// An opaque handle to a framebuffer object. /// <para>In OpenGL this is a FBO handle, in Vulkan a 'VkFramebuffer' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(framebuffer); /// <summary> /// An opaque handle to a descriptor set. /// <para>In D3D12 this is a 'D3D12_GPU_DESCRIPTOR_HANDLE' to a descriptor table, in Vulkan a 'VkDescriptorSet' handle.</para> /// </summary> RESHADE_DEFINE_HANDLE(descriptor_set); /// <summary> /// Describes the color blend state of the output stage. /// </summary> struct blend_desc { /// <summary>Specifies whether to use alpha-to-coverage as a multisampling technique when setting a pixel to a render target.</summary> bool alpha_to_coverage_enable; /// <summary>Specifies whether to enable (or disable) blending for each render target.</summary> bool blend_enable[8]; /// <summary>Specifies whether to enable (or disable) a logical operation for each render target.</summary> bool logic_op_enable[8]; /// <summary>Defines how to combine the <see cref="src_color_blend_factor"/> and <see cref="dst_color_blend_factor"/> operations.</summary> blend_op color_blend_op[8]; /// <summary>Specifies the operation to perform on the RGB value that the pixel shader outputs.</summary> blend_factor src_color_blend_factor[8]; /// <summary>Specifies the operation to perform on the current RGB value in the render target.</summary> blend_factor dst_color_blend_factor[8]; /// <summary>Defines how to combine the <see cref="src_alpha_blend_factor"/> and <see cref="dst_alpha_blend_factor"/> operations.</summary> blend_op alpha_blend_op[8]; /// <summary>Specifies the operation to perform on the alpha value that the pixel shader outputs.</summary> blend_factor src_alpha_blend_factor[8]; /// <summary>Specifies the operation to perform on the current alpha value in the render target.</summary> blend_factor dst_alpha_blend_factor[8]; /// <summary>Specifies the logical operation to configure for each render target. Ignored if <see cref="logic_op_enable"/> is <c>false</c>.</summary> logic_op logic_op[8]; /// <summary>The constant RGBA value used when <see cref="src_color_blend_factor"/> or <see cref="dst_color_blend_factor"/> is <see cref="blend_factor::constant_color"/>.</summary> uint32_t blend_constant; /// <summary>A write mask specifying which color components are written to each render target. Combination of <c>0x1</c> for red, <c>0x2</c> for green, <c>0x4</c> for blue and <c>0x8</c> for alpha.</summary> uint8_t render_target_write_mask[8]; }; /// <summary> /// Describes the state of the rasterizer stage. /// </summary> struct rasterizer_desc { /// <summary>Specifies the fill mode to use when rendering.</summary> fill_mode fill_mode; /// <summary>Specifies that triangles facing the specified direction are not drawn.</summary> cull_mode cull_mode; /// <summary>Determines if a triangle is front or back-facing.</summary> bool front_counter_clockwise; /// <summary>Depth value added to a given pixel.</summary> float depth_bias; /// <summary>Maximum depth bias of a pixel.</summary> float depth_bias_clamp; /// <summary>Scalar on the slope of a given pixel.</summary> float slope_scaled_depth_bias; /// <summary>Specifies whether to enable clipping based on distance.</summary> bool depth_clip_enable; /// <summary>Specifies whether to enable scissor rectangle culling.</summary> bool scissor_enable; /// <summary>Specifies whether to use the quadrilateral or alpha line anti-aliasing algorithm on multisample_enable antialiasing render targets.</summary> bool multisample_enable; /// <summary>Specifies whether to enable line antialiasing. Only applies if doing line drawing and <see cref="multisample_enable"/> is <c>false</c>.</summary> bool antialiased_line_enable; }; /// <summary> /// Describes the depth-stencil state of the output stage. /// </summary> struct depth_stencil_desc { /// <summary>Specifies whether to enable depth testing.</summary> bool depth_enable; /// <summary>Specifies whether writes to the depth-stencil buffer are enabled.</summary> bool depth_write_mask; /// <summary>Specifies the function that compares depth data against existing depth data.</summary> compare_op depth_func; /// <summary>Specifies whether to enable stencil testing.</summary> bool stencil_enable; /// <summary>A mask applied when reading stencil data from the depth-stencil buffer.</summary> uint8_t stencil_read_mask; /// <summary>A mask applied when writing stencil data to the depth-stencil buffer.</summary> uint8_t stencil_write_mask; /// <summary>Reference value to perform against when doing stencil testing.</summary> uint8_t stencil_reference_value; /// <summary>Specifies the function that compares stencil data against existing stencil data for pixels whose surface normal is facing towards the camera.</summary> compare_op front_stencil_func; /// <summary>Specifies the stencil operation to perform when stencil testing and depth testing both pass for pixels whose surface normal is facing towards the camera.</summary> stencil_op front_stencil_pass_op; /// <summary>Specifies the stencil operation to perform when stencil testing fails for pixels whose surface normal is towards the camera.</summary> stencil_op front_stencil_fail_op; /// <summary>Specifies the stencil operation to perform when stencil testing passes and depth testing fails for pixels whose surface normal is facing towards the camera.</summary> stencil_op front_stencil_depth_fail_op; /// <summary>Specifies the function that compares stencil data against existing stencil data for pixels whose surface normal is facing away from the camera.</summary> compare_op back_stencil_func; /// <summary>Specifies the stencil operation to perform when stencil testing and depth testing both pass for pixels whose surface normal is facing away from the camera.</summary> stencil_op back_stencil_pass_op; /// <summary>Specifies the stencil operation to perform when stencil testing fails for pixels whose surface normal is facing away from the camera.</summary> stencil_op back_stencil_fail_op; /// <summary>Specifies the stencil operation to perform when stencil testing passes and depth testing fails for pixels whose surface normal is facing away from the camera.</summary> stencil_op back_stencil_depth_fail_op; }; /// <summary> /// Describes a single element in the the layout of the vertex buffer data for the vertex input stage. /// </summary> struct input_layout_element { /// <summary>The GLSL attribute location associated with this element (<c>layout(location = X)</c>).</summary> uint32_t location; /// <summary>The HLSL semantic associated with this element.</summary> const char *semantic; /// <summary>Optional index for the HLSL semantic (for "TEXCOORD1" set <see cref="semantic"/> to "TEXCOORD" and <see cref="semantic_index"/> to 1).</summary> uint32_t semantic_index; /// <summary>The format of the element data.</summary> format format; /// <summary> The input slot (index of the vertex buffer binding).</summary> uint32_t buffer_binding; /// <summary>Offset (in bytes) from the start of the vertex to this element.</summary> uint32_t offset; /// <summary>Stride of the entire vertex (this has to be consistent for all elements per vertex buffer binding). /// Set to zero in case this is unknown.</summary> uint32_t stride; /// <summary>The number of instances to draw using the same per-instance data before advancing by one element (this has to be consistent for all elements per vertex buffer binding). /// Set to zero to indicate that this element is per-vertex rather than per-instance.</summary> uint32_t instance_step_rate; }; /// <summary> /// Describes a shader module. /// </summary> struct shader_desc { /// <summary>The shader source code.</summary> const void *code; /// <summary>The size (in bytes) of the shader source code.</summary> size_t code_size; /// <summary>The format of the shader source <see cref="code"/>.</summary> shader_format format; /// <summary>Optional entry point name if the shader source code contains multiple entry points. Can be <c>nullptr</c> if it does not.</summary> const char *entry_point; /// <summary>The number of entries in the <see cref="spec_constant_ids"/> and <see cref="spec_constant_values"/> arrays. /// This is meaningful only when <see cref="format"/> is <see cref="shader_format::spirv"/> and is ignored otherwise.</summary> uint32_t num_spec_constants; /// <summary>Pointer to an array of specialization constant indices.</summary> const uint32_t *spec_constant_ids; /// <summary>Pointer to an array of constant values, one for each specialization constant index in <see cref="spec_constant_ids"/>.</summary> const uint32_t *spec_constant_values; }; /// <summary> /// Describes a pipeline state object. /// </summary> struct pipeline_desc { /// <summary>The type of the pipeline state object.</summary> pipeline_stage type; /// <summary>The descriptor and constant layout of the pipeline.</summary> pipeline_layout layout; union { /// <summary> /// Used when pipeline type is <see cref="pipeline_stage::all_compute"/> or a subset of it. /// </summary> struct { /// <summary>The compute shader module to use.</summary> /// <seealso cref="shader_stage::compute"/> /// <seealso cref="pipeline_stage::compute_shader"/> shader_desc shader; } compute; /// <summary> /// Used when pipeline type is <see cref="pipeline_stage::all_graphics"/> or a subset of it. /// </summary> struct { /// <summary>The vertex shader module to use.</summary> /// <seealso cref="shader_stage::vertex"/> /// <seealso cref="pipeline_stage::vertex_shader"/> shader_desc vertex_shader; /// <summary>The optional hull shader module to use.</summary> /// <seealso cref="shader_stage::hull"/> /// <seealso cref="pipeline_stage::hull_shader"/> shader_desc hull_shader; /// <summary>The optional domain shader module to use.</summary> /// <seealso cref="shader_stage::domain"/> /// <seealso cref="pipeline_stage::domain_shader"/> shader_desc domain_shader; /// <summary>The optional geometry shader module to use.</summary> /// <seealso cref="shader_stage::geometry"/> /// <seealso cref="pipeline_stage::geometry_shader"/> shader_desc geometry_shader; /// <summary>The pixel shader module to use.</summary> /// <seealso cref="shader_stage::pixel"/> /// <seealso cref="pipeline_stage::pixel_shader"/> shader_desc pixel_shader; /// <summary>Describes the layout of the vertex buffer data for the vertex input stage. /// Elements following one with the format set to <see cref="format::unknown"/> will be ignored (which is used to terminate this list).</summary> /// <seealso cref="pipeline_stage::input_assembler"/> input_layout_element input_layout[16]; /// <summary>Describes the blend state of the output stage.</summary> /// <seealso cref="pipeline_stage::output_merger"/> blend_desc blend_state; /// <summary>Describes the state of the rasterizer stage.</summary> /// <seealso cref="pipeline_stage::rasterizer"/> rasterizer_desc rasterizer_state; /// <summary>Describes thel state of the depth-stencil stage.</summary> /// <seealso cref="pipeline_stage::depth_stencil"/> depth_stencil_desc depth_stencil_state; /// <summary>The sample mask for the blend state.</summary> uint32_t sample_mask; /// <summary>The number of samples per pixel.</summary> uint32_t sample_count; /// <summary>The primitive topology to use when rendering.</summary> primitive_topology topology; /// <summary>The maximum number of viewports that may be bound via <see cref="command_list::bind_viewports"/> with this pipeline.</summary> uint32_t viewport_count; /// <summary>A render pass that describes the format of the render target and depth-stencil views that may be used with this pipeline.</summary> render_pass render_pass_template; /// <summary>A list of all pipeline states that may be dynamically updated via <see cref="command_list::bind_pipeline_states"/>. /// Elements following one set to <see cref="dynamic_state::unknown"/> will be ignored (which is used to terminate this list).</summary> dynamic_state dynamic_states[32]; } graphics; }; }; /// <summary> /// Describes the data structure returned by <see cref="query_type::pipeline_statistics"/> queries. /// </summary> struct pipeline_statistics { uint64_t input_assembler_vertices; uint64_t input_assembler_primitives; uint64_t vertex_shader_invocations; uint64_t geometry_shader_invocations; uint64_t geometry_shader_primitives; uint64_t clipping_invocations; uint64_t clipping_primitives; uint64_t pixel_shader_invocations; uint64_t hull_shader_invocations; uint64_t domain_shader_invocations; uint64_t compute_shader_invocations; }; /// <summary> /// Specifies a range of constants in a pipeline layout. /// </summary> struct constant_range { /// <summary>The push constant offset (in 32-bit values, only used by Vulkan).</summary> uint32_t offset; /// <summary>The D3D10/D3D11/D3D12 constant buffer register index.</summary> uint32_t dx_register_index; /// <summary>The D3D12 constant buffer register space.</summary> uint32_t dx_register_space; /// <summary>The number of constants in this range (in 32-bit values).</summary> uint32_t count; /// <summary>The shader pipeline stages that can make use of the constants in this range.</summary> shader_stage visibility; }; /// <summary> /// Specifies a range of descriptors in a descriptor set layout. /// </summary> struct descriptor_range { /// <summary>The offset of this range in the descriptor set (in descriptors).</summary> uint32_t offset; /// <summary>The OpenGL/Vulkan binding index (<c>layout(binding=X)</c> in GLSL).</summary> uint32_t binding; /// <summary>The D3D9/D3D10/D3D11/D3D12 shader register index (<c>register(xX)</c> in HLSL).</summary> uint32_t dx_register_index; /// <summary>The D3D12 register space (<c>register(..., spaceX)</c> in HLSL).</summary> uint32_t dx_register_space; /// <summary>The type of the descriptors in this range.</summary> descriptor_type type; /// <summary>The number of descriptors in the range (size of the array in GLSL).</summary> uint32_t array_size; /// <summary>The shader pipeline stages that can make use of the descriptors in this range.</summary> shader_stage visibility; }; /// <summary> /// Describes a single parameter in a pipeline layout. /// </summary> struct pipeline_layout_param { pipeline_layout_param_type type; union { descriptor_set_layout descriptor_layout; constant_range push_constants; }; }; /// <summary> /// Describes a render pass. /// </summary> struct render_pass_desc { format depth_stencil_format; format render_targets_format[8]; uint16_t samples; }; /// <summary> /// Describes a framebuffer object. /// </summary> struct framebuffer_desc { render_pass render_pass_template; resource_view depth_stencil; resource_view render_targets[8]; }; /// <summary> /// All information needed to copy descriptors between descriptor sets. /// </summary> struct copy_descriptor_set { /// <summary>The descriptor set to copy from.</summary> descriptor_set src_set; /// <summary>The offset in the source set to start copying from.</summary> /// <seealso cref="descriptor_range::offset"/> uint32_t src_offset; /// <summary>The descriptor set to copy to.</summary> descriptor_set dst_set; /// <summary>The offset in the destination set to start copying to.</summary> /// <seealso cref="descriptor_range::offset"/> uint32_t dst_offset; /// <summary>The number of descriptors to copy, starting at the specified source offset to the destination offset.</summary> uint32_t count; }; /// <summary> /// All information needed to update descriptors in a single descriptor set. /// </summary> struct write_descriptor_set { /// <summary>The descriptor set to update.</summary> descriptor_set set; /// <summary>The offset in the <see cref="set"/> to start updating at.</summary> /// <seealso cref="descriptor_range::offset"/> uint32_t offset; /// <summary>The number of descriptors to update, starting at the specified <see cref="offset"/>.</summary> uint32_t count; /// <summary>The type of the specified <see cref="descriptors"/>.</summary> descriptor_type type; /// <summary>A pointer to an array of descriptors to update in the set. /// Depending on the descriptor <see cref="type"/> this should be pointer to an array of <see cref="buffer_range"/>, <see cref="resource_view"/>, <see cref="sampler"/> or <see cref="sampler_with_resource_view"/>.</summary> const void *descriptors; }; /// <summary> /// A constant buffer resource descriptor. /// </summary> struct buffer_range { resource buffer; uint64_t offset; uint64_t size; }; /// <summary> /// A combined sampler and resource view descriptor. /// </summary> struct sampler_with_resource_view { sampler sampler; resource_view view; }; } }
#include <stdio.h> #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <unordered_set> #include <array> #include <stack> #include <map> #include <set> #include <algorithm> #include <cmath> #include <chrono> #include <ranges> bool explode_number(std::string& nr) { // look for pair nested inside four other pairs -> stack depth 4 int depth = 0; int nested_pair_start = -1; int nested_pair_end = -1; int idx = 0; for (auto c : nr) { switch(c) { case '[': if (depth == 4) { nested_pair_start = idx; } depth++; break; case ']': depth--; if (depth == 4) { nested_pair_end = idx; } break; } if (nested_pair_end > -1) break; idx++; } if (nested_pair_end > -1) { std::string nested_pair = nr.substr(nested_pair_start, nested_pair_end - nested_pair_start + 1); //printf("nested pair: %s\n", nested_pair.c_str()); std::istringstream np(nested_pair); std::string s; getline(np, s, '['); getline(np, s, ','); int nr1 = std::atoi(s.c_str()); getline(np, s, ']'); int nr2 = std::atoi(s.c_str()); // find right number (if any) int right_nr_idx = nested_pair_end + 1; while (!isdigit(nr[right_nr_idx])) { right_nr_idx++; if (right_nr_idx == nr.length()) break; } if (right_nr_idx < nr.length()) { int right_bracket_idx = right_nr_idx; while (isdigit(nr[right_bracket_idx])) { right_bracket_idx++; } int nr3 = std::atoi(nr.substr(right_nr_idx, right_bracket_idx - right_nr_idx).c_str()); // replace with sum nr2 + nr3 nr.replace(right_nr_idx, right_bracket_idx - right_nr_idx, std::to_string(nr2 + nr3)); } // replace nested pair with 0 nr.replace(nested_pair_start, nested_pair_end - nested_pair_start + 1, "0"); // find left comma (if any) int left_nr_idx = nested_pair_start - 1; while (!isdigit(nr[left_nr_idx])) { left_nr_idx--; if (left_nr_idx < 0) break; } if (left_nr_idx > 0) { int left_bracket_idx = left_nr_idx; while (isdigit(nr[left_bracket_idx])) { left_bracket_idx--; } int nr0 = std::atoi(nr.substr(left_bracket_idx + 1, left_nr_idx - left_bracket_idx).c_str()); // replace with sum nr0 + nr1 nr.replace(left_bracket_idx + 1, left_nr_idx - left_bracket_idx, std::to_string(nr0 + nr1)); } return true; } return false; } void explode_number_test(std::string nr) { printf("Exploding %s\n", nr.c_str()); if (explode_number(nr)) { printf("Result: %s\n", nr.c_str()); } else { printf("Didn't explode\n"); } printf("\n"); } bool split_number(std::string& nr) { // check for split action int current_number = 0; int idx = 0; int number_start = 0; int number_end = 0; bool in_number = false; bool split_action = false; for (auto c : nr) { switch(c) { case '[': case ']': case ',': if (current_number >= 10) { split_action = true; } current_number = 0; in_number = false; break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (!in_number) { number_start = idx; } else { number_end = idx; } in_number = true; current_number = current_number * 10 + (c - '0'); break; } if (split_action) break; idx++; } if (split_action) { int nr_to_split = std::atoi(nr.substr(number_start, number_end - number_start + 1).c_str()); int nr1 = nr_to_split / 2; int nr2 = (nr_to_split + 1) / 2; auto new_string = std::string("["); new_string += std::to_string(nr1); new_string += std::string(","); new_string += std::to_string(nr2); new_string += std::string("]"); nr.replace(number_start, number_end - number_start + 1, new_string); printf("split action: %i => %s\n", nr_to_split, new_string.c_str()); } return split_action; } std::string reduce_number(std::string nr) { printf("Reducing %s\n", nr.c_str()); for (;;) { bool explode_action = explode_number(nr); if (explode_action) { printf("after explode: %s\n", nr.c_str()); continue; } bool split_action = split_number(nr); if (split_action) { printf("after split: %s\n", nr.c_str()); } if (!split_action) break; } return nr; } std::string add_numbers(std::string nr1, std::string nr2) { return std::string("[") + nr1 + std::string(",") + nr2 + std::string("]"); } int magnitude(std::string nr, int& idx) { // first character is expected to be '[' int left_magnitude = 0; int right_magnitude = 0; // check second character idx++; int start_idx = idx; if (nr[idx] == '[') { // recursion left_magnitude = magnitude(nr, idx) * 3; idx++; } else { while (isdigit(nr[idx])) { idx++; } left_magnitude = std::atoi(nr.substr(start_idx, idx - start_idx).c_str()) * 3; } idx++; start_idx = idx; if (nr[idx] == '[') { // recursion right_magnitude = magnitude(nr, idx) * 2; idx++; } else { while (isdigit(nr[idx])) { idx++; } right_magnitude = std::atoi(nr.substr(start_idx, idx - start_idx).c_str()) * 2; } return left_magnitude + right_magnitude; } void magnitude_test(std::string nr) { int idx = 0; printf("Magnitude of %s: %i\n", nr.c_str(), magnitude(nr, idx)); } int main() { //std::ifstream input("example1.txt"); //std::ifstream input("example2.txt"); std::ifstream input("input.txt"); if (!input.is_open()) { printf("Error opening file\n"); return -1; } // explode tests /* explode_number_test(std::string("[1,2]")); // expected: "didn't explode" explode_number_test(std::string("[[[[[9,8],1],2],3],4]")); // expected: [[[[0,9],2],3],4] explode_number_test(std::string("[7,[6,[5,[4,[3,2]]]]]")); // expected: [7,[6,[5,[7,0]]]] explode_number_test(std::string("[[6,[5,[4,[3,2]]]],1]")); // expected: [[6,[5,[7,0]]],3] explode_number_test(std::string("[[3,[2,[1,[7,3]]]],[6,[5,[4,[3,2]]]]]")); // expected: [[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]] explode_number_test(std::string("[[3,[2,[8,0]]],[9,[5,[4,[3,2]]]]]")); // expected: [[3,[2,[8,0]]],[9,[5,[7,0]]]] */ // add and reduce test //reduce_number(add_numbers("[[[[4,3],4],4],[7,[[8,4],9]]]", "[1,1]")); // expected: /*after addition: [[[[[4,3],4],4],[7,[[8,4],9]]],[1,1]] after explode: [[[[0,7],4],[7,[[8,4],9]]],[1,1]] after explode: [[[[0,7],4],[15,[0,13]]],[1,1]] after split: [[[[0,7],4],[[7,8],[0,13]]],[1,1]] after split: [[[[0,7],4],[[7,8],[0,[6,7]]]],[1,1]] after explode: [[[[0,7],4],[[7,8],[6,0]]],[8,1]]*/ // magnitude tests /* magnitude_test(std::string("[9,1]")); // expected: 29 magnitude_test(std::string("[[9,1],[1,9]]")); // expected: 129 magnitude_test(std::string("[[1,2],[[3,4],5]]")); // expected: 143 magnitude_test(std::string("[[[[0,7],4],[[7,8],[6,0]]],[8,1]]")); // expected: 1384 magnitude_test(std::string("[[[[1,1],[2,2]],[3,3]],[4,4]]")); // expected: 445 magnitude_test(std::string("[[[[3,0],[5,3]],[4,4]],[5,5]]")); // expected: 791 magnitude_test(std::string("[[[[5,0],[7,4]],[5,5]],[6,6]]")); // expected: 1137 magnitude_test(std::string("[[[[8,7],[7,7]],[[8,6],[7,7]]],[[[0,7],[6,6]],[8,7]]]")); // expected: 3488 */ std::vector<std::string> numbers; std::string line; while (getline(input, line)) { numbers.push_back(line); } int largest_magnitude = 0; for (int nr0 = 0; nr0 < numbers.size(); nr0++) { for (int nr1 = 0; nr1 < numbers.size(); nr1++) { if (nr0 == nr1) continue; int idx = 0; int mg = magnitude(reduce_number(add_numbers(numbers[nr0], numbers[nr1])), idx); largest_magnitude = std::max(largest_magnitude, mg); } } printf("largest magnitude: %i\n", largest_magnitude); return 0; }
/* Copyright 2021 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 <memory> #include <string> #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "mlir/IR/Builders.h" // from @llvm-project #include "mlir/IR/MLIRContext.h" // from @llvm-project #include "mlir/IR/OpDefinition.h" // from @llvm-project #include "mlir/IR/Operation.h" // from @llvm-project #include "mlir/Pass/Pass.h" // from @llvm-project #include "mlir/Pass/PassRegistry.h" // from @llvm-project #include "mlir/Support/LLVM.h" // from @llvm-project #include "tensorflow/compiler/mlir/lite/experimental/tac/common/cost.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/common/subgraph.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/common/targets.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/common/utils.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/transforms/cost_model.h" #include "tensorflow/compiler/mlir/lite/experimental/tac/transforms/passes.h" #include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" namespace mlir { namespace TFL { namespace tac { namespace { // We will caculate the total compute cost for each Func Op. // // The compute cost is simply an add-up of the costs of all the operations // within the FuncOp. (Excluding const ops since they're just "data".) // We will ignore quant/dequant/requant costs within the Func Op as well, // intuition: // // The assumpution is that quant/dequant/requant will only happen at the begin // and the end of the FuncOp (basically the "boundaries" of the subgraph). // So we can imagine if multiple "same-inference-typed" graph are presented at // the same time, the quant/dequant ops pair can be squashed: // // dequant ------------ // | // ops... FuncOp1 // | // quant ------------- // | <--- can be squashed // dequant ------------- // | // ops... FuncOp2 // | // quant --------------- // // But it's true quant & dequant ops can happen "within" the FuncOp as well, // normally as "quantization params" adjust. We should check more careful to // include those as those ops wouldn't be "squashed". class ComputeCostPass : public mlir::PassWrapper<ComputeCostPass, mlir::OperationPass<ModuleOp>> { private: llvm::StringRef getArgument() const final { return "tfl-compute-cost"; } llvm::StringRef getDescription() const final { return "Compute the total cost for each available subgraph."; } void runOnOperation() override; }; void ComputeCostPass::runOnOperation() { auto module = getOperation(); for (auto func : module.getOps<FuncOp>()) { // We only care about those functions annotated with "tac.interface_name". auto interface_name = GetInterFaceName(func); if (!interface_name.hasValue()) continue; auto target = GetTargetAnnotation(func); if (!target.hasValue()) { func.emitError("we cannot get hardware info for this function."); signalPassFailure(); } float total_cost = GetCostForFunc(&func, target.getValue()); OpBuilder builder(func); UpdateCost(func, total_cost, &builder); } } } // namespace std::unique_ptr<OperationPass<ModuleOp>> CreateComputeCostPass() { return std::make_unique<ComputeCostPass>(); } static PassRegistration<ComputeCostPass> pass; } // namespace tac } // namespace TFL } // namespace mlir
// // StaticModule.hpp // MNN // // Created by MNN on b'2020/09/10'. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef StaticModule_hpp #define StaticModule_hpp #include <set> #include <MNN/expr/Module.hpp> namespace MNN { class Session; class Backend; namespace Express { struct NetStorage; class StaticModule : public Module { public: StaticModule(const void* buffer, size_t length, const std::vector<std::string>& inputs, const std::vector<std::string>& outputs, const Module::Config& config); virtual ~ StaticModule(); virtual std::vector<Express::VARP> onForward(const std::vector<Express::VARP>& inputs) override; void setReusedTensors(std::set<int> reused); private: StaticModule() = default; Module* clone(CloneContext* ctx) const override; std::vector<std::string> mInputs; std::vector<std::string> mOutputs; std::shared_ptr<Session> mSession; std::vector<Tensor*> mInputTensors; std::vector<Tensor*> mOutputTensors; bool mShapeFix; int mOutputNumbers; // First: outputIndex, Second: outputTensor Index std::vector<int> mOutputFromTensor; // First: outputIndex, Second: input var index std::vector<std::pair<int, int>> mOutputFromInput; void resizeTensor(Tensor* tensor, const std::vector<int>& dims); // the outputs will be used as inputs std::set<int> mReusedTensors; std::shared_ptr<Backend> mResourceBackend; std::shared_ptr<NetStorage> mNetStorage; }; } } #endif
// Copyright (c) 2017-2021 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/json/ #ifndef TAO_JSON_JAXN_FROM_STRING_HPP #define TAO_JSON_JAXN_FROM_STRING_HPP #include <cstddef> #include <utility> #include "../events/to_value.hpp" #include "../events/transformer.hpp" #include "events/from_string.hpp" namespace tao::json::jaxn { template< template< typename... > class Traits, template< typename... > class... Transformers, typename... Ts > [[nodiscard]] basic_value< Traits > basic_from_string( Ts&&... ts ) { json::events::transformer< json::events::to_basic_value< Traits >, Transformers... > consumer; events::from_string( consumer, std::forward< Ts >( ts )... ); return std::move( consumer.value ); } template< template< typename... > class... Transformers, typename... Ts > [[nodiscard]] value from_string( Ts&&... ts ) { return basic_from_string< traits, Transformers... >( std::forward< Ts >( ts )... ); } inline namespace literals { [[nodiscard]] inline value operator"" _jaxn( const char* data, const std::size_t size ) { return jaxn::from_string( data, size, "literal" ); } } // namespace literals } // namespace tao::json::jaxn #endif
// // LSTMWeightInt8.cpp // MNNConverter // // Created by MNN on 2020/09/17. // Copyright © 2018, Alibaba Group Holding Limited // #include <flatbuffers/util.h> #include "../../common/Global.hpp" #include "../TemplateMerge.hpp" #include "MNN/expr/ExprCreator.hpp" #include "MNN_generated.h" #include "MergeHelpers.hpp" #include "cli.hpp" namespace MNN { namespace Express { class LSTMWeightInt8 { public: LSTMWeightInt8(); }; LSTMWeightInt8::LSTMWeightInt8() { auto match = [](EXPRP expr) -> bool { auto gConverterConfig = Global<modelConfig>::Get(); if (!gConverterConfig->weightQuantBits) { return false; } if (!expr->get()) { return false; } if (expr->get()->type() != OpType_LSTM) { return false; } if (expr->inputs().size() != 6) { return false; } for (int i = 1; i < 4; i++) { auto input = expr->inputs()[i]; const Op* op = input->expr().first->get(); if (input->expr().first->inputType() != VARP::CONSTANT) { return false; } auto inputInfo = input->getInfo(); if (inputInfo->type != halide_type_of<float>()) { return false; } } return true /*matched*/; }; auto fold = [this](EXPRP expr) -> bool { auto allInputs = expr->inputs(); std::vector<VARP> lstmInputs; lstmInputs.emplace_back(allInputs[0]); for (int i = 1; i < 4; i++) { VARP weightVar = allInputs[i]; auto weightInfo = weightVar->getInfo(); int lastDimSize = weightInfo->dim[weightInfo->dim.size() - 1]; std::vector<int> reduceDims; for (int j = 0; j < weightInfo->dim.size(); j++) { reduceDims.push_back(j); } VARP mins = _ReduceMin(weightVar, reduceDims, true); VARP maxs = _ReduceMax(weightVar, reduceDims, true); VARP scales = (maxs - mins) / _Scalar<float>(127. + 128.); VARP quantWeight = _Cast<int8_t>(_Round((weightVar - mins) / scales) - _Scalar<float>(128.)); VARP minsConst = _Const(mins->readMap<void>(), mins->getInfo()->dim, mins->getInfo()->order, mins->getInfo()->type); VARP scalesConst = _Const(scales->readMap<void>(), scales->getInfo()->dim, scales->getInfo()->order, scales->getInfo()->type); VARP quantWeightConst = _Const(quantWeight->readMap<void>(), quantWeight->getInfo()->dim, quantWeight->getInfo()->order, quantWeight->getInfo()->type); VARP deQuantWeight = (_Cast<float>(quantWeightConst) + _Scalar<float>(128.)) * scalesConst + minsConst; lstmInputs.emplace_back(deQuantWeight); } lstmInputs.emplace_back(allInputs[4]); lstmInputs.emplace_back(allInputs[5]); auto lstm_op = expr->get(); EXPRP lstm_expr = Expr::create(lstm_op->UnPack(), lstmInputs, 3); lstm_expr->setName(expr->name()); VARP lstm_var0 = Variable::create(lstm_expr, 0); lstm_var0->setName(expr->outputName(0)); VARP lstm_var1 = Variable::create(lstm_expr, 1); lstm_var1->setName(expr->outputName(1)); VARP lstm_var2 = Variable::create(lstm_expr, 2); lstm_var2->setName(expr->outputName(2)); Expr::replace(expr, lstm_expr); return true /*modified*/; }; TemplateMerge::getInstance("Merge").insertTemplate("LSTMWeightInt8", match, fold, PASS_PRIORITY_LOW); } static LSTMWeightInt8 g_lstm_weight_int8; } // namespace Express } // namespace MNN
#include<stdio.h> #include<math.h> #include<graphics.h> int main(){ int x1,y1,x2,y2,gd,gm; int ymax,a[4][8]; float par[4][4],b[4][8]; int i,j,k,m,n,p; int xp, yp, zp, x, y, z; a[0][0] = 100; a[1][0] = 100; a[2][0] = -100; a[0][1] = 200; a[1][1] = 100; a[2][1] = -100; a[0][2] = 200; a[1][2] = 200; a[2][2] = -100; a[0][3] = 100; a[1][3] = 200; a[2][3] = -100; a[0][4] = 100; a[1][4] = 100; a[2][4] = -200; a[0][5] = 200; a[1][5] = 100; a[2][5] = -200; a[0][6] = 200; a[1][6] = 200; a[2][6] = -200; a[0][7] = 100; a[1][7] = 200; a[2][7] = -200; detectgraph(&gd,&gm); initgraph(&gd,&gm, NULL); ymax = getmaxy(); xp = 300; yp = 320; zp = 100; for(j=0; j<8; j++) { x = a[0][j]; y = a[1][j]; z = a[2][j]; b[0][j] = xp - ( (float)( x - xp )/(z - zp)) * (zp); b[1][j] = yp - ( (float)( y - yp )/(z - zp)) * (zp); } /*- front plane display -*/ for(j=0;j<3;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1,ymax-y1,x2,ymax-y2); } x1=(int) b[0][3]; y1=(int) b[1][3]; x2=(int) b[0][0]; y2=(int) b[1][0]; line( x1, ymax-y1, x2, ymax-y2); /*- back plane display -*/ setcolor(11); for(j=4;j<7;j++) { x1=(int) b[0][j]; y1=(int) b[1][j]; x2=(int) b[0][j+1]; y2=(int) b[1][j+1]; line( x1, ymax-y1, x2, ymax-y2); } x1=(int) b[0][7]; y1=(int) b[1][7]; x2=(int) b[0][4]; y2=(int) b[1][4]; line( x1, ymax-y1, x2, ymax-y2); setcolor(7); for(i=0;i<4;i++) { x1=(int) b[0][i]; y1=(int) b[1][i]; x2=(int) b[0][4+i]; y2=(int) b[1][4+i]; line( x1, ymax-y1, x2, ymax-y2); } getch(); return 0; }
/**************************************************************************** * * Copyright (c) 2015, Cadence Design Systems. All Rights Reserved. * * This file contains confidential information that may not be * distributed under any circumstances without the written permision * of Cadence Design Systems. * ****************************************************************************/ /**************************************************************************** * * This file is used to wrap the three different versions of the DUT * block called "dut". By default, it will include the behavioral * model. Otherwise, it will include the RTL C++ or the RTL Verilog * depending on the definition of either of "RTL" or "COSIM". * ****************************************************************************/ #include "dut_sc_wrap.h" #include "dut_sc_foreign.h" // The following threads are used to connect structured ports to the actual // RTL ports void dut_wrapper::InitInstances( ) { dut0 = new dut( "dut" ); dut0->clk(clk); dut0->rst(rst); dut0->din_busy(din.busy); dut0->din_vld(din.vld); dut0->din_data(din.data); dut0->dout_busy(dout.busy); dut0->dout_vld(dout.vld); dut0->dout_data(dout.data); } void dut_wrapper::InitThreads() { } void dut_wrapper::DeleteInstances() { if (dut0) { delete dut0; dut0 = 0; } }
/**************************************************************************** * * Copyright 2018 Samsung Electronics 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 <tinyara/config.h> #include <tinyara/init.h> #include <fcntl.h> #include <wifi_manager/wifi_manager.h> #include <media/MediaPlayer.h> #include <media/MediaRecorder.h> #include <media/MediaPlayerObserverInterface.h> #include <media/MediaRecorderObserverInterface.h> #include <media/SocketOutputDataSource.h> #include <iostream> #include <memory> #define SAY_OK_OR_ERROR(condition) if (ret == (condition)) { std::cout << "Ok" << std::endl; } else { std::cout << "Error" << std::endl; } #define TEST_SERVER_IP_ADDR "192.168.1.215" #define TEST_SERVER_PORT 9098 constexpr int APP_ON = 0; constexpr int RECORDER_START = 1; constexpr int RECORDER_PAUSE = 2; constexpr int RECORDER_RESUME = 3; constexpr int RECORDER_STOP = 4; constexpr int APP_OFF = 5; using namespace std; using namespace media; using namespace media::stream; static std::string g_ipAddr = ""; static uint32_t g_port = 0; static void wifi_sta_connected(wifi_manager_result_e result) { std::cout << __FUNCTION__ << std::endl; } static void wifi_sta_disconnected(wifi_manager_disconnect_e disconn) { std::cout << __FUNCTION__ << std::endl; } static wifi_manager_cb_s wifi_callbacks = { wifi_sta_connected, wifi_sta_disconnected, NULL, NULL, NULL, }; class MediaStreamerTest : public MediaRecorderObserverInterface, public enable_shared_from_this<MediaStreamerTest> { public: void onRecordStarted(Id id) { std::cout << "onRecordStarted" << std::endl; } void onRecordPaused(Id id) { std::cout << "onRecordPaused" << std::endl; } void onRecordFinished(Id id) { std::cout << "onRecordFinished" << std::endl; } void onRecordError(Id id) { std::cout << "onRecordError" << std::endl; } void start() { appRunning = true; while (appRunning) { printRecorderMenu(); switch (userInput(APP_ON, APP_OFF)) { case APP_ON: { std::cout << "SELECTED APP ON" << std::endl; mr.create(); mr.setObserver(shared_from_this()); mr.setDataSource(unique_ptr<SocketOutputDataSource>(new SocketOutputDataSource(2, 16000, AUDIO_FORMAT_TYPE_S16_LE, g_ipAddr, 9098))); } break; case RECORDER_START: { std::cout << "SELECTED RECORDER_START" << std::endl; if (mr.prepare() == RECORDER_OK) { mr.start(); } else { std::cout << "prepare failed" << std::endl; } } break; case RECORDER_PAUSE: { std::cout << "SELECTED RECORDER_PAUSE" << std::endl; mr.pause(); } break; case RECORDER_RESUME: { std::cout << "SELECTED RECORDER_RESUME" << std::endl; mr.start(); } break; case RECORDER_STOP: { std::cout << "SELECTED RECORDER_STOP" << std::endl; if (mr.stop() == RECORDER_OK) { mr.unprepare(); } } break; case APP_OFF: { std::cout << "SELECTED APP_OFF" << std::endl; mr.destroy(); appRunning = false; } break; } } } void printRecorderMenu() { std::cout << "========================================" << std::endl; std::cout << "0. RECORDER APP ON" << std::endl; std::cout << "1. RECORDER Start" << std::endl; std::cout << "2. RECORDER Pause" << std::endl; std::cout << "3. RECORDER Resume" << std::endl; std::cout << "4. RECORDER Stop" << std::endl; std::cout << "5. RECORDER APP OFF" << std::endl; std::cout << "========================================" << std::endl; } int userInput(int min, int max) { assert(min <= max); int input = 0; std::cin >> input; std::cout << std::endl; if (!std::cin.fail()) { if (min <= input && input <= max) { std::cout << "return input" << std::endl; return input; } } std::cin.clear(); std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::cout << "Invalid Input, please try again" << std::endl; return input; } MediaStreamerTest() : appRunning(false) { wifi_manager_result_e ret = WIFI_MANAGER_FAIL; wifi_manager_ap_config_s config; std::cout << "wifi_manager_init()..."; ret = wifi_manager_init(&wifi_callbacks); SAY_OK_OR_ERROR(WIFI_MANAGER_SUCCESS); config.ssid_length = strlen(CONFIG_EXAMPLES_MEDIASTREAMER_SSID); config.passphrase_length = strlen(CONFIG_EXAMPLES_MEDIASTREAMER_PASSPHRASE); strncpy(config.ssid, CONFIG_EXAMPLES_MEDIASTREAMER_SSID, config.ssid_length + 1); strncpy(config.passphrase, CONFIG_EXAMPLES_MEDIASTREAMER_PASSPHRASE, config.passphrase_length + 1); config.ap_auth_type = (wifi_manager_ap_auth_type_e)CONFIG_EXAMPLES_MEDIASTREAMER_AUTHENTICATION; config.ap_crypto_type = (wifi_manager_ap_crypto_type_e)CONFIG_EXAMPLES_MEDIASTREAMER_CRYPTO; std::cout << "AP config: " << config.ssid << "(" << config.ssid_length << ") " << config.passphrase << "(" << config.passphrase_length << ") " << config.ap_auth_type << ", " << config.ap_crypto_type << std::endl; /* current wifi mode is station, then this try will succeed */ std::cout << "wifi_manager_connect_ap()..."; ret = wifi_manager_connect_ap(&config); SAY_OK_OR_ERROR(WIFI_MANAGER_SUCCESS); } ~MediaStreamerTest() { wifi_manager_result_e ret = WIFI_MANAGER_FAIL; std::cout << "wifi_manager_deinit()..."; ret = wifi_manager_deinit(); SAY_OK_OR_ERROR(WIFI_MANAGER_SUCCESS); } private: bool appRunning; MediaRecorder mr; MediaPlayer mp; }; extern "C" { int mediastreamer_main(int argc, char *argv[]) { /** * Need to sleep for WiFi initialized. */ int i = 0; for(i = 0; i < 3; i++) { printf("Wait (%d/3) sec...\n", i + 1); sleep(1); } g_ipAddr = TEST_SERVER_IP_ADDR; g_port = TEST_SERVER_PORT; auto mediaStreamerTest = make_shared<MediaStreamerTest>(); mediaStreamerTest->start(); return 0; } }
/* * * Copyright (c) 2014, weizhenwei * 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 {organization} 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: 95-Unique_Binary_Search_Trees_II.cpp * * * Brief: https://oj.leetcode.com/problems/unique-binary-search-trees-ii/ * Given n, generate all structurally unique BST's (binary search trees) that * store values 1...n. * * For example, * Given n = 3, your program should return all 5 unique BST's shown below. * * 1 3 3 2 1 * \ / / / \ \ * 3 2 1 1 3 2 * / / \ \ * 2 1 2 3 * * * Date: 2015.01.26 * * Author: weizhenwei <weizhenwei1988@gmail.com> * * ***************************************************************************** */ #include <stdio.h> #include <vector> using std::vector; // definition for binary tree; typedef struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }TreeNode; // originates from: https://oj.leetcode.com/discuss/21932/my-c-solution class Solution_Unique_Binary_Search_Tree { private: vector<TreeNode *> getTrees(int n, int offset) { vector<TreeNode *> ans; if (n == 0) { ans.push_back(NULL); return ans; } int i, j, k; for (i = 1; i <= n; i++) { // left nodes is smaller than i; vector<TreeNode *> left = getTrees(i - 1, offset); // right nodes is bigger than i; vector<TreeNode *> right = getTrees(n - i, i + offset); for (j = 0; j < left.size(); j++) { for (k = 0; k < right.size(); k++) { TreeNode *root = new TreeNode(i + offset); root->left = left[j]; root->right = right[k]; ans.push_back(root); } // k } // j } // i return ans; } public: vector<TreeNode *>generateTrees(int n) { return getTrees(n, 0); } }; static void print_tree(TreeNode *root) { if (root) { if (root->left) { if (root->left->left) { printf("root->left->left:%d\n", root->left->left->val); } printf("root->left:%d\n", root->left->val); if (root->left->right) { printf("root->left->right:%d\n", root->left->right->val); } } printf("root:%d\n", root->val); if (root->right) { if (root->right->left) { printf("root->right->left:%d\n", root->right->left->val); } printf("root->right:%d\n", root->right->val); if (root->right->right) { printf("root->right->right:%d\n", root->right->right->val); } } } printf("\n"); } int main(int argc, char *argv[]) { Solution_Unique_Binary_Search_Tree solution; int n = 3; vector<TreeNode *> trees = solution.generateTrees(n); for (int i = 0; i < trees.size(); i++) { print_tree(trees[i]); } return 0; }
// Copyright (c) 2016-2020 Intel Corporation // // 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 "reorder_kernel_fast_b1.h" #include "kernel_selector_utils.h" namespace kernel_selector { ParamsKey ReorderKernelFastBatch1::GetSupportedKey() const { ParamsKey k; k.EnableInputDataType(Datatype::F16); k.EnableInputDataType(Datatype::F32); k.EnableOutputDataType(Datatype::F16); k.EnableOutputDataType(Datatype::F32); k.EnableDifferentTypes(); k.EnableInputLayout(DataLayout::bfyx); k.EnableInputLayout(DataLayout::yxfb); k.EnableInputLayout(DataLayout::byxf); k.EnableInputLayout(DataLayout::fyxb); k.EnableInputLayout(DataLayout::bfzyx); k.EnableInputLayout(DataLayout::bfwzyx); k.EnableInputLayout(DataLayout::bs_f_bsv8__af8); k.EnableInputLayout(DataLayout::bs_f_bsv16__af8); k.EnableInputLayout(DataLayout::b_fs_yx_fsv16); k.EnableInputLayout(DataLayout::b_fs_zyx_fsv16); k.EnableOutputLayout(DataLayout::bfyx); k.EnableOutputLayout(DataLayout::yxfb); k.EnableOutputLayout(DataLayout::byxf); k.EnableOutputLayout(DataLayout::fyxb); k.EnableOutputLayout(DataLayout::bfzyx); k.EnableOutputLayout(DataLayout::bfwzyx); k.EnableOutputLayout(DataLayout::bs_f_bsv8__af8); k.EnableOutputLayout(DataLayout::bs_f_bsv16__af8); k.EnableOutputLayout(DataLayout::b_fs_yx_fsv16); k.EnableOutputLayout(DataLayout::b_fs_zyx_fsv16); k.EnableTensorOffset(); k.EnableTensorPitches(); k.EnableBatching(); return k; } bool ReorderKernelFastBatch1::Validate(const Params& p, const optional_params& o) const { if (!ReorderKernelBase::Validate(p, o)) { return false; } const reorder_params& params = static_cast<const reorder_params&>(p); if (params.output.GetLayout() == DataLayout::fs_b_yx_fsv32) return false; if (params.inputs[0].GetLayout() == DataLayout::fs_b_yx_fsv32) return false; return true; } JitConstants ReorderKernelFastBatch1::GetJitConstants(const reorder_params& params) const { auto jit = ReorderKernelBase::GetJitConstants(params); jit.Merge(GetTensorFriendlyWorkGroupsJit(params.inputs[0])); KernelData kd = KernelData::Default<reorder_params>(params); reorder_params& newParams = *static_cast<reorder_params*>(kd.params.get()); const auto& input = newParams.inputs[0]; jit.AddConstant(MakeJitConstant("ELEMENTS_COUNT", input.LogicalSize())); const auto& output = newParams.output; if (input.GetLayout() == output.GetLayout() && input.SameDimsSizes(output) && !input.PitchesDifferFromLogicalDims() && !output.PitchesDifferFromLogicalDims() && input.GetDType() != output.GetDType() && !params.has_padded_output && params.mode == MeanSubtractMode::NONE) { jit.AddConstant(MakeJitConstant("CHANGE_DATA_TYPE_ONLY", 1)); } return jit; } ReorderKernelFastBatch1::DispatchData ReorderKernelFastBatch1::SetDefault(const reorder_params& params) const { DispatchData dispatchData; const auto& output = params.output; unsigned int gws = (unsigned int)output.LogicalSize(); dispatchData.gws[0] = Align(gws, 32); dispatchData.gws[1] = 1; dispatchData.gws[2] = 1; dispatchData.lws[0] = 32; dispatchData.lws[1] = 1; dispatchData.lws[2] = 1; return dispatchData; } KernelsData ReorderKernelFastBatch1::GetKernelsData(const Params& params, const optional_params& options) const { assert(params.GetType() == KernelType::REORDER); const reorder_params& orgParams = static_cast<const reorder_params&>(params); const auto& input = orgParams.inputs[0]; const auto& output = orgParams.output; auto estimatedTime = DONT_USE_IF_HAVE_SOMETHING_ELSE; if (input.Batch().v == 1 && output.Batch().v == 1) estimatedTime = FORCE_PRIORITY_6; return GetCommonKernelsData(orgParams, options, estimatedTime); } } // namespace kernel_selector
#include "sentence_splitter.h" #include "gtest/gtest.h" #include "gmock/gmock.h" TEST(Sentence, ChrLength) { ASSERT_EQ(3, kss::getUTF8ChrLength("안", 0)); ASSERT_EQ(1, kss::getUTF8ChrLength("1", 0)); ASSERT_EQ(1, kss::getUTF8ChrLength("a", 0)); ASSERT_EQ(3, kss::getUTF8ChrLength("안녕", 3)); ASSERT_EQ(1, kss::getUTF8ChrLength("abc", 1)); ASSERT_EQ(3, kss::getUTF8ChrLength("a반가워", 1)); } TEST(Sentence, Input) { std::string input1 = "회사 동료 분들과 다녀왔는데 분위기도 좋고 음식도 맛있었어요 다만, 강남 토끼정이 강남 쉑쉑버거 골목길로 쭉 올라가야 하는데 다들 쉑쉑버거의 유혹에 넘어갈 뻔 했답니다 강남역 맛집 토끼정의 외부 모습."; std::string input2 = "역시 토끼정 본 점 답죠?ㅎㅅㅎ 건물은 크지만 간판이 없기 때문에 지나칠 수 있으니 조심하세요 강남 토끼정의 내부 인테리어."; std::string input3 = "전체적으로 편안하고 아늑한 공간으로 꾸며져 있었습니다ㅎㅎ 한 가지 아쉬웠던 건 조명이 너무 어두워 눈이 침침했던..."; std::string input4 = "총 5명이서 먹고 싶은 음식 하나씩 골라 다양하게 주문했어요 첫 번째 준비된 메뉴는 토끼정 고로케와 깻잎 불고기 사라다를 듬뿍 올려 먹는 맛있는 밥입니다."; std::string input5 = "다들 엄청 잘 드셨습니다ㅋㅋ 이건 제가 시킨 촉촉한 고로케와 크림스튜우동."; std::string input6 = "와사비를 안 좋아하는 저는 불행인지 다행인지 연어 지라시를 매우 맛있게 먹었습니다ㅋㅋㅋ 다음 메뉴는 달짝지근한 숯불 갈비 덮밥입니다!"; std::string input7 = "(물론 전 안 먹었지만...다른 분들이 그렇다고 하더라구요ㅋㅋㅋㅋㅋㅋㅋ) 마지막 메인 메뉴 양송이 크림수프와 숯불떡갈비 밥입니다."; std::string input8 = "크림스튜 우동 만큼이나 대박 맛있습니다...ㅠㅠㅠㅠㅠㅠ (크림 소스면 다 좋아하는 거 절대 아닙니다ㅋㅋㅋㅋㅋㅋ) 강남 토끼정 요리는 다 맛있지만 크림소스 요리를 참 잘하는 거 같네요 요건 물만 마시기 아쉬워 시킨 뉴자몽과 밀키소다 딸기통통!"; std::string input9 = "건물 위치도 강남 대로변에서 조금 떨어져 있어 내부 인테리어처럼 아늑한 느낌도 있었구요ㅎㅎ 기회가 되면 다들 꼭 들러보세요~"; std::string input10 = "요건 물만 마시기 아쉬워 시킨 뉴자몽과 밀키소다 딸기통통! 유자와 자몽의 맛을 함께 느낄 수 있는 뉴자몽은 상큼함 그 자체였어요. 하치만 저는 딸기통통 밀키소다가 더 맛있었습니다ㅎㅎ"; std::string input11 = "한다...라고 뭐라고?"; std::string input12 = "한다...라 뭐라고?"; std::string input13 = "지금으로서는 이번 사태의 근본적 책임이 일본에 있다는 점과 이로 인해 세계 경제가 피해를 볼 수 있다"; std::string input14 = "기회가 되면 다들 꼭 들러보세요.....!하"; ASSERT_THAT(splitSentences(input1), testing::ElementsAre("회사 동료 분들과 다녀왔는데 분위기도 좋고 음식도 맛있었어요", "다만, 강남 토끼정이 강남 쉑쉑버거 골목길로 쭉 올라가야 하는데 다들 쉑쉑버거의 유혹에 넘어갈 뻔 했답니다", "강남역 맛집 토끼정의 외부 모습.")); ASSERT_THAT(splitSentences(input2), testing::ElementsAre("역시 토끼정 본 점 답죠?ㅎㅅㅎ", "건물은 크지만 간판이 없기 때문에 지나칠 수 있으니 조심하세요", "강남 토끼정의 내부 인테리어.")); ASSERT_THAT(splitSentences(input3), testing::ElementsAre("전체적으로 편안하고 아늑한 공간으로 꾸며져 있었습니다ㅎㅎ", "한 가지 아쉬웠던 건 조명이 너무 어두워 눈이 침침했던...")); ASSERT_THAT(splitSentences(input4), testing::ElementsAre("총 5명이서 먹고 싶은 음식 하나씩 골라 다양하게 주문했어요", "첫 번째 준비된 메뉴는 토끼정 고로케와 깻잎 불고기 사라다를 듬뿍 올려 먹는 맛있는 밥입니다.")); ASSERT_THAT(splitSentences(input5), testing::ElementsAre("다들 엄청 잘 드셨습니다ㅋㅋ", "이건 제가 시킨 촉촉한 고로케와 크림스튜우동.")); ASSERT_THAT(splitSentences(input6), testing::ElementsAre("와사비를 안 좋아하는 저는 불행인지 다행인지 연어 지라시를 매우 맛있게 먹었습니다ㅋㅋㅋ", "다음 메뉴는 달짝지근한 숯불 갈비 덮밥입니다!")); ASSERT_THAT(splitSentences(input7), testing::ElementsAre("(물론 전 안 먹었지만...다른 분들이 그렇다고 하더라구요ㅋㅋㅋㅋㅋㅋㅋ)", "마지막 메인 메뉴 양송이 크림수프와 숯불떡갈비 밥입니다.")); ASSERT_THAT(splitSentences(input8), testing::ElementsAre("크림스튜 우동 만큼이나 대박 맛있습니다...ㅠㅠㅠㅠㅠㅠ", "(크림 소스면 다 좋아하는 거 절대 아닙니다ㅋㅋㅋㅋㅋㅋ)", "강남 토끼정 요리는 다 맛있지만 크림소스 요리를 참 잘하는 거 같네요", "요건 물만 마시기 아쉬워 시킨 뉴자몽과 밀키소다 딸기통통!")); ASSERT_THAT(splitSentences(input9), testing::ElementsAre("건물 위치도 강남 대로변에서 조금 떨어져 있어 내부 인테리어처럼 아늑한 느낌도 있었구요ㅎㅎ", "기회가 되면 다들 꼭 들러보세요~")); ASSERT_THAT(splitSentences(input10), testing::ElementsAre("요건 물만 마시기 아쉬워 시킨 뉴자몽과 밀키소다 딸기통통! 유자와 자몽의 맛을 함께 느낄 수 있는 뉴자몽은 상큼함 그 자체였어요.", "하치만 저는 딸기통통 밀키소다가 더 맛있었습니다ㅎㅎ")); ASSERT_THAT(splitSentences(input11), testing::ElementsAre("한다...라고 뭐라고?")); ASSERT_THAT(splitSentences(input12), testing::ElementsAre("한다...라 뭐라고?")); ASSERT_THAT(splitSentences(input13), testing::ElementsAre("지금으로서는 이번 사태의 근본적 책임이 일본에 있다는 점과 이로 인해 세계 경제가 피해를 볼 수 있다")); ASSERT_THAT(splitSentences(input14), testing::ElementsAre("기회가 되면 다들 꼭 들러보세요.....!","하")); } TEST(Sentence, MapCheck) { ASSERT_EQ(kss::map[kss::Stats::YO]["구"], kss::ID::PREV); ASSERT_EQ(kss::map[kss::Stats::YO]["꽥"], kss::ID::NONE); ASSERT_EQ(kss::map[kss::Stats::COMMON]["ㅋ"], kss::ID::CONT); }
//================================================================================================= /*! // \file src/mathtest/tsvecdmatmult/VCbDDb.cpp // \brief Source file for the VCbDDb sparse vector/dense matrix multiplication math test // // Copyright (C) 2013 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/CompressedVector.h> #include <blaze/math/DiagonalMatrix.h> #include <blaze/math/DynamicMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/tsvecdmatmult/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'VCbDDb'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions typedef blaze::CompressedVector<TypeB> VCb; typedef blaze::DiagonalMatrix< blaze::DynamicMatrix<TypeB> > DDb; // Creator type definitions typedef blazetest::Creator<VCb> CVCb; typedef blazetest::Creator<DDb> CDDb; // Running tests with small vectors and matrices for( size_t i=0UL; i<=6UL; ++i ) { for( size_t j=0UL; j<=i; ++j ) { RUN_TSVECDMATMULT_OPERATION_TEST( CVCb( i, j ), CDDb( i ) ); } } // Running tests with large vectors and matrices RUN_TSVECDMATMULT_OPERATION_TEST( CVCb( 67UL, 7UL ), CDDb( 67UL ) ); RUN_TSVECDMATMULT_OPERATION_TEST( CVCb( 127UL, 13UL ), CDDb( 127UL ) ); RUN_TSVECDMATMULT_OPERATION_TEST( CVCb( 64UL, 8UL ), CDDb( 64UL ) ); RUN_TSVECDMATMULT_OPERATION_TEST( CVCb( 128UL, 16UL ), CDDb( 128UL ) ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during sparse vector/dense matrix multiplication:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Copyright (c) 2017 The Astral Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/init.h" #include "net.h" #include "util.h" #include "utilmoneystr.h" #include "validation.h" #include "wallet/wallet.h" #include "wallet/rpcwallet.h" std::string GetWalletHelpString(bool showDebug) { std::string strUsage = HelpMessageGroup(_("Wallet options:")); strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls")); strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE)); strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE))); strUsage += HelpMessageOpt("-discardfee=<amt>", strprintf(_("The fee rate (in %s/kB) that indicates your tolerance for discarding change by adding it to the fee (default: %s). " "Note: An output is discarded if it is dust at this rate, but we will always discard up to the dust relay fee and a discard fee above that is limited by the fee estimate for the longest target"), CURRENCY_UNIT, FormatMoney(DEFAULT_DISCARD_FEE))); strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE))); strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"), CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK()))); strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup")); strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet on startup")); strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE)); strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET)); strUsage += HelpMessageOpt("-walletrbf", strprintf(_("Send transactions with full-RBF opt-in enabled (default: %u)"), DEFAULT_WALLET_RBF)); strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup")); strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), DEFAULT_WALLET_DAT)); strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST)); strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)")); strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") + " " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)")); if (showDebug) { strUsage += HelpMessageGroup(_("Wallet debugging/testing options:")); strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE)); strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET)); strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB)); strUsage += HelpMessageOpt("-walletrejectlongchains", strprintf(_("Wallet will not create transactions that violate mempool chain limits (default: %u)"), DEFAULT_WALLET_REJECT_LONG_CHAINS)); } return strUsage; } bool WalletParameterInteraction() { gArgs.SoftSetArg("-wallet", DEFAULT_WALLET_DAT); const bool is_multiwallet = gArgs.GetArgs("-wallet").size() > 1; if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) return true; if (gArgs.GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY) && gArgs.SoftSetBoolArg("-walletbroadcast", false)) { LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__); } if (gArgs.GetBoolArg("-salvagewallet", false)) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-salvagewallet")); } // Rewrite just private keys: rescan to find transactions if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__); } } int zapwallettxes = gArgs.GetArg("-zapwallettxes", 0); // -zapwallettxes implies dropping the mempool on startup if (zapwallettxes != 0 && gArgs.SoftSetBoolArg("-persistmempool", false)) { LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -persistmempool=0\n", __func__, zapwallettxes); } // -zapwallettxes implies a rescan if (zapwallettxes != 0) { if (is_multiwallet) { return InitError(strprintf("%s is only allowed with a single wallet file", "-zapwallettxes")); } if (gArgs.SoftSetBoolArg("-rescan", true)) { LogPrintf("%s: parameter interaction: -zapwallettxes=%s -> setting -rescan=1\n", __func__, zapwallettxes); } } if (is_multiwallet) { if (gArgs.GetBoolArg("-upgradewallet", false)) { return InitError(strprintf("%s is only allowed with a single wallet file", "-upgradewallet")); } } if (gArgs.GetBoolArg("-sysperms", false)) return InitError("-sysperms is not allowed in combination with enabled wallet functionality"); if (gArgs.GetArg("-prune", 0) && gArgs.GetBoolArg("-rescan", false)) return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again.")); if (::minRelayTxFee.GetFeePerK() > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-minrelaytxfee") + " " + _("The wallet will avoid paying less than the minimum relay fee.")); if (gArgs.IsArgSet("-mintxfee")) { CAmount n = 0; if (!ParseMoney(gArgs.GetArg("-mintxfee", ""), n) || 0 == n) return InitError(AmountErrMsg("mintxfee", gArgs.GetArg("-mintxfee", ""))); if (n > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-mintxfee") + " " + _("This is the minimum transaction fee you pay on every transaction.")); CWallet::minTxFee = CFeeRate(n); } if (gArgs.IsArgSet("-fallbackfee")) { CAmount nFeePerK = 0; if (!ParseMoney(gArgs.GetArg("-fallbackfee", ""), nFeePerK)) return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), gArgs.GetArg("-fallbackfee", ""))); if (nFeePerK > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-fallbackfee") + " " + _("This is the transaction fee you may pay when fee estimates are not available.")); CWallet::fallbackFee = CFeeRate(nFeePerK); } if (gArgs.IsArgSet("-discardfee")) { CAmount nFeePerK = 0; if (!ParseMoney(gArgs.GetArg("-discardfee", ""), nFeePerK)) return InitError(strprintf(_("Invalid amount for -discardfee=<amount>: '%s'"), gArgs.GetArg("-discardfee", ""))); if (nFeePerK > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-discardfee") + " " + _("This is the transaction fee you may discard if change is smaller than dust at this level")); CWallet::m_discard_rate = CFeeRate(nFeePerK); } if (gArgs.IsArgSet("-paytxfee")) { CAmount nFeePerK = 0; if (!ParseMoney(gArgs.GetArg("-paytxfee", ""), nFeePerK)) return InitError(AmountErrMsg("paytxfee", gArgs.GetArg("-paytxfee", ""))); if (nFeePerK > HIGH_TX_FEE_PER_KB) InitWarning(AmountHighWarn("-paytxfee") + " " + _("This is the transaction fee you will pay if you send a transaction.")); payTxFee = CFeeRate(nFeePerK, 1000); if (payTxFee < ::minRelayTxFee) { return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), gArgs.GetArg("-paytxfee", ""), ::minRelayTxFee.ToString())); } } if (gArgs.IsArgSet("-maxtxfee")) { CAmount nMaxFee = 0; if (!ParseMoney(gArgs.GetArg("-maxtxfee", ""), nMaxFee)) return InitError(AmountErrMsg("maxtxfee", gArgs.GetArg("-maxtxfee", ""))); if (nMaxFee > HIGH_MAX_TX_FEE) InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction.")); maxTxFee = nMaxFee; if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) { return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"), gArgs.GetArg("-maxtxfee", ""), ::minRelayTxFee.ToString())); } } nTxConfirmTarget = gArgs.GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET); bSpendZeroConfChange = gArgs.GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE); fWalletRbf = gArgs.GetBoolArg("-walletrbf", DEFAULT_WALLET_RBF); return true; } void RegisterWalletRPC(CRPCTable &t) { if (gArgs.GetBoolArg("-disablewallet", false)) return; RegisterWalletRPCCommands(t); } bool VerifyWallets() { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) return true; uiInterface.InitMessage(_("Verifying wallet(s)...")); // Keep track of each wallet absolute path to detect duplicates. std::set<fs::path> wallet_paths; for (const std::string& walletFile : gArgs.GetArgs("-wallet")) { if (boost::filesystem::path(walletFile).filename() != walletFile) { return InitError(strprintf(_("Error loading wallet %s. -wallet parameter must only specify a filename (not a path)."), walletFile)); } if (SanitizeString(walletFile, SAFE_CHARS_FILENAME) != walletFile) { return InitError(strprintf(_("Error loading wallet %s. Invalid characters in -wallet filename."), walletFile)); } fs::path wallet_path = fs::absolute(walletFile, GetDataDir()); if (fs::exists(wallet_path) && (!fs::is_regular_file(wallet_path) || fs::is_symlink(wallet_path))) { return InitError(strprintf(_("Error loading wallet %s. -wallet filename must be a regular file."), walletFile)); } if (!wallet_paths.insert(wallet_path).second) { return InitError(strprintf(_("Error loading wallet %s. Duplicate -wallet filename specified."), walletFile)); } std::string strError; if (!CWalletDB::VerifyEnvironment(walletFile, GetDataDir().string(), strError)) { return InitError(strError); } if (gArgs.GetBoolArg("-salvagewallet", false)) { // Recover readable keypairs: CWallet dummyWallet; std::string backup_filename; if (!CWalletDB::Recover(walletFile, (void *)&dummyWallet, CWalletDB::RecoverKeysOnlyFilter, backup_filename)) { return false; } } std::string strWarning; bool dbV = CWalletDB::VerifyDatabaseFile(walletFile, GetDataDir().string(), strWarning, strError); if (!strWarning.empty()) { InitWarning(strWarning); } if (!dbV) { InitError(strError); return false; } } return true; } bool OpenWallets() { if (gArgs.GetBoolArg("-disablewallet", DEFAULT_DISABLE_WALLET)) { LogPrintf("Wallet disabled!\n"); return true; } for (const std::string& walletFile : gArgs.GetArgs("-wallet")) { CWallet * const pwallet = CWallet::CreateWalletFromFile(walletFile); if (!pwallet) { return false; } vpwallets.push_back(pwallet); } return true; } void StartWallets(CScheduler& scheduler) { for (CWalletRef pwallet : vpwallets) { pwallet->postInitProcess(scheduler); } } void FlushWallets() { for (CWalletRef pwallet : vpwallets) { pwallet->Flush(false); } } void StopWallets() { for (CWalletRef pwallet : vpwallets) { pwallet->Flush(true); } } void CloseWallets() { for (CWalletRef pwallet : vpwallets) { delete pwallet; } vpwallets.clear(); }
#pragma once #include <bts/blockchain/types.hpp> #include <bts/blockchain/withdraw_types.hpp> #include <bts/blockchain/transaction.hpp> namespace bts { namespace blockchain { struct asset_record { enum { market_issued_asset = -2, market_feed_issued_asset = -3 }; asset_record() :id(0),issuer_account_id(0),precision(0),current_share_supply(0),maximum_share_supply(0),collected_fees(0){} share_type available_shares()const; bool can_issue( const asset& amount )const; bool can_issue( const share_type& amount )const; bool is_null()const; /** the asset is issued by the market and not by any user */ bool is_market_issued()const; bool uses_market_feed()const; asset_record make_null()const; uint64_t get_precision()const; asset_id_type id; std::string symbol; std::string name; std::string description; fc::variant public_data; account_id_type issuer_account_id; uint64_t precision; fc::time_point_sec registration_date; fc::time_point_sec last_update; share_type current_share_supply; share_type maximum_share_supply; share_type collected_fees; }; typedef fc::optional<asset_record> oasset_record; } } // bts::blockchain FC_REFLECT( bts::blockchain::asset_record, (id) (symbol) (name) (description) (public_data) (issuer_account_id) (precision) (registration_date) (last_update) (current_share_supply) (maximum_share_supply) (collected_fees) )
///////////////////////////////////////////////////////////////////////////////////////////////// // // Tencent is pleased to support the open source community by making libpag available. // // Copyright (C) 2021 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 "pag/pag.h" namespace pag { static const char sdkVersion[] = "4.0.0.1"; std::string PAG::SDKVersion() { return sdkVersion; } } // namespace pag
/* $Id: time-darwin.cpp $ */ /** @file * IPRT - Time, Darwin. */ /* * Copyright (C) 2006-2015 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. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #define LOG_GROUP RTLOGGROUP_TIME #define RTTIME_INCL_TIMEVAL #include <mach/mach_time.h> #include <mach/kern_return.h> #include <sys/time.h> #include <time.h> #include <iprt/time.h> #include <iprt/assert.h> #include "internal/time.h" /******************************************************************************* * Global Variables * *******************************************************************************/ static struct mach_timebase_info g_Info = { 0, 0 }; static double g_rdFactor = 0.0; static bool g_fFailedToGetTimeBaseInfo = false; /** * Perform lazy init (pray we're not racing anyone in a bad way). */ static void rtTimeDarwinLazyInit(void) { struct mach_timebase_info Info; if (mach_timebase_info(&Info) == KERN_SUCCESS) { g_rdFactor = (double)Info.numer / (double)Info.denom; g_Info = Info; } else { g_fFailedToGetTimeBaseInfo = true; Assert(g_Info.denom == 0 && g_Info.numer == 0 && g_rdFactor == 0.0); } } /** * Internal worker. * @returns Nanosecond timestamp. */ DECLINLINE(uint64_t) rtTimeGetSystemNanoTS(void) { /* Lazy init. */ if (RT_UNLIKELY(g_Info.denom == 0 && !g_fFailedToGetTimeBaseInfo)) rtTimeDarwinLazyInit(); /* special case: absolute time is in nanoseconds */ if (g_Info.denom == 1 && g_Info.numer == 1) return mach_absolute_time(); /* general case: multiply by factor to get nanoseconds. */ if (g_rdFactor != 0.0) return mach_absolute_time() * g_rdFactor; /* worst case: fallback to gettimeofday(). */ struct timeval tv; gettimeofday(&tv, NULL); return (uint64_t)tv.tv_sec * RT_NS_1SEC_64 + (uint64_t)(tv.tv_usec * RT_NS_1US); } RTDECL(uint64_t) RTTimeSystemNanoTS(void) { return rtTimeGetSystemNanoTS(); } RTDECL(uint64_t) RTTimeSystemMilliTS(void) { return rtTimeGetSystemNanoTS() / RT_NS_1MS; } RTDECL(PRTTIMESPEC) RTTimeNow(PRTTIMESPEC pTime) { /** @todo find nanosecond API for getting time of day. */ struct timeval tv; gettimeofday(&tv, NULL); return RTTimeSpecSetTimeval(pTime, &tv); }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 <sstream> #include <google/protobuf/compiler/code_generator.h> #include <google/protobuf/compiler/plugin.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/compiler/csharp/csharp_doc_comment.h> #include <google/protobuf/compiler/csharp/csharp_enum.h> #include <google/protobuf/compiler/csharp/csharp_helpers.h> #include <google/protobuf/compiler/csharp/csharp_options.h> using google::protobuf::internal::scoped_ptr; namespace google { namespace protobuf { namespace compiler { namespace csharp { EnumGenerator::EnumGenerator(const EnumDescriptor* descriptor, const Options* options) : SourceGeneratorBase(descriptor->file(), options), descriptor_(descriptor) { } EnumGenerator::~EnumGenerator() { } void EnumGenerator::Generate(io::Printer* printer) { WriteEnumDocComment(printer, descriptor_); printer->Print("$access_level$ enum $name$ {\n", "access_level", class_access_level(), "name", descriptor_->name()); printer->Indent(); std::set<string> used_names; for (int i = 0; i < descriptor_->value_count(); i++) { WriteEnumValueDocComment(printer, descriptor_->value(i)); string original_name = descriptor_->value(i)->name(); string name = options()->legacy_enum_values ? descriptor_->value(i)->name() : GetEnumValueName(descriptor_->name(), descriptor_->value(i)->name()); // Make sure we don't get any duplicate names due to prefix removal. while (!used_names.insert(name).second) { // It's possible we'll end up giving this warning multiple times, but that's better than not at all. GOOGLE_LOG(WARNING) << "Duplicate enum value " << name << " (originally " << original_name << ") in " << descriptor_->name() << "; adding underscore to distinguish"; name += "_"; } printer->Print("[pbr::OriginalName(\"$original_name$\")] $name$ = $number$,\n", "original_name", original_name, "name", name, "number", SimpleItoa(descriptor_->value(i)->number())); } printer->Outdent(); printer->Print("}\n"); printer->Print("\n"); } } // namespace csharp } // namespace compiler } // namespace protobuf } // namespace google
// Copyright 2018 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 "third_party/blink/renderer/modules/keyboard/keyboard_layout_map.h" namespace blink { class KeyboardLayoutMapIterationSource final : public PairIterable<String, String>::IterationSource { public: KeyboardLayoutMapIterationSource(const KeyboardLayoutMap& map) : map_(map), iterator_(map_->Map().begin()) {} bool Next(ScriptState* script_state, String& map_key, String& map_value, ExceptionState&) override { if (iterator_ == map_->Map().end()) return false; map_key = iterator_->key; map_value = iterator_->value; ++iterator_; return true; } void Trace(blink::Visitor* visitor) override { visitor->Trace(map_); PairIterable<String, String>::IterationSource::Trace(visitor); } private: // Needs to be kept alive while we're iterating over it. const Member<const KeyboardLayoutMap> map_; HashMap<String, String>::const_iterator iterator_; }; KeyboardLayoutMap::KeyboardLayoutMap(const HashMap<String, String>& map) : layout_map_(map) {} PairIterable<String, String>::IterationSource* KeyboardLayoutMap::StartIteration(ScriptState*, ExceptionState&) { return new KeyboardLayoutMapIterationSource(*this); } bool KeyboardLayoutMap::GetMapEntry(ScriptState*, const String& key, String& value, ExceptionState&) { auto it = layout_map_.find(key); if (it == layout_map_.end()) return false; value = it->value; return true; } } // namespace blink
#include "stub/populators.h" #include "mem/extract.h" #if defined _LINUX static constexpr uint8_t s_Buf_CPopulationManager_m_RespecPoints[] = { 0x55, // +0000 push ebp 0x89, 0xe5, // +0001 mov ebp,esp 0x57, // +0003 push edi 0x56, // +0004 push esi 0x53, // +0005 push ebx 0x83, 0xec, 0x3c, // +0006 sub esp,0x3c 0x8b, 0x5d, 0x08, // +0009 mov ebx,[ebp+this] 0x8d, 0x83, 0xe4, 0x06, 0x00, 0x00, // +000C lea eax,[ebx+0xVVVVVVVV] 0x89, 0x04, 0x24, // +0012 mov [esp],eax 0xe8, 0xe6, 0x64, 0x00, 0x00, // +0015 call CUtlRBTree<...>::RemoveAll }; struct CExtract_CPopulationManager_m_RespecPoints : public IExtract<CPopulationManager::SteamIDMap *> { using T = CPopulationManager::SteamIDMap *; CExtract_CPopulationManager_m_RespecPoints() : IExtract<T>(sizeof(s_Buf_CPopulationManager_m_RespecPoints)) {} virtual bool GetExtractInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CPopulationManager_m_RespecPoints); mask.SetRange(0x06 + 2, 1, 0x00); mask.SetRange(0x0c + 2, 4, 0x00); mask.SetRange(0x15 + 1, 4, 0x00); return true; } virtual const char *GetFuncName() const override { return "CPopulationManager::ResetRespecPoints"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0000; } virtual uint32_t GetExtractOffset() const override { return 0x000c + 2; } virtual T AdjustValue(T val) const override { return reinterpret_cast<T>((uintptr_t)val - 0x4); } }; static constexpr uint8_t s_Buf_CPopulationManager_m_bAllocatedBots[] = { 0x8b, 0x75, 0x08, // +0000 mov esi,[ebp+this] 0x80, 0xbe, 0x00, 0x00, 0x00, 0x00, 0x00, // +0003 cmp byte ptr [esi+0xVVVVVVVV],0 0x74, 0x00, // +000A jz +0x?? }; struct CExtract_CPopulationManager_m_bAllocatedBots : public IExtract<bool *> { using T = bool *; CExtract_CPopulationManager_m_bAllocatedBots() : IExtract<T>(sizeof(s_Buf_CPopulationManager_m_bAllocatedBots)) {} virtual bool GetExtractInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CPopulationManager_m_bAllocatedBots); mask.SetRange(0x03 + 2, 2, 0x00); mask.SetRange(0x0a + 1, 1, 0x00); return true; } virtual const char *GetFuncName() const override { return "CPopulationManager::AllocateBots"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0010; } // @ +0x0006 virtual uint32_t GetExtractOffset() const override { return 0x0003 + 2; } }; static constexpr uint8_t s_Buf_CPopulationManager_m_pTemplates[] = { 0x8B, 0x83, 0x90, 0x05, 0x00, 0x00, 0x85, 0xC0, }; struct CExtract_CPopulationManager_m_pTemplates : public IExtract<KeyValues **> { using T = KeyValues **; CExtract_CPopulationManager_m_pTemplates() : IExtract<T>(sizeof(s_Buf_CPopulationManager_m_pTemplates)) {} virtual bool GetExtractInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CPopulationManager_m_pTemplates); mask.SetRange(0x00 + 2, 4, 0x00); return true; } virtual const char *GetFuncName() const override { return "CPopulationManager::~CPopulationManager [D2]"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x00FF; } virtual uint32_t GetExtractOffset() const override { return 0x0000 + 2; } }; /*static constexpr uint8_t s_Buf_CWave_m_waveSpawnVector[] = { 0x55, // 0000 0x89, 0xE5, // 0001 0x56, // 0003 0x8B, 0x45, 0x08, // 0004 0x53, // 0007 0x8B, 0x58, 0x00, // 0008 0x85, 0xDB // 000B }; struct CExtract_CWave_m_waveSpawnVector : public IExtract<CUtlVector< CWaveSpawnPopulator * > *> { using T = CUtlVector< CWaveSpawnPopulator * > *; CExtract_CPopulationManager_m_bAllocatedBots() : IExtract<T>(sizeof(s_Buf_CWave_m_waveSpawnVector)) {} virtual bool GetExtractInfo(ByteBuf& buf, ByteBuf& mask) const override { buf.CopyFrom(s_Buf_CWave_m_waveSpawnVector); mask.SetRange(0x08 + 2, 1, 0x00); return true; } virtual const char *GetFuncName() const override { return "CWave::IsDoneWithNonSupportWaves"; } virtual uint32_t GetFuncOffMin() const override { return 0x0000; } virtual uint32_t GetFuncOffMax() const override { return 0x0000; } // @ +0x0006 virtual uint32_t GetExtractOffset() const override { return 0x0008 + 2; } virtual T AdjustValue(T val) const override { return reinterpret_cast<T>((uintptr_t)val - 0x4); } };*/ #elif defined _WINDOWS using CExtract_CPopulationManager_m_RespecPoints = IExtractStub; using CExtract_CPopulationManager_m_bAllocatedBots = IExtractStub; using CExtract_CPopulationManager_m_pTemplates = IExtractStub; #endif MemberFuncThunk<CPopulationManager *, bool, KeyValues *> CPopulationManager::ft_LoadMvMMission("CPopulationManager::LoadMvMMission"); MemberFuncThunk<CPopulationManager *, CWave *> CPopulationManager::ft_GetCurrentWave("CPopulationManager::GetCurrentWave"); MemberFuncThunk<CPopulationManager *, void> CPopulationManager::ft_ResetMap ("CPopulationManager::ResetMap"); MemberFuncThunk<CPopulationManager *, void> CPopulationManager::ft_PauseSpawning ("CPopulationManager::PauseSpawning"); MemberFuncThunk<CPopulationManager *, void> CPopulationManager::ft_UnpauseSpawning("CPopulationManager::UnpauseSpawning"); MemberFuncThunk<CPopulationManager *, void> CPopulationManager::ft_AllocateBots ("CPopulationManager::AllocateBots"); MemberFuncThunk<CPopulationManager *, bool> CPopulationManager::ft_IsInEndlessWaves("CPopulationManager::IsInEndlessWaves"); MemberFuncThunk<CPopulationManager *, void, CTFPlayer *> CPopulationManager::ft_RemovePlayerAndItemUpgradesFromHistory ("CPopulationManager::RemovePlayerAndItemUpgradesFromHistory"); MemberFuncThunk<CPopulationManager *, CUtlVector< CUpgradeInfo > *, CTFPlayer *> CPopulationManager::ft_GetPlayerUpgradeHistory ("CPopulationManager::GetPlayerUpgradeHistory"); StaticFuncThunk<int, CUtlVector<CTFPlayer *> *> CPopulationManager::ft_CollectMvMBots("CPopulationManager::CollectMvMBots"); StaticFuncThunk<void, CUtlVector<CUtlString> &> CPopulationManager::ft_FindDefaultPopulationFileShortNames("CPopulationManager::FindDefaultPopulationFileShortNames"); IMPL_EXTRACT(CPopulationManager::SteamIDMap, CPopulationManager, m_RespecPoints, new CExtract_CPopulationManager_m_RespecPoints()); IMPL_EXTRACT(bool, CPopulationManager, m_bAllocatedBots, new CExtract_CPopulationManager_m_bAllocatedBots()); IMPL_EXTRACT(KeyValues *, CPopulationManager, m_pTemplates, new CExtract_CPopulationManager_m_pTemplates()); GlobalThunk<CPopulationManager *> g_pPopulationManager("g_pPopulationManager"); MemberFuncThunk<CWave *, void, string_t, int, unsigned int> CWave::ft_AddClassType ("CWave::AddClassType"); MemberFuncThunk<CWave *, void> CWave::ft_ForceFinish ("CWave::ForceFinish"); MemberFuncThunk<CWave *, void> CWave::ft_ActiveWaveUpdate ("CWave::ActiveWaveUpdate"); MemberFuncThunk<CWave *, void> CWave::ft_WaveCompleteUpdate("CWave::WaveCompleteUpdate"); MemberFuncThunk<CWave *, bool> CWave::ft_IsDoneWithNonSupportWaves("CWave::IsDoneWithNonSupportWaves"); MemberFuncThunk<CWaveSpawnPopulator *, int> CWaveSpawnPopulator::ft_GetCurrencyAmountPerDeath("CWaveSpawnPopulator::GetCurrencyAmountPerDeath"); MemberFuncThunk<CMissionPopulator *, bool, int> CMissionPopulator::ft_UpdateMission("CMissionPopulator::UpdateMission"); MemberVFuncThunk<IPopulationSpawner *, string_t, int > IPopulationSpawner::vt_GetClassIcon(TypeName<IPopulationSpawner>(), "IPopulationSpawner::GetClassIcon"); MemberVFuncThunk<IPopulationSpawner *, bool, int > IPopulationSpawner::vt_IsMiniBoss (TypeName<IPopulationSpawner>(), "IPopulationSpawner::IsMiniBoss"); MemberVFuncThunk<IPopulationSpawner *, bool, CTFBot::AttributeType, int> IPopulationSpawner::vt_HasAttribute(TypeName<IPopulationSpawner>(), "IPopulationSpawner::HasAttribute"); MemberVFuncThunk<IPopulationSpawner *, bool, KeyValues * > IPopulationSpawner::vt_Parse (TypeName<CWaveSpawnPopulator>(), "CWaveSpawnPopulator::Parse"); StaticFuncThunk<bool, const Vector&> ft_IsSpaceToSpawnHere("IsSpaceToSpawnHere"); StaticFuncThunk<bool, CTFBot::EventChangeAttributes_t &, KeyValues *> ft_ParseDynamicAttributes("ParseDynamicAttributes");
/* *********************************************************************************************************************** * * Copyright (c) 2016-2019 Advanced Micro Devices, Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * **********************************************************************************************************************/ #include "core/cmdStream.h" #include "core/device.h" #include "core/internalMemMgr.h" #include "core/hw/gfxip/gfx6/gfx6Gds.h" #include "core/hw/gfxip/gfx6/gfx6Device.h" #include "core/hw/gfxip/gfx6/gfx6CmdStream.h" using namespace Util; namespace Pal { namespace Gfx6 { // ===================================================================================================================== // Loads data from memory to GDS before the specified HW pipeline point. void BuildLoadGds( CmdStream* pCmdStream, const CmdUtil* pCmdUtil, HwPipePoint pipePoint, uint32 dstGdsOffset, const IGpuMemory& srcGpuMemory, gpusize srcMemOffset, uint32 size) { PAL_ASSERT(((dstGdsOffset % 4) == 0) && ((srcMemOffset % 4) == 0) && ((size % 4) == 0)); uint32* pCmdSpace = pCmdStream->ReserveCommands(); // Use DMA_DATA to copy from memory to GDS. DmaDataInfo dmaData = {}; dmaData.dstSel = CPDMA_DST_SEL_GDS; dmaData.dstAddr = dstGdsOffset; dmaData.dstAddrSpace = CPDMA_ADDR_SPACE_MEM; dmaData.srcSel = CPDMA_SRC_SEL_SRC_ADDR; dmaData.srcAddr = srcGpuMemory.Desc().gpuVirtAddr + srcMemOffset; dmaData.srcAddrSpace = CPDMA_ADDR_SPACE_MEM; dmaData.numBytes = static_cast<uint32>(size); dmaData.sync = true; dmaData.usePfp = false; pCmdSpace += pCmdUtil->BuildDmaData(dmaData, pCmdSpace); pCmdStream->CommitCommands(pCmdSpace); } // ===================================================================================================================== // Stores data from GDS to memory after the specified HW pipeline point. void BuildStoreGds( CmdStream* pCmdStream, const CmdUtil* pCmdUtil, HwPipePoint pipePoint, uint32 srcGdsOffset, const IGpuMemory& dstGpuMemory, gpusize dstMemOffset, uint32 size, bool waitForWC, bool forComputeEngine, gpusize fenceAddr) { PAL_ASSERT(((srcGdsOffset % 4) == 0) && ((dstMemOffset % 4) == 0) && ((size % 4) == 0)); // Depending on the HW pipeline point we'll have to do the following (considering limitations of CP): // - HwPipeTop, HwPipePostIndexFetch: Simply do a CPDMA from GDS to memory // - HwPipePreRasterization, HwPipePostPs: Do a WRITE_EVENT_EOS(PS_DONE) to copy from GDS to memory // - HwPipePostCs: Do a WRITE_EVENT_EOS(CS_DONE) to copy from GDS to memory // - HwPipePostBlt, HwPipeBottom: Do a partial CS flush and then a WRITE_EVENT_EOS(PS_DONE) to copy // Decide whether to do CPDMA or WRITE_EVENT based on the specified HW pipeline point. const bool useCpdma = (pipePoint == HwPipeTop) || (pipePoint == HwPipePostIndexFetch); uint32* pCmdSpace = pCmdStream->ReserveCommands(); if (useCpdma) { // Use DMA_DATA to copy from GDS to memory. DmaDataInfo dmaData = {}; dmaData.dstSel = CPDMA_DST_SEL_DST_ADDR; dmaData.dstAddr = dstGpuMemory.Desc().gpuVirtAddr + dstMemOffset; dmaData.dstAddrSpace = CPDMA_ADDR_SPACE_MEM; dmaData.srcSel = CPDMA_SRC_SEL_GDS; dmaData.srcAddr = srcGdsOffset; dmaData.srcAddrSpace = CPDMA_ADDR_SPACE_MEM; dmaData.numBytes = static_cast<uint32>(size); dmaData.sync = true; dmaData.usePfp = false; pCmdSpace += pCmdUtil->BuildDmaData(dmaData, pCmdSpace); } else { // Depending on what HW pipeline point is used we have to use different event type. VGT_EVENT_TYPE eventType = PS_DONE; switch (pipePoint) { case HwPipePreRasterization: case HwPipePostPs: eventType = PS_DONE; break; case HwPipePostCs: eventType = CS_DONE; break; case HwPipePostBlt: case HwPipeBottom: if (forComputeEngine) { // For compute engines bottom of pipe is practically equivalent with CS_DONE. eventType = CS_DONE; } else { // Do a partial CS flush first, as there's no way to tell CP to write GDS after bottom of pipe, // so after the partial CS flush we'll simply use PS_DONE instead. pCmdSpace += pCmdUtil->BuildEventWrite(CS_PARTIAL_FLUSH, pCmdSpace); eventType = PS_DONE; } break; default: PAL_ASSERT(!"Unexpected HW pipeline point"); } // WRITE_EVENT requires GDS offset and size to be in dwords. const uint32 gdsDwordOffset = static_cast<uint32>(srcGdsOffset / sizeof(uint32)); const uint32 gdsDwordSize = static_cast<uint32>(size / sizeof(uint32)); // Use WRITE_EVENT to copy from GDS to memory. pCmdSpace += pCmdUtil->BuildGenericEosEvent(eventType, dstGpuMemory.Desc().gpuVirtAddr + dstMemOffset, EVENT_WRITE_EOS_CMD_STORE_GDS_DATA_TO_MEMORY, 0, gdsDwordOffset, gdsDwordSize, forComputeEngine, pCmdSpace); if (waitForWC) { // This will need a lot of extra space, so commit current commands and reserve a new chunk. pCmdStream->CommitCommands(pCmdSpace); pCmdSpace = pCmdStream->ReserveCommands(); pCmdSpace += pCmdUtil->BuildWaitOnGenericEosEvent(eventType, fenceAddr, forComputeEngine, pCmdSpace); } } pCmdStream->CommitCommands(pCmdSpace); } // ===================================================================================================================== // Updates data in GDS before the specified HW pipeline point. void BuildUpdateGds( CmdStream* pCmdStream, const CmdUtil* pCmdUtil, HwPipePoint pipePoint, uint32 gdsOffset, uint32 dataSize, const uint32* pData) { PAL_ASSERT(((gdsOffset % 4) == 0) && ((dataSize % 4) == 0) && (pData != nullptr)); // Use WRITE_DATA to update the contents of the GDS. We'll need to know how many DWORDs we can write in a single // WRITE_DATA packet without exceeding the size of the reserve buffer. const uint32 maxDwordsPerBatch = pCmdStream->ReserveLimit() - CmdUtil::GetWriteDataHeaderSize(); uint32 dataDwords = static_cast<uint32>(dataSize / sizeof(uint32)); WriteDataInfo writeData = {}; writeData.dstAddr = gdsOffset; writeData.engineSel = WRITE_DATA_ENGINE_ME; writeData.dstSel = WRITE_DATA_DST_SEL_GDS; while (dataDwords > 0) { const uint32 batchDwords = Min(dataDwords, maxDwordsPerBatch); uint32* pCmdSpace = pCmdStream->ReserveCommands(); pCmdSpace += pCmdUtil->BuildWriteData(writeData, batchDwords, pData, pCmdSpace); pCmdStream->CommitCommands(pCmdSpace); dataDwords -= batchDwords; writeData.dstAddr += batchDwords * sizeof(uint32); pData += batchDwords; } } // ===================================================================================================================== // Fills data in GDS before the specified HW pipeline point. void BuildFillGds( CmdStream* pCmdStream, const CmdUtil* pCmdUtil, HwPipePoint pipePoint, uint32 gdsOffset, uint32 fillSize, uint32 data) { PAL_ASSERT(((gdsOffset % 4) == 0) && ((fillSize % 4) == 0)); uint32* pCmdSpace = pCmdStream->ReserveCommands(); // Use DMA_DATA to fill GDS range. DmaDataInfo dmaData = {}; dmaData.dstSel = CPDMA_DST_SEL_GDS; dmaData.dstAddr = gdsOffset; dmaData.dstAddrSpace = CPDMA_ADDR_SPACE_MEM; dmaData.srcSel = CPDMA_SRC_SEL_DATA; dmaData.srcData = data; dmaData.numBytes = static_cast<uint32>(fillSize); dmaData.sync = true; dmaData.usePfp = false; pCmdSpace += pCmdUtil->BuildDmaData(dmaData, pCmdSpace); pCmdStream->CommitCommands(pCmdSpace); } } // Gfx6 } // Pal
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // 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 "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "util/engine/test_engines.hpp" #include "util/test_case.hpp" #include "util/test_control.hpp" using namespace std; using namespace ngraph; static string s_manifest = "${MANIFEST}"; using TestEngine = test::ENGINE_CLASS_NAME(${BACKEND_NAME}); NGRAPH_TEST(${BACKEND_NAME}, logical_xor) { Shape shape{2, 2, 2}; auto A = make_shared<op::Parameter>(element::boolean, shape); auto B = make_shared<op::Parameter>(element::boolean, shape); auto f = make_shared<Function>(make_shared<op::Xor>(A, B), ParameterVector{A, B}); std::vector<char> a{1, 0, 1, 1, 1, 0, 1, 0}; std::vector<char> b{0, 0, 1, 0, 0, 1, 1, 0}; auto test_case = test::TestCase<TestEngine>(f); test_case.add_multiple_inputs<char>({a, b}); test_case.add_expected_output<char>(shape, {1, 0, 0, 1, 1, 1, 0, 0}); test_case.run(); }
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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 "BlackboxTests.hpp" #include "PubSubReader.hpp" #include "PubSubWriter.hpp" #include <fastdds/dds/log/Log.hpp> #include <fastrtps/xmlparser/XMLProfileManager.h> #include <rtps/transport/test_UDPv4Transport.h> using namespace eprosima::fastrtps; using namespace eprosima::fastrtps::rtps; using test_UDPv4Transport = eprosima::fastdds::rtps::test_UDPv4Transport; using test_UDPv4TransportDescriptor = eprosima::fastdds::rtps::test_UDPv4TransportDescriptor; enum communication_type { TRANSPORT, INTRAPROCESS, DATASHARING }; using test_params = std::tuple<communication_type, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy>; class PubSubFragments : public testing::TestWithParam<test_params> { public: void SetUp() override { LibrarySettingsAttributes library_settings; switch (std::get<0>(GetParam())) { case INTRAPROCESS: library_settings.intraprocess_delivery = IntraprocessDeliveryType::INTRAPROCESS_FULL; xmlparser::XMLProfileManager::library_settings(library_settings); break; case DATASHARING: enable_datasharing = true; break; case TRANSPORT: default: break; } scheduler_policy_ = std::get<1>(GetParam()); } void TearDown() override { LibrarySettingsAttributes library_settings; switch (std::get<0>(GetParam())) { case INTRAPROCESS: library_settings.intraprocess_delivery = IntraprocessDeliveryType::INTRAPROCESS_OFF; xmlparser::XMLProfileManager::library_settings(library_settings); break; case DATASHARING: enable_datasharing = false; break; case TRANSPORT: default: break; } } protected: void do_fragment_test( const std::string& topic_name, std::list<Data1mb>& data, bool asynchronous, bool reliable, bool volatile_reader, bool volatile_writer, bool small_fragments) { PubSubReader<Data1mbType> reader(topic_name); PubSubWriter<Data1mbType> writer(topic_name); reader .socket_buffer_size(1048576) // accomodate large and fast fragments .history_depth(static_cast<int32_t>(data.size())) .reliability(reliable ? eprosima::fastrtps::RELIABLE_RELIABILITY_QOS : eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS) .durability_kind(volatile_reader ? eprosima::fastrtps::VOLATILE_DURABILITY_QOS : eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS) .init(); ASSERT_TRUE(reader.isInitialized()); if (small_fragments) { auto testTransport = std::make_shared<UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 1024; testTransport->maxMessageSize = 1024; testTransport->receiveBufferSize = 65536; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); } if (asynchronous) { writer.asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE). add_throughput_controller_descriptor_to_pparams(scheduler_policy_, 0, 0); } writer .history_depth(static_cast<int32_t>(data.size())) .reliability(reliable ? eprosima::fastrtps::RELIABLE_RELIABILITY_QOS : eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS) .durability_kind(volatile_writer ? eprosima::fastrtps::VOLATILE_DURABILITY_QOS : eprosima::fastrtps::TRANSIENT_LOCAL_DURABILITY_QOS) .init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); reader.startReception(data); // Send data writer.send(data, reliable ? 0u : 10u); ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. if (reliable) { reader.block_for_all(); } else { reader.block_for_at_least(2); } } eprosima::fastdds::rtps::FlowControllerSchedulerPolicy scheduler_policy_; }; TEST_P(PubSubFragments, PubSubAsNonReliableData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, true, false, false); } TEST_P(PubSubFragments, PubSubAsNonReliableVolatileData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, true, true, false); } TEST_P(PubSubFragments, PubSubAsNonReliableTransientLocalData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, false, false, false); } TEST_P(PubSubFragments, PubSubAsNonReliableData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, true, false, true); } TEST_P(PubSubFragments, PubSubAsNonReliableVolatileData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, true, true, true); } TEST_P(PubSubFragments, PubSubAsNonReliableTransientLocalData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, false, false, false, true); } TEST_P(PubSubFragments, PubSubAsReliableData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, true, false, false); } TEST_P(PubSubFragments, PubSubAsReliableVolatileData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, true, true, false); } TEST_P(PubSubFragments, PubSubAsReliableTransientLocalData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, false, false, false); } TEST_P(PubSubFragments, PubSubAsReliableData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, true, false, true); } TEST_P(PubSubFragments, PubSubAsReliableVolatileData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, true, true, true); } TEST_P(PubSubFragments, PubSubAsReliableTransientLocalData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, false, true, false, false, true); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, true, false, false); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableVolatileData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, true, true, false); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableTransientLocalData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, false, false, false); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, true, false, true); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableVolatileData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, true, true, true); } TEST_P(PubSubFragments, AsyncPubSubAsNonReliableTransientLocalData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, false, false, false, true); } TEST_P(PubSubFragments, AsyncPubSubAsReliableData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, true, false, false); } TEST_P(PubSubFragments, AsyncPubSubAsReliableVolatileData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, true, true, false); } TEST_P(PubSubFragments, AsyncPubSubAsReliableTransientLocalData300kb) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, false, false, false); } TEST_P(PubSubFragments, AsyncPubSubAsReliableData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, true, false, true); } TEST_P(PubSubFragments, AsyncPubSubAsReliableVolatileData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, true, true, true); } TEST_P(PubSubFragments, AsyncPubSubAsReliableTransientLocalData300kbSmallFragments) { auto data = default_data300kb_data_generator(); do_fragment_test(TEST_TOPIC_NAME, data, true, true, false, false, true); } class PubSubFragmentsLimited : public testing::TestWithParam<eprosima::fastdds::rtps::FlowControllerSchedulerPolicy> { public: void SetUp() override { scheduler_policy_ = GetParam(); } void TearDown() override { } protected: eprosima::fastdds::rtps::FlowControllerSchedulerPolicy scheduler_policy_; }; TEST_P(PubSubFragmentsLimited, AsyncPubSubAsNonReliableData300kbWithFlowControl) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 65536; uint32_t periodInMs = 50; writer.history_depth(10). reliability(eprosima::fastrtps::BEST_EFFORT_RELIABILITY_QOS). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE). add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_at_least(2); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableData300kbWithFlowControl) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(5). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 65536; uint32_t periodInMs = 50; writer.history_depth(5). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE). add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_all(); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableData300kbInLossyConditions) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(5). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 300000; uint32_t periodInMs = 200; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs); // To simulate lossy conditions, we are going to remove the default // bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 65536; testTransport->receiveBufferSize = 65536; // We drop 20% of all data frags testTransport->dropDataFragMessagesPercentage = 20; testTransport->dropLogLength = 1; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(5). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_all(); // Sanity check. Make sure we have dropped a few packets ASSERT_EQ( test_UDPv4Transport::test_UDPv4Transport_DropLog.size(), testTransport->dropLogLength); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableVolatileData300kbInLossyConditions) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(5). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 300000; uint32_t periodInMs = 200; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs); // To simulate lossy conditions, we are going to remove the default // bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 65536; testTransport->receiveBufferSize = 65536; // We drop 20% of all data frags testTransport->dropDataFragMessagesPercentage = 20; testTransport->dropLogLength = 1; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(5). durability_kind(eprosima::fastrtps::VOLATILE_DURABILITY_QOS). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_all(); // Sanity check. Make sure we have dropped a few packets ASSERT_EQ( test_UDPv4Transport::test_UDPv4Transport_DropLog.size(), testTransport->dropLogLength); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableData300kbInLossyConditionsSmallFragments) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(5). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 300000; uint32_t periodInMs = 200; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs); // To simulate lossy conditions, we are going to remove the default // bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 1024; testTransport->maxMessageSize = 1024; testTransport->receiveBufferSize = 65536; // We are sending around 300 fragments per sample. // We drop 1% of all data frags testTransport->dropDataFragMessagesPercentage = 1; testTransport->dropLogLength = 1; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(5). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_all(); // Sanity check. Make sure we have dropped a few packets ASSERT_EQ( test_UDPv4Transport::test_UDPv4Transport_DropLog.size(), testTransport->dropLogLength); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableKeyedData300kbKeepLast1InLossyConditionsSmallFragments) { PubSubReader<KeyedData1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<KeyedData1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(2) .reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS) .init(); ASSERT_TRUE(reader.isInitialized()); // To simulate lossy conditions, we are going to remove the default // builtin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->maxMessageSize = 1024; // We drop 20% of all data frags testTransport->dropDataFragMessagesPercentage = 20; testTransport->dropLogLength = 1; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 153601; uint32_t periodInMs = 100; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs) .heartbeat_period_seconds(0) .heartbeat_period_nanosec(1000000) .history_depth(1) .asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_keyeddata300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data, 100); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_seq({ 0, 5 }); // Sanity check. Make sure we have dropped a few packets ASSERT_EQ( test_UDPv4Transport::test_UDPv4Transport_DropLog.size(), testTransport->dropLogLength); } TEST_P(PubSubFragmentsLimited, AsyncPubSubAsReliableVolatileData300kbInLossyConditionsSmallFragments) { PubSubReader<Data1mbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data1mbType> writer(TEST_TOPIC_NAME); reader.history_depth(5). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t bytesPerPeriod = 300000; uint32_t periodInMs = 200; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, bytesPerPeriod, periodInMs); // To simulate lossy conditions, we are going to remove the default // bultin transport, and instead use a lossy shim layer variant. auto testTransport = std::make_shared<test_UDPv4TransportDescriptor>(); testTransport->sendBufferSize = 1024; testTransport->maxMessageSize = 1024; testTransport->receiveBufferSize = 65536; // We are sending around 300 fragments per sample. // We drop 1% of all data frags testTransport->dropDataFragMessagesPercentage = 1; testTransport->dropLogLength = 1; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(5). durability_kind(eprosima::fastrtps::VOLATILE_DURABILITY_QOS). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data300kb_data_generator(5); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. reader.block_for_all(); // Sanity check. Make sure we have dropped a few packets ASSERT_EQ( test_UDPv4Transport::test_UDPv4Transport_DropLog.size(), testTransport->dropLogLength); } TEST_P(PubSubFragmentsLimited, AsyncFragmentSizeTest) { // ThroghputController size large than maxMessageSize. { PubSubReader<Data64kbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data64kbType> writer(TEST_TOPIC_NAME); reader.history_depth(10). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t size = 32536; uint32_t periodInMs = 500; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, size, periodInMs); auto testTransport = std::make_shared<UDPv4TransportDescriptor>(); testTransport->maxMessageSize = 32000; testTransport->sendBufferSize = 65536; testTransport->receiveBufferSize = 65536; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(10).asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data64kb_data_generator(); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. std::this_thread::sleep_for(std::chrono::seconds(3)); size_t current_received = reader.getReceivedCount(); ASSERT_GE(current_received, static_cast<size_t>(1)); ASSERT_LE(current_received, static_cast<size_t>(3)); } // ThroghputController size smaller than maxMessageSize. { PubSubReader<Data64kbType> reader(TEST_TOPIC_NAME); PubSubWriter<Data64kbType> writer(TEST_TOPIC_NAME); reader.history_depth(10). reliability(eprosima::fastrtps::RELIABLE_RELIABILITY_QOS).init(); ASSERT_TRUE(reader.isInitialized()); // When doing fragmentation, it is necessary to have some degree of // flow control not to overrun the receive buffer. uint32_t size = 32000; uint32_t periodInMs = 500; writer.add_throughput_controller_descriptor_to_pparams(scheduler_policy_, size, periodInMs); auto testTransport = std::make_shared<UDPv4TransportDescriptor>(); testTransport->maxMessageSize = 32536; testTransport->sendBufferSize = 65536; testTransport->receiveBufferSize = 65536; writer.disable_builtin_transport(); writer.add_user_transport_to_pparams(testTransport); writer.history_depth(10). asynchronously(eprosima::fastrtps::ASYNCHRONOUS_PUBLISH_MODE).init(); ASSERT_TRUE(writer.isInitialized()); // Because its volatile the durability // Wait for discovery. writer.wait_discovery(); reader.wait_discovery(); auto data = default_data64kb_data_generator(); reader.startReception(data); // Send data writer.send(data); // In this test all data should be sent. ASSERT_TRUE(data.empty()); // Block reader until reception finished or timeout. std::this_thread::sleep_for(std::chrono::seconds(3)); size_t current_received = reader.getReceivedCount(); ASSERT_GE(current_received, static_cast<size_t>(1)); ASSERT_LE(current_received, static_cast<size_t>(3)); } } #ifdef INSTANTIATE_TEST_SUITE_P #define GTEST_INSTANTIATE_TEST_MACRO(x, y, z, w) INSTANTIATE_TEST_SUITE_P(x, y, z, w) #else #define GTEST_INSTANTIATE_TEST_MACRO(x, y, z, w) INSTANTIATE_TEST_CASE_P(x, y, z, w) #endif // ifdef INSTANTIATE_TEST_SUITE_P GTEST_INSTANTIATE_TEST_MACRO(PubSubFragments, PubSubFragments, testing::Combine( testing::Values(TRANSPORT, INTRAPROCESS, DATASHARING), testing::Values( eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::FIFO, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::ROUND_ROBIN, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::HIGH_PRIORITY, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION )), [](const testing::TestParamInfo<PubSubFragments::ParamType>& info) { std::string suffix; switch (std::get<1>(info.param)) { case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: suffix = "_SCHED_RESERV"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::HIGH_PRIORITY: suffix = "_SCHED_HIGH"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::ROUND_ROBIN: suffix = "_SCHED_ROBIN"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::FIFO: default: suffix = "_SCHED_FIFO"; } switch (std::get<0>(info.param)) { case INTRAPROCESS: return "Intraprocess" + suffix; case DATASHARING: return "Datasharing" + suffix; case TRANSPORT: default: return "Transport" + suffix; } }); GTEST_INSTANTIATE_TEST_MACRO(PubSubFragmentsLimited, PubSubFragmentsLimited, testing::Values( eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::FIFO, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::ROUND_ROBIN, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::HIGH_PRIORITY, eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION ), [](const testing::TestParamInfo<PubSubFragmentsLimited::ParamType>& info) { std::string suffix; switch (info.param) { case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::PRIORITY_WITH_RESERVATION: suffix = "_SCHED_RESERV"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::HIGH_PRIORITY: suffix = "_SCHED_HIGH"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::ROUND_ROBIN: suffix = "_SCHED_ROBIN"; break; case eprosima::fastdds::rtps::FlowControllerSchedulerPolicy::FIFO: default: suffix = "_SCHED_FIFO"; } return "Transport" + suffix; });
/* This program reads 2 compressed processed pileups (explicit ATCG counters) and looks for common lines between them. A "common line couple" is a couple of lines, one from the first file and the other from the second, with same chromosome and base number. This program needs Boost and ZLib libraries to work with gzipped files in input and output. If a common line couple is found, the program writes those lines in two corresponding output files. Also output is made on compressed text files. COMMAND LINE USAGE: "./common_lines_to_files.x processed_pileup_1 processed_pileup_2 common_processed_pileup_1 common_processed_pileup_2" Operatively it reads processed_pileup_2 and search it's lines in processed_pileup_1. NOTE THAT: For consistency the output of a run of this program with swapped arguments, file_1 with file_2, should be the same! It should find the same common lines, but the numbers of discarded and read lines may be different. */ #include <iostream> #include <string> #include <sstream> #include <fstream> #include <cassert> //Boost #include <fstream> #include <iostream> #include <boost/iostreams/filtering_streambuf.hpp> #include <boost/iostreams/copy.hpp> #include <boost/iostreams/filter/gzip.hpp> using namespace std; //Function to compute mut_freq from ATCG data for a line double compute_mut_freq(string ATCG_data); //Function to compute mut_freq from ATCG data for a line int compute_coverage(string ATCG_data); int main(int argc, char** argv){ //******************************************* // COMMAND LINE ARGS //******************************************* if (argc != 5){ cerr << "Usage: " << argv[0] << " processed_pileup_1 processed_pileup_2" << " common_lines_file_1 common_lines_file_2" << endl; return -1; } //filenames args string pseudo_pileup_1 = argv[1]; string pseudo_pileup_2 = argv[2]; string common_1 = argv[3]; string common_2 = argv[4]; //******************************************* // COMPRESSED INPUT //******************************************* //(IN) FILE 1 -------------------------------------------------- //assume it's compressed (.gz) ifstream file_1(pseudo_pileup_1, ios_base::in | ios_base::binary); if (file_1.is_open() == false) { cerr << "File 1 not opened: exit!" <<endl; return -1; } //uncompress boost::iostreams::filtering_streambuf<boost::iostreams::input> file_1_inbuf; file_1_inbuf.push(boost::iostreams::gzip_decompressor()); file_1_inbuf.push(file_1); //Convert streambuf to istream istream file_1_instream(&file_1_inbuf); cerr << endl << "File 1 opened." << endl; //(IN) FILE 2 -------------------------------------------------- //assume it's compressed (.gz) ifstream file_2(pseudo_pileup_2, ios_base::in | ios_base::binary); if (file_2.is_open() == false) { cerr << "File 2 file not opened: exit!" <<endl; return -1; } //uncompress boost::iostreams::filtering_streambuf<boost::iostreams::input> file_2_inbuf; file_2_inbuf.push(boost::iostreams::gzip_decompressor()); file_2_inbuf.push(file_2); //Convert streambuf to istream istream file_2_instream(&file_2_inbuf); cerr << "File 2 opened." << endl << endl; //******************************************* // COMPRESSED OUTPUT //******************************************* // Out for file 1 ofstream out_file_1(common_1, ios_base::out | ios_base::binary); boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf_1; outbuf_1.push(boost::iostreams::gzip_compressor()); outbuf_1.push(out_file_1); //Convert streambuf to ostream ostream out_1(&outbuf_1); // Out for file 2 ofstream out_file_2(common_2, ios_base::out | ios_base::binary); boost::iostreams::filtering_streambuf<boost::iostreams::output> outbuf_2; outbuf_2.push(boost::iostreams::gzip_compressor()); outbuf_2.push(out_file_2); //Convert streambuf to ostream ostream out_2(&outbuf_2); //******************************************* // PARSING VARIABLES //******************************************* //File 1 parsing variables------------- string file_1_line; //line of the file to parse string file_1_chromosome; //pos int file_1_chromosome_number = 0; long int file_1_base_number = 0; //1-based string file_1_ATCG_data; //not used here //File 2 parsing variables------------- string file_2_line; //line of the file to parse string file_2_chromosome; int file_2_chromosome_number = 0; long int file_2_base_number = 0; string file_2_ATCG_data; //not used here //Useful variables long int file_1_line_counter= 0; long int file_2_line_counter= 0; long int found_lines = 0; long int not_found_lines = 0; int current_chr = 0; long int found_in_chr = 0; bool file_1_ended = false; double mut_freq_1; double mut_freq_2; int coverage; //****************************************** //-------------------------------------- // START // // for all lines in file 2 search the // corrisponding line in file 1 //-------------------------------------- //****************************************** cerr<< "Start reading files." << endl << endl; //read first line of file 1 getline(file_1_instream, file_1_line); file_1_line_counter++; stringstream file_1_linestream(file_1_line); //get file_1 pos finding the separator ('\t') getline(file_1_linestream, file_1_chromosome, '\t'); // "chrN", N integer // ^ file_1_chromosome_number = atoi(&file_1_chromosome[3]); //get file_1 loc file_1_linestream >> file_1_base_number; //get file_1 ATCG data finding the separator ('\n') getline(file_1_linestream, file_1_ATCG_data, '\n'); //Loop for all line in file 2 while (getline(file_2_instream, file_2_line)) { //until file_2 EOF //Parse file 2 input line stringstream file_2_linestream(file_2_line); file_2_line_counter++; //get file_2 line pos finding the separator ('\t') getline(file_2_linestream, file_2_chromosome, '\t'); //get file_2 loc file_2_linestream >> file_2_base_number; //we need chromosome numeber and loc //extract chromosome number from chromosome string // "chrN", N integer // ^ file_2_chromosome_number = atoi(&file_2_chromosome[3]); //get file_2 ATCG data finding the separator ('\n') getline(file_2_linestream, file_2_ATCG_data, '\n'); //cout<< "File 2 line red: " <<file_2_chromosome << " " << file_2_base_number << " "<< file_2_ATCG_data<< endl; //Add line to file 2 histogram mut_freq_2 = compute_mut_freq(file_2_ATCG_data); if(mut_freq_2 < 0.) { //rarely there are "M","N", or "R" in reference //we need to skip that line cerr << "Freq error! Skip this line from file 2:"<< endl << file_2_chromosome << "\t" << file_2_base_number << file_2_ATCG_data<< endl; } //Go on with file 1 until we find or exceed the line while((file_1_chromosome_number < file_2_chromosome_number) || ( (file_1_chromosome_number == file_2_chromosome_number) && (file_1_base_number < file_2_base_number) ) ){ //cout <<"Discarded from file 1 "<<file_1_chromosome << " " << file_1_base_number << " "<< file_1_ATCG_data<< endl; // read next line on file_1 if(getline(file_1_instream, file_1_line)){//if not file 1 EOF file_1_line_counter++; stringstream file_1_linestream(file_1_line); //get file_1 pos finding the separator ('\t') getline(file_1_linestream, file_1_chromosome, '\t'); // "chrN", N integer // ^ file_1_chromosome_number = atoi(&file_1_chromosome[3]); //get file_1 loc file_1_linestream >> file_1_base_number; //get file_1 ATCG data finding the separator ('\n') getline(file_1_linestream, file_1_ATCG_data, '\n'); } //if not file 1 EOF else{ // file 1 finished before file 2 if (!file_1_ended){ cout << "File 1 finished before file 2." <<endl; cout << "Last line was: " << file_1_chromosome << " " << file_1_base_number << endl; file_1_ended = true; } break; //break file 1 loop // we don't break also file 2 loop just to count it's lines } } //file 1 loop //cout<< "Last line after file 1 loop" << endl; //cout<<file_1_chromosome << " " << file_1_base_number << " "<< file_1_ATCG_data<< endl; //count common lines per chromosome if (file_2_chromosome_number != current_chr){ //check if chromosomes are ordered assert(current_chr < file_2_chromosome_number); if (current_chr != 0) { cout << "---> Found in chr" << current_chr <<" "<< found_in_chr << " common lines"<< endl; found_in_chr = 0; } current_chr = file_2_chromosome_number; } if ((file_1_chromosome_number == file_2_chromosome_number) && (file_1_base_number == file_2_base_number)) { //cout << "Found line!" << endl; // We found a common line! mut_freq_2 = compute_mut_freq(file_2_ATCG_data); mut_freq_1 = compute_mut_freq(file_1_ATCG_data); if(mut_freq_1 >= 0. && mut_freq_2 >= 0.) { //rarely there are "M","N", or "R" in reference //we need to skip that line found_lines++; found_in_chr++; //output relative lines to outfiles //formatted correcly out_1 << file_1_chromosome << "\t" << file_1_base_number << file_1_ATCG_data << endl; out_2 << file_2_chromosome << "\t" << file_2_base_number << file_2_ATCG_data << endl; } } else { //line not found //cout << "Not common line: " <<file_1_chromosome << " " << file_1_base_number << " "<< file_1_ATCG_data<< endl; //cout<< "Looking for: " <<file_2_chromosome << " " << file_2_base_number << endl<<endl; if (!file_1_ended){ // the last line red from file 1 // is after the one we are looking for assert( ( (file_1_chromosome_number == file_2_chromosome_number) && (file_1_base_number > file_2_base_number) ) || (file_1_chromosome_number > file_2_chromosome_number) ); } not_found_lines++; //cout << "Not found line!" << endl; } } //file 2 loop, until file 2 EOF //print last chromosome counter cout << "---> Found in chr" << current_chr <<" "<< found_in_chr << " common lines"<< endl; cout << endl; //print summary cout << "Terminated: " << endl << "total common lines found " << found_lines << " of " << file_2_line_counter << " red from file 2." << endl; cout << "Lines not found " << not_found_lines << endl; if (file_1_ended) { cout << "File 1 ended before file 2 was totally red." << endl; cout << "File 1 total lines: " << file_1_line_counter << endl; } else { cout << "File 2 was totally red, but file 1 was not." << endl; cout << "File 1 lines red: " << file_1_line_counter << endl; } //******************************************* // CLEANUP //******************************************* //close input files file_1.close(); file_2.close(); //close output boost::iostreams::close(outbuf_1); boost::iostreams::close(outbuf_2); out_file_1.close(); out_file_2.close(); cout << "Otput written on files."<<endl; //end return 0; } //main() end //Function to compute mut_freq from ATCG data for a line double compute_mut_freq(string ATCG_data){ char reference; int A_counter; int T_counter; int C_counter; int G_counter; int a_counter; int t_counter; int c_counter; int g_counter; stringstream ATCG_linestream(ATCG_data); int coverage = 0; double mut_freq; ATCG_linestream >> reference; //rarely there are "M","N", or "R" in reference //we need to discard that line if(reference != 'A' && reference != 'T' && reference != 'C' && reference != 'G') { //reference is not A, T, C, G // return -1. as impossible frequency return -1.; } ATCG_linestream >> A_counter; coverage += A_counter; ATCG_linestream >> T_counter; coverage += T_counter; ATCG_linestream >> C_counter; coverage += C_counter; ATCG_linestream >> G_counter; coverage += G_counter; ATCG_linestream >> a_counter; coverage += a_counter; ATCG_linestream >> t_counter; coverage += t_counter; ATCG_linestream >> c_counter; coverage += c_counter; ATCG_linestream >> g_counter; coverage += g_counter; if (reference == 'A'){ int muted_reads = coverage - ( A_counter + a_counter); mut_freq = double(muted_reads)/double(coverage); } if (reference == 'T'){ int muted_reads = coverage - ( T_counter + t_counter); mut_freq = double(muted_reads)/double(coverage); } if (reference == 'C'){ int muted_reads = coverage - ( C_counter + c_counter); mut_freq = double(muted_reads)/double(coverage); } if (reference == 'G'){ int muted_reads = coverage - ( G_counter + g_counter); mut_freq = double(muted_reads)/double(coverage); } return mut_freq; } //Function to compute mut_freq from ATCG data for a line int compute_coverage(string ATCG_data){ char reference; int A_counter; int T_counter; int C_counter; int G_counter; int a_counter; int t_counter; int c_counter; int g_counter; stringstream ATCG_linestream(ATCG_data); int coverage = 0; double mut_freq; ATCG_linestream >> reference; ATCG_linestream >> A_counter; coverage += A_counter; ATCG_linestream >> T_counter; coverage += T_counter; ATCG_linestream >> C_counter; coverage += C_counter; ATCG_linestream >> G_counter; coverage += G_counter; ATCG_linestream >> a_counter; coverage += a_counter; ATCG_linestream >> t_counter; coverage += t_counter; ATCG_linestream >> c_counter; coverage += c_counter; ATCG_linestream >> g_counter; coverage += g_counter; return coverage; }
#include "bgspch.h" #include "Engine/Renderer/API/Framebuffer.h" #include "Engine/Renderer/API/RendererAPI.h" #include "Engine/Renderer/Renderer.h" #include "Engine/Core/Core.h" #include "Platform/DX11/DX11Framebuffer.h" namespace BIGOS { std::shared_ptr<Framebuffer> Framebuffer::Create(const FramebufferSpecification& spec) { switch (Renderer::GetAPI()) { case RendererAPI::API::NONE: BGS_CORE_ASSERT(false, "RendererAPI::None is currently not supported!"); return nullptr; case RendererAPI::API::OPENGL: BGS_CORE_ASSERT(false, "RendererAPI::OPENGL is currently not supported!"); return nullptr; case RendererAPI::API::DIRECTX11: return std::make_shared<DX11Framebuffer>(spec); case RendererAPI::API::VULKAN: BGS_CORE_ASSERT(false, "RendererAPI::VULKAN is currently not supported!"); return nullptr; } BGS_CORE_ASSERT(false, "Unknown RendererAPI!"); return nullptr; } }
// Copyright (c) 2020 Xi Cheng. All rights reserved. // Use of this source code is governed by a Apache License 2.0 that can be // found in the LICENSE file. #include <chrono> #include <ctime> #include <vector> #include "gtest/gtest.h" #include "src/delay_queue.h" struct Task { using TimePoint = std::chrono::high_resolution_clock::time_point; // Constructor, setting the scheduled time Task(uint64_t delay_milliseconds) : scheduledTime_(std::chrono::high_resolution_clock::now()), delay_milliseconds_(delay_milliseconds) {} // A trivial task run function to ensure the timing is correct void run() { executeTime_ = std::chrono::high_resolution_clock::now(); auto delay_duration_milliseconds = std::chrono::duration_cast< std::chrono::milliseconds>(executeTime_ - scheduledTime_).count(); // Make sure that the actual delay duration is higher than or equal to // the configured value EXPECT_GE(delay_duration_milliseconds, delay_milliseconds_); // Make sure that the difference between the actual delay duration // and the configured value is within an acceptable range EXPECT_LE(delay_duration_milliseconds - delay_milliseconds_, epsilon_milliseconds_); } // Two timepoint indicating the time when a task is scheduled and the time // that it gets executed TimePoint scheduledTime_; TimePoint executeTime_; // The delay expressed in milliseconds uint64_t delay_milliseconds_; // A small amount of time duration when checking the executed time. Note // that here this value represents 0.1 second, and the task's delay time // in this test is on the scale of seconds. We expect this level of // tolerance to work fine in this non-stress test uint64_t epsilon_milliseconds_ = 100; }; class DelayQueueTimeCheckUnitTest : public ::testing::Test { protected: DelayQueue delay_queue_; // Test mode enum TaskInsertSequence { sequential_, reverse_, random_ }; // Helper function to test different scenario for the single thread case. // This function creates a {num_tasks} number of tasks with an // {interval_milliseconds} duration apart from each other, and would insert // the tasks to delay queue according to the pattern specified by {mode} void MultipleTaskTestSingleThread(unsigned int num_tasks, unsigned int interval_milliseconds, TaskInsertSequence mode) { std::vector<Task> tasks; // Get the task objects initialized for (unsigned int i = 0; i < num_tasks; i++) { tasks.emplace_back(i * interval_milliseconds); } // Emit tasks std::vector<std::future<void>> task_futures(num_tasks); switch (mode) { case sequential_: for (unsigned int i = 0; i < num_tasks; i++) { task_futures[i] = delay_queue_.AddTask(tasks[i].delay_milliseconds_, std::bind(&Task::run, &tasks[i])); } break; case reverse_: for (unsigned int i = 0; i < num_tasks; i++) { task_futures[i] = delay_queue_.AddTask( tasks[num_tasks - i - 1].delay_milliseconds_, std::bind(&Task::run, &tasks[num_tasks - i - 1])); } break; case random_: // Use the current time as seed for random generator std::srand(std::time(nullptr)); std::vector<int> task_idx; for (unsigned int i = 0; i < num_tasks; i++) { task_idx.push_back(i); } // Randomly shuffle the task to be added to the delay queue for (unsigned int i = 0; i < num_tasks; i++) { int idx = std::rand() % task_idx.size(); task_futures[i] = delay_queue_.AddTask( tasks[task_idx[idx]].delay_milliseconds_, std::bind(&Task::run, &tasks[task_idx[idx]])); // Remove the task index selected task_idx.erase(task_idx.begin() + idx); } break; } // Wait for task to complete for (auto& task_future : task_futures) { task_future.get(); } } }; // Single task, ensure that the timing is correct TEST_F(DelayQueueTimeCheckUnitTest, SingleTask) { Task task(1000); // Delay time 1s auto task_future = delay_queue_.AddTask(task.delay_milliseconds_, std::bind(&Task::run, &task)); // Wait for the task to complete task_future.get(); } // Test multiple tasks added in sequence TEST_F(DelayQueueTimeCheckUnitTest, MultipleTaskSequential) { MultipleTaskTestSingleThread(10, 1000, TaskInsertSequence::sequential_); } // Test multiple tasks added in reverse sequence TEST_F(DelayQueueTimeCheckUnitTest, MultipleTaskReverse) { MultipleTaskTestSingleThread(10, 1000, TaskInsertSequence::reverse_); } // Test multiple tasks added in random order TEST_F(DelayQueueTimeCheckUnitTest, MultipleTaskRandom) { MultipleTaskTestSingleThread(10, 1000, TaskInsertSequence::random_); }
#include <iostream> using namespace std; int main() { // simply echo the input number int x; cin >> x; cout << x << endl; return 0; }
/** * @file hmm_regression.hpp * @author Michael Fox * * Definition of HMMRegression class. */ #ifndef MLPACK_METHODS_HMM_HMM_REGRESSION_HPP #define MLPACK_METHODS_HMM_HMM_REGRESSION_HPP #include <mlpack/core.hpp> #include <mlpack/core/dists/regression_distribution.hpp> #include "hmm.hpp" namespace mlpack { namespace hmm /** Hidden Markov Models. */ { /** * A class that represents a Hidden Markov Model Regression (HMMR). HMMR is an * extension of Hidden Markov Models to regression analysis. The method is * described in (Fridman, 1993) * https://www.ima.umn.edu/preprints/January1994/1195.pdf * An HMMR is a linear regression model whose coefficients are determined by a * finite-state Markov chain. The error terms are conditionally independently * normally distributed with zero mean and state-dependent variance. Let Q_t be * a finite-state Markov chain, X_t a vector of predictors and Y_t a response. * The HMMR is * Y_t = X_t \beta_{Q_t} + \sigma_{Q_t} \epsilon_t * * This HMMR class supports training (supervised and unsupervised), prediction * of state sequences via the Viterbi algorithm, estimation of state * probabilities, filtering and smoothing of responses, and calculation of the * log-likelihood of a given sequence. * * Usage of the HMMR class generally involves either training an HMMR or loading * an already-known HMMR and using to filter a sequence. * Example code for supervised training of an HMMR is given below. * * @code * // Each column is a vector of predictors for a single observation. * arma::mat predictors(5, 100, arma::fill::randn); * // Responses for each observation * arma::vec responses(100, arma::fill::randn); * * // Create an untrained HMMR with 3 hidden states * RegressionDistribution rd(predictors, responses); * arma::mat transition("0.5 0.5;" "0.5 0.5;"); * std::vector<RegressionDistribution> emissions(2,rd); * HMMRegression hmmr("0.9 0.1", transition, emissions); * * // Train the HMM (supply a state sequence to perform supervised training) * std::vector<arma::mat> predictorsSeq(1, predictors); * std::vector< arma::vec> responsesSeq(1, responses); * hmmr.Train(predictorsSeq, responsesSeq); * hmm.Train(observations, states); * @endcode * * Once initialized, the HMMR can evaluate the probability of a certain sequence * (with LogLikelihood()), predict the most likely sequence of hidden states * (with Predict()), estimate the probabilities of each state for a sequence of * observations (with Estimate()), or perform filtering or smoothing of * observations. * */ class HMMRegression : public HMM<distribution::RegressionDistribution> { public: /** * Create the Hidden Markov Model Regression with the given number of hidden * states and the given default regression emission. The dimensionality of the * observations is taken from the emissions variable, so it is important that * the given default emission distribution is set with the correct * dimensionality. Alternately, set the dimensionality with Dimensionality(). * Optionally, the tolerance for convergence of the Baum-Welch algorithm can * be set. * * By default, the transition matrix and initial probability vector are set to * contain equal probability for each state. * * @param states Number of states. * @param emissions Default distribution for emissions. * @param tolerance Tolerance for convergence of training algorithm * (Baum-Welch). */ HMMRegression(const size_t states, const distribution::RegressionDistribution emissions, const double tolerance = 1e-5) : HMM<distribution::RegressionDistribution>(states, emissions, tolerance) { /* nothing to do */ } /** * Create the Hidden Markov Model Regression with the given initial * probability vector, the given transition matrix, and the given regression * emission distributions. The dimensionality of the observations of the HMMR * are taken from the given emission distributions. Alternately, the * dimensionality can be set with Dimensionality(). * * The initial state probability vector should have length equal to the number * of states, and each entry represents the probability of being in the given * state at time T = 0 (the beginning of a sequence). * * The transition matrix should be such that T(i, j) is the probability of * transition to state i from state j. The columns of the matrix should sum * to 1. * * Optionally, the tolerance for convergence of the Baum-Welch algorithm can * be set. * * @param initial Initial state probabilities. * @param transition Transition matrix. * @param emission Emission distributions. * @param tolerance Tolerance for convergence of training algorithm * (Baum-Welch). */ HMMRegression(const arma::vec& initial, const arma::mat& transition, const std::vector<distribution::RegressionDistribution>& emission, const double tolerance = 1e-5) : HMM<distribution::RegressionDistribution>(initial, transition, emission, tolerance) { /* nothing to do */ } /** * Train the model using the Baum-Welch algorithm, with only the given * predictors and responses. Instead of giving a guess transition and emission * here, do that in the constructor. Each matrix in the vector of predictors * corresponds to an individual data sequence, and likewise for each vec in * the vector of responses. The number of rows in each matrix of predictors * plus one should be equal to the dimensionality of the HMM (which is set in * the constructor). * * It is preferable to use the other overload of Train(), with labeled data. * That will produce much better results. However, if labeled data is * unavailable, this will work. In addition, it is possible to use Train() * with labeled data first, and then continue to train the model using this * overload of Train() with unlabeled data. * * The tolerance of the Baum-Welch algorithm can be set either in the * constructor or with the Tolerance() method. When the change in * log-likelihood of the model between iterations is less than the tolerance, * the Baum-Welch algorithm terminates. * * @note * Train() can be called multiple times with different sequences; each time it * is called, it uses the current parameters of the HMM as a starting point * for training. * @endnote * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. */ void Train(const std::vector<arma::mat>& predictors, const std::vector<arma::vec>& responses); /** * Train the model using the given labeled observations; the transition and * regression emissions are directly estimated. Each matrix in the vector of * predictors corresponds to an individual data sequence, and likewise for * each vec in the vector of responses. The number of rows in each matrix of * predictors plus one should be equal to the dimensionality of the HMM * (which is set in the constructor). * * @note * Train() can be called multiple times with different sequences; each time it * is called, it uses the current parameters of the HMMR as a starting point * for training. * @endnote * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param stateSeq Vector of state sequences, corresponding to each * observation. */ void Train(const std::vector<arma::mat>& predictors, const std::vector<arma::vec>& responses, const std::vector<arma::Row<size_t> >& stateSeq); /** * Estimate the probabilities of each hidden state at each time step for each * given data observation, using the Forward-Backward algorithm. Each matrix * which is returned has columns equal to the number of data observations, and * rows equal to the number of hidden states in the model. The log-likelihood * of the most probable sequence is returned. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param stateProb Matrix in which the probabilities of each state at each * time interval will be stored. * @param forwardProb Matrix in which the forward probabilities of each state * at each time interval will be stored. * @param backwardProb Matrix in which the backward probabilities of each * state at each time interval will be stored. * @param scales Vector in which the scaling factors at each time interval * will be stored. * @return Log-likelihood of most likely state sequence. */ double Estimate(const arma::mat& predictors, const arma::vec& responses, arma::mat& stateProb, arma::mat& forwardProb, arma::mat& backwardProb, arma::vec& scales) const; /** * Estimate the probabilities of each hidden state at each time step of each * given data observation, using the Forward-Backward algorithm. The returned * matrix of state probabilities has columns equal to the number of data * observations, and rows equal to the number of hidden states in the model. * The log-likelihood of the most probable sequence is returned. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param stateProb Probabilities of each state at each time interval. * @return Log-likelihood of most likely state sequence. */ double Estimate(const arma::mat& predictors, const arma::vec& responses, arma::mat& stateProb) const; /** * Compute the most probable hidden state sequence for the given predictors * and responses, using the Viterbi algorithm, returning the log-likelihood of * the most likely state sequence. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param stateSeq Vector in which the most probable state sequence will be * stored. * @return Log-likelihood of most probable state sequence. */ double Predict(const arma::mat& predictors, const arma::vec& responses, arma::Row<size_t>& stateSeq) const; /** * Compute the log-likelihood of the given predictors and responses. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @return Log-likelihood of the given sequence. */ double LogLikelihood(const arma::mat& predictors, const arma::vec& responses) const; /** * HMMR filtering. Computes the k-step-ahead expected response at each time * conditioned only on prior observations. That is * E{ Y[t+k] | Y[0], ..., Y[t] }. * The returned matrix has columns equal to the number of observations. Note * that the expectation may not be meaningful for discrete emissions. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param initial Distribution of initial state. * @param ahead Number of steps ahead (k) for expectations. * @param filterSeq Vector in which the expected emission sequence will be * stored. */ void Filter(const arma::mat& predictors, const arma::vec& responses, arma::vec& filterSeq, size_t ahead = 0) const; /** * HMM smoothing. Computes expected emission at each time conditioned on all * observations. That is * E{ Y[t] | Y[0], ..., Y[T] }. * The returned matrix has columns equal to the number of observations. Note * that the expectation may not be meaningful for discrete emissions. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences.. * @param initial Distribution of initial state. * @param smoothSeq Vector in which the expected emission sequence will be * stored. */ void Smooth(const arma::mat& predictors, const arma::vec& responses, arma::vec& smoothSeq) const; private: /** * Utility functions to facilitate the use of the HMM class for HMMR. */ void StackData(const std::vector<arma::mat>& predictors, const std::vector<arma::vec>& responses, std::vector<arma::mat>& dataSeq) const; void StackData(const arma::mat& predictors, const arma::vec& responses, arma::mat& dataSeq) const; /** * The Forward algorithm (part of the Forward-Backward algorithm). Computes * forward probabilities for each state for each observation in the given data * sequence. The returned matrix has rows equal to the number of hidden * states and columns equal to the number of observations. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param scales Vector in which scaling factors will be saved. * @param forwardProb Matrix in which forward probabilities will be saved. */ void Forward(const arma::mat& predictors, const arma::vec& responses, arma::vec& scales, arma::mat& forwardProb) const; /** * The Backward algorithm (part of the Forward-Backward algorithm). Computes * backward probabilities for each state for each observation in the given * data sequence, using the scaling factors found (presumably) by Forward(). * The returned matrix has rows equal to the number of hidden states and * columns equal to the number of observations. * * @param predictors Vector of predictor sequences. * @param responses Vector of response sequences. * @param scales Vector of scaling factors. * @param backwardProb Matrix in which backward probabilities will be saved. */ void Backward(const arma::mat& predictors, const arma::vec& responses, const arma::vec& scales, arma::mat& backwardProb) const; }; } // namespace hmm } // namespace mlpack // Include implementation. #include "hmm_regression_impl.hpp" #endif
/* * File: tac_converter.cpp * * Created on June 1, 2016, 10:19 PM */ #include "mcc/tac/tac.h" #include "mcc/cfg/cfg.h" #include "mcc/gas/gas.h" #include "mcc/gas/helper/tac_converters.h" #include "mcc/gas/helper/tac_float_converters.h" #include "mcc/gas/helper/tac_int_converters.h" #include "mcc/tac/array.h" #include "mcc/tac/array_access.h" #include "mcc/tac/helper/ast_converters.h" using namespace mcc::tac; using namespace mcc::gas; using namespace mcc::cfg; bool resultAvailable; Label::ptr_t currentFunction; OperatorName lastOperator; std::vector<std::tuple<Label::ptr_t, Array::ptr_t, mcc::gas::Operand::ptr_t>> declaredArrays; namespace mcc { namespace gas { namespace helper { void convertTac(Gas *gas, Tac &tac) { auto codeLines = tac.codeLines; for (auto tripleIt = codeLines.begin(); tripleIt != codeLines.end(); ++tripleIt) { auto triple = *tripleIt; auto op = triple->getOperator(); // check if array should be cleaned if (op.getName() != OperatorName::RET) { // return is handled separately auto nextTripleIt = std::next(tripleIt); bool isScopeEnd = (nextTripleIt == codeLines.end()); if (!isScopeEnd) { auto curScope = triple->getScope(); auto nextScope = (*nextTripleIt)->getScope(); if (*nextScope < *curScope) { isScopeEnd = true; } } if (isScopeEnd) { // clean up arrays cleanUpArrays(gas, triple); } } switch (op.getName()) { case OperatorName::NOP: /*Do nothing*/ break; case OperatorName::ADD: case OperatorName::SUB: case OperatorName::MUL: case OperatorName::DIV: convertArithmetic(gas, triple); break; case OperatorName::ASSIGN: convertAssign(gas, triple); break; case OperatorName::LABEL: convertLabel(gas, triple); break; case OperatorName::JUMP: convertJump(gas, triple); break; case OperatorName::JUMPFALSE: convertJumpFalse(gas, triple); break; case OperatorName::EQ: case OperatorName::NE: case OperatorName::LE: case OperatorName::GE: case OperatorName::LT: case OperatorName::GT: convertLogicOperator(gas, triple); break; case OperatorName::MINUS: convertMinus(gas, triple); break; case OperatorName::NOT: // TODO should be checked in previous stages assert(triple->getType() == Type::BOOL && "NOT operation only for booleans!"); convertNot(gas, triple); break; case OperatorName::PUSH: convertPush(gas, triple); break; case OperatorName::POP: /*Do nothing*/ break; case OperatorName::CALL: convertCall(gas, triple); break; case OperatorName::RET: convertReturn(gas, triple); break; } // declare arrays auto arrayDeclVec = tac.getArrayDeclVec(); for (auto arrayDecl : *arrayDeclVec) { auto declLine = arrayDecl.second; if (declLine == nullptr || triple == declLine) { // if array not already declared auto arr = arrayDecl.first; if (lookupDeclaredArray(currentFunction, arr) == declaredArrays.end()) { declareArray(gas, currentFunction, arr); } } } } for (auto arr : declaredArrays) { std::cout << std::get<1>(arr)->getValue() << std::endl; } assert(declaredArrays.empty() && "Arrays are not fully cleaned up!"); } void convertArithmetic(Gas *gas, Triple::ptr_t triple) { switch (triple->getType()) { case Type::INT: convertIntArithmetic(gas, triple); break; case Type::FLOAT: convertFloatArithmetic(gas, triple); break; default: assert(false && "Unhandled operator type in arithmetic conversion"); } } void convertAssign(Gas *gas, Triple::ptr_t triple) { if (triple->containsArg2()) { auto arg2 = triple->getArg2(); switch (arg2->getType()) { case Type::INT: convertIntAssign(gas, triple); break; case Type::FLOAT: convertFloatAssign(gas, triple); break; default: assert("Unhandled type of arg2 in assign op!"); } } else { assert(false && "Assignment does not contain arg2!"); } } void convertLabel(Gas *gas, Triple::ptr_t triple) { auto labelTriple = std::static_pointer_cast<Label>(triple); auto label = std::make_shared<Mnemonic>(labelTriple->getName()); gas->addMnemonic(label); // Add function entry if (labelTriple->isFunctionEntry()) { currentFunction = labelTriple; createFunctionProlog(gas, labelTriple); } } void convertJump(Gas *gas, Triple::ptr_t triple) { if (triple->containsArg1()) { auto operand = triple->getArg1(); if (tac::helper::isType<Label>(operand)) { auto label = std::static_pointer_cast<Label>(operand); auto asmLabel = std::make_shared<Operand>(label->getName()); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::JMP, asmLabel)); } } } void convertJumpFalse(Gas *gas, Triple::ptr_t triple) { auto condition = std::static_pointer_cast<Triple>(triple->getArg1()); switch (condition->getArg1()->getType()) { case Type::INT: convertIntJumpFalse(gas, triple); break; case Type::FLOAT: convertFloatJumpFalse(gas, triple); break; default: std::cout << triple->getType() << std::endl; assert(false && "Unhandled operator type in logic conversion"); } } void convertLogicOperator(Gas *gas, Triple::ptr_t triple) { auto operatorName = triple->getOperator().getName(); // use type of an argument because switch (triple->getArg1()->getType()) { case Type::INT: convertIntLogicOperator(gas, triple); break; case Type::FLOAT: convertFloatLogicOperator(gas, triple); break; default: std::cout << triple->getType() << std::endl; assert(false && "Unhandled operator type in logic conversion"); } lastOperator = operatorName; } void convertMinus(Gas *gas, Triple::ptr_t triple) { // TODO distinguish float and int switch (triple->getType()) { case Type::INT: convertUnary(gas, triple, Instruction::NEG); break; case Type::FLOAT: convertFloatMinus(gas, triple); break; default: assert(false && "Unhandled type in convertMinus!"); } } void convertNot(Gas *gas, Triple::ptr_t triple) { convertUnary(gas, triple, Instruction::NOT); } void convertPush(Gas *gas, Triple::ptr_t triple) { convertUnary(gas, triple, Instruction::PUSH); } void convertUnary(Gas *gas, Triple::ptr_t triple, Instruction i) { bool containsTargetVar = triple->containsTargetVar(); Operand::ptr_t tmp; if (containsTargetVar) { tmp = gas->getRegisterManager()->getTmpRegister(); } auto operand = gas->loadOperand(currentFunction, triple->getArg1(), tmp); gas->addMnemonic(std::make_shared<Mnemonic>(i, operand)); if (containsTargetVar) { auto var = triple->getTargetVariable(); gas->storeOperandFromRegister(currentFunction, var, operand); } } void convertCall(Gas *gas, Triple::ptr_t triple) { if (triple->containsArg1()) { auto operand = triple->getArg1(); if (tac::helper::isType<Label>(operand)) { auto label = std::static_pointer_cast<Label>(operand); auto asmLabel = std::make_shared<Operand>(label->getName()); prepareCall(gas, label); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::CALL, asmLabel)); // Assign result to variable if (triple->containsTargetVar()) { auto destVar = triple->getTargetVariable(); // TODO check if correct if (destVar->getType() != Type::NONE) { resultAvailable = true; auto result = std::make_shared<Operand>(Register::EAX); gas->storeOperandFromRegister(currentFunction, destVar, result); } } cleanUpCall(gas, label); } } } void convertReturn(Gas *gas, Triple::ptr_t triple) { if (triple->containsArg1()) { // TODO godbolt produces different gas code for float, but it seems to work // with the int implementation auto reg = gas->loadOperand(currentFunction, triple->getArg1()); auto eax = std::make_shared<Operand>(Register::EAX); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::MOV, eax, reg)); } cleanUpArrays(gas, triple); createFunctionEpilog(gas, currentFunction); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::RET)); } void prepareCall(Gas *gas, Label::ptr_t functionLabel) { // TODO find better solution unsigned argSize = gas->getRegisterManager()->lookupFunctionArgSize(functionLabel); unsigned pos = gas->getAsmInstructions().size() - argSize / 4; gas->storeRegisters({Register::ECX, Register::EDX}, pos); resultAvailable = false; } void cleanUpCall(Gas *gas, Label::ptr_t functionLabel) { // Cleanup stack unsigned argSize = gas->getRegisterManager()->lookupFunctionArgSize(functionLabel); std::vector<Mnemonic::ptr_t>::iterator it = gas->getAsmInstructions().end(); int lineOffset = 0; if (resultAvailable) --lineOffset; resultAvailable = false; if (argSize > 0) { auto esp = std::make_shared<Operand>(Register::ESP); auto stackspaceOp = std::make_shared<Operand>(std::to_string(argSize)); gas->getAsmInstructions().insert( it + lineOffset, std::make_shared<Mnemonic>(Instruction::ADD, esp, stackspaceOp)); } // Restore registers gas->restoreRegisters({Register::EDX, Register::ECX}, gas->getAsmInstructions().size() + lineOffset); } void createFunctionProlog(Gas *gas, Label::ptr_t functionLabel) { auto ebp = std::make_shared<Operand>(Register::EBP); auto esp = std::make_shared<Operand>(Register::ESP); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::PUSH, ebp)); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::MOV, ebp, esp)); unsigned stackSpace = gas->getRegisterManager()->lookupFunctionStackSpace(functionLabel); // Do we need space for temporaries on the stack? if (stackSpace > 0) { auto stackspaceOp = std::make_shared<Operand>(std::to_string(stackSpace)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::SUB, esp, stackspaceOp)); } // Store callee saved registers gas->storeRegisters({Register::EBX, Register::EDI, Register::ESI}); // load function arguments for (auto var : gas->getRegisterManager()->lookupFunctionVariables(functionLabel)) { auto targetReg = gas->getRegisterManager()->getLocationForVariable(functionLabel, var); auto varOffset = gas->getRegisterManager()->lookupVariableStackOffset( functionLabel, var); auto argAddrOp = std::make_shared<Operand>(varOffset); if (targetReg->toString() != argAddrOp->toString()) { gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::MOV, targetReg, argAddrOp)); } } } void createFunctionEpilog(Gas *gas, Label::ptr_t functionLabel) { unsigned stackSpace = gas->getRegisterManager()->lookupFunctionStackSpace(functionLabel); auto esp = std::make_shared<Operand>(Register::ESP); auto ebp = std::make_shared<Operand>(Register::EBP); gas->restoreRegisters({Register::ESI, Register::EDI, Register::EBX}); // Cleanup stack if (stackSpace > 0) { auto stackspaceOp = std::make_shared<Operand>(std::to_string(stackSpace)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::ADD, esp, stackspaceOp)); } gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::MOV, esp, ebp)); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::POP, ebp)); } std::vector< std::tuple<Label::ptr_t, Array::ptr_t, mcc::gas::Operand::ptr_t>>::iterator lookupDeclaredArray(Label::ptr_t functionLabel, Array::ptr_t array) { auto searchPair = std::make_pair(functionLabel, array); for (auto pairIt = declaredArrays.begin(); pairIt != declaredArrays.end(); ++pairIt) { auto curPair = std::make_pair(std::get<0>(*pairIt), std::get<1>(*pairIt)); if (!mcc::gas::labelArrayPairLess()(searchPair, curPair) && !mcc::gas::labelArrayPairLess()(curPair, searchPair)) { return pairIt; } } return declaredArrays.end(); } void declareArray(Gas *gas, Label::ptr_t functionLabel, Array::ptr_t arr) { auto esp = std::make_shared<Operand>(Register::ESP); auto tmp = gas->getRegisterManager()->getTmpRegister(); // store start address auto arrOp = gas->loadOperand(functionLabel, arr); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::MOV, arrOp, esp)); // make space on stack for new array auto arrLength = arr->length(); auto arrLengthOp = gas->loadOperand(currentFunction, arr->length()); auto arrTypeSize = gas->getRegisterManager()->getSize(arr->getType()); auto arrTypeSizeOp = std::make_shared<Operand>(std::to_string(arrTypeSize)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::MOV, tmp, arrLengthOp)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::IMUL, tmp, arrTypeSizeOp)); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::SUB, esp, tmp)); // store as defined declaredArrays.push_back(std::make_tuple(functionLabel, arr, arrLengthOp)); } void cleanUpArrays(Gas *gas, Triple::ptr_t triple) { // clean up arrays auto tripleScope = triple->getScope(); for (auto definedArrIt = declaredArrays.rbegin(); definedArrIt != declaredArrays.rend(); ++definedArrIt) { auto definedArrFunc = std::get<0>(*definedArrIt); auto definedArr = std::get<1>(*definedArrIt); auto definedArrLength = std::get<2>(*definedArrIt); auto arrScope = definedArr->getScope(); if (*tripleScope <= *arrScope) { // clean auto esp = std::make_shared<Operand>(Register::ESP); auto tmp = gas->getRegisterManager()->getTmpRegister(); // if return and tmp is EAX, get new temp to not overwrite EAX if (triple->getOperator().getName() == OperatorName::RET && tmp->getRegister() == Register::EAX) { tmp = gas->getRegisterManager()->getTmpRegister(); } auto arrTypeSize = gas->getRegisterManager()->getSize(definedArr->getType()); auto arrTypeSizeOp = std::make_shared<Operand>(std::to_string(arrTypeSize)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::MOV, tmp, definedArrLength)); gas->addMnemonic( std::make_shared<Mnemonic>(Instruction::IMUL, tmp, arrTypeSizeOp)); gas->addMnemonic(std::make_shared<Mnemonic>(Instruction::ADD, esp, tmp)); // delete current array from declaredArrays vector declaredArrays.erase(std::next(definedArrIt).base()); } } } } } }
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision_transformations/fake_quantize_and_max_pool_transformation.hpp" #include <memory> #include <tuple> #include <vector> #include <string> //#include <ie_core.hpp> #include <transformations/init_node_info.hpp> #include "lpt_ngraph_functions/common/fake_quantize_on_data.hpp" #include "lpt_ngraph_functions/max_pool_function.hpp" namespace LayerTestsDefinitions { std::string FakeQuantizeAndMaxPoolTransformation::getTestCaseName(testing::TestParamInfo<FakeQuantizeAndMaxPoolTransformationParams> obj) { ngraph::element::Type precision; ngraph::PartialShape inputShapes; std::string targetDevice; ngraph::pass::low_precision::LayerTransformation::Params params; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize; std::tie(precision, inputShapes, targetDevice, params, fakeQuantize) = obj.param; return getTestCaseNameByParams(precision, inputShapes, targetDevice, params); } void FakeQuantizeAndMaxPoolTransformation::SetUp() { ngraph::element::Type precision; ngraph::PartialShape inputShape; ngraph::pass::low_precision::LayerTransformation::Params params; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize; std::tie(precision, inputShape, targetDevice, params, fakeQuantize) = this->GetParam(); function = ngraph::builder::subgraph::MaxPoolFunction::getOriginal( precision, inputShape, fakeQuantize); ngraph::pass::InitNodeInfo().run_on_function(function); validate(); } void FakeQuantizeAndMaxPoolTransformation::validate() { ngraph::element::Type precision; ngraph::PartialShape inputShapes; std::string targetDevice; ngraph::pass::low_precision::LayerTransformation::Params params; ngraph::builder::subgraph::FakeQuantizeOnData fakeQuantize; std::tie(precision, inputShapes, targetDevice, params, fakeQuantize) = this->GetParam(); const auto transformed = transformNGraph(params, getLowPrecisionTransformationsNGraph(params)); EXPECT_EQ(1ul, transformed->get_output_size()); const auto output = transformed->get_output_op(0); const auto scaleShift = output->get_input_node_shared_ptr(0); ASSERT_FALSE(scaleShift == nullptr); const std::string typeName = scaleShift->get_type_name(); ASSERT_EQ("ScaleShiftIE", typeName); } TEST_P(FakeQuantizeAndMaxPoolTransformation, CompareWithRefImpl) { Run(); }; } // namespace LayerTestsDefinitions
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "paddle/fluid/memory/allocation/auto_growth_best_fit_allocator.h" #include <algorithm> #include <list> #include <map> #include <memory> #include <mutex> // NOLINT #include <unordered_map> #include "paddle/fluid/memory/allocation/aligned_allocator.h" DEFINE_bool(free_idle_chunk, false, "Whether to free idle chunk when each allocation is freed. " "If false, all freed allocation would be cached to speed up next " "allocation request. If true, no allocation would be cached. This " "flag only works when FLAGS_allocator_strategy=auto_growth."); DEFINE_bool(free_when_no_cache_hit, true, "Whether to free idle chunks when no cache hit. If true, idle " "chunk would be freed when no cache hit; if false, idle " "chunk would be freed when out of memory occurs. This flag " "only works when FLAGS_allocator_strategy=auto_growth."); namespace paddle { namespace memory { namespace allocation { AutoGrowthBestFitAllocator::AutoGrowthBestFitAllocator( const std::shared_ptr<Allocator> &underlying_allocator, size_t alignment, size_t chunk_size) : underlying_allocator_( std::make_shared<AlignedAllocator>(underlying_allocator, alignment)), alignment_(alignment), chunk_size_(std::max(AlignedSize(chunk_size, alignment), alignment)) {} Allocation *AutoGrowthBestFitAllocator::AllocateImpl(size_t size) { size = AlignedSize(size, alignment_); std::lock_guard<std::mutex> guard(mtx_); auto iter = free_blocks_.lower_bound(std::make_pair(size, nullptr)); BlockIt block_it; if (iter != free_blocks_.end()) { block_it = iter->second; free_blocks_.erase(iter); auto *chunk = block_it->chunk_; size_t remaining_size = block_it->size_ - size; if (remaining_size == 0) { block_it->is_free_ = false; } else { auto remaining_free_block = chunk->blocks_.insert( block_it, Block(block_it->ptr_, remaining_size, true, chunk)); free_blocks_.emplace(std::make_pair(remaining_size, block_it->ptr_), remaining_free_block); block_it->ptr_ = reinterpret_cast<uint8_t *>(block_it->ptr_) + remaining_size; block_it->size_ = size; block_it->is_free_ = false; } } else { if (FLAGS_free_when_no_cache_hit) { FreeIdleChunks(); } size_t realloc_size = std::max(size, chunk_size_); try { chunks_.emplace_back(underlying_allocator_->Allocate(realloc_size)); } catch (BadAlloc &ex) { if (FLAGS_free_when_no_cache_hit) throw ex; FreeIdleChunks(); chunks_.emplace_back(underlying_allocator_->Allocate(realloc_size)); } auto *chunk = &(*chunks_.rbegin()); realloc_size = chunk->allocation_->size(); uint8_t *p = reinterpret_cast<uint8_t *>(chunk->allocation_->ptr()); auto &blocks = chunk->blocks_; size_t remaining_size = realloc_size - size; if (remaining_size > 0) { blocks.emplace_back(p, remaining_size, true, chunk); free_blocks_.emplace(std::make_pair(remaining_size, p), --(blocks.end())); } blocks.emplace_back(p + remaining_size, size, false, chunk); block_it = --(blocks.end()); VLOG(2) << "Not found and reallocate " << realloc_size << ", and remaining " << remaining_size; } return new BlockAllocation(block_it); } void AutoGrowthBestFitAllocator::FreeImpl(Allocation *allocation) { std::lock_guard<std::mutex> guard(mtx_); auto block_it = static_cast<BlockAllocation *>(allocation)->block_it_; auto &blocks = block_it->chunk_->blocks_; block_it->is_free_ = true; if (block_it != blocks.begin()) { auto prev_it = block_it; --prev_it; if (prev_it->is_free_) { free_blocks_.erase(std::make_pair(prev_it->size_, prev_it->ptr_)); prev_it->size_ += block_it->size_; blocks.erase(block_it); block_it = prev_it; } } auto next_it = block_it; ++next_it; if (next_it != blocks.end() && next_it->is_free_) { free_blocks_.erase(std::make_pair(next_it->size_, next_it->ptr_)); block_it->size_ += next_it->size_; blocks.erase(next_it); } free_blocks_.emplace(std::make_pair(block_it->size_, block_it->ptr_), block_it); delete allocation; if (FLAGS_free_idle_chunk) { FreeIdleChunks(); } } void AutoGrowthBestFitAllocator::FreeIdleChunks() { for (auto chunk_it = chunks_.begin(); chunk_it != chunks_.end();) { auto &blocks = chunk_it->blocks_; if (blocks.size() == 1 && blocks.begin()->is_free_) { auto &block = *blocks.begin(); VLOG(2) << "Free chunk with size " << block.size_; free_blocks_.erase(std::make_pair(block.size_, block.ptr_)); chunk_it = chunks_.erase(chunk_it); } else { ++chunk_it; } } } } // namespace allocation } // namespace memory } // namespace paddle
// Copyright (c) 2011-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The ZCore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/zcore-config.h" #endif #include "optionsmodel.h" #include "bitcoinunits.h" #include "guiutil.h" #include "amount.h" #include "init.h" #include "main.h" // For DEFAULT_SCRIPTCHECK_THREADS #include "net.h" #include "txdb.h" // for -dbcache defaults #ifdef ENABLE_WALLET #include "wallet/wallet.h" #include "wallet/walletdb.h" #endif #include "darksend.h" #ifdef ENABLE_WALLET #include "masternodeconfig.h" #endif #include <QNetworkProxy> #include <QSettings> #include <QStringList> OptionsModel::OptionsModel(QObject *parent, bool resetSettings) : QAbstractListModel(parent) { Init(resetSettings); } void OptionsModel::addOverriddenOption(const std::string &option) { strOverriddenByCommandLine += QString::fromStdString(option) + "=" + QString::fromStdString(mapArgs[option]) + " "; } // Writes all missing QSettings with their default values void OptionsModel::Init(bool resetSettings) { if (resetSettings) Reset(); this->resetSettings = resetSettings; QSettings settings; // Ensure restart flag is unset on client startup setRestartRequired(false); // These are Qt-only settings: // Window if (!settings.contains("fMinimizeToTray")) settings.setValue("fMinimizeToTray", false); fMinimizeToTray = settings.value("fMinimizeToTray").toBool(); if (!settings.contains("fMinimizeOnClose")) settings.setValue("fMinimizeOnClose", false); fMinimizeOnClose = settings.value("fMinimizeOnClose").toBool(); // Display if (!settings.contains("nDisplayUnit")) settings.setValue("nDisplayUnit", BitcoinUnits::ZCR); nDisplayUnit = settings.value("nDisplayUnit").toInt(); if (!settings.contains("strThirdPartyTxUrls")) settings.setValue("strThirdPartyTxUrls", ""); strThirdPartyTxUrls = settings.value("strThirdPartyTxUrls", "").toString(); if (!settings.contains("fCoinControlFeatures")) settings.setValue("fCoinControlFeatures", false); fCoinControlFeatures = settings.value("fCoinControlFeatures", false).toBool(); if (!settings.contains("digits")) settings.setValue("digits", "2"); if (!settings.contains("theme")) settings.setValue("theme", ""); if (!settings.contains("fShowMasternodesTab")) settings.setValue("fShowMasternodesTab", masternodeConfig.getCount()); if (!settings.contains("fShowAdvancedPSUI")) settings.setValue("fShowAdvancedPSUI", false); fShowAdvancedPSUI = settings.value("fShowAdvancedPSUI", false).toBool(); if (!settings.contains("fLowKeysWarning")) settings.setValue("fLowKeysWarning", true); // These are shared with the core or have a command-line parameter // and we want command-line parameters to overwrite the GUI settings. // // If setting doesn't exist create it with defaults. // // If SoftSetArg() or SoftSetBoolArg() return false we were overridden // by command-line and show this in the UI. // Main if (!settings.contains("nDatabaseCache")) settings.setValue("nDatabaseCache", (qint64)nDefaultDbCache); if (!SoftSetArg("-dbcache", settings.value("nDatabaseCache").toString().toStdString())) addOverriddenOption("-dbcache"); if (!settings.contains("nThreadsScriptVerif")) settings.setValue("nThreadsScriptVerif", DEFAULT_SCRIPTCHECK_THREADS); if (!SoftSetArg("-par", settings.value("nThreadsScriptVerif").toString().toStdString())) addOverriddenOption("-par"); // Wallet #ifdef ENABLE_WALLET if (!settings.contains("bSpendZeroConfChange")) settings.setValue("bSpendZeroConfChange", true); if (!SoftSetBoolArg("-spendzeroconfchange", settings.value("bSpendZeroConfChange").toBool())) addOverriddenOption("-spendzeroconfchange"); // PrivateSend if (!settings.contains("nPrivateSendRounds")) settings.setValue("nPrivateSendRounds", DEFAULT_PRIVATESEND_ROUNDS); if (!SoftSetArg("-privatesendrounds", settings.value("nPrivateSendRounds").toString().toStdString())) addOverriddenOption("-privatesendrounds"); nPrivateSendRounds = settings.value("nPrivateSendRounds").toInt(); if (!settings.contains("nPrivateSendAmount")) { // for migration from old settings if (!settings.contains("nAnonymizeZCoreAmount")) settings.setValue("nPrivateSendAmount", DEFAULT_PRIVATESEND_AMOUNT); else settings.setValue("nPrivateSendAmount", settings.value("nAnonymizeZCoreAmount").toInt()); } if (!SoftSetArg("-privatesendamount", settings.value("nPrivateSendAmount").toString().toStdString())) addOverriddenOption("-privatesendamount"); nPrivateSendAmount = settings.value("nPrivateSendAmount").toInt(); if (!settings.contains("fPrivateSendMultiSession")) settings.setValue("fPrivateSendMultiSession", DEFAULT_PRIVATESEND_MULTISESSION); if (!SoftSetBoolArg("-privatesendmultisession", settings.value("fPrivateSendMultiSession").toBool())) addOverriddenOption("-privatesendmultisession"); fPrivateSendMultiSession = settings.value("fPrivateSendMultiSession").toBool(); #endif // Network if (!settings.contains("fUseUPnP")) settings.setValue("fUseUPnP", DEFAULT_UPNP); if (!SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool())) addOverriddenOption("-upnp"); if (!settings.contains("fListen")) settings.setValue("fListen", DEFAULT_LISTEN); if (!SoftSetBoolArg("-listen", settings.value("fListen").toBool())) addOverriddenOption("-listen"); if (!settings.contains("fUseProxy")) settings.setValue("fUseProxy", false); if (!settings.contains("addrProxy")) settings.setValue("addrProxy", "127.0.0.1:9050"); // Only try to set -proxy, if user has enabled fUseProxy if (settings.value("fUseProxy").toBool() && !SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString())) addOverriddenOption("-proxy"); else if(!settings.value("fUseProxy").toBool() && !GetArg("-proxy", "").empty()) addOverriddenOption("-proxy"); if (!settings.contains("fUseSeparateProxyTor")) settings.setValue("fUseSeparateProxyTor", false); if (!settings.contains("addrSeparateProxyTor")) settings.setValue("addrSeparateProxyTor", "127.0.0.1:9050"); // Only try to set -onion, if user has enabled fUseSeparateProxyTor if (settings.value("fUseSeparateProxyTor").toBool() && !SoftSetArg("-onion", settings.value("addrSeparateProxyTor").toString().toStdString())) addOverriddenOption("-onion"); else if(!settings.value("fUseSeparateProxyTor").toBool() && !GetArg("-onion", "").empty()) addOverriddenOption("-onion"); // Display if (!settings.contains("language")) settings.setValue("language", ""); if (!SoftSetArg("-lang", settings.value("language").toString().toStdString())) addOverriddenOption("-lang"); language = settings.value("language").toString(); } void OptionsModel::Reset() { QSettings settings; // Remove all entries from our QSettings object settings.clear(); resetSettings = true; // Needed in zcore.cpp during shotdown to also remove the window positions // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } // read QSettings values and return them QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return GUIUtil::GetStartOnSystemStartup(); case MinimizeToTray: return fMinimizeToTray; case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP"); #else return false; #endif case MinimizeOnClose: return fMinimizeOnClose; // default proxy case ProxyUse: return settings.value("fUseProxy", false); case ProxyIP: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(0); } case ProxyPort: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(1); } // separate Tor proxy case ProxyUseTor: return settings.value("fUseSeparateProxyTor", false); case ProxyIPTor: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(0); } case ProxyPortTor: { // contains IP at index 0 and port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); return strlIpPort.at(1); } #ifdef ENABLE_WALLET case SpendZeroConfChange: return settings.value("bSpendZeroConfChange"); case ShowMasternodesTab: return settings.value("fShowMasternodesTab"); case ShowAdvancedPSUI: return fShowAdvancedPSUI; case LowKeysWarning: return settings.value("fLowKeysWarning"); case PrivateSendRounds: return settings.value("nPrivateSendRounds"); case PrivateSendAmount: return settings.value("nPrivateSendAmount"); case PrivateSendMultiSession: return settings.value("fPrivateSendMultiSession"); #endif case DisplayUnit: return nDisplayUnit; case ThirdPartyTxUrls: return strThirdPartyTxUrls; case Digits: return settings.value("digits"); case Theme: return settings.value("theme"); case Language: return settings.value("language"); case CoinControlFeatures: return fCoinControlFeatures; case DatabaseCache: return settings.value("nDatabaseCache"); case ThreadsScriptVerif: return settings.value("nThreadsScriptVerif"); case Listen: return settings.value("fListen"); default: return QVariant(); } } return QVariant(); } // write QSettings values bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: // core option - can be changed on-the-fly settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; // default proxy case ProxyUse: if (settings.value("fUseProxy") != value) { settings.setValue("fUseProxy", value.toBool()); setRestartRequired(true); } break; case ProxyIP: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrProxy") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; case ProxyPort: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrProxy").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrProxy") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrProxy", strNewValue); setRestartRequired(true); } } break; // separate Tor proxy case ProxyUseTor: if (settings.value("fUseSeparateProxyTor") != value) { settings.setValue("fUseSeparateProxyTor", value.toBool()); setRestartRequired(true); } break; case ProxyIPTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed IP if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(0) != value.toString()) { // construct new value from new IP and current port QString strNewValue = value.toString() + ":" + strlIpPort.at(1); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; case ProxyPortTor: { // contains current IP at index 0 and current port at index 1 QStringList strlIpPort = settings.value("addrSeparateProxyTor").toString().split(":", QString::SkipEmptyParts); // if that key doesn't exist or has a changed port if (!settings.contains("addrSeparateProxyTor") || strlIpPort.at(1) != value.toString()) { // construct new value from current IP and new port QString strNewValue = strlIpPort.at(0) + ":" + value.toString(); settings.setValue("addrSeparateProxyTor", strNewValue); setRestartRequired(true); } } break; #ifdef ENABLE_WALLET case SpendZeroConfChange: if (settings.value("bSpendZeroConfChange") != value) { settings.setValue("bSpendZeroConfChange", value); setRestartRequired(true); } break; case ShowMasternodesTab: if (settings.value("fShowMasternodesTab") != value) { settings.setValue("fShowMasternodesTab", value); setRestartRequired(true); } break; case ShowAdvancedPSUI: fShowAdvancedPSUI = value.toBool(); settings.setValue("fShowAdvancedPSUI", fShowAdvancedPSUI); Q_EMIT advancedPSUIChanged(fShowAdvancedPSUI); break; case LowKeysWarning: settings.setValue("fLowKeysWarning", value); break; case PrivateSendRounds: if (settings.value("nPrivateSendRounds") != value) { nPrivateSendRounds = value.toInt(); settings.setValue("nPrivateSendRounds", nPrivateSendRounds); Q_EMIT privateSendRoundsChanged(); } break; case PrivateSendAmount: if (settings.value("nPrivateSendAmount") != value) { nPrivateSendAmount = value.toInt(); settings.setValue("nPrivateSendAmount", nPrivateSendAmount); Q_EMIT privateSentAmountChanged(); } break; case PrivateSendMultiSession: if (settings.value("fPrivateSendMultiSession") != value) { fPrivateSendMultiSession = value.toBool(); settings.setValue("fPrivateSendMultiSession", fPrivateSendMultiSession); } break; #endif case DisplayUnit: setDisplayUnit(value); break; case ThirdPartyTxUrls: if (strThirdPartyTxUrls != value.toString()) { strThirdPartyTxUrls = value.toString(); settings.setValue("strThirdPartyTxUrls", strThirdPartyTxUrls); setRestartRequired(true); } break; case Digits: if (settings.value("digits") != value) { settings.setValue("digits", value); setRestartRequired(true); } break; case Theme: if (settings.value("theme") != value) { settings.setValue("theme", value); setRestartRequired(true); } break; case Language: if (settings.value("language") != value) { settings.setValue("language", value); setRestartRequired(true); } break; case CoinControlFeatures: fCoinControlFeatures = value.toBool(); settings.setValue("fCoinControlFeatures", fCoinControlFeatures); Q_EMIT coinControlFeaturesChanged(fCoinControlFeatures); break; case DatabaseCache: if (settings.value("nDatabaseCache") != value) { settings.setValue("nDatabaseCache", value); setRestartRequired(true); } break; case ThreadsScriptVerif: if (settings.value("nThreadsScriptVerif") != value) { settings.setValue("nThreadsScriptVerif", value); setRestartRequired(true); } break; case Listen: if (settings.value("fListen") != value) { settings.setValue("fListen", value); setRestartRequired(true); } break; default: break; } } Q_EMIT dataChanged(index, index); return successful; } /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void OptionsModel::setDisplayUnit(const QVariant &value) { if (!value.isNull()) { QSettings settings; nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); Q_EMIT displayUnitChanged(nDisplayUnit); } } bool OptionsModel::getProxySettings(QNetworkProxy& proxy) const { // Directly query current base proxy, because // GUI settings can be overridden with -proxy. proxyType curProxy; if (GetProxy(NET_IPV4, curProxy)) { proxy.setType(QNetworkProxy::Socks5Proxy); proxy.setHostName(QString::fromStdString(curProxy.proxy.ToStringIP())); proxy.setPort(curProxy.proxy.GetPort()); return true; } else proxy.setType(QNetworkProxy::NoProxy); return false; } void OptionsModel::setRestartRequired(bool fRequired) { QSettings settings; return settings.setValue("fRestartRequired", fRequired); } bool OptionsModel::isRestartRequired() { QSettings settings; return settings.value("fRestartRequired", false).toBool(); }
#include "Vulkan/VkIndirectDrawablePool.h" namespace Azura { namespace Vulkan { } // namespace Vulkan } // namespace Azura
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2010, 2011, 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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. // // Author: sameeragarwal@google.com (Sameer Agarwal) // // Template specialization of SchurEliminator. // // ======================================== // THIS FILE IS AUTOGENERATED. DO NOT EDIT. // THIS FILE IS AUTOGENERATED. DO NOT EDIT. // THIS FILE IS AUTOGENERATED. DO NOT EDIT. // THIS FILE IS AUTOGENERATED. DO NOT EDIT. //========================================= // // This file is generated using generate_eliminator_specializations.py. // Editing it manually is not recommended. #include "ceres/schur_eliminator_impl.h" #include "ceres/internal/eigen.h" namespace ceres { namespace internal { template class SchurEliminator<4, 4, 2>; } // namespace internal } // namespace ceres
// RobotBuilder Version: 1.5 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "AutonOneTote.h" #include "LiftXTicks.h" #include "../Subsystems/Lift.h" #include "DriveXFeet.h" #include "ParallelArmsOut.h" #include "ParallelArmsIn.h" #include "DelayCommand.h" AutonOneTote::AutonOneTote() { // Add Commands here: // e.g. AddSequential(new Command1()); // AddSequential(new Command2()); // these will run in order. // To run multiple commands at the same time, // use AddParallel() // e.g. AddParallel(new Command1()); // AddSequential(new Command2()); // Command1 and Command2 will run in parallel. // A command group will require all of the subsystems that each member // would require. // e.g. if Command1 requires chassis, and Command2 requires arm, // a CommandGroup containing them would require both the chassis and the // arm. // grabbing one tote and moving it to auto zone and move away AddSequential (new ParallelArmsIn()); AddSequential (new DelayCommand(1)); AddSequential(new LiftXTicks(Lift:: TOTE_TWO_ENGAGE_TICKS,Lift::SPEED_UP)); AddSequential (new DriveXFeet(-10, .3)); AddSequential(new LiftXTicks(Lift:: TOTE_ONE_ENGAGE_TICKS,Lift::SPEED_DOWN)); AddSequential (new ParallelArmsOut()); // may want to add this to all command groups so it is ovbious we are not touching totes; AddSequential (new DriveXFeet(-.5, .3)); // to clear away from bin AddSequential (new LiftXTicks(Lift::TOTE_TWO_ENGAGE_TICKS, Lift::SPEED_UP)); }
/* // Definition for a Node. class Node { public: int val; vector<Node*> children; Node() {} Node(int _val) { val = _val; } Node(int _val, vector<Node*> _children) { val = _val; children = _children; } }; */ class Solution { public: void postorder(Node* root,vector<int>&v){ if(root==NULL){ return; } vector<Node*> child=root->children; for(int i=0;i<child.size();i++){ postorder(child[i],v); } v.push_back(root->val); } vector<int> postorder(Node* root) { vector<int>v; postorder(root,v); return v; } };
#include "blockexplorer.h" #include "bitcoinunits.h" #include "chainparams.h" #include "clientmodel.h" #include "core_io.h" #include "main.h" #include "net.h" #include "txdb.h" #include "ui_blockexplorer.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include <QDateTime> #include <QKeyEvent> #include <QMessageBox> #include <set> extern double GetDifficulty(const CBlockIndex* blockindex = NULL); inline std::string utostr(unsigned int n) { return strprintf("%u", n); } static std::string makeHRef(const std::string& Str) { return "<a href=\"" + Str + "\">" + Str + "</a>"; } static int64_t getTxIn(const CTransaction& tx) { if (tx.IsCoinBase()) return 0; int64_t Sum = 0; for (unsigned int i = 0; i < tx.vin.size(); i++) Sum += getPrevOut(tx.vin[i].prevout).nValue; return Sum; } static std::string ValueToString(int64_t nValue, bool AllowNegative = false) { if (nValue < 0 && !AllowNegative) return "<span>" + _("unknown") + "</span>"; QString Str = BitcoinUnits::formatWithUnit(BitcoinUnits::TME, nValue); if (AllowNegative && nValue > 0) Str = '+' + Str; return std::string("<span>") + Str.toUtf8().data() + "</span>"; } static std::string ScriptToString(const CScript& Script, bool Long = false, bool Highlight = false) { if (Script.empty()) return "unknown"; CTxDestination Dest; CBitcoinAddress Address; if (ExtractDestination(Script, Dest) && Address.Set(Dest)) { if (Highlight) return "<span class=\"addr\">" + Address.ToString() + "</span>"; else return makeHRef(Address.ToString()); } else return Long ? "<pre>" + FormatScript(Script) + "</pre>" : _("Non-standard script"); } static std::string TimeToString(uint64_t Time) { QDateTime timestamp; timestamp.setTime_t(Time); return timestamp.toString("yyyy-MM-dd hh:mm:ss").toUtf8().data(); } static std::string makeHTMLTableRow(const std::string* pCells, int n) { std::string Result = "<tr>"; for (int i = 0; i < n; i++) { Result += "<td class=\"d" + utostr(i) + "\">"; Result += pCells[i]; Result += "</td>"; } Result += "</tr>"; return Result; } static const char* table = "<table>"; static std::string makeHTMLTable(const std::string* pCells, int nRows, int nColumns) { std::string Table = table; for (int i = 0; i < nRows; i++) Table += makeHTMLTableRow(pCells + i * nColumns, nColumns); Table += "</table>"; return Table; } static std::string TxToRow(const CTransaction& tx, const CScript& Highlight = CScript(), const std::string& Prepend = std::string(), int64_t* pSum = NULL) { std::string InAmounts, InAddresses, OutAmounts, OutAddresses; int64_t Delta = 0; for (unsigned int j = 0; j < tx.vin.size(); j++) { if (tx.IsCoinBase()) { InAmounts += ValueToString(tx.GetValueOut()); InAddresses += "coinbase"; } else { CTxOut PrevOut = getPrevOut(tx.vin[j].prevout); InAmounts += ValueToString(PrevOut.nValue); InAddresses += ScriptToString(PrevOut.scriptPubKey, false, PrevOut.scriptPubKey == Highlight).c_str(); if (PrevOut.scriptPubKey == Highlight) Delta -= PrevOut.nValue; } if (j + 1 != tx.vin.size()) { InAmounts += "<br/>"; InAddresses += "<br/>"; } } for (unsigned int j = 0; j < tx.vout.size(); j++) { CTxOut Out = tx.vout[j]; OutAmounts += ValueToString(Out.nValue); OutAddresses += ScriptToString(Out.scriptPubKey, false, Out.scriptPubKey == Highlight); if (Out.scriptPubKey == Highlight) Delta += Out.nValue; if (j + 1 != tx.vout.size()) { OutAmounts += "<br/>"; OutAddresses += "<br/>"; } } std::string List[8] = { Prepend, makeHRef(tx.GetHash().GetHex()), InAddresses, InAmounts, OutAddresses, OutAmounts, "", ""}; int n = sizeof(List) / sizeof(std::string) - 2; if (!Highlight.empty()) { List[n++] = std::string("<font color=\"") + ((Delta > 0) ? "green" : "red") + "\">" + ValueToString(Delta, true) + "</font>"; *pSum += Delta; List[n++] = ValueToString(*pSum); return makeHTMLTableRow(List, n); } return makeHTMLTableRow(List + 1, n - 1); } CTxOut getPrevOut(const COutPoint& out) { CTransaction tx; uint256 hashBlock; if (GetTransaction(out.hash, tx, hashBlock, true)) return tx.vout[out.n]; return CTxOut(); } void getNextIn(const COutPoint& Out, uint256& Hash, unsigned int& n) { // Hash = 0; // n = 0; // if (paddressmap) // paddressmap->ReadNextIn(Out, Hash, n); } const CBlockIndex* getexplorerBlockIndex(int64_t height) { std::string hex = getexplorerBlockHash(height); uint256 hash = uint256S(hex); return mapBlockIndex[hash]; } std::string getexplorerBlockHash(int64_t Height) { std::string genesisblockhash = "0000041e482b9b9691d98eefb48473405c0b8ec31b76df3797c74a78680ef818"; CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()]; if ((Height < 0) || (Height > pindexBest->nHeight)) { return genesisblockhash; } CBlock block; CBlockIndex* pblockindex = mapBlockIndex[chainActive.Tip()->GetBlockHash()]; while (pblockindex->nHeight > Height) pblockindex = pblockindex->pprev; return pblockindex->GetBlockHash().GetHex(); // pblockindex->phashBlock->GetHex(); } std::string BlockToString(CBlockIndex* pBlock) { if (!pBlock) return ""; CBlock block; ReadBlockFromDisk(block, pBlock); int64_t Fees = 0; int64_t OutVolume = 0; int64_t Reward = 0; std::string TxLabels[] = {_("Hash"), _("From"), _("Amount"), _("To"), _("Amount")}; std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string)); for (unsigned int i = 0; i < block.vtx.size(); i++) { const CTransaction& tx = block.vtx[i]; TxContent += TxToRow(tx); int64_t In = getTxIn(tx); int64_t Out = tx.GetValueOut(); if (tx.IsCoinBase()) Reward += Out; else if (In < 0) Fees = -MAX_MONEY; else { Fees += In - Out; OutVolume += Out; } } TxContent += "</table>"; int64_t Generated; if (pBlock->nHeight == 0) Generated = OutVolume; else Generated = GetBlockValue(pBlock->nHeight - 1); std::string BlockContentCells[] = { _("Height"), itostr(pBlock->nHeight), _("Size"), itostr(GetSerializeSize(block, SER_NETWORK, PROTOCOL_VERSION)), _("Number of Transactions"), itostr(block.vtx.size()), _("Value Out"), ValueToString(OutVolume), _("Fees"), ValueToString(Fees), _("Generated"), ValueToString(Generated), _("Timestamp"), TimeToString(block.nTime), _("Difficulty"), strprintf("%.4f", GetDifficulty(pBlock)), _("Bits"), utostr(block.nBits), _("Nonce"), utostr(block.nNonce), _("Version"), itostr(block.nVersion), _("Hash"), "<pre>" + block.GetHash().GetHex() + "</pre>", _("Merkle Root"), "<pre>" + block.hashMerkleRoot.GetHex() + "</pre>", // _("Hash Whole Block"), "<pre>" + block.hashWholeBlock.GetHex() + "</pre>" // _("Miner Signature"), "<pre>" + block.MinerSignature.ToString() + "</pre>" }; std::string BlockContent = makeHTMLTable(BlockContentCells, sizeof(BlockContentCells) / (2 * sizeof(std::string)), 2); std::string Content; Content += "<h2><a class=\"nav\" href="; Content += itostr(pBlock->nHeight - 1); Content += ">◄&nbsp;</a>"; Content += _("Block"); Content += " "; Content += itostr(pBlock->nHeight); Content += "<a class=\"nav\" href="; Content += itostr(pBlock->nHeight + 1); Content += ">&nbsp;►</a></h2>"; Content += BlockContent; Content += "</br>"; /* if (block.nHeight > getThirdHardforkBlock()) { std::vector<std::string> votes[2]; for (int i = 0; i < 2; i++) { for (unsigned int j = 0; j < block.vvotes[i].size(); j++) { votes[i].push_back(block.vvotes[i][j].hash.ToString() + ':' + itostr(block.vvotes[i][j].n)); } } Content += "<h3>" + _("Votes +") + "</h3>"; Content += makeHTMLTable(&votes[1][0], votes[1].size(), 1); Content += "</br>"; Content += "<h3>" + _("Votes -") + "</h3>"; Content += makeHTMLTable(&votes[0][0], votes[0].size(), 1); Content += "</br>"; } */ Content += "<h2>" + _("Transactions") + "</h2>"; Content += TxContent; return Content; } std::string TxToString(uint256 BlockHash, const CTransaction& tx) { int64_t Input = 0; int64_t Output = tx.GetValueOut(); std::string InputsContentCells[] = {_("#"), _("Taken from"), _("Address"), _("Amount")}; std::string InputsContent = makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string)); std::string OutputsContentCells[] = {_("#"), _("Redeemed in"), _("Address"), _("Amount")}; std::string OutputsContent = makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string)); if (tx.IsCoinBase()) { std::string InputsContentCells[] = { "0", "coinbase", "-", ValueToString(Output)}; InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string)); } else for (unsigned int i = 0; i < tx.vin.size(); i++) { COutPoint Out = tx.vin[i].prevout; CTxOut PrevOut = getPrevOut(tx.vin[i].prevout); if (PrevOut.nValue < 0) Input = -MAX_MONEY; else Input += PrevOut.nValue; std::string InputsContentCells[] = { itostr(i), "<span>" + makeHRef(Out.hash.GetHex()) + ":" + itostr(Out.n) + "</span>", ScriptToString(PrevOut.scriptPubKey, true), ValueToString(PrevOut.nValue)}; InputsContent += makeHTMLTableRow(InputsContentCells, sizeof(InputsContentCells) / sizeof(std::string)); } uint256 TxHash = tx.GetHash(); for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& Out = tx.vout[i]; uint256 HashNext = uint256S("0"); unsigned int nNext = 0; bool fAddrIndex = false; getNextIn(COutPoint(TxHash, i), HashNext, nNext); std::string OutputsContentCells[] = { itostr(i), (HashNext == uint256S("0")) ? (fAddrIndex ? _("no") : _("unknown")) : "<span>" + makeHRef(HashNext.GetHex()) + ":" + itostr(nNext) + "</span>", ScriptToString(Out.scriptPubKey, true), ValueToString(Out.nValue)}; OutputsContent += makeHTMLTableRow(OutputsContentCells, sizeof(OutputsContentCells) / sizeof(std::string)); } InputsContent = table + InputsContent + "</table>"; OutputsContent = table + OutputsContent + "</table>"; std::string Hash = TxHash.GetHex(); std::string Labels[] = { _("In Block"), "", _("Size"), itostr(GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION)), _("Input"), tx.IsCoinBase() ? "-" : ValueToString(Input), _("Output"), ValueToString(Output), _("Fees"), tx.IsCoinBase() ? "-" : ValueToString(Input - Output), _("Timestamp"), "", _("Hash"), "<pre>" + Hash + "</pre>", }; // std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(BlockHash); BlockMap::iterator iter = mapBlockIndex.find(BlockHash); if (iter != mapBlockIndex.end()) { CBlockIndex* pIndex = iter->second; Labels[0 * 2 + 1] = makeHRef(itostr(pIndex->nHeight)); Labels[5 * 2 + 1] = TimeToString(pIndex->nTime); } std::string Content; Content += "<h2>" + _("Transaction") + "&nbsp;<span>" + Hash + "</span></h2>"; Content += makeHTMLTable(Labels, sizeof(Labels) / (2 * sizeof(std::string)), 2); Content += "</br>"; Content += "<h3>" + _("Inputs") + "</h3>"; Content += InputsContent; Content += "</br>"; Content += "<h3>" + _("Outputs") + "</h3>"; Content += OutputsContent; return Content; } std::string AddressToString(const CBitcoinAddress& Address) { std::string TxLabels[] = { _("Date"), _("Hash"), _("From"), _("Amount"), _("To"), _("Amount"), _("Delta"), _("Balance")}; std::string TxContent = table + makeHTMLTableRow(TxLabels, sizeof(TxLabels) / sizeof(std::string)); std::set<COutPoint> PrevOuts; /* CScript AddressScript; AddressScript.SetDestination(Address.Get()); int64_t Sum = 0; bool fAddrIndex = false; if (!fAddrIndex) return ""; // it will take too long to find transactions by address else { std::vector<CDiskTxPos> Txs; paddressmap->GetTxs(Txs, AddressScript.GetID()); BOOST_FOREACH (const CDiskTxPos& pos, Txs) { CTransaction tx; CBlock block; uint256 bhash = block.GetHash(); GetTransaction(pos.nTxOffset, tx, bhash); std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash()); if (mi == mapBlockIndex.end()) continue; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) continue; std::string Prepend = "<a href=\"" + itostr(pindex->nHeight) + "\">" + TimeToString(pindex->nTime) + "</a>"; TxContent += TxToRow(tx, AddressScript, Prepend, &Sum); } } */ TxContent += "</table>"; std::string Content; Content += "<h1>" + _("Transactions to/from") + "&nbsp;<span>" + Address.ToString() + "</span></h1>"; Content += TxContent; return Content; } BlockExplorer::BlockExplorer(QWidget* parent) : QMainWindow(parent), ui(new Ui::BlockExplorer), m_NeverShown(true), m_HistoryIndex(0) { ui->setupUi(this); connect(ui->pushSearch, SIGNAL(released()), this, SLOT(onSearch())); connect(ui->content, SIGNAL(linkActivated(const QString&)), this, SLOT(goTo(const QString&))); connect(ui->back, SIGNAL(released()), this, SLOT(back())); connect(ui->forward, SIGNAL(released()), this, SLOT(forward())); } BlockExplorer::~BlockExplorer() { delete ui; } void BlockExplorer::keyPressEvent(QKeyEvent* event) { switch ((Qt::Key)event->key()) { case Qt::Key_Enter: case Qt::Key_Return: onSearch(); return; default: return QMainWindow::keyPressEvent(event); } } void BlockExplorer::showEvent(QShowEvent*) { if (m_NeverShown) { m_NeverShown = false; CBlockIndex* pindexBest = mapBlockIndex[chainActive.Tip()->GetBlockHash()]; setBlock(pindexBest); QString text = QString("%1").arg(pindexBest->nHeight); ui->searchBox->setText(text); m_History.push_back(text); updateNavButtons(); if (!GetBoolArg("-txindex", false)) { QString Warning = tr("Not all transactions will be shown. To view all transactions you need to set txindex=1 in the configuration file (Tattoo.conf)."); QMessageBox::warning(this, "Tattoo Core Blockchain Explorer", Warning, QMessageBox::Ok); } } } bool BlockExplorer::switchTo(const QString& query) { bool IsOk; int64_t AsInt = query.toInt(&IsOk); // If query is integer, get hash from height if (IsOk && AsInt >= 0 && AsInt <= chainActive.Tip()->nHeight) { std::string hex = getexplorerBlockHash(AsInt); uint256 hash = uint256S(hex); CBlockIndex* pIndex = mapBlockIndex[hash]; if (pIndex) { setBlock(pIndex); return true; } } // If the query is not an integer, assume it is a block hash uint256 hash = uint256S(query.toUtf8().constData()); // std::map<uint256, CBlockIndex*>::iterator iter = mapBlockIndex.find(hash); BlockMap::iterator iter = mapBlockIndex.find(hash); if (iter != mapBlockIndex.end()) { setBlock(iter->second); return true; } // If the query is neither an integer nor a block hash, assume a transaction hash CTransaction tx; uint256 hashBlock = 0; if (GetTransaction(hash, tx, hashBlock, true)) { setContent(TxToString(hashBlock, tx)); return true; } // If the query is not an integer, nor a block hash, nor a transaction hash, assume an address CBitcoinAddress Address; Address.SetString(query.toUtf8().constData()); if (Address.IsValid()) { std::string Content = AddressToString(Address); if (Content.empty()) return false; setContent(Content); return true; } return false; } void BlockExplorer::goTo(const QString& query) { if (switchTo(query)) { ui->searchBox->setText(query); while (m_History.size() > m_HistoryIndex + 1) m_History.pop_back(); m_History.push_back(query); m_HistoryIndex = m_History.size() - 1; updateNavButtons(); } } void BlockExplorer::onSearch() { goTo(ui->searchBox->text()); } void BlockExplorer::setBlock(CBlockIndex* pBlock) { setContent(BlockToString(pBlock)); } void BlockExplorer::setContent(const std::string& Content) { QString CSS = "body {font-size:12px; background-color: #C8E5E2; color:#444;}\n a, span { font-family: monospace; }\n span.addr {color:#13BE5D; font-weight: bold;}\n table tr td {padding: 3px; border: none; background-color: #A1CDC8;}\n td.d0 {font-weight: bold; color:#f8f8f8;}\n h2, h3 { white-space:nowrap; color:#1B7884;}\n a { text-decoration:none; }\n a.nav {color:green;}\n"; QString FullContent = "<html><head><style type=\"text/css\">" + CSS + "</style></head>" + "<body>" + Content.c_str() + "</body></html>"; // printf(FullContent.toUtf8()); ui->content->setText(FullContent); } void BlockExplorer::back() { int NewIndex = m_HistoryIndex - 1; if (0 <= NewIndex && NewIndex < m_History.size()) { m_HistoryIndex = NewIndex; ui->searchBox->setText(m_History[NewIndex]); switchTo(m_History[NewIndex]); updateNavButtons(); } } void BlockExplorer::forward() { int NewIndex = m_HistoryIndex + 1; if (0 <= NewIndex && NewIndex < m_History.size()) { m_HistoryIndex = NewIndex; ui->searchBox->setText(m_History[NewIndex]); switchTo(m_History[NewIndex]); updateNavButtons(); } } void BlockExplorer::updateNavButtons() { ui->back->setEnabled(m_HistoryIndex - 1 >= 0); ui->forward->setEnabled(m_HistoryIndex + 1 < m_History.size()); }
// Copyright 2006-2009 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // CPU specific code for arm independent of OS goes here. #ifdef __arm__ #ifdef __QNXNTO__ #include <sys/mman.h> // for cache flushing. #undef MAP_TYPE // NOLINT #elif defined(V8_TARGET_OS_IOS) #include <libkern/OSCacheControl.h> #elif V8_OS_FREEBSD #include <machine/sysarch.h> // for cache flushing #include <sys/types.h> #else #include <sys/syscall.h> // for cache flushing. #endif #endif #if V8_TARGET_ARCH_ARM #include "src/codegen/cpu-features.h" namespace v8 { namespace internal { // The inlining of this seems to trigger an LTO bug that clobbers a register, // see https://crbug.com/952759 and https://bugs.llvm.org/show_bug.cgi?id=41575. V8_NOINLINE void CpuFeatures::FlushICache(void* start, size_t size) { #if !defined(USE_SIMULATOR) #if V8_OS_QNX msync(start, size, MS_SYNC | MS_INVALIDATE_ICACHE); #elif defined(V8_TARGET_OS_IOS) sys_icache_invalidate(start, size); #elif V8_OS_FREEBSD struct arm_sync_icache_args args = { .addr = reinterpret_cast<uintptr_t>(start), .len = size}; sysarch(ARM_SYNC_ICACHE, reinterpret_cast<void*>(&args)); #else register uint32_t beg asm("r0") = reinterpret_cast<uint32_t>(start); register uint32_t end asm("r1") = beg + size; register uint32_t flg asm("r2") = 0; asm volatile( // This assembly works for both ARM and Thumb targets. // Preserve r7; it is callee-saved, and GCC uses it as a frame pointer for // Thumb targets. " push {r7}\n" // r0 = beg // r1 = end // r2 = flags (0) " ldr r7, =%c[scno]\n" // r7 = syscall number " svc 0\n" " pop {r7}\n" : : "r"(beg), "r"(end), "r"(flg), [scno] "i"(__ARM_NR_cacheflush) : "memory"); #endif #endif // !USE_SIMULATOR } } // namespace internal } // namespace v8 #endif // V8_TARGET_ARCH_ARM
#include "windowsetting.h" #include "ui_windowsetting.h" #include "generalwindow.h" #include <QtDebug> #include "database.h" WindowSetting::WindowSetting(QWidget *parent) : QDialog(parent), ui(new Ui::WindowSetting) { ui->setupUi(this); m_main = qobject_cast<generalWindow*>(parent); this->setModal(true); connect(this, &WindowSetting::dialogClosed, this, &WindowSetting::on_pushButton_Cancel_clicked); this->m_TypeNextMusic = static_cast <nextMusic>(ui->TypePlay->currentIndex()); this->m_TypeSort = static_cast <Sort>(ui->TypeSort->currentIndex()); connect(&m_time, &QTimer::timeout, this, &WindowSetting::timeoutResetTimer); connect(&m_timeOf, &QTimer::timeout, m_main, &QApplication::closeAllWindows); m_time.setInterval(1000); } WindowSetting::~WindowSetting() { m_main->m_db->addTypeSort(ui->TypePlay->currentIndex(), ui->TypeSort->currentIndex()); delete ui; } void WindowSetting::on_pushButton_Save_clicked() { this->m_TypeNextMusic = static_cast <nextMusic>(ui->TypePlay->currentIndex()); if (this->m_TypeSort != static_cast <Sort>(ui->TypeSort->currentIndex())) { this->m_TypeSort = static_cast <Sort>(ui->TypeSort->currentIndex()); this->m_main->setSort(this->m_TypeSort); } this->hide(); } void WindowSetting::loadingSettings(DataBase *db) { ui->TypeSort->setCurrentIndex(db->GetSort()); ui->TypePlay->setCurrentIndex(db->GetType()); this->m_TypeNextMusic = static_cast <nextMusic>(ui->TypePlay->currentIndex()); this->m_TypeSort = static_cast <Sort>(ui->TypeSort->currentIndex()); this->m_main->setSort(this->m_TypeSort); } void WindowSetting::timeoutResetTimer(void) { if (!this->isHidden()) { int time = this->m_timeOf.remainingTime() / 1000; ui->TimeToShotdown->setText(QString::number(time / 60) + ":" + QString::number(time % 60)); } } void WindowSetting::on_pushButton_Cancel_clicked() { ui->TypePlay->setCurrentIndex(static_cast<int>(this->m_TypeNextMusic)); ui->TypeSort->setCurrentIndex(static_cast<int>(this->m_TypeSort)); this->hide(); } WindowSetting::nextMusic WindowSetting::getTypeNext() { return this->m_TypeNextMusic; } WindowSetting::Sort WindowSetting::getTypeSort(void) { return this->m_TypeSort; } void WindowSetting::setSortType(WindowSetting::Sort type) { if (Sort::random == type) this->m_TypeSort = Sort::user; else { this->m_TypeSort = type; } ui->TypeSort->setCurrentIndex(static_cast<int>(this->m_TypeSort)); } void WindowSetting::on_pushButtonStart_clicked() { switch (this->ui->Times->currentIndex()) { case 0: m_time.stop(); m_timeOf.stop(); ui->TimeToShotdown->setText("Off"); break; case 1: m_time.start(); m_timeOf.setInterval(1*60*1000); m_timeOf.start(); break; case 2: m_time.start(); m_timeOf.setInterval(5*60*1000); m_timeOf.start(); break; case 3: m_time.start(); m_timeOf.setInterval(10*60*1000); m_timeOf.start(); break; case 4: m_time.start(); m_timeOf.setInterval(15*60*1000); m_timeOf.start(); break; } }
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz> 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 "BufferState.h" #include <Corrade/Containers/StringView.h> #include <Corrade/Utility/Assert.h> #include "Magnum/GL/Context.h" #include "Magnum/GL/Extensions.h" #include "Magnum/GL/Implementation/State.h" namespace Magnum { namespace GL { namespace Implementation { using namespace Containers::Literals; const Buffer::TargetHint BufferState::targetForIndex[] = { Buffer::TargetHint::Array, Buffer::TargetHint::ElementArray, #ifndef MAGNUM_TARGET_GLES2 Buffer::TargetHint::CopyRead, Buffer::TargetHint::CopyWrite, Buffer::TargetHint::PixelPack, Buffer::TargetHint::PixelUnpack, Buffer::TargetHint::TransformFeedback, Buffer::TargetHint::Uniform, #ifndef MAGNUM_TARGET_WEBGL Buffer::TargetHint::AtomicCounter, Buffer::TargetHint::DispatchIndirect, Buffer::TargetHint::DrawIndirect, Buffer::TargetHint::ShaderStorage, Buffer::TargetHint::Texture #endif #endif }; std::size_t BufferState::indexForTarget(Buffer::TargetHint target) { switch(target) { case Buffer::TargetHint::Array: return 1; case Buffer::TargetHint::ElementArray: return 2; #ifndef MAGNUM_TARGET_GLES2 case Buffer::TargetHint::CopyRead: return 3; case Buffer::TargetHint::CopyWrite: return 4; case Buffer::TargetHint::PixelPack: return 5; case Buffer::TargetHint::PixelUnpack: return 6; case Buffer::TargetHint::TransformFeedback: return 7; case Buffer::TargetHint::Uniform: return 8; #ifndef MAGNUM_TARGET_WEBGL case Buffer::TargetHint::AtomicCounter: return 9; case Buffer::TargetHint::DispatchIndirect: return 10; case Buffer::TargetHint::DrawIndirect: return 11; case Buffer::TargetHint::ShaderStorage: return 12; case Buffer::TargetHint::Texture: return 13; #endif #endif } CORRADE_INTERNAL_ASSERT_UNREACHABLE(); /* LCOV_EXCL_LINE */ } BufferState::BufferState(Context& context, Containers::StaticArrayView<Implementation::ExtensionCount, const char*> extensions): bindings() #ifndef MAGNUM_TARGET_GLES2 #ifndef MAGNUM_TARGET_GLES , minMapAlignment(0) #endif #ifndef MAGNUM_TARGET_WEBGL , maxAtomicCounterBindings{0}, maxShaderStorageBindings{0}, shaderStorageOffsetAlignment{0} #endif , uniformOffsetAlignment{0}, maxUniformBindings{0} #endif { /* DSA, except Intel Windows, because I have no patience for that anymore */ #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::ARB::direct_state_access>() #ifdef CORRADE_TARGET_WINDOWS && (!(context.detectedDriver() & Context::DetectedDriver::IntelWindows) || context.isDriverWorkaroundDisabled("intel-windows-crazy-broken-buffer-dsa"_s)) #endif ) { extensions[Extensions::ARB::direct_state_access::Index] = Extensions::ARB::direct_state_access::string(); createImplementation = &Buffer::createImplementationDSA; copyImplementation = &Buffer::copyImplementationDSA; #ifndef MAGNUM_TARGET_GLES storageImplementation = &Buffer::storageImplementationDSA; #endif getParameterImplementation = &Buffer::getParameterImplementationDSA; getSubDataImplementation = &Buffer::getSubDataImplementationDSA; dataImplementation = &Buffer::dataImplementationDSA; subDataImplementation = &Buffer::subDataImplementationDSA; mapImplementation = &Buffer::mapImplementationDSA; mapRangeImplementation = &Buffer::mapRangeImplementationDSA; flushMappedRangeImplementation = &Buffer::flushMappedRangeImplementationDSA; unmapImplementation = &Buffer::unmapImplementationDSA; } else #endif { createImplementation = &Buffer::createImplementationDefault; #ifndef MAGNUM_TARGET_GLES2 copyImplementation = &Buffer::copyImplementationDefault; #endif #ifndef MAGNUM_TARGET_GLES storageImplementation = &Buffer::storageImplementationDefault; #endif getParameterImplementation = &Buffer::getParameterImplementationDefault; #ifndef MAGNUM_TARGET_GLES getSubDataImplementation = &Buffer::getSubDataImplementationDefault; #endif dataImplementation = &Buffer::dataImplementationDefault; subDataImplementation = &Buffer::subDataImplementationDefault; #ifndef MAGNUM_TARGET_WEBGL mapImplementation = &Buffer::mapImplementationDefault; mapRangeImplementation = &Buffer::mapRangeImplementationDefault; flushMappedRangeImplementation = &Buffer::flushMappedRangeImplementationDefault; unmapImplementation = &Buffer::unmapImplementationDefault; #endif } #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::ARB::invalidate_subdata>()) { extensions[Extensions::ARB::invalidate_subdata::Index] = Extensions::ARB::invalidate_subdata::string(); invalidateImplementation = &Buffer::invalidateImplementationARB; invalidateSubImplementation = &Buffer::invalidateSubImplementationARB; } else #endif { invalidateImplementation = &Buffer::invalidateImplementationNoOp; invalidateSubImplementation = &Buffer::invalidateSubImplementationNoOp; } #ifndef MAGNUM_TARGET_GLES2 #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::ARB::multi_bind>()) { extensions[Extensions::ARB::multi_bind::Index] = Extensions::ARB::multi_bind::string(); bindBasesImplementation = &Buffer::bindImplementationMulti; bindRangesImplementation = &Buffer::bindImplementationMulti; } else #endif { bindBasesImplementation = &Buffer::bindImplementationFallback; bindRangesImplementation = &Buffer::bindImplementationFallback; } #endif #ifndef MAGNUM_TARGET_GLES if(context.isExtensionSupported<Extensions::ARB::direct_state_access>() && (context.detectedDriver() & Context::DetectedDriver::Svga3D) && !context.isDriverWorkaroundDisabled("svga3d-broken-dsa-bufferdata"_s)) { dataImplementation = &Buffer::dataImplementationDefault; } #endif #if defined(MAGNUM_TARGET_GLES) && !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL) if((context.detectedDriver() & Context::DetectedDriver::SwiftShader) && !context.isDriverWorkaroundDisabled("swiftshader-broken-xfb-buffer-binding-target"_s)) { setTargetHintImplementation = &Buffer::setTargetHintImplementationSwiftShader; } else #endif { setTargetHintImplementation = &Buffer::setTargetHintImplementationDefault; } #if defined(CORRADE_TARGET_APPLE) && !defined(MAGNUM_TARGET_GLES) if(!context.isDriverWorkaroundDisabled("apple-buffer-texture-unbind-on-buffer-modify"_s)) { dataImplementation = &Buffer::dataImplementationApple; subDataImplementation = &Buffer::subDataImplementationApple; mapImplementation = &Buffer::mapImplementationApple; mapRangeImplementation = &Buffer::mapRangeImplementationApple; unmapImplementation = &Buffer::unmapImplementationApple; /* No need for Apple-specific invalidate*Implementation, as the extension isn't supported anyway */ CORRADE_INTERNAL_ASSERT(!context.isExtensionSupported<Extensions::ARB::invalidate_subdata>()); } #endif #ifdef MAGNUM_TARGET_GLES static_cast<void>(context); static_cast<void>(extensions); #endif } void BufferState::reset() { for(GLuint& i: bindings) i = State::DisengagedBinding; } }}}
// Fill out your copyright notice in the Description page of Project Settings. #include "PhysicsVolume_Cell.h" void APhysicsVolume_Cell::PostInitializeComponents() { Super::PostInitializeComponents(); bWaterVolume = true; FluidFriction = 1000.f; }
/** * \file * * \copyright * Copyright (c) 2012-2020, OpenGeoSys Community (http://www.opengeosys.org) * Distributed under a Modified BSD License. * See accompanying file LICENSE.txt or * http://www.opengeosys.org/project/license */ #include "Curve.h" namespace MaterialPropertyLib { Curve::Curve(std::string name, Variable const independent_variable, MathLib::PiecewiseLinearInterpolation const& curve) : independent_variable_(independent_variable), curve_(curve) { name_ = std::move(name); } PropertyDataType Curve::value(VariableArray const& variable_array, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { auto const x = std::get<double>( variable_array[static_cast<int>(independent_variable_)]); return curve_.getValue(x); } PropertyDataType Curve::dValue(VariableArray const& variable_array, Variable const /*primary_variable*/, ParameterLib::SpatialPosition const& /*pos*/, double const /*t*/, double const /*dt*/) const { auto const x = std::get<double>( variable_array[static_cast<int>(independent_variable_)]); return curve_.getDerivative(x); } } // namespace MaterialPropertyLib
#include "test/integration/integration.h" #include <chrono> #include <cstdint> #include <functional> #include <list> #include <memory> #include <string> #include <vector> #include "envoy/admin/v3/config_dump.pb.h" #include "envoy/api/v2/discovery.pb.h" #include "envoy/buffer/buffer.h" #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/endpoint/v3/endpoint_components.pb.h" #include "envoy/extensions/transport_sockets/tls/v3/cert.pb.h" #include "envoy/http/header_map.h" #include "common/api/api_impl.h" #include "common/buffer/buffer_impl.h" #include "common/common/assert.h" #include "common/common/fmt.h" #include "common/config/api_version.h" #include "common/event/dispatcher_impl.h" #include "common/event/libevent.h" #include "common/network/connection_impl.h" #include "common/network/utility.h" #include "common/upstream/upstream_impl.h" #include "extensions/transport_sockets/tls/context_config_impl.h" #include "extensions/transport_sockets/tls/context_manager_impl.h" #include "extensions/transport_sockets/tls/ssl_socket.h" #include "test/integration/autonomous_upstream.h" #include "test/integration/utility.h" #include "test/test_common/environment.h" #include "test/test_common/network_utility.h" #include "absl/container/fixed_array.h" #include "absl/strings/str_join.h" #include "gtest/gtest.h" using testing::_; using testing::AnyNumber; using testing::AssertionFailure; using testing::AssertionResult; using testing::AssertionSuccess; using testing::AtLeast; using testing::Invoke; using testing::IsSubstring; using testing::NiceMock; using testing::ReturnRef; namespace Envoy { IntegrationStreamDecoder::IntegrationStreamDecoder(Event::Dispatcher& dispatcher) : dispatcher_(dispatcher) {} void IntegrationStreamDecoder::waitForContinueHeaders() { if (!continue_headers_.get()) { waiting_for_continue_headers_ = true; dispatcher_.run(Event::Dispatcher::RunType::Block); } } void IntegrationStreamDecoder::waitForHeaders() { if (!headers_.get()) { waiting_for_headers_ = true; dispatcher_.run(Event::Dispatcher::RunType::Block); } } void IntegrationStreamDecoder::waitForBodyData(uint64_t size) { ASSERT(body_data_waiting_length_ == 0); body_data_waiting_length_ = size; body_data_waiting_length_ -= std::min(body_data_waiting_length_, static_cast<uint64_t>(body_.size())); if (body_data_waiting_length_ > 0) { dispatcher_.run(Event::Dispatcher::RunType::Block); } } void IntegrationStreamDecoder::waitForEndStream() { if (!saw_end_stream_) { waiting_for_end_stream_ = true; dispatcher_.run(Event::Dispatcher::RunType::Block); } } void IntegrationStreamDecoder::waitForReset() { if (!saw_reset_) { waiting_for_reset_ = true; dispatcher_.run(Event::Dispatcher::RunType::Block); } } void IntegrationStreamDecoder::decode100ContinueHeaders(Http::ResponseHeaderMapPtr&& headers) { continue_headers_ = std::move(headers); if (waiting_for_continue_headers_) { dispatcher_.exit(); } } void IntegrationStreamDecoder::decodeHeaders(Http::ResponseHeaderMapPtr&& headers, bool end_stream) { saw_end_stream_ = end_stream; headers_ = std::move(headers); if ((end_stream && waiting_for_end_stream_) || waiting_for_headers_) { dispatcher_.exit(); } } void IntegrationStreamDecoder::decodeData(Buffer::Instance& data, bool end_stream) { saw_end_stream_ = end_stream; body_ += data.toString(); if (end_stream && waiting_for_end_stream_) { dispatcher_.exit(); } else if (body_data_waiting_length_ > 0) { body_data_waiting_length_ -= std::min(body_data_waiting_length_, data.length()); if (body_data_waiting_length_ == 0) { dispatcher_.exit(); } } } void IntegrationStreamDecoder::decodeTrailers(Http::ResponseTrailerMapPtr&& trailers) { saw_end_stream_ = true; trailers_ = std::move(trailers); if (waiting_for_end_stream_) { dispatcher_.exit(); } } void IntegrationStreamDecoder::decodeMetadata(Http::MetadataMapPtr&& metadata_map) { // Combines newly received metadata with the existing metadata. for (const auto& metadata : *metadata_map) { duplicated_metadata_key_count_[metadata.first]++; metadata_map_->insert(metadata); } } void IntegrationStreamDecoder::onResetStream(Http::StreamResetReason reason, absl::string_view) { saw_reset_ = true; reset_reason_ = reason; if (waiting_for_reset_) { dispatcher_.exit(); } } IntegrationTcpClient::IntegrationTcpClient( Event::Dispatcher& dispatcher, Event::TestTimeSystem& time_system, MockBufferFactory& factory, uint32_t port, Network::Address::IpVersion version, bool enable_half_close, const Network::ConnectionSocket::OptionsSharedPtr& options) : time_system_(time_system), payload_reader_(new WaitForPayloadReader(dispatcher)), callbacks_(new ConnectionCallbacks(*this)) { EXPECT_CALL(factory, create_(_, _, _)) .WillOnce(Invoke([&](std::function<void()> below_low, std::function<void()> above_high, std::function<void()> above_overflow) -> Buffer::Instance* { client_write_buffer_ = new NiceMock<MockWatermarkBuffer>(below_low, above_high, above_overflow); return client_write_buffer_; })); connection_ = dispatcher.createClientConnection( Network::Utility::resolveUrl( fmt::format("tcp://{}:{}", Network::Test::getLoopbackAddressUrlString(version), port)), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), options); ON_CALL(*client_write_buffer_, drain(_)) .WillByDefault(testing::Invoke(client_write_buffer_, &MockWatermarkBuffer::baseDrain)); EXPECT_CALL(*client_write_buffer_, drain(_)).Times(AnyNumber()); connection_->enableHalfClose(enable_half_close); connection_->addConnectionCallbacks(*callbacks_); connection_->addReadFilter(payload_reader_); connection_->connect(); } void IntegrationTcpClient::close() { connection_->close(Network::ConnectionCloseType::NoFlush); } void IntegrationTcpClient::waitForData(const std::string& data, bool exact_match) { auto found = payload_reader_->data().find(data); if (found == 0 || (!exact_match && found != std::string::npos)) { return; } payload_reader_->set_data_to_wait_for(data, exact_match); connection_->dispatcher().run(Event::Dispatcher::RunType::Block); } AssertionResult IntegrationTcpClient::waitForData(size_t length, std::chrono::milliseconds timeout) { if (payload_reader_->data().size() >= length) { return AssertionSuccess(); } return payload_reader_->waitForLength(length, timeout); } void IntegrationTcpClient::waitForDisconnect(bool ignore_spurious_events) { Event::TimerPtr timeout_timer = connection_->dispatcher().createTimer([this]() -> void { connection_->dispatcher().exit(); }); timeout_timer->enableTimer(TestUtility::DefaultTimeout); if (ignore_spurious_events) { while (!disconnected_ && timeout_timer->enabled()) { connection_->dispatcher().run(Event::Dispatcher::RunType::Block); } } else { connection_->dispatcher().run(Event::Dispatcher::RunType::Block); } EXPECT_TRUE(disconnected_); } void IntegrationTcpClient::waitForHalfClose() { if (payload_reader_->readLastByte()) { return; } connection_->dispatcher().run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(payload_reader_->readLastByte()); } void IntegrationTcpClient::readDisable(bool disabled) { connection_->readDisable(disabled); } AssertionResult IntegrationTcpClient::write(const std::string& data, bool end_stream, bool verify, std::chrono::milliseconds timeout) { auto end_time = time_system_.monotonicTime() + timeout; Buffer::OwnedImpl buffer(data); if (verify) { EXPECT_CALL(*client_write_buffer_, move(_)); if (!data.empty()) { EXPECT_CALL(*client_write_buffer_, write(_)).Times(AtLeast(1)); } } int bytes_expected = client_write_buffer_->bytes_written() + data.size(); connection_->write(buffer, end_stream); do { connection_->dispatcher().run(Event::Dispatcher::RunType::NonBlock); if (client_write_buffer_->bytes_written() == bytes_expected || disconnected_) { break; } } while (time_system_.monotonicTime() < end_time); if (time_system_.monotonicTime() >= end_time) { return AssertionFailure() << "Timed out completing write"; } else if (verify && (disconnected_ || client_write_buffer_->bytes_written() != bytes_expected)) { return AssertionFailure() << "Failed to complete write or unexpected disconnect. disconnected_: " << disconnected_ << " bytes_written: " << client_write_buffer_->bytes_written() << " bytes_expected: " << bytes_expected; } return AssertionSuccess(); } void IntegrationTcpClient::ConnectionCallbacks::onEvent(Network::ConnectionEvent event) { if (event == Network::ConnectionEvent::RemoteClose) { parent_.disconnected_ = true; parent_.connection_->dispatcher().exit(); } } BaseIntegrationTest::BaseIntegrationTest(const InstanceConstSharedPtrFn& upstream_address_fn, Network::Address::IpVersion version, const std::string& config) : api_(Api::createApiForTest(stats_store_)), mock_buffer_factory_(new NiceMock<MockBufferFactory>), dispatcher_(api_->allocateDispatcher("test_thread", Buffer::WatermarkFactoryPtr{mock_buffer_factory_})), version_(version), upstream_address_fn_(upstream_address_fn), config_helper_(version, *api_, config), default_log_level_(TestEnvironment::getOptions().logLevel()) { // This is a hack, but there are situations where we disconnect fake upstream connections and // then we expect the server connection pool to get the disconnect before the next test starts. // This does not always happen. This pause should allow the server to pick up the disconnect // notification and clear the pool connection if necessary. A real fix would require adding fairly // complex test hooks to the server and/or spin waiting on stats, neither of which I think are // necessary right now. timeSystem().advanceTimeWait(std::chrono::milliseconds(10)); ON_CALL(*mock_buffer_factory_, create_(_, _, _)) .WillByDefault(Invoke([](std::function<void()> below_low, std::function<void()> above_high, std::function<void()> above_overflow) -> Buffer::Instance* { return new Buffer::WatermarkBuffer(below_low, above_high, above_overflow); })); ON_CALL(factory_context_, api()).WillByDefault(ReturnRef(*api_)); // In ENVOY_USE_LEGACY_CODECS_IN_INTEGRATION_TESTS mode, set runtime config to use legacy codecs. #ifdef ENVOY_USE_LEGACY_CODECS_IN__INTEGRATION_TESTS ENVOY_LOG_MISC(debug, "Using legacy codecs"); setLegacyCodecs(); #endif } BaseIntegrationTest::BaseIntegrationTest(Network::Address::IpVersion version, const std::string& config) : BaseIntegrationTest( [version](int) { return Network::Utility::parseInternetAddress( Network::Test::getAnyAddressString(version), 0); }, version, config) {} Network::ClientConnectionPtr BaseIntegrationTest::makeClientConnection(uint32_t port) { return makeClientConnectionWithOptions(port, nullptr); } Network::ClientConnectionPtr BaseIntegrationTest::makeClientConnectionWithOptions( uint32_t port, const Network::ConnectionSocket::OptionsSharedPtr& options) { Network::ClientConnectionPtr connection(dispatcher_->createClientConnection( Network::Utility::resolveUrl( fmt::format("tcp://{}:{}", Network::Test::getLoopbackAddressUrlString(version_), port)), Network::Address::InstanceConstSharedPtr(), Network::Test::createRawBufferSocket(), options)); connection->enableHalfClose(enable_half_close_); return connection; } void BaseIntegrationTest::initialize() { RELEASE_ASSERT(!initialized_, ""); RELEASE_ASSERT(Event::Libevent::Global::initialized(), ""); initialized_ = true; createUpstreams(); createXdsUpstream(); createEnvoy(); } void BaseIntegrationTest::createUpstreams() { for (uint32_t i = 0; i < fake_upstreams_count_; ++i) { auto endpoint = upstream_address_fn_(i); if (autonomous_upstream_) { fake_upstreams_.emplace_back(new AutonomousUpstream( endpoint, upstream_protocol_, *time_system_, autonomous_allow_incomplete_streams_)); } else { fake_upstreams_.emplace_back(new FakeUpstream(endpoint, upstream_protocol_, *time_system_, enable_half_close_, udp_fake_upstream_)); } } } void BaseIntegrationTest::createEnvoy() { std::vector<uint32_t> ports; for (auto& upstream : fake_upstreams_) { if (upstream->localAddress()->ip()) { ports.push_back(upstream->localAddress()->ip()->port()); } } if (use_lds_) { ENVOY_LOG_MISC(debug, "Setting up file-based LDS"); // Before finalization, set up a real lds path, replacing the default /dev/null std::string lds_path = TestEnvironment::temporaryPath(TestUtility::uniqueFilename()); config_helper_.addConfigModifier( [lds_path](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { bootstrap.mutable_dynamic_resources()->mutable_lds_config()->set_path(lds_path); }); } // Note that finalize assumes that every fake_upstream_ must correspond to a bootstrap config // static entry. So, if you want to manually create a fake upstream without specifying it in the // config, you will need to do so *after* initialize() (which calls this function) is done. config_helper_.finalize(ports); envoy::config::bootstrap::v3::Bootstrap bootstrap = config_helper_.bootstrap(); if (use_lds_) { // After the config has been finalized, write the final listener config to the lds file. const std::string lds_path = config_helper_.bootstrap().dynamic_resources().lds_config().path(); API_NO_BOOST(envoy::api::v2::DiscoveryResponse) lds; lds.set_version_info("0"); for (auto& listener : config_helper_.bootstrap().static_resources().listeners()) { ProtobufWkt::Any* resource = lds.add_resources(); resource->PackFrom(listener); } TestEnvironment::writeStringToFileForTest(lds_path, MessageUtil::getJsonStringFromMessage(lds), true); // Now that the listeners have been written to the lds file, remove them from static resources // or they will not be reloadable. bootstrap.mutable_static_resources()->mutable_listeners()->Clear(); } ENVOY_LOG_MISC(debug, "Running Envoy with configuration:\n{}", MessageUtil::getYamlStringFromMessage(bootstrap)); const std::string bootstrap_path = TestEnvironment::writeStringToFileForTest( "bootstrap.pb", TestUtility::getProtobufBinaryStringFromMessage(bootstrap)); std::vector<std::string> named_ports; const auto& static_resources = config_helper_.bootstrap().static_resources(); named_ports.reserve(static_resources.listeners_size()); for (int i = 0; i < static_resources.listeners_size(); ++i) { named_ports.push_back(static_resources.listeners(i).name()); } createGeneratedApiTestServer(bootstrap_path, named_ports, {false, true, false}, false); } void BaseIntegrationTest::setUpstreamProtocol(FakeHttpConnection::Type protocol) { upstream_protocol_ = protocol; if (upstream_protocol_ == FakeHttpConnection::Type::HTTP2) { config_helper_.addConfigModifier( [&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { RELEASE_ASSERT(bootstrap.mutable_static_resources()->clusters_size() >= 1, ""); auto* cluster = bootstrap.mutable_static_resources()->mutable_clusters(0); cluster->mutable_http2_protocol_options(); }); } else { RELEASE_ASSERT(protocol == FakeHttpConnection::Type::HTTP1, ""); } } IntegrationTcpClientPtr BaseIntegrationTest::makeTcpConnection(uint32_t port, const Network::ConnectionSocket::OptionsSharedPtr& options) { return std::make_unique<IntegrationTcpClient>(*dispatcher_, time_system_, *mock_buffer_factory_, port, version_, enable_half_close_, options); } void BaseIntegrationTest::registerPort(const std::string& key, uint32_t port) { port_map_[key] = port; } uint32_t BaseIntegrationTest::lookupPort(const std::string& key) { auto it = port_map_.find(key); if (it != port_map_.end()) { return it->second; } RELEASE_ASSERT( false, fmt::format("lookupPort() called on service type '{}', which has not been added to port_map_", key)); } void BaseIntegrationTest::setUpstreamAddress( uint32_t upstream_index, envoy::config::endpoint::v3::LbEndpoint& endpoint) const { auto* socket_address = endpoint.mutable_endpoint()->mutable_address()->mutable_socket_address(); socket_address->set_address(Network::Test::getLoopbackAddressString(version_)); socket_address->set_port_value(fake_upstreams_[upstream_index]->localAddress()->ip()->port()); } void BaseIntegrationTest::registerTestServerPorts(const std::vector<std::string>& port_names) { bool listeners_ready = false; absl::Mutex l; std::vector<std::reference_wrapper<Network::ListenerConfig>> listeners; test_server_->server().dispatcher().post([this, &listeners, &listeners_ready, &l]() { listeners = test_server_->server().listenerManager().listeners(); l.Lock(); listeners_ready = true; l.Unlock(); }); l.LockWhen(absl::Condition(&listeners_ready)); l.Unlock(); auto listener_it = listeners.cbegin(); auto port_it = port_names.cbegin(); for (; port_it != port_names.end() && listener_it != listeners.end(); ++port_it, ++listener_it) { const auto listen_addr = listener_it->get().listenSocketFactory().localAddress(); if (listen_addr->type() == Network::Address::Type::Ip) { ENVOY_LOG(debug, "registered '{}' as port {}.", *port_it, listen_addr->ip()->port()); registerPort(*port_it, listen_addr->ip()->port()); } } const auto admin_addr = test_server_->server().admin().socket().localAddress(); if (admin_addr->type() == Network::Address::Type::Ip) { registerPort("admin", admin_addr->ip()->port()); } } std::string getListenerDetails(Envoy::Server::Instance& server) { const auto& cbs_maps = server.admin().getConfigTracker().getCallbacksMap(); ProtobufTypes::MessagePtr details = cbs_maps.at("listeners")(); auto listener_info = Protobuf::down_cast<envoy::admin::v3::ListenersConfigDump>(*details); return MessageUtil::getYamlStringFromMessage(listener_info.dynamic_listeners(0).error_state()); } void BaseIntegrationTest::createGeneratedApiTestServer( const std::string& bootstrap_path, const std::vector<std::string>& port_names, Server::FieldValidationConfig validator_config, bool allow_lds_rejection) { test_server_ = IntegrationTestServer::create( bootstrap_path, version_, on_server_ready_function_, on_server_init_function_, deterministic_, timeSystem(), *api_, defer_listener_finalization_, process_object_, validator_config, concurrency_, drain_time_, drain_strategy_, use_real_stats_); if (config_helper_.bootstrap().static_resources().listeners_size() > 0 && !defer_listener_finalization_) { // Wait for listeners to be created before invoking registerTestServerPorts() below, as that // needs to know about the bound listener ports. auto end_time = time_system_.monotonicTime() + TestUtility::DefaultTimeout; const char* success = "listener_manager.listener_create_success"; const char* rejected = "listener_manager.lds.update_rejected"; for (Stats::CounterSharedPtr success_counter = test_server_->counter(success), rejected_counter = test_server_->counter(rejected); (success_counter == nullptr || success_counter->value() < concurrency_ * config_helper_.bootstrap().static_resources().listeners_size()) && (!allow_lds_rejection || rejected_counter == nullptr || rejected_counter->value() == 0); success_counter = test_server_->counter(success), rejected_counter = test_server_->counter(rejected)) { if (time_system_.monotonicTime() >= end_time) { RELEASE_ASSERT(0, "Timed out waiting for listeners."); } if (!allow_lds_rejection) { RELEASE_ASSERT(rejected_counter == nullptr || rejected_counter->value() == 0, absl::StrCat("Lds update failed. Details\n", getListenerDetails(test_server_->server()))); } time_system_.advanceTimeWait(std::chrono::milliseconds(10)); } registerTestServerPorts(port_names); } } void BaseIntegrationTest::createApiTestServer(const ApiFilesystemConfig& api_filesystem_config, const std::vector<std::string>& port_names, Server::FieldValidationConfig validator_config, bool allow_lds_rejection) { const std::string eds_path = TestEnvironment::temporaryFileSubstitute( api_filesystem_config.eds_path_, port_map_, version_); const std::string cds_path = TestEnvironment::temporaryFileSubstitute( api_filesystem_config.cds_path_, {{"eds_json_path", eds_path}}, port_map_, version_); const std::string rds_path = TestEnvironment::temporaryFileSubstitute( api_filesystem_config.rds_path_, port_map_, version_); const std::string lds_path = TestEnvironment::temporaryFileSubstitute( api_filesystem_config.lds_path_, {{"rds_json_path", rds_path}}, port_map_, version_); createGeneratedApiTestServer(TestEnvironment::temporaryFileSubstitute( api_filesystem_config.bootstrap_path_, {{"cds_json_path", cds_path}, {"lds_json_path", lds_path}}, port_map_, version_), port_names, validator_config, allow_lds_rejection); } void BaseIntegrationTest::sendRawHttpAndWaitForResponse(int port, const char* raw_http, std::string* response, bool disconnect_after_headers_complete) { auto connection = createConnectionDriver( port, raw_http, [response, disconnect_after_headers_complete](Network::ClientConnection& client, const Buffer::Instance& data) -> void { response->append(data.toString()); if (disconnect_after_headers_complete && response->find("\r\n\r\n") != std::string::npos) { client.close(Network::ConnectionCloseType::NoFlush); } }); connection->run(); } void BaseIntegrationTest::useListenerAccessLog(absl::string_view format) { listener_access_log_name_ = TestEnvironment::temporaryPath(TestUtility::uniqueFilename()); ASSERT_TRUE(config_helper_.setListenerAccessLog(listener_access_log_name_, format)); } // Assuming logs are newline delineated, return the start index of the nth entry. // If there are not n entries, it will return file.length() (end of the string // index) size_t entryIndex(const std::string& file, uint32_t entry) { size_t index = 0; for (uint32_t i = 0; i < entry; ++i) { index = file.find('\n', index); if (index == std::string::npos || index == file.length()) { return file.length(); } ++index; } return index; } std::string BaseIntegrationTest::waitForAccessLog(const std::string& filename, uint32_t entry) { // Wait a max of 1s for logs to flush to disk. for (int i = 0; i < 1000; ++i) { std::string contents = TestEnvironment::readFileToStringForTest(filename, false); size_t index = entryIndex(contents, entry); if (contents.length() > index) { return contents.substr(index); } absl::SleepFor(absl::Milliseconds(1)); } RELEASE_ASSERT(0, "Timed out waiting for access log"); return ""; } void BaseIntegrationTest::createXdsUpstream() { if (create_xds_upstream_ == false) { return; } if (tls_xds_upstream_ == false) { fake_upstreams_.emplace_back( new FakeUpstream(0, FakeHttpConnection::Type::HTTP2, version_, timeSystem())); } else { envoy::extensions::transport_sockets::tls::v3::DownstreamTlsContext tls_context; auto* common_tls_context = tls_context.mutable_common_tls_context(); common_tls_context->add_alpn_protocols(Http::Utility::AlpnNames::get().Http2); auto* tls_cert = common_tls_context->add_tls_certificates(); tls_cert->mutable_certificate_chain()->set_filename( TestEnvironment::runfilesPath("test/config/integration/certs/upstreamcert.pem")); tls_cert->mutable_private_key()->set_filename( TestEnvironment::runfilesPath("test/config/integration/certs/upstreamkey.pem")); auto cfg = std::make_unique<Extensions::TransportSockets::Tls::ServerContextConfigImpl>( tls_context, factory_context_); upstream_stats_store_ = std::make_unique<Stats::TestIsolatedStoreImpl>(); auto context = std::make_unique<Extensions::TransportSockets::Tls::ServerSslSocketFactory>( std::move(cfg), context_manager_, *upstream_stats_store_, std::vector<std::string>{}); fake_upstreams_.emplace_back(new FakeUpstream( std::move(context), 0, FakeHttpConnection::Type::HTTP2, version_, timeSystem())); } xds_upstream_ = fake_upstreams_[1].get(); // Don't ASSERT fail if an xDS reconnect ends up unparented. xds_upstream_->set_allow_unexpected_disconnects(true); } void BaseIntegrationTest::createXdsConnection() { AssertionResult result = xds_upstream_->waitForHttpConnection(*dispatcher_, xds_connection_); RELEASE_ASSERT(result, result.message()); } void BaseIntegrationTest::cleanUpXdsConnection() { AssertionResult result = xds_connection_->close(); RELEASE_ASSERT(result, result.message()); result = xds_connection_->waitForDisconnect(); RELEASE_ASSERT(result, result.message()); xds_connection_.reset(); } AssertionResult BaseIntegrationTest::compareDiscoveryRequest( const std::string& expected_type_url, const std::string& expected_version, const std::vector<std::string>& expected_resource_names, const std::vector<std::string>& expected_resource_names_added, const std::vector<std::string>& expected_resource_names_removed, bool expect_node, const Protobuf::int32 expected_error_code, const std::string& expected_error_substring) { if (sotw_or_delta_ == Grpc::SotwOrDelta::Sotw) { return compareSotwDiscoveryRequest(expected_type_url, expected_version, expected_resource_names, expect_node, expected_error_code, expected_error_substring); } else { return compareDeltaDiscoveryRequest(expected_type_url, expected_resource_names_added, expected_resource_names_removed, expected_error_code, expected_error_substring); } } AssertionResult BaseIntegrationTest::compareSotwDiscoveryRequest( const std::string& expected_type_url, const std::string& expected_version, const std::vector<std::string>& expected_resource_names, bool expect_node, const Protobuf::int32 expected_error_code, const std::string& expected_error_substring) { API_NO_BOOST(envoy::api::v2::DiscoveryRequest) discovery_request; VERIFY_ASSERTION(xds_stream_->waitForGrpcMessage(*dispatcher_, discovery_request)); if (expect_node) { EXPECT_TRUE(discovery_request.has_node()); EXPECT_FALSE(discovery_request.node().id().empty()); EXPECT_FALSE(discovery_request.node().cluster().empty()); } else { EXPECT_FALSE(discovery_request.has_node()); } if (expected_type_url != discovery_request.type_url()) { return AssertionFailure() << fmt::format("type_url {} does not match expected {}", discovery_request.type_url(), expected_type_url); } if (!(expected_error_code == discovery_request.error_detail().code())) { return AssertionFailure() << fmt::format("error_code {} does not match expected {}", discovery_request.error_detail().code(), expected_error_code); } EXPECT_TRUE( IsSubstring("", "", expected_error_substring, discovery_request.error_detail().message())); const std::vector<std::string> resource_names(discovery_request.resource_names().cbegin(), discovery_request.resource_names().cend()); if (expected_resource_names != resource_names) { return AssertionFailure() << fmt::format( "resources {} do not match expected {} in {}", absl::StrJoin(resource_names, ","), absl::StrJoin(expected_resource_names, ","), discovery_request.DebugString()); } if (expected_version != discovery_request.version_info()) { return AssertionFailure() << fmt::format("version {} does not match expected {} in {}", discovery_request.version_info(), expected_version, discovery_request.DebugString()); } return AssertionSuccess(); } AssertionResult compareSets(const std::set<std::string>& set1, const std::set<std::string>& set2, absl::string_view name) { if (set1 == set2) { return AssertionSuccess(); } auto failure = AssertionFailure() << name << " field not as expected.\nExpected: {"; for (const auto& x : set1) { failure << x << ", "; } failure << "}\nActual: {"; for (const auto& x : set2) { failure << x << ", "; } return failure << "}"; } AssertionResult BaseIntegrationTest::waitForPortAvailable(uint32_t port, std::chrono::milliseconds timeout) { const auto end_time = time_system_.monotonicTime() + timeout; while (time_system_.monotonicTime() < end_time) { try { Network::TcpListenSocket(Network::Utility::getAddressWithPort( *Network::Test::getCanonicalLoopbackAddress(version_), port), nullptr, true); return AssertionSuccess(); } catch (const EnvoyException&) { timeSystem().advanceTimeWait(std::chrono::milliseconds(100)); } } return AssertionFailure() << "Timeout waiting for port availability"; } AssertionResult BaseIntegrationTest::compareDeltaDiscoveryRequest( const std::string& expected_type_url, const std::vector<std::string>& expected_resource_subscriptions, const std::vector<std::string>& expected_resource_unsubscriptions, FakeStreamPtr& xds_stream, const Protobuf::int32 expected_error_code, const std::string& expected_error_substring) { API_NO_BOOST(envoy::api::v2::DeltaDiscoveryRequest) request; VERIFY_ASSERTION(xds_stream->waitForGrpcMessage(*dispatcher_, request)); // Verify all we care about node. if (!request.has_node() || request.node().id().empty() || request.node().cluster().empty()) { return AssertionFailure() << "Weird node field"; } if (request.type_url() != expected_type_url) { return AssertionFailure() << fmt::format("type_url {} does not match expected {}.", request.type_url(), expected_type_url); } // Sort to ignore ordering. std::set<std::string> expected_sub{expected_resource_subscriptions.begin(), expected_resource_subscriptions.end()}; std::set<std::string> expected_unsub{expected_resource_unsubscriptions.begin(), expected_resource_unsubscriptions.end()}; std::set<std::string> actual_sub{request.resource_names_subscribe().begin(), request.resource_names_subscribe().end()}; std::set<std::string> actual_unsub{request.resource_names_unsubscribe().begin(), request.resource_names_unsubscribe().end()}; auto sub_result = compareSets(expected_sub, actual_sub, "expected_resource_subscriptions"); if (!sub_result) { return sub_result; } auto unsub_result = compareSets(expected_unsub, actual_unsub, "expected_resource_unsubscriptions"); if (!unsub_result) { return unsub_result; } // (We don't care about response_nonce or initial_resource_versions.) if (request.error_detail().code() != expected_error_code) { return AssertionFailure() << fmt::format( "error code {} does not match expected {}. (Error message is {}).", request.error_detail().code(), expected_error_code, request.error_detail().message()); } if (expected_error_code != Grpc::Status::WellKnownGrpcStatus::Ok && request.error_detail().message().find(expected_error_substring) == std::string::npos) { return AssertionFailure() << "\"" << expected_error_substring << "\" is not a substring of actual error message \"" << request.error_detail().message() << "\""; } return AssertionSuccess(); } } // namespace Envoy
/* The MIT License (MIT) Copyright (c) 2013-2015 SRS(ossrs) 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. */ #ifndef SRS_APP_RTMP_CONN_HPP #define SRS_APP_RTMP_CONN_HPP /* #include <srs_app_rtmp_conn.hpp> */ #include <srs_core.hpp> #include <srs_app_st.hpp> #include <srs_app_conn.hpp> #include <srs_app_reload.hpp> #include <srs_rtmp_stack.hpp> class SrsServer; class SrsRtmpServer; class SrsRequest; class SrsResponse; class SrsSource; class SrsRefer; class SrsConsumer; class SrsCommonMessage; class SrsStSocket; #ifdef SRS_AUTO_HTTP_CALLBACK class SrsHttpHooks; #endif class SrsBandwidth; class SrsKbps; class SrsRtmpClient; class SrsSharedPtrMessage; class SrsQueueRecvThread; class SrsPublishRecvThread; class SrsSecurity; class ISrsWakable; // aes key encoder type #define SV_KEY_ENC_TYPE_NONE 0 #define SV_KEY_ENC_TYPE_RSA 1 #define SV_KEY_ENC_TYPE_BASE64 2 #define RTMP_CONNECT_DB_CONF "rtmp_connect_db" #define RTMP_CONN_INFO_TABLE_NAME "connection_info" #define RTMP_STORAGE_SPACE_INFO_NAME "storage_space_info" /** * the client provides the main logic control for RTMP clients. */ class SrsRtmpConn : public virtual SrsConnection, public virtual ISrsReloadHandler { // for the thread to directly access any field of connection. friend class SrsPublishRecvThread; private: SrsServer* server; SrsRequest* req; SrsResponse* res; SrsStSocket* skt; SrsRtmpServer* rtmp; SrsRefer* refer; SrsBandwidth* bandwidth; SrsSecurity* security; // the wakable handler, maybe NULL. ISrsWakable* wakable; // elapse duration in ms // for live play duration, for instance, rtmpdump to record. // @see https://github.com/ossrs/srs/issues/47 int64_t duration; SrsKbps* kbps; // the MR(merged-write) sleep time in ms. int mw_sleep; // the MR(merged-write) only enabled for play. int mw_enabled; // for realtime // @see https://github.com/ossrs/srs/issues/257 bool realtime; // the minimal interval in ms for delivery stream. double send_min_interval; // publish 1st packet timeout in ms int publish_1stpkt_timeout; // publish normal packet timeout in ms int publish_normal_timeout; // whether enable the tcp_nodelay. bool tcp_nodelay; // The type of client, play or publish. SrsRtmpConnType client_type; unsigned long llast_active_time; std::string m_slocal_ip; int m_nport; int64_t m_llast_ping_timestamp; int64_t m_lon_connect_timestamp; static class database_connection_manager* m_pdb_conn_mgr; public: SrsRtmpConn(SrsServer* svr, st_netfd_t c); virtual ~SrsRtmpConn(); public: virtual void dispose(); protected: virtual int do_cycle(); // interface ISrsReloadHandler public: virtual int on_reload_vhost_removed(std::string vhost); virtual int on_reload_vhost_mw(std::string vhost); virtual int on_reload_vhost_smi(std::string vhost); virtual int on_reload_vhost_tcp_nodelay(std::string vhost); virtual int on_reload_vhost_realtime(std::string vhost); virtual int on_reload_vhost_p1stpt(std::string vhost); virtual int on_reload_vhost_pnt(std::string vhost); // interface IKbpsDelta public: virtual void resample(); virtual int64_t get_send_bytes_delta(); virtual int64_t get_recv_bytes_delta(); virtual void cleanup(); #ifdef SRS_AUTO_FORWARD_WEBRTC virtual int send_metadate(SrsOnMetaDataPacket* pmetadata); #endif private: // when valid and connected to vhost/app, service the client. virtual int service_cycle(); // stream(play/publish) service cycle, identify client first. virtual int stream_service_cycle(); virtual int check_vhost(); virtual int playing(SrsSource* source); virtual int do_playing(SrsSource* source, SrsConsumer* consumer, SrsQueueRecvThread* trd); virtual int publishing(SrsSource* source); virtual int do_publishing(SrsSource* source, SrsPublishRecvThread* trd); virtual int acquire_publish(SrsSource* source, bool is_edge); virtual void release_publish(SrsSource* source, bool is_edge); virtual int handle_publish_message(SrsSource* source, SrsCommonMessage* msg, bool is_fmle, bool vhost_is_edge); virtual int process_publish_message(SrsSource* source, SrsCommonMessage* msg, bool vhost_is_edge); virtual int process_play_control_msg(SrsConsumer* consumer, SrsCommonMessage* msg); virtual void change_mw_sleep(int sleep_ms); virtual void set_sock_options(); private: virtual int check_edge_token_traverse_auth(); virtual int connect_server(int origin_index, st_netfd_t* pstsock); virtual int do_token_traverse_auth(SrsRtmpClient* client); private: virtual int http_hooks_on_authorize();// add by dawson for token authorize virtual int http_hooks_on_play_authorize(); // add by zwu for play token authorize virtual int http_hooks_on_connect(); virtual void http_hooks_on_play_close(); virtual void http_hooks_on_close(); virtual int write_database_on_close(); virtual int http_hooks_on_publish(); virtual void http_hooks_on_unpublish(); virtual int http_hooks_on_play(); virtual void http_hooks_on_stop(); virtual bool is_http_hooks_close_enable(); virtual int on_authorize(); virtual int on_connect(); virtual void on_close(); // add by dawson virtual int handle_metadata(SrsOnMetaDataPacket* metadata); virtual int load_write_data_config(); virtual int authorize_check(SrsRtmpConnType type); virtual std::string decrypt_aes_key(int enc_type, const char* enc_buf, int enc_len); int rtmp_connnection_change(int connected); bool write_rtmp_conn_enalbe(); static long llive_rtmp_conn; static long llive_svr_cycle; static long llive_publishing; SrsRtmpConnType m_ertmp_conn_type; /*#ifdef RSA_ENCRYPT_AES_KEY virtual std::string rsa_decrypt(const char* ppriv_key, const char* penc_buf, int len); #endif*/ //virtual int metadata(SrsOnMetaDataPacket* metadata); // add end }; #endif
/* * Carbon Framework Examples * Event send/receive * * Copyright (c) 2016 Softland. All rights reserved. * Licensed under the Apache License, Version 2.0 */ /* * Revision history: * * Revision 1.0, 01.06.2016 11:50:35 * Initial revision. */ #include "receiver.h" #include "event_app.h" /* * Application class constructor * * argc command line argument 'argc' * argv command line argument 'argv' */ CEventApp::CEventApp(int argc, char* argv[]) : CApplication("Event Application", MAKE_VERSION(1,0,0), 1, argc, argv), m_pReceiver(0) { } /* * Application class destructor */ CEventApp::~CEventApp() { shell_assert(m_pReceiver == 0); } /* * Application initialisation * * Return: * ESUCCESS initalisation success * other code initalisation failed, exit application */ result_t CEventApp::init() { result_t nresult; nresult = CApplication::init(); if ( nresult != ESUCCESS ) { return nresult; } log_info(L_GEN, "Custom application initialisation...\n"); /* User application inialisation */ m_pReceiver = new CReceiverModule(this); CModule* arModule[] = { m_pReceiver }; nresult = appInitModules(arModule, ARRAY_SIZE(arModule)); if ( nresult == ESUCCESS ) { CEvent* pEvent; /* * Create an event and send it to the m_pReceiver module * within the same event loop */ log_info(L_GEN, "Sending Test event...\n"); pEvent = new CEvent(EV_TEST, m_pReceiver, (PPARAM)0x1122, (NPARAM)0xEE55, "Test event"); appSendEvent(pEvent); log_info(L_GEN, "Send SIGTERM (or press Ctrl-C) to terminate...\n"); } else { log_error(L_GEN, "initialisation failed, error %d\n", nresult); CApplication::terminate(); } return nresult; } /* * Application termination */ void CEventApp::terminate() { CModule* arModule[] = { m_pReceiver }; log_info(L_GEN, "Custom application termination...\n"); /* User application termination */ appTerminateModules(arModule, ARRAY_SIZE(arModule)); SAFE_DELETE(m_pReceiver); CApplication::terminate(); } /* * Normal C/C++ entry point */ int main(int argc, char* argv[]) { CEventApp app(argc, argv); return app.run(); }
/* * Copyright © 2011,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Google Author(s): Behdad Esfahbod */ #include "options.hh" #ifdef HAVE_FREETYPE #include <hb-ft.h> #endif #include <hb-ot.h> #define DELIMITERS "<+>{},;&#\\xXuUnNiI\n\t\v\f\r " static struct supported_font_funcs_t { char name[4]; void (*func) (hb_font_t *); } supported_font_funcs[] = { #ifdef HAVE_FREETYPE {"ft", hb_ft_font_set_funcs}, #endif {"ot", hb_ot_font_set_funcs}, }; void fail (hb_bool_t suggest_help, const char *format, ...) { const char *msg; va_list vap; va_start (vap, format); msg = g_strdup_vprintf (format, vap); va_end (vap); const char *prgname = g_get_prgname (); g_printerr ("%s: %s\n", prgname, msg); if (suggest_help) g_printerr ("Try `%s --help' for more information.\n", prgname); exit (1); } static gchar * shapers_to_string () { GString *shapers = g_string_new (nullptr); const char **shaper_list = hb_shape_list_shapers (); for (; *shaper_list; shaper_list++) { g_string_append (shapers, *shaper_list); g_string_append_c (shapers, ','); } g_string_truncate (shapers, MAX (0, (gint)shapers->len - 1)); return g_string_free (shapers, false); } static G_GNUC_NORETURN gboolean show_version (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { g_printf ("%s (%s) %s\n", g_get_prgname (), PACKAGE_NAME, PACKAGE_VERSION); char *shapers = shapers_to_string (); g_printf ("Available shapers: %s\n", shapers); g_free (shapers); if (strcmp (HB_VERSION_STRING, hb_version_string ())) g_printf ("Linked HarfBuzz library has a different version: %s\n", hb_version_string ()); exit(0); } void option_parser_t::add_main_options () { GOptionEntry entries[] = { {"version", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &show_version, "Show version numbers", nullptr}, {nullptr} }; g_option_context_add_main_entries (context, entries, nullptr); } static gboolean pre_parse (GOptionContext *context G_GNUC_UNUSED, GOptionGroup *group G_GNUC_UNUSED, gpointer data, GError **error) { option_group_t *option_group = (option_group_t *) data; option_group->pre_parse (error); return *error == nullptr; } static gboolean post_parse (GOptionContext *context G_GNUC_UNUSED, GOptionGroup *group G_GNUC_UNUSED, gpointer data, GError **error) { option_group_t *option_group = static_cast<option_group_t *>(data); option_group->post_parse (error); return *error == nullptr; } void option_parser_t::add_group (GOptionEntry *entries, const gchar *name, const gchar *description, const gchar *help_description, option_group_t *option_group) { GOptionGroup *group = g_option_group_new (name, description, help_description, static_cast<gpointer>(option_group), nullptr); g_option_group_add_entries (group, entries); g_option_group_set_parse_hooks (group, pre_parse, post_parse); g_option_context_add_group (context, group); } void option_parser_t::parse (int *argc, char ***argv) { setlocale (LC_ALL, ""); GError *parse_error = nullptr; if (!g_option_context_parse (context, argc, argv, &parse_error)) { if (parse_error != nullptr) { fail (true, "%s", parse_error->message); //g_error_free (parse_error); } else fail (true, "Option parse error"); } } static gboolean parse_margin (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { view_options_t *view_opts = (view_options_t *) data; view_options_t::margin_t &m = view_opts->margin; switch (sscanf (arg, "%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &m.t, &m.r, &m.b, &m.l)) { case 1: m.r = m.t; HB_FALLTHROUGH; case 2: m.b = m.t; HB_FALLTHROUGH; case 3: m.l = m.r; HB_FALLTHROUGH; case 4: return true; default: g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "%s argument should be one to four space-separated numbers", name); return false; } } static gboolean parse_shapers (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error) { shape_options_t *shape_opts = (shape_options_t *) data; char **shapers = g_strsplit (arg, ",", 0); for (char **shaper = shapers; *shaper; shaper++) { bool found = false; for (const char **hb_shaper = hb_shape_list_shapers (); *hb_shaper; hb_shaper++) { if (strcmp (*shaper, *hb_shaper) == 0) { found = true; break; } } if (!found) { g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Unknown or unsupported shaper: %s", *shaper); g_strfreev (shapers); return false; } } g_strfreev (shape_opts->shapers); shape_opts->shapers = shapers; return true; } static G_GNUC_NORETURN gboolean list_shapers (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { for (const char **shaper = hb_shape_list_shapers (); *shaper; shaper++) g_printf ("%s\n", *shaper); exit(0); } static gboolean parse_features (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { shape_options_t *shape_opts = (shape_options_t *) data; char *s = (char *) arg; char *p; shape_opts->num_features = 0; g_free (shape_opts->features); shape_opts->features = nullptr; if (!*s) return true; /* count the features first, so we can allocate memory */ p = s; do { shape_opts->num_features++; p = strchr (p, ','); if (p) p++; } while (p); shape_opts->features = (hb_feature_t *) calloc (shape_opts->num_features, sizeof (*shape_opts->features)); if (!shape_opts->features) return false; /* now do the actual parsing */ p = s; shape_opts->num_features = 0; while (p && *p) { char *end = strchr (p, ','); if (hb_feature_from_string (p, end ? end - p : -1, &shape_opts->features[shape_opts->num_features])) shape_opts->num_features++; p = end ? end + 1 : nullptr; } return true; } static gboolean parse_variations (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { font_options_t *font_opts = (font_options_t *) data; char *s = (char *) arg; char *p; font_opts->num_variations = 0; g_free (font_opts->variations); font_opts->variations = nullptr; if (!*s) return true; /* count the variations first, so we can allocate memory */ p = s; do { font_opts->num_variations++; p = strchr (p, ','); if (p) p++; } while (p); font_opts->variations = (hb_variation_t *) calloc (font_opts->num_variations, sizeof (*font_opts->variations)); if (!font_opts->variations) return false; /* now do the actual parsing */ p = s; font_opts->num_variations = 0; while (p && *p) { char *end = strchr (p, ','); if (hb_variation_from_string (p, end ? end - p : -1, &font_opts->variations[font_opts->num_variations])) font_opts->num_variations++; p = end ? end + 1 : nullptr; } return true; } static gboolean parse_text (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { text_options_t *text_opts = (text_options_t *) data; if (text_opts->text) { g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Either --text or --unicodes can be provided but not both"); return false; } text_opts->text_len = -1; text_opts->text = g_strdup (arg); return true; } static gboolean parse_unicodes (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { text_options_t *text_opts = (text_options_t *) data; if (text_opts->text) { g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Either --text or --unicodes can be provided but not both"); return false; } GString *gs = g_string_new (nullptr); if (0 == strcmp (arg, "*")) { g_string_append_c (gs, '*'); } else { char *s = (char *) arg; char *p; while (s && *s) { while (*s && strchr (DELIMITERS, *s)) s++; if (!*s) break; errno = 0; hb_codepoint_t u = strtoul (s, &p, 16); if (errno || s == p) { g_string_free (gs, TRUE); g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Failed parsing Unicode values at: '%s'", s); return false; } g_string_append_unichar (gs, u); s = p; } } text_opts->text_len = gs->len; text_opts->text = g_string_free (gs, FALSE); return true; } void view_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"annotate", 0, 0, G_OPTION_ARG_NONE, &this->annotate, "Annotate output rendering", nullptr}, {"background", 0, 0, G_OPTION_ARG_STRING, &this->back, "Set background color (default: " DEFAULT_BACK ")", "rrggbb/rrggbbaa"}, {"foreground", 0, 0, G_OPTION_ARG_STRING, &this->fore, "Set foreground color (default: " DEFAULT_FORE ")", "rrggbb/rrggbbaa"}, {"line-space", 0, 0, G_OPTION_ARG_DOUBLE, &this->line_space, "Set space between lines (default: 0)", "units"}, {"margin", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_margin, "Margin around output (default: " G_STRINGIFY(DEFAULT_MARGIN) ")","one to four numbers"}, {nullptr} }; parser->add_group (entries, "view", "View options:", "Options for output rendering", this); } void shape_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"list-shapers", 0, G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &list_shapers, "List available shapers and quit", nullptr}, {"shaper", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, (gpointer) &parse_shapers, "Hidden duplicate of --shapers", nullptr}, {"shapers", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_shapers, "Set comma-separated list of shapers to try","list"}, {"direction", 0, 0, G_OPTION_ARG_STRING, &this->direction, "Set text direction (default: auto)", "ltr/rtl/ttb/btt"}, {"language", 0, 0, G_OPTION_ARG_STRING, &this->language, "Set text language (default: $LANG)", "langstr"}, {"script", 0, 0, G_OPTION_ARG_STRING, &this->script, "Set text script (default: auto)", "ISO-15924 tag"}, {"bot", 0, 0, G_OPTION_ARG_NONE, &this->bot, "Treat text as beginning-of-paragraph", nullptr}, {"eot", 0, 0, G_OPTION_ARG_NONE, &this->eot, "Treat text as end-of-paragraph", nullptr}, {"preserve-default-ignorables",0, 0, G_OPTION_ARG_NONE, &this->preserve_default_ignorables, "Preserve Default-Ignorable characters", nullptr}, {"remove-default-ignorables",0, 0, G_OPTION_ARG_NONE, &this->remove_default_ignorables, "Remove Default-Ignorable characters", nullptr}, {"invisible-glyph", 0, 0, G_OPTION_ARG_INT, &this->invisible_glyph, "Glyph value to replace Default-Ignorables with", nullptr}, {"utf8-clusters", 0, 0, G_OPTION_ARG_NONE, &this->utf8_clusters, "Use UTF8 byte indices, not char indices", nullptr}, {"cluster-level", 0, 0, G_OPTION_ARG_INT, &this->cluster_level, "Cluster merging level (default: 0)", "0/1/2"}, {"normalize-glyphs",0, 0, G_OPTION_ARG_NONE, &this->normalize_glyphs, "Rearrange glyph clusters in nominal order", nullptr}, {"verify", 0, 0, G_OPTION_ARG_NONE, &this->verify, "Perform sanity checks on shaping results", nullptr}, {"num-iterations", 'n', 0, G_OPTION_ARG_INT, &this->num_iterations, "Run shaper N times (default: 1)", "N"}, {nullptr} }; parser->add_group (entries, "shape", "Shape options:", "Options for the shaping process", this); const gchar *features_help = "Comma-separated list of font features\n" "\n" " Features can be enabled or disabled, either globally or limited to\n" " specific character ranges. The format for specifying feature settings\n" " follows. All valid CSS font-feature-settings values other than 'normal'\n" " and the global values are also accepted, though not documented below.\n" " CSS string escapes are not supported." "\n" " The range indices refer to the positions between Unicode characters,\n" " unless the --utf8-clusters is provided, in which case range indices\n" " refer to UTF-8 byte indices. The position before the first character\n" " is always 0.\n" "\n" " The format is Python-esque. Here is how it all works:\n" "\n" " Syntax: Value: Start: End:\n" "\n" " Setting value:\n" " \"kern\" 1 0 ∞ # Turn feature on\n" " \"+kern\" 1 0 ∞ # Turn feature on\n" " \"-kern\" 0 0 ∞ # Turn feature off\n" " \"kern=0\" 0 0 ∞ # Turn feature off\n" " \"kern=1\" 1 0 ∞ # Turn feature on\n" " \"aalt=2\" 2 0 ∞ # Choose 2nd alternate\n" "\n" " Setting index:\n" " \"kern[]\" 1 0 ∞ # Turn feature on\n" " \"kern[:]\" 1 0 ∞ # Turn feature on\n" " \"kern[5:]\" 1 5 ∞ # Turn feature on, partial\n" " \"kern[:5]\" 1 0 5 # Turn feature on, partial\n" " \"kern[3:5]\" 1 3 5 # Turn feature on, range\n" " \"kern[3]\" 1 3 3+1 # Turn feature on, single char\n" "\n" " Mixing it all:\n" "\n" " \"aalt[3:5]=2\" 2 3 5 # Turn 2nd alternate on for range"; GOptionEntry entries2[] = { {"features", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_features, features_help, "list"}, {nullptr} }; parser->add_group (entries2, "features", "Features options:", "Options for font features used", this); } static gboolean parse_font_size (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { font_options_t *font_opts = (font_options_t *) data; if (0 == strcmp (arg, "upem")) { font_opts->font_size_y = font_opts->font_size_x = FONT_SIZE_UPEM; return true; } switch (sscanf (arg, "%lf%*[ ,]%lf", &font_opts->font_size_x, &font_opts->font_size_y)) { case 1: font_opts->font_size_y = font_opts->font_size_x; HB_FALLTHROUGH; case 2: return true; default: g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "%s argument should be one or two space-separated numbers", name); return false; } } static gboolean parse_font_ppem (const char *name G_GNUC_UNUSED, const char *arg, gpointer data, GError **error G_GNUC_UNUSED) { font_options_t *font_opts = (font_options_t *) data; switch (sscanf (arg, "%d%*[ ,]%d", &font_opts->x_ppem, &font_opts->y_ppem)) { case 1: font_opts->y_ppem = font_opts->x_ppem; HB_FALLTHROUGH; case 2: return true; default: g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "%s argument should be one or two space-separated numbers", name); return false; } } void font_options_t::add_options (option_parser_t *parser) { char *text = nullptr; { static_assert ((ARRAY_LENGTH_CONST (supported_font_funcs) > 0), "No supported font-funcs found."); GString *s = g_string_new (nullptr); g_string_printf (s, "Set font functions implementation to use (default: %s)\n\n Supported font function implementations are: %s", supported_font_funcs[0].name, supported_font_funcs[0].name); for (unsigned int i = 1; i < ARRAY_LENGTH (supported_font_funcs); i++) { g_string_append_c (s, '/'); g_string_append (s, supported_font_funcs[i].name); } text = g_string_free (s, FALSE); parser->free_later (text); } char *font_size_text; if (default_font_size == FONT_SIZE_UPEM) font_size_text = (char *) "Font size (default: upem)"; else { font_size_text = g_strdup_printf ("Font size (default: %d)", default_font_size); parser->free_later (font_size_text); } GOptionEntry entries[] = { {"font-file", 0, 0, G_OPTION_ARG_STRING, &this->font_file, "Set font file-name", "filename"}, {"face-index", 0, 0, G_OPTION_ARG_INT, &this->face_index, "Set face index (default: 0)", "index"}, {"font-size", 0, default_font_size ? 0 : G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_CALLBACK, (gpointer) &parse_font_size, font_size_text, "1/2 integers or 'upem'"}, {"font-ppem", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_font_ppem, "Set x,y pixels per EM (default: 0; disabled)", "1/2 integers"}, {"font-ptem", 0, 0, G_OPTION_ARG_DOUBLE, &this->ptem, "Set font point-size (default: 0; disabled)", "point-size"}, {"font-funcs", 0, 0, G_OPTION_ARG_STRING, &this->font_funcs, text, "impl"}, {"ft-load-flags", 0, 0, G_OPTION_ARG_INT, &this->ft_load_flags, "Set FreeType load-flags (default: 2)", "integer"}, {nullptr} }; parser->add_group (entries, "font", "Font options:", "Options for the font", this); const gchar *variations_help = "Comma-separated list of font variations\n" "\n" " Variations are set globally. The format for specifying variation settings\n" " follows. All valid CSS font-variation-settings values other than 'normal'\n" " and 'inherited' are also accepted, though, not documented below.\n" "\n" " The format is a tag, optionally followed by an equals sign, followed by a\n" " number. For example:\n" "\n" " \"wght=500\"\n" " \"slnt=-7.5\"\n"; GOptionEntry entries2[] = { {"variations", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_variations, variations_help, "list"}, {nullptr} }; parser->add_group (entries2, "variations", "Variations options:", "Options for font variations used", this); } void text_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"text", 0, 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_text, "Set input text", "string"}, {"text-file", 0, 0, G_OPTION_ARG_STRING, &this->text_file, "Set input text file-name\n\n If no text is provided, standard input is used for input.\n", "filename"}, {"unicodes", 'u', 0, G_OPTION_ARG_CALLBACK, (gpointer) &parse_unicodes, "Set input Unicode codepoints", "list of hex numbers"}, {"text-before", 0, 0, G_OPTION_ARG_STRING, &this->text_before, "Set text context before each line", "string"}, {"text-after", 0, 0, G_OPTION_ARG_STRING, &this->text_after, "Set text context after each line", "string"}, {nullptr} }; parser->add_group (entries, "text", "Text options:", "Options for the input text", this); } void output_options_t::add_options (option_parser_t *parser) { const char *text; if (nullptr == supported_formats) text = "Set output serialization format"; else { char *items = g_strjoinv ("/", const_cast<char **> (supported_formats)); text = g_strdup_printf ("Set output format\n\n Supported output formats are: %s", items); g_free (items); parser->free_later ((char *) text); } GOptionEntry entries[] = { {"output-file", 'o', 0, G_OPTION_ARG_STRING, &this->output_file, "Set output file-name (default: stdout)","filename"}, {"output-format", 'O', 0, G_OPTION_ARG_STRING, &this->output_format, text, "format"}, {nullptr} }; parser->add_group (entries, "output", "Output destination & format options:", "Options for the destination & form of the output", this); } hb_font_t * font_options_t::get_font () const { if (font) return font; /* Create the blob */ if (!font_file) fail (true, "No font file set"); const char *font_path = font_file; if (0 == strcmp (font_path, "-")) { #if defined(_WIN32) || defined(__CYGWIN__) setmode (fileno (stdin), O_BINARY); font_path = "STDIN"; #else font_path = "/dev/stdin"; #endif } blob = hb_blob_create_from_file (font_path); if (blob == hb_blob_get_empty ()) fail (false, "Couldn't read or find %s, or it was empty.", font_path); /* Create the face */ hb_face_t *face = hb_face_create (blob, face_index); hb_blob_destroy (blob); font = hb_font_create (face); if (font_size_x == FONT_SIZE_UPEM) font_size_x = hb_face_get_upem (face); if (font_size_y == FONT_SIZE_UPEM) font_size_y = hb_face_get_upem (face); hb_font_set_ppem (font, x_ppem, y_ppem); hb_font_set_ptem (font, ptem); int scale_x = (int) scalbnf (font_size_x, subpixel_bits); int scale_y = (int) scalbnf (font_size_y, subpixel_bits); hb_font_set_scale (font, scale_x, scale_y); hb_face_destroy (face); hb_font_set_variations (font, variations, num_variations); void (*set_font_funcs) (hb_font_t *) = nullptr; if (!font_funcs) { set_font_funcs = supported_font_funcs[0].func; } else { for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++) if (0 == g_ascii_strcasecmp (font_funcs, supported_font_funcs[i].name)) { set_font_funcs = supported_font_funcs[i].func; break; } if (!set_font_funcs) { GString *s = g_string_new (nullptr); for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++) { if (i) g_string_append_c (s, '/'); g_string_append (s, supported_font_funcs[i].name); } char *p = g_string_free (s, FALSE); fail (false, "Unknown font function implementation `%s'; supported values are: %s; default is %s", font_funcs, p, supported_font_funcs[0].name); //free (p); } } set_font_funcs (font); #ifdef HAVE_FREETYPE hb_ft_font_set_load_flags (font, ft_load_flags); #endif return font; } const char * text_options_t::get_line (unsigned int *len) { if (text) { if (!line) { line = text; line_len = text_len; } if (line_len == (unsigned int) -1) line_len = strlen (line); if (!line_len) { *len = 0; return nullptr; } const char *ret = line; const char *p = (const char *) memchr (line, '\n', line_len); unsigned int ret_len; if (!p) { ret_len = line_len; line += ret_len; line_len = 0; } else { ret_len = p - ret; line += ret_len + 1; line_len -= ret_len + 1; } *len = ret_len; return ret; } if (!fp) { if (!text_file) fail (true, "At least one of text or text-file must be set"); if (0 != strcmp (text_file, "-")) fp = fopen (text_file, "r"); else fp = stdin; if (!fp) fail (false, "Failed opening text file `%s': %s", text_file, strerror (errno)); gs = g_string_new (nullptr); } g_string_set_size (gs, 0); char buf[BUFSIZ]; while (fgets (buf, sizeof (buf), fp)) { unsigned int bytes = strlen (buf); if (bytes && buf[bytes - 1] == '\n') { bytes--; g_string_append_len (gs, buf, bytes); break; } g_string_append_len (gs, buf, bytes); } if (ferror (fp)) fail (false, "Failed reading text: %s", strerror (errno)); *len = gs->len; return !*len && feof (fp) ? nullptr : gs->str; } FILE * output_options_t::get_file_handle () { if (fp) return fp; if (output_file) fp = fopen (output_file, "wb"); else { #if defined(_WIN32) || defined(__CYGWIN__) setmode (fileno (stdout), O_BINARY); #endif fp = stdout; } if (!fp) fail (false, "Cannot open output file `%s': %s", g_filename_display_name (output_file), strerror (errno)); return fp; } static gboolean parse_verbose (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { format_options_t *format_opts = (format_options_t *) data; format_opts->show_text = format_opts->show_unicode = format_opts->show_line_num = true; return true; } static gboolean parse_ned (const char *name G_GNUC_UNUSED, const char *arg G_GNUC_UNUSED, gpointer data G_GNUC_UNUSED, GError **error G_GNUC_UNUSED) { format_options_t *format_opts = (format_options_t *) data; format_opts->show_clusters = format_opts->show_advances = false; return true; } void format_options_t::add_options (option_parser_t *parser) { GOptionEntry entries[] = { {"show-text", 0, 0, G_OPTION_ARG_NONE, &this->show_text, "Prefix each line of output with its corresponding input text", nullptr}, {"show-unicode", 0, 0, G_OPTION_ARG_NONE, &this->show_unicode, "Prefix each line of output with its corresponding input codepoint(s)", nullptr}, {"show-line-num", 0, 0, G_OPTION_ARG_NONE, &this->show_line_num, "Prefix each line of output with its corresponding input line number", nullptr}, {"verbose", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &parse_verbose, "Prefix each line of output with all of the above", nullptr}, {"no-glyph-names", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_glyph_names, "Output glyph indices instead of names", nullptr}, {"no-positions", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_positions, "Do not output glyph positions", nullptr}, {"no-advances", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_advances, "Do not output glyph advances", nullptr}, {"no-clusters", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &this->show_clusters, "Do not output cluster indices", nullptr}, {"show-extents", 0, 0, G_OPTION_ARG_NONE, &this->show_extents, "Output glyph extents", nullptr}, {"show-flags", 0, 0, G_OPTION_ARG_NONE, &this->show_flags, "Output glyph flags", nullptr}, {"ned", 'v', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_CALLBACK, (gpointer) &parse_ned, "No Extra Data; Do not output clusters or advances", nullptr}, {"trace", 'V', 0, G_OPTION_ARG_NONE, &this->trace, "Output interim shaping results", nullptr}, {nullptr} }; parser->add_group (entries, "output-syntax", "Output syntax:\n" " text: [<glyph name or index>=<glyph cluster index within input>@<horizontal displacement>,<vertical displacement>+<horizontal advance>,<vertical advance>|...]\n" " json: [{\"g\": <glyph name or index>, \"ax\": <horizontal advance>, \"ay\": <vertical advance>, \"dx\": <horizontal displacement>, \"dy\": <vertical displacement>, \"cl\": <glyph cluster index within input>}, ...]\n" "\nOutput syntax options:", "Options for the syntax of the output", this); } void format_options_t::serialize_unicode (hb_buffer_t *buffer, GString *gs) { unsigned int num_glyphs = hb_buffer_get_length (buffer); hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buffer, nullptr); g_string_append_c (gs, '<'); for (unsigned int i = 0; i < num_glyphs; i++) { if (i) g_string_append_c (gs, ','); g_string_append_printf (gs, "U+%04X", info->codepoint); info++; } g_string_append_c (gs, '>'); } void format_options_t::serialize_glyphs (hb_buffer_t *buffer, hb_font_t *font, hb_buffer_serialize_format_t output_format, hb_buffer_serialize_flags_t flags, GString *gs) { g_string_append_c (gs, '['); unsigned int num_glyphs = hb_buffer_get_length (buffer); unsigned int start = 0; while (start < num_glyphs) { char buf[1024]; unsigned int consumed; start += hb_buffer_serialize_glyphs (buffer, start, num_glyphs, buf, sizeof (buf), &consumed, font, output_format, flags); if (!consumed) break; g_string_append (gs, buf); } g_string_append_c (gs, ']'); } void format_options_t::serialize_line_no (unsigned int line_no, GString *gs) { if (show_line_num) g_string_append_printf (gs, "%d: ", line_no); } void format_options_t::serialize_buffer_of_text (hb_buffer_t *buffer, unsigned int line_no, const char *text, unsigned int text_len, hb_font_t *font, GString *gs) { if (show_text) { serialize_line_no (line_no, gs); g_string_append_c (gs, '('); g_string_append_len (gs, text, text_len); g_string_append_c (gs, ')'); g_string_append_c (gs, '\n'); } if (show_unicode) { serialize_line_no (line_no, gs); serialize_unicode (buffer, gs); g_string_append_c (gs, '\n'); } } void format_options_t::serialize_message (unsigned int line_no, const char *type, const char *msg, GString *gs) { serialize_line_no (line_no, gs); g_string_append_printf (gs, "%s: %s", type, msg); g_string_append_c (gs, '\n'); } void format_options_t::serialize_buffer_of_glyphs (hb_buffer_t *buffer, unsigned int line_no, const char *text, unsigned int text_len, hb_font_t *font, hb_buffer_serialize_format_t output_format, hb_buffer_serialize_flags_t format_flags, GString *gs) { serialize_line_no (line_no, gs); serialize_glyphs (buffer, font, output_format, format_flags, gs); g_string_append_c (gs, '\n'); }
/** @file * * @ingroup dspFilterLib * * @brief Unit test for the FilterLib #TTHighpassButterworth2 class. * * @details Currently this test is just a stub * * @authors Trond Lossius, Tim Place * * @copyright Copyright © 2012 by Trond Lossius & Timothy Place @n * This code is licensed under the terms of the "New BSD License" @n * http://creativecommons.org/licenses/BSD/ */ #include "TTHighpassButterworth2.h" TTErr TTHighpassButterworth2::test(TTValue& returnedTestInfo) { int errorCount = 0; int testAssertionCount = 0; // Wrap up the test results to pass back to whoever called this test return TTTestFinish(testAssertionCount, errorCount, returnedTestInfo); }
// Copyright (c) 2014-2018 The Readercoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <qt/winshutdownmonitor.h> #if defined(Q_OS_WIN) #include <shutdown.h> #include <util/system.h> #include <windows.h> #include <QDebug> #include <openssl/rand.h> // If we don't want a message to be processed by Qt, return true and set result to // the value that the window procedure should return. Otherwise return false. bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult) { Q_UNUSED(eventType); MSG *pMsg = static_cast<MSG *>(pMessage); // Seed OpenSSL PRNG with Windows event data (e.g. mouse movements and other user interactions) if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) { // Warn only once as this is performance-critical static bool warned = false; if (!warned) { LogPrintf("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__); warned = true; } } switch(pMsg->message) { case WM_QUERYENDSESSION: { // Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block // Windows session end until we have finished client shutdown. StartShutdown(); *pnResult = FALSE; return true; } case WM_ENDSESSION: { *pnResult = FALSE; return true; } } return false; } void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId) { typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR); PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate"); if (shutdownBRCreate == nullptr) { qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed"; return; } if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str())) qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason; else qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason; } #endif
//-------------------------------------------------------------------------- // MIT License // // Copyright (c) 2021 Yoshiya Usui // // 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 "NodeList.h" #include "OutputFiles.h" #include <iostream> #include <iomanip> #include <stdlib.h> //// Return the instance of the class //NodeList* NodeList::getInstance(){ // static NodeList instance;// The only instance // return &instance; //} // Default constructer NodeList::NodeList() { } // Destructer NodeList::~NodeList(){ } // Clear list of nodes void NodeList::clearList(){ m_nodes.clear(); } // Add new node and return the ID of the node int NodeList::addNewNode( const Node& node ){ m_nodes.push_back( node ); return static_cast<int>( m_nodes.size() ) - 1; } // Get total number of nodes int NodeList::getTotalNumberOfNode() const{ return static_cast<int>( m_nodes.size() ); } // Set coordinates of node void NodeList::setCoordOfPoints( const int id, const CommonParameters::XY& coord ){ if( id < 0 || id >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << "Error : ID of point is out of range at the function " << __FUNCTION__ << " !! ID = " << id << std::endl; exit(1); } m_nodes[id].setCoordXY( coord ); } // Get coordinates of node CommonParameters::XY NodeList::getCoordXYOfPoints( const int id ) const{ if( id < 0 || id >= static_cast<int>( m_nodes.size() ) ){ //OutputFiles::m_logFile << "Error : ID of point is out of range !! ID = " << id << std::endl; OutputFiles::m_logFile << "Error : ID of point is out of range at the function " << __FUNCTION__ << " !! ID = " << id << std::endl; exit(1); } return m_nodes[id].getCoordXY(); } // Get coordinates of node CommonParameters::XYZ NodeList::getCoordXYZOfPoints( const int id ) const{ if( id < 0 || id >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << "Error : ID of point is out of range at the function " << __FUNCTION__ << " !! ID = " << id << std::endl; exit(1); } return m_nodes[id].getCoordXYZ(); } // Get pointer to the node of the boundary Node* NodeList::getPointerToNode( const int id ){ if( id < 0 || id >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << "Error : ID of point is out of range at the function " << __FUNCTION__ << " !! ID = " << id << std::endl; exit(1); } return &m_nodes[id]; } // Make all node to be fixed void NodeList::makeAllNodeFixed(){ std::vector<Node>::iterator itrEnd = m_nodes.end(); for( std::vector<Node>::iterator itr = m_nodes.begin(); itr != itrEnd; ++itr ){ itr->fixThisNode(); } } // Write nodes of 2D mesh to VTK file void NodeList::writeNode2DListToVTK( const std::string& fileName ) const{ std::ofstream ofsVTK( fileName.c_str() ); if( !ofsVTK ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << std::endl; exit(1); } ofsVTK << "# vtk DataFile Version 2.0" << std::endl; ofsVTK << "NodeList" << std::endl; ofsVTK << "ASCII" << std::endl; ofsVTK << "DATASET UNSTRUCTURED_GRID" << std::endl; ofsVTK.precision(9); ofsVTK << std::fixed; const int numPointsAll = static_cast<int>( m_nodes.size() ); ofsVTK << "POINTS " << numPointsAll << " float" << std::endl; std::vector<Node>::const_iterator itrEnd = m_nodes.end(); for( std::vector<Node>::const_iterator itr = m_nodes.begin(); itr != itrEnd; ++itr ){ ofsVTK << itr->getCoordX() << " " << itr->getCoordY() << " " << 0.0 << std::endl; } ofsVTK << "CELLS " << numPointsAll << " " << numPointsAll * 2 << std::endl; for( int i = 0; i < numPointsAll; ++i ){ ofsVTK << 1 << " " << i << std::endl; } ofsVTK << "CELL_TYPES " << numPointsAll << std::endl; for( int i = 0; i < numPointsAll; ++i ){ ofsVTK << "1" << std::endl; } ofsVTK << "CELL_DATA " << numPointsAll << std::endl; ofsVTK << "SCALARS Location int" << std::endl; ofsVTK << "LOOKUP_TABLE default" << std::endl; for( std::vector<Node>::const_iterator itr = m_nodes.begin(); itr != itrEnd; ++itr ){ ofsVTK << itr->getLocation() << std::endl; } ofsVTK.close(); } // Write node list of 2D mesh to intermediate file after step 1 void NodeList::writeNode2DListToIntermediateFileStep1( const std::string& fileName ) const{ std::ofstream ofs( fileName.c_str() ); if( !ofs.is_open() ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << " !!" << std::endl; exit(1); } const int numNodes = static_cast<int>( m_nodes.size() ); ofs << std::setw(10) << numNodes << std::endl; int icount(0); ofs.precision(12); for( std::vector<Node>::const_iterator itr = m_nodes.begin(); itr != m_nodes.end(); ++itr ){ ofs << std::setw(10) << icount++; ofs << std::setw(25) << std::scientific << itr->getCoordX() << std::setw(25) << std::scientific << itr->getCoordY() << std::setw(25) << std::scientific << 0.0 << std::endl; } ofs.close(); } // Write node list of 2D mesh without the ones of supert triangle to intermediate file after step 2 void NodeList::writeNode2DListToIntermediateFileStep2( const std::string& fileName ) const{ std::ofstream ofs( fileName.c_str() ); if( !ofs.is_open() ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << " !!" << std::endl; exit(1); } const int numNodes = static_cast<int>( m_nodes.size() ) - 3; ofs << std::setw(10) << numNodes << std::endl; int icount(0); ofs.precision(12); std::vector<Node>::const_iterator itr = m_nodes.begin(); advance( itr, 3 ); for( ; itr != m_nodes.end(); ++itr ){ ofs << std::setw(10) << icount++; ofs << std::setw(25) << std::scientific << itr->getCoordX() << std::setw(25) << std::scientific << itr->getCoordY() << std::setw(25) << std::scientific << 0.0 << std::endl; } ofs.close(); } // Write node list of mesh without the ones of supert triangle to intermediate file after step 3 void NodeList::writeNodeListToIntermediateFileStep3( const std::string& fileName ) const{ std::ofstream ofs( fileName.c_str() ); if( !ofs.is_open() ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << " !!" << std::endl; exit(1); } const int numNodes = static_cast<int>( m_nodes.size() ); ofs << std::setw(10) << numNodes << std::endl; int icount(0); ofs.precision(12); for( std::vector<Node>::const_iterator itr = m_nodes.begin(); itr != m_nodes.end(); ++itr ){ ofs << std::setw(10) << icount++; ofs << std::setw(25) << std::scientific << itr->getCoordX() << std::setw(25) << std::scientific << itr->getCoordY() << std::setw(25) << std::scientific << itr->getCoordZ() << std::setw(10) << std::scientific << itr->getLocation() << std::endl; } ofs.close(); } // Read node list of 2D mesh from intermediate file void NodeList::readNode2DListFromIntermediateFile( const std::string& fileName ){ std::ifstream ifs( fileName.c_str() ); if( !ifs.is_open() ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << " !!" << std::endl; exit(1); } OutputFiles::m_logFile << "# Read node list of 2D mesh from " << fileName.c_str() << std::endl; int numNodes(0); ifs >> numNodes; int ibuf(0); double dbuf(0.0); for( int iNode = 0; iNode < numNodes; ++iNode ){ ifs >> ibuf; if( ibuf != iNode ){ OutputFiles::m_logFile << " Error : Node ID must be sequence number from 0 in " << fileName << " !!" << std::endl; exit(1); } CommonParameters::XY coord = { 0.0, 0.0 }; ifs >> coord.X >> coord.Y >> dbuf; m_nodes.push_back( Node( coord, true ) ); } ifs.close(); } // Set node list of 2D mesh void NodeList::setNode2DList( const int numNodes, const CommonParameters::XY* coord2D ){ for( int iNode = 0; iNode < numNodes; ++iNode ){ m_nodes.push_back( Node( coord2D[iNode], true ) ); } } // Read node list of mesh from intermediate file after step 3 void NodeList::readNodeListFromIntermediateFileStep3( const std::string& fileName ){ std::ifstream ifs( fileName.c_str() ); if( !ifs.is_open() ) { OutputFiles::m_logFile << " Error : Cannot open file " << fileName.c_str() << " !!" << std::endl; exit(1); } OutputFiles::m_logFile << "# Read node list of mesh from " << fileName.c_str() << std::endl; int numNodes(0); ifs >> numNodes; int ibuf(0); for( int iNode = 0; iNode < numNodes; ++iNode ){ ifs >> ibuf; if( ibuf != iNode ){ OutputFiles::m_logFile << " Error : Node ID must be sequence number from 0 in " << fileName << " !!" << std::endl; exit(1); } CommonParameters::XYZ coord = { 0.0, 0.0, 0.0 }; ifs >> coord.X >> coord.Y >> coord.Z; int location(CommonParameters::UNKNOWN); ifs >> location; m_nodes.push_back( Node( coord, true, location ) ); } ifs.close(); } // Add IDs of triangles sharing the specified node void NodeList::addTriangleIDs( const int nodeID, const int triangleID ){ if( nodeID < 0 || nodeID >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << " Error : Node ID specified to be added ( " << nodeID << " ) is out of range !!" << std::endl; exit(1); } m_nodes[nodeID].addTriangleIDs( triangleID ); } // Get IDs of triangles sharing the specified node std::vector<int> NodeList::getTriangleIDs( const int nodeID ) const{ if( nodeID < 0 || nodeID >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << " Error : Node ID ( " << nodeID << " ) is out of range !!" << std::endl; exit(1); } return m_nodes[nodeID].getTriangleIDs(); } // Initialize node list void NodeList::initializeNodeList(){ m_nodes.clear(); } // Remove specified node void NodeList::removeNode( const int nodeID ){ if( nodeID < 0 || nodeID >= static_cast<int>( m_nodes.size() ) ){ OutputFiles::m_logFile << " Error : Node ID specified to be removed ( " << nodeID << " ) is out of range !!" << std::endl; exit(1); } std::vector<Node>::iterator itr = m_nodes.begin(); advance( itr, nodeID ); m_nodes.erase( itr ); }
// Copyright 2017 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/browser/devtools/protocol/devtools_download_manager_delegate.h" #include "base/bind.h" #include "base/files/file_util.h" #include "base/task_scheduler/post_task.h" #include "base/threading/thread_restrictions.h" #include "content/browser/devtools/protocol/devtools_download_manager_helper.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/download_item_utils.h" #include "content/public/browser/download_manager.h" #include "net/base/filename_util.h" namespace content { class WebContents; namespace protocol { namespace { DevToolsDownloadManagerDelegate* g_devtools_manager_delegate = nullptr; } // namespace DevToolsDownloadManagerDelegate::DevToolsDownloadManagerDelegate() : download_manager_(nullptr), proxy_download_delegate_(nullptr) { g_devtools_manager_delegate = this; } // static DevToolsDownloadManagerDelegate* DevToolsDownloadManagerDelegate::GetInstance() { if (!g_devtools_manager_delegate) new DevToolsDownloadManagerDelegate(); return g_devtools_manager_delegate; } DevToolsDownloadManagerDelegate::~DevToolsDownloadManagerDelegate() { // Reset the proxy delegate. DevToolsDownloadManagerDelegate* download_delegate = GetInstance(); download_delegate->download_manager_->SetDelegate( download_delegate->proxy_download_delegate_); download_delegate->download_manager_ = nullptr; if (download_manager_) { download_manager_->SetDelegate(proxy_download_delegate_); download_manager_ = nullptr; } g_devtools_manager_delegate = nullptr; } scoped_refptr<DevToolsDownloadManagerDelegate> DevToolsDownloadManagerDelegate::TakeOver( content::DownloadManager* download_manager) { CHECK(download_manager); DevToolsDownloadManagerDelegate* download_delegate = GetInstance(); if (download_manager == download_delegate->download_manager_) return download_delegate; // Recover state of previously owned download manager. if (download_delegate->download_manager_) download_delegate->download_manager_->SetDelegate( download_delegate->proxy_download_delegate_); download_delegate->proxy_download_delegate_ = download_manager->GetDelegate(); // Take over delegate in download_manager. download_delegate->download_manager_ = download_manager; download_manager->SetDelegate(download_delegate); return download_delegate; } void DevToolsDownloadManagerDelegate::Shutdown() { if (proxy_download_delegate_) proxy_download_delegate_->Shutdown(); // Revoke any pending callbacks. download_manager_ et. al. are no longer safe // to access after this point. download_manager_ = nullptr; } bool DevToolsDownloadManagerDelegate::DetermineDownloadTarget( download::DownloadItem* item, const content::DownloadTargetCallback& callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DevToolsDownloadManagerHelper* download_helper = DevToolsDownloadManagerHelper::FromWebContents( DownloadItemUtils::GetWebContents(item)); // Check if we should failback to delegate. if (proxy_download_delegate_ && !download_helper) return proxy_download_delegate_->DetermineDownloadTarget(item, callback); // In headless mode there's no no proxy delegate set, so if there's no // information associated to the download, we deny it by default. if (!download_helper || download_helper->GetDownloadBehavior() != DevToolsDownloadManagerHelper::DownloadBehavior::ALLOW) { base::FilePath empty_path = base::FilePath(); callback.Run(empty_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, empty_path, download::DOWNLOAD_INTERRUPT_REASON_FILE_BLOCKED); return true; } base::FilePath download_path = base::FilePath::FromUTF8Unsafe(download_helper->GetDownloadPath()); FilenameDeterminedCallback filename_determined_callback = base::Bind(&DevToolsDownloadManagerDelegate::OnDownloadPathGenerated, base::Unretained(this), item->GetId(), callback); PostTaskWithTraits( FROM_HERE, {base::MayBlock(), base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN, base::TaskPriority::USER_VISIBLE}, base::BindOnce(&DevToolsDownloadManagerDelegate::GenerateFilename, item->GetURL(), item->GetContentDisposition(), item->GetSuggestedFilename(), item->GetMimeType(), download_path, std::move(filename_determined_callback))); return true; } bool DevToolsDownloadManagerDelegate::ShouldOpenDownload( download::DownloadItem* item, const content::DownloadOpenDelayedCallback& callback) { DevToolsDownloadManagerHelper* download_helper = DevToolsDownloadManagerHelper::FromWebContents( DownloadItemUtils::GetWebContents(item)); if (download_helper) return true; if (proxy_download_delegate_) return proxy_download_delegate_->ShouldOpenDownload(item, callback); return false; } void DevToolsDownloadManagerDelegate::GetNextId( const content::DownloadIdCallback& callback) { static uint32_t next_id = download::DownloadItem::kInvalidId + 1; // Be sure to follow the proxy delegate Ids to avoid compatibility problems // with the download manager. if (proxy_download_delegate_) { proxy_download_delegate_->GetNextId(callback); return; } callback.Run(next_id++); } // static void DevToolsDownloadManagerDelegate::GenerateFilename( const GURL& url, const std::string& content_disposition, const std::string& suggested_filename, const std::string& mime_type, const base::FilePath& suggested_directory, const FilenameDeterminedCallback& callback) { base::AssertBlockingAllowed(); base::FilePath generated_name = net::GenerateFileName(url, content_disposition, std::string(), suggested_filename, mime_type, "download"); if (!base::PathExists(suggested_directory)) base::CreateDirectory(suggested_directory); base::FilePath suggested_path(suggested_directory.Append(generated_name)); content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE, base::BindOnce(callback, suggested_path)); } void DevToolsDownloadManagerDelegate::OnDownloadPathGenerated( uint32_t download_id, const content::DownloadTargetCallback& callback, const base::FilePath& suggested_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); callback.Run(suggested_path, download::DownloadItem::TARGET_DISPOSITION_OVERWRITE, download::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT, suggested_path.AddExtension(FILE_PATH_LITERAL(".crdownload")), download::DOWNLOAD_INTERRUPT_REASON_NONE); } } // namespace protocol } // namespace content
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/call_graph.h" #include "tensorflow/compiler/xla/literal_util.h" #include "tensorflow/compiler/xla/service/hlo_computation.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/status_macros.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/hlo_test_base.h" #include "tensorflow/compiler/xla/util.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/lib/core/status_test_util.h" namespace xla { namespace { using ::testing::UnorderedElementsAre; class CallGraphTest : public HloTestBase { protected: // Build and return a trivial computation taking and returning a scalar. std::unique_ptr<HloComputation> MakeScalarComputation() { HloComputation::Builder builder(TestName() + ".ScalarComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction( HloInstruction::CreateUnary(kScalarShape, HloOpcode::kNegate, param0)); return builder.Build(); } // Build and return a computation which takes a scalar and maps (kMap) the // given computation to the value 'callsites' number of times. std::unique_ptr<HloComputation> MakeMappingComputation( HloComputation* map_computation, int64 callsites) { HloComputation::Builder builder(TestName() + ".MappingComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64 i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateMap( kScalarShape, {last_value}, map_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and calls (kCall) the // given computation with value 'callsites' number of times. std::unique_ptr<HloComputation> MakeCallingComputation( HloComputation* callee_computation, int64 callsites, const string& suffix = ".CallingComputation") { HloComputation::Builder builder(TestName() + suffix); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* last_value = param0; for (int64 i = 0; i < callsites; ++i) { last_value = builder.AddInstruction(HloInstruction::CreateCall( kScalarShape, {last_value}, callee_computation)); } return builder.Build(); } // Build and return a computation which takes a scalar and returns a PRED // value. std::unique_ptr<HloComputation> MakeConditionComputation() { HloComputation::Builder builder(TestName() + ".ConditionComputation"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* zero = builder.AddInstruction( HloInstruction::CreateConstant(LiteralUtil::CreateR0<float>(0.0f))); builder.AddInstruction(HloInstruction::CreateBinary( ShapeUtil::MakeShape(PRED, {}), HloOpcode::kGt, param0, zero)); return builder.Build(); } const Shape kScalarShape = ShapeUtil::MakeShape(F32, {}); }; TEST_F(CallGraphTest, SingletonComputation) { // Test the call graph of a module with a single computation. HloModule module(TestName()); HloComputation* computation = module.AddEntryComputation(MakeScalarComputation()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(1, call_graph->nodes().size()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* node, call_graph->GetNode(computation)); EXPECT_EQ(computation, node->computation()); EXPECT_TRUE(node->callsites().empty()); EXPECT_TRUE(node->callees().empty()); EXPECT_TRUE(node->caller_callsites().empty()); EXPECT_TRUE(node->callers().empty()); EXPECT_EQ(CallContext::kSequential, node->context()); } TEST_F(CallGraphTest, UnreachableComputation) { // Test the call graph of a module with an entry computation and an // unreachable computation. HloModule module(TestName()); HloComputation* entry_computation = module.AddEntryComputation(MakeScalarComputation()); HloComputation* unreachable_computation = module.AddEmbeddedComputation(MakeScalarComputation()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(2, call_graph->nodes().size()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* entry_node, call_graph->GetNode(entry_computation)); EXPECT_EQ(entry_computation, entry_node->computation()); EXPECT_EQ(CallContext::kSequential, entry_node->context()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* unreachable_node, call_graph->GetNode(unreachable_computation)); EXPECT_EQ(unreachable_computation, unreachable_node->computation()); EXPECT_EQ(CallContext::kSequential, unreachable_node->context()); } TEST_F(CallGraphTest, ParallelComputation) { // Test a call graph of a module with an entry computation which calls another // computation in a parallel context via kMap. HloModule module(TestName()); HloComputation* map_computation = module.AddEmbeddedComputation(MakeScalarComputation()); HloComputation* entry_computation = module.AddEntryComputation( MakeMappingComputation(map_computation, /*callsites=*/5)); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(2, call_graph->nodes().size()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* entry_node, call_graph->GetNode(entry_computation)); EXPECT_EQ(entry_computation, entry_node->computation()); EXPECT_EQ(CallContext::kSequential, entry_node->context()); EXPECT_EQ(5, entry_node->callsites().size()); EXPECT_EQ(1, entry_node->callees().size()); EXPECT_TRUE(entry_node->caller_callsites().empty()); EXPECT_TRUE(entry_node->callers().empty()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* map_node, call_graph->GetNode(map_computation)); EXPECT_EQ(map_computation, map_node->computation()); EXPECT_EQ(CallContext::kParallel, map_node->context()); EXPECT_TRUE(map_node->callsites().empty()); EXPECT_TRUE(map_node->callees().empty()); EXPECT_EQ(5, map_node->caller_callsites().size()); EXPECT_EQ(1, map_node->callers().size()); } TEST_F(CallGraphTest, SequentialComputations) { // Test a call graph of a module with an entry computation which calls another // computation in a sequential context via kCall. HloModule module(TestName()); HloComputation* called_computation = module.AddEmbeddedComputation(MakeScalarComputation()); HloComputation* entry_computation = module.AddEntryComputation( MakeCallingComputation(called_computation, /*callsites=*/3)); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(2, call_graph->nodes().size()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* entry_node, call_graph->GetNode(entry_computation)); EXPECT_EQ(entry_computation, entry_node->computation()); EXPECT_EQ(CallContext::kSequential, entry_node->context()); EXPECT_EQ(3, entry_node->callsites().size()); EXPECT_EQ(1, entry_node->callees().size()); EXPECT_TRUE(entry_node->caller_callsites().empty()); EXPECT_TRUE(entry_node->callers().empty()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* called_node, call_graph->GetNode(called_computation)); EXPECT_EQ(called_computation, called_node->computation()); EXPECT_EQ(CallContext::kSequential, called_node->context()); EXPECT_TRUE(called_node->callsites().empty()); EXPECT_TRUE(called_node->callees().empty()); EXPECT_EQ(3, called_node->caller_callsites().size()); EXPECT_EQ(1, called_node->callers().size()); } TEST_F(CallGraphTest, ContextBothComputations) { // Test a call graph of a module with an entry computation which calls another // computation in both a parallel and sequential context. HloModule module(TestName()); HloComputation* subcomputation = module.AddEmbeddedComputation(MakeScalarComputation()); HloComputation::Builder builder(TestName()); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* call = builder.AddInstruction( HloInstruction::CreateCall(kScalarShape, {param0}, subcomputation)); HloInstruction* map = builder.AddInstruction( HloInstruction::CreateMap(kScalarShape, {call}, subcomputation)); HloComputation* entry_computation = module.AddEntryComputation(builder.Build()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(2, call_graph->nodes().size()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* entry_node, call_graph->GetNode(entry_computation)); EXPECT_EQ(entry_computation, entry_node->computation()); EXPECT_EQ(2, entry_node->callsites().size()); const CallSite& call_callsite = entry_node->callsites()[0]; EXPECT_EQ(call, call_callsite.instruction()); EXPECT_THAT(call_callsite.called_computations(), UnorderedElementsAre(subcomputation)); EXPECT_EQ(CallContext::kSequential, call_callsite.context()); EXPECT_EQ(entry_node->GetCallSite(call), &call_callsite); const CallSite& map_callsite = entry_node->callsites()[1]; EXPECT_EQ(map, map_callsite.instruction()); EXPECT_THAT(map_callsite.called_computations(), UnorderedElementsAre(subcomputation)); EXPECT_EQ(CallContext::kParallel, map_callsite.context()); EXPECT_EQ(entry_node->GetCallSite(map), &map_callsite); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* sub_node, call_graph->GetNode(subcomputation)); EXPECT_EQ(CallContext::kBoth, sub_node->context()); } TEST_F(CallGraphTest, ComplexGraph) { // Test a call graph of a module with several computation called in various // contexts. The call graph looks like: // // entry // / | // a | // / | \ | // b | cond // \ | // c // // Calls are made via kCall, kWhile, and kMap instructions. HloModule module(TestName()); HloComputation* cond_computation = module.AddEmbeddedComputation(MakeConditionComputation()); HloComputation* c_computation = module.AddEmbeddedComputation(MakeScalarComputation()); HloComputation* b_computation = module.AddEmbeddedComputation( MakeMappingComputation(c_computation, /*callsites=*/1)); HloComputation* a_computation; { HloComputation::Builder builder(TestName() + ".a"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); HloInstruction* call = builder.AddInstruction( HloInstruction::CreateCall(kScalarShape, {param0}, c_computation)); builder.AddInstruction(HloInstruction::CreateWhile( kScalarShape, cond_computation, b_computation, call)); a_computation = module.AddEmbeddedComputation(builder.Build()); } HloComputation* entry_computation; { HloComputation::Builder builder(TestName() + ".entry"); HloInstruction* param0 = builder.AddInstruction( HloInstruction::CreateParameter(0, kScalarShape, "param0")); builder.AddInstruction(HloInstruction::CreateWhile( kScalarShape, cond_computation, a_computation, param0)); entry_computation = module.AddEntryComputation(builder.Build()); } TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); EXPECT_EQ(5, call_graph->nodes().size()); // Entry computation has one while instruction calling two computations // (cond_computation and a_computation). TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* entry_node, call_graph->GetNode(entry_computation)); ASSERT_EQ(1, entry_node->callsites().size()); const std::vector<HloComputation*>& called_computations = entry_node->callsites()[0].called_computations(); EXPECT_THAT(called_computations, UnorderedElementsAre(cond_computation, a_computation)); EXPECT_EQ(CallContext::kSequential, entry_node->context()); TF_ASSIGN_OR_ASSERT_OK(const CallGraphNode* c_node, call_graph->GetNode(c_computation)); EXPECT_TRUE(c_node->callsites().empty()); EXPECT_THAT(c_node->callers(), UnorderedElementsAre(a_computation, b_computation)); EXPECT_EQ(CallContext::kBoth, c_node->context()); // Visit the graph and verify nodes were visited in callee-before-caller // order. std::vector<const HloComputation*> visited; TF_ASSERT_OK(call_graph->VisitNodes([&visited](const CallGraphNode& node) { visited.push_back(node.computation()); return Status::OK(); })); EXPECT_EQ(visited.size(), 5); // All values in visited should be unique. EXPECT_EQ( std::unordered_set<const HloComputation*>(visited.begin(), visited.end()) .size(), 5); // Verify visitation order of some computations in the graph. auto index_of = [&visited](const HloComputation* comp) { auto it = std::find(visited.begin(), visited.end(), comp); EXPECT_NE(it, visited.end()); return std::distance(visited.begin(), it); }; EXPECT_EQ(4, index_of(entry_computation)); EXPECT_LT(index_of(cond_computation), index_of(a_computation)); EXPECT_LT(index_of(c_computation), index_of(b_computation)); EXPECT_LT(index_of(b_computation), index_of(a_computation)); } TEST_F(CallGraphTest, VisitSingletonComputation) { // Test the call graph visitor with a call graph with a single node. HloModule module(TestName()); HloComputation* computation = module.AddEntryComputation(MakeScalarComputation()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); std::vector<HloComputation*> visited; TF_ASSERT_OK(call_graph->VisitNodes([&visited](const CallGraphNode& node) { visited.push_back(node.computation()); return Status::OK(); })); EXPECT_THAT(visited, UnorderedElementsAre(computation)); } TEST_F(CallGraphTest, VisitUnreachableComputation) { // Test the call graph visitor with a call graph with an unreachable node. HloModule module(TestName()); HloComputation* entry_computation = module.AddEntryComputation(MakeScalarComputation()); HloComputation* unreachable_computation = module.AddEmbeddedComputation(MakeScalarComputation()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); // Test visitation of only reachable nodes. { std::vector<const HloComputation*> visited; TF_ASSERT_OK(call_graph->VisitNodes( [&visited](const CallGraphNode& node) { visited.push_back(node.computation()); return Status::OK(); }, /*visit_unreachable_nodes=*/false)); EXPECT_EQ(visited.size(), 1); EXPECT_EQ(visited[0], entry_computation); } // Test visitation of all nodes (reachable and unreachable). { std::vector<HloComputation*> visited; TF_ASSERT_OK(call_graph->VisitNodes( [&visited](const CallGraphNode& node) { visited.push_back(node.computation()); return Status::OK(); }, /*visit_unreachable_nodes=*/true)); EXPECT_EQ(visited.size(), 2); EXPECT_THAT(visited, UnorderedElementsAre(entry_computation, unreachable_computation)); } } TEST_F(CallGraphTest, VisitWithError) { // Test that the call graph visitor properly propagates errors. HloModule module(TestName()); module.AddEntryComputation(MakeScalarComputation()); TF_ASSIGN_OR_ASSERT_OK(std::unique_ptr<CallGraph> call_graph, CallGraph::Build(&module)); Status status = call_graph->VisitNodes( [](const CallGraphNode&) { return InternalError("Visitation failed"); }); ASSERT_FALSE(status.ok()); ASSERT_EQ(status.code(), tensorflow::error::INTERNAL); ASSERT_THAT(status.error_message(), ::testing::HasSubstr("Visitation failed")); } } // namespace } // namespace xla
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Copyright (c) 2021 The T-Notes developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or https://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "clientversion.h" #include "fs.h" #include "init.h" #include "masternodeconfig.h" #include "noui.h" #include "rpc/server.h" #include "util.h" #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called T_Notes (http://www.t_notes.org), * which enables instant payments to anyone, anywhere in the world. T_Notes uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ static bool fDaemon; void WaitForShutdown() { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } Interrupt(); } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { bool fRet = false; // // Parameters // // If Qt is used, parameters/t-notes.conf are parsed in qt/t_notes.cpp's main() gArgs.ParseParameters(argc, argv); // Process help and version before taking care about datadir if (gArgs.IsArgSet("-?") || gArgs.IsArgSet("-h") || gArgs.IsArgSet("-help") || gArgs.IsArgSet("-version")) { std::string strUsage = _("t-notes Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n"; if (gArgs.IsArgSet("-version")) { strUsage += LicenseInfo(); } else { strUsage += "\n" + _("Usage:") + "\n" + " t_notesd [options] " + _("Start t-notes Daemon") + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return false; } try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", "").c_str()); return false; } try { gArgs.ReadConfigFile(); } catch (const std::exception& e) { fprintf(stderr, "Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch(const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // parse masternode.conf std::string strErr; if (!masternodeConfig.read(strErr)) { fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str()); return false; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i]); exit(EXIT_FAILURE); } } // -server defaults to true for bitcoind but not for the GUI so do this here gArgs.SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // UIError will have been called with detailed error, which ends up on console exit(1); } if (!AppInitParameterInteraction()) { // UIError will have been called with detailed error, which ends up on console exit(1); } if (!AppInitSanityChecks()) { // UIError will have been called with detailed error, which ends up on console exit(1); } #ifndef WIN32 fDaemon = gArgs.GetBoolArg("-daemon", false); if (fDaemon) { fprintf(stdout, "T-Notes server starting\n"); // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif // Set this early so that parameter interactions go to console fRet = AppInitMain(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { Interrupt(); } else { WaitForShutdown(); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect t_notesd signal handlers noui_connect(); return (AppInit(argc, argv) ? 0 : 1); }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #include <google/protobuf/compiler/cpp/cpp_service.h> #include <google/protobuf/compiler/cpp/cpp_helpers.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/stubs/strutil.h> namespace google { namespace protobuf { namespace compiler { namespace cpp { ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor, const Options& options) : descriptor_(descriptor) { vars_["classname"] = descriptor_->name(); vars_["full_name"] = descriptor_->full_name(); if (options.dllexport_decl.empty()) { vars_["dllexport"] = ""; } else { vars_["dllexport"] = options.dllexport_decl + " "; } } ServiceGenerator::~ServiceGenerator() {} void ServiceGenerator::GenerateDeclarations(io::Printer* printer) { // Forward-declare the stub type. printer->Print(vars_, "class $classname$_Stub;\n" "\n"); GenerateInterface(printer); GenerateStubDefinition(printer); } void ServiceGenerator::GenerateInterface(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$ : public ::google::protobuf::Service {\n" " protected:\n" " // This class should be treated as an abstract interface.\n" " inline $classname$() {};\n" " public:\n" " virtual ~$classname$();\n"); printer->Indent(); printer->Print(vars_, "\n" "typedef $classname$_Stub Stub;\n" "\n" "static const ::google::protobuf::ServiceDescriptor* descriptor();\n" "\n"); GenerateMethodSignatures(VIRTUAL, printer); printer->Print( "\n" "// implements Service ----------------------------------------------\n" "\n" "const ::google::protobuf::ServiceDescriptor* GetDescriptor();\n" "void CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done);\n" "const ::google::protobuf::Message& GetRequestPrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n" "const ::google::protobuf::Message& GetResponsePrototype(\n" " const ::google::protobuf::MethodDescriptor* method) const;\n"); printer->Outdent(); printer->Print(vars_, "\n" " private:\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$);\n" "};\n" "\n"); } void ServiceGenerator::GenerateStubDefinition(io::Printer* printer) { printer->Print(vars_, "class $dllexport$$classname$_Stub : public $classname$ {\n" " public:\n"); printer->Indent(); printer->Print(vars_, "$classname$_Stub(::google::protobuf::RpcChannel* channel);\n" "$classname$_Stub(::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership);\n" "~$classname$_Stub();\n" "\n" "inline ::google::protobuf::RpcChannel* channel() { return channel_; }\n" "\n" "// implements $classname$ ------------------------------------------\n" "\n"); GenerateMethodSignatures(NON_VIRTUAL, printer); printer->Outdent(); printer->Print(vars_, " private:\n" " ::google::protobuf::RpcChannel* channel_;\n" " bool owns_channel_;\n" " GOOGLE_DISALLOW_EVIL_CONSTRUCTORS($classname$_Stub);\n" "};\n" "\n"); } void ServiceGenerator::GenerateMethodSignatures( VirtualOrNon virtual_or_non, io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); sub_vars["virtual"] = virtual_or_non == VIRTUAL ? "virtual " : ""; printer->Print(sub_vars, "$virtual$void $name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done);\n"); } } // =================================================================== void ServiceGenerator::GenerateDescriptorInitializer( io::Printer* printer, int index) { map<string, string> vars; vars["classname"] = descriptor_->name(); vars["index"] = SimpleItoa(index); printer->Print(vars, "$classname$_descriptor_ = file->service($index$);\n"); } // =================================================================== void ServiceGenerator::GenerateImplementation(io::Printer* printer) { printer->Print(vars_, "$classname$::~$classname$() {}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::descriptor() {\n" " protobuf_AssignDescriptorsOnce();\n" " return $classname$_descriptor_;\n" "}\n" "\n" "const ::google::protobuf::ServiceDescriptor* $classname$::GetDescriptor() {\n" " protobuf_AssignDescriptorsOnce();\n" " return $classname$_descriptor_;\n" "}\n" "\n"); // Generate methods of the interface. GenerateNotImplementedMethods(printer); GenerateCallMethod(printer); GenerateGetPrototype(REQUEST, printer); GenerateGetPrototype(RESPONSE, printer); // Generate stub implementation. printer->Print(vars_, "$classname$_Stub::$classname$_Stub(::google::protobuf::RpcChannel* channel)\n" " : channel_(channel), owns_channel_(false) {}\n" "$classname$_Stub::$classname$_Stub(\n" " ::google::protobuf::RpcChannel* channel,\n" " ::google::protobuf::Service::ChannelOwnership ownership)\n" " : channel_(channel),\n" " owns_channel_(ownership == ::google::protobuf::Service::STUB_OWNS_CHANNEL) {}\n" "$classname$_Stub::~$classname$_Stub() {\n" " if (owns_channel_) delete channel_;\n" "}\n" "\n"); GenerateStubMethods(printer); } void ServiceGenerator::GenerateNotImplementedMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$*,\n" " $output_type$*,\n" " ::google::protobuf::Closure* done) {\n" " controller->SetFailed(\"Method $name$() not implemented.\");\n" " done->Run();\n" "}\n" "\n"); } } void ServiceGenerator::GenerateCallMethod(io::Printer* printer) { printer->Print(vars_, "void $classname$::CallMethod(const ::google::protobuf::MethodDescriptor* method,\n" " ::google::protobuf::RpcController* controller,\n" " const ::google::protobuf::Message* request,\n" " ::google::protobuf::Message* response,\n" " ::google::protobuf::Closure* done) {\n" " GOOGLE_DCHECK_EQ(method->service(), $classname$_descriptor_);\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); // Note: down_cast does not work here because it only works on pointers, // not references. printer->Print(sub_vars, " case $index$:\n" " $name$(controller,\n" " ::google::protobuf::down_cast<const $input_type$*>(request),\n" " ::google::protobuf::down_cast< $output_type$*>(response),\n" " done);\n" " break;\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " break;\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateGetPrototype(RequestOrResponse which, io::Printer* printer) { if (which == REQUEST) { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetRequestPrototype(\n"); } else { printer->Print(vars_, "const ::google::protobuf::Message& $classname$::GetResponsePrototype(\n"); } printer->Print(vars_, " const ::google::protobuf::MethodDescriptor* method) const {\n" " GOOGLE_DCHECK_EQ(method->service(), descriptor());\n" " switch(method->index()) {\n"); for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); const Descriptor* type = (which == REQUEST) ? method->input_type() : method->output_type(); map<string, string> sub_vars; sub_vars["index"] = SimpleItoa(i); sub_vars["type"] = ClassName(type, true); printer->Print(sub_vars, " case $index$:\n" " return $type$::default_instance();\n"); } printer->Print(vars_, " default:\n" " GOOGLE_LOG(FATAL) << \"Bad method index; this should never happen.\";\n" " return *reinterpret_cast< ::google::protobuf::Message*>(NULL);\n" " }\n" "}\n" "\n"); } void ServiceGenerator::GenerateStubMethods(io::Printer* printer) { for (int i = 0; i < descriptor_->method_count(); i++) { const MethodDescriptor* method = descriptor_->method(i); map<string, string> sub_vars; sub_vars["classname"] = descriptor_->name(); sub_vars["name"] = method->name(); sub_vars["index"] = SimpleItoa(i); sub_vars["input_type"] = ClassName(method->input_type(), true); sub_vars["output_type"] = ClassName(method->output_type(), true); printer->Print(sub_vars, "void $classname$_Stub::$name$(::google::protobuf::RpcController* controller,\n" " const $input_type$* request,\n" " $output_type$* response,\n" " ::google::protobuf::Closure* done) {\n" " channel_->CallMethod(descriptor()->method($index$),\n" " controller, request, response, done);\n" "}\n"); } } } // namespace cpp } // namespace compiler } // namespace protobuf } // namespace google
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<map> #include<ext/pb_ds/tree_policy.hpp> #include<ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; typedef tree<long long,null_type,less<long long>,splay_tree_tag,tree_order_statistics_node_update> splay_tree; inline long long GetLL() { long long num=0;int bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } inline int GetInt() { int num=0,bj=1; char c=getchar(); while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar(); while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar(); return num*bj; } int N; map<long long,int>m;//相同关键字多次插入的标记 //理论上x左移10位+Hash可以实现1024(2^10)个相同关键字的标记 splay_tree tr;//定义splay树 int main() { int opt;long long x; N=GetInt(); for(int i=1;i<=N;i++) { map<long long,int>::iterator it; opt=GetInt(); x=GetLL(); if(opt==1)tr.insert((x<<10)+(m[x]++)); if(opt==2) { tr.erase(tr.find((x<<10)+(--m[x]))); if(!m[x])m.erase(m.find(x)); } if(opt==3)printf("%d\n",tr.order_of_key((x<<10))+1); if(opt==4)printf("%lld\n",*tr.find_by_order((x-1))>>10);//元素(key)->指针 if(opt==5) { it=m.lower_bound(x);//找下界(前驱) it--; printf("%lld\n",it->first); } if(opt==6) { it=m.upper_bound(x);//找上界(后驱) printf("%lld\n",it->first); } } return 0; }
#include <Dot/BinaryReadOperation.hpp> dot::BinaryReadOperation::BinaryReadOperation(Dot &dot, int bytesToRead) : Operation(dot, [](Operation &){}){ //TODO interact with the looper }
/*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*/ #if !defined CUDA_DISABLER #include "TestHypothesesFilter.h" #include "NCVHaarObjectDetection.hpp" TestHypothesesFilter::TestHypothesesFilter(std::string testName_, NCVTestSourceProvider<Ncv32u> &src_, Ncv32u numDstRects_, Ncv32u minNeighbors_, Ncv32f eps_) : NCVTestProvider(testName_), src(src_), numDstRects(numDstRects_), minNeighbors(minNeighbors_), eps(eps_) { } bool TestHypothesesFilter::toString(std::ofstream &strOut) { strOut << "numDstRects=" << numDstRects << std::endl; strOut << "minNeighbors=" << minNeighbors << std::endl; strOut << "eps=" << eps << std::endl; return true; } bool TestHypothesesFilter::init() { this->canvasWidth = 4096; this->canvasHeight = 4096; return true; } bool compareRects(const NcvRect32u &r1, const NcvRect32u &r2, Ncv32f eps) { double delta = eps*(std::min(r1.width, r2.width) + std::min(r1.height, r2.height))*0.5; return std::abs((Ncv32s)r1.x - (Ncv32s)r2.x) <= delta && std::abs((Ncv32s)r1.y - (Ncv32s)r2.y) <= delta && std::abs((Ncv32s)r1.x + (Ncv32s)r1.width - (Ncv32s)r2.x - (Ncv32s)r2.width) <= delta && std::abs((Ncv32s)r1.y + (Ncv32s)r1.height - (Ncv32s)r2.y - (Ncv32s)r2.height) <= delta; } inline bool operator < (const NcvRect32u &a, const NcvRect32u &b) { return a.x < b.x; } bool TestHypothesesFilter::process() { NCVStatus ncvStat; bool rcode = false; NCVVectorAlloc<Ncv32u> h_random32u(*this->allocatorCPU.get(), this->numDstRects * sizeof(NcvRect32u) / sizeof(Ncv32u)); ncvAssertReturn(h_random32u.isMemAllocated(), false); Ncv32u srcSlotSize = 2 * this->minNeighbors + 1; NCVVectorAlloc<NcvRect32u> h_vecSrc(*this->allocatorCPU.get(), this->numDstRects*srcSlotSize); ncvAssertReturn(h_vecSrc.isMemAllocated(), false); NCVVectorAlloc<NcvRect32u> h_vecDst_groundTruth(*this->allocatorCPU.get(), this->numDstRects); ncvAssertReturn(h_vecDst_groundTruth.isMemAllocated(), false); NCV_SET_SKIP_COND(this->allocatorCPU.get()->isCounting()); NCV_SKIP_COND_BEGIN ncvAssertReturn(this->src.fill(h_random32u), false); Ncv32u randCnt = 0; Ncv64f randVal; for (Ncv32u i=0; i<this->numDstRects; i++) { h_vecDst_groundTruth.ptr()[i].x = i * this->canvasWidth / this->numDstRects + this->canvasWidth / (this->numDstRects * 4); h_vecDst_groundTruth.ptr()[i].y = i * this->canvasHeight / this->numDstRects + this->canvasHeight / (this->numDstRects * 4); h_vecDst_groundTruth.ptr()[i].width = this->canvasWidth / (this->numDstRects * 2); h_vecDst_groundTruth.ptr()[i].height = this->canvasHeight / (this->numDstRects * 2); Ncv32u numNeighbors = this->minNeighbors + 1 + (Ncv32u)(((1.0 * h_random32u.ptr()[i]) * (this->minNeighbors + 1)) / 0xFFFFFFFF); numNeighbors = (numNeighbors > srcSlotSize) ? srcSlotSize : numNeighbors; //fill in strong hypotheses (2 * ((1.0 * randVal) / 0xFFFFFFFF) - 1) for (Ncv32u j=0; j<numNeighbors; j++) { randVal = (1.0 * h_random32u.ptr()[randCnt++]) / 0xFFFFFFFF; randCnt = randCnt % h_random32u.length(); h_vecSrc.ptr()[srcSlotSize * i + j].x = h_vecDst_groundTruth.ptr()[i].x + (Ncv32s)(h_vecDst_groundTruth.ptr()[i].width * this->eps * (randVal - 0.5)); randVal = (1.0 * h_random32u.ptr()[randCnt++]) / 0xFFFFFFFF; randCnt = randCnt % h_random32u.length(); h_vecSrc.ptr()[srcSlotSize * i + j].y = h_vecDst_groundTruth.ptr()[i].y + (Ncv32s)(h_vecDst_groundTruth.ptr()[i].height * this->eps * (randVal - 0.5)); h_vecSrc.ptr()[srcSlotSize * i + j].width = h_vecDst_groundTruth.ptr()[i].width; h_vecSrc.ptr()[srcSlotSize * i + j].height = h_vecDst_groundTruth.ptr()[i].height; } //generate weak hypotheses (to be removed in processing) for (Ncv32u j=numNeighbors; j<srcSlotSize; j++) { randVal = (1.0 * h_random32u.ptr()[randCnt++]) / 0xFFFFFFFF; randCnt = randCnt % h_random32u.length(); h_vecSrc.ptr()[srcSlotSize * i + j].x = this->canvasWidth + h_vecDst_groundTruth.ptr()[i].x + (Ncv32s)(h_vecDst_groundTruth.ptr()[i].width * this->eps * (randVal - 0.5)); randVal = (1.0 * h_random32u.ptr()[randCnt++]) / 0xFFFFFFFF; randCnt = randCnt % h_random32u.length(); h_vecSrc.ptr()[srcSlotSize * i + j].y = this->canvasHeight + h_vecDst_groundTruth.ptr()[i].y + (Ncv32s)(h_vecDst_groundTruth.ptr()[i].height * this->eps * (randVal - 0.5)); h_vecSrc.ptr()[srcSlotSize * i + j].width = h_vecDst_groundTruth.ptr()[i].width; h_vecSrc.ptr()[srcSlotSize * i + j].height = h_vecDst_groundTruth.ptr()[i].height; } } //shuffle for (Ncv32u i=0; i<this->numDstRects*srcSlotSize-1; i++) { Ncv32u randValLocal = h_random32u.ptr()[randCnt++]; randCnt = randCnt % h_random32u.length(); Ncv32u secondSwap = randValLocal % (this->numDstRects*srcSlotSize-1 - i); NcvRect32u tmp = h_vecSrc.ptr()[i + secondSwap]; h_vecSrc.ptr()[i + secondSwap] = h_vecSrc.ptr()[i]; h_vecSrc.ptr()[i] = tmp; } NCV_SKIP_COND_END Ncv32u numHypothesesSrc = static_cast<Ncv32u>(h_vecSrc.length()); NCV_SKIP_COND_BEGIN ncvStat = ncvGroupRectangles_host(h_vecSrc, numHypothesesSrc, this->minNeighbors, this->eps, NULL); ncvAssertReturn(ncvStat == NCV_SUCCESS, false); NCV_SKIP_COND_END //verification bool bLoopVirgin = true; NCV_SKIP_COND_BEGIN if (numHypothesesSrc != this->numDstRects) { bLoopVirgin = false; } else { std::vector<NcvRect32u> tmpRects(numHypothesesSrc); memcpy(&tmpRects[0], h_vecSrc.ptr(), numHypothesesSrc * sizeof(NcvRect32u)); std::sort(tmpRects.begin(), tmpRects.end()); for (Ncv32u i=0; i<numHypothesesSrc && bLoopVirgin; i++) { if (!compareRects(tmpRects[i], h_vecDst_groundTruth.ptr()[i], this->eps)) { bLoopVirgin = false; } } } NCV_SKIP_COND_END if (bLoopVirgin) { rcode = true; } return rcode; } bool TestHypothesesFilter::deinit() { return true; } #endif /* CUDA_DISABLER */
#pragma once #include <stdint.h> static const uint16_t RJ_BASE2015_VENDOR_ID = 0x524A; static const uint16_t RJ_BASE2015_PRODUCT_ID = 0x4253; static const uint16_t RJ_BASE2015_RELEASE = 0x0000; // USB "control transfer" commands recognized by the base station enum Base2015ControlCommand { RadioWriteRegister = 1, RadioReadRegister, RadioStrobe, RadioSetChannel, };
// ********************************************************************** // @@@ START COPYRIGHT @@@ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // @@@ END COPYRIGHT @@@ // ********************************************************************** #include <log4cxx/fileappender.h> #include <log4cxx/rollingfileappender.h> #include <log4cxx/patternlayout.h> #include <log4cxx/propertyconfigurator.h> #include <log4cxx/basicconfigurator.h> #include <log4cxx/helpers/exception.h> #include <log4cxx/level.h> #include <QRLogger.h> #include "ComDiags.h" #include "logmxevent.h" #include "NLSConversion.h" #include "Globals.h" #include "PortProcessCalls.h" #include "seabed/ms.h" #include "seabed/fserr.h" BOOL gv_QRLoggerInitialized_ = FALSE; QRLogger *gv_QRLoggerInstance_ = NULL; using namespace log4cxx; using namespace log4cxx::helpers; // SQL categories std::string CAT_SQL = "SQL"; std::string CAT_SQL_EXE = "SQL.EXE"; std::string CAT_SQL_COMP = "SQL.COMP"; std::string CAT_SQL_ESP = "SQL.ESP"; std::string CAT_SQL_LOB = "SQL.LOB"; std::string CAT_SQL_SSMP = "SQL.SSMP"; std::string CAT_SQL_SSCP = "SQL.SSCP"; std::string CAT_SQL_UDR = "SQL.UDR"; std::string CAT_SQL_PRIVMGR = "SQL.PRIVMGR"; std::string CAT_SQL_USTAT = "SQL.USTAT"; // hdfs std::string CAT_SQL_HDFS_JNI_TOP = "SQL.HDFS.JniTop"; std::string CAT_SQL_HDFS_SEQ_FILE_READER = "SQL.HDFS.SeqFileReader"; std::string CAT_SQL_HDFS_SEQ_FILE_WRITER = "SQL.HDFS.SeqFileWriter"; std::string CAT_SQL_HDFS_ORC_FILE_READER = "SQL.HDFS.OrcFileReader"; std::string CAT_SQL_HBASE = "SQL.HBase"; std::string CAT_SQL_HDFS = "SQL.HDFS"; // these categories are currently not used std::string CAT_SQL_QMP = "SQL.Qmp"; std::string CAT_SQL_QMM = "SQL.Qmm"; std::string CAT_SQL_COMP_QR_DESC_GEN = "SQL.COMP"; // ".DescGen"; std::string CAT_SQL_COMP_QR_HANDLER = "SQL.COMP"; // ".QRHandler"; std::string CAT_SQL_COMP_QR_COMMON = "SQL.COMP"; // ".QRCommon"; std::string CAT_SQL_COMP_QR_IPC = "SQL.COMP"; // ".QRCommon.IPC"; std::string CAT_SQL_COMP_MV_REFRESH = "SQL.COMP"; // ".MV.REFRESH"; std::string CAT_SQL_COMP_MVCAND = "SQL.COMP"; // ".MVCandidates"; std::string CAT_SQL_MEMORY = "SQL.COMP"; // ".Memory"; std::string CAT_SQL_COMP_RANGE = "SQL.COMP"; // ".Range"; std::string CAT_QR_TRACER = "QRCommon.Tracer"; std::string CAT_SQL_QMS = "SQL.Qms"; std::string CAT_SQL_QMS_MAIN = "SQL.Qms.Main"; std::string CAT_SQL_QMS_INIT = "SQL.Qms.Init"; std::string CAT_SQL_MVMEMO_JOINGRAPH = "SQL.Qms.MvmemoJoingraph"; std::string CAT_SQL_MVMEMO_STATS = "SQL.Qms.MvmemoStats"; std::string CAT_SQL_QMS_GRP_LATTCE_INDX = "SQL.Qms.LatticeIndex"; std::string CAT_SQL_QMS_MATCHTST_MVDETAILS = "SQL.Qms.MatchTest"; std::string CAT_SQL_QMS_XML = "SQL.Qms.XML"; std::string CAT_SQL_COMP_XML = "SQL.COMP"; // ".XML"; // ************************************************************************** // ************************************************************************** QRLogger::QRLogger() : CommonLogger() ,module_(QRL_NONE) ,processInfo_("") { } // ************************************************************************** // ************************************************************************** QRLogger& QRLogger::instance() { if (gv_QRLoggerInstance_ == NULL) gv_QRLoggerInstance_ = new QRLogger(); return *gv_QRLoggerInstance_; } // ************************************************************************** // construct a string with the node number and PIN of the ancestor // executor process and the string ".log". This will be used as the suffix // of the log name. So if the log name specified by the user in the // configuration file is "sql_events", the actual log name will be // something like "sql_events_0_12345.log" // ************************************************************************** void getMyTopAncestor(char ancsNidPid[]) { short result = 0; NAProcessHandle myPhandle; myPhandle.getmine(); myPhandle.decompose(); char processName[MS_MON_MAX_PROCESS_NAME + 1]; char ppName[MS_MON_MAX_PROCESS_NAME + 1]; memset(processName, 0, sizeof(processName)); memcpy(processName, myPhandle.getPhandleString(), myPhandle.getPhandleStringLen()); memset(ppName, 0, sizeof(ppName)); MS_Mon_Process_Info_Type procInfo; Int32 rc = 0; Int32 ancsNid = 0; Int32 ancsPid = 0; do { rc = msg_mon_get_process_info_detail(processName, &procInfo); ancsNid = procInfo.nid; ancsPid = procInfo.pid; strcpy(ppName, procInfo.parent_name); strcpy(processName, ppName); } while ((rc == XZFIL_ERR_OK) && (procInfo.parent_nid != -1) && (procInfo.parent_pid != -1)); snprintf (ancsNidPid, 5+2*sizeof(Int32), "_%d_%d.log", ancsNid, ancsPid); } // ************************************************************************** // construct a string with the node number of the // process and the string ".log". This will be used as the suffix // of the log name forthis process . So if the log name specified by the // user in the // configuration file is "sql_events", the actual log name will be // something like "sql_events_<nid>.log" // ************************************************************************** void getMyNidSuffix(char stringNidSuffix[]) { short result = 0; NAProcessHandle myPhandle; myPhandle.getmine(); myPhandle.decompose(); Int32 myNid = myPhandle.getCpu(); snprintf (stringNidSuffix, 5+sizeof(Int32), "_%d.log", myNid); } // ************************************************************************** // Call the superclass to configure log4cxx from the config file. // If the configuration file is not found, perform default initialization: // Create an appender, layout, and categories. // Attaches layout to the appender and appender to categories. // ************************************************************************** NABoolean QRLogger::initLog4cxx(const char* configFileName) { NAString logFileName; if (gv_QRLoggerInitialized_) return TRUE; if (CommonLogger::initLog4cxx(configFileName)) { introduceSelf(); gv_QRLoggerInitialized_ = TRUE; return TRUE; } return FALSE; } std::string &QRLogger::getMyDefaultCat() { switch (module_) { case QRL_MXCMP: return CAT_SQL_COMP; break; case QRL_MXEXE: return CAT_SQL_EXE; break; case QRL_ESP: return CAT_SQL_ESP; break; case QRL_LOB: return CAT_SQL_LOB; break; case QRL_SSMP: return CAT_SQL_SSMP; break; case QRL_SSCP: return CAT_SQL_SSCP; break; case QRL_UDR: return CAT_SQL_UDR; break; default: return CAT_SQL; } } const char* QRLogger::getMyProcessInfo() { char procInfo[300]; SB_Phandle_Type myphandle; XPROCESSHANDLE_GETMINE_(&myphandle); char charProcHandle[200]; char myprocname[30]; Int32 mycpu,mypin,mynodenumber=0; short myproclength = 0; XPROCESSHANDLE_DECOMPOSE_(&myphandle, &mycpu, &mypin, &mynodenumber,NULL,100, NULL, myprocname,100, &myproclength); myprocname[myproclength] = '\0'; snprintf(procInfo, 300, "Node Number: %d, CPU: %d, PIN: %d, Process Name: %s", mycpu,mycpu, mypin, myprocname); processInfo_ = procInfo; return processInfo_.data(); } void QRLogger::introduceSelf () { char msg[300]; std::string &myCat = getMyDefaultCat(); // save previous default priority log4cxx::LevelPtr defaultPriority = log4cxx::Logger::getLogger(myCat)->getLevel(); NAString procInfo = getMyProcessInfo(); // change default priority to INFO to be able to printout some informational messages log4cxx::LoggerPtr myLogger(log4cxx::Logger::getLogger(myCat)); myLogger->setLevel(log4cxx::Level::getInfo()); switch (module_) { case QRL_NONE: case QRL_MXCMP: snprintf (msg, 200, "%s,,, A compiler process is launched.", procInfo.data()); break; case QRL_ESP: snprintf (msg, 300, "%s,,, An ESP process is launched.", procInfo.data()); break; case QRL_MXEXE: snprintf (msg, 300, "%s,,, An executor process is launched.", procInfo.data()); break; case QRL_LOB: snprintf (msg, 300, "%s,,, A lobserver process is launched.", procInfo.data()); break; case QRL_SSMP: snprintf (msg, 300, "%s,,, An ssmp process is launched.", procInfo.data()); break; case QRL_SSCP: snprintf (msg, 300, "%s,,, An sscp process is launched.", procInfo.data()); break; case QRL_UDR: snprintf (msg, 300, "%s,,, A udrserver process is launched.", procInfo.data()); break; } LOG4CXX_INFO(myLogger,msg); // restore default priority myLogger->setLevel(defaultPriority); } // ************************************************************************** // Log an exception-type error message: // First log "Error thrown at line <line> in file <filename>:" // Then log the actual error message, which is passed with a variable // number of parameters. The error message is epected to be a single line // of text not exceeding 2K. // This error message can be logged as either ERROR or FATAL type. // Both lines of text are sent to the log file // MVQR failures that prevent only rewrite, and not execution of the original // form of the query, cause an informational rather than an error notification // to be entered in the system log. // ************************************************************************** void QRLogger::logError(const char* file, Int32 line, std::string &cat, logLevel level, const char* logMsgTemplate...) { #define BUFFER_SIZE 2048 char buffer[BUFFER_SIZE]; // This method expects a single line to text. NAString logData = QRLogger::instance().getMyProcessInfo(); if (level == LL_MVQR_FAIL) snprintf(buffer, sizeof(buffer), "%s,,, Attempted MVQR operation (rewrite of query or publication of MV) failed at line %d in file %s:", logData.data(), line, file); else snprintf(buffer, sizeof(buffer), "%s,,, Error thrown at line %d in file %s:", logData.data(), line, file); va_list args; va_start(args, logMsgTemplate); if (level == LL_FATAL) { LOG4CXX_FATAL(log4cxx::Logger::getLogger(cat), buffer); } else { LOG4CXX_ERROR(log4cxx::Logger::getLogger(cat), buffer); } // format actual error message vsnprintf(buffer, BUFFER_SIZE, logMsgTemplate, args); NAString logData2 = QRLogger::instance().getMyProcessInfo(); logData2 += ",,, "; logData2 += buffer; // log actual error msg to logfile. if (level == LL_FATAL) { LOG4CXX_FATAL(log4cxx::Logger::getLogger(cat), logData2.data()); } else { LOG4CXX_ERROR(log4cxx::Logger::getLogger(cat), logData2.data()); } va_end(args); } // This temporary function is used for logging QVP messages only. More extensive // changes to the CommonLogger hierarchy will be made when the QI integration // stream is merged into the mainline. For now, we avoid making changes that // affect MVQR to minimize merge difficulties. void QRLogger::logQVP(ULng32 eventId, std::string &cat, logLevel level, const char* logMsgTemplate...) { // Don't do anything if this message will be ignored anyway. log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat); if ( myLogger ) { log4cxx::LevelPtr myLevel = myLogger->getLevel(); log4cxx::LevelPtr paramLevel = log4cxx::Level::toLevel(level); if ( myLevel && paramLevel ) { if ( myLevel == log4cxx::Level::getOff() ) return; int_32 configuredLevel = myLevel->toInt(); int_32 requestedLevel = paramLevel->toInt(); // If the configured logging level is greater (more restrictive) than // the requested level, don't log. if ( configuredLevel > requestedLevel) return; } }else return; va_list args; va_start(args, logMsgTemplate); char* buffer = buildMsgBuffer(cat, level, logMsgTemplate, args); log1(cat, level, buffer, eventId); va_end(args); } void QRLogger::logDiags(ComDiagsArea* diagsArea, std::string &cat) { const NAWchar* diagMsg; NAString* diagStr; Int32 i; ComCondition* condition; log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat); if ( myLogger ) { log4cxx::LevelPtr myLevel = myLogger->getLevel(); if ( myLevel ) { // If configured Level is the same or less restrictive than WARN (30000) // than report the warning if ( myLevel != log4cxx::Level::getOff() && myLevel->toInt() <= LL_WARN ) { for (i=1; i<=diagsArea->getNumber(DgSqlCode::WARNING_); i++) { condition = diagsArea->getWarningEntry(i); diagMsg = condition->getMessageText(); diagStr = unicodeToChar(diagMsg, NAWstrlen(diagMsg), CharInfo::ISO88591, NULL, TRUE); log(cat, LL_WARN, condition->getSQLCODE(), "", " warn condition %d: %s", i, diagStr->data()); delete diagStr; } } } } } // ************************************************************************** // ************************************************************************** CommonTracer::CommonTracer(const char* fnName, CommonLogger& logger, std::string &logCategory, TraceLevel level, const char* file, Int32 line) : fnName_(fnName), level_(level), file_(file ? file : ""), line_(line), logger_(logger), category_(logCategory) { if (level_ == TL_all) { if (file_.length() == 0) logger_.log(category_, LL_DEBUG, "Entering %s", fnName_.data()); else logger_.log(category_, LL_DEBUG, "Entering %s (file %s, line %d)", fnName_.data(), file_.data(), line_); } } // ************************************************************************** // ************************************************************************** CommonTracer::~CommonTracer() { NAString logMsg; if (level_ >= TL_exceptionOnly && std::uncaught_exception()) logMsg.append("Exiting %s with uncaught exception"); else if (level_ == TL_all) logMsg.append("Exiting %s"); else return; if (file_.length() > 0) { logMsg.append("(file %s, line %d)"); logger_.log(category_, LL_DEBUG, logMsg, fnName_.data(), file_.data(), line_); } else { logger_.log(category_, LL_DEBUG, logMsg, fnName_.data()); } } void QRLogger::log(const std::string &cat, logLevel level, int sqlCode, const char *queryId, const char *logMsgTemplate...) { log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat); if ( myLogger ) { log4cxx::LevelPtr myLevel = myLogger->getLevel(); log4cxx::LevelPtr paramLevel = log4cxx::Level::toLevel(level); if ( myLevel && paramLevel ) { if ( myLevel == log4cxx::Level::getOff() ) return; int_32 configuredLevel = myLevel->toInt(); int_32 requestedLevel = paramLevel->toInt(); // If the configured logging level is greater (more restrictive) than // the requested level, don't log. if ( configuredLevel > requestedLevel) return; } } else return; va_list args ; va_start(args, logMsgTemplate); char* buffer = buildMsgBuffer(cat, level, logMsgTemplate, args); NAString logData = QRLogger::instance().getMyProcessInfo(); char sqlCodeBuf[30]; snprintf(sqlCodeBuf, sizeof(sqlCodeBuf), "%d", sqlCode); logData += ","; if (sqlCode != 0) { logData += " SQLCODE: "; logData += sqlCodeBuf; } logData += ","; if (queryId != NULL && queryId[0] != '\0') { logData += " QID: "; logData += queryId; } logData += ", "; logData += buffer; log1(cat, level, logData.data()); va_end(args); } void QRLogger::log(const std::string &cat, logLevel level, const char *logMsgTemplate...) { log4cxx::LoggerPtr myLogger = log4cxx::Logger::getLogger(cat); if ( myLogger ) { log4cxx::LevelPtr myLevel = myLogger->getLevel(); log4cxx::LevelPtr paramLevel = log4cxx::Level::toLevel(level); if ( myLevel && paramLevel ) { if ( myLevel == log4cxx::Level::getOff() ) return; int_32 configuredLevel = myLevel->toInt(); int_32 requestedLevel = paramLevel->toInt(); // If the configured logging level is greater (more restrictive) than // the requested level, don't log. if ( configuredLevel > requestedLevel) return; } }else return; va_list args ; va_start(args, logMsgTemplate); char* buffer = buildMsgBuffer(cat, level, logMsgTemplate, args); NAString logData = QRLogger::instance().getMyProcessInfo(); // SQLCode and Query id are not provided in this flavor logData += ",,,"; logData += buffer; log1(cat, level, logData.data()); va_end(args); } NABoolean QRLogger::initLog4cxx(ExecutableModule module) { NABoolean retcode; static bool singleSqlLogFile = (getenv("TRAF_MULTIPLE_SQL_LOG_FILE") == NULL); QRLogger::instance().setModule(module); if (singleSqlLogFile) retcode = QRLogger::instance().initLog4cxx("log4cxx.trafodion.sql.config"); else retcode = QRLogger::instance().initLog4cxx("log4cxx.trafodion.masterexe.config"); return retcode; } NABoolean QRLogger::startLogFile(const std::string &cat, const char * logFileName) { NABoolean retcode = TRUE; // assume success try { log4cxx::LoggerPtr logger(Logger::getLogger(cat)); logger->setAdditivity(false); // make this logger non-additive log4cxx::PatternLayout * layout = new PatternLayout("%d, %p, %c, %m%n"); log4cxx::LogString fileName(logFileName); log4cxx::FileAppenderPtr fap(new FileAppender(layout,fileName,false /* no append */)); logger->addAppender(fap); } catch (...) { retcode = FALSE; } return retcode; } NABoolean QRLogger::stopLogFile(const std::string &cat) { NABoolean retcode = TRUE; // assume success try { log4cxx::LoggerPtr logger(Logger::getLogger(cat)); logger->removeAllAppenders(); } catch (...) { retcode = FALSE; } return retcode; } NABoolean QRLogger::getRootLogDirectory(const std::string &cat, std::string &out) { NABoolean retcode = TRUE; // assume success out.clear(); // strip off all but the first qualifier of the category name size_t firstDot = cat.find_first_of('.'); std::string firstQualifier; if (firstDot == std::string::npos) firstQualifier = cat; // no dot, use the whole thing else firstQualifier = cat.substr(0,firstDot); try { log4cxx::LoggerPtr logger(Logger::getLogger(firstQualifier)); log4cxx::AppenderList appenderList = logger->getAllAppenders(); for (size_t i = 0; i < appenderList.size(); i++) { log4cxx::AppenderPtr appender = appenderList[i]; log4cxx::LogString appenderName = appender->getName(); log4cxx::Appender * appenderP = appender; log4cxx::FileAppender * fileAppender = dynamic_cast<FileAppender *>(appenderP); if (fileAppender) { log4cxx::LogString logFileName = fileAppender->getFile(); out = logFileName.data(); size_t lastSlash = out.find_last_of('/'); if (lastSlash != std::string::npos) out = out.substr(0,lastSlash); return TRUE; } } } catch (...) { retcode = FALSE; } return retcode; }
//$Id:$ //------------------------------------------------------------------------------ // SpiceKernelReader //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002 - 2018 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under // FDSS Task order 28. // // Author: Wendy C. Shoan // Created: 2009.02.24 // /** * Implementation of the SpicKernelReader, which reads SPICE data (kernel) files. * This class calls the JPL-supplied CSPICE routines to read the specified * SPICE file and return the requested data. */ //------------------------------------------------------------------------------ #include "SpiceKernelReader.hpp" #include "A1Mjd.hpp" #include "StringUtil.hpp" #include "MessageInterface.hpp" #include "TimeTypes.hpp" #include "TimeSystemConverter.hpp" #include "UtilityException.hpp" //#define DEBUG_SPICE_KERNEL_READER //--------------------------------- // static data //--------------------------------- const Integer SpiceKernelReader::MAX_IDS_PER_KERNEL = 200; const Integer SpiceKernelReader::MAX_COVERAGE_INTERVALS = 200000; //--------------------------------- // public methods //--------------------------------- //------------------------------------------------------------------------------ // SpiceKernelReader() //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceKernelReader class * (default constructor). * */ //------------------------------------------------------------------------------ SpiceKernelReader::SpiceKernelReader() : SpiceInterface(), objectNameSPICE (NULL), naifIDSPICE (-123456789), etSPICE (0.0), referenceFrameSPICE (NULL) { } //------------------------------------------------------------------------------ // SpiceKernelReader(const SpiceKernelReader &reader) //------------------------------------------------------------------------------ /** * This method creates an object of the SpiceKernelReader class, by copying * the input object. * (copy constructor). * * @param <reader> SpiceKernelReader object to copy. */ //------------------------------------------------------------------------------ SpiceKernelReader::SpiceKernelReader(const SpiceKernelReader &reader) : SpiceInterface(reader), objectNameSPICE (NULL), naifIDSPICE (reader.naifIDSPICE), etSPICE (reader.etSPICE), referenceFrameSPICE (NULL) { } //------------------------------------------------------------------------------ // SpiceKernelReader& operator=(const SpiceKernelReader &reader) //------------------------------------------------------------------------------ /** * This method copies the data from the input object to the object. * * @param <reader> the SpiceKernelReader object whose data to assign to "this" * SpiceKernelReader. * * @return "this" SpiceKernelReader with data of input SpiceKernelReader reader. */ //------------------------------------------------------------------------------ SpiceKernelReader& SpiceKernelReader::operator=(const SpiceKernelReader &reader) { if (&reader == this) return *this; SpiceInterface::operator=(reader); objectNameSPICE = reader.objectNameSPICE; naifIDSPICE = reader.naifIDSPICE; etSPICE = reader.etSPICE; referenceFrameSPICE = reader.referenceFrameSPICE; return *this; } //------------------------------------------------------------------------------ // ~SpiceKernelReader() //------------------------------------------------------------------------------ /** * This method is the destructor for the SpiceKernelReader. * */ //------------------------------------------------------------------------------ SpiceKernelReader::~SpiceKernelReader() { }
/* * Copyright (c) 2012, Michael Lehn, Klaus Pototzky * * 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 FLENS development group 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 CXXLAPACK_INTERFACE_ORGTR_TCC #define CXXLAPACK_INTERFACE_ORGTR_TCC 1 #include <iostream> #include "xflens/cxxlapack/interface/interface.h" #include "xflens/cxxlapack/netlib/netlib.h" namespace cxxlapack { template <typename IndexType> IndexType orgtr(char uplo, IndexType n, float *A, IndexType ldA, const float *tau, float *work, IndexType lWork) { CXXLAPACK_DEBUG_OUT("sorgtr"); IndexType info; LAPACK_IMPL(sorgtr)(&uplo, &n, A, &ldA, tau, work, &lWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } template <typename IndexType> IndexType orgtr(char uplo, IndexType n, double *A, IndexType ldA, const double *tau, double *work, IndexType lWork) { CXXLAPACK_DEBUG_OUT("dorgtr"); IndexType info; LAPACK_IMPL(dorgtr)(&uplo, &n, A, &ldA, tau, work, &lWork, &info); # ifndef NDEBUG if (info<0) { std::cerr << "info = " << info << std::endl; } # endif ASSERT(info>=0); return info; } } // namespace cxxlapack #endif // CXXLAPACK_INTERFACE_ORGTR_TCC
// Copyright (c) 2013 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/browser/gpu/gpu_data_manager_impl_private.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/debug/trace_event.h" #include "base/metrics/field_trial.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/sys_info.h" #include "base/version.h" #include "cc/base/switches.h" #include "content/browser/gpu/gpu_process_host.h" #include "content/common/gpu/gpu_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/gpu_data_manager_observer.h" #include "content/public/common/content_client.h" #include "content/public/common/content_constants.h" #include "content/public/common/content_switches.h" #include "content/public/common/web_preferences.h" #include "gpu/command_buffer/service/gpu_switches.h" #include "gpu/config/gpu_control_list_jsons.h" #include "gpu/config/gpu_driver_bug_workaround_type.h" #include "gpu/config/gpu_feature_type.h" #include "gpu/config/gpu_info_collector.h" #include "gpu/config/gpu_util.h" #include "ui/base/ui_base_switches.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_switches.h" #include "ui/gl/gpu_switching_manager.h" #if defined(OS_MACOSX) #include <ApplicationServices/ApplicationServices.h> #endif // OS_MACOSX #if defined(OS_WIN) #include "base/win/windows_version.h" #endif // OS_WIN #if defined(OS_ANDROID) #include "ui/gfx/android/device_display_info.h" #endif // OS_ANDROID namespace content { namespace { enum GpuFeatureStatus { kGpuFeatureEnabled = 0, kGpuFeatureBlacklisted = 1, kGpuFeatureDisabled = 2, // disabled by user but not blacklisted kGpuFeatureNumStatus }; #if defined(OS_WIN) enum WinSubVersion { kWinOthers = 0, kWinXP, kWinVista, kWin7, kWin8, kNumWinSubVersions }; int GetGpuBlacklistHistogramValueWin(GpuFeatureStatus status) { static WinSubVersion sub_version = kNumWinSubVersions; if (sub_version == kNumWinSubVersions) { sub_version = kWinOthers; std::string version_str = base::SysInfo::OperatingSystemVersion(); size_t pos = version_str.find_first_not_of("0123456789."); if (pos != std::string::npos) version_str = version_str.substr(0, pos); Version os_version(version_str); if (os_version.IsValid() && os_version.components().size() >= 2) { const std::vector<uint16>& version_numbers = os_version.components(); if (version_numbers[0] == 5) sub_version = kWinXP; else if (version_numbers[0] == 6 && version_numbers[1] == 0) sub_version = kWinVista; else if (version_numbers[0] == 6 && version_numbers[1] == 1) sub_version = kWin7; else if (version_numbers[0] == 6 && version_numbers[1] == 2) sub_version = kWin8; } } int entry_index = static_cast<int>(sub_version) * kGpuFeatureNumStatus; switch (status) { case kGpuFeatureEnabled: break; case kGpuFeatureBlacklisted: entry_index++; break; case kGpuFeatureDisabled: entry_index += 2; break; } return entry_index; } #endif // OS_WIN // Send UMA histograms about the enabled features and GPU properties. void UpdateStats(const gpu::GPUInfo& gpu_info, const gpu::GpuBlacklist* blacklist, const std::set<int>& blacklisted_features) { uint32 max_entry_id = blacklist->max_entry_id(); if (max_entry_id == 0) { // GPU Blacklist was not loaded. No need to go further. return; } const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); bool disabled = false; // Use entry 0 to capture the total number of times that data // was recorded in this histogram in order to have a convenient // denominator to compute blacklist percentages for the rest of the // entries. UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", 0, max_entry_id + 1); if (blacklisted_features.size() != 0) { std::vector<uint32> flag_entries; blacklist->GetDecisionEntries(&flag_entries, disabled); DCHECK_GT(flag_entries.size(), 0u); for (size_t i = 0; i < flag_entries.size(); ++i) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerEntry", flag_entries[i], max_entry_id + 1); } } // This counts how many users are affected by a disabled entry - this allows // us to understand the impact of an entry before enable it. std::vector<uint32> flag_disabled_entries; disabled = true; blacklist->GetDecisionEntries(&flag_disabled_entries, disabled); for (uint32 disabled_entry : flag_disabled_entries) { UMA_HISTOGRAM_ENUMERATION("GPU.BlacklistTestResultsPerDisabledEntry", disabled_entry, max_entry_id + 1); } const gpu::GpuFeatureType kGpuFeatures[] = { gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS, gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING, gpu::GPU_FEATURE_TYPE_WEBGL}; const std::string kGpuBlacklistFeatureHistogramNames[] = { "GPU.BlacklistFeatureTestResults.Accelerated2dCanvas", "GPU.BlacklistFeatureTestResults.GpuCompositing", "GPU.BlacklistFeatureTestResults.Webgl", }; const bool kGpuFeatureUserFlags[] = { command_line.HasSwitch(switches::kDisableAccelerated2dCanvas), command_line.HasSwitch(switches::kDisableGpu), command_line.HasSwitch(switches::kDisableExperimentalWebGL), }; #if defined(OS_WIN) const std::string kGpuBlacklistFeatureHistogramNamesWin[] = { "GPU.BlacklistFeatureTestResultsWindows.Accelerated2dCanvas", "GPU.BlacklistFeatureTestResultsWindows.GpuCompositing", "GPU.BlacklistFeatureTestResultsWindows.Webgl", }; #endif const size_t kNumFeatures = sizeof(kGpuFeatures) / sizeof(gpu::GpuFeatureType); for (size_t i = 0; i < kNumFeatures; ++i) { // We can't use UMA_HISTOGRAM_ENUMERATION here because the same name is // expected if the macro is used within a loop. GpuFeatureStatus value = kGpuFeatureEnabled; if (blacklisted_features.count(kGpuFeatures[i])) value = kGpuFeatureBlacklisted; else if (kGpuFeatureUserFlags[i]) value = kGpuFeatureDisabled; base::HistogramBase* histogram_pointer = base::LinearHistogram::FactoryGet( kGpuBlacklistFeatureHistogramNames[i], 1, kGpuFeatureNumStatus, kGpuFeatureNumStatus + 1, base::HistogramBase::kUmaTargetedHistogramFlag); histogram_pointer->Add(value); #if defined(OS_WIN) histogram_pointer = base::LinearHistogram::FactoryGet( kGpuBlacklistFeatureHistogramNamesWin[i], 1, kNumWinSubVersions * kGpuFeatureNumStatus, kNumWinSubVersions * kGpuFeatureNumStatus + 1, base::HistogramBase::kUmaTargetedHistogramFlag); histogram_pointer->Add(GetGpuBlacklistHistogramValueWin(value)); #endif } UMA_HISTOGRAM_SPARSE_SLOWLY("GPU.GLResetNotificationStrategy", gpu_info.gl_reset_notification_strategy); } // Combine the integers into a string, seperated by ','. std::string IntSetToString(const std::set<int>& list) { std::string rt; for (std::set<int>::const_iterator it = list.begin(); it != list.end(); ++it) { if (!rt.empty()) rt += ","; rt += base::IntToString(*it); } return rt; } #if defined(OS_MACOSX) void DisplayReconfigCallback(CGDirectDisplayID display, CGDisplayChangeSummaryFlags flags, void* gpu_data_manager) { if (flags == kCGDisplayBeginConfigurationFlag) return; // This call contains no information about the display change GpuDataManagerImpl* manager = reinterpret_cast<GpuDataManagerImpl*>(gpu_data_manager); DCHECK(manager); // Display change. bool display_changed = false; uint32_t displayCount; CGGetActiveDisplayList(0, NULL, &displayCount); if (displayCount != manager->GetDisplayCount()) { manager->SetDisplayCount(displayCount); display_changed = true; } // Gpu change. bool gpu_changed = false; if (flags & kCGDisplayAddFlag) { uint32 vendor_id, device_id; if (gpu::CollectGpuID(&vendor_id, &device_id) == gpu::kCollectInfoSuccess) { gpu_changed = manager->UpdateActiveGpu(vendor_id, device_id); } } if (display_changed || gpu_changed) manager->HandleGpuSwitch(); } #endif // OS_MACOSX // Block all domains' use of 3D APIs for this many milliseconds if // approaching a threshold where system stability might be compromised. const int64 kBlockAllDomainsMs = 10000; const int kNumResetsWithinDuration = 1; // Enums for UMA histograms. enum BlockStatusHistogram { BLOCK_STATUS_NOT_BLOCKED, BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED, BLOCK_STATUS_ALL_DOMAINS_BLOCKED, BLOCK_STATUS_MAX }; } // namespace anonymous void GpuDataManagerImplPrivate::InitializeForTesting( const std::string& gpu_blacklist_json, const gpu::GPUInfo& gpu_info) { // This function is for testing only, so disable histograms. update_histograms_ = false; // Prevent all further initialization. finalized_ = true; InitializeImpl(gpu_blacklist_json, std::string(), gpu_info); } bool GpuDataManagerImplPrivate::IsFeatureBlacklisted(int feature) const { #if defined(OS_CHROMEOS) if (feature == gpu::GPU_FEATURE_TYPE_PANEL_FITTING && base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisablePanelFitting)) { return true; } #endif // OS_CHROMEOS if (use_swiftshader_ || ShouldUseWarp()) { // Skia's software rendering is probably more efficient than going through // software emulation of the GPU, so use that. if (feature == gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS) return true; return false; } return (blacklisted_features_.count(feature) == 1); } bool GpuDataManagerImplPrivate::IsDriverBugWorkaroundActive(int feature) const { return (gpu_driver_bugs_.count(feature) == 1); } size_t GpuDataManagerImplPrivate::GetBlacklistedFeatureCount() const { if (use_swiftshader_ || ShouldUseWarp()) return 1; return blacklisted_features_.size(); } void GpuDataManagerImplPrivate::SetDisplayCount(unsigned int display_count) { display_count_ = display_count; } unsigned int GpuDataManagerImplPrivate::GetDisplayCount() const { return display_count_; } gpu::GPUInfo GpuDataManagerImplPrivate::GetGPUInfo() const { return gpu_info_; } void GpuDataManagerImplPrivate::GetGpuProcessHandles( const GpuDataManager::GetGpuProcessHandlesCallback& callback) const { GpuProcessHost::GetProcessHandles(callback); } bool GpuDataManagerImplPrivate::GpuAccessAllowed( std::string* reason) const { if (use_swiftshader_ || ShouldUseWarp()) return true; if (!gpu_process_accessible_) { if (reason) { *reason = "GPU process launch failed."; } return false; } if (card_blacklisted_) { if (reason) { *reason = "GPU access is disabled "; base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableGpu)) *reason += "through commandline switch --disable-gpu."; else *reason += "in chrome://settings."; } return false; } // We only need to block GPU process if more features are disallowed other // than those in the preliminary gpu feature flags because the latter work // through renderer commandline switches. std::set<int> features = preliminary_blacklisted_features_; gpu::MergeFeatureSets(&features, blacklisted_features_); if (features.size() > preliminary_blacklisted_features_.size()) { if (reason) { *reason = "Features are disabled upon full but not preliminary GPU info."; } return false; } if (blacklisted_features_.size() == gpu::NUMBER_OF_GPU_FEATURE_TYPES) { // On Linux, we use cached GL strings to make blacklist decsions at browser // startup time. We need to launch the GPU process to validate these // strings even if all features are blacklisted. If all GPU features are // disabled, the GPU process will only initialize GL bindings, create a GL // context, and collect full GPU info. #if !defined(OS_LINUX) if (reason) { *reason = "All GPU features are blacklisted."; } return false; #endif } return true; } void GpuDataManagerImplPrivate::RequestCompleteGpuInfoIfNeeded() { if (complete_gpu_info_already_requested_ || IsCompleteGpuInfoAvailable()) return; complete_gpu_info_already_requested_ = true; GpuProcessHost::SendOnIO( #if defined(OS_WIN) GpuProcessHost::GPU_PROCESS_KIND_UNSANDBOXED, #else GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, #endif CAUSE_FOR_GPU_LAUNCH_GPUDATAMANAGER_REQUESTCOMPLETEGPUINFOIFNEEDED, new GpuMsg_CollectGraphicsInfo()); } bool GpuDataManagerImplPrivate::IsEssentialGpuInfoAvailable() const { if (gpu_info_.basic_info_state == gpu::kCollectInfoNone || gpu_info_.context_info_state == gpu::kCollectInfoNone) { return false; } return true; } bool GpuDataManagerImplPrivate::IsCompleteGpuInfoAvailable() const { #if defined(OS_WIN) if (gpu_info_.dx_diagnostics_info_state == gpu::kCollectInfoNone) return false; #endif return IsEssentialGpuInfoAvailable(); } void GpuDataManagerImplPrivate::RequestVideoMemoryUsageStatsUpdate() const { GpuProcessHost::SendOnIO( GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH, new GpuMsg_GetVideoMemoryUsageStats()); } bool GpuDataManagerImplPrivate::ShouldUseSwiftShader() const { return use_swiftshader_; } void GpuDataManagerImplPrivate::RegisterSwiftShaderPath( const base::FilePath& path) { swiftshader_path_ = path; EnableSwiftShaderIfNecessary(); } bool GpuDataManagerImplPrivate::ShouldUseWarp() const { return use_warp_ || CommandLine::ForCurrentProcess()->HasSwitch(switches::kUseWarp); } void GpuDataManagerImplPrivate::AddObserver(GpuDataManagerObserver* observer) { GpuDataManagerImpl::UnlockedSession session(owner_); observer_list_->AddObserver(observer); } void GpuDataManagerImplPrivate::RemoveObserver( GpuDataManagerObserver* observer) { GpuDataManagerImpl::UnlockedSession session(owner_); observer_list_->RemoveObserver(observer); } void GpuDataManagerImplPrivate::UnblockDomainFrom3DAPIs(const GURL& url) { // This method must do two things: // // 1. If the specific domain is blocked, then unblock it. // // 2. Reset our notion of how many GPU resets have occurred recently. // This is necessary even if the specific domain was blocked. // Otherwise, if we call Are3DAPIsBlocked with the same domain right // after unblocking it, it will probably still be blocked because of // the recent GPU reset caused by that domain. // // These policies could be refined, but at a certain point the behavior // will become difficult to explain. std::string domain = GetDomainFromURL(url); blocked_domains_.erase(domain); timestamps_of_gpu_resets_.clear(); } void GpuDataManagerImplPrivate::DisableGpuWatchdog() { GpuProcessHost::SendOnIO( GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH, new GpuMsg_DisableWatchdog); } void GpuDataManagerImplPrivate::SetGLStrings(const std::string& gl_vendor, const std::string& gl_renderer, const std::string& gl_version) { if (gl_vendor.empty() && gl_renderer.empty() && gl_version.empty()) return; // If GPUInfo already got GL strings, do nothing. This is for the rare // situation where GPU process collected GL strings before this call. if (!gpu_info_.gl_vendor.empty() || !gpu_info_.gl_renderer.empty() || !gpu_info_.gl_version.empty()) return; gpu::GPUInfo gpu_info = gpu_info_; gpu_info.gl_vendor = gl_vendor; gpu_info.gl_renderer = gl_renderer; gpu_info.gl_version = gl_version; gpu::CollectDriverInfoGL(&gpu_info); UpdateGpuInfo(gpu_info); UpdateGpuSwitchingManager(gpu_info); UpdatePreliminaryBlacklistedFeatures(); } void GpuDataManagerImplPrivate::GetGLStrings(std::string* gl_vendor, std::string* gl_renderer, std::string* gl_version) { DCHECK(gl_vendor && gl_renderer && gl_version); *gl_vendor = gpu_info_.gl_vendor; *gl_renderer = gpu_info_.gl_renderer; *gl_version = gpu_info_.gl_version; } void GpuDataManagerImplPrivate::Initialize() { TRACE_EVENT0("startup", "GpuDataManagerImpl::Initialize"); if (finalized_) { DVLOG(0) << "GpuDataManagerImpl marked as finalized; skipping Initialize"; return; } const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kSkipGpuDataLoading)) return; gpu::GPUInfo gpu_info; if (command_line->GetSwitchValueASCII( switches::kUseGL) == gfx::kGLImplementationOSMesaName) { // If using the OSMesa GL implementation, use fake vendor and device ids to // make sure it never gets blacklisted. This is better than simply // cancelling GPUInfo gathering as it allows us to proceed with loading the // blacklist below which may have non-device specific entries we want to // apply anyways (e.g., OS version blacklisting). gpu_info.gpu.vendor_id = 0xffff; gpu_info.gpu.device_id = 0xffff; // Also declare the driver_vendor to be osmesa to be able to specify // exceptions based on driver_vendor==osmesa for some blacklist rules. gpu_info.driver_vendor = gfx::kGLImplementationOSMesaName; } else { TRACE_EVENT0("startup", "GpuDataManagerImpl::Initialize:CollectBasicGraphicsInfo"); gpu::CollectBasicGraphicsInfo(&gpu_info); } #if defined(ARCH_CPU_X86_FAMILY) if (!gpu_info.gpu.vendor_id || !gpu_info.gpu.device_id) { gpu_info.context_info_state = gpu::kCollectInfoNonFatalFailure; #if defined(OS_WIN) gpu_info.dx_diagnostics_info_state = gpu::kCollectInfoNonFatalFailure; #endif // OS_WIN } #endif // ARCH_CPU_X86_FAMILY std::string gpu_blacklist_string; std::string gpu_driver_bug_list_string; if (!command_line->HasSwitch(switches::kIgnoreGpuBlacklist) && !command_line->HasSwitch(switches::kUseGpuInTests)) { gpu_blacklist_string = gpu::kSoftwareRenderingListJson; } if (!command_line->HasSwitch(switches::kDisableGpuDriverBugWorkarounds)) { gpu_driver_bug_list_string = gpu::kGpuDriverBugListJson; } InitializeImpl(gpu_blacklist_string, gpu_driver_bug_list_string, gpu_info); } void GpuDataManagerImplPrivate::UpdateGpuInfoHelper() { GetContentClient()->SetGpuInfo(gpu_info_); if (gpu_blacklist_) { std::set<int> features = gpu_blacklist_->MakeDecision( gpu::GpuControlList::kOsAny, std::string(), gpu_info_); if (update_histograms_) UpdateStats(gpu_info_, gpu_blacklist_.get(), features); UpdateBlacklistedFeatures(features); } if (gpu_driver_bug_list_) { gpu_driver_bugs_ = gpu_driver_bug_list_->MakeDecision( gpu::GpuControlList::kOsAny, std::string(), gpu_info_); } gpu::GpuDriverBugList::AppendWorkaroundsFromCommandLine( &gpu_driver_bugs_, *base::CommandLine::ForCurrentProcess()); // We have to update GpuFeatureType before notify all the observers. NotifyGpuInfoUpdate(); } void GpuDataManagerImplPrivate::UpdateGpuInfo(const gpu::GPUInfo& gpu_info) { // No further update of gpu_info if falling back to SwiftShader. if (use_swiftshader_ || ShouldUseWarp()) return; gpu::MergeGPUInfo(&gpu_info_, gpu_info); if (IsCompleteGpuInfoAvailable()) complete_gpu_info_already_requested_ = true; UpdateGpuInfoHelper(); } void GpuDataManagerImplPrivate::UpdateVideoMemoryUsageStats( const GPUVideoMemoryUsageStats& video_memory_usage_stats) { GpuDataManagerImpl::UnlockedSession session(owner_); observer_list_->Notify(&GpuDataManagerObserver::OnVideoMemoryUsageStatsUpdate, video_memory_usage_stats); } void GpuDataManagerImplPrivate::AppendRendererCommandLine( base::CommandLine* command_line) const { DCHECK(command_line); if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) && !command_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) command_line->AppendSwitch(switches::kDisableAcceleratedVideoDecode); #if defined(ENABLE_WEBRTC) if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE) && !command_line->HasSwitch(switches::kDisableWebRtcHWEncoding)) command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding); #endif #if defined(USE_AURA) if (!CanUseGpuBrowserCompositor()) command_line->AppendSwitch(switches::kDisableGpuCompositing); #endif } void GpuDataManagerImplPrivate::AppendGpuCommandLine( base::CommandLine* command_line) const { DCHECK(command_line); std::string use_gl = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kUseGL); base::FilePath swiftshader_path = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kSwiftShaderPath); if (gpu_driver_bugs_.find(gpu::DISABLE_D3D11) != gpu_driver_bugs_.end()) command_line->AppendSwitch(switches::kDisableD3D11); if (use_swiftshader_) { command_line->AppendSwitchASCII(switches::kUseGL, "swiftshader"); if (swiftshader_path.empty()) swiftshader_path = swiftshader_path_; } else if ((IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL) || IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING) || IsFeatureBlacklisted( gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) && (use_gl == "any")) { command_line->AppendSwitchASCII( switches::kUseGL, gfx::kGLImplementationOSMesaName); } else if (!use_gl.empty()) { command_line->AppendSwitchASCII(switches::kUseGL, use_gl); } if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "true"); else command_line->AppendSwitchASCII(switches::kSupportsDualGpus, "false"); if (!swiftshader_path.empty()) { command_line->AppendSwitchPath(switches::kSwiftShaderPath, swiftshader_path); } if (!gpu_driver_bugs_.empty()) { command_line->AppendSwitchASCII(switches::kGpuDriverBugWorkarounds, IntSetToString(gpu_driver_bugs_)); } if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) && !command_line->HasSwitch(switches::kDisableAcceleratedVideoDecode)) { command_line->AppendSwitch(switches::kDisableAcceleratedVideoDecode); } #if defined(ENABLE_WEBRTC) if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_ENCODE) && !command_line->HasSwitch(switches::kDisableWebRtcHWEncoding)) { command_line->AppendSwitch(switches::kDisableWebRtcHWEncoding); } #endif // Pass GPU and driver information to GPU process. We try to avoid full GPU // info collection at GPU process startup, but we need gpu vendor_id, // device_id, driver_vendor, driver_version for deciding whether we need to // collect full info (on Linux) and for crash reporting purpose. command_line->AppendSwitchASCII(switches::kGpuVendorID, base::StringPrintf("0x%04x", gpu_info_.gpu.vendor_id)); command_line->AppendSwitchASCII(switches::kGpuDeviceID, base::StringPrintf("0x%04x", gpu_info_.gpu.device_id)); command_line->AppendSwitchASCII(switches::kGpuDriverVendor, gpu_info_.driver_vendor); command_line->AppendSwitchASCII(switches::kGpuDriverVersion, gpu_info_.driver_version); if (ShouldUseWarp()) command_line->AppendSwitch(switches::kUseWarp); } void GpuDataManagerImplPrivate::AppendPluginCommandLine( base::CommandLine* command_line) const { DCHECK(command_line); #if defined(OS_MACOSX) // TODO(jbauman): Add proper blacklist support for core animation plugins so // special-casing this video card won't be necessary. See // http://crbug.com/134015 if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING)) { if (!command_line->HasSwitch( switches::kDisableCoreAnimationPlugins)) command_line->AppendSwitch( switches::kDisableCoreAnimationPlugins); } #endif } void GpuDataManagerImplPrivate::UpdateRendererWebPrefs( WebPreferences* prefs) const { DCHECK(prefs); if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_WEBGL)) { prefs->experimental_webgl_enabled = false; prefs->pepper_3d_enabled = false; } if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH3D)) prefs->flash_3d_enabled = false; if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D)) { prefs->flash_stage3d_enabled = false; prefs->flash_stage3d_baseline_enabled = false; } if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_FLASH_STAGE3D_BASELINE)) prefs->flash_stage3d_baseline_enabled = false; if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_2D_CANVAS)) prefs->accelerated_2d_canvas_enabled = false; if (IsDriverBugWorkaroundActive(gpu::DISABLE_MULTISAMPLING) || (IsDriverBugWorkaroundActive(gpu::DISABLE_MULTIMONITOR_MULTISAMPLING) && display_count_ > 1)) prefs->gl_multisampling_enabled = false; #if defined(USE_AURA) if (!CanUseGpuBrowserCompositor()) { prefs->accelerated_2d_canvas_enabled = false; prefs->pepper_3d_enabled = false; } #endif if (!IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_ACCELERATED_VIDEO_DECODE) && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableAcceleratedVideoDecode)) { prefs->pepper_accelerated_video_decode_enabled = true; } } void GpuDataManagerImplPrivate::DisableHardwareAcceleration() { card_blacklisted_ = true; for (int i = 0; i < gpu::NUMBER_OF_GPU_FEATURE_TYPES; ++i) blacklisted_features_.insert(i); EnableWarpIfNecessary(); EnableSwiftShaderIfNecessary(); NotifyGpuInfoUpdate(); } std::string GpuDataManagerImplPrivate::GetBlacklistVersion() const { if (gpu_blacklist_) return gpu_blacklist_->version(); return "0"; } std::string GpuDataManagerImplPrivate::GetDriverBugListVersion() const { if (gpu_driver_bug_list_) return gpu_driver_bug_list_->version(); return "0"; } void GpuDataManagerImplPrivate::GetBlacklistReasons( base::ListValue* reasons) const { if (gpu_blacklist_) gpu_blacklist_->GetReasons(reasons, "disabledFeatures"); if (gpu_driver_bug_list_) gpu_driver_bug_list_->GetReasons(reasons, "workarounds"); } void GpuDataManagerImplPrivate::GetDriverBugWorkarounds( base::ListValue* workarounds) const { for (std::set<int>::const_iterator it = gpu_driver_bugs_.begin(); it != gpu_driver_bugs_.end(); ++it) { workarounds->AppendString( gpu::GpuDriverBugWorkaroundTypeToString( static_cast<gpu::GpuDriverBugWorkaroundType>(*it))); } } void GpuDataManagerImplPrivate::AddLogMessage( int level, const std::string& header, const std::string& message) { log_messages_.push_back(LogMessage(level, header, message)); } void GpuDataManagerImplPrivate::ProcessCrashed( base::TerminationStatus exit_code) { if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) { // Unretained is ok, because it's posted to UI thread, the thread // where the singleton GpuDataManagerImpl lives until the end. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&GpuDataManagerImpl::ProcessCrashed, base::Unretained(owner_), exit_code)); return; } { gpu_info_.process_crash_count = GpuProcessHost::gpu_crash_count(); GpuDataManagerImpl::UnlockedSession session(owner_); observer_list_->Notify( &GpuDataManagerObserver::OnGpuProcessCrashed, exit_code); } } base::ListValue* GpuDataManagerImplPrivate::GetLogMessages() const { base::ListValue* value = new base::ListValue; for (size_t ii = 0; ii < log_messages_.size(); ++ii) { base::DictionaryValue* dict = new base::DictionaryValue(); dict->SetInteger("level", log_messages_[ii].level); dict->SetString("header", log_messages_[ii].header); dict->SetString("message", log_messages_[ii].message); value->Append(dict); } return value; } void GpuDataManagerImplPrivate::HandleGpuSwitch() { GpuDataManagerImpl::UnlockedSession session(owner_); // Notify observers in the browser process. ui::GpuSwitchingManager::GetInstance()->NotifyGpuSwitched(); // Pass the notification to the GPU process to notify observers there. GpuProcessHost::SendOnIO( GpuProcessHost::GPU_PROCESS_KIND_SANDBOXED, CAUSE_FOR_GPU_LAUNCH_NO_LAUNCH, new GpuMsg_GpuSwitched); } bool GpuDataManagerImplPrivate::UpdateActiveGpu( uint32 vendor_id, uint32 device_id) { if (gpu_info_.gpu.vendor_id == vendor_id && gpu_info_.gpu.device_id == device_id) { // The primary GPU is active. if (gpu_info_.gpu.active) return false; gpu_info_.gpu.active = true; for (size_t ii = 0; ii < gpu_info_.secondary_gpus.size(); ++ii) gpu_info_.secondary_gpus[ii].active = false; } else { // A secondary GPU is active. for (size_t ii = 0; ii < gpu_info_.secondary_gpus.size(); ++ii) { if (gpu_info_.secondary_gpus[ii].vendor_id == vendor_id && gpu_info_.secondary_gpus[ii].device_id == device_id) { if (gpu_info_.secondary_gpus[ii].active) return false; gpu_info_.secondary_gpus[ii].active = true; } else { gpu_info_.secondary_gpus[ii].active = false; } } gpu_info_.gpu.active = false; } UpdateGpuInfoHelper(); return true; } bool GpuDataManagerImplPrivate::CanUseGpuBrowserCompositor() const { if (CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableGpuCompositing)) return false; if (ShouldUseWarp()) return true; if (ShouldUseSwiftShader()) return false; if (IsFeatureBlacklisted(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING)) return false; return true; } void GpuDataManagerImplPrivate::BlockDomainFrom3DAPIs( const GURL& url, GpuDataManagerImpl::DomainGuilt guilt) { BlockDomainFrom3DAPIsAtTime(url, guilt, base::Time::Now()); } bool GpuDataManagerImplPrivate::Are3DAPIsBlocked(const GURL& url, int render_process_id, int render_view_id, ThreeDAPIType requester) { bool blocked = Are3DAPIsBlockedAtTime(url, base::Time::Now()) != GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED; if (blocked) { // Unretained is ok, because it's posted to UI thread, the thread // where the singleton GpuDataManagerImpl lives until the end. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&GpuDataManagerImpl::Notify3DAPIBlocked, base::Unretained(owner_), url, render_process_id, render_view_id, requester)); } return blocked; } void GpuDataManagerImplPrivate::DisableDomainBlockingFor3DAPIsForTesting() { domain_blocking_enabled_ = false; } // static GpuDataManagerImplPrivate* GpuDataManagerImplPrivate::Create( GpuDataManagerImpl* owner) { return new GpuDataManagerImplPrivate(owner); } GpuDataManagerImplPrivate::GpuDataManagerImplPrivate( GpuDataManagerImpl* owner) : complete_gpu_info_already_requested_(false), observer_list_(new GpuDataManagerObserverList), use_swiftshader_(false), use_warp_(false), card_blacklisted_(false), update_histograms_(true), window_count_(0), domain_blocking_enabled_(true), owner_(owner), display_count_(0), gpu_process_accessible_(true), finalized_(false) { DCHECK(owner_); const base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kDisableGpu)) DisableHardwareAcceleration(); #if defined(OS_MACOSX) CGGetActiveDisplayList (0, NULL, &display_count_); CGDisplayRegisterReconfigurationCallback(DisplayReconfigCallback, owner_); #endif // OS_MACOSX // For testing only. if (command_line->HasSwitch(switches::kDisableDomainBlockingFor3DAPIs)) { domain_blocking_enabled_ = false; } } GpuDataManagerImplPrivate::~GpuDataManagerImplPrivate() { #if defined(OS_MACOSX) CGDisplayRemoveReconfigurationCallback(DisplayReconfigCallback, owner_); #endif } void GpuDataManagerImplPrivate::InitializeImpl( const std::string& gpu_blacklist_json, const std::string& gpu_driver_bug_list_json, const gpu::GPUInfo& gpu_info) { const bool log_gpu_control_list_decisions = base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kLogGpuControlListDecisions); if (!gpu_blacklist_json.empty()) { gpu_blacklist_.reset(gpu::GpuBlacklist::Create()); if (log_gpu_control_list_decisions) gpu_blacklist_->enable_control_list_logging("gpu_blacklist"); bool success = gpu_blacklist_->LoadList( gpu_blacklist_json, gpu::GpuControlList::kCurrentOsOnly); DCHECK(success); } if (!gpu_driver_bug_list_json.empty()) { gpu_driver_bug_list_.reset(gpu::GpuDriverBugList::Create()); if (log_gpu_control_list_decisions) gpu_driver_bug_list_->enable_control_list_logging("gpu_driver_bug_list"); bool success = gpu_driver_bug_list_->LoadList( gpu_driver_bug_list_json, gpu::GpuControlList::kCurrentOsOnly); DCHECK(success); } gpu_info_ = gpu_info; UpdateGpuInfo(gpu_info); UpdateGpuSwitchingManager(gpu_info); UpdatePreliminaryBlacklistedFeatures(); } void GpuDataManagerImplPrivate::UpdateBlacklistedFeatures( const std::set<int>& features) { blacklisted_features_ = features; // Force disable using the GPU for these features, even if they would // otherwise be allowed. if (card_blacklisted_) { blacklisted_features_.insert(gpu::GPU_FEATURE_TYPE_GPU_COMPOSITING); blacklisted_features_.insert(gpu::GPU_FEATURE_TYPE_WEBGL); } EnableWarpIfNecessary(); EnableSwiftShaderIfNecessary(); } void GpuDataManagerImplPrivate::UpdatePreliminaryBlacklistedFeatures() { preliminary_blacklisted_features_ = blacklisted_features_; } void GpuDataManagerImplPrivate::UpdateGpuSwitchingManager( const gpu::GPUInfo& gpu_info) { ui::GpuSwitchingManager::GetInstance()->SetGpuCount( gpu_info.secondary_gpus.size() + 1); if (ui::GpuSwitchingManager::GetInstance()->SupportsDualGpus()) { if (gpu_driver_bugs_.count(gpu::FORCE_DISCRETE_GPU) == 1) ui::GpuSwitchingManager::GetInstance()->ForceUseOfDiscreteGpu(); else if (gpu_driver_bugs_.count(gpu::FORCE_INTEGRATED_GPU) == 1) ui::GpuSwitchingManager::GetInstance()->ForceUseOfIntegratedGpu(); } } void GpuDataManagerImplPrivate::NotifyGpuInfoUpdate() { observer_list_->Notify(&GpuDataManagerObserver::OnGpuInfoUpdate); } void GpuDataManagerImplPrivate::EnableSwiftShaderIfNecessary() { if (ShouldUseWarp()) return; if (!GpuAccessAllowed(NULL) || blacklisted_features_.count(gpu::GPU_FEATURE_TYPE_WEBGL)) { if (!swiftshader_path_.empty() && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableSoftwareRasterizer)) use_swiftshader_ = true; } } void GpuDataManagerImplPrivate::EnableWarpIfNecessary() { #if defined(OS_WIN) if (use_warp_) return; // We should only use WARP if we are unable to use the regular GPU for // compositing, and if we in Metro mode. use_warp_ = CommandLine::ForCurrentProcess()->HasSwitch(switches::kViewerConnect) && !CanUseGpuBrowserCompositor(); #endif } void GpuDataManagerImplPrivate::ForceWarpModeForTesting() { use_warp_ = true; } std::string GpuDataManagerImplPrivate::GetDomainFromURL( const GURL& url) const { // For the moment, we just use the host, or its IP address, as the // entry in the set, rather than trying to figure out the top-level // domain. This does mean that a.foo.com and b.foo.com will be // treated independently in the blocking of a given domain, but it // would require a third-party library to reliably figure out the // top-level domain from a URL. if (!url.has_host()) { return std::string(); } return url.host(); } void GpuDataManagerImplPrivate::BlockDomainFrom3DAPIsAtTime( const GURL& url, GpuDataManagerImpl::DomainGuilt guilt, base::Time at_time) { if (!domain_blocking_enabled_) return; std::string domain = GetDomainFromURL(url); DomainBlockEntry& entry = blocked_domains_[domain]; entry.last_guilt = guilt; timestamps_of_gpu_resets_.push_back(at_time); } GpuDataManagerImpl::DomainBlockStatus GpuDataManagerImplPrivate::Are3DAPIsBlockedAtTime( const GURL& url, base::Time at_time) const { if (!domain_blocking_enabled_) return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED; // Note: adjusting the policies in this code will almost certainly // require adjusting the associated unit tests. std::string domain = GetDomainFromURL(url); DomainBlockMap::const_iterator iter = blocked_domains_.find(domain); if (iter != blocked_domains_.end()) { // Err on the side of caution, and assume that if a particular // domain shows up in the block map, it's there for a good // reason and don't let its presence there automatically expire. UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs", BLOCK_STATUS_SPECIFIC_DOMAIN_BLOCKED, BLOCK_STATUS_MAX); return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_BLOCKED; } // Look at the timestamps of the recent GPU resets to see if there are // enough within the threshold which would cause us to blacklist all // domains. This doesn't need to be overly precise -- if time goes // backward due to a system clock adjustment, that's fine. // // TODO(kbr): make this pay attention to the TDR thresholds in the // Windows registry, but make sure it continues to be testable. { std::list<base::Time>::iterator iter = timestamps_of_gpu_resets_.begin(); int num_resets_within_timeframe = 0; while (iter != timestamps_of_gpu_resets_.end()) { base::Time time = *iter; base::TimeDelta delta_t = at_time - time; // If this entry has "expired", just remove it. if (delta_t.InMilliseconds() > kBlockAllDomainsMs) { iter = timestamps_of_gpu_resets_.erase(iter); continue; } ++num_resets_within_timeframe; ++iter; } if (num_resets_within_timeframe >= kNumResetsWithinDuration) { UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs", BLOCK_STATUS_ALL_DOMAINS_BLOCKED, BLOCK_STATUS_MAX); return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_ALL_DOMAINS_BLOCKED; } } UMA_HISTOGRAM_ENUMERATION("GPU.BlockStatusForClient3DAPIs", BLOCK_STATUS_NOT_BLOCKED, BLOCK_STATUS_MAX); return GpuDataManagerImpl::DOMAIN_BLOCK_STATUS_NOT_BLOCKED; } int64 GpuDataManagerImplPrivate::GetBlockAllDomainsDurationInMs() const { return kBlockAllDomainsMs; } void GpuDataManagerImplPrivate::Notify3DAPIBlocked(const GURL& url, int render_process_id, int render_view_id, ThreeDAPIType requester) { GpuDataManagerImpl::UnlockedSession session(owner_); observer_list_->Notify(&GpuDataManagerObserver::DidBlock3DAPIs, url, render_process_id, render_view_id, requester); } void GpuDataManagerImplPrivate::OnGpuProcessInitFailure() { gpu_process_accessible_ = false; gpu_info_.context_info_state = gpu::kCollectInfoFatalFailure; #if defined(OS_WIN) gpu_info_.dx_diagnostics_info_state = gpu::kCollectInfoFatalFailure; #endif complete_gpu_info_already_requested_ = true; // Some observers might be waiting. NotifyGpuInfoUpdate(); } } // namespace content
#include <map> #include "../Baselib/BaseLib.h" #include "../Commands/Commands.h" /*** * Class constructor/distructor implementation. */ Commands::Commands() { } Commands::~Commands() { commands_dic.clear(); } /*** * Add new command name and callback to list of commands. */ bool Commands::Add(std::string name, CommandCb& pCallback) { bool result = true; if(nullptr == this->Find(name)) { this->commands_dic.insert(std::pair<std::string, CommandCb&>(name, pCallback)); } else { result = false; } return(result); } /*** * Find command clallback function in the commands list according to command name. */ CommandCb* Commands::Find(std::string name) { CommandCb* pCommandCb = nullptr; std::map<std::string, CommandCb>::iterator it = this->commands_dic.find(name); if (it != this->commands_dic.end()) { pCommandCb = &(*it).second; } return (pCommandCb); } /*** * Call for command execution providing a list of parameters as strings. */ bool Commands::Exec(std::string name, std::vector<std::string> params) { bool result = false; CommandCb* pCommandCb = this->Find(name); if (nullptr != pCommandCb) { result = (*pCommandCb)(params); } return (result); }
//================================================================================================= /*! // \file src/main/DMatTDMatAdd.cpp // \brief Source file for the dense matrix/transpose dense matrix addition benchmark // // Copyright (C) 2012-2019 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <algorithm> #include <cstdlib> #include <iostream> #include <stdexcept> #include <string> #include <vector> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/Infinity.h> #include <blaze/util/algorithms/Max.h> #include <blaze/util/Random.h> #include <blaze/util/Timing.h> #include <blazemark/blaze/DMatTDMatAdd.h> #include <blazemark/blaze/init/DynamicMatrix.h> #include <blazemark/blitz/DMatTDMatAdd.h> #include <blazemark/boost/DMatTDMatAdd.h> #include <blazemark/eigen/DMatTDMatAdd.h> #include <blazemark/flens/DMatTDMatAdd.h> #include <blazemark/mtl/DMatTDMatAdd.h> #include <blazemark/system/Blitz.h> #include <blazemark/system/Boost.h> #include <blazemark/system/Config.h> #include <blazemark/system/Eigen.h> #include <blazemark/system/FLENS.h> #include <blazemark/system/MTL.h> #include <blazemark/system/Types.h> #include <blazemark/util/Benchmarks.h> #include <blazemark/util/DynamicDenseRun.h> #include <blazemark/util/Parser.h> #ifdef BLAZE_USE_HPX_THREADS # include <hpx/hpx_main.hpp> #endif //************************************************************************************************* // Using declarations //************************************************************************************************* using blazemark::Benchmarks; using blazemark::DynamicDenseRun; using blazemark::Parser; //================================================================================================= // // TYPE DEFINITIONS // //================================================================================================= //************************************************************************************************* /*!\brief Type of a benchmark run. // // This type definition specifies the type of a single benchmark run for the dense // matrix/transpose dense matrix addition benchmark. */ using Run = DynamicDenseRun; //************************************************************************************************* //================================================================================================= // // UTILITY FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Estimating the necessary number of steps for each benchmark. // // \param run The parameters for the benchmark run. // \return void // // This function estimates the necessary number of steps for the given benchmark based on the // performance of the Blaze library. */ void estimateSteps( Run& run ) { using blazemark::element_t; using blaze::rowMajor; using blaze::columnMajor; ::blaze::setSeed( ::blazemark::seed ); const size_t N( run.getSize() ); blaze::DynamicMatrix<element_t,rowMajor> A( N, N ), C( N, N ); blaze::DynamicMatrix<element_t,columnMajor> B( N, N ); blaze::timing::WcTimer timer; double wct( 0.0 ); size_t steps( 1UL ); blazemark::blaze::init( A ); blazemark::blaze::init( B ); while( true ) { timer.start(); for( size_t i=0UL; i<steps; ++i ) { C = A + B; } timer.end(); wct = timer.last(); if( wct >= 0.2 ) break; steps *= 2UL; } if( C.rows() != N ) std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n"; const size_t estimatedSteps( ( blazemark::runtime * steps ) / timer.last() ); run.setSteps( blaze::max( 1UL, estimatedSteps ) ); } //************************************************************************************************* //************************************************************************************************* /*!\brief Estimating the necessary number of floating point operations. // // \param run The parameters for the benchmark run. // \return void // // This function estimates the number of floating point operations required for a single // computation of the (composite) arithmetic operation. */ void estimateFlops( Run& run ) { const size_t N( run.getSize() ); run.setFlops( N*N ); } //************************************************************************************************* //================================================================================================= // // BENCHMARK FUNCTIONS // //================================================================================================= //************************************************************************************************* /*!\brief Dense matrix/transpose dense matrix addition benchmark function. // // \param runs The specified benchmark runs. // \param benchmarks The selection of benchmarks. // \return void */ void dmattdmatadd( std::vector<Run>& runs, Benchmarks benchmarks ) { std::cout << std::left; std::sort( runs.begin(), runs.end() ); size_t slowSize( blaze::inf ); for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { estimateFlops( *run ); if( run->getSteps() == 0UL ) { if( run->getSize() < slowSize ) { estimateSteps( *run ); if( run->getSteps() == 1UL ) slowSize = run->getSize(); } else run->setSteps( 1UL ); } } if( benchmarks.runBlaze ) { std::cout << " Blaze [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setBlazeResult( blazemark::blaze::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBlazeResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #if BLAZEMARK_BOOST_MODE if( benchmarks.runBoost ) { std::cout << " Boost uBLAS [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setBoostResult( blazemark::boost::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBoostResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_BLITZ_MODE if( benchmarks.runBlitz ) { std::cout << " Blitz++ [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setBlitzResult( blazemark::blitz::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getBlitzResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_FLENS_MODE if( benchmarks.runFLENS ) { std::cout << " FLENS [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setFLENSResult( blazemark::flens::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getFLENSResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_MTL_MODE if( benchmarks.runMTL ) { std::cout << " MTL [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setMTLResult( blazemark::mtl::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getMTLResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif #if BLAZEMARK_EIGEN_MODE if( benchmarks.runEigen ) { std::cout << " Eigen [MFlop/s]:\n"; for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { const size_t N ( run->getSize() ); const size_t steps( run->getSteps() ); run->setEigenResult( blazemark::eigen::dmattdmatadd( N, steps ) ); const double mflops( run->getFlops() * steps / run->getEigenResult() / 1E6 ); std::cout << " " << std::setw(12) << N << mflops << std::endl; } } #endif for( std::vector<Run>::iterator run=runs.begin(); run!=runs.end(); ++run ) { std::cout << *run; } } //************************************************************************************************* //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* /*!\brief The main function for the dense matrix/transpose dense matrix addition benchmark. // // \param argc The total number of command line arguments. // \param argv The array of command line arguments. // \return void */ int main( int argc, char** argv ) { std::cout << "\n Dense Matrix/Transpose Dense Matrix Addition:\n"; Benchmarks benchmarks; try { parseCommandLineArguments( argc, argv, benchmarks ); } catch( std::exception& ex ) { std::cerr << " " << ex.what() << "\n"; return EXIT_FAILURE; } const std::string installPath( INSTALL_PATH ); const std::string parameterFile( installPath + "/params/dmattdmatadd.prm" ); Parser<Run> parser; std::vector<Run> runs; try { parser.parse( parameterFile.c_str(), runs ); } catch( std::exception& ex ) { std::cerr << " Error during parameter extraction: " << ex.what() << "\n"; return EXIT_FAILURE; } try { dmattdmatadd( runs, benchmarks ); } catch( std::exception& ex ) { std::cerr << " Error during benchmark execution: " << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
// ========================================================================== // Munin List Component. // // Copyright (C) 2011 Matthew Chaplain, All Rights Reserved. // // Permission to reproduce, distribute, perform, display, and to prepare // derivitive works from this file under the following conditions: // // 1. Any copy, reproduction or derivitive work of any part of this file // contains this copyright notice and licence in its entirety. // // 2. The rights granted to you under this license automatically terminate // should you attempt to assert any patent claims against the licensor // or contributors, which in any way restrict the ability of any party // from using this software or portions thereof in any form under the // terms of this license. // // Disclaimer: 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 "munin/list.hpp" #include "munin/context.hpp" #include <terminalpp/canvas_view.hpp> #include <terminalpp/string.hpp> #include <terminalpp/virtual_key.hpp> namespace munin { // ========================================================================== // LIST::IMPLEMENTATION STRUCTURE // ========================================================================== struct list::impl { // ====================================================================== // CONSTRUCTOR // ====================================================================== impl(list &self) : self_(self) { } // ====================================================================== // DO_CURSOR_UP_KEY_EVENT // ====================================================================== void do_cursor_up_key_event(odin::u32 times) { if (odin::s32(times) >= item_index_) { self_.set_item_index(0); } else { self_.set_item_index(item_index_ - times); } } // ====================================================================== // DO_CURSOR_DOWN_KEY_EVENT // ====================================================================== void do_cursor_down_key_event(odin::u32 times) { self_.set_item_index(item_index_ + times); } // ====================================================================== // DO_HOME_KEY_EVENT // ====================================================================== void do_home_key_event() { self_.set_item_index(0); } // ====================================================================== // DO_END_KEY_EVENT // ====================================================================== void do_end_key_event() { self_.set_item_index(items_.size() - 1); } // ====================================================================== // DO_VK_EVENT // ====================================================================== void do_vk_event(terminalpp::virtual_key const &vk) { switch (vk.key) { case terminalpp::vk::cursor_up : do_cursor_up_key_event(vk.repeat_count); break; case terminalpp::vk::cursor_down : do_cursor_down_key_event(vk.repeat_count); break; case terminalpp::vk::home : do_home_key_event(); break; case terminalpp::vk::end : do_end_key_event(); break; case terminalpp::vk::bs : // fall-through case terminalpp::vk::del : self_.set_item_index(-1); break; default : // Do nothing. break; } } // ====================================================================== // DO_MOUSE_EVENT // ====================================================================== void do_mouse_event(terminalpp::ansi::mouse::report const &report) { if (report.button_ == terminalpp::ansi::mouse::report::LEFT_BUTTON_DOWN) { auto item_selected = report.y_position_; if (odin::u32(item_selected) <= items_.size()) { if (self_.get_item_index() == item_selected) { self_.set_item_index(-1); } else { self_.set_item_index(item_selected); } } self_.set_focus(); } } list &self_; std::vector<terminalpp::string> items_; odin::s32 item_index_; }; // ========================================================================== // CONSTRUCTOR // ========================================================================== list::list() { pimpl_ = std::make_shared<impl>(std::ref(*this)); pimpl_->item_index_ = -1; } // ========================================================================== // DESTRUCTOR // ========================================================================== list::~list() { } // ========================================================================== // SET_ITEMS // ========================================================================== void list::set_items(std::vector<terminalpp::string> const &items) { auto old_items_size = pimpl_->items_.size(); auto size = get_size(); pimpl_->items_ = std::move(items); // If the displayed item index was previously valid, then ensure that the // currently selected item is not a non-existent item. if (get_item_index() != -1) { set_item_index((std::min)(old_items_size - 1, items.size() - 1)); } // We will probably require redrawing the entire component. on_redraw({rectangle({}, size)}); // This may well change the preferred size of this component. on_preferred_size_changed(); } // ========================================================================== // SET_ITEM_INDEX // ========================================================================== void list::set_item_index(odin::s32 index) { auto old_index = pimpl_->item_index_; if (index >= odin::s32(pimpl_->items_.size())) { index = pimpl_->items_.size() - 1; } pimpl_->item_index_ = index; // We will need to redraw the item both at the old index and the new // index. auto size = get_size(); if (old_index >= 0) { on_redraw({ rectangle( terminalpp::point(0, old_index) , terminalpp::extent(size.width, 1))}); } if (index >= 0) { on_redraw({ rectangle( terminalpp::point(0, index) , terminalpp::extent(size.width, 1))}); } on_item_changed(old_index); on_cursor_position_changed(get_cursor_position()); } // ========================================================================== // GET_ITEM_INDEX // ========================================================================== odin::s32 list::get_item_index() const { return pimpl_->item_index_; } // ========================================================================== // GET_ITEM // ========================================================================== terminalpp::string list::get_item() const { return pimpl_->item_index_ < 0 ? terminalpp::string() : pimpl_->items_[pimpl_->item_index_]; } // ========================================================================== // DO_GET_PREFERRED_SIZE // ========================================================================== terminalpp::extent list::do_get_preferred_size() const { // The preferred size of this component is the widest item wide, and // the number of components high. odin::u32 max_width = 0; for (auto const &item : pimpl_->items_) { max_width = (std::max)(max_width, odin::u32(item.size())); } return terminalpp::extent(max_width, pimpl_->items_.size()); } // ========================================================================== // DO_GET_CURSOR_POSITION // ========================================================================== terminalpp::point list::do_get_cursor_position() const { // The 'cursor' is the selected element, or (0,0) if none is selected. return terminalpp::point( 0 , pimpl_->item_index_ == -1 ? 0 : pimpl_->item_index_); } // ========================================================================== // DO_SET_CURSOR_POSITION // ========================================================================== void list::do_set_cursor_position(terminalpp::point const &position) { set_item_index(position.y); } // ========================================================================== // DO_DRAW // ========================================================================== void list::do_draw( context &ctx , rectangle const &region) { static terminalpp::element const default_element(' '); auto &cvs = ctx.get_canvas(); for (odin::s32 y_coord = region.origin.y; y_coord < region.origin.y + region.size.height; ++y_coord) { if (y_coord < odin::s32(pimpl_->items_.size())) { bool is_selected_item = y_coord >= 0 && y_coord == pimpl_->item_index_; auto item = pimpl_->items_[y_coord]; for (odin::s32 x_coord = region.origin.x; x_coord < region.origin.x + region.size.width; ++x_coord) { auto element = x_coord < odin::s32(item.size()) ? item[x_coord] : default_element; if (is_selected_item) { element.attribute_.polarity_.value_ = element.attribute_.polarity_.value_ == terminalpp::ansi::graphics::polarity::negative ? terminalpp::ansi::graphics::polarity::positive : terminalpp::ansi::graphics::polarity::negative; } cvs[x_coord][y_coord] = element; } } else { for (odin::s32 x_coord = region.origin.x; x_coord < region.origin.x + region.size.width; ++x_coord) { cvs[x_coord][y_coord] = default_element; } } } } // ========================================================================== // DO_EVENT // ========================================================================== void list::do_event(boost::any const &event) { auto const *vk = boost::any_cast<terminalpp::virtual_key>(&event); if (vk) { pimpl_->do_vk_event(*vk); } auto const *report = boost::any_cast<terminalpp::ansi::mouse::report>(&event); if (report) { pimpl_->do_mouse_event(*report); } } // ========================================================================== // MAKE_LIST // ========================================================================== std::shared_ptr<list> make_list() { return std::make_shared<list>(); } }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_class_67b.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml Template File: sources-sinks-67b.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_free_class_67 { typedef struct _structType { TwoIntsClass * structFirst; } structType; #ifndef OMITBAD void badSink(structType myStruct) { TwoIntsClass * data = myStruct.structFirst; /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete to deallocate the memory */ free(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(structType myStruct) { TwoIntsClass * data = myStruct.structFirst; /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete to deallocate the memory */ free(data); } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(structType myStruct) { TwoIntsClass * data = myStruct.structFirst; /* FIX: Deallocate the memory using delete */ delete data; } #endif /* OMITGOOD */ } /* close namespace */
/* The MIT License (MIT) * * Copyright (c) 2015 LabCrypto Org. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANindent_ILITY, * 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 <sys/stat.h> #include <sstream> #include "java_generator.h" #include "../hot.h" #include "../string_helper.h" #include "../os.h" #include "../type_helper.h" namespace org { namespace labcrypto { namespace hottentot { namespace generator { namespace java { void JavaGenerator::GenerateServiceProxy ( ::org::labcrypto::hottentot::generator::Module *pModule ) { int serializableListCounter = 0; ::org::labcrypto::hottentot::generator::Service *pService; std::string basePackageName = pModule->package_; for (uint32_t i = 0; i < pModule->services_.size(); i++) { std::string replacableServiceProxyStrTmp = serviceProxyTmpStr_; pService = pModule->services_.at(i); pService = pModule->services_.at(i); ::org::labcrypto::hottentot::generator::StringHelper::Replace ( replacableServiceProxyStrTmp, "[%INDENT%]", indent_, 1 ); ::org::labcrypto::hottentot::generator::StringHelper::Replace ( replacableServiceProxyStrTmp, "[%BASE_PACKAGE_NAME%]", basePackageName + (extendModule_.size() > 0 ? "." : "") + extendModule_, 1 ); ::org::labcrypto::hottentot::generator::StringHelper::Replace ( replacableServiceProxyStrTmp, "[%SERVICE_NAME%]", pService->name_, 1 ); ::org::labcrypto::hottentot::generator::Method *pMethod; std::string methodsStr; for (uint32_t i = 0; i < pService->methods_.size(); i++) { pMethod = pService->methods_.at(i); std::string fetchedReturnTypeOfList; std::string lowerCaseFetchedReturnTypeOfList; std::string returnType = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaType(pMethod->returnType_); std::string lowerCaseReturnType = pMethod->returnType_; std::string capitalizedReturnType = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pMethod->returnType_); lowerCaseReturnType[0] += 32; if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pMethod->returnType_)) { fetchedReturnTypeOfList = ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pMethod->returnType_); std::string returnTypeOfList = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaClassType(fetchedReturnTypeOfList); returnType = "List<" + returnTypeOfList + ">"; } methodsStr += indent_ + "public " + returnType + " " + pMethod->name_ + "("; ::org::labcrypto::hottentot::generator::Argument *pArg; std::string fetchedArgTypeOfList; std::string argType; for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) { pArg = pMethod->arguments_.at(i); if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pArg->type_)) { fetchedArgTypeOfList = ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pArg->type_); std::string argTypeOfList = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaClassType(fetchedArgTypeOfList); argType = "List<" + argTypeOfList + ">"; } else { argType = ::org::labcrypto::hottentot::generator::TypeHelper::GetJavaType(pArg->type_); } methodsStr += argType + " " + pArg->variable_; if (i < pMethod->arguments_.size() - 1) { methodsStr += ","; } } methodsStr += ") { \n"; for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) { pArg = pMethod->arguments_.at(i); methodsStr += indent_ + indent_ + "//serialize " + pArg->variable_ + "\n"; std::string capitalalizedArgVar = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_); if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pArg->type_)) { std::string fetchedArgTypeOfList; serializableListCounter++; std::stringstream serializableListCounterStream; serializableListCounterStream << serializableListCounter; fetchedArgTypeOfList = ::org::labcrypto::hottentot::generator::TypeHelper::FetchTypeOfList(pArg->type_); std::string upperCaseArgTypeOfList = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(fetchedArgTypeOfList); methodsStr += indent_ + indent_ + "Serializable" + upperCaseArgTypeOfList + "List " + "serializable" + upperCaseArgTypeOfList + "List_" + serializableListCounterStream.str() + " = new Serializable" + upperCaseArgTypeOfList + "List();\n"; methodsStr += "serializable" + upperCaseArgTypeOfList + "List_" + serializableListCounterStream.str() + ".set" + upperCaseArgTypeOfList + "List(" + pArg->variable_ + ");\n"; methodsStr += "byte[] serialized" + capitalalizedArgVar + " = serializable" + upperCaseArgTypeOfList + "List_" + serializableListCounterStream.str() + ".serialize();\n"; } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsUDT(pArg->type_)) { methodsStr += indent_ + indent_ + "byte[] serialized" + capitalalizedArgVar + " = " + pArg->variable_ + ".serialize();\n"; } else { std::string pdtWrapperClass = ::org::labcrypto::hottentot::generator::TypeHelper::GetPdtWrapperClassName(pArg->type_); methodsStr += indent_ + indent_ + pdtWrapperClass + " " + pArg->variable_ + "Wrapper = new " + pdtWrapperClass + "(" + pArg->variable_ + ");\n"; methodsStr += indent_ + indent_ + "byte[] serialized" + capitalalizedArgVar + " = " + pArg->variable_ + "Wrapper.serialize();\n"; } } methodsStr += "\n"; methodsStr += indent_ + indent_ + "//make request\n"; methodsStr += indent_ + indent_ + "Request request = new Request();\n"; std::stringstream serviceId; serviceId << pService->GetHash(); methodsStr += indent_ + indent_ + "request.setServiceId(" + serviceId.str() + "L);\n"; std::stringstream methodId; methodId << pMethod->GetHash(); methodsStr += indent_ + indent_ + "request.setMethodId(" + methodId.str() + "L);\n"; std::stringstream argSize; argSize << pMethod->arguments_.size(); methodsStr += indent_ + indent_ + "request.setArgumentCount((byte) " + argSize.str() + ");\n"; methodsStr += indent_ + indent_ + "request.setType(Request.RequestType."; if (pService->serviceType_ == 0) { methodsStr += "InvokeStateless"; } else if (pService->serviceType_ == 1) { methodsStr += "InvokeStatefull"; } methodsStr += ");\n"; for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) { std::stringstream ssI; pArg = pMethod->arguments_.at(i); ssI << i; std::string capitalizedArgVar = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_); methodsStr += indent_ + indent_ + "Argument arg" + ssI.str() + " = new Argument();\n"; methodsStr += indent_ + indent_ + "arg" + ssI.str() + ".setDataLength(" + "serialized" + capitalizedArgVar + ".length);\n"; methodsStr += indent_ + indent_ + "arg" + ssI.str() + ".setData(serialized" + capitalizedArgVar + ");\n"; methodsStr += indent_ + indent_ + "request.addArgument(arg" + ssI.str() + ");\n"; } methodsStr += indent_ + indent_ + "int dataLength = 0;\n"; methodsStr += indent_ + indent_ + "//calculate data length for every argument\n"; for (uint32_t i = 0; i < pMethod->arguments_.size(); i++) { pArg = pMethod->arguments_.at(i); std::string argDataLengthVarName = pArg->variable_ + "DataLength"; std::string capitalizedArgVar = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(pArg->variable_); std::string argDataLengthByteArrayLengthVarName = pArg->variable_ + "DataLengthByteArrayLength"; methodsStr += indent_ + indent_ + "// calulate " + argDataLengthVarName + "\n"; methodsStr += indent_ + indent_ + "int " + argDataLengthVarName + "= serialized" + capitalizedArgVar + ".length;\n"; methodsStr += indent_ + indent_ + "int " + argDataLengthByteArrayLengthVarName + " = 1;\n"; methodsStr += indent_ + indent_ + "if (" + argDataLengthVarName + " >= 0x80) {\n"; methodsStr += indent_ + indent_ + indent_ + "if (" + argDataLengthVarName + " <= 0xff) {\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x81 0xff\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "" + argDataLengthByteArrayLengthVarName + " = 2;\n"; methodsStr += indent_ + indent_ + indent_ + "} else if (" + argDataLengthVarName + " <= 0xffff) {\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x82 0xff 0xff\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "" + argDataLengthByteArrayLengthVarName + " = 3;\n"; methodsStr += indent_ + indent_ + indent_ + "} else if (" + argDataLengthVarName + " <= 0xffffff) {\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "//ex 0x83 0xff 0xff 0xff\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "" + argDataLengthByteArrayLengthVarName + " = 4;\n"; methodsStr += indent_ + indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "dataLength += " + argDataLengthVarName + " + " + argDataLengthByteArrayLengthVarName + ";\n"; } methodsStr += indent_ + indent_ + "// arg count(1) + request type(1) + method ID(4) + service ID(4) = 10;\n"; methodsStr += indent_ + indent_ + "request.setLength(10 + dataLength);\n"; methodsStr += indent_ + indent_ + "// connect to server\n"; methodsStr += indent_ + indent_ + "TcpClient tcpClient = TcpClientFactory.create();\n"; methodsStr += indent_ + indent_ + "try{\n"; methodsStr += indent_ + indent_ + indent_ + "tcpClient.connect(host, port);\n"; methodsStr += indent_ + indent_ + "} catch (TcpClientConnectException e) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "// serialize request according to HTNP\n"; methodsStr += indent_ + indent_ + "Protocol protocol = ProtocolFactory.create();\n"; methodsStr += indent_ + indent_ + "byte[] serializedRequest = protocol.serializeRequest(request);\n"; methodsStr += indent_ + indent_ + "// send request\n"; methodsStr += indent_ + indent_ + "try {\n"; methodsStr += indent_ + indent_ + indent_ + "tcpClient.write(serializedRequest);\n"; methodsStr += indent_ + indent_ + "} catch (TcpClientWriteException e) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n"; methodsStr += indent_ + indent_ + "}\n"; if (!::org::labcrypto::hottentot::generator::TypeHelper::IsVoid(pMethod->returnType_)) { methodsStr += indent_ + indent_ + "// read response from server\n"; methodsStr += indent_ + indent_ + "byte[] buffer = new byte[256];\n"; methodsStr += indent_ + indent_ + "while (!protocol.isResponseComplete()) {\n"; methodsStr += indent_ + indent_ + indent_ + "byte[] dataChunkRead;\n"; methodsStr += indent_ + indent_ + indent_ + "try {\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "dataChunkRead = tcpClient.read();\n"; methodsStr += indent_ + indent_ + indent_ + "} catch (TcpClientReadException e) {\n"; methodsStr += indent_ + indent_ + indent_ + indent_ + "throw new HottentotRuntimeException(e);\n"; methodsStr += indent_ + indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + indent_ + "protocol.processDataForResponse(dataChunkRead);\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "Response response = protocol.getResponse();\n"; methodsStr += indent_ + indent_ + "// close everything\n"; methodsStr += indent_ + indent_ + " try { \n"; methodsStr += indent_ + indent_ + indent_ + " tcpClient.close(); \n"; methodsStr += indent_ + indent_ + "} catch (TcpClientCloseException e) { \n"; methodsStr += indent_ + indent_ + indent_ + "e.printStackTrace(); \n"; methodsStr += indent_ + indent_ + "} \n"; methodsStr += indent_ + indent_ + "//deserialize " + pMethod->returnType_ + "part from response\n"; if (::org::labcrypto::hottentot::generator::TypeHelper::IsListType(pMethod->returnType_)) { std::string upperCaseReturnTypeOfList = ::org::labcrypto::hottentot::generator::StringHelper::MakeFirstCapital(fetchedReturnTypeOfList); serializableListCounter++; std::stringstream serializableListCounterStream; serializableListCounterStream << serializableListCounter; methodsStr += indent_ + indent_ + "Serializable" + upperCaseReturnTypeOfList + "List" + " serializable" + upperCaseReturnTypeOfList + "List_" + serializableListCounterStream.str() + " = null;\n"; methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new MethodNotSupportRuntimeException();\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "serializable" + upperCaseReturnTypeOfList + "List_" + serializableListCounterStream.str() + " = new Serializable" + upperCaseReturnTypeOfList + "List();\n"; methodsStr += indent_ + indent_ + "serializable" + upperCaseReturnTypeOfList + "List_" + serializableListCounterStream.str() + ".deserialize(response.getData());\n"; methodsStr += indent_ + indent_ + "return serializable" + upperCaseReturnTypeOfList + "List_" + serializableListCounterStream.str() + ".get" + upperCaseReturnTypeOfList + "List();\n"; } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsEnum(pMethod->returnType_)) { methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new MethodNotSupportRuntimeException();\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "return " + pMethod->returnType_ + ".deserialize(response.getData());\n"; } else if (::org::labcrypto::hottentot::generator::TypeHelper::IsUDT(pMethod->returnType_)) { methodsStr += indent_ + indent_ + returnType + " " + lowerCaseReturnType + "= null;\n"; methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new MethodNotSupportRuntimeException();\n"; methodsStr += indent_ + indent_ + "}\n"; methodsStr += indent_ + indent_ + "" + lowerCaseReturnType + "= new " + pMethod->returnType_ + "();\n"; methodsStr += indent_ + indent_ + "" + lowerCaseReturnType + ".deserialize(response.getData());\n"; methodsStr += indent_ + indent_ + "return " + lowerCaseReturnType + ";\n"; } else { methodsStr += indent_ + indent_ + "if (response.getStatusCode() == -1) {\n"; methodsStr += indent_ + indent_ + indent_ + "throw new MethodNotSupportRuntimeException();\n"; methodsStr += indent_ + indent_ + "}\n"; std::string pdtWrapperClassName = ::org::labcrypto::hottentot::generator::TypeHelper::GetPdtWrapperClassName (pMethod->returnType_); methodsStr += indent_ + indent_ + pdtWrapperClassName + " ret = new " + pdtWrapperClassName + "();\n"; methodsStr += indent_ + indent_ + "ret.deserialize(response.getData());\n"; methodsStr += indent_ + indent_ + "return ret.getValue();\n"; } } methodsStr += indent_ + "}\n"; } replacableServiceProxyStrTmp.replace ( replacableServiceProxyStrTmp.find("[%METHODS%]"), 11, methodsStr ); std::string packages = ::org::labcrypto::hottentot::generator::StringHelper::Concat ( ::org::labcrypto::hottentot::generator::StringHelper::Split ( pModule->GetPackage() + (extendModule_.size() > 0 ? "." : "") + extendModule_, '.' ), "/" ); ::org::labcrypto::hottentot::generator::Os::MakeDir(outDir_ + "/" + packages); std::string path = outDir_ + "/" + packages + "/" + pService->name_.c_str() + "ServiceProxy.java"; ::org::labcrypto::hottentot::generator::Os::WriteFile(path , replacableServiceProxyStrTmp); } } } // END NAMESPACE java } // END NAMESPACE generator } // END NAMESPACE hottentot } // END NAMESPACE labcrypto } // END NAMESPACE org
/* MIT License * * Copyright (c) 2021 laferenorg * * 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 C */ #ifndef _FGAME_WINDOW_HEADER_ #define _FGAME_WINDOW_HEADER_ /* Include header library SDL2 */ #include <SDL2/SDL.h> /* Include header in include directory from this project */ #include "../FGBegin.hpp" #include "../FGStruct.hpp" class FGAME_CALL FGWindow { /* This class not have private section */ /* Public function for helper window */ /* This class for get information of window */ public: /* This function for get position of window */ void Position(int& x, int& y, const FGData_System& system, std::string& message_error, bool& errorEvent); /* This function for get Size of window */ void Sizes(int& width, int& height, const FGData_System& system, std::string& message_error, bool& errorEvent); }; #endif /* _FGAME_WINDOW_HEADER_ */
#include "langswitch.h" #include <QVBoxLayout> #include <QTranslator> #include <QApplication> LangSwitch::LangSwitch(QWidget *parent) : QWidget(parent) { createScreen(); } void LangSwitch::createScreen() { combo = new QComboBox; combo->addItem("English", "en"); //(a) combo->addItem("Chinese", "zh"); combo->addItem("Latin", "la"); label = new QLabel; refreshLabel(); //设置标签的内容 QVBoxLayout* layout = new QVBoxLayout; layout->addWidget(combo, 1); layout->addWidget(label, 5); setLayout(layout); connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeLang(int))); //(b) } void LangSwitch::refreshLabel() { label->setText(tr("TXT_HELLO_WORLD", "Hello World")); //(a) } void LangSwitch::changeLang(int index) { QString langCode = combo->itemData(index).toString(); //(a) changeTr(langCode); //读取相应的“.qm”文件 refreshLabel(); //刷新标签上的文字 } void LangSwitch::changeTr(const QString& langCode) { static QTranslator* translator; //(a) if (translator != NULL) { qApp->removeTranslator(translator); delete translator; translator = NULL; } translator = new QTranslator; QString qmFilename = "lang_" + langCode; //(b) if (translator->load(QString("D:/Qt/CH14/CH1402/LangSwitch/")+ qmFilename)) { qApp->installTranslator(translator); } } LangSwitch::~LangSwitch() { }
// Author(s): Wieger Wesselink // Copyright: see the accompanying file COPYING or copy at // https://svn.win.tue.nl/trac/MCRL2/browser/trunk/COPYING // // 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) // /// \file action_rename_test.cpp /// \brief Action rename test. #include "mcrl2/lps/action_rename.h" #include "mcrl2/lps/linearise.h" #include "mcrl2/lps/parse.h" #include "mcrl2/lps/remove.h" #include "mcrl2/lps/rewrite.h" #include <boost/test/minimal.hpp> using namespace mcrl2; using lps::stochastic_specification; using lps::action_rename_specification; // using lps::action_rename; static void test1() { // Check a renaming when more than one renaming rule // for one action is present. const std::string SPEC = "act a:Nat; \n" "proc P(n:Nat) = sum m: Nat. a(m). P(m); \n" "init P(0); \n"; const std::string AR_SPEC = "act b,c:Nat;\n" "var n:Nat;\n" "rename \n" " (n>4) -> a(n) => b(n); \n" " (n<22) -> a(n) => c(n); \n"; stochastic_specification spec=lps::linearise(SPEC); std::istringstream ar_spec_stream(AR_SPEC); action_rename_specification ar_spec = parse_action_rename_specification(ar_spec_stream, spec); stochastic_specification new_spec = action_rename(ar_spec,spec); BOOST_CHECK(new_spec.process().summand_count()==3); } static void test2() { // Check whether new declarations in the rename file // are read properly. Check for renamings of more than one action. const std::string SPEC = "act a,b:Nat; \n" "proc P(n:Nat) = sum m: Nat. a(m). P(m); \n" "init P(0); \n"; const std::string AR_SPEC = "map f:Nat->Nat; \n" "var n':Nat; \n" "eqn f(n')=3; \n" "act c:Nat; \n" "var n:Nat; \n" "rename \n" " (f(n)>23) -> a(n) => b(n); \n" " b(n) => c(n); \n"; stochastic_specification spec=lps::linearise(SPEC); std::istringstream ar_spec_stream(AR_SPEC); action_rename_specification ar_spec = parse_action_rename_specification(ar_spec_stream, spec); stochastic_specification new_spec = action_rename(ar_spec,spec); BOOST_CHECK(new_spec.process().summand_count()==2); } static void test3() { // Check whether constants in an action_rename file are properly translated. const std::string SPEC = "act a,b:Nat; \n" "proc P(n:Nat) = a(1). P(n)+b(1).P(1); \n" "init P(0); \n"; const std::string AR_SPEC = "rename \n" " a(1) => delta; \n"; stochastic_specification spec=lps::linearise(SPEC); std::istringstream ar_spec_stream(AR_SPEC); action_rename_specification ar_spec = parse_action_rename_specification(ar_spec_stream, spec); data::rewriter R (spec.data(), mcrl2::data::rewriter::strategy()); stochastic_specification new_spec = action_rename(ar_spec,spec); lps::rewrite(new_spec, R); lps::remove_trivial_summands(new_spec); BOOST_CHECK(new_spec.process().summand_count()==2); } static void test4() { const std::string SPEC = "sort D = struct d1 | d2;\n" " E = D;\n" "\n" "act a : E;\n" "\n" "proc P(d:D) = a(d) . P(d1);\n" "\n" "init P(d2);\n"; const std::string AR_SPEC = "var e : E;\n" "rename\n" "(e==d1) -> a(e) => tau;\n"; stochastic_specification spec=lps::linearise(SPEC); std::istringstream ar_spec_stream(AR_SPEC); action_rename_specification ar_spec = parse_action_rename_specification(ar_spec_stream, spec); data::rewriter R (spec.data(), mcrl2::data::rewriter::strategy()); stochastic_specification new_spec = action_rename(ar_spec,spec); lps::rewrite(new_spec, R); lps::remove_trivial_summands(new_spec); BOOST_CHECK(new_spec.process().summand_count()==2); } static void test5() // Test whether partial renaming to delta is going well. See bug report #1009. { const std::string SPEC = "sort Command = struct com1 | com2;\n" "sort State = struct st1 | st2;\n" "\n" "proc Parent(id: Nat, children: List(Nat)) =\n" " sum child: Nat, command: Command . (child in children) -> sc(id, child, command) . Parent()\n" "+ sum child: Nat, state: State . (child in children) -> rs(child, id, state) . Parent();\n" "\n" "proc Child(id: Nat, parent: Nat) =\n" " sum command: Command . rc(parent, id, command) . Child()\n" "+ sum state: State . ss(id, parent, state) . Child();\n" "\n" "act sc, rc, cc: Nat # Nat # Command;\n" " rs, ss, cs: Nat # Nat # State;\n" "\n" "act none;\n" "\n" "init\n" " allow({cc, cs, sc, rs},\n" " comm({sc|rc -> cc, rs|ss->cs},\n" " Parent(0, [1, 2]) ||\n" " Child(1, 0) ||\n" " Child(2, 0)\n" " ));\n"; const std::string AR_SPEC = "var c: Command;\n" " s: State;\n" "rename\n" " sc(0, 1, c) => delta;\n" " rs(1, 0, s) => delta;\n"; stochastic_specification spec=lps::linearise(SPEC); std::istringstream ar_spec_stream(AR_SPEC); action_rename_specification ar_spec = parse_action_rename_specification(ar_spec_stream, spec); data::rewriter R (spec.data(), mcrl2::data::rewriter::strategy()); stochastic_specification new_spec = action_rename(ar_spec,spec); lps::rewrite(new_spec, R); lps::remove_trivial_summands(new_spec); BOOST_CHECK(new_spec.process().summand_count()==8); } // Check whether renaming with a regular expression works well static void test_regex1() { const std::string SPEC = "act a_out, b_out, cout, ab_out, ac_out;\n" "init a_out|ab_out . b_out . cout . delta;"; stochastic_specification spec = lps::linearise(SPEC); // This should rename a_out and ac_out, leaving the rest stochastic_specification new_spec = action_rename(std::regex("^([^b]*)_out"), "out_$1", spec); BOOST_CHECK(std::string(new_spec.action_labels().front().name()) == "out_a"); BOOST_CHECK(std::string(new_spec.action_labels().tail().front().name()) == "b_out"); BOOST_CHECK(std::string(new_spec.action_labels().tail().tail().front().name()) == "cout"); BOOST_CHECK(std::string(new_spec.action_labels().tail().tail().tail().front().name()) == "ab_out"); BOOST_CHECK(std::string(new_spec.action_labels().tail().tail().tail().tail().front().name()) == "out_ac"); BOOST_CHECK(std::string(new_spec.process().action_summands()[0].multi_action().actions().front().label().name()) == "out_a"); BOOST_CHECK(std::string(new_spec.process().action_summands()[0].multi_action().actions().tail().front().label().name()) == "ab_out"); BOOST_CHECK(std::string(new_spec.process().action_summands()[1].multi_action().actions().front().label().name()) == "b_out"); BOOST_CHECK(std::string(new_spec.process().action_summands()[2].multi_action().actions().front().label().name()) == "cout"); } // Check whether renaming some actions to delta works static void test_regex2() { const std::string SPEC = "act a_out, b_out, cout, ab_out, ac_out;\n" "init a_out|ab_out . b_out . cout . delta;"; stochastic_specification spec = lps::linearise(SPEC); // This should rename a_out, leaving the rest stochastic_specification new_spec = action_rename(std::regex("^a_out"), "delta", spec); BOOST_CHECK(std::string(new_spec.action_labels().front().name()) == "b_out"); BOOST_CHECK(std::string(new_spec.action_labels().tail().front().name()) == "cout"); BOOST_CHECK(std::string(new_spec.action_labels().tail().tail().front().name()) == "ab_out"); BOOST_CHECK(std::string(new_spec.process().action_summands()[0].multi_action().actions().front().label().name()) == "b_out"); BOOST_CHECK(std::string(new_spec.process().action_summands()[1].multi_action().actions().front().label().name()) == "cout"); BOOST_CHECK(new_spec.process().deadlock_summands().size() == 2); BOOST_CHECK(new_spec.process().deadlock_summands()[1].condition() == spec.process().action_summands()[0].condition()); } // Check whether renaming some actions to tau works static void test_regex3() { const std::string SPEC = "act a_out, b_out, cout, ab_out, ac_out;\n" "init a_out|ab_out . b_out . cout . delta;"; stochastic_specification spec = lps::linearise(SPEC); // This should rename a_out and cout, leaving the rest stochastic_specification new_spec = action_rename(std::regex("^(a_out|cout)$"), "tau", spec); BOOST_CHECK(std::string(new_spec.action_labels().front().name()) == "b_out"); BOOST_CHECK(std::string(new_spec.action_labels().tail().front().name()) == "ab_out"); BOOST_CHECK(std::string(new_spec.action_labels().tail().tail().front().name()) == "ac_out"); BOOST_CHECK(new_spec.process().action_summands()[0].multi_action().actions().size() == 1); BOOST_CHECK(std::string(new_spec.process().action_summands()[0].multi_action().actions().front().label().name()) == "ab_out"); BOOST_CHECK(std::string(new_spec.process().action_summands()[1].multi_action().actions().front().label().name()) == "b_out"); BOOST_CHECK(new_spec.process().action_summands()[2].multi_action().actions().size() == 0); } // Check whether the list of actions contains no duplicates after renaming multiple actions // to one action. static void test_regex4() { const std::string SPEC = "act a_out, b_out;\n" "init a_out . b_out . delta;"; stochastic_specification spec = lps::linearise(SPEC); // This should rename both actions to 'out' stochastic_specification new_spec = action_rename(std::regex("^(a|b)_out$"), "out", spec); BOOST_CHECK(new_spec.action_labels().size() == 1); BOOST_CHECK(std::string(new_spec.action_labels().front().name()) == "out"); } int test_main(int argc, char** argv) { test1(); test2(); test3(); test4(); test5(); // GCC 4.8 does not support regexes. Check the support first. if(std::regex_search("a", std::regex(".*"))) { test_regex1(); test_regex2(); test_regex3(); test_regex4(); } return 0; }
#define BOOST_TEST_MODULE blsvoterset_test_suite #include <boost/test/included/unit_test.hpp> #include <iostream> #include <fc/io/json.hpp> #include <core/BlsVoterSet.h> using namespace futureio; using namespace std; BOOST_AUTO_TEST_SUITE(blsvoterset_test_suite) BOOST_AUTO_TEST_CASE(toString) { CommonEchoMsg commonEchoMsg; commonEchoMsg.blockId = fc::sha256("0000052af4157bf7f13c9f08305d6510053dbb58b1c33d0ea38a3e302c6e3287"); commonEchoMsg.phase = kPhaseBA1; commonEchoMsg.baxCount = 10; #ifdef CONSENSUS_VRF commonEchoMsg.proposerPriority = 0; #else commonEchoMsg.proposer = AccountName(std::string("user.111")); #endif BlsVoterSet blsVoterSet; blsVoterSet.commonEchoMsg = commonEchoMsg; blsVoterSet.accountPool.push_back(AccountName(std::string("user.112"))); blsVoterSet.accountPool.push_back(AccountName(std::string("user.113"))); #ifdef CONSENSUS_VRF blsVoterSet.proofPool.push_back(std::string("proof1")); blsVoterSet.proofPool.push_back(std::string("proof2")); #endif blsVoterSet.sigX = std::string("sigx"); std::string restoreS = blsVoterSet.toString(); cout << "restoreS " << restoreS << std::endl; BlsVoterSet restoreBlsVoterSet(restoreS); BOOST_CHECK(restoreBlsVoterSet.valid() == true); BOOST_CHECK(blsVoterSet == restoreBlsVoterSet); } BOOST_AUTO_TEST_CASE(valid) { std::string s; BlsVoterSet blsVoterSet(s); BOOST_CHECK(blsVoterSet.valid() == false); BlsVoterSet origin; BOOST_CHECK(std::string() == origin.toString()); } BOOST_AUTO_TEST_SUITE_END()
/* ---------------------------------------------------------------- * Antti Jumpponen <kuumies@gmail.com> The implementation of kuu::rasperi::Sampler class. * ---------------------------------------------------------------- */ #include "rasperi_sampler.h" #include <array> #include <iostream> #include <glm/gtx/string_cast.hpp> #include <glm/geometric.hpp> #include <QtGui/QImage> namespace kuu { namespace rasperi { /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ struct Sampler::Impl { Impl(const QImage& map, Filter filter, bool linearizeGamma) : map(map) , filter(filter) , linearizeGamma(linearizeGamma) {} /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::dvec2 wrapTexCoord(glm::dvec2 texCoord) const { texCoord.x = fmod(texCoord.x, 1.0); if (texCoord.x < 0.0) texCoord.x += 1.0; texCoord.y = fmod(texCoord.y, 1.0); if (texCoord.y < 0.0) texCoord.y += 1.0; return texCoord; } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::dvec2 clampTexCoord(glm::dvec2 texCoord) const { texCoord.x = glm::clamp(texCoord.x, 0.0, 1.0); texCoord.y = glm::clamp(texCoord.y, 0.0, 1.0); return texCoord; } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::ivec2 mapCoord(const glm::dvec2& texCoord) const { int px = int(std::floor(texCoord.x * double(map.width() - 1))); int py = int(std::floor(texCoord.y * double(map.height() - 1))); return glm::ivec2(px, py); } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::dvec4 sampleRgbaNearest(glm::dvec2 texCoord) const { //texCoord = wrapTexCoord(texCoord); //texCoord = clampTexCoord(texCoord); //texCoord.x = 1.0 - texCoord.x; texCoord.y = 1.0 - texCoord.y; int px = int(std::floor(texCoord.x * double(map.width() - 1))); int py = int(std::floor(texCoord.y * double(map.height() - 1))); return sampleRgba(px, py); } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::dvec4 sampleRgbaLinear(glm::dvec2 texCoord) const { texCoord.y = 1.0 - texCoord.y; texCoord = wrapTexCoord(texCoord); int px = int(std::floor(texCoord.x * double(map.width() - 1))); int py = int(std::floor(texCoord.y * double(map.height() - 1))); std::array<glm::dvec4, 4> pixels; pixels[0] = sampleRgba(px, py ); pixels[1] = sampleRgba(px + 1, py ); pixels[2] = sampleRgba(px, py + 1); pixels[3] = sampleRgba(px + 1, py + 1); return bilinear<glm::dvec4>(texCoord.x, texCoord.y, pixels[0], pixels[1], pixels[2], pixels[3]); } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ double sampleGrayscaleNearest(glm::dvec2 texCoord) const { //texCoord = wrapTexCoord(texCoord); //texCoord = clampTexCoord(texCoord); //texCoord.x = 1.0 - texCoord.x; texCoord.y = 1.0 - texCoord.y; int px = int(std::floor(texCoord.x * double(map.width() - 1))); int py = int(std::floor(texCoord.y * double(map.height() - 1))); return sampleGrayscale(px, py); } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ double sampleGrayscaleLinear(glm::dvec2 texCoord) const { texCoord.y = 1.0 - texCoord.y; texCoord = wrapTexCoord(texCoord); int px = int(std::floor(texCoord.x * double(map.width() - 1))); int py = int(std::floor(texCoord.y * double(map.height() - 1))); std::array<double, 4> pixels; pixels[0] = sampleGrayscale(px, py ); pixels[1] = sampleGrayscale(px + 1, py ); pixels[2] = sampleGrayscale(px, py + 1); pixels[3] = sampleGrayscale(px + 1, py + 1); return bilinear<double>(texCoord.x, texCoord.y, pixels[0], pixels[1], pixels[2], pixels[3]); } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ glm::dvec4 sampleRgba(int x, int y) const { //x = map.width() - x - 1; if (map.isNull() || map.width() <= 0 || map.height() <= 0) { std::cerr << __FUNCTION__ << ": " << "map error" << std::endl; return glm::dvec4(0.0); } if (map.isNull() || x < 0 || x >= map.width() || y < 0 || y >= map.height()) { std::cerr << __FUNCTION__ << ": " << x << ", " << y << ", " << map.width() << ", " << map.height() << std::endl << std::flush; return glm::dvec4(0.0); } const QRgb* line = reinterpret_cast<const QRgb*>(map.scanLine(y)); const QRgb pixel = line[x]; glm::dvec4 out( double(qRed(pixel)) / 255.0, double(qGreen(pixel)) / 255.0, double(qBlue(pixel)) / 255.0, double(qAlpha(pixel)) / 255.0); out = glm::clamp(out, glm::dvec4(0.0), glm::dvec4(1.0)); if (linearizeGamma) { double gamma = 2.2; out = glm::pow(out, glm::dvec4(gamma)); } return out; } /* ----------------------------------------------------------- * * ----------------------------------------------------------- */ double sampleGrayscale(int x, int y) const { //x = map.width() - x - 1; if (map.isNull() || map.width() <= 0 || map.height() <= 0) { std::cerr << __FUNCTION__ << ": " << "map error" << std::endl; return 0.0; } if (map.isNull() || x < 0 || x >= map.width() || y < 0 || y >= map.height()) { std::cerr << __FUNCTION__ << ": " << x << ", " << y << ", " << map.width() << ", " << map.height() << std::endl; return 0.0; } if (map.format() != QImage::Format_Grayscale8) { std::cerr << __FUNCTION__ << ": " << "map is not a Grayscale8 image" << std::endl; } const uchar* line = map.constScanLine(y); uchar pixel = line[x]; //if (pixel > 0) // std::cout << "jee" << std::endl; double out = double(pixel) / 255.0; out = glm::clamp(out, 0.0, 1.0); if (linearizeGamma) { double gamma = 2.2; out = glm::pow(out, gamma); } return out; } /* ------------------------------------------------------------ * * ------------------------------------------------------------ */ void writeRgba(const glm::dvec2& texCoord, const glm::dvec4& rgba) { glm::dvec2 uv = clampTexCoord(texCoord); glm::ivec2 sc = mapCoord(uv); if (map.isNull() || map.width() <= 0 || map.height() <= 0 || sc.x < 0 || sc.x >= map.width() || sc.y < 0 || sc.y >= map.height()) { std::cerr << __FUNCTION__ << ": " << "map error" << std::endl; return; } std::cout << __FUNCTION__ << ": " << sc.x << ", " << sc.y << std::endl; QRgb* line = reinterpret_cast<QRgb*>(map.scanLine(sc.y)); line[sc.x] = qRgba(qRound(rgba.r * 255.0), qRound(rgba.g * 255.0), qRound(rgba.b * 255.0), qRound(rgba.a * 255.0)); // line[sc.x] = qRgba(0, 0, 255, 255); // map.setPixel(sc.x, sc.y, qRgba(qRound(rgba.r * 255.0), // qRound(rgba.g * 255.0), // qRound(rgba.b * 255.0), // qRound(rgba.a * 255.0))); } /* ------------------------------------------------------------ * https://www.scratchapixel.com/lessons/mathematics-physics-for- computer-graphics/interpolation/bilinear-filtering * ------------------------------------------------------------ */ template<typename T> T bilinear( const double tx, const double ty, const T& c00, const T& c10, const T& c01, const T& c11) const { T a = c00 * (1.0 - tx) + c10 * tx; T b = c01 * (1.0 - tx) + c11 * tx; return a * (1.0 - ty) + b * ty; } QImage map; Filter filter; bool linearizeGamma; }; /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ Sampler::Sampler() : Sampler(QImage()) {} /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ Sampler::Sampler(const QImage& map, Filter filter, bool linearizeGamma) : impl(std::make_shared<Impl>(map, filter, linearizeGamma)) {} /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ bool Sampler::isValid() const { return !impl->map.isNull(); } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ void Sampler::setMap(const QImage& map) { impl->map = map; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ QImage Sampler::map() const { return impl->map; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ void Sampler::setFilter(Sampler::Filter filter) { impl->filter = filter; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ Sampler::Filter Sampler::filter() const { return impl->filter; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ void Sampler::setLinearizeGamma(bool linearize) { impl->linearizeGamma = linearize; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ bool Sampler::linearizeGamma() const { return impl->linearizeGamma; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ glm::dvec4 Sampler::sampleRgba(const glm::dvec2& texCoord) const { switch(impl->filter) { case Filter::Nearest: return impl->sampleRgbaNearest(texCoord); case Filter::Linear: return impl->sampleRgbaLinear(texCoord); } return glm::dvec4(0.0); } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ double Sampler::sampleGrayscale(const glm::dvec2& texCoord) const { switch(impl->filter) { case Filter::Nearest: return impl->sampleGrayscaleNearest(texCoord); case Filter::Linear: return impl->sampleGrayscaleLinear(texCoord); } return 0.0; } /* ---------------------------------------------------------------- * * ---------------------------------------------------------------- */ void Sampler::writeRgba(const glm::dvec2& texCoord, const glm::dvec4& rgba) { impl->writeRgba(texCoord, rgba); } } // namespace rasperi } // namespace kuu
SparseMatrix<double> A(3,3); A.insert(1,2) = 0; A.insert(0,1) = 1; A.insert(2,0) = 2; A.makeCompressed(); cout << "The matrix A is:" << endl << MatrixXd(A) << endl; cout << "it has " << A.nonZeros() << " stored non zero coefficients that are: " << A.coeffs().transpose() << endl; A.coeffs() += 10; cout << "After adding 10 to every stored non zero coefficient, the matrix A is:" << endl << MatrixXd(A) << endl;
/***************************************************************************//*! * * @file markdown-math.hpp * * @author Peter Goldsborough. * *******************************************************************************/ #ifndef MARKDOWN_MATH_HPP #define MARKDOWN_MATH_HPP #include "markdown-abstract-math.hpp" #include <memory> #include <stdexcept> #include <string> #include <v8.h> namespace Markdown { /***********************************************************************//*! * * @brief Renders Math to HTML. * * @details Uses <a href="khan.github.io/KaTeX">KaTeX</a>. * Configuration (key : values [default]): * + all-display-math : (true | false) [false] * + throw : (true | false) [true] * + error-color : (#hex-color) [#CC0000] * ***************************************************************************/ class Math : public AbstractMath { public: /*! The default settings for this math engine. */ static const Configurable::settings_t default_settings; /*******************************************************************//*! * * @brief Constructs a new Math engine. * * @param katex_path The path to the katex folder. * * @param settings The settings for the Math engine. * ***********************************************************************/ Math(const std::string& katex_path = ".", const Configurable::settings_t& settings = default_settings); /*******************************************************************//*! * * @brief Copy-constructs a Math engine. * * @param other The other Math object. * ***********************************************************************/ Math(const Math& other); /*******************************************************************//*! * * @brief Move-constructs a Math engine. * * @param other The other Math object. * ***********************************************************************/ Math(Math&& other) noexcept; /*******************************************************************//*! * * @brief Assigns the Math engine. * * @param other The other Math object. * ***********************************************************************/ Math& operator=(Math other); /*******************************************************************//*! * * @brief Swaps members with another Math engine. * * @param other The other Math object. * ***********************************************************************/ void swap(Math& other) noexcept; /*******************************************************************//*! * * @brief Swaps members of two Math engines. * * @param first The first Math object. * * @param second The second Math object. * ***********************************************************************/ friend void swap(Math& first, Math& second) noexcept; /*******************************************************************//*! * * @brief Destructs the Math engine. * ***********************************************************************/ ~Math(); /*******************************************************************//*! * * @brief Renders a LaTeX expression to HTML. * * @param expression The LaTeX expression to render to HTML. * * @param display_math Whether to use a displaymath environment. * * @return A HTML snippet without any enclosing <html> or <body> tags. * ***********************************************************************/ virtual std::string render(const std::string& expression, bool display_math = false) override; /*******************************************************************//*! * * @brief Returns the currently-set KaTeX path. * ***********************************************************************/ virtual const std::string& katex_path() const noexcept; /*******************************************************************//*! * * @brief Sets the path to the KaTeX directory. * * @param path The new path to the KaTeX directory. * ***********************************************************************/ virtual void katex_path(const std::string& path); private: struct Allocator : public v8::ArrayBuffer::Allocator { virtual void* Allocate(size_t length) override; virtual void* AllocateUninitialized(size_t length) override; virtual void Free(void* data, size_t) override; }; static struct V8 { V8(); ~V8(); std::unique_ptr<v8::Platform> platform; } _v8; /*******************************************************************//*! * * @brief Creates and initializes a new v8::Isolate. * * @details Deals with setting the Allocator instance in the * isolate's parameters. * * @return A __naked pointer__ to a v8::Isolate. * ***********************************************************************/ v8::Isolate* _new_isolate() const; /*******************************************************************//*! * * @brief Compiles and executes JavaScript code via the V8 engine. * * @param source The JavaScript source-code to execute. * * @param context The context in which to compile and execute the code. * * @return Any return value of the execution. * * @throws ParseException If there was an exception in the JS * environment, which can only stem * from a parse-exception. * ***********************************************************************/ v8::Local<v8::Value> _run(const std::string& source, const v8::Local<v8::Context>& context) const; /*******************************************************************//*! * * @brief Retrieves the JavaScript for calling KaTeX. * * @details Handles determining whether to use display-math depending * one the display-mode flag in the configuration and the * display_math parameter passed to the render() method. * * @param expression A LaTeX expression. * * @param display_math The display_math parameter for this expression. * ***********************************************************************/ std::string _get_javascript(const std::string& expression, bool display_math) const; /*******************************************************************//*! * * @brief Escapes backslashes and whitespace in the LaTeX source. * * @details The problem is that even though you may escape backslashes * in the string you pass to the Latex instance, those * backlashes then have to again be escaped for the JavaScript * source (as they are simply backslashes for the JS * environment otherwise, which initiate escape sequences). * * @return The escaped LaTeX string. * ***********************************************************************/ std::string _escape(std::string source) const; /*******************************************************************//*! * * @brief Loads the KaTeX JavaScript library. * * @details The KaTeX library is loaded and executed in the current * V8 context, such that subsequent code executed in that * environment can access the KaTeX library. * * @param context A V8 context object. * ***********************************************************************/ void _load_katex(const v8::Local<v8::Context>& context) const; std::string _handle_error(const std::string& expression) const; /*! A instance of the Allocator struct for the V8 engine. */ mutable Allocator _allocator; /*! The virtual environment in which the V8 runs. */ v8::Isolate* _isolate; /*! A persistent (i.e. non-expiring/global) handle to the context in which the instance interacts with the V8 engine. */ v8::UniquePersistent<v8::Context> _persistent_context; /*! The path to the katex directory. */ std::string _katex_path; }; } #endif /* MARKDOWN_MATH_HPP */
/* Copyright (C) 2019 Jerry R. VanAken This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ //---------------------------------------------------------------------- // // thinline.cpp: // Functions for stroking paths that have line width = 0. This is a // special-case value that signifies line segments that mimic // Bresenham lines. // //---------------------------------------------------------------------- #include <math.h> #include "shapepri.h" namespace { //------------------------------------------------------------------ // // Returns the quadrant number (in range 0 to 3) for vector // (dx,dy). Quadrant boundaries are defined by +/- 45-degree // diagonals. Any pair of adjacent line segments that are both in // the same quadrant are naturally joined. Note that the // ThinJoinLines function is called only to join two adjacent // segments that are in different quadrants. // //------------------------------------------------------------------ int getquadrant(FIX16 dx, FIX16 dy) { int quad; if (abs(dx) > abs(dy)) { quad = (dx < 0) ? 2 : 0; } else { quad = (dy < 0) ? 3 : 1; } return quad; } //------------------------------------------------------------------ // // Half-width offsets for thin stroked line segments. The first // four array elements are the offsets for quadrants 0 to 3. The // quadrant boundaries, in this case, are 45-degree diagonals. The // fifth array element, {0,0}, is used for end points of segments // that need to be capped. // //------------------------------------------------------------------ const VERT16 offset[] = { { 0, -FIX_HALF }, { FIX_HALF, 0 }, { 0, FIX_HALF }, { -FIX_HALF, 0 }, { 0, 0 } }; } //---------------------------------------------------------------------- // // Private function: Joins two thin-stroked line segments. Constructs a // beveled join to connect the end point of the previous line segment // to the start point of the new line segment. This function is called // only if the new line segment and the previous line segment are in // different quadrants. The two directed line segments meet at the x-y // coordinates given by parameter vert. Parameters inquad and outquad are // the quadrant numbers for the incoming and outgoing line segments, // respectively. // //---------------------------------------------------------------------- void PathMgr::ThinJoinLines(const VERT16 *vert, int inquad, int outquad) { VERT16 cdir = offset[outquad]; // offset vector for incoming line VERT16 pdir = offset[inquad]; // offset vector for outgoing line VERT16 v1, v2, xy[4]; v1 = v2 = *vert; if (((inquad | outquad) & 4) != 0) { // Special index value "4" indicates that we're capping a // stroked-line end point, not joining two line segments if (inquad == 4) { v1.x += cdir.y; v1.y -= cdir.x; } else { v2.x -= pdir.y; v2.y += pdir.x; } } xy[0].x = v1.x + pdir.x; xy[0].y = v1.y + pdir.y; xy[1].x = v2.x + cdir.x; xy[1].y = v2.y + cdir.y; xy[2].x = v2.x - cdir.x; xy[2].y = v2.y - cdir.y; xy[3].x = v1.x - pdir.x; xy[3].y = v1.y - pdir.y; _edge->AttachEdge(&xy[0], &xy[1]); _edge->AttachEdge(&xy[2], &xy[3]); } //---------------------------------------------------------------------- // // Private function: Strokes the current path for the special case of a // line width of zero, which specifies that the line segments in the // path are to be drawn as thinly connected, Bresenham-style lines. // Stroke attributes such as line caps, join style, and dashed-line // pattern are ignored for this case. The following function is an // implementation of Vaughan Pratt's method for drawing thin, stroked // lines, as described in section 4.5 of his SIGGRAPH '85 paper on // conic splines. // //---------------------------------------------------------------------- bool PathMgr::ThinStrokePath() { FIGURE *fig = _figure; // empty figure terminates path VERT16 *fpt = _fpoint; // first point (has undefined value) int off; // Each while-loop iteration below processes one figure (aka // subpath), starting with the last figure in the path assert(_fpoint == reinterpret_cast<VERT16*>(_figure + 1)); while ((off = fig->offset) != 0) { VERT16 *vs = &fpt[-2]; // last point in new figure VERT16 *ve = &fpt[-off]; // first point in new figure int nlines = off - 2; FIX16 dx, dy; int prevquad; assert(vs != ve); // figure has at least 2 points fig = &fig[-off]; // header for new figure fpt = ve; // remember first point if (fig->isclosed) { ++nlines; dx = vs[0].x - vs[-1].x; dy = vs[0].y - vs[-1].y; assert((dx | dy) != 0); prevquad = getquadrant(dx, dy); } else { prevquad = 4; // special value: do caps at line ends vs = ve++; } // Each for-loop iteration constructs one line segment for (int i = 0; i < nlines; ++i) { dx = ve->x - vs->x; dy = ve->y - vs->y; assert((dx | dy) != 0); int quad = getquadrant(dx, dy); VERT16 dir = offset[quad]; VERT16 xy[4]; // Offset stroked edges 1/2 pixel from line segment xy[0].x = vs->x + dir.x; xy[0].y = vs->y + dir.y; xy[1].x = xy[0].x + dx; xy[1].y = xy[0].y + dy; xy[2].x = ve->x - dir.x; xy[2].y = ve->y - dir.y; xy[3].x = xy[2].x - dx; xy[3].y = xy[2].y - dy; _edge->AttachEdge(&xy[0], &xy[1]); _edge->AttachEdge(&xy[2], &xy[3]); if (quad != prevquad) { // Join two line segments that are in different quadrants ThinJoinLines(vs, prevquad, quad); prevquad = quad; } vs = ve++; } if (fig->isclosed == false) ThinJoinLines(vs, prevquad, 4); // "4" means "cap this line end" } // Fill the stroked path and initialize current path to empty _edge->TranslateEdges(_scroll.x, _scroll.y); _edge->NormalizeEdges(FILLRULE_WINDING); _edge->ClipEdges(FILLRULE_INTERSECT); return _edge->FillEdgeList(); }
#include <Interpreters/DDLTask.h> #include <base/sort.h> #include <Common/DNSResolver.h> #include <Common/isLocalAddress.h> #include <IO/WriteHelpers.h> #include <IO/ReadHelpers.h> #include <IO/Operators.h> #include <IO/ReadBufferFromString.h> #include <Poco/Net/NetException.h> #include <Common/logger_useful.h> #include <Parsers/ParserQuery.h> #include <Parsers/parseQuery.h> #include <Parsers/ASTQueryWithOnCluster.h> #include <Parsers/formatAST.h> #include <Parsers/ASTQueryWithTableAndOutput.h> #include <Databases/DatabaseReplicated.h> namespace DB { namespace ErrorCodes { extern const int UNKNOWN_FORMAT_VERSION; extern const int UNKNOWN_TYPE_OF_QUERY; extern const int INCONSISTENT_CLUSTER_DEFINITION; extern const int LOGICAL_ERROR; } HostID HostID::fromString(const String & host_port_str) { HostID res; std::tie(res.host_name, res.port) = Cluster::Address::fromString(host_port_str); return res; } bool HostID::isLocalAddress(UInt16 clickhouse_port) const { try { return DB::isLocalAddress(DNSResolver::instance().resolveAddress(host_name, port), clickhouse_port); } catch (const Poco::Net::NetException &) { /// Avoid "Host not found" exceptions return false; } } void DDLLogEntry::assertVersion() const { constexpr UInt64 max_version = 2; if (version == 0 || max_version < version) throw Exception(ErrorCodes::UNKNOWN_FORMAT_VERSION, "Unknown DDLLogEntry format version: {}." "Maximum supported version is {}", version, max_version); } void DDLLogEntry::setSettingsIfRequired(ContextPtr context) { version = context->getSettingsRef().distributed_ddl_entry_format_version; if (version == 2) settings.emplace(context->getSettingsRef().changes()); } String DDLLogEntry::toString() const { WriteBufferFromOwnString wb; wb << "version: " << version << "\n"; wb << "query: " << escape << query << "\n"; bool write_hosts = version == 1 || !hosts.empty(); if (write_hosts) { Strings host_id_strings(hosts.size()); std::transform(hosts.begin(), hosts.end(), host_id_strings.begin(), HostID::applyToString); wb << "hosts: " << host_id_strings << "\n"; } wb << "initiator: " << initiator << "\n"; bool write_settings = 1 <= version && settings && !settings->empty(); if (write_settings) { ASTSetQuery ast; ast.is_standalone = false; ast.changes = *settings; wb << "settings: " << serializeAST(ast) << "\n"; } return wb.str(); } void DDLLogEntry::parse(const String & data) { ReadBufferFromString rb(data); rb >> "version: " >> version >> "\n"; assertVersion(); Strings host_id_strings; rb >> "query: " >> escape >> query >> "\n"; if (version == 1) { rb >> "hosts: " >> host_id_strings >> "\n"; if (!rb.eof()) rb >> "initiator: " >> initiator >> "\n"; else initiator.clear(); } else if (version == 2) { if (!rb.eof() && *rb.position() == 'h') rb >> "hosts: " >> host_id_strings >> "\n"; if (!rb.eof() && *rb.position() == 'i') rb >> "initiator: " >> initiator >> "\n"; if (!rb.eof() && *rb.position() == 's') { String settings_str; rb >> "settings: " >> settings_str >> "\n"; ParserSetQuery parser{true}; constexpr UInt64 max_size = 4096; constexpr UInt64 max_depth = 16; ASTPtr settings_ast = parseQuery(parser, settings_str, max_size, max_depth); settings.emplace(std::move(settings_ast->as<ASTSetQuery>()->changes)); } } assertEOF(rb); if (!host_id_strings.empty()) { hosts.resize(host_id_strings.size()); std::transform(host_id_strings.begin(), host_id_strings.end(), hosts.begin(), HostID::fromString); } } void DDLTaskBase::parseQueryFromEntry(ContextPtr context) { const char * begin = entry.query.data(); const char * end = begin + entry.query.size(); const auto & settings = context->getSettingsRef(); ParserQuery parser_query(end, settings.allow_settings_after_format_in_insert); String description; query = parseQuery(parser_query, begin, end, description, 0, settings.max_parser_depth); } ContextMutablePtr DDLTaskBase::makeQueryContext(ContextPtr from_context, const ZooKeeperPtr & /*zookeeper*/) { auto query_context = Context::createCopy(from_context); query_context->makeQueryContext(); query_context->setCurrentQueryId(""); // generate random query_id query_context->getClientInfo().query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; if (entry.settings) query_context->applySettingsChanges(*entry.settings); return query_context; } bool DDLTask::findCurrentHostID(ContextPtr global_context, Poco::Logger * log) { bool host_in_hostlist = false; for (const HostID & host : entry.hosts) { auto maybe_secure_port = global_context->getTCPPortSecure(); /// The port is considered local if it matches TCP or TCP secure port that the server is listening. bool is_local_port = (maybe_secure_port && host.isLocalAddress(*maybe_secure_port)) || host.isLocalAddress(global_context->getTCPPort()); if (!is_local_port) continue; if (host_in_hostlist) { /// This check could be slow a little bit LOG_WARNING(log, "There are two the same ClickHouse instances in task {}: {} and {}. Will use the first one only.", entry_name, host_id.readableString(), host.readableString()); } else { host_in_hostlist = true; host_id = host; host_id_str = host.toString(); } } return host_in_hostlist; } void DDLTask::setClusterInfo(ContextPtr context, Poco::Logger * log) { auto * query_on_cluster = dynamic_cast<ASTQueryWithOnCluster *>(query.get()); if (!query_on_cluster) throw Exception("Received unknown DDL query", ErrorCodes::UNKNOWN_TYPE_OF_QUERY); cluster_name = query_on_cluster->cluster; cluster = context->tryGetCluster(cluster_name); if (!cluster) throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, "DDL task {} contains current host {} in cluster {}, but there is no such cluster here.", entry_name, host_id.readableString(), cluster_name); /// Try to find host from task host list in cluster /// At the first, try find exact match (host name and ports should be literally equal) /// If the attempt fails, try find it resolving host name of each instance if (!tryFindHostInCluster()) { LOG_WARNING(log, "Not found the exact match of host {} from task {} in cluster {} definition. Will try to find it using host name resolving.", host_id.readableString(), entry_name, cluster_name); if (!tryFindHostInClusterViaResolving(context)) throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, "Not found host {} in definition of cluster {}", host_id.readableString(), cluster_name); LOG_INFO(log, "Resolved host {} from task {} as host {} in definition of cluster {}", host_id.readableString(), entry_name, address_in_cluster.readableString(), cluster_name); } WithoutOnClusterASTRewriteParams params; params.default_database = address_in_cluster.default_database; params.shard_index = address_in_cluster.shard_index; params.replica_index = address_in_cluster.replica_index; query = query_on_cluster->getRewrittenASTWithoutOnCluster(params); query_on_cluster = nullptr; } bool DDLTask::tryFindHostInCluster() { const auto & shards = cluster->getShardsAddresses(); bool found_exact_match = false; String default_database; for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num) { for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num) { const Cluster::Address & address = shards[shard_num][replica_num]; if (address.host_name == host_id.host_name && address.port == host_id.port) { if (found_exact_match) { if (default_database == address.default_database) { throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, "There are two exactly the same ClickHouse instances {} in cluster {}", address.readableString(), cluster_name); } else { /* Circular replication is used. * It is when every physical node contains * replicas of different shards of the same table. * To distinguish one replica from another on the same node, * every shard is placed into separate database. * */ is_circular_replicated = true; auto * query_with_table = dynamic_cast<ASTQueryWithTableAndOutput *>(query.get()); /// For other DDLs like CREATE USER, there is no database name and should be executed successfully. if (query_with_table) { if (!query_with_table->database) throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, "For a distributed DDL on circular replicated cluster its table name must be qualified by database name."); if (default_database == query_with_table->getDatabase()) return true; } } } found_exact_match = true; host_shard_num = shard_num; host_replica_num = replica_num; address_in_cluster = address; default_database = address.default_database; } } } return found_exact_match; } bool DDLTask::tryFindHostInClusterViaResolving(ContextPtr context) { const auto & shards = cluster->getShardsAddresses(); bool found_via_resolving = false; for (size_t shard_num = 0; shard_num < shards.size(); ++shard_num) { for (size_t replica_num = 0; replica_num < shards[shard_num].size(); ++replica_num) { const Cluster::Address & address = shards[shard_num][replica_num]; if (auto resolved = address.getResolvedAddress(); resolved && (isLocalAddress(*resolved, context->getTCPPort()) || (context->getTCPPortSecure() && isLocalAddress(*resolved, *context->getTCPPortSecure())))) { if (found_via_resolving) { throw Exception(ErrorCodes::INCONSISTENT_CLUSTER_DEFINITION, "There are two the same ClickHouse instances in cluster {} : {} and {}", cluster_name, address_in_cluster.readableString(), address.readableString()); } else { found_via_resolving = true; host_shard_num = shard_num; host_replica_num = replica_num; address_in_cluster = address; } } } } return found_via_resolving; } String DDLTask::getShardID() const { /// Generate unique name for shard node, it will be used to execute the query by only single host /// Shard node name has format 'replica_name1,replica_name2,...,replica_nameN' /// Where replica_name is 'replica_config_host_name:replica_port' auto shard_addresses = cluster->getShardsAddresses().at(host_shard_num); Strings replica_names; for (const Cluster::Address & address : shard_addresses) replica_names.emplace_back(address.readableString()); ::sort(replica_names.begin(), replica_names.end()); String res; for (auto it = replica_names.begin(); it != replica_names.end(); ++it) res += *it + (std::next(it) != replica_names.end() ? "," : ""); return res; } DatabaseReplicatedTask::DatabaseReplicatedTask(const String & name, const String & path, DatabaseReplicated * database_) : DDLTaskBase(name, path) , database(database_) { host_id_str = database->getFullReplicaName(); } String DatabaseReplicatedTask::getShardID() const { return database->shard_name; } void DatabaseReplicatedTask::parseQueryFromEntry(ContextPtr context) { DDLTaskBase::parseQueryFromEntry(context); if (auto * ddl_query = dynamic_cast<ASTQueryWithTableAndOutput *>(query.get())) { /// Update database name with actual name of local database assert(!ddl_query->database); ddl_query->setDatabase(database->getDatabaseName()); } } ContextMutablePtr DatabaseReplicatedTask::makeQueryContext(ContextPtr from_context, const ZooKeeperPtr & zookeeper) { auto query_context = DDLTaskBase::makeQueryContext(from_context, zookeeper); query_context->getClientInfo().query_kind = ClientInfo::QueryKind::SECONDARY_QUERY; query_context->getClientInfo().is_replicated_database_internal = true; query_context->setCurrentDatabase(database->getDatabaseName()); auto txn = std::make_shared<ZooKeeperMetadataTransaction>(zookeeper, database->zookeeper_path, is_initial_query, entry_path); query_context->initZooKeeperMetadataTransaction(txn); if (is_initial_query) { txn->addOp(zkutil::makeRemoveRequest(entry_path + "/try", -1)); txn->addOp(zkutil::makeCreateRequest(entry_path + "/committed", host_id_str, zkutil::CreateMode::Persistent)); txn->addOp(zkutil::makeSetRequest(database->zookeeper_path + "/max_log_ptr", toString(getLogEntryNumber(entry_name)), -1)); } txn->addOp(zkutil::makeSetRequest(database->replica_path + "/log_ptr", toString(getLogEntryNumber(entry_name)), -1)); for (auto & op : ops) txn->addOp(std::move(op)); ops.clear(); return query_context; } String DDLTaskBase::getLogEntryName(UInt32 log_entry_number) { return zkutil::getSequentialNodeName("query-", log_entry_number); } UInt32 DDLTaskBase::getLogEntryNumber(const String & log_entry_name) { constexpr const char * name = "query-"; assert(startsWith(log_entry_name, name)); UInt32 num = parse<UInt32>(log_entry_name.substr(strlen(name))); assert(num < std::numeric_limits<Int32>::max()); return num; } void ZooKeeperMetadataTransaction::commit() { if (state != CREATED) throw Exception(ErrorCodes::LOGICAL_ERROR, "Incorrect state ({}), it's a bug", state); state = FAILED; current_zookeeper->multi(ops); state = COMMITTED; } ClusterPtr tryGetReplicatedDatabaseCluster(const String & cluster_name) { if (const auto * replicated_db = dynamic_cast<const DatabaseReplicated *>(DatabaseCatalog::instance().tryGetDatabase(cluster_name).get())) return replicated_db->getCluster(); return {}; } }
#include <iostream> using namespace std; #define PHI 3.14 int main () { float r,s; float Kerucut,selimut; int phi=3.14; cout << " Program Pengerjaan Luas Dan Selimut Kerucut\n"; cout << " \n Muhammad Ilham Nursastrawan_123200168\n"; cout << " \n masukkan Jari Jari : "; cin >> r; cout << " masukkan garis pelukis : "; cin >> s; Kerucut = phi*r*(r+s); selimut = phi*r*s; cout <<" Luas permukaan Kerucut adalah : "<<Kerucut<<endl; cout <<" Luas permukaan selimut adalah : "<<selimut<<endl; return(0); }