text
stringlengths
5
1.04M
// (C) Copyright 2008 CodeRage, LLC (turkanis at coderage dot com) // (C) Copyright 2003-2007 Jonathan Turkanis // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt.) // See http://www.boost.org/libs/iostreams for documentation. #ifndef BOOST_IOSTREAMS_STREAM_HPP_INCLUDED #define BOOST_IOSTREAMS_STREAM_HPP_INCLUDED #if defined(_MSC_VER) # pragma once #endif #include <boost/iostreams/constants.hpp> #include <boost/iostreams/detail/char_traits.hpp> #include <boost/iostreams/detail/config/overload_resolution.hpp> #include <boost/iostreams/detail/forward.hpp> #include <boost/iostreams/detail/iostream.hpp> // standard streams. #include <boost/iostreams/detail/select.hpp> #include <boost/iostreams/stream_buffer.hpp> #include <boost/mpl/and.hpp> #include <boost/type_traits/is_convertible.hpp> #include <boost/utility/base_from_member.hpp> namespace boost { namespace iostreams { namespace detail { template<typename Device, typename Tr> struct stream_traits { typedef typename char_type_of<Device>::type char_type; typedef Tr traits_type; typedef typename category_of<Device>::type mode; typedef typename iostreams::select< // Disambiguation required for Tru64. mpl::and_< is_convertible<mode, input>, is_convertible<mode, output> >, BOOST_IOSTREAMS_BASIC_IOSTREAM(char_type, traits_type), is_convertible<mode, input>, BOOST_IOSTREAMS_BASIC_ISTREAM(char_type, traits_type), else_, BOOST_IOSTREAMS_BASIC_OSTREAM(char_type, traits_type) >::type stream_type; typedef typename iostreams::select< // Disambiguation required for Tru64. mpl::and_< is_convertible<mode, input>, is_convertible<mode, output> >, iostream_tag, is_convertible<mode, input>, istream_tag, else_, ostream_tag >::type stream_tag; }; // By encapsulating initialization in a base, we can define the macro // BOOST_IOSTREAMS_DEFINE_FORWARDING_FUNCTIONS to generate constructors // without base member initializer lists. template< typename Device, typename Tr = BOOST_IOSTREAMS_CHAR_TRAITS( BOOST_DEDUCED_TYPENAME char_type_of<Device>::type ), typename Alloc = std::allocator< BOOST_DEDUCED_TYPENAME char_type_of<Device>::type >, typename Base = // VC6 Workaround. BOOST_DEDUCED_TYPENAME detail::stream_traits<Device, Tr>::stream_type > class stream_base : protected base_from_member< stream_buffer<Device, Tr, Alloc> >, public Base { private: typedef base_from_member< stream_buffer<Device, Tr, Alloc> > pbase_type; typedef typename stream_traits<Device, Tr>::stream_type stream_type; protected: using pbase_type::member; // Avoid warning about 'this' in initializer list. public: stream_base() : pbase_type(), stream_type(&member) { } }; } } } // End namespaces detail, iostreams, boost. #ifdef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION # include <boost/iostreams/detail/broken_overload_resolution/stream.hpp> #else namespace boost { namespace iostreams { // // Template name: stream. // Description: A iostream which reads from and writes to an instance of a // designated device type. // Template parameters: // Device - A device type. // Alloc - The allocator type. // template< typename Device, typename Tr = BOOST_IOSTREAMS_CHAR_TRAITS( BOOST_DEDUCED_TYPENAME char_type_of<Device>::type ), typename Alloc = std::allocator< BOOST_DEDUCED_TYPENAME char_type_of<Device>::type > > struct stream : detail::stream_base<Device, Tr, Alloc> { public: typedef typename char_type_of<Device>::type char_type; struct category : mode_of<Device>::type, closable_tag, detail::stream_traits<Device, Tr>::stream_tag { }; BOOST_IOSTREAMS_STREAMBUF_TYPEDEFS(Tr) private: typedef typename detail::stream_traits< Device, Tr >::stream_type stream_type; public: stream() { } BOOST_IOSTREAMS_FORWARD( stream, open_impl, Device, BOOST_IOSTREAMS_PUSH_PARAMS, BOOST_IOSTREAMS_PUSH_ARGS ) bool is_open() const { return this->member.is_open(); } void close() { this->member.close(); } bool auto_close() const { return this->member.auto_close(); } void set_auto_close(bool close) { this->member.set_auto_close(close); } bool strict_sync() { return this->member.strict_sync(); } Device& operator*() { return *this->member; } Device* operator->() { return &*this->member; } Device* component() { return this->member.component(); } private: void open_impl(const Device& dev BOOST_IOSTREAMS_PUSH_PARAMS()) // For forwarding. { this->clear(); this->member.open(dev BOOST_IOSTREAMS_PUSH_ARGS()); } }; } } // End namespaces iostreams, boost. #endif // #ifdef BOOST_IOSTREAMS_BROKEN_OVERLOAD_RESOLUTION #endif // #ifndef BOOST_IOSTREAMS_stream_HPP_INCLUDED
#pragma once #include "qpup_control_loop.hpp" #include "qpup_hw/qpup_hw_real.hpp" namespace qpup_control { class QPUPControlLoopReal : public QPUPControlLoop { public: explicit QPUPControlLoopReal(const ros::NodeHandle &nh); void runForeverBlocking(); }; } // namespace qpup_control
#include "caffe2/operators/pool_op.h" #include "caffe2/utils/eigen_utils.h" namespace caffe2 { using std::max; using std::min; namespace { // These two classe are just used as template arguments passed to the // PoolGradientOp // template to instantiate the different algorithms. template <typename T> class AveragePool { public: static void process_grad( const T& /*x_data*/, const T& /*y_data*/, const T& dy_data, const T& scale, T& dx_data) { dx_data += (scale * dy_data); } static void process_grad( const int y_col, const int x_col, const float scale, ConstEigenArrayMap<float>& /*x_data*/, ConstEigenArrayMap<float>& /*y_data*/, ConstEigenArrayMap<float>& dy_data, EigenArrayMap<float>& dx_data) { dx_data.col(x_col) += scale * dy_data.col(y_col); } }; template <typename T> class MaxPool { public: static void process_grad( const T& x_data, const T& y_data, const T& dy_data, const T& /*scale*/, T& dx_data) { if (x_data == y_data) { dx_data += dy_data; } } static void process_grad( const int y_col, const int x_col, const float /*scale*/, ConstEigenArrayMap<float>& x_data, ConstEigenArrayMap<float>& y_data, ConstEigenArrayMap<float>& dy_data, EigenArrayMap<float>& dx_data) { dx_data.col(x_col) += dy_data.col(y_col) * (x_data.col(x_col) .cwiseEqual(y_data.col(y_col)) .template cast<float>()); } }; } template <typename T, class Context, typename PoolType> bool PoolGradientOp<T, Context, PoolType>::RunOnDeviceWithOrderNCHW() { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); auto* dX = Output(0); // TODO(Yangqing): Add shape checks. dX->ResizeLike(X); math::Set<float, CPUContext>( X.size(), 0, dX->template mutable_data<float>(), &context_); const float* Xdata = X.template data<float>(); const float* Ydata = Y.template data<float>(); const float* dYdata = dY.template data<float>(); float* dXdata = dX->template mutable_data<float>(); int channels = X.dim32(1); CAFFE_ENFORCE_EQ(channels, dY.dim32(1)); int height = X.dim32(2); int width = kernel_.size() > 1 ? X.dim32(3) : 1; int depth = kernel_.size() > 2 ? X.dim32(4) : 1; vector<int> dims(X.dims().begin() + 2, X.dims().end()); ConvPoolOpBase<CPUContext>::ComputePads(dims); int pooled_height = dY.dim32(2); int pooled_width = kernel_.size() > 1 ? dY.dim32(3) : 1; int pooled_depth = kernel_.size() > 2 ? dY.dim32(4) : 1; // The main loop switch (kernel_.size()) { case 1: for (int n = 0; n < X.dim32(0); ++n) { for (int c = 0; c < channels; ++c) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); float scale = 1. / (hend - hstart); for (int h = hstart; h < hend; ++h) { PoolType::process_grad( Xdata[h], Ydata[ph], dYdata[ph], scale, dXdata[h]); } } // offset Xdata += height; dXdata += height; Ydata += pooled_height; dYdata += pooled_height; } } break; case 2: for (int n = 0; n < X.dim32(0); ++n) { for (int c = 0; c < channels; ++c) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); for (int pw = 0; pw < pooled_width; ++pw) { int wstart = pw * stride_w() - pad_l(); int wend = min(wstart + kernel_w(), width); wstart = max(wstart, 0); float scale = 1. / (hend - hstart) / (wend - wstart); const int pooled_index = ph * pooled_width + pw; for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { const int index = h * width + w; PoolType::process_grad( Xdata[index], Ydata[pooled_index], dYdata[pooled_index], scale, dXdata[index]); } } } } // offset Xdata += height * width; dXdata += height * width; Ydata += pooled_height * pooled_width; dYdata += pooled_height * pooled_width; } } break; case 3: for (int n = 0; n < X.dim32(0); ++n) { for (int c = 0; c < channels; ++c) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); for (int pw = 0; pw < pooled_width; ++pw) { int wstart = pw * stride_w() - pad_l(); int wend = min(wstart + kernel_w(), width); wstart = max(wstart, 0); for (int pd = 0; pd < pooled_depth; ++pd) { int dstart = pd * stride_[2] - pads_[2]; int dend = min(dstart + kernel_[2], depth); dstart = max(dstart, 0); float scale = 1. / (hend - hstart) / (wend - wstart) / (dend - dstart); const int pooled_index = ph * pooled_width * pooled_depth + pw * pooled_depth + pd; for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { for (int d = dstart; d < dend; ++d) { const int index = h * width * depth + w * depth + d; PoolType::process_grad( Xdata[index], Ydata[pooled_index], dYdata[pooled_index], scale, dXdata[index]); } } } } } } // offset Xdata += height * width * depth; dXdata += height * width * depth; Ydata += pooled_height * pooled_width * pooled_depth; dYdata += pooled_height * pooled_width * pooled_depth; } } break; default: CAFFE_THROW("Unsupported pooling size"); return false; } return true; } template <typename T, class Context, typename PoolType> bool PoolGradientOp<T, Context, PoolType>::RunOnDeviceWithOrderNHWC() { auto& X = Input(0); auto& Y = Input(1); auto& dY = Input(2); DCHECK_EQ(dY.ndim(), kernel_.size() + 2); auto* dX = Output(0); dX->ResizeLike(X); int channels = X.dim32(X.ndim() - 1); CAFFE_ENFORCE_EQ(channels, dY.dim32(dY.ndim() - 1)); ConstEigenArrayMap<T> Ymat( Y.template data<float>(), channels, Y.size() / channels); ConstEigenArrayMap<float> dYmat( dY.template data<float>(), channels, Y.size() / channels); ConstEigenArrayMap<float> Xmat( X.template data<float>(), channels, X.size() / channels); EigenArrayMap<float> dXmat( dX->template mutable_data<float>(), channels, X.size() / channels); dXmat.setZero(); int height = X.dim32(1); int width = kernel_.size() > 1 ? X.dim32(2) : 1; int depth = kernel_.size() > 2 ? X.dim32(3) : 1; vector<int> dims(X.dims().begin() + 1, X.dims().end() - 1); ConvPoolOpBase<CPUContext>::ComputePads(dims); int pooled_height = dY.dim32(1); int pooled_width = kernel_.size() > 1 ? dY.dim32(2) : 1; int pooled_depth = kernel_.size() > 2 ? dY.dim32(3) : 1; // The main loop // Do not do openmp here: the following for loops are looping over the pooled // output, so if one parallelizes the outer loops, race conditions could // happen in the inner loops. switch (kernel_.size()) { case 1: for (int n = 0; n < X.dim32(0); ++n) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); const int pool_index = n * pooled_height + ph; const float scale = 1. / (hend - hstart); for (int h = hstart; h < hend; ++h) { const int input_index = n * height + h; PoolType::process_grad( pool_index, input_index, scale, Xmat, Ymat, dYmat, dXmat); } } } break; case 2: for (int n = 0; n < X.dim32(0); ++n) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); for (int pw = 0; pw < pooled_width; ++pw) { int wstart = pw * stride_w() - pad_l(); int wend = min(wstart + kernel_w(), width); wstart = max(wstart, 0); const int pool_index = (n * pooled_height + ph) * pooled_width + pw; const float scale = 1. / (hend - hstart) / (wend - wstart); for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { const int input_index = (n * height + h) * width + w; PoolType::process_grad( pool_index, input_index, scale, Xmat, Ymat, dYmat, dXmat); } } } } } break; case 3: for (int n = 0; n < X.dim32(0); ++n) { for (int ph = 0; ph < pooled_height; ++ph) { int hstart = ph * stride_h() - pad_t(); int hend = min(hstart + kernel_h(), height); hstart = max(hstart, 0); for (int pw = 0; pw < pooled_width; ++pw) { int wstart = pw * stride_w() - pad_l(); int wend = min(wstart + kernel_w(), width); wstart = max(wstart, 0); for (int pd = 0; pd < pooled_depth; ++pd) { int dstart = pd * stride_[2] - pads_[2]; int dend = min(dstart + kernel_[2], depth); dstart = max(dstart, 0); const int pool_index = ((n * pooled_height + ph) * pooled_width + pw) * pooled_depth + pd; const float scale = 1. / (hend - hstart) / (wend - wstart) / (dend - dstart); for (int h = hstart; h < hend; ++h) { for (int w = wstart; w < wend; ++w) { for (int d = dstart; d < dend; ++d) { const int input_index = ((n * height + h) * width + w) * depth + d; PoolType::process_grad( pool_index, input_index, scale, Xmat, Ymat, dYmat, dXmat); } } } } } } } break; default: CAFFE_THROW("Unsupported pooling size"); return false; } return true; } REGISTER_CPU_OPERATOR( AveragePoolGradient, PoolGradientOp<float, CPUContext, AveragePool<float>>); OPERATOR_SCHEMA(AveragePoolGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( AveragePool1DGradient, PoolGradientOp<float, CPUContext, AveragePool<float>>); OPERATOR_SCHEMA(AveragePool1DGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( AveragePool2DGradient, PoolGradientOp<float, CPUContext, AveragePool<float>>); OPERATOR_SCHEMA(AveragePool2DGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( AveragePool3DGradient, PoolGradientOp<float, CPUContext, AveragePool<float>>); OPERATOR_SCHEMA(AveragePool3DGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( MaxPoolGradient, PoolGradientOp<float, CPUContext, MaxPool<float>>); OPERATOR_SCHEMA(MaxPoolGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( MaxPool1DGradient, PoolGradientOp<float, CPUContext, MaxPool<float>>); OPERATOR_SCHEMA(MaxPool1DGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( MaxPool2DGradient, PoolGradientOp<float, CPUContext, MaxPool<float>>); OPERATOR_SCHEMA(MaxPool2DGradient).NumInputs(3).NumOutputs(1); REGISTER_CPU_OPERATOR( MaxPool3DGradient, PoolGradientOp<float, CPUContext, MaxPool<float>>); OPERATOR_SCHEMA(MaxPool3DGradient).NumInputs(3).NumOutputs(1); class GetPoolGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( def_.type() + "Gradient", "", vector<string>{I(0), O(0), GO(0)}, vector<string>{GI(0)}); } }; REGISTER_GRADIENT(AveragePool, GetPoolGradient); REGISTER_GRADIENT(AveragePool1D, GetPoolGradient); REGISTER_GRADIENT(AveragePool2D, GetPoolGradient); REGISTER_GRADIENT(AveragePool3D, GetPoolGradient); REGISTER_GRADIENT(MaxPool, GetPoolGradient); REGISTER_GRADIENT(MaxPool1D, GetPoolGradient); REGISTER_GRADIENT(MaxPool2D, GetPoolGradient); REGISTER_GRADIENT(MaxPool3D, GetPoolGradient); }
#include <Data/RIGID_STRUCTURE.h> #include <Data/RIGID_STRUCTURE_DATA.h> #include <Driver/SIMULATION.h> #include <Force/FORCE.h> #include <Force/SPRING_FORCE.h> #include <Utilities/RANDOM.h> #include <algorithm> #include <cerrno> #include <fstream> #include <iostream> #include <iomanip> #include <string> #include <Data/DATA.h> #include <Data/RIGID_STRUCTURE.h> #include <Data/RIGID_STRUCTURE_DATA.h> #include <Driver/SIMULATION.h> #include <Equation/NONLINEAR_EQUATION.h> using namespace Mechanics; int main(int argc,char **argv) { #if 0 typedef double T; typedef Matrix<T,3,1> TV; auto simulation=std::make_shared<SIMULATION<TV>>(); DATA<TV>& data=simulation->data; FORCE<TV>& force=simulation->force; auto rigid_data=data.template Find_Or_Create<RIGID_STRUCTURE_DATA<TV>>(); auto structure1=std::make_shared<RIGID_STRUCTURE<TV>>(); structure1->frame.position=TV(); structure1->name="first"; structure1->radius=1; structure1->Initialize_Inertia(3.5); rigid_data->structures.push_back(structure1); auto structure2=std::make_shared<RIGID_STRUCTURE<TV>>(); structure2->frame.position=2*TV::UnitX(); structure2->name="second"; structure2->radius=1; structure2->Initialize_Inertia(3.5); rigid_data->structures.push_back(structure2); Matrix<T,Dynamic,1> positions; data.Pack_Positions(positions); auto spring_force=simulation->force.template Find_Or_Create<SPRING_FORCE<TV>>(); typename SPRING_FORCE<TV>::SPRING spring; spring.index={0,1}; spring.offset={TV::UnitX(),TV::UnitY()}; //spring.offset={TV(),TV()}; spring.target_distance=3; spring.stiffness=10; spring_force->springs.push_back(spring); T dt=0.1; T time=0; T epsilon=1; auto equation=new NONLINEAR_EQUATION<TV>(); //*********************** // Set up initial state //*********************** equation->Initialize(data,force); equation->Linearize(data,force,dt,time,true); Matrix<T,Dynamic,1> unknowns=equation->Get_Unknowns(data,force); data.random.Direction(unknowns); equation->Increment_Unknowns(unknowns,data,force); equation->Linearize(data,force,dt,time,false); Matrix<T,Dynamic,1> gradient0;equation->Gradient(gradient0); T f0=equation->Evaluate(); SparseMatrix<T> hessian;equation->Hessian(hessian); //*********************** // Calculate step result //*********************** data.random.Direction(unknowns); auto Evaluate_Step_Error = [&](T eps){ data.Unpack_Positions(positions); equation->Increment_Unknowns(eps*unknowns,data,force); equation->Linearize(data,force,dt,time,false); equation->Increment_Unknowns(-eps*unknowns,data,force); T f1=equation->Evaluate(); T predicted_delta_f=gradient0.dot(eps*unknowns)+(T).5*eps*eps*unknowns.transpose()*hessian*unknowns; T error=f1-f0-predicted_delta_f; return error; }; T last; for(int i=0;i<10;i++,epsilon/=2){ T next=Evaluate_Step_Error(epsilon); if(i>1){std::cout<<"Ratio: "<<last/next<<std::endl;} last=next; } #endif return 0; }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef __OPENCV_IMGCODECS_HPP__ #define __OPENCV_IMGCODECS_HPP__ #include "opencv2/core.hpp" /** @defgroup imgcodecs Image file reading and writing @{ @defgroup imgcodecs_c C API @defgroup imgcodecs_ios iOS glue @} */ //////////////////////////////// image codec //////////////////////////////// namespace cv { //! @addtogroup imgcodecs //! @{ //! Imread flags enum ImreadModes { IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image. IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image. IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. IMREAD_REDUCED_COLOR_8 = 65 //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. }; //! Imwrite flags enum ImwriteFlags { IMWRITE_JPEG_QUALITY = 1, //!< For JPEG, it can be a quality from 0 to 100 (the higher is the better). Default value is 95. IMWRITE_JPEG_PROGRESSIVE = 2, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_OPTIMIZE = 3, //!< Enable JPEG features, 0 or 1, default is False. IMWRITE_JPEG_RST_INTERVAL = 4, //!< JPEG restart interval, 0 - 65535, default is 0 - no restart. IMWRITE_JPEG_LUMA_QUALITY = 5, //!< Separate luma quality level, 0 - 100, default is 0 - don't use. IMWRITE_JPEG_CHROMA_QUALITY = 6, //!< Separate chroma quality level, 0 - 100, default is 0 - don't use. IMWRITE_PNG_COMPRESSION = 16, //!< For PNG, it can be the compression level from 0 to 9. A higher value means a smaller size and longer compression time. Default value is 3. IMWRITE_PNG_STRATEGY = 17, //!< One of cv::ImwritePNGFlags, default is IMWRITE_PNG_STRATEGY_DEFAULT. IMWRITE_PNG_BILEVEL = 18, //!< Binary level PNG, 0 or 1, default is 0. IMWRITE_PXM_BINARY = 32, //!< For PPM, PGM, or PBM, it can be a binary format flag, 0 or 1. Default value is 1. IMWRITE_WEBP_QUALITY = 64 //!< For WEBP, it can be a quality from 1 to 100 (the higher is the better). By default (without any parameter) and for quality above 100 the lossless compression is used. }; //! Imwrite PNG specific flags used to tune the compression algorithm. /** These flags will be modify the way of PNG image compression and will be passed to the underlying zlib processing stage. - The effect of IMWRITE_PNG_STRATEGY_FILTERED is to force more Huffman coding and less string matching; it is somewhat intermediate between IMWRITE_PNG_STRATEGY_DEFAULT and IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY. - IMWRITE_PNG_STRATEGY_RLE is designed to be almost as fast as IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY, but give better compression for PNG image data. - The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately. - IMWRITE_PNG_STRATEGY_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. */ enum ImwritePNGFlags { IMWRITE_PNG_STRATEGY_DEFAULT = 0, //!< Use this value for normal data. IMWRITE_PNG_STRATEGY_FILTERED = 1, //!< Use this value for data produced by a filter (or predictor).Filtered data consists mostly of small values with a somewhat random distribution. In this case, the compression algorithm is tuned to compress them better. IMWRITE_PNG_STRATEGY_HUFFMAN_ONLY = 2, //!< Use this value to force Huffman encoding only (no string match). IMWRITE_PNG_STRATEGY_RLE = 3, //!< Use this value to limit match distances to one (run-length encoding). IMWRITE_PNG_STRATEGY_FIXED = 4 //!< Using this value prevents the use of dynamic Huffman codes, allowing for a simpler decoder for special applications. }; /** @brief Loads an image from a file. @anchor imread The function imread loads an image from the specified file and returns it. If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ). Currently, the following file formats are supported: - Windows bitmaps - \*.bmp, \*.dib (always supported) - JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section) - JPEG 2000 files - \*.jp2 (see the *Notes* section) - Portable Network Graphics - \*.png (see the *Notes* section) - WebP - \*.webp (see the *Notes* section) - Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported) - Sun rasters - \*.sr, \*.ras (always supported) - TIFF files - \*.tiff, \*.tif (see the *Notes* section) - OpenEXR Image files - \*.exr (see the *Notes* section) - Radiance HDR - \*.hdr, \*.pic (always supported) - Raster and Vector geospatial data supported by Gdal (see the *Notes* section) @note - The function determines the type of an image by the content, not by the file extension. - In the case of color images, the decoded images will have the channels stored in **B G R** order. - On Microsoft Windows\* OS and MacOSX\*, the codecs shipped with an OpenCV image (libjpeg, libpng, libtiff, and libjasper) are used by default. So, OpenCV can always read JPEGs, PNGs, and TIFFs. On MacOSX, there is also an option to use native MacOSX image readers. But beware that currently these native image loaders give images with different pixel values because of the color management embedded into MacOSX. - On Linux\*, BSD flavors and other Unix-like open-source operating systems, OpenCV looks for codecs supplied with an OS image. Install the relevant packages (do not forget the development files, for example, "libjpeg-dev", in Debian\* and Ubuntu\*) to get the codec support or turn on the OPENCV_BUILD_3RDPARTY_LIBS flag in CMake. - In the case you set *WITH_GDAL* flag to true in CMake and @ref IMREAD_LOAD_GDAL to load the image, then [GDAL](http://www.gdal.org) driver will be used in order to decode the image by supporting the following formats: [Raster](http://www.gdal.org/formats_list.html), [Vector](http://www.gdal.org/ogr_formats.html). @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes */ CV_EXPORTS_W Mat imread( const String& filename, int flags = IMREAD_COLOR ); /** @brief Loads a multi-page image from a file. The function imreadmulti loads a multi-page image from the specified file into a vector of Mat objects. @param filename Name of file to be loaded. @param flags Flag that can take values of cv::ImreadModes, default with cv::IMREAD_ANYCOLOR. @param mats A vector of Mat objects holding each page, if more than one. @sa cv::imread */ CV_EXPORTS_W bool imreadmulti(const String& filename, std::vector<Mat>& mats, int flags = IMREAD_ANYCOLOR); /** @brief Saves an image to a specified file. The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see cv::imread for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with 'BGR' channel order) images can be saved using this function. If the format, depth or channel order is different, use Mat::convertTo , and cv::cvtColor to convert it before saving. Or, use the universal FileStorage I/O functions to save the image to XML or YAML format. It is possible to store PNG images with an alpha channel using this function. To do this, create 8-bit (or 16-bit) 4-channel image BGRA, where the alpha channel goes last. Fully transparent pixels should have alpha set to 0, fully opaque pixels should have alpha set to 255/65535. The sample below shows how to create such a BGRA image and store to PNG file. It also demonstrates how to set custom compression parameters : @code #include <opencv2/opencv.hpp> using namespace cv; using namespace std; void createAlphaMat(Mat &mat) { CV_Assert(mat.channels() == 4); for (int i = 0; i < mat.rows; ++i) { for (int j = 0; j < mat.cols; ++j) { Vec4b& bgra = mat.at<Vec4b>(i, j); bgra[0] = UCHAR_MAX; // Blue bgra[1] = saturate_cast<uchar>((float (mat.cols - j)) / ((float)mat.cols) * UCHAR_MAX); // Green bgra[2] = saturate_cast<uchar>((float (mat.rows - i)) / ((float)mat.rows) * UCHAR_MAX); // Red bgra[3] = saturate_cast<uchar>(0.5 * (bgra[1] + bgra[2])); // Alpha } } } int main(int argv, char **argc) { // Create mat with alpha channel Mat mat(480, 640, CV_8UC4); createAlphaMat(mat); vector<int> compression_params; compression_params.push_back(IMWRITE_PNG_COMPRESSION); compression_params.push_back(9); try { imwrite("alpha.png", mat, compression_params); } catch (cv::Exception& ex) { fprintf(stderr, "Exception converting image to PNG format: %s\n", ex.what()); return 1; } fprintf(stdout, "Saved PNG file with alpha data.\n"); return 0; } @endcode @param filename Name of the file. @param img Image to be saved. @param params Format-specific parameters encoded as pairs (paramId_1, paramValue_1, paramId_2, paramValue_2, ... .) see cv::ImwriteFlags */ CV_EXPORTS_W bool imwrite( const String& filename, InputArray img, const std::vector<int>& params = std::vector<int>()); /** @brief Reads an image from a buffer in memory. The function imdecode reads an image from the specified buffer in the memory. If the buffer is too short or contains invalid data, the function returns an empty matrix ( Mat::data==NULL ). See cv::imread for the list of supported formats and flags description. @note In the case of color images, the decoded images will have the channels stored in **B G R** order. @param buf Input array or vector of bytes. @param flags The same flags as in cv::imread, see cv::ImreadModes. */ CV_EXPORTS_W Mat imdecode( InputArray buf, int flags ); /** @overload @param buf @param flags @param dst The optional output placeholder for the decoded matrix. It can save the image reallocations when the function is called repeatedly for images of the same size. */ CV_EXPORTS Mat imdecode( InputArray buf, int flags, Mat* dst); /** @brief Encodes an image into a memory buffer. The function imencode compresses the image and stores it in the memory buffer that is resized to fit the result. See cv::imwrite for the list of supported formats and flags description. @param ext File extension that defines the output format. @param img Image to be written. @param buf Output buffer resized to fit the compressed image. @param params Format-specific parameters. See cv::imwrite and cv::ImwriteFlags. */ CV_EXPORTS_W bool imencode( const String& ext, InputArray img, CV_OUT std::vector<uchar>& buf, const std::vector<int>& params = std::vector<int>()); //! @} imgcodecs } // cv #endif //__OPENCV_IMGCODECS_HPP__
//------------------------------------------------------------------------------ // debugserver.cc // (C) 2008 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "debug/debugserver.h" #include "debug/debugtimer.h" #include "debug/debugcounter.h" namespace Debug { __ImplementClass(Debug::DebugServer, 'DBGS', Core::RefCounted); __ImplementInterfaceSingleton(Debug::DebugServer); using namespace Util; //------------------------------------------------------------------------------ /** */ DebugServer::DebugServer() : isOpen(false) { __ConstructInterfaceSingleton; } //------------------------------------------------------------------------------ /** */ DebugServer::~DebugServer() { n_assert(!this->isOpen); __DestructInterfaceSingleton; } //------------------------------------------------------------------------------ /** */ void DebugServer::Open() { this->critSect.Enter(); n_assert(!this->isOpen); this->isOpen = true; this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ void DebugServer::Close() { this->critSect.Enter(); n_assert(this->isOpen); this->debugTimers.Clear(); this->debugCounters.Clear(); this->isOpen = false; this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ void DebugServer::RegisterDebugTimer(const Ptr<DebugTimer>& timer) { this->critSect.Enter(); n_assert(this->isOpen); n_assert(!this->debugTimers.Contains(timer->GetName())); this->debugTimers.Add(timer->GetName(), timer); this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ void DebugServer::UnregisterDebugTimer(const Ptr<DebugTimer>& timer) { this->critSect.Enter(); n_assert(this->isOpen); n_assert(this->debugTimers.Contains(timer->GetName())); this->debugTimers.Erase(timer->GetName()); this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ void DebugServer::RegisterDebugCounter(const Ptr<DebugCounter>& counter) { this->critSect.Enter(); n_assert(this->isOpen); n_assert(!this->debugCounters.Contains(counter->GetName())); this->debugCounters.Add(counter->GetName(), counter); this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ void DebugServer::UnregisterDebugCounter(const Ptr<DebugCounter>& counter) { this->critSect.Enter(); n_assert(this->isOpen); n_assert(this->debugCounters.Contains(counter->GetName())); this->debugCounters.Erase(counter->GetName()); this->critSect.Leave(); } //------------------------------------------------------------------------------ /** */ Array<Ptr<DebugTimer> > DebugServer::GetDebugTimers() const { this->critSect.Enter(); Array<Ptr<DebugTimer> > result = this->debugTimers.ValuesAsArray(); this->critSect.Leave(); return result; } //------------------------------------------------------------------------------ /** */ Array<Ptr<DebugCounter> > DebugServer::GetDebugCounters() const { this->critSect.Enter(); Array<Ptr<DebugCounter> > result = this->debugCounters.ValuesAsArray(); this->critSect.Leave(); return result; } //------------------------------------------------------------------------------ /** */ Ptr<DebugTimer> DebugServer::GetDebugTimerByName(const StringAtom& name) const { Ptr<DebugTimer> result; this->critSect.Enter(); if (this->debugTimers.Contains(name)) { result = this->debugTimers[name]; } this->critSect.Leave(); return result; } //------------------------------------------------------------------------------ /** */ Ptr<DebugCounter> DebugServer::GetDebugCounterByName(const StringAtom& name) const { Ptr<DebugCounter> result; this->critSect.Enter(); if (this->debugCounters.Contains(name)) { result = this->debugCounters[name]; } this->critSect.Leave(); return result; } } // namespace Debug
//MOHAMMAD added #include "caffe2/operators/elementwise_op.h" #include "caffe2/utils/math.h" namespace caffe2 { struct AbsCPUFunctor { template <typename T> inline void operator()(const int n, const T* x, T* y, CPUContext* device_context) { math::Abs<T, CPUContext>(n, x, y, device_context); } }; struct AbsGradientCPUFunctor { template <typename T> inline void Run(const int n, const T* x, const T* dy, T* dx, CPUContext* /* unused */) { ConstEigenVectorArrayMap<T> dyM(dy, n); ConstEigenVectorArrayMap<T> xM(x, n); EigenVectorMap<T>(dx, n) = (xM == T(0)).select(T(0), (xM > T(0)).select(dyM, -dyM)); } }; REGISTER_CPU_OPERATOR( Abs, UnaryElementwiseOp<TensorTypes<float>, CPUContext, AbsCPUFunctor>); REGISTER_CPU_OPERATOR( AbsGradient, BinaryElementwiseOp< TensorTypes<float>, CPUContext, WithoutBroadcast<AbsGradientCPUFunctor>>); OPERATOR_SCHEMA(Abs) .NumInputs(1) .NumOutputs(1) .IdenticalTypeAndShape() .SetDoc(R"DOC( Calculates the absolute value of the given input tensor, element-wise. )DOC") .Input(0, "input", "Input tensor") .Output( 0, "output", "The absolute value of the input tensor computed element-wise"); OPERATOR_SCHEMA(AbsGradient).NumInputs(2).NumOutputs(1).IdenticalTypeAndShape(); class GetAbsGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return SingleGradientDef( "AbsGradient", "", std::vector<string>{I(0), GO(0)}, std::vector<string>{GI(0)}); } }; REGISTER_GRADIENT(Abs, GetAbsGradient); } // namespace caffe2
// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQSBMLFileDialog.cpp,v $ // $Revision: 1.12 $ // $Name: $ // $Author: shoops $ // $Date: 2012/04/27 16:33:29 $ // End CVS Header // Copyright (C) 2012 - 2010 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. // Copyright (C) 2001 - 2007 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc. and EML Research, gGmbH. // All rights reserved. #include <QtCore/QRegExp> #include "copasi.h" #include "CQSBMLFileDialog.h" #include "CopasiFileDialog.h" // static std::pair< QString, std::pair< unsigned C_INT32, unsigned C_INT32 > > CQSBMLFileDialog::getSaveFileName(QWidget * parent, const char * name, const QString & startWith, const QString & caption, unsigned int sbmlLevel, unsigned int sbmlVersion) { std::pair< QString, std::pair< unsigned C_INT32, unsigned C_INT32 > > NameAndVersion; QString Filter = "Level 1 Version 2 (*.xml);;" "Level 2 Version 1 (*.xml);;" "Level 2 Version 2 (*.xml);;" "Level 2 Version 3 (*.xml);;" "Level 2 Version 4 (*.xml);;" "Level 3 Version 1 (*.xml)"; QString SelectedFilter = QString("Level %1 Version %2 (*.xml)").arg(QString::number(sbmlLevel)).arg(QString::number(sbmlVersion));; // The default export is L2V4 if (Filter.indexOf(SelectedFilter) == -1) { SelectedFilter = "Level 2 Version 4 (*.xml)"; } // We need to avoid the KDE dialog at least under Qt 4.7 and KDE 4.5 // See: Bug 1651 QFileDialog::Options DontUseNativeDialog = 0; #ifdef Linux DontUseNativeDialog = QFileDialog::DontUseNativeDialog; #endif // Linux NameAndVersion.first = CopasiFileDialog::getSaveFileName(parent, name, startWith, Filter, caption, &SelectedFilter, DontUseNativeDialog); QRegExp Pattern("Level (\\d) Version (\\d) \\(\\*\\.xml\\)"); if (Pattern.exactMatch(SelectedFilter)) { NameAndVersion.second.first = Pattern.cap(1).toInt(); NameAndVersion.second.second = Pattern.cap(2).toInt(); } else { NameAndVersion.second.first = 2; NameAndVersion.second.second = 4; } return NameAndVersion; }
/* This file contains HEAP definitions. Kalev Kask, May 2002. */ #ifndef HEAP_HXX_INCLUDED #define HEAP_HXX_INCLUDED #define HEAP_DEFAULT_SIZE 128 #define HEAP_SIZE_LIMIT 1048576 class CMauiHeap { protected : // number of elements in the heap; actual key/data array sizes are m_size+1 since user keys/data start from [1] unsigned long m_size ; // allocated space; as the max number of elements that can be accomodated. unsigned long m_allocated_space ; // When reallocating the heap, DBM will reserve that much more memory. // If this variable is 0, DBM will never reallocate. // That means that when the heap is full and the user calls Insert() on the heap, it will fail. // Initially equal to DBM_HEAP_DEFAULT_SIZE. unsigned long m_re_allocation_size ; // keys by which the heap is sorted; keys start from [1] long *m_key ; // information associated with every key long *m_data ; // if TRUE, largest comes first; otherwise smallest comes first. // default is TRUE. bool m_bSortOrderIsDecreasing ; private : // when the heap is full, then DBM tries to reallocate the entire heap int ReAllocateMemory(void) ; // assume a new key was placed at index 'Idx'; assume the size of the heap is correct and anything // above m_data[Idx] is correct. Fix the data below m_data[Idx]. int UpdateHeap_AfterRemove(unsigned long Idx) ; public : // Default constructor creates an empty heap of size DBM_HEAP_DEFAULT_SIZE. CMauiHeap(void) ; // This constructor creates a heap from a set of keys. CMauiHeap(unsigned long size, /* number of keys, has to be >= 0 */ long *key, /* an array of keys */ long *data, /* data associated with each key */ unsigned long space, /* how much space to allocate for the heap */ unsigned long re_allocation_size = HEAP_DEFAULT_SIZE) ; int Import(unsigned long size, /* number of keys, has to be >= 0 */ long *key, /* an array of keys */ long *data /* data associated with each key */) ; ~CMauiHeap(void) ; int AllocateMemory(long size) ; void SetReAllocationSize(long reallocation_size) ; // has to be non-negative. default DBM_HEAP_DEFAULT_SIZE. long CheckHeap(void) ; // returns TRUE iff the heap is OK. inline void SetSortOrder(bool NewOrder) { m_bSortOrderIsDecreasing = NewOrder ; } inline void Empty(void) { m_size = 0 ; } // this will empty the heap. inline long GetSize(void) const { return m_size ; } inline long GetSpace(void) const { return m_allocated_space ; } long Insert(long key, long data) ; // returns FALSE iff it fails (no memory) // remove the largest key/data; returns FALSE if the heap is empty long Remove(long *key /* return key */, long *data /* return data, can be NULL */) ; // remove a specific key/data; returns FALSE if the key is not in the heap long Remove_key(long key /* key to remove */, long *data /* return data, can be NULL */) ; long Remove_data(long *key /* return key */, long data /* data to remove */) ; // remove element at specific idx long Remove_idx(long idx, long *key, long *data) ; int ContainsKey(long key) ; int ContainsData(long data) ; // This function returns the first (topmost) key and the data associated with it, // but does not remove it from the heap. long GetFirst(long *key /* return key */, long *data /* return data, can be NULL */) ; // returns FALSE if the heap is empty inline void GetIdx(int idx, long & key, long & data) { key = m_key[idx] ; data = m_data[idx] ; } } ; class CMauiHeap_Basic { protected : // number of elements in the heap; actual key/data array sizes are m_size+1 since user keys/data start from [1] unsigned long m_size ; // allocated space; as the max number of elements that can be accomodated. unsigned long m_allocated_space ; // When reallocating the heap, DBM will reserve that much more memory. // If this variable is 0, DBM will never reallocate. // That means that when the heap is full and the user calls Insert() on the heap, it will fail. // Initially equal to DBM_HEAP_DEFAULT_SIZE. unsigned long m_re_allocation_size ; // keys by which the heap is sorted; keys start from [1] long *m_key ; // if TRUE, largest comes first; otherwise smallest comes first. // default is TRUE. bool m_bSortOrderIsDecreasing ; private : // when the heap is full, then DBM tries to reallocate the entire heap int ReAllocateMemory(void) ; // assume a new key was placed at index 'Idx'; assume the size of the heap is correct and anything // above m_data[Idx] is correct. Fix the data below m_data[Idx]. int UpdateHeap_AfterRemove(unsigned long Idx) ; public : // Default constructor creates an empty heap of size DBM_HEAP_DEFAULT_SIZE. CMauiHeap_Basic(void) ; // This constructor creates a heap from a set of keys. CMauiHeap_Basic(unsigned long size, /* number of keys, has to be >= 0 */ long *key, /* an array of keys */ unsigned long space, /* how much space to allocate for the heap */ unsigned long re_allocation_size = HEAP_DEFAULT_SIZE) ; int Import(unsigned long size, /* number of keys, has to be >= 0 */ long *key/* an array of keys */) ; ~CMauiHeap_Basic(void) ; int operator=(const CMauiHeap_Basic & Heap) ; int AllocateMemory(long size) ; void SetReAllocationSize(long reallocation_size) ; // has to be non-negative. default DBM_HEAP_DEFAULT_SIZE. long CheckHeap(void) ; // returns TRUE iff the heap is OK. inline void SetSortOrder(bool NewOrder) { m_bSortOrderIsDecreasing = NewOrder ; } inline void Empty(void) { m_size = 0 ; } // this will empty the heap. inline long GetSize(void) const { return m_size ; } inline long GetSpace(void) const { return m_allocated_space ; } long Insert(long key) ; // returns FALSE iff it fails (no memory) // remove the largest key/data; returns FALSE if the heap is empty long Remove(long *key /* return key */) ; // remove a specific key/data; returns FALSE if the key is not in the heap long Remove_key(long key /* key to remove */) ; // remove element at specific idx long Remove_idx(long idx, long *key) ; int ContainsKey(long key) ; // This function returns the first (topmost) key and the data associated with it, // but does not remove it from the heap. long GetFirst(long *key /* return key */) ; // returns FALSE if the heap is empty inline void GetIdx(int idx, long & key) { key = m_key[idx] ; } } ; /* Reduction -> after heap is constructed, its size will be reduced, one at a time until 0. PermutationMapping -> we keep track of how the original order of items changes over time. */ class CMauiHeap_Basic_ReductionWithPermutationMapping { protected : // number of elements in the heap; actual key/data array sizes are m_size+1 since user keys/data start from [1] unsigned long m_size ; // allocated space; as the max number of elements that can be accomodated. unsigned long m_allocated_space ; // When reallocating the heap, DBM will reserve that much more memory. // If this variable is 0, DBM will never reallocate. // That means that when the heap is full and the user calls Insert() on the heap, it will fail. // Initially equal to DBM_HEAP_DEFAULT_SIZE. unsigned long m_re_allocation_size ; // keys by which the heap is sorted; keys start from [1] long *m_key ; // mapping data : // Original index of the corresponding element; e.g. m_CurrentIdx2OriginalIdxMap[5] = 3 means that element 5 was originally 3rd in the input list long *m_CurrentIdx2OriginalIdxMap ; // Position of the corresponding element with the given original index; e.g. m_OriginalIdx2CurrentIdxMap[3] = 5 means that 3rd element in the original input list is at position 5 long *m_OriginalIdx2CurrentIdxMap ; // we have the property that m_OriginalIdx2CurrentIdxMap[m_CurrentIdx2OriginalIdxMap[i]] = i, where i is an index into m_key[] // if TRUE, largest comes first; otherwise smallest comes first. // default is TRUE. bool m_bSortOrderIsDecreasing ; private : // when the heap is full, then DBM tries to reallocate the entire heap int ReAllocateMemory(void) ; // assume a new key was placed at index 'Idx'; assume the size of the heap is correct and anything // above m_data[Idx] is correct. Fix the data below m_data[Idx]. int UpdateHeap_AfterRemove(unsigned long Idx) ; public : // Default constructor creates an empty heap of size DBM_HEAP_DEFAULT_SIZE. CMauiHeap_Basic_ReductionWithPermutationMapping(void) ; int Import(unsigned long size, /* number of keys, has to be >= 0 */ long *key/* an array of keys */) ; ~CMauiHeap_Basic_ReductionWithPermutationMapping(void) ; inline long OriginalIdx2CurrentIdxMap(int idx) const { return m_OriginalIdx2CurrentIdxMap[idx] ; } inline long CurrentIdx2OriginalIdxMap(int idx) const { return m_CurrentIdx2OriginalIdxMap[idx] ; } int operator=(const CMauiHeap_Basic_ReductionWithPermutationMapping & Heap) ; int AllocateMemory(long size) ; void SetReAllocationSize(long reallocation_size) ; // has to be non-negative. default DBM_HEAP_DEFAULT_SIZE. // update key at the given position int UpdateKey(unsigned long Idx, long new_key) ; long CheckHeap(void) ; // returns TRUE iff the heap is OK. inline void SetSortOrder(bool NewOrder) { m_bSortOrderIsDecreasing = NewOrder ; } inline void Empty(void) { m_size = 0 ; } // this will empty the heap. inline long GetSize(void) const { return m_size ; } inline long GetSpace(void) const { return m_allocated_space ; } long Insert(long key) ; // returns FALSE iff it fails (no memory) // remove the largest key/data; returns FALSE if the heap is empty long Remove(long *key /* return key */) ; // remove a specific key/data; returns FALSE if the key is not in the heap long Remove_key(long key /* key to remove */) ; // remove element at specific idx long Remove_idx(long idx, long *key) ; int ContainsKey(long key) ; // This function returns the first (topmost) key and the data associated with it, // but does not remove it from the heap. long GetFirst(long *key /* return key */) ; // returns FALSE if the heap is empty inline void GetIdx(int idx, long & key) const { key = m_key[idx] ; } } ; #endif // HEAP_HXX_INCLUDED
/********************************************************************** * $Id: cpl_path.cpp 25181 2012-10-27 11:52:46Z rouault $ * * Project: CPL - Common Portability Library * Purpose: Portable filename/path parsing, and forming ala "Glob API". * Author: Frank Warmerdam, warmerdam@pobox.com * ********************************************************************** * Copyright (c) 1999, Frank Warmerdam * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "cpl_conv.h" #include "cpl_string.h" #include "cpl_multiproc.h" CPL_CVSID("$Id: cpl_path.cpp 25181 2012-10-27 11:52:46Z rouault $"); /* should be size of larged possible filename */ #define CPL_PATH_BUF_SIZE 2048 #define CPL_PATH_BUF_COUNT 10 #if defined(WIN32) || defined(WIN32CE) #define SEP_CHAR '\\' #define SEP_STRING "\\" #else #define SEP_CHAR '/' #define SEP_STRING "/" #endif static const char* CPLStaticBufferTooSmall(char *pszStaticResult) { CPLError(CE_Failure, CPLE_AppDefined, "Destination buffer too small"); strcpy( pszStaticResult, "" ); return pszStaticResult; } /************************************************************************/ /* CPLGetStaticResult() */ /************************************************************************/ static char *CPLGetStaticResult() { char *pachBufRingInfo = (char *) CPLGetTLS( CTLS_PATHBUF ); if( pachBufRingInfo == NULL ) { pachBufRingInfo = (char *) CPLCalloc(1, sizeof(int) + CPL_PATH_BUF_SIZE * CPL_PATH_BUF_COUNT); CPLSetTLS( CTLS_PATHBUF, pachBufRingInfo, TRUE ); } /* -------------------------------------------------------------------- */ /* Work out which string in the "ring" we want to use this */ /* time. */ /* -------------------------------------------------------------------- */ int *pnBufIndex = (int *) pachBufRingInfo; int nOffset = sizeof(int) + *pnBufIndex * CPL_PATH_BUF_SIZE; char *pachBuffer = pachBufRingInfo + nOffset; *pnBufIndex = (*pnBufIndex + 1) % CPL_PATH_BUF_COUNT; return pachBuffer; } /************************************************************************/ /* CPLFindFilenameStart() */ /************************************************************************/ static int CPLFindFilenameStart( const char * pszFilename ) { size_t iFileStart; for( iFileStart = strlen(pszFilename); iFileStart > 0 && pszFilename[iFileStart-1] != '/' && pszFilename[iFileStart-1] != '\\'; iFileStart-- ) {} return (int)iFileStart; } /************************************************************************/ /* CPLGetPath() */ /************************************************************************/ /** * Extract directory path portion of filename. * * Returns a string containing the directory path portion of the passed * filename. If there is no path in the passed filename an empty string * will be returned (not NULL). * * <pre> * CPLGetPath( "abc/def.xyz" ) == "abc" * CPLGetPath( "/abc/def/" ) == "/abc/def" * CPLGetPath( "/" ) == "/" * CPLGetPath( "/abc/def" ) == "/abc" * CPLGetPath( "abc" ) == "" * </pre> * * @param pszFilename the filename potentially including a path. * * @return Path in an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. The returned * will generally not contain a trailing path separator. */ const char *CPLGetPath( const char *pszFilename ) { int iFileStart = CPLFindFilenameStart(pszFilename); char *pszStaticResult = CPLGetStaticResult(); if( iFileStart >= CPL_PATH_BUF_SIZE ) return CPLStaticBufferTooSmall(pszStaticResult); CPLAssert( ! (pszFilename >= pszStaticResult && pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE) ); if( iFileStart == 0 ) { strcpy( pszStaticResult, "" ); return pszStaticResult; } CPLStrlcpy( pszStaticResult, pszFilename, iFileStart+1 ); if( iFileStart > 1 && (pszStaticResult[iFileStart-1] == '/' || pszStaticResult[iFileStart-1] == '\\') ) pszStaticResult[iFileStart-1] = '\0'; return pszStaticResult; } /************************************************************************/ /* CPLGetDirname() */ /************************************************************************/ /** * Extract directory path portion of filename. * * Returns a string containing the directory path portion of the passed * filename. If there is no path in the passed filename the dot will be * returned. It is the only difference from CPLGetPath(). * * <pre> * CPLGetDirname( "abc/def.xyz" ) == "abc" * CPLGetDirname( "/abc/def/" ) == "/abc/def" * CPLGetDirname( "/" ) == "/" * CPLGetDirname( "/abc/def" ) == "/abc" * CPLGetDirname( "abc" ) == "." * </pre> * * @param pszFilename the filename potentially including a path. * * @return Path in an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. The returned * will generally not contain a trailing path separator. */ const char *CPLGetDirname( const char *pszFilename ) { int iFileStart = CPLFindFilenameStart(pszFilename); char *pszStaticResult = CPLGetStaticResult(); if( iFileStart >= CPL_PATH_BUF_SIZE ) return CPLStaticBufferTooSmall(pszStaticResult); CPLAssert( ! (pszFilename >= pszStaticResult && pszFilename < pszStaticResult + CPL_PATH_BUF_SIZE) ); if( iFileStart == 0 ) { strcpy( pszStaticResult, "." ); return pszStaticResult; } CPLStrlcpy( pszStaticResult, pszFilename, iFileStart+1 ); if( iFileStart > 1 && (pszStaticResult[iFileStart-1] == '/' || pszStaticResult[iFileStart-1] == '\\') ) pszStaticResult[iFileStart-1] = '\0'; return pszStaticResult; } /************************************************************************/ /* CPLGetFilename() */ /************************************************************************/ /** * Extract non-directory portion of filename. * * Returns a string containing the bare filename portion of the passed * filename. If there is no filename (passed value ends in trailing directory * separator) an empty string is returned. * * <pre> * CPLGetFilename( "abc/def.xyz" ) == "def.xyz" * CPLGetFilename( "/abc/def/" ) == "" * CPLGetFilename( "abc/def" ) == "def" * </pre> * * @param pszFullFilename the full filename potentially including a path. * * @return just the non-directory portion of the path (points back into original string). */ const char *CPLGetFilename( const char *pszFullFilename ) { int iFileStart = CPLFindFilenameStart( pszFullFilename ); return pszFullFilename + iFileStart; } /************************************************************************/ /* CPLGetBasename() */ /************************************************************************/ /** * Extract basename (non-directory, non-extension) portion of filename. * * Returns a string containing the file basename portion of the passed * name. If there is no basename (passed value ends in trailing directory * separator, or filename starts with a dot) an empty string is returned. * * <pre> * CPLGetBasename( "abc/def.xyz" ) == "def" * CPLGetBasename( "abc/def" ) == "def" * CPLGetBasename( "abc/def/" ) == "" * </pre> * * @param pszFullFilename the full filename potentially including a path. * * @return just the non-directory, non-extension portion of the path in * an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. */ const char *CPLGetBasename( const char *pszFullFilename ) { size_t iFileStart = CPLFindFilenameStart( pszFullFilename ); size_t iExtStart, nLength; char *pszStaticResult = CPLGetStaticResult(); CPLAssert( ! (pszFullFilename >= pszStaticResult && pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE) ); for( iExtStart = strlen(pszFullFilename); iExtStart > iFileStart && pszFullFilename[iExtStart] != '.'; iExtStart-- ) {} if( iExtStart == iFileStart ) iExtStart = strlen(pszFullFilename); nLength = iExtStart - iFileStart; if (nLength >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); CPLStrlcpy( pszStaticResult, pszFullFilename + iFileStart, nLength + 1 ); return pszStaticResult; } /************************************************************************/ /* CPLGetExtension() */ /************************************************************************/ /** * Extract filename extension from full filename. * * Returns a string containing the extention portion of the passed * name. If there is no extension (the filename has no dot) an empty string * is returned. The returned extension will not include the period. * * <pre> * CPLGetExtension( "abc/def.xyz" ) == "xyz" * CPLGetExtension( "abc/def" ) == "" * </pre> * * @param pszFullFilename the full filename potentially including a path. * * @return just the extension portion of the path in * an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. */ const char *CPLGetExtension( const char *pszFullFilename ) { size_t iFileStart = CPLFindFilenameStart( pszFullFilename ); size_t iExtStart; char *pszStaticResult = CPLGetStaticResult(); CPLAssert( ! (pszFullFilename >= pszStaticResult && pszFullFilename < pszStaticResult + CPL_PATH_BUF_SIZE) ); for( iExtStart = strlen(pszFullFilename); iExtStart > iFileStart && pszFullFilename[iExtStart] != '.'; iExtStart-- ) {} if( iExtStart == iFileStart ) iExtStart = strlen(pszFullFilename)-1; if (CPLStrlcpy( pszStaticResult, pszFullFilename+iExtStart+1, CPL_PATH_BUF_SIZE ) >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); return pszStaticResult; } /************************************************************************/ /* CPLGetCurrentDir() */ /************************************************************************/ /** * Get the current working directory name. * * @return a pointer to buffer, containing current working directory path * or NULL in case of error. User is responsible to free that buffer * after usage with CPLFree() function. * If HAVE_GETCWD macro is not defined, the function returns NULL. **/ char *CPLGetCurrentDir() { size_t nPathMax; char *pszDirPath; # ifdef _MAX_PATH nPathMax = _MAX_PATH; # elif PATH_MAX nPathMax = PATH_MAX; # else nPathMax = 8192; # endif pszDirPath = (char*)CPLMalloc( nPathMax ); if ( !pszDirPath ) return NULL; #ifdef HAVE_GETCWD return getcwd( pszDirPath, nPathMax ); #else return NULL; #endif /* HAVE_GETCWD */ } /************************************************************************/ /* CPLResetExtension() */ /************************************************************************/ /** * Replace the extension with the provided one. * * @param pszPath the input path, this string is not altered. * @param pszExt the new extension to apply to the given path. * * @return an altered filename with the new extension. Do not * modify or free the returned string. The string may be destroyed by the * next CPL call. */ const char *CPLResetExtension( const char *pszPath, const char *pszExt ) { char *pszStaticResult = CPLGetStaticResult(); size_t i; CPLAssert( ! (pszPath >= pszStaticResult && pszPath < pszStaticResult + CPL_PATH_BUF_SIZE) ); /* -------------------------------------------------------------------- */ /* First, try and strip off any existing extension. */ /* -------------------------------------------------------------------- */ if (CPLStrlcpy( pszStaticResult, pszPath, CPL_PATH_BUF_SIZE ) >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); if (*pszStaticResult) { for( i = strlen(pszStaticResult) - 1; i > 0; i-- ) { if( pszStaticResult[i] == '.' ) { pszStaticResult[i] = '\0'; break; } if( pszStaticResult[i] == '/' || pszStaticResult[i] == '\\' || pszStaticResult[i] == ':' ) break; } } /* -------------------------------------------------------------------- */ /* Append the new extension. */ /* -------------------------------------------------------------------- */ if (CPLStrlcat( pszStaticResult, ".", CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE || CPLStrlcat( pszStaticResult, pszExt, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); return pszStaticResult; } /************************************************************************/ /* CPLFormFilename() */ /************************************************************************/ /** * Build a full file path from a passed path, file basename and extension. * * The path, and extension are optional. The basename may in fact contain * an extension if desired. * * <pre> * CPLFormFilename("abc/xyz","def", ".dat" ) == "abc/xyz/def.dat" * CPLFormFilename(NULL,"def", NULL ) == "def" * CPLFormFilename(NULL,"abc/def.dat", NULL ) == "abc/def.dat" * CPLFormFilename("/abc/xyz/","def.dat", NULL ) == "/abc/xyz/def.dat" * </pre> * * @param pszPath directory path to the directory containing the file. This * may be relative or absolute, and may have a trailing path separator or * not. May be NULL. * * @param pszBasename file basename. May optionally have path and/or * extension. Must *NOT* be NULL. * * @param pszExtension file extension, optionally including the period. May * be NULL. * * @return a fully formed filename in an internal static string. Do not * modify or free the returned string. The string may be destroyed by the * next CPL call. */ const char *CPLFormFilename( const char * pszPath, const char * pszBasename, const char * pszExtension ) { char *pszStaticResult = CPLGetStaticResult(); const char *pszAddedPathSep = ""; const char *pszAddedExtSep = ""; CPLAssert( ! (pszPath >= pszStaticResult && pszPath < pszStaticResult + CPL_PATH_BUF_SIZE) ); CPLAssert( ! (pszBasename >= pszStaticResult && pszBasename < pszStaticResult + CPL_PATH_BUF_SIZE) ); if( pszBasename[0] == '.' && pszBasename[1] == '/' ) pszBasename += 2; if( pszPath == NULL ) pszPath = ""; else if( strlen(pszPath) > 0 && pszPath[strlen(pszPath)-1] != '/' && pszPath[strlen(pszPath)-1] != '\\' ) { /* FIXME? would be better to ask the filesystems what they */ /* prefer as directory separator */ if (strncmp(pszPath, "/vsicurl/", 9) == 0) pszAddedPathSep = "/"; else pszAddedPathSep = SEP_STRING; } if( pszExtension == NULL ) pszExtension = ""; else if( pszExtension[0] != '.' && strlen(pszExtension) > 0 ) pszAddedExtSep = "."; if (CPLStrlcpy( pszStaticResult, pszPath, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE || CPLStrlcat( pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE || CPLStrlcat( pszStaticResult, pszBasename, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE || CPLStrlcat( pszStaticResult, pszAddedExtSep, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE || CPLStrlcat( pszStaticResult, pszExtension, CPL_PATH_BUF_SIZE) >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); return pszStaticResult; } /************************************************************************/ /* CPLFormCIFilename() */ /************************************************************************/ /** * Case insensitive file searching, returing full path. * * This function tries to return the path to a file regardless of * whether the file exactly matches the basename, and extension case, or * is all upper case, or all lower case. The path is treated as case * sensitive. This function is equivelent to CPLFormFilename() on * case insensitive file systems (like Windows). * * @param pszPath directory path to the directory containing the file. This * may be relative or absolute, and may have a trailing path separator or * not. May be NULL. * * @param pszBasename file basename. May optionally have path and/or * extension. May not be NULL. * * @param pszExtension file extension, optionally including the period. May * be NULL. * * @return a fully formed filename in an internal static string. Do not * modify or free the returned string. The string may be destroyed by the * next CPL call. */ const char *CPLFormCIFilename( const char * pszPath, const char * pszBasename, const char * pszExtension ) { // On case insensitive filesystems, just default to // CPLFormFilename() if( !VSIIsCaseSensitiveFS(pszPath) ) return CPLFormFilename( pszPath, pszBasename, pszExtension ); const char *pszAddedExtSep = ""; char *pszFilename; const char *pszFullPath; int nLen = strlen(pszBasename)+2, i; VSIStatBufL sStatBuf; int nStatRet; if( pszExtension != NULL ) nLen += strlen(pszExtension); pszFilename = (char *) CPLMalloc(nLen); if( pszExtension == NULL ) pszExtension = ""; else if( pszExtension[0] != '.' && strlen(pszExtension) > 0 ) pszAddedExtSep = "."; sprintf( pszFilename, "%s%s%s", pszBasename, pszAddedExtSep, pszExtension ); pszFullPath = CPLFormFilename( pszPath, pszFilename, NULL ); nStatRet = VSIStatExL( pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG ); if( nStatRet != 0 ) { for( i = 0; pszFilename[i] != '\0'; i++ ) { if( islower(pszFilename[i]) ) pszFilename[i] = (char) toupper(pszFilename[i]); } pszFullPath = CPLFormFilename( pszPath, pszFilename, NULL ); nStatRet = VSIStatExL( pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG ); } if( nStatRet != 0 ) { for( i = 0; pszFilename[i] != '\0'; i++ ) { if( isupper(pszFilename[i]) ) pszFilename[i] = (char) tolower(pszFilename[i]); } pszFullPath = CPLFormFilename( pszPath, pszFilename, NULL ); nStatRet = VSIStatExL( pszFullPath, &sStatBuf, VSI_STAT_EXISTS_FLAG ); } if( nStatRet != 0 ) pszFullPath = CPLFormFilename( pszPath, pszBasename, pszExtension ); CPLFree( pszFilename ); return pszFullPath; } /************************************************************************/ /* CPLProjectRelativeFilename() */ /************************************************************************/ /** * Find a file relative to a project file. * * Given the path to a "project" directory, and a path to a secondary file * referenced from that project, build a path to the secondary file * that the current application can use. If the secondary path is already * absolute, rather than relative, then it will be returned unaltered. * * Examples: * <pre> * CPLProjectRelativeFilename("abc/def","tmp/abc.gif") == "abc/def/tmp/abc.gif" * CPLProjectRelativeFilename("abc/def","/tmp/abc.gif") == "/tmp/abc.gif" * CPLProjectRelativeFilename("/xy", "abc.gif") == "/xy/abc.gif" * CPLProjectRelativeFilename("/abc/def","../abc.gif") == "/abc/def/../abc.gif" * CPLProjectRelativeFilename("C:\WIN","abc.gif") == "C:\WIN\abc.gif" * </pre> * * @param pszProjectDir the directory relative to which the secondary files * path should be interpreted. * @param pszSecondaryFilename the filename (potentially with path) that * is to be interpreted relative to the project directory. * * @return a composed path to the secondary file. The returned string is * internal and should not be altered, freed, or depending on past the next * CPL call. */ const char *CPLProjectRelativeFilename( const char *pszProjectDir, const char *pszSecondaryFilename ) { char *pszStaticResult = CPLGetStaticResult(); CPLAssert( ! (pszProjectDir >= pszStaticResult && pszProjectDir < pszStaticResult + CPL_PATH_BUF_SIZE) ); CPLAssert( ! (pszSecondaryFilename >= pszStaticResult && pszSecondaryFilename < pszStaticResult + CPL_PATH_BUF_SIZE) ); if( !CPLIsFilenameRelative( pszSecondaryFilename ) ) return pszSecondaryFilename; if( pszProjectDir == NULL || strlen(pszProjectDir) == 0 ) return pszSecondaryFilename; if (CPLStrlcpy( pszStaticResult, pszProjectDir, CPL_PATH_BUF_SIZE ) >= CPL_PATH_BUF_SIZE) goto error; if( pszProjectDir[strlen(pszProjectDir)-1] != '/' && pszProjectDir[strlen(pszProjectDir)-1] != '\\' ) { /* FIXME? would be better to ask the filesystems what they */ /* prefer as directory separator */ const char* pszAddedPathSep; if (strncmp(pszStaticResult, "/vsicurl/", 9) == 0) pszAddedPathSep = "/"; else pszAddedPathSep = SEP_STRING; if (CPLStrlcat( pszStaticResult, pszAddedPathSep, CPL_PATH_BUF_SIZE ) >= CPL_PATH_BUF_SIZE) goto error; } if (CPLStrlcat( pszStaticResult, pszSecondaryFilename, CPL_PATH_BUF_SIZE ) >= CPL_PATH_BUF_SIZE) goto error; return pszStaticResult; error: return CPLStaticBufferTooSmall(pszStaticResult); } /************************************************************************/ /* CPLIsFilenameRelative() */ /************************************************************************/ /** * Is filename relative or absolute? * * The test is filesystem convention agnostic. That is it will test for * Unix style and windows style path conventions regardless of the actual * system in use. * * @param pszFilename the filename with path to test. * * @return TRUE if the filename is relative or FALSE if it is absolute. */ int CPLIsFilenameRelative( const char *pszFilename ) { if( (strlen(pszFilename) > 2 && (strncmp(pszFilename+1,":\\",2) == 0 || strncmp(pszFilename+1,":/",2) == 0)) || pszFilename[0] == '\\' || pszFilename[0] == '/' ) return FALSE; else return TRUE; } /************************************************************************/ /* CPLExtractRelativePath() */ /************************************************************************/ /** * Get relative path from directory to target file. * * Computes a relative path for pszTarget relative to pszBaseDir. * Currently this only works if they share a common base path. The returned * path is normally into the pszTarget string. It should only be considered * valid as long as pszTarget is valid or till the next call to * this function, whichever comes first. * * @param pszBaseDir the name of the directory relative to which the path * should be computed. pszBaseDir may be NULL in which case the original * target is returned without relitivizing. * * @param pszTarget the filename to be changed to be relative to pszBaseDir. * * @param pbGotRelative Pointer to location in which a flag is placed * indicating that the returned path is relative to the basename (TRUE) or * not (FALSE). This pointer may be NULL if flag is not desired. * * @return an adjusted path or the original if it could not be made relative * to the pszBaseFile's path. **/ const char *CPLExtractRelativePath( const char *pszBaseDir, const char *pszTarget, int *pbGotRelative ) { size_t nBasePathLen; /* -------------------------------------------------------------------- */ /* If we don't have a basedir, then we can't relativize the path. */ /* -------------------------------------------------------------------- */ if( pszBaseDir == NULL ) { if( pbGotRelative != NULL ) *pbGotRelative = FALSE; return pszTarget; } nBasePathLen = strlen(pszBaseDir); /* -------------------------------------------------------------------- */ /* One simple case is when the base dir is '.' and the target */ /* filename is relative. */ /* -------------------------------------------------------------------- */ if( (nBasePathLen == 0 || EQUAL(pszBaseDir,".")) && CPLIsFilenameRelative(pszTarget) ) { if( pbGotRelative != NULL ) *pbGotRelative = TRUE; return pszTarget; } /* -------------------------------------------------------------------- */ /* By this point, if we don't have a base path, we can't have a */ /* meaningful common prefix. */ /* -------------------------------------------------------------------- */ if( nBasePathLen == 0 ) { if( pbGotRelative != NULL ) *pbGotRelative = FALSE; return pszTarget; } /* -------------------------------------------------------------------- */ /* If we don't have a common path prefix, then we can't get a */ /* relative path. */ /* -------------------------------------------------------------------- */ if( !EQUALN(pszBaseDir,pszTarget,nBasePathLen) || (pszTarget[nBasePathLen] != '\\' && pszTarget[nBasePathLen] != '/') ) { if( pbGotRelative != NULL ) *pbGotRelative = FALSE; return pszTarget; } /* -------------------------------------------------------------------- */ /* We have a relative path. Strip it off to get a string to */ /* return. */ /* -------------------------------------------------------------------- */ if( pbGotRelative != NULL ) *pbGotRelative = TRUE; return pszTarget + nBasePathLen + 1; } /************************************************************************/ /* CPLCleanTrailingSlash() */ /************************************************************************/ /** * Remove trailing forward/backward slash from the path for unix/windows resp. * * Returns a string containing the portion of the passed path string with * trailing slash removed. If there is no path in the passed filename * an empty string will be returned (not NULL). * * <pre> * CPLCleanTrailingSlash( "abc/def/" ) == "abc/def" * CPLCleanTrailingSlash( "abc/def" ) == "abc/def" * CPLCleanTrailingSlash( "c:\abc\def\" ) == "c:\abc\def" * CPLCleanTrailingSlash( "c:\abc\def" ) == "c:\abc\def" * CPLCleanTrailingSlash( "abc" ) == "abc" * </pre> * * @param pszPath the path to be cleaned up * * @return Path in an internal string which must not be freed. The string * may be destroyed by the next CPL filename handling call. */ const char *CPLCleanTrailingSlash( const char *pszPath ) { char *pszStaticResult = CPLGetStaticResult(); int iPathLength = strlen(pszPath); CPLAssert( ! (pszPath >= pszStaticResult && pszPath < pszStaticResult + CPL_PATH_BUF_SIZE) ); if (iPathLength >= CPL_PATH_BUF_SIZE) return CPLStaticBufferTooSmall(pszStaticResult); CPLStrlcpy( pszStaticResult, pszPath, iPathLength+1 ); if( iPathLength > 0 && (pszStaticResult[iPathLength-1] == '\\' || pszStaticResult[iPathLength-1] == '/')) pszStaticResult[iPathLength-1] = '\0'; return pszStaticResult; } /************************************************************************/ /* CPLCorrespondingPaths() */ /************************************************************************/ /** * Identify corresponding paths. * * Given a prototype old and new filename this function will attempt * to determine corresponding names for a set of other old filenames that * will rename them in a similar manner. This correspondance assumes there * are two possibly kinds of renaming going on. A change of path, and a * change of filename stem. * * If a consistent renaming cannot be established for all the files this * function will return indicating an error. * * The returned file list becomes owned by the caller and should be destroyed * with CSLDestroy(). * * @param pszOldFilename path to old prototype file. * @param pszNewFilename path to new prototype file. * @param papszFileList list of other files associated with pszOldFilename to * rename similarly. * * @return a list of files corresponding to papszFileList but renamed to * correspond to pszNewFilename. */ char **CPLCorrespondingPaths( const char *pszOldFilename, const char *pszNewFilename, char **papszFileList ) { CPLString osOldPath = CPLGetPath( pszOldFilename ); CPLString osNewPath = CPLGetPath( pszNewFilename ); CPLString osOldBasename = CPLGetBasename( pszOldFilename ); CPLString osNewBasename = CPLGetBasename( pszNewFilename ); int i; if( CSLCount(papszFileList) == 0 ) return NULL; /* -------------------------------------------------------------------- */ /* There is a special case for a one item list which exactly */ /* matches the old name, to rename to the new name. */ /* -------------------------------------------------------------------- */ if( CSLCount(papszFileList) == 1 && strcmp(pszOldFilename,papszFileList[0]) == 0 ) { return CSLAddString( NULL, pszNewFilename ); } /* -------------------------------------------------------------------- */ /* If the basename is changing, verify that all source files */ /* have the same starting basename. */ /* -------------------------------------------------------------------- */ if( osOldBasename != osNewBasename ) { for( i=0; papszFileList[i] != NULL; i++ ) { if( osOldBasename == CPLGetBasename( papszFileList[i] ) ) continue; CPLString osFilePath, osFileName; osFilePath = CPLGetPath( papszFileList[i] ); osFileName = CPLGetFilename( papszFileList[i] ); if( !EQUALN(osFileName,osOldBasename,osOldBasename.size()) || !EQUAL(osFilePath,osOldPath) || osFileName[osOldBasename.size()] != '.' ) { CPLError( CE_Failure, CPLE_AppDefined, "Unable to rename fileset due irregular basenames."); return NULL; } } } /* -------------------------------------------------------------------- */ /* If the filename portions differs, ensure they only differ in */ /* basename. */ /* -------------------------------------------------------------------- */ if( osOldBasename != osNewBasename ) { CPLString osOldExtra = CPLGetFilename(pszOldFilename) + strlen(osOldBasename); CPLString osNewExtra = CPLGetFilename(pszNewFilename) + strlen(osNewBasename); if( osOldExtra != osNewExtra ) { CPLError( CE_Failure, CPLE_AppDefined, "Unable to rename fileset due to irregular filename correspondence." ); return NULL; } } /* -------------------------------------------------------------------- */ /* Generate the new filenames. */ /* -------------------------------------------------------------------- */ char **papszNewList = NULL; for( i=0; papszFileList[i] != NULL; i++ ) { CPLString osNewFilename; CPLString osOldFilename = CPLGetFilename( papszFileList[i] ); if( osOldBasename == osNewBasename ) osNewFilename = CPLFormFilename( osNewPath, osOldFilename, NULL ); else osNewFilename = CPLFormFilename( osNewPath, osNewBasename, osOldFilename.c_str()+strlen(osOldBasename)); papszNewList = CSLAddString( papszNewList, osNewFilename ); } return papszNewList; } /************************************************************************/ /* CPLGenerateTempFilename() */ /************************************************************************/ /** * Generate temporary file name. * * Returns a filename that may be used for a temporary file. The location * of the file tries to follow operating system semantics but may be * forced via the CPL_TMPDIR configuration option. * * @param pszStem if non-NULL this will be part of the filename. * * @return a filename which is valid till the next CPL call in this thread. */ const char *CPLGenerateTempFilename( const char *pszStem ) { const char *pszDir = CPLGetConfigOption( "CPL_TMPDIR", NULL ); static volatile int nTempFileCounter = 0; if( pszDir == NULL ) pszDir = CPLGetConfigOption( "TMPDIR", NULL ); if( pszDir == NULL ) pszDir = CPLGetConfigOption( "TEMP", NULL ); if( pszDir == NULL ) pszDir = "."; CPLString osFilename; if( pszStem == NULL ) pszStem = ""; osFilename.Printf( "%s%u_%d", pszStem, (int) CPLGetPID(), nTempFileCounter++ ); return CPLFormFilename( pszDir, osFilename, NULL ); }
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "Props.h" #include <fabric/core/propsConversions.h> #include <folly/dynamic.h> namespace facebook { namespace react { Props::Props(const Props &sourceProps, const RawProps &rawProps): nativeId(convertRawProp(rawProps, "nativeID", sourceProps.nativeId)) {}; } // namespace react } // namespace facebook
// Copyright (c) 2011-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // #include <fs.h> #include <test/util/setup_common.h> #include <util/getuniquepath.h> #include <util/system.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(fs_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(fsbridge_fstream) { fs::path tmpfolder = GetDataDir(); // tmpfile1 should be the same as tmpfile2 fs::path tmpfile1 = tmpfolder / "fs_tests_₿_🏃"; fs::path tmpfile2 = tmpfolder / "fs_tests_₿_🏃"; { fsbridge::ofstream file(tmpfile1); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile2); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } { fsbridge::ifstream file(tmpfile1, std::ios_base::in | std::ios_base::ate); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, ""); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::app); file << "tests"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcointests"); } { fsbridge::ofstream file(tmpfile2, std::ios_base::out | std::ios_base::trunc); file << "bitcoin"; } { fsbridge::ifstream file(tmpfile1); std::string input_buffer; file >> input_buffer; BOOST_CHECK_EQUAL(input_buffer, "bitcoin"); } { fs::path p1 = GetUniquePath(tmpfolder); fs::path p2 = GetUniquePath(tmpfolder); fs::path p3 = GetUniquePath(tmpfolder); // Ensure that the parent path is always the same. BOOST_CHECK_EQUAL(tmpfolder, p1.parent_path()); BOOST_CHECK_EQUAL(tmpfolder, p2.parent_path()); BOOST_CHECK_EQUAL(tmpfolder, p3.parent_path()); // Ensure that generated paths are actually different. BOOST_CHECK(p1 != p2); BOOST_CHECK(p2 != p3); BOOST_CHECK(p1 != p3); } } BOOST_AUTO_TEST_SUITE_END()
#include "perf_precomp.hpp" using namespace std; using namespace cv; using namespace perf; using std::tr1::make_tuple; using std::tr1::get; enum { TYPE_5_8 =FastFeatureDetector::TYPE_5_8, TYPE_7_12 = FastFeatureDetector::TYPE_7_12, TYPE_9_16 = FastFeatureDetector::TYPE_9_16 }; CV_ENUM(FastType, TYPE_5_8, TYPE_7_12, TYPE_9_16) typedef std::tr1::tuple<string, FastType> File_Type_t; typedef perf::TestBaseWithParam<File_Type_t> fast; #define FAST_IMAGES \ "cv/detectors_descriptors_evaluation/images_datasets/leuven/img1.png",\ "stitching/a3.png" PERF_TEST_P(fast, detect, testing::Combine( testing::Values(FAST_IMAGES), FastType::all() )) { string filename = getDataPath(get<0>(GetParam())); int type = get<1>(GetParam()); Mat frame = imread(filename, IMREAD_GRAYSCALE); if (frame.empty()) FAIL() << "Unable to load source image " << filename; declare.in(frame); Ptr<FeatureDetector> fd = FastFeatureDetector::create(20, true, type); ASSERT_FALSE( fd.empty() ); vector<KeyPoint> points; TEST_CYCLE() fd->detect(frame, points); SANITY_CHECK_KEYPOINTS(points); }
#include <stan/math/rev/arr.hpp> #include <gtest/gtest.h> #include <vector> TEST(AgradRevErrorHandlingScalar, CheckConsistentSizeVarCheckVectorized) { using stan::math::check_consistent_sizes; using stan::math::var; using std::vector; int N = 5; const char* function = "check_consistent_size"; vector<var> a; vector<var> b; for (int i = 0; i < N; ++i) { b.push_back(var(i + 1)); a.push_back(var(i)); } size_t stack_size = stan::math::ChainableStack::var_stack_.size(); EXPECT_EQ(10U, stack_size); EXPECT_NO_THROW(check_consistent_sizes(function, "a", a, "b", b)); size_t stack_size_after_call = stan::math::ChainableStack::var_stack_.size(); EXPECT_EQ(10U, stack_size_after_call); stan::math::recover_memory(); }
// ---------------------------------------------------------- /*! \class AObjectA \title \brief Template file classes/cpp/file.cpp \list \li @notice Template file classes/file.h \li @copyright Arboreus (http://arboreus.systems) \li @author Alexandr Kirilov (http://alexandr.kirilov.me) \li @created 13/10/2020 at 06:31:20 \endlist */ // ---------------------------------------------------------- // Class header #include "aobjecta.h" // ----------- /*! \fn Doc. */ AObjectA::AObjectA(void) { ALOG << "AObjectA created" << endl; } // ----------- /*! \fn Doc. */ AObjectA::~AObjectA(void) { ALOG << "AObjectA deleted" << endl; } // ----------- /*! \fn Doc. */ string AObjectA::mTestString(void) { return pTestString; }
#include "internal.hpp" auto string_from(const Token_type &token_type) -> std::string { switch (token_type) { case Token_type::nil: return "nil"; case Token_type::number: return "number"; case Token_type::string: return "string"; case Token_type::boolean: return "boolean"; case Token_type::identifier: return "identifier"; case Token_type::left_parenthesis: return "left_parenthesis"; case Token_type::right_parenthesis: return "right_parenthesis"; } return "unknown"; } struct Token::Impl final { std::string token_value = ""; Token_type token_type = Token_type::nil; char padding[4] = {0}; }; Token::Token() : impl(std::make_shared<Impl>()) {} Token::Token(const Token_type token_type, std::string token_value) : Token() { impl->token_value = std::move(token_value); impl->token_type = token_type; } const Token_type &Token::type() const noexcept { return impl->token_type; } const std::string &Token::value() const noexcept { return impl->token_value; } auto consume_from(Token_list &token_list) -> Token { auto token = token_list.front(); token_list.erase(std::begin(token_list)); return token; } auto string_from(const Token &token) noexcept -> std::string { return std::string("{") + string_from(token.type()) + "," + token.value() + "}"; } auto variant_from(const Token &token) -> Variant { switch (token.type()) { case Token_type::nil: return Variant(); case Token_type::number: return Variant(std::stod(token.value())); case Token_type::string: return Variant(std::string(std::cbegin(token.value()) + 1, std::cend(token.value()) - 1)); case Token_type::boolean: return Variant(token.value() == "#t" ? true : false); case Token_type::identifier: case Token_type::left_parenthesis: case Token_type::right_parenthesis: break; } throw std::runtime_error("Can't convert token to variant."); } auto operator==(const Token &left, const Token &right) -> bool { return left.type() == right.type() && left.value() == right.value(); } auto operator!=(const Token &left, const Token &right) -> bool { return !(left == right); }
/** * \file DlgWzskFilDownload.cpp * job handler for job DlgWzskFilDownload (implementation) * \copyright (C) 2016-2020 MPSI Technologies GmbH * \author Emily Johnson (auto-generation) * \date created: 5 Dec 2020 */ // IP header --- ABOVE #ifdef WZSKCMBD #include <Wzskcmbd.h> #else #include <Wzskd.h> #endif #include "DlgWzskFilDownload.h" #include "DlgWzskFilDownload_blks.cpp" using namespace std; using namespace Sbecore; using namespace Xmlio; // IP ns.cust --- INSERT /****************************************************************************** class DlgWzskFilDownload ******************************************************************************/ DlgWzskFilDownload::DlgWzskFilDownload( XchgWzsk* xchg , DbsWzsk* dbswzsk , const ubigint jrefSup , const uint ixWzskVLocale ) : JobWzsk(xchg, VecWzskVJob::DLGWZSKFILDOWNLOAD, jrefSup, ixWzskVLocale) { jref = xchg->addJob(dbswzsk, this, jrefSup); // IP constructor.cust1 --- INSERT // IP constructor.cust2 --- INSERT set<uint> moditems; refresh(dbswzsk, moditems); // IP constructor.cust3 --- INSERT // IP constructor.spec3 --- INSERT }; DlgWzskFilDownload::~DlgWzskFilDownload() { // IP destructor.spec --- INSERT // IP destructor.cust --- INSERT xchg->removeJobByJref(jref); }; // IP cust --- INSERT DpchEngWzsk* DlgWzskFilDownload::getNewDpchEng( set<uint> items ) { DpchEngWzsk* dpcheng = NULL; if (items.empty()) { dpcheng = new DpchEngWzskConfirm(true, jref, ""); } else { insert(items, DpchEngData::JREF); dpcheng = new DpchEngData(jref, &continf, items); }; return dpcheng; }; void DlgWzskFilDownload::refresh( DbsWzsk* dbswzsk , set<uint>& moditems , const bool unmute ) { if (muteRefresh && !unmute) return; muteRefresh = true; ContInf oldContinf(continf); // IP refresh --- RBEGIN // continf continf.Dld = StubWzsk::getStubFilStd(dbswzsk, xchg->getRefPreset(VecWzskVPreset::PREWZSKREFFIL, jref)); // IP refresh --- REND if (continf.diff(&oldContinf).size() != 0) insert(moditems, DpchEngData::CONTINF); muteRefresh = false; }; void DlgWzskFilDownload::handleRequest( DbsWzsk* dbswzsk , ReqWzsk* req ) { if (req->ixVBasetype == ReqWzsk::VecVBasetype::CMD) { reqCmd = req; if (req->cmd == "cmdset") { } else { cout << "\tinvalid command!" << endl; }; if (!req->retain) reqCmd = NULL; } else if (req->ixVBasetype == ReqWzsk::VecVBasetype::DPCHAPP) { if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPWZSKINIT) { handleDpchAppWzskInit(dbswzsk, (DpchAppWzskInit*) (req->dpchapp), &(req->dpcheng)); } else if (req->dpchapp->ixWzskVDpch == VecWzskVDpch::DPCHAPPDLGWZSKFILDOWNLOADDO) { DpchAppDo* dpchappdo = (DpchAppDo*) (req->dpchapp); if (dpchappdo->ixVDo != 0) { if (dpchappdo->ixVDo == VecVDo::BUTDNECLICK) { handleDpchAppDoButDneClick(dbswzsk, &(req->dpcheng)); }; }; }; } else if (req->ixVBasetype == ReqWzsk::VecVBasetype::DOWNLOAD) { req->filename = handleDownload(dbswzsk); }; }; void DlgWzskFilDownload::handleDpchAppWzskInit( DbsWzsk* dbswzsk , DpchAppWzskInit* dpchappwzskinit , DpchEngWzsk** dpcheng ) { *dpcheng = getNewDpchEng({DpchEngData::ALL}); }; void DlgWzskFilDownload::handleDpchAppDoButDneClick( DbsWzsk* dbswzsk , DpchEngWzsk** dpcheng ) { // IP handleDpchAppDoButDneClick --- IBEGIN *dpcheng = new DpchEngWzskConfirm(true, jref, ""); xchg->triggerCall(dbswzsk, VecWzskVCall::CALLWZSKDLGCLOSE, jref); // IP handleDpchAppDoButDneClick --- IEND }; string DlgWzskFilDownload::handleDownload( DbsWzsk* dbswzsk ) { // IP handleDownload --- RBEGIN string retval; retval = Acv::getfile(dbswzsk, xchg->getRefPreset(VecWzskVPreset::PREWZSKREFFIL, jref)); if (retval != "") retval = xchg->acvpath + "/" + retval; return retval; // IP handleDownload --- REND };
/* This test is part of pocl. * Author: Kalle Raiskila, 2014 * * Test the OpenCL-C 'shuffle' command by looping * over all permutations of data and mask vector * lengths. Only one data type at a time is tested, * the type to test is passed as command line argument * (this allows for more interactive testsuite, and * non-supported types (e.g. half, double) are easier * to filter out). * The data to be shuffled is vectors where the elemnet * data equals the element index (i.e. [0,1,2,3]) but * the shuffle pattern masks are generated with rand(). */ #include "poclu.h" #include <cstdio> #include <cstring> #include <CL/cl.h> #include <iostream> #include <cmath> #include <cstdlib> cl_context ctx; cl_device_id did; cl_platform_id pid; cl_command_queue queue; #define ERRCHECK() if (check_cl_error(errcode, __LINE__, __FUNCTION__)) abort(); static const unsigned vecelts[] = {2,4,8,16}; static const int stimuli[] = {4, 2, 69, 4, 5, 0, 45, 16, 4, 6, 1, 18, 28, 14, 22, 16, 8, 2, 0, 31, 42, 11, 62, 88, 99, 23, 13}; template <typename D, typename M> class TestShuffle { cl_mem mem_in1, mem_in2, mem_out, mem_mask1, mem_mask2; cl_program prog; D in1 [16] __attribute__ ((aligned (128))); D in2 [16] __attribute__ ((aligned (128))); D out [16] __attribute__ ((aligned (128))); M mask1 [16] __attribute__ ((aligned (128))); M mask2 [16] __attribute__ ((aligned (128))); const char* ocl_type; unsigned size; cl_int errcode; private: /* Prints into std::string all the OpenCL kernel sources for each n,m combo */ void testcase_src(std::string & src) { char buf[1024]; int rv; unsigned n, m; const char* mask_type; switch(sizeof(M)) { case 1: mask_type = "uchar"; break; case 2: mask_type = "ushort"; break; case 4: mask_type = "uint"; break; case 8: mask_type = "ulong"; break; default: mask_type = "UNKNOWN_MASK"; } for(unsigned n_loop=0; n_loop<4; n_loop++) { for(unsigned m_loop=0; m_loop<4; m_loop++) { n = vecelts[n_loop]; m = vecelts[m_loop]; rv = 0; buf[0] = 0; rv=sprintf(buf, "__kernel void test_shuffle_%d_%d(" "__global const %s%d *in, __global const %s%d *mask, __global %s%d *out) {\n" "*out = shuffle( *in, *mask);\n}\n", m, n, ocl_type, m, mask_type, n, ocl_type, n); rv+=sprintf(buf+rv, "__kernel void test_shuffle2_%d_%d(" "__global const %s%d *in1, __global const %s%d *in2, __global const %s%d *mask, __global %s%d *out) {\n" "*out = shuffle2( *in1, *in2, *mask);\n}\n", m, n, ocl_type, m, ocl_type, m, mask_type, n, ocl_type, n); src.append(buf); } } } #define nsize n #define msize m // assume out is filled with 'shuffle(in, mask)' // return true if ok bool output_matches_1(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned mm = mask1[i] % msize; error |= (out[i] != in1[mm]); } return !error; } // assume out is filled with 'shuffle2(in1, in2, mask)' // return true if ok bool output_matches_2(unsigned n, unsigned m) { bool error=false; for(unsigned i=0; i<n; i++) { unsigned msk = mask2[i] % (2*msize); D correct = (msk < msize) ? in1[msk] : in2[msk-msize]; if (out[i] != correct) { error |= true; printf("element %d should be %d (mask %d), got %d\n", i, (int)correct, (int)mask2[i], (int)out[i]); } } return !error; } // helpers: prints a vector as [0, 1, 2] // cast to int, so vectors of 'char' come out correctly void print_in1(unsigned n, unsigned m) { std::cout << "["<<(int)in1[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in1[i]; std::cout << "]"; } void print_in2(unsigned n, unsigned m) { std::cout << "["<<(int)in2[0]; for(unsigned i=1; i<m; i++) std::cout << ", " <<(int)in2[i]; std::cout << "]"; } void print_mask1(unsigned n, unsigned m) { std::cout << "["<<(int)mask1[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask1[i]; std::cout << "]"; } void print_mask2(unsigned n, unsigned m) { std::cout << "["<<(int)mask2[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)mask2[i]; std::cout << "]"; } void print_out(unsigned n, unsigned m) { std::cout << "["<<(int)out[0]; for(unsigned i=1; i<n; i++) std::cout << ", " <<(int)out[i]; std::cout << "]"; } /* Run one shuffle test, return true if successful*/ bool run_single_test(unsigned n, unsigned m){ bool rv=true; cl_kernel krn, krn2; char kern_name[128], kern_name2[128]; snprintf(kern_name, 128, "test_shuffle_%d_%d", m, n); krn = clCreateKernel(prog, kern_name, &errcode); ERRCHECK() errcode = clSetKernelArg( krn, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn, 1, sizeof(cl_mem), &mem_mask1 ); ERRCHECK() errcode = clSetKernelArg( krn, 2, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_1(n, m)) { std::cout << "Error in shuffle " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle( "; print_in1(n, m); std::cout << ", "; print_mask1(n, m); std::cout << ");" << std::endl; rv=false; } clReleaseKernel(krn); // Now test shuffle2() snprintf(kern_name2, 128, "test_shuffle2_%d_%d", m, n); krn2 = clCreateKernel(prog, kern_name2, &errcode); ERRCHECK() errcode = clSetKernelArg( krn2, 0, sizeof(cl_mem), &mem_in1 ); ERRCHECK() errcode = clSetKernelArg( krn2, 1, sizeof(cl_mem), &mem_in2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 2, sizeof(cl_mem), &mem_mask2 ); ERRCHECK() errcode = clSetKernelArg( krn2, 3, sizeof(cl_mem), &mem_out ); ERRCHECK() errcode = clEnqueueTask( queue, krn2, 0, NULL, NULL ); ERRCHECK() errcode = clEnqueueReadBuffer( queue, mem_out, CL_TRUE, 0, size, out, 0, NULL, NULL ); ERRCHECK() errcode = clFinish(queue); ERRCHECK() if(!output_matches_2(n, m)) { std::cout << "Error in shuffle2 " << ocl_type << " " << m; std::cout << " => " << ocl_type << " " << n << " :"; print_out(n, m); std::cout << " = shuffle2( "; print_in1(n, m); std::cout << ", "; print_in2(n, m); std::cout << ", "; print_mask2(n, m); std::cout << ");" << std::endl; rv=false; } clReleaseKernel(krn2); return rv; } public: TestShuffle(const char* type) { ocl_type = type; size = sizeof(D) * 16; for(unsigned i=0; i<16; i++) { mask1[i] = (M)stimuli[i]; mask2[i] = (M)stimuli[i]; } for (unsigned n_loop = 0; n_loop < 4; n_loop++) { for (unsigned m_loop = 0; m_loop < 4; m_loop++) { unsigned m = vecelts[m_loop]; for (unsigned i = 0; i < m; i++) { in2[i] = (D)(i + m); in1[i] = (D)i; } } } } unsigned run() { // Fixed pseudorandom stimuli to make the test deterministic. // Random stimuli leads to randomly appearing/disappearing // problems which are irritating and hard to reproduce. Values which reduce // to element 3 might produce an undefined value in case of 3 element inputs so // let's not use them in the stimulus. mem_in1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in1, &errcode); ERRCHECK() mem_in2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, in2, &errcode); ERRCHECK() mem_mask1 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask1, &errcode); ERRCHECK() mem_mask2 = clCreateBuffer(ctx, CL_MEM_READ_ONLY | CL_MEM_USE_HOST_PTR, size, mask2, &errcode); ERRCHECK() mem_out = clCreateBuffer(ctx, CL_MEM_WRITE_ONLY, size, NULL, &errcode); ERRCHECK() std::string source; testcase_src(source); const char *c_src = source.c_str(); size_t srclen = source.size(); prog = clCreateProgramWithSource(ctx, 1, &c_src, &srclen, &errcode); ERRCHECK() errcode = clBuildProgram(prog, 0, NULL, NULL, NULL, NULL); ERRCHECK() unsigned errors = 0; for (unsigned n_loop = 0; n_loop < 4; n_loop++) { for (unsigned m_loop = 0; m_loop < 4; m_loop++) { if (!run_single_test(vecelts[n_loop], vecelts[m_loop])) errors++; } } clReleaseMemObject(mem_in1); clReleaseMemObject(mem_in2); clReleaseMemObject(mem_mask1); clReleaseMemObject(mem_mask2); clReleaseMemObject(mem_out); clReleaseProgram(prog); return errors; } }; int main( int argc, char *argv[]) { unsigned num_errors = 0; if( argc != 2 ) { std::cout << "give element type"<<std::endl; exit(-1); } poclu_get_any_device( &ctx, &did, &queue); #if (__GNUC__ > 5) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wignored-attributes" #endif /* Loop over input (m) and output (n) vector lengths. * The big if-else is needed to pass the string * representation to runtest. * This cannot be fully templated, as there is a * 'typedef short int half', which would cause the * templating mechanism to create the test for shorts instead * of halfs. */ if( strcmp("char", argv[1]) == 0 ) { TestShuffle<cl_char, cl_uchar> t("char"); num_errors = t.run(); } else if( strcmp("uchar", argv[1]) == 0 ) { TestShuffle<cl_uchar, cl_uchar> t("uchar"); num_errors = t.run(); } else if( strcmp("short", argv[1]) == 0 ) { TestShuffle<cl_short, cl_ushort> t("short"); num_errors = t.run(); } else if( strcmp("ushort", argv[1]) == 0 ) { TestShuffle<cl_ushort, cl_ushort> t("ushort"); num_errors = t.run(); } else if( strcmp("int", argv[1]) == 0 ) { TestShuffle<cl_int, cl_uint> t("int"); num_errors = t.run(); } else if( strcmp("uint", argv[1]) == 0 ) { TestShuffle<cl_uint, cl_uint> t("uint"); num_errors = t.run(); } else if( strcmp("long", argv[1]) == 0 ) { TestShuffle<cl_long, cl_ulong> t("long"); num_errors = t.run(); } else if( strcmp("ulong", argv[1]) == 0 ) { TestShuffle<cl_ulong, cl_ulong> t("ulong"); num_errors = t.run(); } else if( strcmp("half", argv[1]) == 0 ) { TestShuffle<cl_half, cl_ushort> t("half"); num_errors = t.run(); } else if( strcmp("float", argv[1]) == 0 ) { TestShuffle<cl_float, cl_uint> t("float"); num_errors = t.run(); } else if( strcmp("double", argv[1]) == 0 ) { TestShuffle<cl_double, cl_ulong> t("double"); num_errors = t.run(); } else { std::cout << "Error: unknown type " << argv[1] << ": use OCL-C types"<<std::endl; return -1; } #if (__GNUC__ > 5) #pragma GCC diagnostic pop #endif clReleaseCommandQueue(queue); clUnloadCompiler(); clReleaseContext(ctx); if( num_errors == 0) std::cout << "OK" << std::endl; return num_errors; }
#include <print.hpp> #include <gtest/gtest.h> TEST(Print, InFileStream) { std::string filepath = "file.txt"; std::string text = "hello"; std::ofstream out{filepath}; print(text, out); out.close(); std::string result; std::ifstream in{filepath}; in >> result; EXPECT_EQ(result, text); }
/* * Copyright (c) 2017, Graphics Lab, Georgia Tech Research Corporation * Copyright (c) 2017, Personal Robotics Lab, Carnegie Mellon University * All rights reserved. * * This file is provided under the following "BSD-style" License: * 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. * 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. */ #ifndef DART_COLLISION_ODE_DETAIL_ODEMESH_HPP_ #define DART_COLLISION_ODE_DETAIL_ODEMESH_HPP_ #include <ode/ode.h> #include <assimp/scene.h> #include "dart/collision/ode/detail/OdeGeom.hpp" namespace dart { namespace collision { namespace detail { class OdeMesh : public OdeGeom { public: /// Constructor OdeMesh( const OdeCollisionObject* parent, const aiScene* scene, const Eigen::Vector3d& scale = Eigen::Vector3d::Ones()); /// Destructor virtual ~OdeMesh(); // Documentation inherited void updateEngineData() override; private: void fillArrays( const aiScene* scene, const Eigen::Vector3d& scale = Eigen::Vector3d::Ones()); private: /// Array of vertex values. std::vector<double> mVertices; /// Array of normals values. std::vector<double> mNormals; /// Array of index values. std::vector<int> mIndices; /// ODE trimesh data. dTriMeshDataID mOdeTriMeshDataId; }; } // namespace detail } // namespace collision } // namespace dart #endif // DART_COLLISION_ODE_DETAIL_ODEMESH_HPP_
/* * Copyright (c) 2016, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements IPv6 addresses. */ #include "ip6_address.hpp" #include <stdio.h> #include "common/code_utils.hpp" #include "common/encoding.hpp" #include "common/instance.hpp" #include "common/numeric_limits.hpp" #include "common/random.hpp" #include "net/ip4_address.hpp" #include "net/netif.hpp" using ot::Encoding::BigEndian::HostSwap32; namespace ot { namespace Ip6 { //--------------------------------------------------------------------------------------------------------------------- // NetworkPrefix methods Error NetworkPrefix::GenerateRandomUla(void) { m8[0] = 0xfd; return Random::Crypto::FillBuffer(&m8[1], kSize - 1); } //--------------------------------------------------------------------------------------------------------------------- // Prefix methods void Prefix::Set(const uint8_t *aPrefix, uint8_t aLength) { memcpy(mPrefix.mFields.m8, aPrefix, SizeForLength(aLength)); mLength = aLength; } bool Prefix::IsEqual(const uint8_t *aPrefixBytes, uint8_t aPrefixLength) const { return (mLength == aPrefixLength) && (MatchLength(GetBytes(), aPrefixBytes, GetBytesSize()) >= mLength); } bool Prefix::operator<(const Prefix &aOther) const { bool isSmaller; uint8_t matchedLength; VerifyOrExit(GetLength() == aOther.GetLength(), isSmaller = GetLength() < aOther.GetLength()); matchedLength = MatchLength(GetBytes(), aOther.GetBytes(), GetBytesSize()); VerifyOrExit(matchedLength < GetLength(), isSmaller = false); isSmaller = GetBytes()[matchedLength / CHAR_BIT] < aOther.GetBytes()[matchedLength / CHAR_BIT]; exit: return isSmaller; } uint8_t Prefix::MatchLength(const uint8_t *aPrefixA, const uint8_t *aPrefixB, uint8_t aMaxSize) { uint8_t matchedLength = 0; OT_ASSERT(aMaxSize <= Address::kSize); for (uint8_t i = 0; i < aMaxSize; i++) { uint8_t diff = aPrefixA[i] ^ aPrefixB[i]; if (diff == 0) { matchedLength += CHAR_BIT; } else { while ((diff & 0x80) == 0) { matchedLength++; diff <<= 1; } break; } } return matchedLength; } Prefix::InfoString Prefix::ToString(void) const { InfoString string; uint8_t sizeInUint16 = (GetBytesSize() + sizeof(uint16_t) - 1) / sizeof(uint16_t); for (uint16_t i = 0; i < sizeInUint16; i++) { IgnoreError(string.Append("%s%x", (i > 0) ? ":" : "", HostSwap16(mPrefix.mFields.m16[i]))); } if (GetBytesSize() < Address::kSize - 1) { IgnoreError(string.Append("::")); } IgnoreError(string.Append("/%d", mLength)); return string; } //--------------------------------------------------------------------------------------------------------------------- // InterfaceIdentifier methods bool InterfaceIdentifier::IsUnspecified(void) const { return (mFields.m32[0] == 0) && (mFields.m32[1] == 0); } bool InterfaceIdentifier::IsReserved(void) const { return IsSubnetRouterAnycast() || IsReservedSubnetAnycast() || IsAnycastLocator(); } bool InterfaceIdentifier::IsSubnetRouterAnycast(void) const { return (mFields.m32[0] == 0) && (mFields.m32[1] == 0); } bool InterfaceIdentifier::IsReservedSubnetAnycast(void) const { // Format of IID in a Reserved Subnet Anycast Address (RFC 2526) // // | 57 bits | 7 bits | // +------------------+------------+ // | 1111110111...111 | anycast ID | // +------------------+------------+ return (mFields.m32[0] == HostSwap32(0xfdffffff) && mFields.m16[2] == HostSwap16(0xffff) && mFields.m8[6] == 0xff && mFields.m8[7] >= 0x80); } void InterfaceIdentifier::GenerateRandom(void) { Error error; OT_UNUSED_VARIABLE(error); error = Random::Crypto::FillBuffer(mFields.m8, kSize); OT_ASSERT(error == kErrorNone); } void InterfaceIdentifier::SetBytes(const uint8_t *aBuffer) { memcpy(mFields.m8, aBuffer, kSize); } void InterfaceIdentifier::SetFromExtAddress(const Mac::ExtAddress &aExtAddress) { Mac::ExtAddress addr; addr = aExtAddress; addr.ToggleLocal(); addr.CopyTo(mFields.m8); } void InterfaceIdentifier::ConvertToExtAddress(Mac::ExtAddress &aExtAddress) const { aExtAddress.Set(mFields.m8); aExtAddress.ToggleLocal(); } void InterfaceIdentifier::ConvertToMacAddress(Mac::Address &aMacAddress) const { aMacAddress.SetExtended(mFields.m8); aMacAddress.GetExtended().ToggleLocal(); } void InterfaceIdentifier::SetToLocator(uint16_t aLocator) { // Locator IID pattern `0000:00ff:fe00:xxxx` mFields.m32[0] = HostSwap32(0x000000ff); mFields.m16[2] = HostSwap16(0xfe00); mFields.m16[3] = HostSwap16(aLocator); } bool InterfaceIdentifier::IsLocator(void) const { // Locator IID pattern 0000:00ff:fe00:xxxx return (mFields.m32[0] == HostSwap32(0x000000ff) && mFields.m16[2] == HostSwap16(0xfe00)); } bool InterfaceIdentifier::IsRoutingLocator(void) const { return (IsLocator() && (mFields.m8[6] < kAloc16Mask) && ((mFields.m8[6] & kRloc16ReservedBitMask) == 0)); } bool InterfaceIdentifier::IsAnycastLocator(void) const { // Anycast locator range 0xfc00- 0xfcff (`kAloc16Mask` is 0xfc) return (IsLocator() && (mFields.m8[6] == kAloc16Mask)); } bool InterfaceIdentifier::IsAnycastServiceLocator(void) const { uint16_t locator = GetLocator(); return (IsLocator() && (locator >= Mle::kAloc16ServiceStart) && (locator <= Mle::kAloc16ServiceEnd)); } InterfaceIdentifier::InfoString InterfaceIdentifier::ToString(void) const { InfoString string; IgnoreError(string.AppendHexBytes(mFields.m8, kSize)); return string; } //--------------------------------------------------------------------------------------------------------------------- // Address methods bool Address::IsUnspecified(void) const { return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == 0); } bool Address::IsLoopback(void) const { return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(1)); } bool Address::IsLinkLocal(void) const { return (mFields.m16[0] & HostSwap16(0xffc0)) == HostSwap16(0xfe80); } void Address::SetToLinkLocalAddress(const Mac::ExtAddress &aExtAddress) { mFields.m32[0] = HostSwap32(0xfe800000); mFields.m32[1] = 0; GetIid().SetFromExtAddress(aExtAddress); } void Address::SetToLinkLocalAddress(const InterfaceIdentifier &aIid) { mFields.m32[0] = HostSwap32(0xfe800000); mFields.m32[1] = 0; SetIid(aIid); } bool Address::IsLinkLocalMulticast(void) const { return IsMulticast() && (GetScope() == kLinkLocalScope); } bool Address::IsLinkLocalAllNodesMulticast(void) const { return (*this == GetLinkLocalAllNodesMulticast()); } void Address::SetToLinkLocalAllNodesMulticast(void) { *this = GetLinkLocalAllNodesMulticast(); } bool Address::IsLinkLocalAllRoutersMulticast(void) const { return (*this == GetLinkLocalAllRoutersMulticast()); } void Address::SetToLinkLocalAllRoutersMulticast(void) { *this = GetLinkLocalAllRoutersMulticast(); } bool Address::IsRealmLocalMulticast(void) const { return IsMulticast() && (GetScope() == kRealmLocalScope); } bool Address::IsMulticastLargerThanRealmLocal(void) const { return IsMulticast() && (GetScope() > kRealmLocalScope); } bool Address::IsRealmLocalAllNodesMulticast(void) const { return (*this == GetRealmLocalAllNodesMulticast()); } void Address::SetToRealmLocalAllNodesMulticast(void) { *this = GetRealmLocalAllNodesMulticast(); } bool Address::IsRealmLocalAllRoutersMulticast(void) const { return (*this == GetRealmLocalAllRoutersMulticast()); } void Address::SetToRealmLocalAllRoutersMulticast(void) { *this = GetRealmLocalAllRoutersMulticast(); } bool Address::IsRealmLocalAllMplForwarders(void) const { return (*this == GetRealmLocalAllMplForwarders()); } void Address::SetToRealmLocalAllMplForwarders(void) { *this = GetRealmLocalAllMplForwarders(); } bool Address::MatchesPrefix(const Prefix &aPrefix) const { return Prefix::MatchLength(mFields.m8, aPrefix.GetBytes(), aPrefix.GetBytesSize()) >= aPrefix.GetLength(); } bool Address::MatchesPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) const { return Prefix::MatchLength(mFields.m8, aPrefix, Prefix::SizeForLength(aPrefixLength)) >= aPrefixLength; } void Address::SetPrefix(const NetworkPrefix &aNetworkPrefix) { mFields.mComponents.mNetworkPrefix = aNetworkPrefix; } void Address::SetPrefix(const Prefix &aPrefix) { SetPrefix(0, aPrefix.GetBytes(), aPrefix.GetLength()); } void Address::SetPrefix(uint8_t aOffset, const uint8_t *aPrefix, uint8_t aPrefixLength) { uint8_t bytes = aPrefixLength / CHAR_BIT; uint8_t extraBits = aPrefixLength % CHAR_BIT; OT_ASSERT(aPrefixLength <= (sizeof(Address) - aOffset) * CHAR_BIT); memcpy(mFields.m8 + aOffset, aPrefix, bytes); if (extraBits > 0) { uint8_t index = aOffset + bytes; uint8_t mask = ((0x80 >> (extraBits - 1)) - 1); // `mask` has its higher (msb) `extraBits` bits as `0` and the remaining as `1`. // Example with `extraBits` = 3: // ((0x80 >> 2) - 1) = (0b0010_0000 - 1) = 0b0001_1111 mFields.m8[index] &= mask; mFields.m8[index] |= (aPrefix[index] & ~mask); } } void Address::SetMulticastNetworkPrefix(const uint8_t *aPrefix, uint8_t aPrefixLength) { SetPrefix(kMulticastNetworkPrefixOffset, aPrefix, aPrefixLength); mFields.m8[kMulticastNetworkPrefixLengthOffset] = aPrefixLength; } void Address::SetToLocator(const NetworkPrefix &aNetworkPrefix, uint16_t aLocator) { SetPrefix(aNetworkPrefix); GetIid().SetToLocator(aLocator); } uint8_t Address::GetScope(void) const { uint8_t rval; if (IsMulticast()) { rval = mFields.m8[1] & 0xf; } else if (IsLinkLocal()) { rval = kLinkLocalScope; } else if (IsLoopback()) { rval = kNodeLocalScope; } else { rval = kGlobalScope; } return rval; } uint8_t Address::PrefixMatch(const Address &aOther) const { return Prefix::MatchLength(mFields.m8, aOther.mFields.m8, sizeof(Address)); } bool Address::MatchesFilter(TypeFilter aFilter) const { bool matches = true; switch (aFilter) { case kTypeAny: break; case kTypeUnicast: matches = !IsUnspecified() && !IsMulticast(); break; case kTypeMulticast: matches = IsMulticast(); break; case kTypeMulticastLargerThanRealmLocal: matches = IsMulticastLargerThanRealmLocal(); break; } return matches; } void Address::SetFromTranslatedIp4Address(const Prefix &aPrefix, const Ip4::Address &aIp4Address) { // The prefix length must be 32, 40, 48, 56, 64, 96. IPv4 bytes are added // after the prefix, skipping over the bits 64 to 71 (byte at `kSkipIndex`) // which must be set to zero. The suffix is set to zero (per RFC 6502). // // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |PL| 0-------------32--40--48--56--64--72--80--88--96--104---------| // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |32| prefix |v4(32) | u | suffix | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |40| prefix |v4(24) | u |(8)| suffix | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |48| prefix |v4(16) | u | (16) | suffix | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |56| prefix |(8)| u | v4(24) | suffix | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |64| prefix | u | v4(32) | suffix | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ // |96| prefix | v4(32) | // +--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ enum : uint8_t { kSkipIndex = 8, }; uint8_t prefixLen = aPrefix.GetLength(); uint8_t ip6Index; OT_ASSERT((prefixLen == 32) || (prefixLen == 40) || (prefixLen == 48) || (prefixLen == 56) || (prefixLen == 64) || (prefixLen == 96)); Clear(); SetPrefix(aPrefix); ip6Index = prefixLen / CHAR_BIT; for (uint8_t i = 0; i < Ip4::Address::kSize; i++) { if (ip6Index == kSkipIndex) { ip6Index++; } mFields.m8[ip6Index++] = aIp4Address.GetBytes()[i]; } } Error Address::FromString(const char *aString) { enum : uint8_t { kInvalidIndex = 0xff, }; enum : char { kColonChar = ':', kDotChar = '.', kNullChar = '\0', }; Error error = kErrorParse; uint8_t index = 0; uint8_t endIndex = kSize / sizeof(uint16_t); uint8_t colonIndex = kInvalidIndex; bool hasIp4 = false; // Check if the string starts with "::". if (*aString == kColonChar) { aString++; VerifyOrExit(*aString == kColonChar); aString++; colonIndex = index; } while (*aString != kNullChar) { const char *start = aString; uint32_t value = 0; // Parse hex number while (true) { char c = *aString; uint8_t digit; if (('A' <= c) && (c <= 'F')) { digit = static_cast<uint8_t>(c - 'A' + 10); } else if (('a' <= c) && (c <= 'f')) { digit = static_cast<uint8_t>(c - 'a' + 10); } else if (('0' <= c) && (c <= '9')) { digit = static_cast<uint8_t>(c - '0'); } else { break; } aString++; value = (value << 4) + digit; VerifyOrExit(value <= NumericLimits<uint16_t>::Max()); } VerifyOrExit(aString != start); if (*aString == kDotChar) { // IPv6 address contains an embedded IPv4 address. aString = start; hasIp4 = true; endIndex -= Ip4::Address::kSize / sizeof(uint16_t); VerifyOrExit(index <= endIndex); break; } VerifyOrExit((*aString == kColonChar) || (*aString == kNullChar)); VerifyOrExit(index < endIndex); mFields.m16[index++] = HostSwap16(static_cast<uint16_t>(value)); if (*aString == kColonChar) { aString++; if (*aString == kColonChar) { VerifyOrExit(colonIndex == kInvalidIndex); colonIndex = index; aString++; } } } if (index < endIndex) { uint8_t wordsToCopy; VerifyOrExit(colonIndex != kInvalidIndex); wordsToCopy = index - colonIndex; memmove(&mFields.m16[endIndex - wordsToCopy], &mFields.m16[colonIndex], wordsToCopy * sizeof(uint16_t)); memset(&mFields.m16[colonIndex], 0, (endIndex - index) * sizeof(uint16_t)); } if (hasIp4) { Ip4::Address ip4Addr; SuccessOrExit(error = ip4Addr.FromString(aString)); memcpy(OT_ARRAY_END(mFields.m8) - Ip4::Address::kSize, ip4Addr.GetBytes(), Ip4::Address::kSize); } error = kErrorNone; exit: return error; } Address::InfoString Address::ToString(void) const { return InfoString("%x:%x:%x:%x:%x:%x:%x:%x", HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]), HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), HostSwap16(mFields.m16[4]), HostSwap16(mFields.m16[5]), HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7])); } const Address &Address::GetLinkLocalAllNodesMulticast(void) { return static_cast<const Address &>(Netif::kLinkLocalAllNodesMulticastAddress.mAddress); } const Address &Address::GetLinkLocalAllRoutersMulticast(void) { return static_cast<const Address &>(Netif::kLinkLocalAllRoutersMulticastAddress.mAddress); } const Address &Address::GetRealmLocalAllNodesMulticast(void) { return static_cast<const Address &>(Netif::kRealmLocalAllNodesMulticastAddress.mAddress); } const Address &Address::GetRealmLocalAllRoutersMulticast(void) { return static_cast<const Address &>(Netif::kRealmLocalAllRoutersMulticastAddress.mAddress); } const Address &Address::GetRealmLocalAllMplForwarders(void) { return static_cast<const Address &>(Netif::kRealmLocalAllMplForwardersMulticastAddress.mAddress); } } // namespace Ip6 } // namespace ot
#include <asf.hpp> int main() { std::string expected("Hello, world!"); std::string actual; try { actual = asf::format("{1}, {0}!", "world", "Hello"); } catch(...) { return -1; } return (actual == expected) ? 0 : -1; }
/* This file was generated automatically by the Snowball to ANSI C compiler */ #include "header.h" #ifdef __cplusplus extern "C" { #endif extern int english_ISO_8859_1_stem(struct SN_env* z); #ifdef __cplusplus } #endif static int r_exception2(struct SN_env* z); static int r_exception1(struct SN_env* z); static int r_Step_5(struct SN_env* z); static int r_Step_4(struct SN_env* z); static int r_Step_3(struct SN_env* z); static int r_Step_2(struct SN_env* z); static int r_Step_1c(struct SN_env* z); static int r_Step_1b(struct SN_env* z); static int r_Step_1a(struct SN_env* z); static int r_R2(struct SN_env* z); static int r_R1(struct SN_env* z); static int r_shortv(struct SN_env* z); static int r_mark_regions(struct SN_env* z); static int r_postlude(struct SN_env* z); static int r_prelude(struct SN_env* z); #ifdef __cplusplus extern "C" { #endif extern struct SN_env* english_ISO_8859_1_create_env(void); extern void english_ISO_8859_1_close_env(struct SN_env* z); #ifdef __cplusplus } #endif static const symbol s_0_0[5] = {'a', 'r', 's', 'e', 'n'}; static const symbol s_0_1[6] = {'c', 'o', 'm', 'm', 'u', 'n'}; static const symbol s_0_2[5] = {'g', 'e', 'n', 'e', 'r'}; static const struct among a_0[3] = { /* 0 */ {5, s_0_0, -1, -1, 0}, /* 1 */ {6, s_0_1, -1, -1, 0}, /* 2 */ {5, s_0_2, -1, -1, 0}}; static const symbol s_1_0[1] = {'\''}; static const symbol s_1_1[3] = {'\'', 's', '\''}; static const symbol s_1_2[2] = {'\'', 's'}; static const struct among a_1[3] = { /* 0 */ {1, s_1_0, -1, 1, 0}, /* 1 */ {3, s_1_1, 0, 1, 0}, /* 2 */ {2, s_1_2, -1, 1, 0}}; static const symbol s_2_0[3] = {'i', 'e', 'd'}; static const symbol s_2_1[1] = {'s'}; static const symbol s_2_2[3] = {'i', 'e', 's'}; static const symbol s_2_3[4] = {'s', 's', 'e', 's'}; static const symbol s_2_4[2] = {'s', 's'}; static const symbol s_2_5[2] = {'u', 's'}; static const struct among a_2[6] = { /* 0 */ {3, s_2_0, -1, 2, 0}, /* 1 */ {1, s_2_1, -1, 3, 0}, /* 2 */ {3, s_2_2, 1, 2, 0}, /* 3 */ {4, s_2_3, 1, 1, 0}, /* 4 */ {2, s_2_4, 1, -1, 0}, /* 5 */ {2, s_2_5, 1, -1, 0}}; static const symbol s_3_1[2] = {'b', 'b'}; static const symbol s_3_2[2] = {'d', 'd'}; static const symbol s_3_3[2] = {'f', 'f'}; static const symbol s_3_4[2] = {'g', 'g'}; static const symbol s_3_5[2] = {'b', 'l'}; static const symbol s_3_6[2] = {'m', 'm'}; static const symbol s_3_7[2] = {'n', 'n'}; static const symbol s_3_8[2] = {'p', 'p'}; static const symbol s_3_9[2] = {'r', 'r'}; static const symbol s_3_10[2] = {'a', 't'}; static const symbol s_3_11[2] = {'t', 't'}; static const symbol s_3_12[2] = {'i', 'z'}; static const struct among a_3[13] = { /* 0 */ {0, 0, -1, 3, 0}, /* 1 */ {2, s_3_1, 0, 2, 0}, /* 2 */ {2, s_3_2, 0, 2, 0}, /* 3 */ {2, s_3_3, 0, 2, 0}, /* 4 */ {2, s_3_4, 0, 2, 0}, /* 5 */ {2, s_3_5, 0, 1, 0}, /* 6 */ {2, s_3_6, 0, 2, 0}, /* 7 */ {2, s_3_7, 0, 2, 0}, /* 8 */ {2, s_3_8, 0, 2, 0}, /* 9 */ {2, s_3_9, 0, 2, 0}, /* 10 */ {2, s_3_10, 0, 1, 0}, /* 11 */ {2, s_3_11, 0, 2, 0}, /* 12 */ {2, s_3_12, 0, 1, 0}}; static const symbol s_4_0[2] = {'e', 'd'}; static const symbol s_4_1[3] = {'e', 'e', 'd'}; static const symbol s_4_2[3] = {'i', 'n', 'g'}; static const symbol s_4_3[4] = {'e', 'd', 'l', 'y'}; static const symbol s_4_4[5] = {'e', 'e', 'd', 'l', 'y'}; static const symbol s_4_5[5] = {'i', 'n', 'g', 'l', 'y'}; static const struct among a_4[6] = { /* 0 */ {2, s_4_0, -1, 2, 0}, /* 1 */ {3, s_4_1, 0, 1, 0}, /* 2 */ {3, s_4_2, -1, 2, 0}, /* 3 */ {4, s_4_3, -1, 2, 0}, /* 4 */ {5, s_4_4, 3, 1, 0}, /* 5 */ {5, s_4_5, -1, 2, 0}}; static const symbol s_5_0[4] = {'a', 'n', 'c', 'i'}; static const symbol s_5_1[4] = {'e', 'n', 'c', 'i'}; static const symbol s_5_2[3] = {'o', 'g', 'i'}; static const symbol s_5_3[2] = {'l', 'i'}; static const symbol s_5_4[3] = {'b', 'l', 'i'}; static const symbol s_5_5[4] = {'a', 'b', 'l', 'i'}; static const symbol s_5_6[4] = {'a', 'l', 'l', 'i'}; static const symbol s_5_7[5] = {'f', 'u', 'l', 'l', 'i'}; static const symbol s_5_8[6] = {'l', 'e', 's', 's', 'l', 'i'}; static const symbol s_5_9[5] = {'o', 'u', 's', 'l', 'i'}; static const symbol s_5_10[5] = {'e', 'n', 't', 'l', 'i'}; static const symbol s_5_11[5] = {'a', 'l', 'i', 't', 'i'}; static const symbol s_5_12[6] = {'b', 'i', 'l', 'i', 't', 'i'}; static const symbol s_5_13[5] = {'i', 'v', 'i', 't', 'i'}; static const symbol s_5_14[6] = {'t', 'i', 'o', 'n', 'a', 'l'}; static const symbol s_5_15[7] = {'a', 't', 'i', 'o', 'n', 'a', 'l'}; static const symbol s_5_16[5] = {'a', 'l', 'i', 's', 'm'}; static const symbol s_5_17[5] = {'a', 't', 'i', 'o', 'n'}; static const symbol s_5_18[7] = {'i', 'z', 'a', 't', 'i', 'o', 'n'}; static const symbol s_5_19[4] = {'i', 'z', 'e', 'r'}; static const symbol s_5_20[4] = {'a', 't', 'o', 'r'}; static const symbol s_5_21[7] = {'i', 'v', 'e', 'n', 'e', 's', 's'}; static const symbol s_5_22[7] = {'f', 'u', 'l', 'n', 'e', 's', 's'}; static const symbol s_5_23[7] = {'o', 'u', 's', 'n', 'e', 's', 's'}; static const struct among a_5[24] = { /* 0 */ {4, s_5_0, -1, 3, 0}, /* 1 */ {4, s_5_1, -1, 2, 0}, /* 2 */ {3, s_5_2, -1, 13, 0}, /* 3 */ {2, s_5_3, -1, 16, 0}, /* 4 */ {3, s_5_4, 3, 12, 0}, /* 5 */ {4, s_5_5, 4, 4, 0}, /* 6 */ {4, s_5_6, 3, 8, 0}, /* 7 */ {5, s_5_7, 3, 14, 0}, /* 8 */ {6, s_5_8, 3, 15, 0}, /* 9 */ {5, s_5_9, 3, 10, 0}, /* 10 */ {5, s_5_10, 3, 5, 0}, /* 11 */ {5, s_5_11, -1, 8, 0}, /* 12 */ {6, s_5_12, -1, 12, 0}, /* 13 */ {5, s_5_13, -1, 11, 0}, /* 14 */ {6, s_5_14, -1, 1, 0}, /* 15 */ {7, s_5_15, 14, 7, 0}, /* 16 */ {5, s_5_16, -1, 8, 0}, /* 17 */ {5, s_5_17, -1, 7, 0}, /* 18 */ {7, s_5_18, 17, 6, 0}, /* 19 */ {4, s_5_19, -1, 6, 0}, /* 20 */ {4, s_5_20, -1, 7, 0}, /* 21 */ {7, s_5_21, -1, 11, 0}, /* 22 */ {7, s_5_22, -1, 9, 0}, /* 23 */ {7, s_5_23, -1, 10, 0}}; static const symbol s_6_0[5] = {'i', 'c', 'a', 't', 'e'}; static const symbol s_6_1[5] = {'a', 't', 'i', 'v', 'e'}; static const symbol s_6_2[5] = {'a', 'l', 'i', 'z', 'e'}; static const symbol s_6_3[5] = {'i', 'c', 'i', 't', 'i'}; static const symbol s_6_4[4] = {'i', 'c', 'a', 'l'}; static const symbol s_6_5[6] = {'t', 'i', 'o', 'n', 'a', 'l'}; static const symbol s_6_6[7] = {'a', 't', 'i', 'o', 'n', 'a', 'l'}; static const symbol s_6_7[3] = {'f', 'u', 'l'}; static const symbol s_6_8[4] = {'n', 'e', 's', 's'}; static const struct among a_6[9] = { /* 0 */ {5, s_6_0, -1, 4, 0}, /* 1 */ {5, s_6_1, -1, 6, 0}, /* 2 */ {5, s_6_2, -1, 3, 0}, /* 3 */ {5, s_6_3, -1, 4, 0}, /* 4 */ {4, s_6_4, -1, 4, 0}, /* 5 */ {6, s_6_5, -1, 1, 0}, /* 6 */ {7, s_6_6, 5, 2, 0}, /* 7 */ {3, s_6_7, -1, 5, 0}, /* 8 */ {4, s_6_8, -1, 5, 0}}; static const symbol s_7_0[2] = {'i', 'c'}; static const symbol s_7_1[4] = {'a', 'n', 'c', 'e'}; static const symbol s_7_2[4] = {'e', 'n', 'c', 'e'}; static const symbol s_7_3[4] = {'a', 'b', 'l', 'e'}; static const symbol s_7_4[4] = {'i', 'b', 'l', 'e'}; static const symbol s_7_5[3] = {'a', 't', 'e'}; static const symbol s_7_6[3] = {'i', 'v', 'e'}; static const symbol s_7_7[3] = {'i', 'z', 'e'}; static const symbol s_7_8[3] = {'i', 't', 'i'}; static const symbol s_7_9[2] = {'a', 'l'}; static const symbol s_7_10[3] = {'i', 's', 'm'}; static const symbol s_7_11[3] = {'i', 'o', 'n'}; static const symbol s_7_12[2] = {'e', 'r'}; static const symbol s_7_13[3] = {'o', 'u', 's'}; static const symbol s_7_14[3] = {'a', 'n', 't'}; static const symbol s_7_15[3] = {'e', 'n', 't'}; static const symbol s_7_16[4] = {'m', 'e', 'n', 't'}; static const symbol s_7_17[5] = {'e', 'm', 'e', 'n', 't'}; static const struct among a_7[18] = { /* 0 */ {2, s_7_0, -1, 1, 0}, /* 1 */ {4, s_7_1, -1, 1, 0}, /* 2 */ {4, s_7_2, -1, 1, 0}, /* 3 */ {4, s_7_3, -1, 1, 0}, /* 4 */ {4, s_7_4, -1, 1, 0}, /* 5 */ {3, s_7_5, -1, 1, 0}, /* 6 */ {3, s_7_6, -1, 1, 0}, /* 7 */ {3, s_7_7, -1, 1, 0}, /* 8 */ {3, s_7_8, -1, 1, 0}, /* 9 */ {2, s_7_9, -1, 1, 0}, /* 10 */ {3, s_7_10, -1, 1, 0}, /* 11 */ {3, s_7_11, -1, 2, 0}, /* 12 */ {2, s_7_12, -1, 1, 0}, /* 13 */ {3, s_7_13, -1, 1, 0}, /* 14 */ {3, s_7_14, -1, 1, 0}, /* 15 */ {3, s_7_15, -1, 1, 0}, /* 16 */ {4, s_7_16, 15, 1, 0}, /* 17 */ {5, s_7_17, 16, 1, 0}}; static const symbol s_8_0[1] = {'e'}; static const symbol s_8_1[1] = {'l'}; static const struct among a_8[2] = { /* 0 */ {1, s_8_0, -1, 1, 0}, /* 1 */ {1, s_8_1, -1, 2, 0}}; static const symbol s_9_0[7] = {'s', 'u', 'c', 'c', 'e', 'e', 'd'}; static const symbol s_9_1[7] = {'p', 'r', 'o', 'c', 'e', 'e', 'd'}; static const symbol s_9_2[6] = {'e', 'x', 'c', 'e', 'e', 'd'}; static const symbol s_9_3[7] = {'c', 'a', 'n', 'n', 'i', 'n', 'g'}; static const symbol s_9_4[6] = {'i', 'n', 'n', 'i', 'n', 'g'}; static const symbol s_9_5[7] = {'e', 'a', 'r', 'r', 'i', 'n', 'g'}; static const symbol s_9_6[7] = {'h', 'e', 'r', 'r', 'i', 'n', 'g'}; static const symbol s_9_7[6] = {'o', 'u', 't', 'i', 'n', 'g'}; static const struct among a_9[8] = { /* 0 */ {7, s_9_0, -1, -1, 0}, /* 1 */ {7, s_9_1, -1, -1, 0}, /* 2 */ {6, s_9_2, -1, -1, 0}, /* 3 */ {7, s_9_3, -1, -1, 0}, /* 4 */ {6, s_9_4, -1, -1, 0}, /* 5 */ {7, s_9_5, -1, -1, 0}, /* 6 */ {7, s_9_6, -1, -1, 0}, /* 7 */ {6, s_9_7, -1, -1, 0}}; static const symbol s_10_0[5] = {'a', 'n', 'd', 'e', 's'}; static const symbol s_10_1[5] = {'a', 't', 'l', 'a', 's'}; static const symbol s_10_2[4] = {'b', 'i', 'a', 's'}; static const symbol s_10_3[6] = {'c', 'o', 's', 'm', 'o', 's'}; static const symbol s_10_4[5] = {'d', 'y', 'i', 'n', 'g'}; static const symbol s_10_5[5] = {'e', 'a', 'r', 'l', 'y'}; static const symbol s_10_6[6] = {'g', 'e', 'n', 't', 'l', 'y'}; static const symbol s_10_7[4] = {'h', 'o', 'w', 'e'}; static const symbol s_10_8[4] = {'i', 'd', 'l', 'y'}; static const symbol s_10_9[5] = {'l', 'y', 'i', 'n', 'g'}; static const symbol s_10_10[4] = {'n', 'e', 'w', 's'}; static const symbol s_10_11[4] = {'o', 'n', 'l', 'y'}; static const symbol s_10_12[6] = {'s', 'i', 'n', 'g', 'l', 'y'}; static const symbol s_10_13[5] = {'s', 'k', 'i', 'e', 's'}; static const symbol s_10_14[4] = {'s', 'k', 'i', 's'}; static const symbol s_10_15[3] = {'s', 'k', 'y'}; static const symbol s_10_16[5] = {'t', 'y', 'i', 'n', 'g'}; static const symbol s_10_17[4] = {'u', 'g', 'l', 'y'}; static const struct among a_10[18] = { /* 0 */ {5, s_10_0, -1, -1, 0}, /* 1 */ {5, s_10_1, -1, -1, 0}, /* 2 */ {4, s_10_2, -1, -1, 0}, /* 3 */ {6, s_10_3, -1, -1, 0}, /* 4 */ {5, s_10_4, -1, 3, 0}, /* 5 */ {5, s_10_5, -1, 9, 0}, /* 6 */ {6, s_10_6, -1, 7, 0}, /* 7 */ {4, s_10_7, -1, -1, 0}, /* 8 */ {4, s_10_8, -1, 6, 0}, /* 9 */ {5, s_10_9, -1, 4, 0}, /* 10 */ {4, s_10_10, -1, -1, 0}, /* 11 */ {4, s_10_11, -1, 10, 0}, /* 12 */ {6, s_10_12, -1, 11, 0}, /* 13 */ {5, s_10_13, -1, 2, 0}, /* 14 */ {4, s_10_14, -1, 1, 0}, /* 15 */ {3, s_10_15, -1, -1, 0}, /* 16 */ {5, s_10_16, -1, 5, 0}, /* 17 */ {4, s_10_17, -1, 8, 0}}; static const unsigned char g_v[] = {17, 65, 16, 1}; static const unsigned char g_v_WXY[] = {1, 17, 65, 208, 1}; static const unsigned char g_valid_LI[] = {55, 141, 2}; static const symbol s_0[] = {'\''}; static const symbol s_1[] = {'y'}; static const symbol s_2[] = {'Y'}; static const symbol s_3[] = {'y'}; static const symbol s_4[] = {'Y'}; static const symbol s_5[] = {'s', 's'}; static const symbol s_6[] = {'i'}; static const symbol s_7[] = {'i', 'e'}; static const symbol s_8[] = {'e', 'e'}; static const symbol s_9[] = {'e'}; static const symbol s_10[] = {'e'}; static const symbol s_11[] = {'y'}; static const symbol s_12[] = {'Y'}; static const symbol s_13[] = {'i'}; static const symbol s_14[] = {'t', 'i', 'o', 'n'}; static const symbol s_15[] = {'e', 'n', 'c', 'e'}; static const symbol s_16[] = {'a', 'n', 'c', 'e'}; static const symbol s_17[] = {'a', 'b', 'l', 'e'}; static const symbol s_18[] = {'e', 'n', 't'}; static const symbol s_19[] = {'i', 'z', 'e'}; static const symbol s_20[] = {'a', 't', 'e'}; static const symbol s_21[] = {'a', 'l'}; static const symbol s_22[] = {'f', 'u', 'l'}; static const symbol s_23[] = {'o', 'u', 's'}; static const symbol s_24[] = {'i', 'v', 'e'}; static const symbol s_25[] = {'b', 'l', 'e'}; static const symbol s_26[] = {'l'}; static const symbol s_27[] = {'o', 'g'}; static const symbol s_28[] = {'f', 'u', 'l'}; static const symbol s_29[] = {'l', 'e', 's', 's'}; static const symbol s_30[] = {'t', 'i', 'o', 'n'}; static const symbol s_31[] = {'a', 't', 'e'}; static const symbol s_32[] = {'a', 'l'}; static const symbol s_33[] = {'i', 'c'}; static const symbol s_34[] = {'s'}; static const symbol s_35[] = {'t'}; static const symbol s_36[] = {'l'}; static const symbol s_37[] = {'s', 'k', 'i'}; static const symbol s_38[] = {'s', 'k', 'y'}; static const symbol s_39[] = {'d', 'i', 'e'}; static const symbol s_40[] = {'l', 'i', 'e'}; static const symbol s_41[] = {'t', 'i', 'e'}; static const symbol s_42[] = {'i', 'd', 'l'}; static const symbol s_43[] = {'g', 'e', 'n', 't', 'l'}; static const symbol s_44[] = {'u', 'g', 'l', 'i'}; static const symbol s_45[] = {'e', 'a', 'r', 'l', 'i'}; static const symbol s_46[] = {'o', 'n', 'l', 'i'}; static const symbol s_47[] = {'s', 'i', 'n', 'g', 'l'}; static const symbol s_48[] = {'Y'}; static const symbol s_49[] = {'y'}; static int r_prelude(struct SN_env* z) { z->B[0] = 0; /* unset Y_found, line 26 */ { int c1 = z->c; /* do, line 27 */ z->bra = z->c; /* [, line 27 */ if (!(eq_s(z, 1, s_0))) { goto lab0; } z->ket = z->c; /* ], line 27 */ { int ret = slice_del(z); /* delete, line 27 */ if (ret < 0) { return ret; } } lab0: z->c = c1; } { int c2 = z->c; /* do, line 28 */ z->bra = z->c; /* [, line 28 */ if (!(eq_s(z, 1, s_1))) { goto lab1; } z->ket = z->c; /* ], line 28 */ { int ret = slice_from_s(z, 1, s_2); /* <-, line 28 */ if (ret < 0) { return ret; } } z->B[0] = 1; /* set Y_found, line 28 */ lab1: z->c = c2; } { int c3 = z->c; /* do, line 29 */ while (1) { /* repeat, line 29 */ int c4 = z->c; while (1) { /* goto, line 29 */ int c5 = z->c; if (in_grouping(z, g_v, 97, 121, 0)) { goto lab4; } z->bra = z->c; /* [, line 29 */ if (!(eq_s(z, 1, s_3))) { goto lab4; } z->ket = z->c; /* ], line 29 */ z->c = c5; break; lab4: z->c = c5; if (z->c >= z->l) { goto lab3; } z->c++; /* goto, line 29 */ } { int ret = slice_from_s(z, 1, s_4); /* <-, line 29 */ if (ret < 0) { return ret; } } z->B[0] = 1; /* set Y_found, line 29 */ continue; lab3: z->c = c4; break; } z->c = c3; } return 1; } static int r_mark_regions(struct SN_env* z) { z->I[0] = z->l; z->I[1] = z->l; { int c1 = z->c; /* do, line 35 */ { int c2 = z->c; /* or, line 41 */ if (z->c + 4 >= z->l || (z->p[z->c + 4] >> 5) != 3 || !((2375680 >> (z->p[z->c + 4] & 0x1f)) & 1)) { goto lab2; } if (!(find_among(z, a_0, 3))) { goto lab2; /* among, line 36 */ } goto lab1; lab2: z->c = c2; { /* gopast */ /* grouping v, line 41 */ int ret = out_grouping(z, g_v, 97, 121, 1); if (ret < 0) goto lab0; z->c += ret; } { /* gopast */ /* non v, line 41 */ int ret = in_grouping(z, g_v, 97, 121, 1); if (ret < 0) { goto lab0; } z->c += ret; } } lab1: z->I[0] = z->c; /* setmark p1, line 42 */ { /* gopast */ /* grouping v, line 43 */ int ret = out_grouping(z, g_v, 97, 121, 1); if (ret < 0) { goto lab0; } z->c += ret; } { /* gopast */ /* non v, line 43 */ int ret = in_grouping(z, g_v, 97, 121, 1); if (ret < 0) { goto lab0; } z->c += ret; } z->I[1] = z->c; /* setmark p2, line 43 */ lab0: z->c = c1; } return 1; } static int r_shortv(struct SN_env* z) { { int m1 = z->l - z->c; (void)m1; /* or, line 51 */ if (out_grouping_b(z, g_v_WXY, 89, 121, 0) || in_grouping_b(z, g_v, 97, 121, 0) || out_grouping_b(z, g_v, 97, 121, 0)) { goto lab1; } goto lab0; lab1: z->c = z->l - m1; if (out_grouping_b(z, g_v, 97, 121, 0) || in_grouping_b(z, g_v, 97, 121, 0) || z->c > z->lb) { return 0; /* atlimit, line 52 */ } } lab0: return 1; } static int r_R1(struct SN_env* z) { return (!(z->I[0] <= z->c)) ? 0 : 1; } static int r_R2(struct SN_env* z) { return (!(z->I[1] <= z->c)) ? 0 : 1; } static int r_Step_1a(struct SN_env* z) { int among_var; { int m_keep = z->l - z->c; /* (void) m_keep */ /* try, line 59 */ z->ket = z->c; /* [, line 60 */ if (z->c <= z->lb || (z->p[z->c - 1] != 39 && z->p[z->c - 1] != 115)) { z->c = z->l - m_keep; goto lab0; } among_var = find_among_b(z, a_1, 3); /* substring, line 60 */ if (!(among_var)) { z->c = z->l - m_keep; goto lab0; } z->bra = z->c; /* ], line 60 */ switch (among_var) { case 0: { z->c = z->l - m_keep; goto lab0; } case 1: { int ret = slice_del(z); /* delete, line 62 */ if (ret < 0) { return ret; } } break; default: break; } lab0:; } z->ket = z->c; /* [, line 65 */ if (z->c <= z->lb || (z->p[z->c - 1] != 100 && z->p[z->c - 1] != 115)) { return 0; } among_var = find_among_b(z, a_2, 6); /* substring, line 65 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 65 */ switch (among_var) { case 0: return 0; case 1: { int ret = slice_from_s(z, 2, s_5); /* <-, line 66 */ if (ret < 0) { return ret; } } break; case 2: { int m1 = z->l - z->c; (void)m1; /* or, line 68 */ { int ret = z->c - 2; if (z->lb > ret || ret > z->l) { goto lab2; } z->c = ret; /* hop, line 68 */ } { int ret = slice_from_s(z, 1, s_6); /* <-, line 68 */ if (ret < 0) { return ret; } } goto lab1; lab2: z->c = z->l - m1; { int ret = slice_from_s(z, 2, s_7); /* <-, line 68 */ if (ret < 0) { return ret; } } } lab1: break; case 3: if (z->c <= z->lb) { return 0; } z->c--; /* next, line 69 */ { /* gopast */ /* grouping v, line 69 */ int ret = out_grouping_b(z, g_v, 97, 121, 1); if (ret < 0) { return 0; } z->c -= ret; } { int ret = slice_del(z); /* delete, line 69 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_Step_1b(struct SN_env* z) { int among_var; z->ket = z->c; /* [, line 75 */ if (z->c - 1 <= z->lb || (z->p[z->c - 1] >> 5) != 3 || !((33554576 >> (z->p[z->c - 1] & 0x1f)) & 1)) { return 0; } among_var = find_among_b(z, a_4, 6); /* substring, line 75 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 75 */ switch (among_var) { case 0: return 0; case 1: { int ret = r_R1(z); if (ret == 0) { return 0; /* call R1, line 77 */ } if (ret < 0) { return ret; } } { int ret = slice_from_s(z, 2, s_8); /* <-, line 77 */ if (ret < 0) { return ret; } } break; case 2: { int m_test = z->l - z->c; /* test, line 80 */ { /* gopast */ /* grouping v, line 80 */ int ret = out_grouping_b(z, g_v, 97, 121, 1); if (ret < 0) { return 0; } z->c -= ret; } z->c = z->l - m_test; } { int ret = slice_del(z); /* delete, line 80 */ if (ret < 0) { return ret; } } { int m_test = z->l - z->c; /* test, line 81 */ if (z->c - 1 <= z->lb || (z->p[z->c - 1] >> 5) != 3 || !((68514004 >> (z->p[z->c - 1] & 0x1f)) & 1)) { among_var = 3; } else { among_var = find_among_b(z, a_3, 13); /* substring, line 81 */ } if (!(among_var)) { return 0; } z->c = z->l - m_test; } switch (among_var) { case 0: return 0; case 1: { int c_keep = z->c; int ret = insert_s(z, z->c, z->c, 1, s_9); /* <+, line 83 */ z->c = c_keep; if (ret < 0) { return ret; } } break; case 2: z->ket = z->c; /* [, line 86 */ if (z->c <= z->lb) { return 0; } z->c--; /* next, line 86 */ z->bra = z->c; /* ], line 86 */ { int ret = slice_del(z); /* delete, line 86 */ if (ret < 0) { return ret; } } break; case 3: if (z->c != z->I[0]) { return 0; /* atmark, line 87 */ } { int m_test = z->l - z->c; /* test, line 87 */ { int ret = r_shortv(z); if (ret == 0) { return 0; /* call shortv, line 87 */ } if (ret < 0) { return ret; } } z->c = z->l - m_test; } { int c_keep = z->c; int ret = insert_s(z, z->c, z->c, 1, s_10); /* <+, line 87 */ z->c = c_keep; if (ret < 0) { return ret; } } break; default: break; } break; default: break; } return 1; } static int r_Step_1c(struct SN_env* z) { z->ket = z->c; /* [, line 94 */ { int m1 = z->l - z->c; (void)m1; /* or, line 94 */ if (!(eq_s_b(z, 1, s_11))) { goto lab1; } goto lab0; lab1: z->c = z->l - m1; if (!(eq_s_b(z, 1, s_12))) { return 0; } } lab0: z->bra = z->c; /* ], line 94 */ if (out_grouping_b(z, g_v, 97, 121, 0)) { return 0; } { int m2 = z->l - z->c; (void)m2; /* not, line 95 */ if (z->c > z->lb) { goto lab2; /* atlimit, line 95 */ } return 0; lab2: z->c = z->l - m2; } { int ret = slice_from_s(z, 1, s_13); /* <-, line 96 */ if (ret < 0) { return ret; } } return 1; } static int r_Step_2(struct SN_env* z) { int among_var; z->ket = z->c; /* [, line 100 */ if (z->c - 1 <= z->lb || (z->p[z->c - 1] >> 5) != 3 || !((815616 >> (z->p[z->c - 1] & 0x1f)) & 1)) { return 0; } among_var = find_among_b(z, a_5, 24); /* substring, line 100 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 100 */ { int ret = r_R1(z); if (ret == 0) { return 0; /* call R1, line 100 */ } if (ret < 0) { return ret; } } switch (among_var) { case 0: return 0; case 1: { int ret = slice_from_s(z, 4, s_14); /* <-, line 101 */ if (ret < 0) { return ret; } } break; case 2: { int ret = slice_from_s(z, 4, s_15); /* <-, line 102 */ if (ret < 0) { return ret; } } break; case 3: { int ret = slice_from_s(z, 4, s_16); /* <-, line 103 */ if (ret < 0) { return ret; } } break; case 4: { int ret = slice_from_s(z, 4, s_17); /* <-, line 104 */ if (ret < 0) { return ret; } } break; case 5: { int ret = slice_from_s(z, 3, s_18); /* <-, line 105 */ if (ret < 0) { return ret; } } break; case 6: { int ret = slice_from_s(z, 3, s_19); /* <-, line 107 */ if (ret < 0) { return ret; } } break; case 7: { int ret = slice_from_s(z, 3, s_20); /* <-, line 109 */ if (ret < 0) { return ret; } } break; case 8: { int ret = slice_from_s(z, 2, s_21); /* <-, line 111 */ if (ret < 0) { return ret; } } break; case 9: { int ret = slice_from_s(z, 3, s_22); /* <-, line 112 */ if (ret < 0) { return ret; } } break; case 10: { int ret = slice_from_s(z, 3, s_23); /* <-, line 114 */ if (ret < 0) { return ret; } } break; case 11: { int ret = slice_from_s(z, 3, s_24); /* <-, line 116 */ if (ret < 0) { return ret; } } break; case 12: { int ret = slice_from_s(z, 3, s_25); /* <-, line 118 */ if (ret < 0) { return ret; } } break; case 13: if (!(eq_s_b(z, 1, s_26))) { return 0; } { int ret = slice_from_s(z, 2, s_27); /* <-, line 119 */ if (ret < 0) { return ret; } } break; case 14: { int ret = slice_from_s(z, 3, s_28); /* <-, line 120 */ if (ret < 0) { return ret; } } break; case 15: { int ret = slice_from_s(z, 4, s_29); /* <-, line 121 */ if (ret < 0) { return ret; } } break; case 16: if (in_grouping_b(z, g_valid_LI, 99, 116, 0)) { return 0; } { int ret = slice_del(z); /* delete, line 122 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_Step_3(struct SN_env* z) { int among_var; z->ket = z->c; /* [, line 127 */ if (z->c - 2 <= z->lb || (z->p[z->c - 1] >> 5) != 3 || !((528928 >> (z->p[z->c - 1] & 0x1f)) & 1)) { return 0; } among_var = find_among_b(z, a_6, 9); /* substring, line 127 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 127 */ { int ret = r_R1(z); if (ret == 0) { return 0; /* call R1, line 127 */ } if (ret < 0) { return ret; } } switch (among_var) { case 0: return 0; case 1: { int ret = slice_from_s(z, 4, s_30); /* <-, line 128 */ if (ret < 0) { return ret; } } break; case 2: { int ret = slice_from_s(z, 3, s_31); /* <-, line 129 */ if (ret < 0) { return ret; } } break; case 3: { int ret = slice_from_s(z, 2, s_32); /* <-, line 130 */ if (ret < 0) { return ret; } } break; case 4: { int ret = slice_from_s(z, 2, s_33); /* <-, line 132 */ if (ret < 0) { return ret; } } break; case 5: { int ret = slice_del(z); /* delete, line 134 */ if (ret < 0) { return ret; } } break; case 6: { int ret = r_R2(z); if (ret == 0) { return 0; /* call R2, line 136 */ } if (ret < 0) { return ret; } } { int ret = slice_del(z); /* delete, line 136 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_Step_4(struct SN_env* z) { int among_var; z->ket = z->c; /* [, line 141 */ if (z->c - 1 <= z->lb || (z->p[z->c - 1] >> 5) != 3 || !((1864232 >> (z->p[z->c - 1] & 0x1f)) & 1)) { return 0; } among_var = find_among_b(z, a_7, 18); /* substring, line 141 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 141 */ { int ret = r_R2(z); if (ret == 0) { return 0; /* call R2, line 141 */ } if (ret < 0) { return ret; } } switch (among_var) { case 0: return 0; case 1: { int ret = slice_del(z); /* delete, line 144 */ if (ret < 0) { return ret; } } break; case 2: { int m1 = z->l - z->c; (void)m1; /* or, line 145 */ if (!(eq_s_b(z, 1, s_34))) { goto lab1; } goto lab0; lab1: z->c = z->l - m1; if (!(eq_s_b(z, 1, s_35))) { return 0; } } lab0 : { int ret = slice_del(z); /* delete, line 145 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_Step_5(struct SN_env* z) { int among_var; z->ket = z->c; /* [, line 150 */ if (z->c <= z->lb || (z->p[z->c - 1] != 101 && z->p[z->c - 1] != 108)) { return 0; } among_var = find_among_b(z, a_8, 2); /* substring, line 150 */ if (!(among_var)) { return 0; } z->bra = z->c; /* ], line 150 */ switch (among_var) { case 0: return 0; case 1: { int m1 = z->l - z->c; (void)m1; /* or, line 151 */ { int ret = r_R2(z); if (ret == 0) { goto lab1; /* call R2, line 151 */ } if (ret < 0) { return ret; } } goto lab0; lab1: z->c = z->l - m1; { int ret = r_R1(z); if (ret == 0) { return 0; /* call R1, line 151 */ } if (ret < 0) { return ret; } } { int m2 = z->l - z->c; (void)m2; /* not, line 151 */ { int ret = r_shortv(z); if (ret == 0) { goto lab2; /* call shortv, line 151 */ } if (ret < 0) { return ret; } } return 0; lab2: z->c = z->l - m2; } } lab0 : { int ret = slice_del(z); /* delete, line 151 */ if (ret < 0) { return ret; } } break; case 2: { int ret = r_R2(z); if (ret == 0) { return 0; /* call R2, line 152 */ } if (ret < 0) { return ret; } } if (!(eq_s_b(z, 1, s_36))) { return 0; } { int ret = slice_del(z); /* delete, line 152 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_exception2(struct SN_env* z) { z->ket = z->c; /* [, line 158 */ if (z->c - 5 <= z->lb || (z->p[z->c - 1] != 100 && z->p[z->c - 1] != 103)) { return 0; } if (!(find_among_b(z, a_9, 8))) { return 0; /* substring, line 158 */ } z->bra = z->c; /* ], line 158 */ if (z->c > z->lb) { return 0; /* atlimit, line 158 */ } return 1; } static int r_exception1(struct SN_env* z) { int among_var; z->bra = z->c; /* [, line 170 */ if (z->c + 2 >= z->l || (z->p[z->c + 2] >> 5) != 3 || !((42750482 >> (z->p[z->c + 2] & 0x1f)) & 1)) { return 0; } among_var = find_among(z, a_10, 18); /* substring, line 170 */ if (!(among_var)) { return 0; } z->ket = z->c; /* ], line 170 */ if (z->c < z->l) { return 0; /* atlimit, line 170 */ } switch (among_var) { case 0: return 0; case 1: { int ret = slice_from_s(z, 3, s_37); /* <-, line 174 */ if (ret < 0) { return ret; } } break; case 2: { int ret = slice_from_s(z, 3, s_38); /* <-, line 175 */ if (ret < 0) { return ret; } } break; case 3: { int ret = slice_from_s(z, 3, s_39); /* <-, line 176 */ if (ret < 0) { return ret; } } break; case 4: { int ret = slice_from_s(z, 3, s_40); /* <-, line 177 */ if (ret < 0) { return ret; } } break; case 5: { int ret = slice_from_s(z, 3, s_41); /* <-, line 178 */ if (ret < 0) { return ret; } } break; case 6: { int ret = slice_from_s(z, 3, s_42); /* <-, line 182 */ if (ret < 0) { return ret; } } break; case 7: { int ret = slice_from_s(z, 5, s_43); /* <-, line 183 */ if (ret < 0) { return ret; } } break; case 8: { int ret = slice_from_s(z, 4, s_44); /* <-, line 184 */ if (ret < 0) { return ret; } } break; case 9: { int ret = slice_from_s(z, 5, s_45); /* <-, line 185 */ if (ret < 0) { return ret; } } break; case 10: { int ret = slice_from_s(z, 4, s_46); /* <-, line 186 */ if (ret < 0) { return ret; } } break; case 11: { int ret = slice_from_s(z, 5, s_47); /* <-, line 187 */ if (ret < 0) { return ret; } } break; default: break; } return 1; } static int r_postlude(struct SN_env* z) { if (!(z->B[0])) { return 0; /* Boolean test Y_found, line 203 */ } while (1) { /* repeat, line 203 */ int c1 = z->c; while (1) { /* goto, line 203 */ int c2 = z->c; z->bra = z->c; /* [, line 203 */ if (!(eq_s(z, 1, s_48))) { goto lab1; } z->ket = z->c; /* ], line 203 */ z->c = c2; break; lab1: z->c = c2; if (z->c >= z->l) { goto lab0; } z->c++; /* goto, line 203 */ } { int ret = slice_from_s(z, 1, s_49); /* <-, line 203 */ if (ret < 0) { return ret; } } continue; lab0: z->c = c1; break; } return 1; } extern int english_ISO_8859_1_stem(struct SN_env* z) { { int c1 = z->c; /* or, line 207 */ { int ret = r_exception1(z); if (ret == 0) { goto lab1; /* call exception1, line 207 */ } if (ret < 0) { return ret; } } goto lab0; lab1: z->c = c1; { int c2 = z->c; /* not, line 208 */ { int ret = z->c + 3; if (0 > ret || ret > z->l) { goto lab3; } z->c = ret; /* hop, line 208 */ } goto lab2; lab3: z->c = c2; } goto lab0; lab2: z->c = c1; { int c3 = z->c; /* do, line 209 */ { int ret = r_prelude(z); if (ret == 0) { goto lab4; /* call prelude, line 209 */ } if (ret < 0) { return ret; } } lab4: z->c = c3; } { int c4 = z->c; /* do, line 210 */ { int ret = r_mark_regions(z); if (ret == 0) { goto lab5; /* call mark_regions, line 210 */ } if (ret < 0) { return ret; } } lab5: z->c = c4; } z->lb = z->c; z->c = z->l; /* backwards, line 211 */ { int m5 = z->l - z->c; (void)m5; /* do, line 213 */ { int ret = r_Step_1a(z); if (ret == 0) { goto lab6; /* call Step_1a, line 213 */ } if (ret < 0) { return ret; } } lab6: z->c = z->l - m5; } { int m6 = z->l - z->c; (void)m6; /* or, line 215 */ { int ret = r_exception2(z); if (ret == 0) { goto lab8; /* call exception2, line 215 */ } if (ret < 0) { return ret; } } goto lab7; lab8: z->c = z->l - m6; { int m7 = z->l - z->c; (void)m7; /* do, line 217 */ { int ret = r_Step_1b(z); if (ret == 0) { goto lab9; /* call Step_1b, line 217 */ } if (ret < 0) { return ret; } } lab9: z->c = z->l - m7; } { int m8 = z->l - z->c; (void)m8; /* do, line 218 */ { int ret = r_Step_1c(z); if (ret == 0) { goto lab10; /* call Step_1c, line 218 */ } if (ret < 0) { return ret; } } lab10: z->c = z->l - m8; } { int m9 = z->l - z->c; (void)m9; /* do, line 220 */ { int ret = r_Step_2(z); if (ret == 0) { goto lab11; /* call Step_2, line 220 */ } if (ret < 0) { return ret; } } lab11: z->c = z->l - m9; } { int m10 = z->l - z->c; (void)m10; /* do, line 221 */ { int ret = r_Step_3(z); if (ret == 0) { goto lab12; /* call Step_3, line 221 */ } if (ret < 0) { return ret; } } lab12: z->c = z->l - m10; } { int m11 = z->l - z->c; (void)m11; /* do, line 222 */ { int ret = r_Step_4(z); if (ret == 0) { goto lab13; /* call Step_4, line 222 */ } if (ret < 0) { return ret; } } lab13: z->c = z->l - m11; } { int m12 = z->l - z->c; (void)m12; /* do, line 224 */ { int ret = r_Step_5(z); if (ret == 0) { goto lab14; /* call Step_5, line 224 */ } if (ret < 0) { return ret; } } lab14: z->c = z->l - m12; } } lab7: z->c = z->lb; { int c13 = z->c; /* do, line 227 */ { int ret = r_postlude(z); if (ret == 0) { goto lab15; /* call postlude, line 227 */ } if (ret < 0) { return ret; } } lab15: z->c = c13; } } lab0: return 1; } extern struct SN_env* english_ISO_8859_1_create_env(void) { return SN_create_env(0, 2, 1); } extern void english_ISO_8859_1_close_env(struct SN_env* z) { SN_close_env(z, 0); }
#pragma once // This file is generated from the Game's Reflection data #include <cstdint> namespace RED4ext { namespace game { enum class MessageSender : uint32_t { NPC = 0, Player = 1, }; } // namespace game } // namespace RED4ext
/******************************************************************************* * Copyright 2021 Arm Ltd. and affiliates. * SPDX-License-Identifier: Apache-2.0 * * 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 <fstream> #include <string> #include <vector> #include "tensorflow/cc/client/client_session.h" #include "tensorflow/cc/ops/const_op.h" #include "tensorflow/cc/ops/image_ops.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/cc/saved_model/loader.h" namespace tf = tensorflow; using tensorflow::string; namespace utils { // Load the labels in a given file into a standard vector std::vector<std::string> get_labels(std::string filename) { std::ifstream file(filename); std::vector<std::string> labels; if (file.is_open()) { std::string line; while (std::getline(file, line)) { labels.push_back(line); } file.close(); } else { fprintf(stderr, ">>> ERROR: cannot read labels file.\n"); } return labels; } // Print graph nodes void print_graph_nodes(tf::GraphDef &graph_def) { int node_count = graph_def.node_size(); for (int i = 0; i < node_count; i++) { auto n = graph_def.node(i); std::cout << ">>> Name : " << n.name() << std::endl; } } // Print prediction void print_prediction(float score, int label_index, std::string label_name) { printf(">> Prediction confidence %6.3f - %s (label %d)\n", score * 100, label_name.c_str(), label_index); } // Get the image from disk as a float array of numbers, resized and normalized tf::Status read_image_into_tensor(const std::string &filename, tf::int32 img_w, tf::int32 img_h, std::vector<tf::Tensor> *out_tensors) { string output_name = "normalized"; tf::Scope root = tf::Scope::NewRootScope(); auto file_reader = tf::ops::ReadFile(root.WithOpName("file_reader"), filename); const int wanted_channels = 3; tf::Output image_reader = tf::ops::DecodeJpeg(root.WithOpName("file_decoder"), file_reader, tf::ops::DecodeJpeg::Channels(wanted_channels)); auto float_caster = tf::ops::Cast(root.WithOpName("float_caster"), image_reader, tf::DT_FLOAT); auto image_expander = tf::ops::ExpandDims(root.WithOpName("expand_dims"), float_caster, 0); float input_mean = 0; float input_std = 255; // Resize to graph expectation auto resized = tf::ops::ResizeBilinear( root, image_expander, tf::ops::Const(root.WithOpName("size"), {img_w, img_h})); // Normalize pixel value: subtract the mean and divide by the scale tf::ops::Div(root.WithOpName(output_name), tf::ops::Sub(root, resized, {input_mean}), {input_std}); // Run the graph we just constructed and return the outputs tf::GraphDef graph; TF_RETURN_IF_ERROR(root.ToGraphDef(&graph)); std::unique_ptr<tf::Session> session(tf::NewSession(tf::SessionOptions())); TF_RETURN_IF_ERROR(session->Create(graph)); TF_RETURN_IF_ERROR(session->Run({}, {output_name}, {}, out_tensors)); return tf::Status::OK(); } // Get the top predictions: score and label tf::Status get_top_labels(const std::vector<tf::Tensor> &outputs, int count, tf::Tensor *indices, tf::Tensor *scores) { auto root = tf::Scope::NewRootScope(); std::string output_name = "top_k"; tf::ops::TopK(root.WithOpName(output_name), outputs[0], count); tf::GraphDef graph; root.ToGraphDef(&graph); std::unique_ptr<tf::Session> session(tf::NewSession(tf::SessionOptions())); session->Create(graph); // :0 to specify scores // :1 to specify indices std::vector<tf::Tensor> out_tensors; auto status = session->Run({}, {output_name + ":0", output_name + ":1"}, {}, &out_tensors); *scores = out_tensors[0]; *indices = out_tensors[1]; return tf::Status::OK(); } } // namespace utils
 // HOOKDemoCatalogDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "HOOKDemoCatalog.h" #include "HOOKDemoCatalogDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CHOOKDemoCatalogDlg 对话框 CHOOKDemoCatalogDlg::CHOOKDemoCatalogDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_HOOKDEMOCATALOG_DIALOG, pParent) , deposit(0) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CHOOKDemoCatalogDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT2, deposit); DDV_MinMaxInt(pDX, deposit, 0, INT_MAX); } BEGIN_MESSAGE_MAP(CHOOKDemoCatalogDlg, CDialogEx) ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDOK, &CHOOKDemoCatalogDlg::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CHOOKDemoCatalogDlg::OnBnClickedCancel) END_MESSAGE_MAP() // CHOOKDemoCatalogDlg 消息处理程序 BOOL CHOOKDemoCatalogDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 GetDlgItem(IDC_EDIT2)->EnableWindow(FALSE); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CHOOKDemoCatalogDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CHOOKDemoCatalogDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } int deposit_fun(int i, int p) { i += p; return i; } void CHOOKDemoCatalogDlg::OnBnClickedOk() { // TODO: 在此添加控件通知处理程序代码 // CDialogEx::OnOK(); deposit = deposit_fun(deposit,100); UpdateData(FALSE); MessageBox(TEXT("存款成功")); } void CHOOKDemoCatalogDlg::OnBnClickedCancel() { // TODO: 在此添加控件通知处理程序代码 // CDialogEx::OnCancel(); if (deposit < 100) { MessageBox(TEXT("余额不足 被保安吊打")); return; } deposit -= 100; UpdateData(FALSE); }
#include "population.h" Population::Population() : _current_gen(0) { for (uint64_t i = 0; i < Settings::inst()->_individual_count; ++i) { _genome.push_back(std::unique_ptr<Individual>(new Individual())); } } uint64_t Population::getCurrent_gen() const { return _current_gen; } void Population::fitness_testing() { _current.max = -INFINITY; _current.min = 1; _current.average = 0; for (auto &indiv : _genome) { float f = indiv->evaluate_fitness(); _current.max = std::max(f, _current.max); _current.min = std::min(f, _current.min); _current.average += f; } //TODO maybe add fitness evaluation of children too for (auto &indiv : _children) { /*float f = */indiv->evaluate_fitness(); //just evaluate, not log stat /*_current.max = std::max(f, _current.max); _current.min = std::min(f, _current.min); _current.average += f;*/ } _current.average /= _genome.size(); } void Population::adult_selection() { //TODO maybe clean the _children vector switch (Settings::inst()->_adult_sel_strat) { case FULL_GEN_REPLACE: adult_selection_full_gen_replace(); break; case OVER_PRODUCTION: adult_selection_over_production(); break; case GENERATIONAL_MIXING: adult_selection_generational_mixing(); break; case FULL_GEN_REPLACE_MOD: adult_selection_full_gen_replace_mod(); break; case OVER_PRODUCTION_MOD: adult_selection_over_production_mod(); break; case GENERATIONAL_MIXING_MOD: adult_selection_generational_mixing_mod(); break; default: std::cerr << "no adult strategy selected: " << Settings::inst()->_adult_sel_strat << std::endl; exit(1); } } void Population::adult_selection_full_gen_replace() { for (uint64_t i = 0; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i]); } } //with elitism -> we need at least population of size 2 void Population::adult_selection_full_gen_replace_mod() { std::sort(_genome.begin(), _genome.end(), _decreasing_comparator); for (uint64_t i = 2; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i]); } } void Population::adult_selection_over_production() { std::shuffle(_children.begin(), _children.end(), Settings::inst()->_randomness_source); for (uint64_t i = 0; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i]); } } void Population::adult_selection_over_production_mod() { std::sort(_children.begin(), _children.end(), _decreasing_comparator); for (uint64_t i = 0; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i]); } } void Population::adult_selection_generational_mixing() { std::shuffle(_genome.begin(), _genome.end(), Settings::inst()->_randomness_source); uint64_t preserve = Settings::inst()->_adult_preserve_count; for (uint64_t i = preserve; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i-preserve]); } for (uint64_t i = Settings::inst()->_individual_count - preserve; i < _children.size(); ++i) { _genome.push_back(std::move(_children[i])); } std::shuffle(_genome.begin(), _genome.end(), Settings::inst()->_randomness_source); while (_genome.size() > Settings::inst()->_individual_count) { _genome.pop_back(); } } void Population::adult_selection_generational_mixing_mod() { std::sort(_children.begin(), _children.end(), _decreasing_comparator); std::sort(_genome.begin(), _genome.end(), _decreasing_comparator); uint64_t preserve = Settings::inst()->_adult_preserve_count; for (uint64_t i = preserve; i < _genome.size(); ++i) { _genome[i] = std::move(_children[i-preserve]); } } void Population::adult_selection_deterministic_mixing() { for (uint64_t i = 0; i < _children.size(); ++i) { _genome.push_back(std::move(_children[i])); } std::sort(_genome.begin(), _genome.end(), _decreasing_comparator); while (_genome.size() > Settings::inst()->_individual_count) { _genome.pop_back(); } } void Population::parent_selection() { _parents.erase(_parents.begin(), _parents.end()); switch (Settings::inst()->_parent_sel_strat) { case FITNESS_PROPORTIONATE: parent_selection_fitness_proportional(); break; case SIGMA_SCALING: parent_selection_sigma_scaling(); break; case TOURNAMENT: parent_selection_tournament(); break; case BOLTZMANN: parent_selection_boltzmann(); break; case RANK: parent_selection_rank(); break; case DETERMINISTIC_UNIFORM: parent_selection_deterministic_uniform(); break; case STOCHASTIC_UNIFORM: parent_selection_stochastic_uniform(); break; default: std::cerr << "no parent strategy selected: " << Settings::inst()->_parent_sel_strat << std::endl; exit(1); } } void Population::parent_selection_fitness_proportional() { std::vector<float> stacked_fitness; for (const auto &i : _genome) { stacked_fitness.push_back(i->getFitness()); } for (uint64_t i = 1; i < stacked_fitness.size(); ++i) { stacked_fitness[i] += stacked_fitness[i-1]; } std::uniform_real_distribution<float> rnd_float(0, stacked_fitness[stacked_fitness.size() - 1]); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { float r = rnd_float(Settings::inst()->_randomness_source); uint64_t par = 0; while (par < stacked_fitness.size() && r > stacked_fitness[par]) ++par; _parents.push_back(par); } } float Population::get_sigma_scaling(uint64_t i, float sig) const { return (1 + (_genome[i]->getFitness() + _current.average) / (2 * sig)); } float Population::get_sigma() const { float v = 0; for (auto const &i : _genome) { v += std::pow(i->getFitness() - _current.average, 2); } return v / _genome.size(); } uint64_t Population::get_best_id() const { uint64_t pos = 0; for (uint64_t i = 1; i < _genome.size(); ++i) { pos = (_genome[pos]->getFitness() < _genome[i]->getFitness()) ? i : pos; } return pos; } void Population::parent_selection_sigma_scaling() { std::vector<float> stacked_fitness; float sig = get_sigma(); stacked_fitness.push_back(get_sigma_scaling(0, sig)); for (uint64_t i = 1; i < _genome.size(); ++i) { stacked_fitness.push_back(get_sigma_scaling(i, sig) + stacked_fitness[i-1]); } std::uniform_real_distribution<float> rnd_float(0, stacked_fitness[stacked_fitness.size() - 1]); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { float r = rnd_float(Settings::inst()->_randomness_source); uint64_t par = 0; while (par < stacked_fitness.size() && r > stacked_fitness[par]) ++par; _parents.push_back(par); } } void Population::parent_selection_tournament() { std::uniform_int_distribution<uint64_t> rnd_int(0, _genome.size()-1); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { uint64_t par = rnd_int(Settings::inst()->_randomness_source); // to tournament is nominated_tournament_k individuals, the best is choosed as parent for (uint64_t j = 0; j < Settings::inst()->_tournament_k; ++j) { uint64_t alt = rnd_int(Settings::inst()->_randomness_source); if (_genome[alt]->getFitness() > _genome[par]->getFitness()) par = alt; } _parents.push_back(par); } } float Population::get_boltzmann(uint64_t i) const { float res = std::exp(_genome[i]->getFitness() / (_current_gen + 1)); return (res / std::exp(_current.average / (_current_gen + 1))); } void Population::parent_selection_boltzmann() { std::vector<float> stacked_fitness; stacked_fitness.push_back(get_boltzmann(0)); for (uint64_t i = 1; i < _genome.size(); ++i) { stacked_fitness.push_back(get_boltzmann(i) + stacked_fitness[i-1]); } std::uniform_real_distribution<float> rnd_float(0, stacked_fitness[stacked_fitness.size() - 1]); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { float r = rnd_float(Settings::inst()->_randomness_source); uint64_t par = 0; while (par < stacked_fitness.size() && r > stacked_fitness[par]) ++par; _parents.push_back(par); } } void Population::parent_selection_rank() { std::vector<uint64_t> stacked_fitness; std::sort(_genome.begin(), _genome.end(), _increasing_comparator); while (_genome[_genome.size() - 1]->getFitness() < 0 && _genome.size() > 2) { _genome.pop_back(); } stacked_fitness.push_back(1); for (uint64_t i = 1; i < _genome.size(); ++i) { stacked_fitness.push_back(i + stacked_fitness[i - 1] + 1); } std::uniform_int_distribution<uint64_t> rnd_int(0, stacked_fitness[stacked_fitness.size() - 1]); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { uint64_t r = rnd_int(Settings::inst()->_randomness_source); uint64_t par = 0; while (par < stacked_fitness.size() && r > stacked_fitness[par]) ++par; _parents.push_back(par); } } /*void Population::parent_selection_rank() { std::vector<uint64_t> stacked_fitness; std::sort(_genome.begin(), _genome.end(), _increasing_comparator); stacked_fitness.push_back(1); for (uint64_t i = 1; i < _genome.size(); ++i) { stacked_fitness.push_back(i + stacked_fitness[i - 1] + 1); } std::uniform_int_distribution<uint64_t> rnd_int(0, stacked_fitness[stacked_fitness.size() - 1]); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { uint64_t r = rnd_int(Settings::inst()->_randomness_source); uint64_t par = 0; while (par < stacked_fitness.size() && r > stacked_fitness[par]) ++par; _parents.push_back(par); } }*/ void Population::parent_selection_deterministic_uniform() { for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { // I assume, that this is runned with _parent_count beeing multiple of _genome.size _parents.push_back(i % _genome.size()); } } void Population::parent_selection_stochastic_uniform() { std::uniform_int_distribution<uint64_t> rnd_int(0, _genome.size() - 1); for (uint64_t i = 0; i < Settings::inst()->_parent_count; ++i) { _parents.push_back(rnd_int(Settings::inst()->_randomness_source)); } } void Population::reproduction() { std::uniform_int_distribution<uint64_t> rnd_int(0, _parents.size() - 1); std::bernoulli_distribution crossover(Settings::inst()->_crossover_probability); std::bernoulli_distribution mutate(Settings::inst()->_mutation_probability); _children.erase(_children.begin(), _children.end()); //_children from previous run for (uint64_t i = 0; i < Settings::inst()->_children_count; ++i) { std::unique_ptr<Individual> offspring; if (crossover(Settings::inst()->_randomness_source)) offspring = _genome[ _parents[ rnd_int(Settings::inst()->_randomness_source)]] ->cross_over( _genome[ _parents[ rnd_int(Settings::inst()->_randomness_source)]]); else offspring = _genome[ _parents[ rnd_int(Settings::inst()->_randomness_source)]] ->get_copy(); while (mutate(Settings::inst()->_randomness_source)) { offspring->mutate(); } _children.push_back(move(offspring)); } } Stats Population::evaluate() { ++_current_gen; fitness_testing(); //so individuals have set current fitness if (_current_gen != 1) adult_selection(); parent_selection(); reproduction(); return _current; } void Population::log() const { Settings::inst()->_log << std::endl << _current_gen; Settings::inst()->_log << ";" << _current.min; Settings::inst()->_log << ";" << _current.max; Settings::inst()->_log << ";" << _current.average; Settings::inst()->_log << ";" << get_sigma(); } void Population::print_final_fitness() const { Settings::inst()->_log << "Final results:" << std::endl; std::cout << "Final results:" << std::endl; Settings::inst()->_log << "Fitness min:" << _current.min << std::endl; std::cout << "Fitness min:" << _current.min << std::endl; Settings::inst()->_log << "Fitness max:" << _current.max << std::endl; std::cout << "Fitness max:" << _current.max << std::endl; Settings::inst()->_log << "Fitness avg:" << _current.average << std::endl; std::cout << "Fitness avg:" << _current.average << std::endl; } std::unique_ptr<Individual> Population::getBestIndividual() const { return _genome[0]->get_copy(); }
#include "global.h" #include "RageFile.h" #include "RageSurface.h" #include "RageSurface_Load_BMP.h" #include "RageUtil.h" using namespace FileReading; /* Tested with http://entropymine.com/jason/bmpsuite/. */ enum { COMP_BI_RGB = 0, COMP_BI_RLE4, /* unsupported */ COMP_BI_RLE8, /* unsupported */ COMP_BI_BITFIELDS }; /* When returning error, the first error encountered takes priority. */ #define FATAL_ERROR(s) \ \ { \ if (sError.size() == 0) \ sError = (s); \ return RageSurfaceUtils::OPEN_FATAL_ERROR; \ \ } static RageSurfaceUtils::OpenResult LoadBMP(RageFile& f, RageSurface*& img, RString& sError) { char magic[2]; ReadBytes(f, magic, 2, sError); if (magic[0] != 'B' || magic[1] != 'M') { sError = "not a BMP"; return RageSurfaceUtils::OPEN_UNKNOWN_FILE_FORMAT; } img = nullptr; read_u32_le(f, sError); /* file size */ read_u32_le(f, sError); /* unused */ uint32_t iDataOffset = read_u32_le(f, sError); uint32_t iHeaderSize = read_u32_le(f, sError); uint32_t iWidth, iHeight, iPlanes, iBPP, iCompression = COMP_BI_RGB, iColors = 0; if (iHeaderSize == 12) { /* OS/2 format */ iWidth = read_u16_le(f, sError); iHeight = read_u16_le(f, sError); iPlanes = read_u16_le(f, sError); iBPP = read_u16_le(f, sError); } else if (iHeaderSize == 40) { iWidth = read_u32_le(f, sError); iHeight = read_u32_le(f, sError); iPlanes = read_u16_le(f, sError); iBPP = read_u16_le(f, sError); iCompression = read_u32_le(f, sError); read_u32_le(f, sError); /* bitmap size */ read_u32_le(f, sError); /* horiz resolution */ read_u32_le(f, sError); /* vert resolution */ iColors = read_u32_le(f, sError); read_u32_le(f, sError); /* "important" colors */ } else FATAL_ERROR( ssprintf("expected header size of 40, got %u", iHeaderSize)); if (iBPP <= 8 && iColors == 0) iColors = 1 << iBPP; if (iPlanes != 1) FATAL_ERROR(ssprintf("expected one plane, got %u", iPlanes)); if (iBPP != 1 && iBPP != 4 && iBPP != 8 && iBPP != 16 && iBPP != 24 && iBPP != 32) FATAL_ERROR(ssprintf("unsupported bpp %u", iBPP)); if (iCompression != COMP_BI_RGB && iCompression != COMP_BI_BITFIELDS) FATAL_ERROR(ssprintf("unsupported compression %u", iCompression)); if (iCompression == COMP_BI_BITFIELDS && iBPP <= 8) FATAL_ERROR(ssprintf("BI_BITFIELDS unexpected with bpp %u", iBPP)); int iFileBPP = iBPP; iBPP = max(iBPP, 8u); int Rmask = 0, Gmask = 0, Bmask = 0, Amask = 0; switch (iBPP) { case 16: Rmask = Swap16LE(0x7C00); Gmask = Swap16LE(0x03E0); Bmask = Swap16LE(0x001F); break; case 24: Rmask = Swap24LE(0xFF0000); Gmask = Swap24LE(0x00FF00); Bmask = Swap24LE(0x0000FF); break; case 32: Rmask = Swap32LE(0x00FF0000); Gmask = Swap32LE(0x0000FF00); Bmask = Swap32LE(0x000000FF); break; } if (iCompression == COMP_BI_BITFIELDS) { Rmask = read_u32_le(f, sError); Gmask = read_u32_le(f, sError); Bmask = read_u32_le(f, sError); } /* Stop on error before we use any of the values we just read. */ if (sError.size() != 0) return RageSurfaceUtils::OPEN_FATAL_ERROR; img = CreateSurface(iWidth, iHeight, iBPP, Rmask, Gmask, Bmask, Amask); if (iBPP == 8) { RageSurfaceColor Palette[256]; ZERO(Palette); if (iColors > 256) FATAL_ERROR(ssprintf("unexpected colors %i", iColors)); for (unsigned i = 0; i < iColors; ++i) { Palette[i].b = read_8(f, sError); Palette[i].g = read_8(f, sError); Palette[i].r = read_8(f, sError); Palette[i].a = 0xFF; /* Windows BMP palettes are padded to 32bpp. */ if (iHeaderSize == 40) read_8(f, sError); } memcpy(img->fmt.palette->colors, Palette, sizeof(Palette)); } /* Stop on error before we seek, so we don't return the wrong error message. */ if (sError.size() != 0) return RageSurfaceUtils::OPEN_FATAL_ERROR; int iFilePitch = iFileBPP * iWidth; // in bits iFilePitch = (iFilePitch + 7) / 8; // in bytes: round up iFilePitch = (iFilePitch + 3) & ~3; // round up a multiple of 4 { int ret = f.Seek(iDataOffset); if (ret == -1) FATAL_ERROR(f.GetError()); if (ret != (int)iDataOffset) FATAL_ERROR("Unexpected end of file"); } for (int y = (int)iHeight - 1; y >= 0; --y) { uint8_t* pRow = img->pixels + img->pitch * y; RString buf; f.Read(buf, iFilePitch); /* Expand 1- and 4-bits to 8-bits. */ if (iFileBPP == 1) { for (unsigned x = 0; x < iWidth; ++x) { int iByteNo = x >> 3; int iBitNo = 7 - (x & 7); int iBit = 1 << iBitNo; pRow[x] = !!(buf[iByteNo] & iBit); } } else if (iFileBPP == 4) { for (unsigned x = 0; x < iWidth; ++x) { if ((x & 1) == 0) pRow[x] = buf[x / 2] & 0x0F; else pRow[x] = (buf[x / 2] >> 4) & 0x0F; } } else memcpy(pRow, buf.data(), img->pitch); } return sError.size() != 0 ? RageSurfaceUtils::OPEN_FATAL_ERROR : RageSurfaceUtils::OPEN_OK; } RageSurfaceUtils::OpenResult RageSurface_Load_BMP(const RString& sPath, RageSurface*& img, bool bHeaderOnly, RString& error) { RageFile f; if (!f.Open(sPath)) { error = f.GetError(); return RageSurfaceUtils::OPEN_FATAL_ERROR; } RageSurfaceUtils::OpenResult ret; img = nullptr; ret = LoadBMP(f, img, error); if (ret != RageSurfaceUtils::OPEN_OK && img != nullptr) { delete img; img = nullptr; } return ret; } /* * Copyright (c) 2004 Glenn Maynard * 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, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
#include "SecuredMenuPopup.h" #include "tcMenu.h" #include "BaseDialog.h" const char pgmProceedText[] PROGMEM = "Proceed"; const char pgmCancelText[] PROGMEM = "Cancel"; const char pgmHeaderNotAuth[] PROGMEM = "Pin incorrect"; RENDERING_CALLBACK_NAME_INVOKE(fnpopupPasswordRtCall, textItemRenderFn, "Password", -1, NULL) RENDERING_CALLBACK_NAME_INVOKE(fnpopupSubmenuSecured, backSubItemRenderFn, "Enter PIN", -1, NULL) SecuredMenuPopup::SecuredMenuPopup(AuthenticationManager * authentication) : backMenuItem(fnpopupSubmenuSecured, &pinEntryItem), pinEntryItem(fnpopupPasswordRtCall, nextRandomId(), MAX_PIN_LENGTH, &actionProceedItem), actionProceedItem(secPopupActionRenderFn, 1, &actionCancelItem), actionCancelItem(secPopupActionRenderFn, 0, NULL) { this->authentication = authentication; } MenuItem* SecuredMenuPopup::start(SubMenuItem* securedMenu) { actionProceedItem.setSecuredItem(securedMenu); actionProceedItem.setActive(false); actionCancelItem.setSecuredItem(NULL); actionCancelItem.setActive(false); backMenuItem.setActive(false); pinEntryItem.setTextValue("", true); pinEntryItem.setPasswordField(true); pinEntryItem.setActive(false); pinEntryItem.setEditing(false); return &backMenuItem; } int secPopupActionRenderFn(RuntimeMenuItem* item, uint8_t row, RenderFnMode mode, char* buffer, int bufferSize) { if (item->getMenuType() != MENUTYPE_ACTIVATE_SUBMENU) return false; ActivateSubMenuItem* act = reinterpret_cast<ActivateSubMenuItem*>(item); switch (mode) { case RENDERFN_VALUE: buffer[0] = 0; return true; case RENDERFN_NAME: strncpy_P(buffer, (row != 0) ? pgmProceedText : pgmCancelText, bufferSize); return true; case RENDERFN_EEPROM_POS: return -1; case RENDERFN_INVOKE: if(act->getSecuredItem() != NULL) { if (menuMgr.secureMenuInstance()->doesPinMatch()) { menuMgr.navigateToMenu(act->getSecuredItem()->getChild()); } else { menuMgr.resetMenu(false); BaseDialog* dlg = menuMgr.getRenderer()->getDialog(); dlg->setButtons(BTNTYPE_NONE, BTNTYPE_CLOSE); char sz[15]; act->getSecuredItem()->copyNameToBuffer(sz, sizeof(sz)); dlg->show(pgmHeaderNotAuth, false); dlg->copyIntoBuffer(sz); } } else { menuMgr.resetMenu(false); } return true; default: return false; } }
// -*- C++ -*- // // Package: PhysicsTools/NanoAOD // Class: LeptonJetVarProducer // /**\class LeptonJetVarProducer LeptonJetVarProducer.cc PhysicsTools/NanoAOD/plugins/LeptonJetVarProducer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Marco Peruzzi // Created: Tue, 05 Sep 2017 12:24:38 GMT // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/PatCandidates/interface/Jet.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/Common/interface/View.h" #include "DataFormats/Candidate/interface/VertexCompositePtrCandidate.h" #include "PhysicsTools/NanoAOD/interface/MatchingUtils.h" // // class declaration // template <typename T> class LeptonJetVarProducer : public edm::global::EDProducer<> { public: explicit LeptonJetVarProducer(const edm::ParameterSet& iConfig) : srcJet_(consumes<edm::View<pat::Jet>>(iConfig.getParameter<edm::InputTag>("srcJet"))), srcLep_(consumes<edm::View<T>>(iConfig.getParameter<edm::InputTag>("srcLep"))), srcVtx_(consumes<std::vector<reco::Vertex>>(iConfig.getParameter<edm::InputTag>("srcVtx"))) { produces<edm::ValueMap<float>>("ptRatio"); produces<edm::ValueMap<float>>("ptRel"); produces<edm::ValueMap<float>>("jetNDauChargedMVASel"); produces<edm::ValueMap<reco::CandidatePtr>>("jetForLepJetVar"); } ~LeptonJetVarProducer() override{}; static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; std::tuple<float, float, float> calculatePtRatioRel(edm::Ptr<reco::Candidate> lep, edm::Ptr<pat::Jet> jet, const reco::Vertex& vtx) const; // ----------member data --------------------------- edm::EDGetTokenT<edm::View<pat::Jet>> srcJet_; edm::EDGetTokenT<edm::View<T>> srcLep_; edm::EDGetTokenT<std::vector<reco::Vertex>> srcVtx_; }; // // constants, enums and typedefs // // // static data member definitions // // // member functions // // ------------ method called to produce the data ------------ template <typename T> void LeptonJetVarProducer<T>::produce(edm::StreamID streamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const { edm::Handle<edm::View<pat::Jet>> srcJet; iEvent.getByToken(srcJet_, srcJet); edm::Handle<edm::View<T>> srcLep; iEvent.getByToken(srcLep_, srcLep); edm::Handle<std::vector<reco::Vertex>> srcVtx; iEvent.getByToken(srcVtx_, srcVtx); unsigned int nJet = srcJet->size(); unsigned int nLep = srcLep->size(); std::vector<float> ptRatio(nLep, -1); std::vector<float> ptRel(nLep, -1); std::vector<float> jetNDauChargedMVASel(nLep, 0); std::vector<reco::CandidatePtr> jetForLepJetVar(nLep, reco::CandidatePtr()); const auto& pv = (*srcVtx)[0]; for (unsigned int il = 0; il < nLep; il++) { for (unsigned int ij = 0; ij < nJet; ij++) { auto lep = srcLep->ptrAt(il); auto jet = srcJet->ptrAt(ij); if (matchByCommonSourceCandidatePtr(*lep, *jet)) { auto res = calculatePtRatioRel(lep, jet, pv); ptRatio[il] = std::get<0>(res); ptRel[il] = std::get<1>(res); jetNDauChargedMVASel[il] = std::get<2>(res); jetForLepJetVar[il] = jet; break; // take leading jet with shared source candidates } } } std::unique_ptr<edm::ValueMap<float>> ptRatioV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerRatio(*ptRatioV); fillerRatio.insert(srcLep, ptRatio.begin(), ptRatio.end()); fillerRatio.fill(); iEvent.put(std::move(ptRatioV), "ptRatio"); std::unique_ptr<edm::ValueMap<float>> ptRelV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerRel(*ptRelV); fillerRel.insert(srcLep, ptRel.begin(), ptRel.end()); fillerRel.fill(); iEvent.put(std::move(ptRelV), "ptRel"); std::unique_ptr<edm::ValueMap<float>> jetNDauChargedMVASelV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerNDau(*jetNDauChargedMVASelV); fillerNDau.insert(srcLep, jetNDauChargedMVASel.begin(), jetNDauChargedMVASel.end()); fillerNDau.fill(); iEvent.put(std::move(jetNDauChargedMVASelV), "jetNDauChargedMVASel"); std::unique_ptr<edm::ValueMap<reco::CandidatePtr>> jetForLepJetVarV(new edm::ValueMap<reco::CandidatePtr>()); edm::ValueMap<reco::CandidatePtr>::Filler fillerjetForLepJetVar(*jetForLepJetVarV); fillerjetForLepJetVar.insert(srcLep, jetForLepJetVar.begin(), jetForLepJetVar.end()); fillerjetForLepJetVar.fill(); iEvent.put(std::move(jetForLepJetVarV), "jetForLepJetVar"); } template <typename T> std::tuple<float, float, float> LeptonJetVarProducer<T>::calculatePtRatioRel(edm::Ptr<reco::Candidate> lep, edm::Ptr<pat::Jet> jet, const reco::Vertex& vtx) const { auto rawp4 = jet->correctedP4("Uncorrected"); auto lepp4 = lep->p4(); if ((rawp4 - lepp4).R() < 1e-4) return std::tuple<float, float, float>(1.0, 0.0, 0.0); auto l1corrFactor = jet->jecFactor("L1FastJet") / jet->jecFactor("Uncorrected"); auto jetp4 = (rawp4 - lepp4 * (1.0 / l1corrFactor)) * (jet->pt() / rawp4.pt()) + lepp4; auto ptratio = lepp4.pt() / jetp4.pt(); auto ptrel = lepp4.Vect().Cross((jetp4 - lepp4).Vect().Unit()).R(); unsigned int jndau = 0; for (const auto _d : jet->daughterPtrVector()) { const auto d = dynamic_cast<const pat::PackedCandidate*>(_d.get()); if (d->charge() == 0) continue; if (d->fromPV() <= 1) continue; if (deltaR(*d, *lep) > 0.4) continue; if (!(d->hasTrackDetails())) continue; auto tk = d->pseudoTrack(); if (tk.pt() > 1 && tk.hitPattern().numberOfValidHits() >= 8 && tk.hitPattern().numberOfValidPixelHits() >= 2 && tk.normalizedChi2() < 5 && fabs(tk.dxy(vtx.position())) < 0.2 && fabs(tk.dz(vtx.position())) < 17) jndau++; } return std::tuple<float, float, float>(ptratio, ptrel, float(jndau)); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ template <typename T> void LeptonJetVarProducer<T>::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { //The following says we do not know what parameters are allowed so do no validation // Please change this to state exactly what you do use, even if it is no parameters edm::ParameterSetDescription desc; desc.add<edm::InputTag>("srcJet")->setComment("jet input collection"); desc.add<edm::InputTag>("srcLep")->setComment("lepton input collection"); desc.add<edm::InputTag>("srcVtx")->setComment("primary vertex input collection"); std::string modname; if (typeid(T) == typeid(pat::Muon)) modname += "Muon"; else if (typeid(T) == typeid(pat::Electron)) modname += "Electron"; modname += "JetVarProducer"; descriptions.add(modname, desc); } typedef LeptonJetVarProducer<pat::Muon> MuonJetVarProducer; typedef LeptonJetVarProducer<pat::Electron> ElectronJetVarProducer; //define this as a plug-in DEFINE_FWK_MODULE(MuonJetVarProducer); DEFINE_FWK_MODULE(ElectronJetVarProducer);
#ifndef _GRBL_CONTROLLER_ #define _GRBL_CONTROLLER_ #include "vars.hpp" #include "ui.hpp" #include "evt-ctrl.hpp" // GRBL status are : Idle, Run, Hold, Jog, Alarm, Door, Check, Home, Sleep // a message should look like (note : GRBL sent or WPOS or MPos depending on grbl parameter : to get WPos, we have to set "$10=0" // <Jog|WPos:1329.142,0.000,0.000|Bf:32,254|FS:2000,0|Ov:100,100,100|A:FM> // <Idle|WPos:0.000,0.000,0.000|FS:0.0,0> or e.g. <Idle|MPos:0.000,0.000,0.000|FS:0.0,0|WCO:0.000,0.000,0.000> //CLOSED // START // WPOS_HEADER // WPOS_DATA // HEADER // F_DATA // F_DATA // WCO_DATA // note : status can also be with a ":" like Hold:1 // outside <...>, we can get "Ok" and "error:12" followed by an CR and/or LF // we can also get messages: They are enclosed between [....] ; they are currently discarded. // used to decode the status and position sent by GRBL enum GrblStatus { GRBL_UNKNOWN, GRBL_IDLE, GRBL_RUN, GRBL_HOLD, GRBL_JOG, GRBL_ALARM, GRBL_DOOR, GRBL_CHECK, GRBL_HOME, GRBL_SLEEP }; #define MAXSIZE_OF_SIM 512 #define GRBL_STATUS_IDLE "idle" #define GRBL_STATUS_RUN "run" #define GRBL_STATUS_HOLD "hold" #define GRBL_STATUS_JOG "jog" #define GRBL_STATUS_ALARM "alarm" #define GRBL_STATUS_DOOR "door" #define GRBL_STATUS_CHECK "check" #define GRBL_STATUS_HOME "home" #define GRBL_STATUS_SLEEP "sleep" #define GRBL_STATE_G20 "g20" #define GRBL_STATE_G21 "g21" #define GRBL_STATE_G90 "g90" #define GRBL_STATE_G91 "g91" #define STR_GRBL_BUF_MAX_SIZE 256 #define STR_GRBL_BUF_MAX_WRITE_SIZE 256 enum GrblPrintStatus { empty, full, waitForStatus }; enum GrblStep { M1, M10, M100 }; class GrblCtrl { public: GrblCtrl(); void setup(); void loop(); void print(const char *filename); void remove(const char *filename); void spool(); void serial(const char *message); void setBusy(boolean _busyState); boolean isBusy(); boolean home(); boolean unlock(); boolean reset(); boolean pause(); boolean resume(); boolean status(); boolean move(EventGrbl sens, float distance); boolean move(float x, float y, float z, int speed); boolean setXYZ(EventGrbl param); void jogMoveXY(float x, float y); void jogMoveZ(float z); // Event handler void notify(const Event *event); static GrblCtrl *instance(); void getStoredMpos(float *x, float *y, float *z); void getStoredWpos(float *x, float *y, float *z); void getWorkingMpos(float *x, float *y, float *z); void getWorkingWpos(float *x, float *y, float *z); void getStoredModal(bool *metric, bool *abs); void getWorkingModal(bool *metric, bool *abs); void forceWrite(boolean flush, const char *grbl, ...); bool tryWrite(boolean flush, const char *grbl, ...); protected: void error(const char *message); void alarm(const char *message); void status(const char *message); int available(); int read(); void write(boolean flush, const char *data); void flush(); void decodeStatus(const char *, const char *); void decodeState(const char *, const char *); void decodeError(const char *, const char *); void decodeAlarm(const char *, const char *); void decodeOk(const char *, const char *); void decodeFeedback(const char *, const char *); void script(const char *input, char *output); void evaluate(const char *input, char *output, int sz); bool heartbeat(); private: // jog long lastJog = 0; float xyzJogPas = 0.1; float xyzL1Pas = 0.1; float xyzL2Pas = 0.5; float xyzL3Pas = 5; // this buffer is used to store a few char received from GRBL before decoding them char strGrblBuf[STR_GRBL_BUF_MAX_SIZE]; // lower version of strGrblBuf char strGrblBufNoCase[STR_GRBL_BUF_MAX_SIZE]; char printBuffer[STR_GRBL_BUF_MAX_SIZE]; char evalBuffer[STR_GRBL_BUF_MAX_SIZE]; // write buffer char writeBuffer[STR_GRBL_BUF_MAX_WRITE_SIZE]; // state GrblStatus grblState = GRBL_UNKNOWN; struct { struct { float x, y, z; } mpos; struct { float x, y, z; } wpos; boolean grblStatusMetric; boolean grblStatusAbs; } stored; struct { struct { float x, y, z; } mpos; struct { float x, y, z; } wpos; boolean grblStatusMetric; boolean grblStatusAbs; } working; uint8_t strGrblIdx; uint8_t txRead = 0; uint8_t txWrite = 0; uint8_t byteRead = 0; boolean busy = true; boolean isPrinting = false; int toPrintLines = 0; int printedLines = 0; boolean isPaused = false; GrblPrintStatus grblPrintStatus = empty; GrblStep step = M1; long lastStatus = 0; // only for simulation char internalSerialBuffer[MAXSIZE_OF_SIM]; int internalSerialIndex = 0; int internalSerialCounter = 0; int uTime = 0; }; #endif
#include <Engine/Window.h> #include <Engine/Log.h> #include <Engine/Settings.h> #include <Engine/DebugUI.h> #include <Engine/HashName.h> #include <Windows.h> INT APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) { afex::log::Init(); afex::g_Settings.Load(); auto const& windowSettings = afex::g_Settings.Window; afex::Window* window = afex::Window::Create(windowSettings.width, windowSettings.height, windowSettings.title); while (window->Update()) { } afex::g_Settings.Save(); delete window; return 0; }
/** * @file llurlhistory.cpp * @brief Manages a list of recent URLs * * $LicenseInfo:firstyear=2007&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "llviewerprecompiledheaders.h" #include "llurlhistory.h" #include "lldir.h" #include "llsdserialize.h" LLSD LLURLHistory::sHistorySD; const int MAX_URL_COUNT = 10; ///////////////////////////////////////////////////////////////////////////// // static bool LLURLHistory::loadFile(const std::string& filename) { bool dataloaded = false; sHistorySD = LLSD(); LLSD data; std::string user_filename(gDirUtilp->getLindenUserDir() + gDirUtilp->getDirDelimiter() + filename); llifstream file(user_filename.c_str()); if (file.is_open()) { LLSDSerialize::fromXML(data, file); if (data.isUndefined()) { LL_WARNS() << "error loading " << user_filename << LL_ENDL; } else { LL_INFOS() << "Loaded history file at " << user_filename << LL_ENDL; sHistorySD = data; dataloaded = true; } } else { LL_INFOS() << "Unable to open history file at " << user_filename << LL_ENDL; } return dataloaded; } // static bool LLURLHistory::saveFile(const std::string& filename) { std::string temp_str = gDirUtilp->getLindenUserDir(); if( temp_str.empty() ) { LL_INFOS() << "Can't save URL history - no user directory set yet." << LL_ENDL; return false; } temp_str += gDirUtilp->getDirDelimiter() + filename; llofstream out(temp_str.c_str()); if (!out.good()) { LL_WARNS() << "Unable to open " << temp_str << " for output." << LL_ENDL; return false; } LLSDSerialize::toXML(sHistorySD, out); out.close(); return true; } // static // This function returns a portion of the history llsd that contains the collected // url history LLSD LLURLHistory::getURLHistory(const std::string& collection) { if(sHistorySD.has(collection)) { return sHistorySD[collection]; } return LLSD(); } // static void LLURLHistory::addURL(const std::string& collection, const std::string& url) { if(!url.empty()) { LLURI u(url); std::string simplified_url = u.scheme() + "://" + u.authority() + u.path(); sHistorySD[collection].insert(0, simplified_url); LLURLHistory::limitSize(collection); } } // static void LLURLHistory::removeURL(const std::string& collection, const std::string& url) { if(!url.empty()) { LLURI u(url); std::string simplified_url = u.scheme() + "://" + u.authority() + u.path(); for(int index = 0; index < sHistorySD[collection].size(); index++) { if(sHistorySD[collection].get(index).asString() == simplified_url) { sHistorySD[collection].erase(index); } } } } // static void LLURLHistory::clear(const std::string& collection) { sHistorySD[ collection ] = LLSD(); } void LLURLHistory::limitSize(const std::string& collection) { while(sHistorySD[collection].size() > MAX_URL_COUNT) { sHistorySD[collection].erase(MAX_URL_COUNT); } }
class Solution { public: int projectionArea(vector<vector<int>>& grid) { int m = grid.size(), n = grid[0].size(); int side = 0, front = 0, top = 0; for(int i = 0; i < m; ++i) { int temp = 0; for(int j = 0; j < n; ++j) { if (grid[i][j] > 0) ++top; if (grid[i][j] > temp) temp = grid[i][j]; } side += temp; } for(int j = 0; j < n; ++j) { int temp = 0; for(int i = 0; i < m; ++i) { if (grid[i][j] > temp) temp = grid[i][j]; } front += temp; } return side + front + top; } };
// Copyright 2018 Google LLC // // 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 "google/cloud/bigtable/benchmarks/random_mutation.h" #include "google/cloud/bigtable/benchmarks/constants.h" namespace google { namespace cloud { namespace bigtable { namespace benchmarks { bigtable::Mutation MakeRandomMutation(google::cloud::internal::DefaultPRNG& gen, int f) { std::string field = "field" + std::to_string(f); return bigtable::SetCell(kColumnFamily, std::move(field), std::chrono::milliseconds(0), MakeRandomValue(gen)); } std::string MakeRandomValue(google::cloud::internal::DefaultPRNG& generator) { static std::string const kLetters( "ABCDEFGHIJLKMNOPQRSTUVWXYZabcdefghijlkmnopqrstuvwxyz0123456789-/_"); return google::cloud::internal::Sample(generator, kFieldSize, kLetters); } } // namespace benchmarks } // namespace bigtable } // namespace cloud } // namespace google
#include "Model.h" #include <iostream> #include <string> #include <stb_image/stb_image.h> void Model::Draw(Shader shader, const std::string& uniformName) { for (unsigned int i = 0; i < Meshes.size(); i++) { Meshes[i].Draw(shader, uniformName); } } void Model::loadModel(std::string path) { Assimp::Importer import; const aiScene *scene = import.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "ERROR::ASSIMP::" << import.GetErrorString() << std::endl; return; } directory = path.substr(0, path.find_last_of('/')); processNode(scene->mRootNode, scene); } void Model::processNode(aiNode * node, const aiScene * scene) { // process all the node's meshes (if any) for (unsigned int i = 0; i < node->mNumMeshes; i++) { aiMesh *mesh = scene->mMeshes[node->mMeshes[i]]; Meshes.push_back(processMesh(mesh, scene)); } // then do the same for each of its children for (unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh * mesh, const aiScene * scene) { std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<Texture> textures; // walk through each of the mesh's vertices for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; glm::vec3 vector; // we declare a placeholder vector since assimp uses its own vector class that doesn't directly convert to glm's vec3 class so we transfer the data to this placeholder glm::vec3 first. // positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.Position = vector; // normals vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.Normal = vector; // texture coordinates if (mesh->mTextureCoords[0]) // does the mesh contain texture coordinates? { glm::vec2 vec; // a vertex can contain up to 8 different texture coordinates. We thus make the assumption that we won't // use models where a vertex can have multiple texture coordinates so we always take the first set (0). vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.TexCoord = vec; } else vertex.TexCoord = glm::vec2(0.0f, 0.0f); // tangent vector.x = mesh->mTangents[i].x; vector.y = mesh->mTangents[i].y; vector.z = mesh->mTangents[i].z; vertex.Tangent = vector; // bitangent vector.x = mesh->mBitangents[i].x; vector.y = mesh->mBitangents[i].y; vector.z = mesh->mBitangents[i].z; vertex.Bitangent = vector; vertices.push_back(vertex); } // now wak through each of the mesh's faces (a face is a mesh its triangle) and retrieve the corresponding vertex indices. for (unsigned int i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // retrieve all indices of the face and store them in the indices vector for (unsigned int j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } // process materials aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // we assume a convention for sampler names in the shaders. Each diffuse texture should be named // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. // Same applies to other texture as the following list summarizes: // diffuse: texture_diffuseN // specular: texture_specularN // normal: texture_normalN // 1. diffuse maps std::vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, TextureType::DIFFUSE); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. specular maps std::vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, TextureType::SPECULAR); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. normal maps std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, TextureType::NORMAL); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. height maps std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, TextureType::HEIGHT); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); // return a mesh object created from the extracted mesh data return Mesh(vertices, indices, textures); } std::vector<Texture> Model::loadMaterialTextures(aiMaterial * mat, aiTextureType type, TextureType typeName) { std::vector<Texture> textures; for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); bool skip = false; for (unsigned int j = 0; j < TexturesLoaded.size(); j++) { if (std::strcmp(TexturesLoaded[j].path.data(), str.C_Str()) == 0) { textures.push_back(TexturesLoaded[j]); skip = true; // a texture with the same filepath has already been loaded, continue to next one. (optimization) break; } } if (skip == false) { Texture texture; texture.path = str.C_Str(); texture.id = TextureFromFile(texture.path, directory); texture.type = typeName; textures.push_back(texture); TexturesLoaded.push_back(texture); } } return textures; } unsigned int TextureFromFile(const std::string& path, const std::string &directory, bool gamma) { std::string filename = directory + '/' + path; unsigned int textureID; glGenTextures(1, &textureID); int width, height, nrComponents; unsigned char *data = stbi_load(filename.c_str(), &width, &height, &nrComponents, 0); if (data) { GLenum format; if (nrComponents == 1) format = GL_RED; else if (nrComponents == 3) format = GL_RGB; else if (nrComponents == 4) format = GL_RGBA; glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); } else { std::cout << "Texture failed to load at path: " << path << std::endl; stbi_image_free(data); } return textureID; }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_FUZZY_FUNCTIONS_SIMD_COMMON_FUZZY_DEFINITELY_NOT_EQUAL_HPP_INCLUDED #define NT2_FUZZY_FUNCTIONS_SIMD_COMMON_FUZZY_DEFINITELY_NOT_EQUAL_HPP_INCLUDED #include <nt2/fuzzy/functions/fuzzy_definitely_not_equal.hpp> #include <nt2/include/functions/simd/multiplies.hpp> #include <nt2/include/functions/simd/is_greater.hpp> #include <nt2/include/functions/simd/max.hpp> #include <nt2/include/functions/simd/abs.hpp> #include <nt2/include/functions/simd/dist.hpp> ///////////////////////////////////////////////////////////////////////////// // Implementation when type is arithmetic_ ///////////////////////////////////////////////////////////////////////////// namespace nt2 { namespace ext { BOOST_DISPATCH_IMPLEMENT (fuzzy_definitely_not_equal_, tag::cpu_, (A0)(X), ((simd_<arithmetic_<A0>,X>)) ((simd_<arithmetic_<A0>,X>)) ((simd_<arithmetic_<A0>,X>)) ) { typedef typename meta::as_logical<A0>::type result_type; NT2_FUNCTOR_CALL_REPEAT(3) { return gt(dist(a0, a1), max(abs(a0),abs(a1))*a2); } }; } } #endif
#include <QtGlobal> // Automatically generated by extract_strings_qt.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *monkecoin_strings[] = { QT_TRANSLATE_NOOP("monkecoin-core", "The %s developers"), QT_TRANSLATE_NOOP("monkecoin-core", "" "%s corrupt. Try using the wallet tool monkecoin-wallet to salvage or restoring " "a backup."), QT_TRANSLATE_NOOP("monkecoin-core", "" "-maxtxfee is set very high! Fees this large could be paid on a single " "transaction."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Cannot obtain a lock on data directory %s. %s is probably already running."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Cannot provide specific connections and have addrman find outgoing " "connections at the same."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Cannot upgrade a non HD split wallet without upgrading to support pre split " "keypool. Please use version 169900 or no version specified."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Distributed under the MIT software license, see the accompanying file %s or " "%s"), QT_TRANSLATE_NOOP("monkecoin-core", "" "Error reading %s! All keys read correctly, but transaction data or address " "book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("monkecoin-core", "" "Fee estimation failed. Fallbackfee is disabled. Wait a few blocks or enable -" "fallbackfee."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("monkecoin-core", "" "More than one onion bind address is provided. Using %s for the automatically " "created Tor onion service."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Please check that your computer's date and time are correct! If your clock " "is wrong, %s will not work properly."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Please contribute if you find %s useful. Visit %s for further information " "about the software."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Prune configured below the minimum of %d MiB. Please use a higher number."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Prune: last wallet synchronisation goes beyond pruned data. You need to -" "reindex (download the whole blockchain again in case of pruned node)"), QT_TRANSLATE_NOOP("monkecoin-core", "" "SQLiteDatabase: Failed to prepare the statement to fetch sqlite wallet " "schema version: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "" "SQLiteDatabase: Failed to prepare the statement to fetch the application id: " "%s"), QT_TRANSLATE_NOOP("monkecoin-core", "" "SQLiteDatabase: Unknown sqlite wallet schema version %d. Only version %d is " "supported"), QT_TRANSLATE_NOOP("monkecoin-core", "" "The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. Only " "rebuild the block database if you are sure that your computer's date and " "time are correct"), QT_TRANSLATE_NOOP("monkecoin-core", "" "The transaction amount is too small to send after the fee has been deducted"), QT_TRANSLATE_NOOP("monkecoin-core", "" "This error could occur if this wallet was not shutdown cleanly and was last " "loaded using a build with a newer version of Berkeley DB. If so, please use " "the software that last loaded this wallet"), QT_TRANSLATE_NOOP("monkecoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("monkecoin-core", "" "This is the maximum transaction fee you pay (in addition to the normal fee) " "to prioritize partial spend avoidance over regular coin selection."), QT_TRANSLATE_NOOP("monkecoin-core", "" "This is the transaction fee you may discard if change is smaller than dust " "at this level"), QT_TRANSLATE_NOOP("monkecoin-core", "" "This is the transaction fee you may pay when fee estimates are not available."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Total length of network version string (%i) exceeds maximum length (%i). " "Reduce the number or size of uacomments."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Transaction needs a change address, but we can't generate it. Please call " "keypoolrefill first."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Unable to replay blocks. You will need to rebuild the database using -" "reindex-chainstate."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Unable to rewind the database to a pre-fork state. You will need to " "redownload the blockchain"), QT_TRANSLATE_NOOP("monkecoin-core", "" "Warning: Private keys detected in wallet {%s} with disabled private keys"), QT_TRANSLATE_NOOP("monkecoin-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), QT_TRANSLATE_NOOP("monkecoin-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("monkecoin-core", "" "You need to rebuild the database using -reindex to go back to unpruned " "mode. This will redownload the entire blockchain"), QT_TRANSLATE_NOOP("monkecoin-core", "%s is set very high!"), QT_TRANSLATE_NOOP("monkecoin-core", "-maxmempool must be at least %d MB"), QT_TRANSLATE_NOOP("monkecoin-core", "A fatal internal error occurred, see debug.log for details"), QT_TRANSLATE_NOOP("monkecoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("monkecoin-core", "Cannot resolve -%s address: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Cannot set -peerblockfilters without -blockfilterindex."), QT_TRANSLATE_NOOP("monkecoin-core", "Cannot write to data directory '%s'; check permissions."), QT_TRANSLATE_NOOP("monkecoin-core", "Change index out of range"), QT_TRANSLATE_NOOP("monkecoin-core", "Config setting for %s only applied on %s network when in [%s] section."), QT_TRANSLATE_NOOP("monkecoin-core", "Copyright (C) %i-%i"), QT_TRANSLATE_NOOP("monkecoin-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("monkecoin-core", "Could not find asmap file %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Could not parse asmap file %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Disk space is too low!"), QT_TRANSLATE_NOOP("monkecoin-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("monkecoin-core", "Done loading"), QT_TRANSLATE_NOOP("monkecoin-core", "Error initializing block database"), QT_TRANSLATE_NOOP("monkecoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("monkecoin-core", "Error loading %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Error loading %s: Private keys can only be disabled during creation"), QT_TRANSLATE_NOOP("monkecoin-core", "Error loading %s: Wallet corrupted"), QT_TRANSLATE_NOOP("monkecoin-core", "Error loading %s: Wallet requires newer version of %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Error loading block database"), QT_TRANSLATE_NOOP("monkecoin-core", "Error opening block database"), QT_TRANSLATE_NOOP("monkecoin-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("monkecoin-core", "Error upgrading chainstate database"), QT_TRANSLATE_NOOP("monkecoin-core", "Error: Disk space is low for %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Error: Keypool ran out, please call keypoolrefill first"), QT_TRANSLATE_NOOP("monkecoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("monkecoin-core", "Failed to rescan the wallet during initialization"), QT_TRANSLATE_NOOP("monkecoin-core", "Failed to verify database"), QT_TRANSLATE_NOOP("monkecoin-core", "Fee rate (%s) is lower than the minimum fee rate setting (%s)"), QT_TRANSLATE_NOOP("monkecoin-core", "Ignoring duplicate -wallet %s."), QT_TRANSLATE_NOOP("monkecoin-core", "Importing..."), QT_TRANSLATE_NOOP("monkecoin-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("monkecoin-core", "Initialization sanity check failed. %s is shutting down."), QT_TRANSLATE_NOOP("monkecoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid -onion address or hostname: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid -proxy address or hostname: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid P2P permission: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid amount for -%s=<amount>: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid amount for -discardfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid amount for -fallbackfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("monkecoin-core", "Invalid netmask specified in -whitelist: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Loading P2P addresses..."), QT_TRANSLATE_NOOP("monkecoin-core", "Loading banlist..."), QT_TRANSLATE_NOOP("monkecoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("monkecoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("monkecoin-core", "Need to specify a port with -whitebind: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "No proxy server specified. Use -proxy=<ip> or -proxy=<ip:port>."), QT_TRANSLATE_NOOP("monkecoin-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("monkecoin-core", "Prune cannot be configured with a negative value."), QT_TRANSLATE_NOOP("monkecoin-core", "Prune mode is incompatible with -blockfilterindex."), QT_TRANSLATE_NOOP("monkecoin-core", "Prune mode is incompatible with -txindex."), QT_TRANSLATE_NOOP("monkecoin-core", "Pruning blockstore..."), QT_TRANSLATE_NOOP("monkecoin-core", "Reducing -maxconnections from %d to %d, because of system limitations."), QT_TRANSLATE_NOOP("monkecoin-core", "Replaying blocks..."), QT_TRANSLATE_NOOP("monkecoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("monkecoin-core", "Rewinding blocks..."), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Failed to execute statement to verify database: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Failed to fetch sqlite wallet schema version: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Failed to fetch the application id: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Failed to prepare statement to verify database: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Failed to read database verification error: %s"), QT_TRANSLATE_NOOP("monkecoin-core", "SQLiteDatabase: Unexpected application id. Expected %u, got %u"), QT_TRANSLATE_NOOP("monkecoin-core", "Section [%s] is not recognized."), QT_TRANSLATE_NOOP("monkecoin-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("monkecoin-core", "Specified -walletdir \"%s\" does not exist"), QT_TRANSLATE_NOOP("monkecoin-core", "Specified -walletdir \"%s\" is a relative path"), QT_TRANSLATE_NOOP("monkecoin-core", "Specified -walletdir \"%s\" is not a directory"), QT_TRANSLATE_NOOP("monkecoin-core", "Specified blocks directory \"%s\" does not exist."), QT_TRANSLATE_NOOP("monkecoin-core", "Starting network threads..."), QT_TRANSLATE_NOOP("monkecoin-core", "The source code is available from %s."), QT_TRANSLATE_NOOP("monkecoin-core", "The specified config file %s does not exist\n"), QT_TRANSLATE_NOOP("monkecoin-core", "The transaction amount is too small to pay the fee"), QT_TRANSLATE_NOOP("monkecoin-core", "The wallet will avoid paying less than the minimum relay fee."), QT_TRANSLATE_NOOP("monkecoin-core", "This is experimental software."), QT_TRANSLATE_NOOP("monkecoin-core", "This is the minimum transaction fee you pay on every transaction."), QT_TRANSLATE_NOOP("monkecoin-core", "This is the transaction fee you will pay if you send a transaction."), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction amounts must not be negative"), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction fee and change calculation failed"), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction has too long of a mempool chain"), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction must have at least one recipient"), QT_TRANSLATE_NOOP("monkecoin-core", "Transaction too large"), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to bind to %s on this computer. %s is probably already running."), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to create the PID file '%s': %s"), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to generate initial keys"), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to generate keys"), QT_TRANSLATE_NOOP("monkecoin-core", "Unable to start HTTP server. See debug log for details."), QT_TRANSLATE_NOOP("monkecoin-core", "Unknown -blockfilterindex value %s."), QT_TRANSLATE_NOOP("monkecoin-core", "Unknown address type '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Unknown change type '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("monkecoin-core", "Unsupported logging category %s=%s."), QT_TRANSLATE_NOOP("monkecoin-core", "Upgrading UTXO database"), QT_TRANSLATE_NOOP("monkecoin-core", "Upgrading txindex database"), QT_TRANSLATE_NOOP("monkecoin-core", "User Agent comment (%s) contains unsafe characters."), QT_TRANSLATE_NOOP("monkecoin-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("monkecoin-core", "Verifying wallet(s)..."), QT_TRANSLATE_NOOP("monkecoin-core", "Wallet needed to be rewritten: restart %s to complete"), QT_TRANSLATE_NOOP("monkecoin-core", "Warning: unknown new rules activated (versionbit %i)"), };
#include <sstream> #include <vector> #include <iostream> #include <cstring> using namespace std; vector<int> parseInts(string str) { // Complete this function stringstream sso(str); vector<int> result; char ch; int tmp; while(sso>>tmp) { result.push_back(tmp); sso>>ch; } return result; } int main() { string str; cin >> str; vector<int> integers = parseInts(str); for(int i = 0; i < integers.size(); i++) { cout << integers[i] << "\n"; } return 0; }
/* * * Copyright (c) 2021 Project CHIP 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 <crypto/CHIPCryptoPAL.h> #include <credentials/CHIPCert.h> #include <credentials/CertificationDeclaration.h> #include <credentials/DeviceAttestationCredsProvider.h> #include <credentials/DeviceAttestationVerifier.h> #include <credentials/examples/DefaultDeviceAttestationVerifier.h> #include <credentials/examples/DeviceAttestationCredsExample.h> #include <lib/core/CHIPError.h> #include <lib/support/CHIPMem.h> #include <lib/support/Span.h> #include <lib/support/UnitTestRegistration.h> #include <nlunit-test.h> using namespace chip; using namespace chip::Crypto; using namespace chip::Credentials; namespace { constexpr uint8_t kExpectedDacPublicKey[] = { 0x04, 0x7a, 0x84, 0x58, 0xaf, 0xbb, 0x9b, 0xcd, 0x15, 0xe1, 0x9a, 0xdc, 0xd2, 0x66, 0xf6, 0x6c, 0x9c, 0x2f, 0x60, 0x7c, 0x74, 0x74, 0x7a, 0x35, 0xf8, 0x0f, 0x37, 0xe1, 0x18, 0x13, 0x3f, 0x80, 0xf1, 0x76, 0x01, 0x13, 0x27, 0x8f, 0x91, 0xf1, 0x5a, 0xa0, 0xf7, 0xf8, 0x79, 0x32, 0x09, 0x4f, 0xe6, 0x9f, 0xb7, 0x28, 0x68, 0xa8, 0x1e, 0x26, 0x97, 0x9b, 0x36, 0x8b, 0x33, 0xb5, 0x54, 0x31, 0x03 }; constexpr uint8_t kExpectedPaiPublicKey[] = { 0x04, 0xca, 0x73, 0xce, 0x46, 0x41, 0xbf, 0x08, 0x3b, 0x4a, 0x33, 0x8d, 0xa0, 0x43, 0x1a, 0x0a, 0x32, 0x30, 0x7f, 0x66, 0xd1, 0x60, 0x57, 0x4b, 0x66, 0x12, 0x2f, 0x25, 0x06, 0xcf, 0x6a, 0xd3, 0x70, 0xe3, 0x7f, 0x65, 0xd6, 0x34, 0x7a, 0xe7, 0x97, 0xa1, 0x97, 0x26, 0x50, 0x50, 0x97, 0x6d, 0x34, 0xac, 0x7b, 0x63, 0x7b, 0x3b, 0xda, 0x0b, 0x5b, 0xd8, 0x43, 0xed, 0x8e, 0x5d, 0x5e, 0x9b, 0xf2 }; } // namespace static void TestDACProvidersExample_Providers(nlTestSuite * inSuite, void * inContext) { uint8_t der_cert_buf[kMaxDERCertLength]; MutableByteSpan der_cert_span(der_cert_buf); // Make sure default provider exists and is not implemented on at least one method DeviceAttestationCredentialsProvider * default_provider = GetDeviceAttestationCredentialsProvider(); NL_TEST_ASSERT(inSuite, default_provider != nullptr); CHIP_ERROR err = default_provider->GetDeviceAttestationCert(der_cert_span); NL_TEST_ASSERT(inSuite, err == CHIP_ERROR_NOT_IMPLEMENTED); // Replace default provider with example provider DeviceAttestationCredentialsProvider * example_dac_provider = Examples::GetExampleDACProvider(); NL_TEST_ASSERT(inSuite, example_dac_provider != nullptr); NL_TEST_ASSERT(inSuite, default_provider != example_dac_provider); SetDeviceAttestationCredentialsProvider(example_dac_provider); default_provider = GetDeviceAttestationCredentialsProvider(); NL_TEST_ASSERT(inSuite, default_provider == example_dac_provider); // Make sure DAC is what we expect, by validating public key memset(der_cert_span.data(), 0, der_cert_span.size()); err = example_dac_provider->GetDeviceAttestationCert(der_cert_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); P256PublicKey dac_public_key; err = ExtractPubkeyFromX509Cert(der_cert_span, dac_public_key); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, dac_public_key.Length() == sizeof(kExpectedDacPublicKey)); NL_TEST_ASSERT(inSuite, 0 == memcmp(dac_public_key.ConstBytes(), kExpectedDacPublicKey, sizeof(kExpectedDacPublicKey))); // Make sure PAI is what we expect, by validating public key der_cert_span = MutableByteSpan{ der_cert_span }; memset(der_cert_span.data(), 0, der_cert_span.size()); err = example_dac_provider->GetProductAttestationIntermediateCert(der_cert_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); P256PublicKey pai_public_key; err = ExtractPubkeyFromX509Cert(der_cert_span, pai_public_key); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, pai_public_key.Length() == sizeof(kExpectedPaiPublicKey)); NL_TEST_ASSERT(inSuite, 0 == memcmp(pai_public_key.ConstBytes(), kExpectedPaiPublicKey, sizeof(kExpectedPaiPublicKey))); // Check for CD presence uint8_t other_data_buf[256]; MutableByteSpan other_data_span(other_data_buf); memset(other_data_span.data(), 0, other_data_span.size()); err = example_dac_provider->GetCertificationDeclaration(other_data_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, other_data_span.size() > 0); NL_TEST_ASSERT(inSuite, other_data_span.data()[0] != 0); // Check for firmware information presence other_data_span = MutableByteSpan{ other_data_buf }; memset(other_data_span.data(), 0, other_data_span.size()); err = example_dac_provider->GetFirmwareInformation(other_data_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, other_data_span.size() == 0); } static void TestDACProvidersExample_Signature(nlTestSuite * inSuite, void * inContext) { constexpr uint8_t kExampleDigest[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37 }; DeviceAttestationCredentialsProvider * example_dac_provider = Examples::GetExampleDACProvider(); NL_TEST_ASSERT(inSuite, example_dac_provider != nullptr); // Sign using the example attestation private key P256ECDSASignature da_signature; MutableByteSpan out_sig_span(da_signature.Bytes(), da_signature.Capacity()); CHIP_ERROR err = example_dac_provider->SignWithDeviceAttestationKey(ByteSpan{ kExampleDigest }, out_sig_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, out_sig_span.size() == kP256_ECDSA_Signature_Length_Raw); da_signature.SetLength(out_sig_span.size()); // Get DAC from the provider uint8_t dac_cert_buf[kMaxDERCertLength]; MutableByteSpan dac_cert_span(dac_cert_buf); memset(dac_cert_span.data(), 0, dac_cert_span.size()); err = example_dac_provider->GetDeviceAttestationCert(dac_cert_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); // Extract public key from DAC, prior to signature verification P256PublicKey dac_public_key; err = ExtractPubkeyFromX509Cert(dac_cert_span, dac_public_key); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, dac_public_key.Length() == sizeof(kExpectedDacPublicKey)); NL_TEST_ASSERT(inSuite, 0 == memcmp(dac_public_key.ConstBytes(), kExpectedDacPublicKey, sizeof(kExpectedDacPublicKey))); // Verify round trip signature err = dac_public_key.ECDSA_validate_hash_signature(&kExampleDigest[0], sizeof(kExampleDigest), da_signature); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); } static void TestDACVerifierExample_AttestationInfoVerification(nlTestSuite * inSuite, void * inContext) { CHIP_ERROR err = CHIP_NO_ERROR; uint8_t attestationElementsTestVector[] = { 0x15, 0x30, 0x01, 0xeb, 0x30, 0x81, 0xe8, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02, 0xa0, 0x81, 0xda, 0x30, 0x81, 0xd7, 0x02, 0x01, 0x03, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x45, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x01, 0xa0, 0x38, 0x04, 0x36, 0x15, 0x24, 0x00, 0x01, 0x25, 0x01, 0xf1, 0xff, 0x36, 0x02, 0x05, 0x00, 0x80, 0x18, 0x25, 0x03, 0x34, 0x12, 0x2c, 0x04, 0x13, 0x5a, 0x49, 0x47, 0x32, 0x30, 0x31, 0x34, 0x31, 0x5a, 0x42, 0x33, 0x33, 0x30, 0x30, 0x30, 0x31, 0x2d, 0x32, 0x34, 0x24, 0x05, 0x00, 0x24, 0x06, 0x00, 0x25, 0x07, 0x94, 0x26, 0x24, 0x08, 0x00, 0x18, 0x31, 0x7c, 0x30, 0x7a, 0x02, 0x01, 0x03, 0x80, 0x14, 0x62, 0xfa, 0x82, 0x33, 0x59, 0xac, 0xfa, 0xa9, 0x96, 0x3e, 0x1c, 0xfa, 0x14, 0x0a, 0xdd, 0xf5, 0x04, 0xf3, 0x71, 0x60, 0x30, 0x0b, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x04, 0x46, 0x30, 0x44, 0x02, 0x20, 0x43, 0xa6, 0x3f, 0x2b, 0x94, 0x3d, 0xf3, 0x3c, 0x38, 0xb3, 0xe0, 0x2f, 0xca, 0xa7, 0x5f, 0xe3, 0x53, 0x2a, 0xeb, 0xbf, 0x5e, 0x63, 0xf5, 0xbb, 0xdb, 0xc0, 0xb1, 0xf0, 0x1d, 0x3c, 0x4f, 0x60, 0x02, 0x20, 0x4c, 0x1a, 0xbf, 0x5f, 0x18, 0x07, 0xb8, 0x18, 0x94, 0xb1, 0x57, 0x6c, 0x47, 0xe4, 0x72, 0x4e, 0x4d, 0x96, 0x6c, 0x61, 0x2e, 0xd3, 0xfa, 0x25, 0xc1, 0x18, 0xc3, 0xf2, 0xb3, 0xf9, 0x03, 0x69, 0x30, 0x02, 0x20, 0xe0, 0x42, 0x1b, 0x91, 0xc6, 0xfd, 0xcd, 0xb4, 0x0e, 0x2a, 0x4d, 0x2c, 0xf3, 0x1d, 0xb2, 0xb4, 0xe1, 0x8b, 0x41, 0x1b, 0x1d, 0x3a, 0xd4, 0xd1, 0x2a, 0x9d, 0x90, 0xaa, 0x8e, 0x52, 0xfa, 0xe2, 0x26, 0x03, 0xfd, 0xc6, 0x5b, 0x28, 0xd0, 0xf1, 0xff, 0x3e, 0x00, 0x01, 0x00, 0x17, 0x73, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x5f, 0x76, 0x65, 0x6e, 0x64, 0x6f, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x31, 0xd0, 0xf1, 0xff, 0x3e, 0x00, 0x03, 0x00, 0x18, 0x76, 0x65, 0x6e, 0x64, 0x6f, 0x72, 0x5f, 0x72, 0x65, 0x73, 0x65, 0x72, 0x76, 0x65, 0x64, 0x33, 0x5f, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x18 }; uint8_t attestationChallengeTestVector[] = { 0x7a, 0x49, 0x53, 0x05, 0xd0, 0x77, 0x79, 0xa4, 0x94, 0xdd, 0x39, 0xa0, 0x85, 0x1b, 0x66, 0x0d }; uint8_t attestationSignatureTestVector[] = { 0x79, 0x82, 0x53, 0x5d, 0x24, 0xcf, 0xe1, 0x4a, 0x71, 0xab, 0x04, 0x24, 0xcf, 0x0b, 0xac, 0xf1, 0xe3, 0x45, 0x48, 0x7e, 0xd5, 0x0f, 0x1a, 0xc0, 0xbc, 0x25, 0x9e, 0xcc, 0xfb, 0x39, 0x08, 0x1e, 0x61, 0xa9, 0x26, 0x7e, 0x74, 0xf8, 0x55, 0xda, 0x53, 0x63, 0x83, 0x74, 0xa0, 0x16, 0x71, 0xcf, 0x3d, 0x7d, 0xb8, 0xcc, 0x17, 0x0b, 0x38, 0x03, 0x45, 0xe6, 0x0b, 0xc8, 0x6f, 0xdf, 0x45, 0x9e }; uint8_t attestationNonceTestVector[] = { 0xe0, 0x42, 0x1b, 0x91, 0xc6, 0xfd, 0xcd, 0xb4, 0x0e, 0x2a, 0x4d, 0x2c, 0xf3, 0x1d, 0xb2, 0xb4, 0xe1, 0x8b, 0x41, 0x1b, 0x1d, 0x3a, 0xd4, 0xd1, 0x2a, 0x9d, 0x90, 0xaa, 0x8e, 0x52, 0xfa, 0xe2 }; // Make sure default verifier exists and is not implemented on at least one method DeviceAttestationVerifier * default_verifier = GetDeviceAttestationVerifier(); NL_TEST_ASSERT(inSuite, default_verifier != nullptr); AttestationVerificationResult attestation_result = default_verifier->VerifyAttestationInformation(ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan(), ByteSpan()); NL_TEST_ASSERT(inSuite, attestation_result == AttestationVerificationResult::kNotImplemented); // Replace default verifier with example verifier DeviceAttestationVerifier * example_dac_verifier = GetDefaultDACVerifier(); NL_TEST_ASSERT(inSuite, example_dac_verifier != nullptr); NL_TEST_ASSERT(inSuite, default_verifier != example_dac_verifier); SetDeviceAttestationVerifier(example_dac_verifier); default_verifier = GetDeviceAttestationVerifier(); NL_TEST_ASSERT(inSuite, default_verifier == example_dac_verifier); DeviceAttestationCredentialsProvider * example_dac_provider = Examples::GetExampleDACProvider(); NL_TEST_ASSERT(inSuite, example_dac_provider != nullptr); SetDeviceAttestationCredentialsProvider(example_dac_provider); DeviceAttestationCredentialsProvider * default_provider = GetDeviceAttestationCredentialsProvider(); NL_TEST_ASSERT(inSuite, default_provider == example_dac_provider); uint8_t dac[kMaxDERCertLength]; uint8_t pai[kMaxDERCertLength]; MutableByteSpan dac_span(dac); MutableByteSpan pai_span(pai); err = default_provider->GetDeviceAttestationCert(dac_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); err = default_provider->GetProductAttestationIntermediateCert(pai_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); attestation_result = default_verifier->VerifyAttestationInformation( ByteSpan(attestationElementsTestVector), ByteSpan(attestationChallengeTestVector), ByteSpan(attestationSignatureTestVector), pai_span, dac_span, ByteSpan(attestationNonceTestVector)); NL_TEST_ASSERT(inSuite, attestation_result == AttestationVerificationResult::kSuccess); } static void TestDACVerifierExample_CertDeclarationVerification(nlTestSuite * inSuite, void * inContext) { // -> format_version = 1 // -> vendor_id = 0xFFF1 // -> product_id_array = [ 0x8000 ] // -> device_type_id = 0x1234 // -> certificate_id = "ZIG20141ZB330001-24" // -> security_level = 0 // -> security_information = 0 // -> version_number = 0x2694 // -> certification_type = 0 // -> dac_origin_vendor_id is not present // -> dac_origin_product_id is not present static constexpr CertificationElements sTestCMS_CertElements = { 1, 0xFFF1, { 0x8000 }, 1, 0x1234, "ZIG20141ZB330001-24", 0, 0, 0x2694, 0, 0, 0, false }; static constexpr uint8_t sTestCMS_CDContent[] = { 0x15, 0x24, 0x00, 0x01, 0x25, 0x01, 0xf1, 0xff, 0x36, 0x02, 0x05, 0x00, 0x80, 0x18, 0x25, 0x03, 0x34, 0x12, 0x2c, 0x04, 0x13, 0x5a, 0x49, 0x47, 0x32, 0x30, 0x31, 0x34, 0x31, 0x5a, 0x42, 0x33, 0x33, 0x30, 0x30, 0x30, 0x31, 0x2d, 0x32, 0x34, 0x24, 0x05, 0x00, 0x24, 0x06, 0x00, 0x25, 0x07, 0x94, 0x26, 0x24, 0x08, 0x00, 0x18 }; CHIP_ERROR err = CHIP_NO_ERROR; // Replace default verifier with example verifier DeviceAttestationVerifier * example_dac_verifier = GetDefaultDACVerifier(); NL_TEST_ASSERT(inSuite, example_dac_verifier != nullptr); SetDeviceAttestationVerifier(example_dac_verifier); DeviceAttestationVerifier * default_verifier = GetDeviceAttestationVerifier(); NL_TEST_ASSERT(inSuite, default_verifier == example_dac_verifier); DeviceAttestationCredentialsProvider * example_dac_provider = Examples::GetExampleDACProvider(); NL_TEST_ASSERT(inSuite, example_dac_provider != nullptr); SetDeviceAttestationCredentialsProvider(example_dac_provider); DeviceAttestationCredentialsProvider * default_provider = GetDeviceAttestationCredentialsProvider(); NL_TEST_ASSERT(inSuite, default_provider == example_dac_provider); // Check for CD presence uint8_t cd_data_buf[kMaxCMSSignedCDMessage] = { 0 }; MutableByteSpan cd_data_span(cd_data_buf); err = example_dac_provider->GetCertificationDeclaration(cd_data_span); NL_TEST_ASSERT(inSuite, err == CHIP_NO_ERROR); NL_TEST_ASSERT(inSuite, cd_data_span.size() > 0); NL_TEST_ASSERT(inSuite, cd_data_span.data()[0] != 0); ByteSpan cd_payload; AttestationVerificationResult attestation_result = default_verifier->ValidateCertificationDeclarationSignature(cd_data_span, cd_payload); NL_TEST_ASSERT(inSuite, attestation_result == AttestationVerificationResult::kSuccess); NL_TEST_ASSERT(inSuite, cd_payload.data_equal(ByteSpan(sTestCMS_CDContent))); DeviceInfoForAttestation deviceInfo{ .vendorId = sTestCMS_CertElements.VendorId, .productId = sTestCMS_CertElements.ProductIds[0], .dacVendorId = sTestCMS_CertElements.VendorId, .dacProductId = sTestCMS_CertElements.ProductIds[0], .paiVendorId = sTestCMS_CertElements.VendorId, .paiProductId = sTestCMS_CertElements.ProductIds[0], .paaVendorId = sTestCMS_CertElements.VendorId, }; attestation_result = default_verifier->ValidateCertificateDeclarationPayload(cd_payload, ByteSpan(), deviceInfo); NL_TEST_ASSERT(inSuite, attestation_result == AttestationVerificationResult::kSuccess); } /** * Set up the test suite. */ int TestDeviceAttestation_Setup(void * inContext) { CHIP_ERROR error = chip::Platform::MemoryInit(); if (error != CHIP_NO_ERROR) { return FAILURE; } return SUCCESS; } /** * Tear down the test suite. */ int TestDeviceAttestation_Teardown(void * inContext) { chip::Platform::MemoryShutdown(); return SUCCESS; } /** * Test Suite. It lists all the test functions. */ // clang-format off static const nlTest sTests[] = { NL_TEST_DEF("Test Example Device Attestation Credentials Providers", TestDACProvidersExample_Providers), NL_TEST_DEF("Test Example Device Attestation Signature", TestDACProvidersExample_Signature), NL_TEST_DEF("Test Example Device Attestation Information Verification", TestDACVerifierExample_AttestationInfoVerification), NL_TEST_DEF("Test Example Device Attestation Certification Declaration Verification", TestDACVerifierExample_CertDeclarationVerification), NL_TEST_SENTINEL() }; // clang-format on int TestDeviceAttestation() { // clang-format off nlTestSuite theSuite = { "Device Attestation Credentials", &sTests[0], TestDeviceAttestation_Setup, TestDeviceAttestation_Teardown }; // clang-format on nlTestRunner(&theSuite, nullptr); return (nlTestRunnerStats(&theSuite)); } CHIP_REGISTER_TEST_SUITE(TestDeviceAttestation);
// -*- C++ -*- // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Michael A.G. Aivazis // California Institute of Technology // (C) 1998-2003 All Rights Reserved // // <LicenseText> // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #include <portinfo> #include <Python.h> PyObject *pyjournal_runtimeError = 0; // version // $Id$ // End of file
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vpu/frontend/frontend.hpp> #include <memory> #include <string> #include <set> #include <vector> #include <utility> #include <vpu/compile_env.hpp> namespace vpu { namespace { class ConvertStage final : public StageNode { protected: StagePtr cloneImpl() const override { return std::make_shared<ConvertStage>(*this); } void propagateScaleFactorsImpl( const SmallVector<float>& inputScales, ScalePropagationStep step, StageDataInfo<float>& scaleInfo) override { auto input = inputEdge(0)->input(); auto output = outputEdge(0)->output(); auto inputScale = inputScales[0]; if (_type == StageType::Convert_f16f32) { IE_ASSERT(output->usage() == DataUsage::Output); IE_ASSERT(step == ScalePropagationStep::Propagate); scaleInfo.setInput(inputEdge(0), 1.0f); scaleInfo.setOutput(outputEdge(0), 1.0f); } else { IE_ASSERT(input->usage() == DataUsage::Input); scaleInfo.setOutput(outputEdge(0), inputScale); if (step == ScalePropagationStep::ScaleInput) { attrs().get<float>("scale") *= inputScale; attrs().get<float>("bias") *= inputScale; } } } void propagateDataOrderImpl(StageDataInfo<DimsOrder>& orderInfo) override { auto input = inputEdge(0)->input(); auto output = outputEdge(0)->output(); if (_type == StageType::Convert_f16f32) { IE_ASSERT(output->usage() == DataUsage::Output || output->usage() == DataUsage::Intermediate); auto outDimsOrder = output->desc().dimsOrder(); // HCW is not supported IE_ASSERT(outDimsOrder.dimInd(Dim::C) != 1); orderInfo.setInput(inputEdge(0), outDimsOrder); } else { IE_ASSERT(input->usage() == DataUsage::Input || input->usage() == DataUsage::Intermediate); auto inDimsOrder = input->desc().dimsOrder(); // HCW is not supported IE_ASSERT(inDimsOrder.dimInd(Dim::C) != 1); orderInfo.setOutput(outputEdge(0), inDimsOrder); } } void getDataStridesRequirementsImpl(StageDataInfo<StridesRequirement>& stridesInfo) override { auto input = inputEdge(0)->input(); auto output = outputEdge(0)->output(); auto inDimsOrder = input->desc().dimsOrder(); StridesRequirement reqs; if (input->desc().dim(Dim::N, 1) > 1) { // To merge batch into previous dimension. reqs.add(inDimsOrder.dimInd(Dim::N), DimStride::Compact); } if (_type == StageType::Convert_f16f32) { IE_ASSERT(output->usage() == DataUsage::Output || output->usage() == DataUsage::Intermediate); stridesInfo.setInput(inputEdge(0), reqs); stridesInfo.setOutput(outputEdge(0), StridesRequirement::compact()); } else { IE_ASSERT(input->usage() == DataUsage::Input || input->usage() == DataUsage::Intermediate); stridesInfo.setInput(inputEdge(0), StridesRequirement::compact()); stridesInfo.setOutput(outputEdge(0), reqs); } } void finalizeDataLayoutImpl() override { } void getBatchSupportInfoImpl(StageDataInfo<BatchSupport>& batchInfo) override { // Convert will support batch by merging it with previous dimension. } StageSHAVEsRequirements getSHAVEsRequirementsImpl() const override { // TODO: more SHAVEs leads to hang on public MTCNN network with U8 input return StageSHAVEsRequirements::TwoOrOne; } void initialCheckImpl() const override { const auto expectedTypes = EnumMap<StageType, std::pair<DataType, DataType>>{ {StageType::Convert_u8f16, {DataType::U8, DataType::FP16}}, {StageType::Convert_f16f32, {DataType::FP16, DataType::FP32}}, {StageType::Convert_f32f16, {DataType::FP32, DataType::FP16}}, }; auto match = expectedTypes.find(_type); if (match == expectedTypes.end()) { VPU_THROW_EXCEPTION << "unknown type"; } const auto& types = match->second; const auto& srcType = types.first; const auto& dstType = types.second; assertInputsOutputsTypes(this, {{srcType}}, {{dstType}}); } void serializeParamsImpl(BlobSerializer& serializer) const override { auto scale = attrs().get<float>("scale"); auto bias = attrs().get<float>("bias"); auto convertFromDetOutput = attrs().getOrDefault<bool>("convertFromDetOutput", false); auto haveBatch = attrs().getOrDefault<bool>("haveBatch", true); serializer.append(static_cast<float>(scale)); serializer.append(static_cast<float>(bias)); serializer.append(static_cast<int32_t>(convertFromDetOutput)); serializer.append(static_cast<int32_t>(haveBatch)); } void serializeDataImpl(BlobSerializer& serializer) const override { auto input = inputEdge(0)->input(); auto output = outputEdge(0)->output(); if (input->desc().dimsOrder() == DimsOrder::NC) { input->serializeOldBuffer( handle_from_this(), serializer, DimsOrder::HWC, { {Dim::W, {Dim::N}}, {Dim::C, {Dim::C}} }); output->serializeOldBuffer( handle_from_this(), serializer, DimsOrder::HWC, { {Dim::W, {Dim::N}}, {Dim::C, {Dim::C}} }); } else if (input->desc().dim(Dim::N, 1) > 1) { auto perm = input->desc().dimsOrder().toPermutation(); IE_ASSERT(perm.size() == 4); auto batchDimInd = input->desc().dimsOrder().dimInd(Dim::N); IE_ASSERT(batchDimInd == perm.size() - 1); input->serializeOldBuffer( handle_from_this(), serializer, DimsOrder::HWC, { {Dim::H, {perm[2], perm[3]}}, {Dim::W, {perm[1]}}, {Dim::C, {perm[0]}} }); output->serializeOldBuffer( handle_from_this(), serializer, DimsOrder::HWC, { {Dim::H, {perm[2], perm[3]}}, {Dim::W, {perm[1]}}, {Dim::C, {perm[0]}} }); } else { input->serializeOldBuffer(handle_from_this(), serializer); output->serializeOldBuffer(handle_from_this(), serializer); } } }; } // namespace Stage StageBuilder::createConvertStage( const Model::Ptr& model, const std::string& name, const Data& input, const Data& output, StageType type, float scale, float bias) { auto stage = model->addNewStage<ConvertStage>( name, type, nullptr, {input}, {output}); stage->attrs().set("scale", scale); stage->attrs().set("bias", bias); return stage; } void FrontEnd::addDataTypeConvertStages(const Model::Ptr& model) { VPU_PROFILE(addDataTypeConvertStages); const auto& env = CompileEnv::get(); if (env.config.inputScale != 1.f) { env.log->warning("[VPU] GraphTransformer : INPUT_NORM option is deprecated"); } if (env.config.inputBias != 0.f) { env.log->warning("[VPU] GraphTransformer : INPUT_BIAS option is deprecated"); } const bool hasScaleBias = env.config.inputScale != 1.0f || env.config.inputBias != 0.0f; for (const auto& input : model->datas()) { if (input->usage() != DataUsage::Input) continue; const auto& type = input->desc().type(); if (type == DataType::FP16 && hasScaleBias) { std::ostringstream postfixOstr; if (env.config.inputScale != 1.0f) { postfixOstr << "@SCALE=" << std::to_string(env.config.inputScale); } if (env.config.inputBias != 0.0f) { postfixOstr << "@BIAS=" << std::to_string(env.config.inputBias); } auto postfix = postfixOstr.str(); auto scaledInput = model->duplicateData( input, postfix); bindData(scaledInput, input->origData()); _stageBuilder->addPowerStage( model, scaledInput->name(), nullptr, env.config.inputScale, 1.0f, env.config.inputBias, input, scaledInput); } if (type != DataType::FP32 && type != DataType::U8) { continue; } env.log->debug("convert input %s to FP16", input->name()); auto fp16Desc = input->desc(); fp16Desc.setType(DataType::FP16); auto inputFP16 = model->duplicateData( input, "@FP16", fp16Desc); input->attrs().set<Data>("fp16_copy", inputFP16); bindData(inputFP16, input->origData()); auto stageType = StageType::None; switch (input->desc().type()) { case DataType::U8: stageType = StageType::Convert_u8f16; break; case DataType::FP32: stageType = StageType::Convert_f32f16; break; default: VPU_THROW_EXCEPTION << "Unsupported input data type : " << input->desc().type(); } _stageBuilder->createConvertStage( model, inputFP16->name(), input, inputFP16, stageType, env.config.inputScale, env.config.inputBias); } for (const auto& output : model->datas()) { if (output->usage() != DataUsage::Output) continue; const auto& actualType = output->desc().type(); if (actualType != DataType::FP32) { // Output datas keep their precision (intermeadiate have been forced to FP16 in case of FP32 from IR). // If FP32 output has been requested VPU executes in FP16 with following convert FP16 -> FP32 continue; } env.log->debug("convert output %s from FP16", output->name()); auto fp16Desc = output->desc(); fp16Desc.setType(DataType::FP16); auto outputFP16 = model->duplicateData( output, "@FP16", fp16Desc); output->attrs().set<Data>("fp16_copy", outputFP16); bindData(outputFP16, output->origData()); auto stage = _stageBuilder->createConvertStage( model, outputFP16->name(), outputFP16, output, StageType::Convert_f16f32); auto withDetectionOutput = model->attrs().getOrDefault<bool>("withDetectionOutput", false); stage->attrs().set<bool>("convertFromDetOutput", withDetectionOutput); auto haveBatch = _unbatchedOutputs.count(output->origData()) == 0; stage->attrs().set<bool>("haveBatch", haveBatch); } } } // namespace vpu
/* * Copyright (c) 2008-2018 SLIBIO <https://github.com/SLIBIO> * * 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 "slib/core/definition.h" #if defined(SLIB_PLATFORM_IS_WINDOWS) #include "slib/core/time.h" #include "slib/core/platform_windows.h" namespace slib { sl_bool Time::_get(TimeComponents& output, sl_bool flagUTC) const noexcept { SYSTEMTIME st; if (!(Windows::getSYSTEMTIME(*this, flagUTC, &st))) { return sl_false; } output.year = st.wYear; output.month = (sl_uint8)(st.wMonth); output.day = (sl_uint8)(st.wDay); output.dayOfWeek = (sl_uint8)(st.wDayOfWeek); output.hour = (sl_uint8)(st.wHour); output.minute = (sl_uint8)(st.wMinute); output.second = (sl_uint8)(st.wSecond); return sl_true; } sl_int64 Time::_set(sl_int32 year, sl_int32 month, sl_int32 day, sl_int32 hour, sl_int32 minute, sl_int32 second, sl_bool flagUTC) noexcept { SYSTEMTIME st; st.wYear = (WORD)year; st.wMonth = (WORD)month; st.wDay = (WORD)day; st.wDayOfWeek = 0; st.wHour = (WORD)hour; st.wMinute = (WORD)minute; st.wSecond = (WORD)second; st.wMilliseconds = 0; return Windows::getTime(&st, flagUTC).toInt(); } void Time::_setNow() noexcept { SYSTEMTIME st; GetSystemTime(&st); sl_int64 n; SystemTimeToFileTime(&st, (PFILETIME)&n); m_time = n / 10 - SLIB_INT64(11644473600000000); // Convert 1601 Based (FILETIME mode) to 1970 Based (time_t mode) } sl_bool Time::_setToSystem() const noexcept { #if defined(SLIB_PLATFORM_IS_WIN32) SYSTEMTIME st; sl_int64 n = (m_time + SLIB_INT64(11644473600000000)) * 10; // Convert 1970 Based (time_t mode) to 1601 Based (FILETIME mode) if (!(FileTimeToSystemTime((PFILETIME)&n, &st))) { return sl_false; } return 0 != SetSystemTime(&st); #else return sl_false; #endif } } #endif
/* DHT library MIT license written by Adafruit Industries */ #include "DHT.h" DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { _pin = pin; _type = type; _count = count; firstreading = true; } void DHT::begin(void) { // set up the pins! pinMode(_pin, INPUT); digitalWrite(_pin, HIGH); _lastreadtime = 0; } //boolean S == Scale. True == Farenheit; False == Celcius float DHT::readTemperature(bool S) { float f; if (read()) { switch (_type) { case DHT11: f = data[2]; if (S) f = convertCtoF(f); return f; case DHT22: case DHT21: f = data[2] & 0x7F; f *= 256; f += data[3]; f /= 10; if (data[2] & 0x80) f *= -1; if (S) f = convertCtoF(f); return f; } } Serial.print("Read fail"); return NAN; } float DHT::convertCtoF(float c) { return c * 9 / 5 + 32; } float DHT::readHumidity(void) { float f; if (read()) { switch (_type) { case DHT11: f = data[0]; return f; case DHT22: case DHT21: f = data[0]; f *= 256; f += data[1]; f /= 10; return f; } } Serial.print("Read fail"); return NAN; } boolean DHT::read(void) { uint8_t laststate = HIGH; uint8_t counter = 0; uint8_t j = 0, i; unsigned long currenttime; // pull the pin high and wait 250 milliseconds digitalWrite(_pin, HIGH); delay(250); currenttime = millis(); if (currenttime < _lastreadtime) { // ie there was a rollover _lastreadtime = 0; } if (!firstreading && ((currenttime - _lastreadtime) < 2000)) { return true; // return last correct measurement //delay(2000 - (currenttime - _lastreadtime)); } firstreading = false; /* Serial.print("Currtime: "); Serial.print(currenttime); Serial.print(" Lasttime: "); Serial.print(_lastreadtime); */ _lastreadtime = millis(); data[0] = data[1] = data[2] = data[3] = data[4] = 0; // now pull it low for ~20 milliseconds pinMode(_pin, OUTPUT); digitalWrite(_pin, LOW); delay(20); cli(); digitalWrite(_pin, HIGH); delayMicroseconds(40); pinMode(_pin, INPUT); // read in timings for (i = 0; i < MAXTIMINGS; i++) { counter = 0; while (digitalRead(_pin) == laststate) { counter++; delayMicroseconds(1); if (counter == 255) { break; } } laststate = digitalRead(_pin); if (counter == 255) break; // ignore first 3 transitions if ((i >= 4) && (i % 2 == 0)) { // shove each bit into the storage bytes data[j / 8] <<= 1; if (counter > _count) data[j / 8] |= 1; j++; } } sei(); /* Serial.println(j, DEC); Serial.print(data[0], HEX); Serial.print(", "); Serial.print(data[1], HEX); Serial.print(", "); Serial.print(data[2], HEX); Serial.print(", "); Serial.print(data[3], HEX); Serial.print(", "); Serial.print(data[4], HEX); Serial.print(" =? "); Serial.println(data[0] + data[1] + data[2] + data[3], HEX); */ // check we read 40 bits and that the checksum matches if ((j >= 40) && (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF))) { return true; } return false; }
#include<bits/stdc++.h> #define IMAX 1<<29 #define PI 3.14159265359 using namespace std; #define rep_(i, a_, b_, a, b, ...) for (int i = (a), i##_len = (b); i < i##_len; ++i) #define rep(i, ...) rep_(i, __VA_ARGS__, __VA_ARGS__, 0, __VA_ARGS__) template <class T> using Graph = vector<vector<T>>; /******** Utility ***************/ int bsize(int bits, int _max){ int c = 0; for(int ix=0; ix!=_max; ++ix) if((bits&(1<<ix)) !=0){ ++c; } return c; } long factrial(long n){ assert(n >= 0); if(n <= 1) return 1; long _sum = 1; for(int ix=0; ix!=(n-1); ++ix) _sum *= n-ix; return _sum; } template<typename T> void show(vector<T> v) { for(auto _v: v) cout << _v << " "; cout << endl; } template<typename T> void show(vector<T> v, int maxrow) // 適度に改行入れるver { for(int ix=0; ix!=v.size(); ++ix){ if(ix!=0 && ix%maxrow==0) cout << endl; cout << v[ix] << " "; } cout << endl; } template<typename T> void show2(vector<vector<T>> v) { int ix = 0; for(auto __v: v){ cout << "[" << ix++ << "] ("; for(auto _v: __v){ cout << _v << ", "; } cout << ")" << endl; } } // G: Graph // v: 次に訪れる頂点 // d: 最初に頂点を見つけたタイムスタンプ(行きがけ順) // -1で初期化されている必要がある // f: ある頂点の隣接リストを探索し終えた時刻のタイムスタンプ(帰りがけ順) // -1で初期化されている必要がある // timestamp: タイムスタンプ // @return: vの隣接頂点の探索に要した時間 template<typename T> void dfs(const Graph<T> &G, int v, vector<T> &d, vector<T> &f, T &timestamp) { d[v] = timestamp++; for(auto next_v: G[v]){ // 隣接する頂点を探索 if(d[next_v] != -1){ // 既に探索済み continue; }else{ dfs(G, next_v, d, f, timestamp); // 次の頂点をDFS } } f[v] = timestamp++; } // G: Graph // dist: startからの最小距離 // start: start地点 template<typename T> void bfs(const Graph<T> &G, vector<int> &dist, const int start) { // init queue<int> que; dist.assign(dist.size(), -1); dist[start] = 0; que.push(start); // BFS while(!que.empty()){ int v = que.front(); que.pop(); for(auto next_v: G[v]){ if(dist[next_v] != -1) // 訪問済み continue; dist[next_v] = dist[v] + 1; que.push(next_v); } } } // グラフの周りに余白をつけていること前提 void genGraph(Graph<int> &G, vector<string> &board, int R, int C) { for(int row=1; row!=R-1; ++row){ for(int col=1; col!=C-1; ++col){ if(board[row][col] == '#') continue; if(board[row-1][col] == '.') G[(row-1)*C + col].push_back(row*C + col); if(board[row][col-1] == '.') G[(row)*C + col-1].push_back(row*C + col); if(board[row][col+1] == '.') G[(row)*C + col+1].push_back(row*C + col); if(board[row+1][col] == '.') G[(row+1)*C + col].push_back(row*C + col); } } } /******** end of Utility ***************/ int main(void) { // input int N; cin >> N; // main vector<string> S(N); S[0] = "1"; for (int ix = 1; ix != N; ++ix) { S[ix] = S[ix - 1] + " " + to_string(ix + 1) + " " + S[ix - 1]; } // print cout << S[N-1] << endl; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: NoteLineConnectionController #include "GlobalNamespace/NoteLineConnectionController.hpp" // Including type: Zenject.MonoMemoryPool`1 #include "Zenject/MonoMemoryPool_1.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: namespace GlobalNamespace { // WARNING Size may be invalid! // Autogenerated type: NoteLineConnectionController/Pool // [TokenAttribute] Offset: FFFFFFFF class NoteLineConnectionController::Pool : public Zenject::MonoMemoryPool_1<GlobalNamespace::NoteLineConnectionController*> { public: // Creating value type constructor for type: Pool Pool() noexcept {} // public System.Void .ctor() // Offset: 0x124D040 // Implemented from: Zenject.MonoMemoryPool`1 // Base method: System.Void MonoMemoryPool_1::.ctor() // Base method: System.Void MemoryPool_1::.ctor() // Base method: System.Void MemoryPoolBase_1::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static NoteLineConnectionController::Pool* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::NoteLineConnectionController::Pool::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<NoteLineConnectionController::Pool*, creationType>())); } }; // NoteLineConnectionController/Pool } DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::NoteLineConnectionController::Pool*, "", "NoteLineConnectionController/Pool"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: GlobalNamespace::NoteLineConnectionController::Pool::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
#include "Session.h" #include <algorithm> #include <mutex> #include <vector> using namespace std; #include <scx/CharsetHelper.h> #include <scx/IconvHelper.h> using namespace scx; #include "AppEnv.h" #include "Protocol.h" using namespace Protocol; const size_t PAYLOADBUF_MAX_KEEP = 1024; const size_t SENDOUTBUF_MAX_KEEP = 1024 * 4; const size_t MEDIAITEMS_IN_CHUNK = 20; #define SEND_PACKET(group, stream) \ { \ int payloadSize = (BufObj(nullptr) stream).Offset(); \ char* buf = GetPayloadBuffer(group, payloadSize); \ BufObj(buf) stream; \ } \ SendOut() #define SEND_PLAYER_PACKET(stream) \ SEND_PACKET(Protocol::Group::Player, stream) #define SEND_PLAYLIST_PACKET(stream) \ SEND_PACKET(Protocol::Group::Playlist, stream) #define BINARY_MASK(a, b) \ (((a) << 1) | (b)) Session::Session(ServerContext* data) : m_Context(data), m_GotReqStopService(false) { lock_guard<mutex> locker(m_Context->mtx); m_Context->sigPlayNextItem.Connect(&Session::SlotPlayNextItem, this); } Session::~Session() { m_Socket.Close(); lock_guard<mutex> locker(m_Context->mtx); m_Context->sigPlayNextItem.Disconnect(this); m_Context = nullptr; } bool Session::Run(const TcpSocket& socket, int notifyFd) { m_GotReqStopService = false; m_Socket = socket; m_NotifyFd = notifyFd; m_RecvThread = thread([this] { vector<char> headerBuf(Header::Size()); vector<char> payloadBuf; Header header(Group::None, -1); char* buf; int len; NotifySupportedSuffixes(); while (!m_GotReqStopService) { if (!m_Socket.RecvN(headerBuf.data(), headerBuf.size())) break; if (!header.Read(headerBuf.data())) break; if (header.payloadSize <= 0) continue; payloadBuf.resize(header.payloadSize); if (payloadBuf.size() > PAYLOADBUF_MAX_KEEP && (size_t)header.payloadSize <= PAYLOADBUF_MAX_KEEP) payloadBuf.shrink_to_fit(); buf = payloadBuf.data(); len = header.payloadSize; if (!m_Socket.RecvN(buf, len)) break; switch (header.group) { case Group::App: HandleApp(buf, len); break; case Group::Player: HandlePlayer(buf, len); break; case Group::Playlist: HandlePlaylist(buf, len); break; } } if (!m_GotReqStopService) { ptr_t ptr = reinterpret_cast<ptr_t>(this); write(m_NotifyFd, "q", 1); write(m_NotifyFd, &ptr, sizeof(ptr)); } }); return true; } void Session::Stop() { m_Socket.Shutdown(); if (m_RecvThread.joinable()) m_RecvThread.join(); } void Session::NotifySupportedSuffixes() { lock_guard<mutex> locker(m_Context->mtx); const auto& s1 = m_Context->player.SupportedSuffixes(); auto s2 = m_Context->loader.SupportedSuffixes(); s2.insert(s2.begin(), s1.begin(), s1.end()); SEND_PACKET((char)Protocol::Group::App, << (char)Op::App::Suffixes << s2); } void Session::HandleApp(char* buf, int len) { char op; BufObj(buf) >> op; switch (op) { case Op::App::StopService: { m_GotReqStopService = true; write(m_NotifyFd, "Q", 1); } break; default: break; } } void Session::HandlePlayer(char* _buf, int len) { if (len < 1) return; BufObj buf(_buf); char op; buf >> op; switch (op) { case Op::Player::Pause: PlayerPause(buf); break; case Op::Player::Seek: PlayerSeek(buf); break; case Op::Player::Volume: PlayerVolume(buf); break; case Op::Player::PlayMode: PlayerPlayMode(buf); break; case Op::Player::PlayNext: PlayerPlayNext(buf); break; case Op::Player::Sync: PlayerSync(buf); break; default: break; } } void Session::PlayerPause(BufObj&) { lock_guard<mutex> locker(m_Context->mtx); m_Context->PausePlayer(); SEND_PLAYER_PACKET(<< (char)Op::Player::Pause); } void Session::PlayerSeek(BufObj& buf) { char direct = buf.Fetch<char>(); lock_guard<mutex> locker(m_Context->mtx); switch (direct) { case 1: case -1: { int64_t delta = direct * 1000 * 3; uint64_t pos = m_Context->player.CurrentMs() + delta; m_Context->player.SeekTime(pos); SEND_PLAYER_PACKET(<< (char)Op::Player::Seek); } break; default: break; } } void Session::PlayerVolume(BufObj& buf) { char change = buf.Fetch<char>(); lock_guard<mutex> locker(m_Context->mtx); switch (change) { case 0: break; case 1: case -1: { int vol = m_Context->player.Volume() + change * 5; if (vol > 100) vol = 100; else if (vol < 0) vol = 0; m_Context->player.SetVolume(vol); } break; default: return; } SEND_PLAYER_PACKET(<< (char)Op::Player::Volume << (char)m_Context->player.Volume()); } void Session::PlayerPlayMode(BufObj& buf) { char next = buf.Fetch<char>(); lock_guard<mutex> locker(m_Context->mtx); switch (next) { case 1: { m_Context->NextPlayMode(); } case 0: { string mode = mous::ToString(m_Context->playMode); SEND_PLAYER_PACKET(<< (char)Op::Player::PlayMode << mode); } break; default: break; } } void Session::PlayerPlayNext(BufObj& buf) { char direct = buf.Fetch<char>(); lock_guard<mutex> locker(m_Context->mtx); bool hasNext = m_Context->PlayNext(direct); SEND_PLAYER_PACKET(<< (char)Op::Player::PlayNext << (char)(hasNext ? 1 : 0)); } void Session::PlayerSync(BufObj& buf) { int running = buf.Fetch<char>(); lock_guard<mutex> locker(m_Context->mtx); PlayerStatus status = m_Context->player.Status(); int nowRunning = status == PlayerStatus::Playing ? 1 : 0; int mask = BINARY_MASK(running, nowRunning); switch (mask) { case BINARY_MASK(0, 1): { const MediaItem* item = m_Context->ItemInPlaying(); if (item) { SendMediaItemInfo(*item); } } case BINARY_MASK(1, 1): { uint64_t ms = m_Context->player.OffsetMs(); int32_t bitRate = m_Context->player.BitRate(); SEND_PLAYER_PACKET(<< (char)Op::Player::ItemProgress << ms << bitRate); } break; case BINARY_MASK(1, 0): case BINARY_MASK(0, 0): break; default: break; } SEND_PLAYER_PACKET(<< (char)Op::Player::Sync << (char)nowRunning); } void Session::HandlePlaylist(char* _buf, int len) { if (len < 1) return; BufObj buf(_buf); char op; buf >> op; switch (op) { case Op::Playlist::Switch: PlaylistSwitch(buf); break; case Op::Playlist::Select: PlaylistSelect(buf); break; case Op::Playlist::Play: PlaylistPlay(buf); break; case Op::Playlist::Append: PlaylistAppend(buf); break; case Op::Playlist::Remove: PlaylistRemove(buf); break; case Op::Playlist::Move: PlaylistMove(buf); break; case Op::Playlist::Clear: PlaylistClear(buf); break; case Op::Playlist::Sync: PlaylistSync(buf); break; default: break; } } void Session::PlaylistSwitch(BufObj& buf) { char iList; buf >> iList; lock_guard<mutex> locker(m_Context->mtx); if (iList < 0 || (size_t)iList >= m_Context->playlists.size()) return; m_Context->selectedPlaylist = iList; } void Session::PlaylistSelect(BufObj& buf) { char iList; int32_t iItem; buf >> iList >> iItem; if (iList < 0 || (size_t)iList >= m_Context->selectedItem.size()) return; if ((iItem < 0 || iItem >= m_Context->playlists[iList].Count()) && !m_Context->playlists[iList].Empty()) return; m_Context->selectedItem[iList] = iItem; } void Session::PlaylistPlay(BufObj& buf) { char iList; int32_t iItem; buf >> iList >> iItem; lock_guard<mutex> locker(m_Context->mtx); if (iList < 0 || (size_t)iList >= m_Context->playlists.size()) return; if (iItem < 0 || iItem >= m_Context->playlists[iList].Count()) return; bool ok = m_Context->PlayAt(iList, iItem); if (ok) { const MediaItem* item = m_Context->ItemInPlaying(); if (item) { SendMediaItemInfo(*item); } } SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Play << (char)iList << (char)(ok ? 1 : 0)); } void Session::PlaylistAppend(BufObj& buf) { char iList; string path; buf >> iList >> path; lock_guard<mutex> locker(m_Context->mtx); if (iList < 0 || (size_t)iList >= m_Context->playlists.size()) return; deque<MediaItem> list; if (m_Context->loader.LoadMedia(path, list) != ErrorCode::Ok) return; if (list.empty()) return; for (auto& item : list) { MediaTag& tag = item.tag; TryConvertToUtf8(tag.title); TryConvertToUtf8(tag.artist); TryConvertToUtf8(tag.album); } m_Context->playlists[iList].Append(list); SendMediaItemsByChunk(iList, list); } void Session::PlaylistRemove(BufObj& buf) { char iList; int32_t iItem; buf >> iList >> iItem; unique_lock<mutex> locker(m_Context->mtx); if (iList >= 0 && (size_t)iList < m_Context->playlists.size()) { if (iItem >= 0 && iItem < m_Context->playlists[iList].Count()) { m_Context->playlists[iList].Remove(iItem); } } locker.unlock(); SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Remove << iList << iItem); } void Session::PlaylistMove(BufObj& buf) { char iList; int32_t iItem; char direct; buf >> iList >> iItem >> direct; unique_lock<mutex> locker(m_Context->mtx); const int total = m_Context->playlists[iList].Count(); if (total > 0 && iList >= 0 && (size_t)iList < m_Context->playlists.size()) { int newPos = direct > 0 ? iItem + 2 : iItem - 1; if (newPos >= 0 && newPos <= total) { if (newPos >= 0 && iItem <= total) { m_Context->playlists[iList].Move(iItem, newPos); } } } locker.unlock(); SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Move << iList << iItem << direct); } void Session::PlaylistClear(BufObj& buf) { char iList; buf >> iList; unique_lock<mutex> locker(m_Context->mtx); if (iList >= 0 && (size_t)iList < m_Context->playlists.size()) { m_Context->playlists[iList].Clear(); } locker.unlock(); SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Clear << iList); } void Session::PlaylistSync(BufObj& buf) { char iList; buf >> iList; lock_guard<mutex> locker(m_Context->mtx); // send playlist if (iList >= 0 && (size_t)iList < m_Context->playlists.size()) { const deque<MediaItem>& list = m_Context->playlists[iList].Items(); SendMediaItemsByChunk(iList, list); } // recover previous status if ((int)iList == m_Context->selectedPlaylist) { SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Switch << (char)m_Context->selectedPlaylist); } for (size_t i = 0; i < m_Context->selectedItem.size(); ++i) { SEND_PLAYLIST_PACKET(<< (char)Op::Playlist::Select << (char)i << (int32_t)m_Context->selectedItem[i]); } } void Session::SlotPlayNextItem(const mous::MediaItem& item) { SendMediaItemInfo(item); } char* Session::GetPayloadBuffer(char group, int payloadSize) { Header header(group, payloadSize); size_t totalSize = header.TotalSize(); m_SendOutBuf.resize(totalSize); if (m_SendOutBuf.size() > SENDOUTBUF_MAX_KEEP && totalSize <= SENDOUTBUF_MAX_KEEP) m_SendOutBuf.shrink_to_fit(); char* buf = m_SendOutBuf.data(); header.Write(buf); return buf + Header::Size(); } void Session::SendOut() { m_Socket.SendN(m_SendOutBuf.data(), m_SendOutBuf.size()); } void Session::TryConvertToUtf8(string& str) const { using namespace CharsetHelper; using namespace IconvHelper; if (str.empty()) { str = "(empty)"; return; } if (IsUtf8(str.c_str())) return; const char* bad = "?????"; const auto env = GlobalAppEnv::Instance(); string tmp; if (ConvFromTo(env->ifNotUtf8, "UTF-8", str.data(), str.size(), tmp)) { str = tmp; } else { str = bad; } } void Session::SendMediaItemsByChunk(char index, const deque<MediaItem>& list) { // assume less than 65535 for (size_t off = 0, count = 0; off < list.size(); off += count) { count = std::min(list.size() - off, MEDIAITEMS_IN_CHUNK); BufObj buf(nullptr); buf << (char)Op::Playlist::Append << index << (int32_t)count; for (size_t i = 0; i < count; ++i) { list[off + i] >> buf; } buf.SetBuffer(GetPayloadBuffer(Group::Playlist, buf.Offset())); buf << (char)Op::Playlist::Append << index << (int32_t)count; for (size_t i = 0; i < count; ++i) { list[off + i] >> buf; } SendOut(); cout << count << endl; } } void Session::SendMediaItemInfo(const MediaItem& item) { char op = Op::Player::ItemInfo; int32_t sampleRate = m_Context->player.SamleRate(); uint64_t duration = m_Context->player.RangeDuration(); BufObj buf(nullptr); buf << op; item >> buf; buf << sampleRate << duration; buf.SetBuffer(GetPayloadBuffer(Group::Player, buf.Offset())); buf << op; item >> buf; buf << sampleRate << duration; SendOut(); }
#include <iostream> #include <vector> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { // 特判 int size = prices.size(); if (size < 2) { return 0; } // dp[j] ,i 表示 [0, i] 区间里,状态为 j 的最大收益 // j = 0:什么都不操作 // j = 1:第 1 次买入一支股票 // j = 2:第 1 次卖出一支股票 // j = 3:第 2 次买入一支股票 // j = 4:第 2 次卖出一支股票 vector<int> dp(5); dp[0] = 0; dp[1] = -prices[0]; dp[2] = INT16_MIN; dp[3] = INT16_MIN; dp[4] = INT16_MIN; for (int i = 1; i < size; i++) { if (dp[3] != INT16_MIN) { dp[4] = max(dp[4], dp[3] + prices[i]); } if (dp[2] != INT16_MIN) { dp[3] = max(dp[3], dp[2] - prices[i]); } dp[2] = max(dp[2], dp[1] + prices[i]); dp[1] = max(dp[1], -prices[i]); } return max(0, max(dp[2], dp[4])); } };
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Atom/RHI.Reflect/PipelineLayoutDescriptor.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Utils/TypeHash.h> namespace AZ { namespace RHI { void ResourceBindingInfo::Reflect(AZ::ReflectContext* context) { if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context)) { serializeContext->Class<ResourceBindingInfo>() ->Version(0) ->Field("m_shaderStageMask", &ResourceBindingInfo::m_shaderStageMask) ->Field("m_registerId", &ResourceBindingInfo::m_registerId); } } HashValue64 ResourceBindingInfo::GetHash() const { return TypeHash64(*this); } void ShaderResourceGroupBindingInfo::Reflect(AZ::ReflectContext* context) { ResourceBindingInfo::Reflect(context); if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context)) { serializeContext->Class<ShaderResourceGroupBindingInfo>() ->Version(0) ->Field("m_constantDataBindingInfo", &ShaderResourceGroupBindingInfo::m_constantDataBindingInfo) ->Field("m_resourcesRegisterMap", &ShaderResourceGroupBindingInfo::m_resourcesRegisterMap) ->Field("m_spaceId", &ShaderResourceGroupBindingInfo::m_spaceId); } } HashValue64 ShaderResourceGroupBindingInfo::GetHash() const { HashValue64 seed = TypeHash64(m_constantDataBindingInfo); for (const auto& resourceInfo : m_resourcesRegisterMap) { seed = TypeHash64(resourceInfo.first.GetHash(), seed); seed = TypeHash64(resourceInfo.second, seed); } seed = TypeHash64(m_spaceId, seed); return seed; } void PipelineLayoutDescriptor::Reflect(AZ::ReflectContext* context) { ShaderResourceGroupBindingInfo::Reflect(context); ConstantsLayout::Reflect(context); if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context)) { serializeContext->Class<PipelineLayoutDescriptor>() ->Version(4) ->Field("m_shaderResourceGroupLayoutsInfo", &PipelineLayoutDescriptor::m_shaderResourceGroupLayoutsInfo) ->Field("m_rootConstantLayout", &PipelineLayoutDescriptor::m_rootConstantsLayout) ->Field("m_bindingSlotToIndex", &PipelineLayoutDescriptor::m_bindingSlotToIndex) ->Field("m_hash", &PipelineLayoutDescriptor::m_hash); } } RHI::Ptr<PipelineLayoutDescriptor> PipelineLayoutDescriptor::Create() { return aznew PipelineLayoutDescriptor; } bool PipelineLayoutDescriptor::IsFinalized() const { return m_hash != InvalidHash; } void PipelineLayoutDescriptor::Reset() { m_hash = InvalidHash; m_shaderResourceGroupLayoutsInfo.clear(); m_bindingSlotToIndex.fill(RHI::Limits::Pipeline::ShaderResourceGroupCountMax); ResetInternal(); } ResultCode PipelineLayoutDescriptor::Finalize() { ResultCode resultCode = FinalizeInternal(); if (resultCode == ResultCode::Success) { HashValue64 seed = HashValue64{ 0 }; for (const ShaderResourceGroupLayoutInfo& layoutInfo : m_shaderResourceGroupLayoutsInfo) { seed = TypeHash64(layoutInfo.first->GetHash(), seed); seed = TypeHash64(layoutInfo.second.GetHash(), seed); } if (m_rootConstantsLayout) { seed = TypeHash64(m_rootConstantsLayout->GetHash(), seed); } for (const auto& index : m_bindingSlotToIndex) { seed = TypeHash64(index, seed); } m_hash = GetHashInternal(seed); } return resultCode; } void PipelineLayoutDescriptor::ResetInternal() {} ResultCode PipelineLayoutDescriptor::FinalizeInternal() { return ResultCode::Success; } HashValue64 PipelineLayoutDescriptor::GetHashInternal(HashValue64 seed) const { return seed; } void PipelineLayoutDescriptor::AddShaderResourceGroupLayoutInfo(const ShaderResourceGroupLayout& layout, const ShaderResourceGroupBindingInfo& shaderResourceGroupInfo) { m_bindingSlotToIndex[layout.GetBindingSlot()] = aznumeric_caster(m_shaderResourceGroupLayoutsInfo.size()); // NOTE: The const_cast is required because serialization does not allow for ConstPtr. However, // the layout is always treated as immutable internally, and is only exposed as such externally. m_shaderResourceGroupLayoutsInfo.push_back({ const_cast<ShaderResourceGroupLayout*>(&layout), shaderResourceGroupInfo }); } void PipelineLayoutDescriptor::SetRootConstantsLayout(const ConstantsLayout& rootConstantsLayout) { // NOTE: The const_cast is required because serialization does not allow for ConstPtr.However, // the layout is always treated as immutable internally, and is only exposed as such externally. m_rootConstantsLayout = const_cast<ConstantsLayout*>(&rootConstantsLayout); } size_t PipelineLayoutDescriptor::GetShaderResourceGroupLayoutCount() const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_shaderResourceGroupLayoutsInfo.size(); } const ShaderResourceGroupLayout* PipelineLayoutDescriptor::GetShaderResourceGroupLayout(size_t index) const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_shaderResourceGroupLayoutsInfo[index].first.get(); } const ShaderResourceGroupBindingInfo& PipelineLayoutDescriptor::GetShaderResourceGroupBindingInfo(size_t index) const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_shaderResourceGroupLayoutsInfo[index].second; } const ConstantsLayout* PipelineLayoutDescriptor::GetRootConstantsLayout() const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_rootConstantsLayout.get(); } HashValue64 PipelineLayoutDescriptor::GetHash() const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_hash; } uint32_t PipelineLayoutDescriptor::GetShaderResourceGroupIndexFromBindingSlot(uint32_t bindingSlot) const { AZ_Assert(IsFinalized(), "Accessor called on a non-finalized pipeline layout. This is not permitted."); return m_bindingSlotToIndex[bindingSlot]; } } }
/*========================================================================= Program: ALBA (Agile Library for Biomedical Applications) Module: vtkALBAPastValuesListTest Authors: Nigel McFarlane Copyright (c) BIC All rights reserved. See Copyright.txt or This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ //---------------------------------------------------------------------------- // NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first. // This force to include Window,wxWidgets and VTK exactly in this order. // Failing in doing this will result in a run-time error saying: // "Failure#0: The value of ESP was not properly saved across a function call" //---------------------------------------------------------------------------- #include "albaDefines.h" #include <cppunit/config/SourcePrefix.h> #include "vtkALBAPastValuesList.h" #include "vtkALBAPastValuesListTest.h" #include "albaConfigure.h" //#define TESTDATA ALBA_DATA_ROOT"/FEM/ANSYS" #define FTOL 0.0000001 static const bool renderingOn = false ; // switch interactive rendering on void vtkALBAPastValuesListTest::TestFixture() { } //------------------------------------------------------------------------------ // Test with 20 values void vtkALBAPastValuesListTest::TestPastValues() //------------------------------------------------------------------------------ { int i ; // test data produced by MS Excel double testData[22] = {122,310,939,824,587,998,218,446,122,298,146,893,438,949,252,95,883,482,330,784,784,1000} ; double min3[22] = {122,122,122,310,587,587,218,218,122,122,122,146,146,438,252,95,95,95,330,330,330,784} ; double max3[22] = {122,310,939,939,939,998,998,998,446,446,298,893,893,949,949,949,883,883,883,784,784,1000} ; double median3[22] = {122,216,310,824,824,824,587,446,218,298,146,298,438,893,438,252,252,482,482,482,784,784} ; double median4[22] = {122,216,310,567,705.5,881.5,705.5,516.5,332,258,222,222,368,665.5,665.5,345,567.5,367,406,633,633,784} ; double mean4[22] = {122,216,457,548.75,665,837,656.75,562.25,446,271,253,364.75,443.75,606.5,633,433.5,544.75,428,447.5,619.75,595,724.5} ; // set up an example to contain 3 past values and load data into it // At each step we check that the stats are correct. vtkALBAPastValuesList *PastVals3 = new vtkALBAPastValuesList(3) ; for (i = 0 ; i < 22 ; i++){ PastVals3->AddNewValue(testData[i]) ; CPPUNIT_ASSERT(PastVals3->GetMin() == min3[i]) ; CPPUNIT_ASSERT(PastVals3->GetMax() == max3[i]) ; CPPUNIT_ASSERT(PastVals3->GetMedian() == median3[i]) ; } // set up an example to contain 4 past values and load data into it // At each step we check that the stats are correct. vtkALBAPastValuesList *PastVals4 = new vtkALBAPastValuesList(4) ; for (i = 0 ; i < 22 ; i++){ PastVals4->AddNewValue(testData[i]) ; CPPUNIT_ASSERT(PastVals4->GetMedian() == median4[i]) ; CPPUNIT_ASSERT(PastVals4->GetMean() == mean4[i]) ; } delete PastVals3 ; delete PastVals4 ; }
#include <gtest/gtest.h> #include <fstream> #include <iostream> #include "keysecure.hpp" TEST(TestKeysecure, check_amount_of_entries) { kfp::Keysecure key("test_db.kfp", "conf", "123456"); std::vector<kfp::Entry> all_entries = key.get_db(); ASSERT_EQ(2, all_entries.size()); } TEST(TestKeysecure, check_entry_values) { kfp::Keysecure key("test_db.kfp", "conf", "123456"); std::vector<kfp::Entry> all_entries = key.get_db(); kfp::Entry entry = all_entries[0]; ASSERT_EQ(entry["notes"], "gmail is from google"); ASSERT_EQ(entry["password"], "123456 PPP"); ASSERT_EQ(entry["path"], ""); ASSERT_EQ(entry["title"], "gmail"); ASSERT_EQ(entry["url"], "gmail.com"); ASSERT_EQ(entry["username"], "bob@gmail.com"); entry = all_entries[1]; ASSERT_EQ(entry["notes"], "netflix is awesome"); ASSERT_EQ(entry["password"], "qwerty;;;,,,, sdf"); ASSERT_EQ(entry["path"], ""); ASSERT_EQ(entry["title"], "netflix.com"); ASSERT_EQ(entry["url"], "netflix"); ASSERT_EQ(entry["username"], "bob@gmail.com"); } TEST(TestKeysecure, create_new_database) { std::string db_name = "newdatabase.kfp"; std::remove(db_name.c_str()); kfp::Keysecure key(db_name, "conf", "123456"); std::ifstream file(db_name); ASSERT_EQ(file.good(), true); int num_of_line = 0; std::string line; while (std::getline(file, line)) ++num_of_line; ASSERT_EQ(num_of_line, 0); std::remove(db_name.c_str()); } TEST(TestKeysecure, add_new_entry) { std::string db_name = "newdatabase_add.kfp"; std::remove(db_name.c_str()); kfp::Keysecure key(db_name, "conf", "123456"); kfp::Entry entry; entry["title"] = "po=lo"; entry["username"] = "bob@gmail.com"; entry["url"] = "netf\nlix.com"; entry["path"] = ""; entry["password"] = "qwerty;;;,,,, sdf"; entry["notes"] = "netflix is awesome"; key.add_entry(entry); std::vector<kfp::Entry> all_entries = key.get_db(); kfp::Entry entry_from_file = all_entries[0]; ASSERT_EQ(entry_from_file["title"], "po=lo"); ASSERT_EQ(entry_from_file["username"], "bob@gmail.com"); ASSERT_EQ(entry_from_file["url"], "netf\nlix.com"); ASSERT_EQ(entry_from_file["path"], ""); ASSERT_EQ(entry_from_file["password"], "qwerty;;;,,,, sdf"); ASSERT_EQ(entry_from_file["notes"], "netflix is awesome"); // check whether it open db properly kfp::Keysecure key_again(db_name, "conf", "123456"); std::remove(db_name.c_str()); } TEST(TestKeysecure, delete_entry) { std::string db_name = "newdatabase_delete.kfp"; std::remove(db_name.c_str()); kfp::Keysecure key(db_name, "conf", "123456"); kfp::Entry entry1; entry1["title"] = "polo"; entry1["username"] = "bob@gmail.com"; entry1["url"] = "netflix.com"; entry1["path"] = "of life"; entry1["password"] = "qwerty;;;,,,, sdf"; entry1["notes"] = "netflix is awesome"; key.add_entry(entry1); kfp::Entry entry2; entry2["title"] = "hoho"; entry2["username"] = "bob@gmail.com"; entry2["url"] = "netflix.com"; entry2["path"] = "of life"; entry2["password"] = "qwerty;;;,,,, sdf"; entry2["notes"] = "netflix is awesome"; key.add_entry(entry2); std::vector<kfp::Entry> all_entries = key.get_db(); ASSERT_EQ(all_entries.size(), 2); key.delete_entry(entry2); all_entries = key.get_db(); ASSERT_EQ(all_entries.size(), 1); // check whether it open db properly kfp::Keysecure key_again(db_name, "conf", "123456"); std::remove(db_name.c_str()); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); // ::testing::GTEST_FLAG(filter) = "*dd_new_entr*"; return RUN_ALL_TESTS(); }
#pragma once #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/quaternion.hpp> #include <cmath> #include <utility> #include <vector> #include <list> #include <map> #include <queue> #include <stack> #include "filesystem.h" #include "shader_s.h" //#include "Solver/Rubik.cpp" #include "optimal_solver.h" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #define SIN(x) sin(x * 3.141592653589/180) #define COS(x) cos(x * 3.141592653589/180) #define RED glm::vec3(1.0,0.0,0.0) #define GREEN glm::vec3(0.0,1.0,0.0) #define BLUE glm::vec3(0.0,0.0,1.0) #define WHITE glm::vec3(1.0,1.0,1.0) #define YELLOW glm::vec3(1.0,1.0,0.0) #define ORANGE glm::vec3(1.0,0.5,0.0) #define menora < #define print << #define mayora > #define NCUBES 27 #define limite 180 void framebuffer_size_callback(GLFWwindow* window, int width, int height); void mouse_callback(GLFWwindow* window, double xpos, double ypos); void scroll_callback(GLFWwindow* window, double xoffset, double yoffset); void processInput(GLFWwindow* window); using namespace std; unsigned int *textures[6]; glm::vec3 centerPositions[] = { glm::vec3(1.0f, -1.0f, -1.0f), }; glm::vec3 NegcenterPositions[] = { glm::vec3(-1.0f, 1.0f, 1.0f), }; // camera glm::vec3 cameraPos = glm::vec3(3.0f, 1.0f, 10.0f); glm::vec3 cameraFront = glm::vec3(0.0f, 0.0f, -1.0f); glm::vec3 cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); bool firstMouse = true; float yaw = -90.0f; // yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing to the right so we initially rotate a bit to the left. float pitch = 0.0f; float lastX = 800.0f / 2.0; float lastY = 600.0 / 2.0; float fov = 45.0f; // timing float deltaTime = 0.0f; // time between current frame and last frame float lastFrame = 0.0f; void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; float mixValue = 0.0f; bool setVBOChange = false; vector <float> color_actual = { 1.0f, 0.0f, 0.0f }; bool vali_tri = false; bool vali_cuad = false; bool vali_rombo = false; int cont_tri = 0; int cont_rombo = 0; int cont_estrella = 0; int cont_cuadrado = 0; int valid1 = false; int valid2 =0; int valid3 = 0; int valicamara = 0; int valicamara2 = 0; int valiInicial = 0; bool valid4 = false; bool valiAnimacion = false; int valisolver = 0; int valid = 0; float* ptr_vertices = nullptr; float* ptr_verticesT = nullptr; float* ptr_verticesC = nullptr; float* ptr_verticesR = nullptr; float* ptr_verticesE = nullptr; int cont = 0; int cont1 = 0; int n_elm =192; int n_ind = 24; float pto_medio[2]; queue <string> solucion; struct Vertice { float x, y, z, a, b, c, n, m; Vertice(float x_ = 0, float y_ = 0, float z_ = 0, float a_ = 0, float b_ = 0, float c_ = 0, float n_ = 0, float m_ = 0) : x(x_), y(y_), z(z_), a(a_), b(b_), c(c_), n(n_), m(m_) {} }; // a // // // b c struct Triangulo { Vertice a, b, c; Triangulo(Vertice x_, Vertice y_, Vertice z_) { a = x_; b = y_; c = z_; a.n = 1.0f; //derecha a.m = 0.0f; b.n = 0.0f; //izquierda b.m = 0.0f; c.n = 0.5f; //arriba c.m = 1.0f; } //int nivel; //char posicion;//('A','C', 'I', 'D') }; queue <Triangulo> actuales_T; void dibujar_Tri(Triangulo tri) { unsigned int indices[] = { // note that we start from 0! 0, 1, 2, // first Triangle }; } void act_Vert_1_tr(Triangulo tri) { actuales_T.push(tri); float vertices_temp[] = { tri.a.x,tri.a.y,tri.a.z,tri.a.a,tri.a.b,tri.a.c,tri.a.n,tri.a.m,tri.b.x,tri.b.y,tri.b.z,tri.b.a,tri.b.b,tri.b.c,tri.b.n,tri.b.m,tri.c.x,tri.c.y,tri.c.z,tri.c.a,tri.c.b,tri.c.c,tri.c.n,tri.c.m }; unsigned int n = n_elm; unsigned int n1 = n_ind; int c = n + 24; float* p1 = new float[c]; n_elm += 24; n_ind += 3; for (int i = 0; i < n; i++) { p1[i] = ptr_vertices[i]; } for (int i = 0; i < 24; i++) { p1[n + i] = vertices_temp[i]; } delete[] ptr_vertices; ptr_vertices = &(p1[0]); } //int time = 0; int timebase = 0; GLfloat angulo = 5; GLfloat origen = -8; GLfloat direccion = -1; std::string& rtrim(std::string& str, const std::string& chars = "\t\n\v\f\r ") { str.erase(str.find_last_not_of(chars) + 1); return str; } typedef pair<int, int> par_mapa; unsigned int VBO[NCUBES], VAO[NCUBES]; float* punteros[NCUBES]; map <int, int> indice_tag; float toRadians(int x) {return x * 3.141592653589 / 180.0;} int valiLeft = 0; int valiFront = 0; int valiUp = 0; int valiRight = 0; int valiDown = 0; int valiBack = 0; glm::mat4 rotarRight(int& valiRight, int i, glm::mat4 model) { vector<int> my_list = { 0,3,6,9,12,15,18,21,24 }; vector<int> cambio = { 18,9,0,21,12,3,24,15,6 }; map<int, int>::iterator q = indice_tag.find(i); //cout print "entra" print i print endl; if (find(my_list.begin(), my_list.end(), i) != my_list.end()) { //cout print "compara"; model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiRight), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::translate(model, NegcenterPositions[0]); if (valiAnimacion == true) { if (i == my_list[0] || i == my_list[1] || i == my_list[2]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, 1.0f)); } if (i == my_list[0] || i == my_list[3] || i == my_list[6]) { model = glm::translate(model, glm::vec3(0.0f, 1.0f, 0.0f)); } if (i == my_list[2] || i == my_list[5] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); } if (i == my_list[6] || i == my_list[7] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, -1.0f)); } } if (valiRight == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(1.5708, 0, 0); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiRight += 1; if (valiRight == 18) { //cout print "actualizar" print endl; map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); //cout print p->first print " " print p->second print endl; p->second = temp[t]; //cout print p->first print " " print p->second print endl; } valiRight = 0; } } //cout print valiLeft print endl; return model; } glm::mat4 rotarLeft(int &valiLeft, int i, glm::mat4 model) { vector<int> my_list= { 2,5,8,11,14,17,20,23,26 }; vector<int> cambio = { 20,11,2,23,14,5,26,17,8 }; map<int, int>::iterator q= indice_tag.find(i); if (find(my_list.begin(), my_list.end(),i) != my_list.end()) { model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiLeft), glm::vec3(1.0f, 0.0f, 0.0f)); model = glm::translate(model, NegcenterPositions[0]); if (valiAnimacion == true) { if (i == 2 || i == 5 || i == 8) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, 1.0f)); } if (i == 2 || i == 11 || i == 20) { model = glm::translate(model, glm::vec3(0.0f, 1.0f, 0.0f)); } if (i == 8 || i == 17 || i == 26) { model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); } if (i == 20 || i == 23 || i == 26) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, -1.0f)); } } if (valiLeft == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(1.5708, 0, 0); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiLeft += 1; if (valiLeft == 18) { map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); p->second = temp[t]; } valiLeft = 0; } } //cout print valiLeft print endl; return model; } glm::mat4 rotarDown(int& valiDown, int i, glm::mat4 model) { vector<int> my_list = { 6,7,8,15,16,17,24,25,26 }; //vector<int> mylist = { 18,19,20,21,22,23,24,25,26 }; //vector<int> cambio = { 20,23,26,19,22,25,18,21,24 }; vector<int> cambio = {24,15,6,25,16,7,26,17,8 }; map<int, int>::iterator q = indice_tag.find(i); //cout print "entra" print i print endl; if (find(my_list.begin(), my_list.end(), i) != my_list.end()) { //cout print "compara"; model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiDown), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::translate(model, NegcenterPositions[0]); if (valiAnimacion == true) { if (i == my_list[0] || i == my_list[1] || i == my_list[2]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, 1.0f)); } if (i == my_list[0] || i == my_list[3] || i == my_list[6]) { model = glm::translate(model, glm::vec3(-1.0f, 0.0f, 0.0f)); } if (i == my_list[2] || i == my_list[5] || i == my_list[8]) { model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f)); } if (i == my_list[6] || i == my_list[7] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, -1.0f)); } } if (valiDown == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(0, 1.5708,0); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiDown += 1; if (valiDown == 18) { //cout print "actualizar" print endl; map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); // cout print p->first print " " print p->second print endl; p->second = temp[t]; // cout print p->first print " " print p->second print endl; } valiDown = 0; } } //cout print valiLeft print endl; return model; } glm::mat4 rotarBack(int& valiBack, int i, glm::mat4 model) { vector<int> my_list = { 18,19,20,21,22,23,24,25,26 }; vector<int> cambio = { 20,23,26,19,22,25,18,21,24 }; map<int, int>::iterator q = indice_tag.find(i); //cout print "entra" print i print endl; if (find(my_list.begin(), my_list.end(), i) != my_list.end()) { //cout print "compara"; model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiBack), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::translate(model, NegcenterPositions[0]); if( valiAnimacion==true){ if (i == my_list[0] || i == my_list[1] || i == my_list[2]) { model = glm::translate(model, glm::vec3(0.0f, 1.0f, 0.0f)); } if (i == my_list[0] || i == my_list[3] || i == my_list[6]) { model = glm::translate(model, glm::vec3(-1.0f, 0.0f, 0.0f)); } if (i == my_list[2] || i == my_list[5] || i == my_list[8]) { model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f)); } if (i == my_list[6] || i == my_list[7] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); } } if (valiBack == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(0, 0, 1.5708); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiBack += 1; if (valiBack == 18) { //cout print "actualizar" print endl; map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); //cout print p->first print " " print p->second print endl; p->second = temp[t]; //cout print p->first print " " print p->second print endl; } valiBack = 0; } } //cout print valiLeft print endl; return model; } glm::mat4 rotarFront(int& valiFront, int i, glm::mat4 model) { vector<int> my_list = { 0,1,2,3,4,5,6,7,8}; vector<int> cambio = { 2,5,8,1,4,7,0,3,6}; map<int, int>::iterator q = indice_tag.find(i); //cout print "entra" print i print endl; if (find(my_list.begin(), my_list.end(),i) != my_list.end()) { //cout print "compara"; model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiFront), glm::vec3(0.0f, 0.0f, 1.0f)); model = glm::translate(model, NegcenterPositions[0]); if (valiAnimacion == true) { if (i == my_list[0] || i == my_list[1] || i == my_list[2]) { model = glm::translate(model, glm::vec3(0.0f, 1.0f, 0.0f)); } if (i == my_list[0] || i == my_list[3] || i == my_list[6]) { model = glm::translate(model, glm::vec3(-1.0f, 0.0f, 0.0f)); } if (i == my_list[2] || i == my_list[5] || i == my_list[8]) { model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f)); } if (i == my_list[6] || i == my_list[7] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, -1.0f, 0.0f)); } } if (valiFront == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(0, 0, 1.5708); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiFront += 1; if (valiFront == 18) { //cout print "actualizar" print endl; map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); //cout print p->first print " " print p->second print endl; p->second = temp[t]; //cout print p->first print " " print p->second print endl; } valiFront = 0; } } //cout print valiLeft print endl; return model; } glm::mat4 rotarUp(int& valiUp, int i, glm::mat4 model) { vector<int> my_list = { 0,1,2,9,10,11,18,19,20 }; vector<int> cambio = { 18,9,0,19,10,1,20,11,2 }; map<int, int>::iterator q = indice_tag.find(i); //cout print "entra" print i print endl; if (find(my_list.begin(), my_list.end(), i) != my_list.end()) { //cout print "compara"; model = glm::translate(model, centerPositions[0]); model = glm::rotate(model, toRadians(5 * valiUp), glm::vec3(0.0f, 1.0f, 0.0f)); model = glm::translate(model, NegcenterPositions[0]); if (valiAnimacion == true) { if (i == my_list[0] || i == my_list[1] || i == my_list[2]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, 1.0f)); } if (i == my_list[0] || i == my_list[3] || i == my_list[6]) { model = glm::translate(model, glm::vec3(-1.0f, 0.0f, 0.0f)); } if (i == my_list[2] || i == my_list[5] || i == my_list[8]) { model = glm::translate(model, glm::vec3(1.0f, 0.0f, 0.0f)); } if (i == my_list[6] || i == my_list[7] || i == my_list[8]) { model = glm::translate(model, glm::vec3(0.0f, 0.0f, -1.0f)); } } if (valiUp == 17) { //cout print "actualizamos cubo" print i print endl; glm::quat MyQuaternion; // Direct specification of the 4 components // You almost never use this directly // RotationAngle is in radians glm::vec3 EulerAngles(0, 1.5708, 0); MyQuaternion = glm::quat(EulerAngles); for (int s = 0; s < 36; ++s) { //cout print "antes:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; glm::vec3 point = { punteros[q->second][s * 8], punteros[q->second][(s * 8) + 1], punteros[q->second][(s * 8) + 2] }; glm::vec3 rotated_point = centerPositions[0] + (MyQuaternion * (point - centerPositions[0])); punteros[q->second][s * 8] = rotated_point[0]; punteros[q->second][(s * 8) + 1] = rotated_point[1]; punteros[q->second][(s * 8) + 2] = rotated_point[2]; //cout print "despues:" print i print endl; //cout print "x=" print punteros[i][s * 8] print " ,y=" print punteros[i][(s * 8) + 1] print " ,z=" print punteros[i][(s * 8) + 2] print endl; } } } if (i == 26) { valiUp += 1; if (valiUp == 18) { //cout print "actualizar" print endl; map<int, int>::iterator p; vector<float > temp; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(cambio[t]); temp.push_back(p->second); } //cout print "mapa" print endl; for (int t = 0; t menora 9; ++t) { p = indice_tag.find(my_list[t]); //cout print p->first print " " print p->second print endl; p->second = temp[t]; //cout print p->first print " " print p->second print endl; } valiUp = 0; } } //cout print valiLeft print endl; return model; } void resolver(string mov) { if (mov == "F") { } } queue<string> moves_(string solu) { vector<string> temp; queue <string> mystack; std::istringstream isstream(solu); std::string palabra; while (isstream >> palabra) { temp.push_back(palabra); } for (int i = 0; i < temp.size(); ++i) { //cout print "temp " print temp[i] print endl;; } for (int i = 0; i < temp.size(); ++i) { char inicial=temp[i][0]; string ini (1,temp[i][0]); // cout print"inicial " print inicial print endl; if (temp[i][1]) { //cout print"segundo " print temp[i][1] print endl; string tempo = "a'"; char a = tempo[1]; if (temp[i][1] == '2') { string pushear = ini + "'"; for (int i = 0; i < 2; ++i) { mystack.push(pushear); } } if (temp[i][1] == a) { //cout print"apostrofe " print a print endl; string pushear = ini + "'"; // cout print"pushear " print pushear print endl; mystack.push(pushear); } } else { string pushear = ini + "'"; for (int i = 0; i < 3; ++i) { mystack.push(pushear); } } } return mystack; } string movimientos = ""; int main() { // string a="hola mi nombre es este "; //rtrim(a); //cout print a print "seee" print endl; std::cout << "** Main **" << std::endl; std::cout << "** Movimientos hechos: **" << std::endl; //movimientos += "R' U"; //OptimalSolver os(6); //os.solve(movimientos); /* std::cout << "** A-perm **" << std::endl; os.solve("R' F R' B2 R F' R' B2 R2"); std::cout << "** T-perm **" << std::endl; os.solve("R U R' U' R' F R2 U' R' U' R U R' F'"); std::cout << "** Y-perm **" << std::endl; os.solve("F R U' R' U' R U R' F' R U R' U' R' F R F'"); std::cout << "** E-perm **" << std::endl; os.solve("R' U L' D2 L U' R L' U R' D2 R U' L"); std::cout << "** Z-perm **" << std::endl; os.solve("R U R' U R' U' R' U R U' R' U' R2 U R U2"); std::cout << "** Pi-COLL **" << std::endl; os.solve("U2 F U R U' R' U R U2 R' U' R U R' F'"); std::cout << "** Random (15 moves) **" << std::endl; os.solve("U' B D R2 F' L2 R U' B' D' L B2 F' L2 R'"); std::cout << "** Random (16 moves) **" << std::endl; os.solve("R' L2 D' R' L B2 L2 F D' U F D' L D2 R2 D");*/ /* Cube myCube(false); int scrambleNum = 0; string a="R' F U' D2 R F R' L2 F' B2 U' F2 B' R2 B D2 B' U2 R2"; while (std::getline(std::cin, a)) { ++scrambleNum; std::string scramble = format(a); std::cout << "Scramble #" << scrambleNum << ": "; myCube.moves(scramble); Cross::solveCross(myCube); std::cout << "Cross solved" << std::endl; Corners::solveCorners(myCube); std::cout << "Corners solved" << std::endl; Edges::solveEdges(myCube); std::cout << "Edges solved" << std::endl;; OLL::solveOLL(myCube); std::cout << "OLL solved" << std::endl; PLL::solvePLL(myCube); std::cout << "PLL solved" << std::endl; } */ for (int j = 0; j < 6; ++j) { textures[j] = new unsigned int[9]; } // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); glfwSetKeyCallback(window, key_callback); glfwSetCursorPosCallback(window, mouse_callback); glfwSetScrollCallback(window, scroll_callback); // tell GLFW to capture our mouse glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // configure global opengl state // ----------------------------- glEnable(GL_DEPTH_TEST); // build and compile our shader zprogram // ------------------------------------ Shader ourShader("C://Users//USER//Desktop//Universidad//actual//grafica_//GLFW_GLAD_GLUT_GLEW_cmake_project//src//TestCube1//Shaders//3.3.shader.vs", "C://Users//USER//Desktop//Universidad//actual//grafica_//GLFW_GLAD_GLUT_GLEW_cmake_project//src//TestCube1//Shaders//3.3.shader.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ for (int i = 0; i menora NCUBES; ++i) { indice_tag.insert(par_mapa(i, i)); } float vertices[288] = { // positions // colors // texture coords ////// cubo -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, ///////BACK 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 1.0f, 1.0f, //FRONT 0.5f, 0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0,0.5,0.0, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0,0.5,0.0, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 1.0,0.5,0.0, 1.0f, 1.0f, //left -0.5f, -0.5f, -0.5f, 1.0,0.5,0.0, 1.0f, 1.0f, -0.5f, -0.5f, 0.5f, 1.0,0.5,0.0, 0.0f, 1.0f, -0.5f, 0.5f, 0.5f, 1.0,0.5,0.0, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, //right 0.5f, -0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.8f, 0.9f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.8f, 0.9f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.8f, 0.9f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.8f, 0.9f, 1.0f, 1.0f, //down -0.5f, -0.5f, 0.5f, 1.0f, 0.8f, 0.9f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 1.0f, 0.8f, 0.9f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.2f, 0.9f, 0.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.2f, 0.9f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.2f, 0.9f, 1.0f, 1.0f, //TOP 0.5f, 0.5f, 0.5f, 0.0f, 0.2f, 0.9f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.2f, 0.9f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.2f, 0.9f, 0.0f, 0.0f, }; for (int j = 0; j < NCUBES; ++j) { punteros[j] = new float[288]; } for (int i = 0; i < NCUBES; ++i) { for (int j = 0; j < 288; ++j) { punteros[i][j] = vertices[j]; } } glm::vec3 pPositions[] = { glm::vec3(0.0f, 5.0f, -5.0f), }; glm::vec3 dPositions[] = { glm::vec3(0.0f, 5.0f, 0.0f), }; pto_medio[0] = 0; pto_medio[1] = 0; float* p1 = new float[432]; float* pt = new float[288]; float* pc = new float[144];//432 float* pr = new float[288]; for (int i = 0; i < 288; i++) { pt[i] = vertices[i]; } for (int i = 0; i < 288; i++) { pr[i] = vertices[i]; } ptr_vertices = &(p1[0]); ptr_verticesT = &(pt[0]); ptr_verticesC = &(pc[0]); ptr_verticesR = &(pr[0]); float vec_dir[3]; vec_dir[0] = 1.0f; vec_dir[1] = 0.0f; vec_dir[2] = 0.0f; //////////////////////////////////////////////////////////SE MODIFICA for (int j = 1; j < 3; ++j) { for (int i = 0; i < 36; ++i) { punteros[j][i * 8] = punteros[j - 1][i * 8] + vec_dir[0]; punteros[j][(i * 8) + 1] = punteros[j - 1][(i * 8) + 1] + vec_dir[1]; punteros[j][(i * 8) + 2] = punteros[j - 1][(i * 8) + 2] + vec_dir[2]; } } for (int j = 3; j < 9; ++j) { for (int i = 0; i < 36; ++i) { punteros[j][i * 8] = punteros[j - 3][i * 8] + vec_dir[1]; punteros[j][(i * 8) + 1] = punteros[j - 3][(i * 8) + 1] - vec_dir[0]; punteros[j][(i * 8) + 2] = punteros[j - 3][(i * 8) + 2] + vec_dir[2]; } } for (int j = 9; j < 27; ++j) { for (int i = 0; i < 36; ++i) { punteros[j][i * 8] = punteros[j - 9][i * 8] + vec_dir[1]; punteros[j][(i * 8) + 1] = punteros[j - 9][(i * 8) + 1] - vec_dir[2]; punteros[j][(i * 8) + 2] = punteros[j - 9][(i * 8) + 2] - vec_dir[0]; } } //////////////////////////////////////////////////////////SE MODIFICA //////////////////////////////////////////////////////////SE MODIFICA //////////////////////////////////////////////////////////SE MODIFICA //////////////////////////////////////////////////////////SE MODIFICA for (int j = 0; j < 27; j++) { if ((j % 3) != 2) { for (int i = 18; i < 24; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; } } } for (int j = 0; j < 27; j++) { if ((j % 3) != 0) { for (int i = 12; i < 18; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; } } } for (int j = 0; j < 6; j++) { for (int i = 24; i < 30; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; punteros[j + 9][(i * 8) + 4] = 0.0f; punteros[j + 9][(i * 8) + 5] = 0.0f; punteros[j + 9][(i * 8) + 6] = 0.0f; punteros[j + 18][(i * 8) + 4] = 0.0f; punteros[j + 18][(i * 8) + 5] = 0.0f; punteros[j + 18][(i * 8) + 6] = 0.0f; } } for (int j = 3; j < 9; j++) { for (int i = 30; i < 36; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; punteros[j + 9][(i * 8) + 4] = 0.0f; punteros[j + 9][(i * 8) + 5] = 0.0f; punteros[j + 9][(i * 8) + 6] = 0.0f; punteros[j + 18][(i * 8) + 4] = 0.0f; punteros[j + 18][(i * 8) + 5] = 0.0f; punteros[j + 18][(i * 8) + 6] = 0.0f; } } for (int j = 0; j < 18; j++) { for (int i = 0; i < 6; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; } } for (int j = 9; j < 27; j++) { for (int i = 6; i < 12; i++) { punteros[j][(i * 8) + 4] = 0.0f; punteros[j][(i * 8) + 5] = 0.0f; punteros[j][(i * 8) + 6] = 0.0f; } } // Vertice a(-1.0f, -0.8f, 0.0f, 1.0f, 0.0f, 0.1f, 0.0f, 0.0f); //Vertice b(1.0f, -0.8f, 0.0f, 0.0f, 1.0f, 0.1f, 1.0f, 0.0f); //Vertice c(0.0f, 0.93f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, 1.0f); //Triangulo trian(a, b, c); //actuales_T.push(trian); glGenVertexArrays(NCUBES, VAO); glGenBuffers(NCUBES, VBO); for (int j = 0; j < NCUBES; ++j) { glBindVertexArray(VAO[j]); glBindBuffer(GL_ARRAY_BUFFER, VBO[j]); glBufferData(GL_ARRAY_BUFFER, sizeof(punteros[j][0]) * 288, punteros[j], GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // texture coord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); } // load and create a texture // ------------------------- // cara front // --------- stbi_set_flip_vertically_on_load(true); for (int j = 0; j < 9; ++j) { string temp = "F"; glGenTextures(1, &textures[0][j]); glBindTexture(GL_TEXTURE_2D, textures[0][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; // cout print temp print(0 * 9) + j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath(temp).c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } //cara left stbi_set_flip_vertically_on_load(false); for (int j = 0; j < 9; ++j) { string temp = "L"; glGenTextures(1, &textures[1][j]); glBindTexture(GL_TEXTURE_2D, textures[1][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; // cout print temp print(1 * 9) + j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath(temp).c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } stbi_set_flip_vertically_on_load(true); //cara up for (int j = 0; j < 9; ++j) { string temp = "U"; glGenTextures(1, &textures[2][j]); glBindTexture(GL_TEXTURE_2D, textures[2][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; //cout print temp print(2 * 9) + j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath(temp).c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } stbi_set_flip_vertically_on_load(true); //cara back for (int j = 0; j < 9; ++j) { string temp = "B"; glGenTextures(1, &textures[3][j]); glBindTexture(GL_TEXTURE_2D, textures[3][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; //cout print temp print(3 * 9) + j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath(temp).c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } stbi_set_flip_vertically_on_load(true); //cara right for (int j = 0; j < 9; ++j) { string temp = "R"; glGenTextures(1, &textures[4][j]); glBindTexture(GL_TEXTURE_2D, textures[4][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; //cout print temp print (4 * 9) + j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath("wall.jpg").c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } stbi_set_flip_vertically_on_load(true); //cara down for (int j = 0; j < 9; ++j) { string temp = "D"; glGenTextures(1, &textures[5][j]); glBindTexture(GL_TEXTURE_2D, textures[5][j]); // set the texture wrapping parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // set texture wrapping to GL_REPEAT (default wrapping method) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // set texture filtering parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // load image, create texture and generate mipmaps int width, height, nrChannels; temp += to_string(j); temp += ".jpg"; //cout print temp print (5*9)+j print endl; // tell stb_image.h to flip loaded texture's on the y-axis. // The FileSystem::getPath(...) is part of the GitHub repository so we can find files on any IDE/platform; replace it with your own image path. unsigned char* data = stbi_load(FileSystem::getPath(temp).c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture " << 0 print j print std::endl; } stbi_image_free(data); } // ------------------------------------------------------------------------------------------- ourShader.use(); // don't forget to activate/use the shader before setting uniforms! // either set it manually like so: // glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 0); // or set it via the texture class //ourShader.setInt("texture2", 1); //ourShader.setInt("texture2", 1); // ourShader.setInt("texture3", 2); int fcont = 0; std::cout << "M activa la animacion de explocion " << std::endl; std::cout <<"la camara se mueve con W, A,S,D y con el mouse" << std::endl; std::cout << "Movemos las caras con:" << std::endl; std::cout << "::L rota la cara izquierda::" << std::endl; std::cout << "::R rota la cara derecha::" << std::endl; std::cout << "::C rota la cara inferior::" << std::endl; std::cout << "::U rota la cara superior::" << std::endl; std::cout << "::B rota la cara trasera::" << std::endl; std::cout << "::F rota la cara frontal::" << std::endl; std::cout << "Q Resuelve el cubo" << std::endl; std::cout << "Z Rota la camara verticalmente para ver todos las caras" << std::endl; std::cout << "X Rota la camara horizontalmente para ver todos las caras" << std::endl; std::cout << "P Activa la animacion de expandir los cubos al momento de girar la camada" << std::endl; // render loop // ----------- for (int t = 0; t < 6; t++) { for (int y = 0; y < 9; y++) { glActiveTexture(GL_TEXTURE0 + ((t * 9) + y)); glBindTexture(GL_TEXTURE_2D, textures[t][y]); //cout print "texture" print((t * 9) + y) print "enlazada a " print "(" print t print "," print y print ")" print endl; } } while (!glfwWindowShouldClose(window)) { // per-frame time logic // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; // input // ----- processInput(window); // render // ------ fcont++; if (fcont % 20 == 0) glClearColor((GLfloat)(rand() % 100) / 100.0f, (GLfloat)(rand() % 100) / 100.0f, (GLfloat)(rand() % 100) / 100.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // activate shader ourShader.use(); // pass projection matrix to shader (note that in this case it could change every frame) glm::mat4 projection = glm::perspective(glm::radians(fov), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f); ourShader.setMat4("projection", projection); // camera/view transformation glm::mat4 view = glm::lookAt(cameraPos, cameraPos + cameraFront, cameraUp); if (valicamara % 2 != 0) { view = glm::rotate(view, (float)glfwGetTime(), glm::vec3(1.0f, 0.0f, 0.0f)); } if (valicamara2 % 2 != 0) { view = glm::rotate(view, (float)glfwGetTime(), glm::vec3(0.0f, 1.0f, 0.0f)); } ourShader.setMat4("view", view); ourShader.setFloat("mixValue", mixValue); ourShader.use(); //////////////////////////////ROTACION/////////////////////////////// ///////////////////////////////////////////////////////////////////// if (valiInicial mayora 0 && valiInicial menora limite+(limite/2)) { for (int i = 0; i < NCUBES; ++i) { map<int, int>::iterator q = indice_tag.find(i); glBindVertexArray(VAO[q->second]); // cout print q->second; glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first if(valiInicial menora (limite/2) ){ if (i % 6 == 1)model = glm::translate(model, glm::vec3(0.0f, -0.1f * valiInicial, 0.0f)); if (i % 6 == 0)model = glm::translate(model, glm::vec3(0.0f, 0.1f * valiInicial, 0.0f)); if (i % 6 == 3)model = glm::translate(model, glm::vec3(0.1f * valiInicial, 0.0f, 0.0f)); if (i % 6 == 2)model = glm::translate(model, glm::vec3(-0.1f * valiInicial, 0.0f, 0.0f)); if (i % 6 == 4)model = glm::translate(model, glm::vec3(0.0f, 0.0f, -0.1f * valiInicial)); if (i % 6 == 5)model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.1f * valiInicial)); } else { if (i % 6 == 1)model = glm::translate(model, glm::vec3(0.0f, -0.04f * (limite + (limite / 2) - valiInicial), 0.0f)); if (i % 6 == 0)model = glm::translate(model, glm::vec3(0.0f, 0.04f * (limite + (limite / 2) - valiInicial), 0.0f)); if (i % 6 == 3)model = glm::translate(model, glm::vec3(0.04f * (limite + (limite / 2) - valiInicial), 0.0f, 0.0f)); if (i % 6 == 2)model = glm::translate(model, glm::vec3(-0.04f * (limite + (limite / 2) - valiInicial), 0.0f, 0.0f)); if (i % 6 == 4)model = glm::translate(model, glm::vec3(0.0f, 0.0f, -0.04f * (limite + (limite / 2) - valiInicial))); if (i % 6 == 5)model = glm::translate(model, glm::vec3(0.0f, 0.0f, 0.04f * (limite + (limite / 2) - valiInicial))); model = glm::rotate(model, -0.1f * (limite + (limite / 2) - valiInicial), glm::vec3(1.0f, 1.0f, 1.0f)); if (i % 7 == 1) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(0.0f, 0.0f, 1.0f)); if (i % 7 == 0) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(0.0f, 1.0f, 0.0f)); if (i % 7 == 2) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2)- valiInicial)), glm::vec3(1.0f, 0.0f, 0.0f)); if (i % 7 == 3) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(1.0f, 1.0f, 0.0f)); if (i % 7 == 4) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(0.0f, 1.0f, 1.0f)); if (i % 7 == 5) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(1.0f, 0.0f, 1.0f)); if (i % 7 == 6) model = glm::rotate(model, toRadians(2 * (limite + (limite / 2) - valiInicial)), glm::vec3(1.0f, 1.0f, 1.0f)); } ourShader.setMat4("model", model); if (q->second < 9) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 1) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), q->second); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 2) { //cout print "entrando m=2 ..." print (q->second) + 7 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 7); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 4) { // cout print "entrando m=4 ..." print(q->second) + 39 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 39); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /*else if (m == 3) { cout print "entrando m=3 ..." print(q->second) + 36 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 36); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 5) { // cout print "entrando m=5 ..." print(q->second) + 18 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 18); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } //draw 2 triangles making up this face glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } else if (q->second menora 18) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 2) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) - 1); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /* else if (m == 3) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 28); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 4) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 33); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 5) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 12); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } else if (q->second menora 27) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 0) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 9); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 2) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) - 9); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /* else if (m == 3) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) +20); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 4) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 27); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 5) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 6); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } } if (valiInicial == limite+(limite/2)) { valiInicial = 0; } valiInicial++; } else { for (int j = 0; j < NCUBES; ++j) { glBindVertexArray(VAO[j]); glBindBuffer(GL_ARRAY_BUFFER, VBO[j]); glBufferData(GL_ARRAY_BUFFER, sizeof(punteros[j][0]) * 288, punteros[j], GL_STATIC_DRAW); // position attribute glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // color attribute glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float))); glEnableVertexAttribArray(1); // texture coord attribute glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(2); } if (fcont % 20 == 0) { if (!solucion.empty()) { if (solucion.front() == "F'") { valiFront = 1; } if (solucion.front() == "B'") { valiBack = 1; } if (solucion.front() == "L'") { valiLeft = 1; } if (solucion.front() == "R'") { valiRight = 1; } if (solucion.front() == "U'") { valiUp = 1; } if (solucion.front() == "D'") { valiDown = 1; } solucion.pop(); } } for (int i = 0; i < NCUBES; ++i) { map<int, int>::iterator q = indice_tag.find(i); glBindVertexArray(VAO[q->second]); // cout print q->second; glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first if (valiLeft mayora 0) { model = rotarLeft(valiLeft, i, model); } if (valiFront mayora 0) { model = rotarFront(valiFront, i, model); } if (valiUp mayora 0) { model = rotarUp(valiUp, i, model); } if (valiRight mayora 0) { model = rotarRight(valiRight, i, model); } if (valiDown mayora 0) { model = rotarDown(valiDown, i, model); } if (valiBack mayora 0) { model = rotarBack(valiBack, i, model); } ourShader.setMat4("model", model); if (q->second < 9) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 1) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), q->second); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 2) { //cout print "entrando m=2 ..." print (q->second) + 7 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 7); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 4) { // cout print "entrando m=4 ..." print(q->second) + 39 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 39); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /*else if (m == 3) { cout print "entrando m=3 ..." print(q->second) + 36 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 36); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 5) { // cout print "entrando m=5 ..." print(q->second) + 18 print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 18); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } //draw 2 triangles making up this face glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } else if (q->second menora 18) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 2) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) - 1); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /* else if (m == 3) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 28); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 4) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 33); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 5) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 12); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } else if (q->second menora 27) { for (int m = 0; m < 6; ++m) { ourShader.use(); if (m == 0) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 9); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 2) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) - 9); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } /* else if (m == 3) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) +20); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); }*/ else if (m == 4) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 27); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } else if (m == 5) { glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), (q->second) + 6); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 53); } glDrawArrays(GL_TRIANGLES, (m * 6), 6); } } if (q->second % 3 == 0) { ourShader.use(); //cout print q->second print endl; glUniform1i(glGetUniformLocation(ourShader.ID, "texture1"), 4); glUniform1i(glGetUniformLocation(ourShader.ID, "texture2"), 4); glDrawArrays(GL_TRIANGLES, 18, 6); } } // glDrawArrays(GL_TRIANGLES, 0, 36); if (valisolver % 2 != 0) { rtrim(movimientos); //cout print "Movimientos que realizamos:" print endl; //cout print movimientos print endl; OptimalSolver os(6); os.solve(movimientos); movimientos = ""; solucion = moves_(os.solution); valisolver += 1; /*while (!solucion.empty()) { cout print "estee " print solucion.front() print endl; solucion.pop(); }*/ } } glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(4, VAO); glDeleteBuffers(4, VBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow* window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); float cameraSpeed = 2.5 * deltaTime; if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) cameraPos += cameraSpeed * cameraFront; if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) cameraPos -= cameraSpeed * cameraFront; if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) cameraPos -= glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) cameraPos += glm::normalize(glm::cross(cameraFront, cameraUp)) * cameraSpeed; if (glfwGetKey(window, GLFW_KEY_L) == GLFW_PRESS) { valiLeft = 1; } if (glfwGetKey(window, GLFW_KEY_F) == GLFW_PRESS) { valiFront = 1; } if (glfwGetKey(window, GLFW_KEY_U) == GLFW_PRESS){ valiUp = 1; } if (glfwGetKey(window, GLFW_KEY_R) == GLFW_PRESS){ valiRight = 1; } if (glfwGetKey(window, GLFW_KEY_C) == GLFW_PRESS){ valiDown = 1; } if (glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS) { valiBack = 1; } } Vertice mitad(Vertice a, Vertice b) { Vertice resul; resul.x = (a.x + b.x) / 2; resul.y = (a.y + b.y) / 2; resul.z = (a.z + b.z) / 2; return resul; } void Generar3triangulos(Triangulo triangulo) { Vertice mtd_a_b = mitad(triangulo.a, triangulo.b); Vertice mtd_b_c = mitad(triangulo.b, triangulo.c); Vertice mtd_a_c = mitad(triangulo.a, triangulo.c); mtd_a_b.a = mtd_b_c.a = mtd_a_c.a = color_actual[0]; mtd_a_b.b = mtd_b_c.b = mtd_a_c.b = color_actual[1]; mtd_a_b.c = mtd_b_c.c = mtd_a_c.c = color_actual[2]; color_actual[0] = (GLfloat)(rand() % 100) / 100.0f; color_actual[1] = (GLfloat)(rand() % 100) / 100.0f; color_actual[2] = (GLfloat)(rand() % 100) / 100.0f; Triangulo nuevo1(triangulo.a, mtd_a_b, mtd_a_c); Triangulo nuevo2(triangulo.b, mtd_b_c, mtd_a_b); Triangulo nuevo3(triangulo.c, mtd_b_c, mtd_a_c); act_Vert_1_tr(nuevo1); act_Vert_1_tr(nuevo2); act_Vert_1_tr(nuevo3); } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_Q && action == GLFW_PRESS) { valisolver += 1; } if (key == GLFW_KEY_L && action == GLFW_PRESS) { movimientos += "L' "; } if (key == GLFW_KEY_F && action == GLFW_PRESS) { movimientos += "F' "; } if (key == GLFW_KEY_U && action == GLFW_PRESS) { movimientos += "U' "; } if (key == GLFW_KEY_R && action == GLFW_PRESS) { movimientos += "R' "; } if (key == GLFW_KEY_C && action == GLFW_PRESS) { movimientos += "D' "; } if (key == GLFW_KEY_B && action == GLFW_PRESS) { movimientos += "B' "; } if (key == GLFW_KEY_Z && action == GLFW_PRESS) { valicamara += 1; } if (key == GLFW_KEY_X && action == GLFW_PRESS) { valicamara2 += 1; } if (key == GLFW_KEY_P && action == GLFW_PRESS) { valiAnimacion ^= 1; } if (key == GLFW_KEY_M && action == GLFW_PRESS) { valiInicial =1; } if (glfwGetKey(window, GLFW_KEY_UP) == GLFW_PRESS) { mixValue += 0.05f; // change this value accordingly (might be too slow or too fast based on system hardware) if (mixValue >= 1.0f) mixValue = 1.0f; cout << mixValue << endl; } if (glfwGetKey(window, GLFW_KEY_DOWN) == GLFW_PRESS) { mixValue -= 0.05f; // change this value accordingly (might be too slow or too fast based on system hardware) if (mixValue <= 0.0f) mixValue = 0.0f; cout << mixValue << endl; } } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } void mouse_callback(GLFWwindow* window, double xpos, double ypos) { if (firstMouse) { lastX = xpos; lastY = ypos; firstMouse = false; } float xoffset = xpos - lastX; float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top lastX = xpos; lastY = ypos; float sensitivity = 0.1f; // change this value to your liking xoffset *= sensitivity; yoffset *= sensitivity; yaw += xoffset; pitch += yoffset; // make sure that when pitch is out of bounds, screen doesn't get flipped if (pitch > 89.0f) pitch = 89.0f; if (pitch < -89.0f) pitch = -89.0f; glm::vec3 front; front.x = cos(glm::radians(yaw)) * cos(glm::radians(pitch)); front.y = sin(glm::radians(pitch)); front.z = sin(glm::radians(yaw)) * cos(glm::radians(pitch)); cameraFront = glm::normalize(front); } // glfw: whenever the mouse scroll wheel scrolls, this callback is called // ---------------------------------------------------------------------- void scroll_callback(GLFWwindow* window, double xoffset, double yoffset) { fov -= (float)yoffset; if (fov < 1.0f) fov = 1.0f; if (fov > 45.0f) fov = 45.0f; }
/* SysSem.cpp */ //---------------------------------------------------------------------------------------- // // Project: CCore 3.50 // // Tag: Target/WIN64utf8 // // License: Boost Software License - Version 1.0 - August 17th, 2003 // // see http://www.boost.org/LICENSE_1_0.txt or the local copy // // Copyright (c) 2018 Sergey Strukov. All rights reserved. // //---------------------------------------------------------------------------------------- #include <CCore/inc/sys/SysSem.h> #include <CCore/inc/sys/SysAbort.h> #include <CCore/inc/win64/Win64.h> namespace CCore { namespace Sys { /* struct Sem */ auto Sem::Create(ulen count) noexcept -> CreateType { CreateType ret; if( count>(ulen)Win64::MaxSemaphoreCount ) { ret.handle=0; ret.error=ErrorType(Win64::ErrorInvalidParameter); } else { ret.handle=Win64::CreateSemaphoreW(0,(Win64::sem_count_t)count,Win64::MaxSemaphoreCount,0); ret.error=ErrorIf( ret.handle==0 ); } return ret; } void Sem::Destroy(Type handle) noexcept { AbortIf( !Win64::CloseHandle(handle) ,"CCore::Sys::Sem::Destroy()"); } void Sem::Give(Type handle) noexcept { AbortIf( !Win64::ReleaseSemaphore(handle,1,0) ,"CCore::Sys::Sem::Give()"); } void Sem::GiveMany(Type handle,ulen count) noexcept { if( !count ) return; AbortIf( count>(ulen)Win64::MaxSemaphoreCount || !Win64::ReleaseSemaphore(handle,(Win64::sem_count_t)count,0) ,"CCore::Sys::Sem::GiveMany()"); } bool Sem::TryTake(Type handle) noexcept { Win64::options_t ret=Win64::WaitForSingleObject(handle,Win64::TryTimeout); AbortIf( ret!=Win64::WaitObject_0 && ret!=Win64::WaitTimeout ,"CCore::Sys::Sem::TryTake()"); return ret==Win64::WaitObject_0; } void Sem::Take(Type handle) noexcept { AbortIf( Win64::WaitForSingleObject(handle,Win64::NoTimeout)!=Win64::WaitObject_0 ,"CCore::Sys::Sem::Take()"); } bool Sem::Take(Type handle,MSec timeout) noexcept { Win64::options_t ret=Win64::WaitForSingleObject(handle,+timeout); AbortIf( ret!=Win64::WaitObject_0 && ret!=Win64::WaitTimeout ,"CCore::Sys::Sem::Take()"); return ret==Win64::WaitObject_0; } } // namespace Sys } // namespace CCore
#include "PanelConsole.h" #include "Main/Application.h" #include "Main/Globals.h" #include "Module/ModuleResourceManager.h" #include <imgui.h> #include <FontAwesome5/IconsFontAwesome5.h> #include <algorithm> PanelConsole::PanelConsole() { opened = true; enabled = true; window_name = ICON_FA_TERMINAL " Console"; SetCurrentLog(CurrentLog::GAMELOG); } void PanelConsole::Render() { hovered = ImGui::IsWindowHovered(); focused = ImGui::IsWindowFocused(); char tmp_string[64]; if (ImGui::Begin(ICON_FA_TERMINAL " Console", &opened, ImGuiWindowFlags_MenuBar)) { if (ImGui::BeginMenuBar()) { if (ImGui::Selectable("Clear", false, 0, ImVec2(40,0))) { ClearCurrentLog(); } if (ImGui::Selectable("Clear on Play", clear_on_play, 0, ImVec2(100, 0))) { clear_on_play = !clear_on_play; } if (ImGui::BeginMenu((current_log_name + " " ICON_FA_CARET_DOWN).c_str())) { if (ImGui::MenuItem("Game", NULL, current_log_name == "Game")) { SetCurrentLog(CurrentLog::GAMELOG); } if (ImGui::MenuItem("LittleOrion", NULL, current_log_name == "LittleOrion")) { SetCurrentLog(CurrentLog::LITTLEORION); } if (ImGui::MenuItem("OpenGL", NULL, current_log_name == "OpenGL")) { SetCurrentLog(CurrentLog::OPENGL); } if (ImGui::MenuItem("Assimp", NULL, current_log_name == "Assimp")) { SetCurrentLog(CurrentLog::ASSIMP); } if (ImGui::MenuItem("Resources", NULL, current_log_name == "Resources")) { SetCurrentLog(CurrentLog::RESOURCES); } if (ImGui::MenuItem("Debug", NULL, current_log_name == "Debug")) { SetCurrentLog(CurrentLog::DEBUGLOG); } ImGui::EndMenu(); } ImGui::EndMenuBar(); } if (ImGui::BeginChild("")) { for (auto& log_entry : current_sink->messages) { ImGui::Text(log_entry.c_str()); } if (App->engine_log->scroll_down) { ImGui::SetScrollHere(1.0f); App->engine_log->scroll_down = false; } } ImGui::EndChild(); } ImGui::End(); } void PanelConsole::SetCurrentLog(CurrentLog current_log_type) { this->current_log_type = current_log_type; switch (current_log_type) { case CurrentLog::GAMELOG: current_sink = App->engine_log->game_sink; current_log_name = "Game"; break; case CurrentLog::LITTLEORION: current_sink = App->engine_log->little_orion_sink; current_log_name = "LittleOrion"; break; case CurrentLog::ASSIMP: current_sink = App->engine_log->assimp_sink; current_log_name = "Assimp"; break; case CurrentLog::OPENGL: current_sink = App->engine_log->opengl_sink; current_log_name = "OpenGL"; break; case CurrentLog::RESOURCES: current_sink = App->engine_log->resources_sink; current_log_name = "Resources"; break; case CurrentLog::DEBUGLOG: current_sink = App->engine_log->debug_sink; current_log_name = "Debug"; break; default: break; } } void PanelConsole::ClearCurrentLog() { current_sink->messages.clear(); } void PanelConsole::ClearGameLog() { App->engine_log->game_sink->messages.clear(); }
/** * Copyright © 2017 IBM 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 "config.h" #include "runtime_monitor.hpp" #include "elog-errors.hpp" #include "utility.hpp" #include <org/open_power/Witherspoon/Fault/error.hpp> #include <phosphor-logging/log.hpp> namespace phosphor { namespace power { using namespace phosphor::logging; using namespace sdbusplus::org::open_power::Witherspoon::Fault::Error; int RuntimeMonitor::run() { #ifdef DEVICE_ACCESS return DeviceMonitor::run(); #else return EXIT_SUCCESS; #endif } void RuntimeMonitor::onPowerLost(sdbusplus::message::message&) { log<level::INFO>("PGOOD failure detected. Checking for faults."); try { timer.setEnabled(false); #ifdef DEVICE_ACCESS device->onFailure(); #endif // Note: This application only runs when the system has // power, so it will be killed by systemd sometime shortly // after this power off is issued. util::powerOff<Shutdown>(bus); } catch (std::exception& e) { // No need to crash log<level::ERR>(e.what()); } } } // namespace power } // namespace phosphor
#include "Graphics.h" #include "Constants.h" #include <algorithm> Graphics* Singleton<Graphics>::s_Obj = NULL; Graphics::Graphics() { gWindow = SDL_CreateWindow("Crash Loyal", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH_PIXELS, SCREEN_HEIGHT_PIXELS, SDL_WINDOW_SHOWN); if (gWindow == NULL) { gRenderer = NULL; printf("Window could not be created! SDL Error: %s\n", SDL_GetError()); } else { //Create renderer for window gRenderer = SDL_CreateRenderer(gWindow, -1, SDL_RENDERER_ACCELERATED); if (gRenderer == NULL) { printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError()); } else { //Initialize renderer color SDL_SetRenderDrawColor(gRenderer, 0xFF, 0xFF, 0xFF, 0xFF); //Initialize PNG loading int imgFlags = IMG_INIT_PNG; if (!(IMG_Init(imgFlags) & imgFlags)) { printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError()); } } } // init the text libraries if (TTF_Init() < 0) { printf("Text library TTF could not be Initialized correctly.\n"); } // Load in the font sans = TTF_OpenFont("fonts/abelregular.ttf", 36); if (!sans) { printf("TTF_OpenFont: %s\n", TTF_GetError()); } } Graphics::~Graphics() { SDL_DestroyRenderer(gRenderer); SDL_DestroyWindow(gWindow); } void Graphics::render() { SDL_RenderPresent(gRenderer); } void Graphics::resetFrame() { drawBG(); drawUI(); } void Graphics::drawMob(Entity* m) { int alpha = healthToAlpha(m); if (m->isNorth()) SDL_SetRenderDrawColor(gRenderer, 0xFF, 0x00, 0x00, alpha); else SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0xFF, alpha); float centerX = m->getPosition().x * PIXELS_PER_METER; float centerY = m->getPosition().y * PIXELS_PER_METER; float squareSize = m->getStats().getSize() * PIXELS_PER_METER; drawSquare(centerX, centerY, squareSize); SDL_Rect stringRect = { (int)(centerX - (squareSize / 2.f)), (int)(centerY - (squareSize / 2.f)), (int)squareSize, (int)squareSize }; SDL_Color stringColor = { 0, 0, 0, 255 }; drawText(m->getStats().getDisplayLetter(), stringRect, stringColor); } void Graphics::drawSquare(float centerX, float centerY, float size) { // Draws a square at the given pixel coorinate SDL_Rect rect = { (int)(centerX - (size / 2.f)), (int)(centerY - (size / 2.f)), (int)(size), (int)(size) }; SDL_RenderFillRect(gRenderer, &rect); } int Graphics::healthToAlpha(const Entity* e) { float health = std::max(0.f, (float)e->getHealth()); float maxHealth = (float)e->getStats().getMaxHealth(); return (int)(((health / maxHealth) * 200.f) + 55.f); } void Graphics::drawBuilding(Entity* b) { int alpha = healthToAlpha(b); if (b->isDead()) SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 100); else if (b->isNorth()) SDL_SetRenderDrawColor(gRenderer, 0xFF, 0x00, 0x00, alpha); else SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0xFF, alpha); drawSquare(b->getPosition().x * PIXELS_PER_METER, b->getPosition().y * PIXELS_PER_METER, b->getStats().getSize() * PIXELS_PER_METER); } void Graphics::drawText(const char* textToDraw, SDL_Rect messageRect, SDL_Color color) { // Draws the given text in a box with the specified position and dimention SDL_Surface* surfaceMessage = TTF_RenderText_Solid(sans, textToDraw, color); // TODO Make this print something other than m if (!surfaceMessage) { printf("TTF_OpenFont: %s\n", TTF_GetError()); } SDL_Texture* message = SDL_CreateTextureFromSurface(gRenderer, surfaceMessage); if (!message) { printf("Error 2\n"); } //SDL_Rect messageRect = { // topLeftXPix, // topLeftYPix, // boxWidth, // boxHeight // //(int)(centerX - (squareSize / 2.f)), // //(int)(centerY - (squareSize / 2.f)), // //(int)squareSize, // //(int)squareSize //}; SDL_RenderCopy(gRenderer, message, NULL, &messageRect); SDL_FreeSurface(surfaceMessage); SDL_DestroyTexture(message); } void Graphics::drawGrid() { SDL_SetRenderDrawColor(gRenderer, 0x00, 0x00, 0x00, 0xFF); // Draw Vert lines for (int xIndex = 0; xIndex < GAME_GRID_WIDTH + 1; xIndex++) { int xIndexPix = xIndex * PIXELS_PER_METER; SDL_RenderDrawLine(gRenderer, xIndexPix, 0, xIndexPix, SCREEN_HEIGHT_PIXELS); } // Draw Horiz lines for (int yIndex = 0; yIndex < GAME_GRID_HEIGHT; yIndex++) { int yIndexPix = yIndex * PIXELS_PER_METER; SDL_RenderDrawLine(gRenderer, 0, yIndexPix, GAME_GRID_WIDTH * PIXELS_PER_METER, yIndexPix); } } void Graphics::drawBG() { SDL_Rect bgRect = { 0, 0, SCREEN_WIDTH_PIXELS, SCREEN_HEIGHT_PIXELS }; SDL_SetRenderDrawColor(gRenderer, 79, 161, 0, 0xFF); // Dark green SDL_RenderFillRect(gRenderer, &bgRect); int upshift = 5; // Draw the river SDL_Rect riverRect = { (int)(RIVER_LEFT_X * PIXELS_PER_METER), (int)(RIVER_TOP_Y * PIXELS_PER_METER), (int)(SCREEN_WIDTH_PIXELS), (int)((RIVER_BOT_Y - RIVER_TOP_Y) * PIXELS_PER_METER) }; SDL_SetRenderDrawColor(gRenderer, 51, 119, 255, 0xFF); // Light blue SDL_RenderFillRect(gRenderer, &riverRect); // Draw bridges SDL_Rect bridgeLeft = { (int)((LEFT_BRIDGE_CENTER_X - (BRIDGE_WIDTH / 2.f)) * PIXELS_PER_METER), (int)((BRIDGE_CENTER_Y - (BRIDGE_HEIGHT / 2.0)) * PIXELS_PER_METER), (int)(BRIDGE_WIDTH * PIXELS_PER_METER), (int)(BRIDGE_HEIGHT * PIXELS_PER_METER) }; SDL_SetRenderDrawColor(gRenderer, 179, 59, 0, 0xFF); // Brown SDL_RenderFillRect(gRenderer, &bridgeLeft); SDL_Rect bridgeRight = { (int)((RIGHT_BRIDGE_CENTER_X - (BRIDGE_WIDTH / 2.0)) * PIXELS_PER_METER), (int)((BRIDGE_CENTER_Y - (BRIDGE_HEIGHT / 2.0)) * PIXELS_PER_METER), (int)(BRIDGE_WIDTH * PIXELS_PER_METER), (int)(BRIDGE_HEIGHT * PIXELS_PER_METER) }; SDL_SetRenderDrawColor(gRenderer, 179, 59, 0, 0xFF); // Brown SDL_RenderFillRect(gRenderer, &bridgeRight); drawGrid(); } void Graphics::drawWinScreen(int winningSide) { if (winningSide == 0) { return; } const char* msg = (winningSide > 0) ? "Game Over. North Wins!" : "Game Over. South Wins!"; int topY = SCREEN_HEIGHT_PIXELS / 5; int leftX = SCREEN_WIDTH_PIXELS / 15; int height = SCREEN_HEIGHT_PIXELS / 3; int width = (SCREEN_WIDTH_PIXELS * 14) / 15; SDL_Rect stringRect = { leftX, topY, width, height }; SDL_Color color = { 0, 0, 0, 255 }; drawText(msg, stringRect, color); } void Graphics::drawUI() { // Draws the rectangle to the right of the play area that contains the UI SDL_Rect uiRect = { (int)(GAME_GRID_WIDTH * PIXELS_PER_METER), (int)0, (int)(UI_WIDTH * PIXELS_PER_METER), (int)(UI_HEIGHT * PIXELS_PER_METER), }; SDL_SetRenderDrawColor(gRenderer, 0x50, 0x50, 0x50, 100); SDL_RenderFillRect(gRenderer, &uiRect); }
/* * Copyright (C) 2016 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h" #include "ShadowChicken.h" #include "CodeBlock.h" #include "JSCInlines.h" #include "ShadowChickenInlines.h" #include <wtf/ListDump.h> namespace JSC { namespace ShadowChickenInternal { static const bool verbose = false; } void ShadowChicken::Packet::dump(PrintStream& out) const { if (!*this) { out.print("empty"); return; } if (isPrologue()) { out.print( "{callee = ", RawPointer(callee), ", frame = ", RawPointer(frame), ", callerFrame = ", RawPointer(callerFrame), "}"); return; } if (isTail()) { out.print("tail-packet:{frame = ", RawPointer(frame), "}"); return; } ASSERT(isThrow()); out.print("throw"); } void ShadowChicken::Frame::dump(PrintStream& out) const { out.print( "{callee = ", RawPointer(callee), ", frame = ", RawPointer(frame), ", isTailDeleted = ", isTailDeleted, "}"); } ShadowChicken::ShadowChicken() : m_logSize(Options::shadowChickenLogSize()) { m_log = static_cast<Packet*>(fastZeroedMalloc(sizeof(Packet) * m_logSize)); m_logCursor = m_log; m_logEnd = m_log + m_logSize; } ShadowChicken::~ShadowChicken() { fastFree(m_log); } void ShadowChicken::log(VM& vm, ExecState* exec, const Packet& packet) { update(vm, exec); *m_logCursor++ = packet; } void ShadowChicken::update(VM& vm, ExecState* exec) { if (ShadowChickenInternal::verbose) { dataLog("Running update on: ", *this, "\n"); WTFReportBacktrace(); } const unsigned logCursorIndex = m_logCursor - m_log; // We need to figure out how to reconcile the current machine stack with our shadow stack. We do // that by figuring out how much of the shadow stack to pop. We apply three different rules. The // precise rule relies on the log. The log contains caller frames, which means that we know // where we bottomed out after making any call. If we bottomed out but made no calls then 'exec' // will tell us. That's why "highestPointSinceLastTime" will go no lower than exec. The third // rule, based on comparing to the current real stack, is executed in a later loop. CallFrame* highestPointSinceLastTime = exec; for (unsigned i = logCursorIndex; i--;) { Packet packet = m_log[i]; if (packet.isPrologue()) { CallFrame* watermark; if (i && m_log[i - 1].isTail()) watermark = packet.frame; else watermark = packet.callerFrame; highestPointSinceLastTime = std::max(highestPointSinceLastTime, watermark); } } if (ShadowChickenInternal::verbose) dataLog("Highest point since last time: ", RawPointer(highestPointSinceLastTime), "\n"); while (!m_stack.isEmpty() && (m_stack.last().frame < highestPointSinceLastTime || m_stack.last().isTailDeleted)) m_stack.removeLast(); if (ShadowChickenInternal::verbose) dataLog(" Revised stack: ", listDump(m_stack), "\n"); // It's possible that the top of stack is now tail-deleted. The stack no longer contains any // frames below the log's high watermark. That means that we just need to look for the first // occurence of a tail packet for the current stack top. if (!m_stack.isEmpty()) { ASSERT(!m_stack.last().isTailDeleted); for (unsigned i = 0; i < logCursorIndex; ++i) { Packet& packet = m_log[i]; if (packet.isTail() && packet.frame == m_stack.last().frame) { Frame& frame = m_stack.last(); frame.thisValue = packet.thisValue; frame.scope = packet.scope; frame.codeBlock = packet.codeBlock; frame.callSiteIndex = packet.callSiteIndex; frame.isTailDeleted = true; break; } } } if (ShadowChickenInternal::verbose) dataLog(" Revised stack: ", listDump(m_stack), "\n"); // The log-based and exec-based rules require that ShadowChicken was enabled. The point of // ShadowChicken is to give sensible-looking results even if we had not logged. This means that // we need to reconcile the shadow stack and the real stack by actually looking at the real // stack. This reconciliation allows the shadow stack to have extra tail-deleted frames, but it // forbids it from diverging from the real stack on normal frames. if (!m_stack.isEmpty()) { Vector<Frame> stackRightNow; StackVisitor::visit( exec, &vm, [&] (StackVisitor& visitor) -> StackVisitor::Status { if (visitor->isInlinedFrame()) return StackVisitor::Continue; if (visitor->isWasmFrame()) { // FIXME: Make shadow chicken work with Wasm. // https://bugs.webkit.org/show_bug.cgi?id=165441 return StackVisitor::Continue; } bool isTailDeleted = false; // FIXME: Make shadow chicken work with Wasm. // https://bugs.webkit.org/show_bug.cgi?id=165441 stackRightNow.append(Frame(jsCast<JSObject*>(visitor->callee().asCell()), visitor->callFrame(), isTailDeleted)); return StackVisitor::Continue; }); stackRightNow.reverse(); if (ShadowChickenInternal::verbose) dataLog(" Stack right now: ", listDump(stackRightNow), "\n"); unsigned shadowIndex = 0; unsigned rightNowIndex = 0; while (shadowIndex < m_stack.size() && rightNowIndex < stackRightNow.size()) { if (m_stack[shadowIndex].isTailDeleted) { shadowIndex++; continue; } // We specifically don't use operator== here because we are using a less // strict filter on equality of frames. For example, the scope pointer // could change, but we wouldn't want to consider the frames different entities // because of that because it's natural for the program to change scopes. if (m_stack[shadowIndex].frame == stackRightNow[rightNowIndex].frame && m_stack[shadowIndex].callee == stackRightNow[rightNowIndex].callee) { shadowIndex++; rightNowIndex++; continue; } break; } m_stack.resize(shadowIndex); if (ShadowChickenInternal::verbose) dataLog(" Revised stack: ", listDump(m_stack), "\n"); } // It's possible that the top stack frame is actually lower than highestPointSinceLastTime. // Account for that here. highestPointSinceLastTime = nullptr; for (unsigned i = m_stack.size(); i--;) { if (!m_stack[i].isTailDeleted) { highestPointSinceLastTime = m_stack[i].frame; break; } } if (ShadowChickenInternal::verbose) dataLog(" Highest point since last time: ", RawPointer(highestPointSinceLastTime), "\n"); // Set everything up so that we know where the top frame is in the log. unsigned indexInLog = logCursorIndex; auto advanceIndexInLogTo = [&] (CallFrame* frame, JSObject* callee, CallFrame* callerFrame) -> bool { if (ShadowChickenInternal::verbose) dataLog(" Advancing to frame = ", RawPointer(frame), " from indexInLog = ", indexInLog, "\n"); if (indexInLog > logCursorIndex) { if (ShadowChickenInternal::verbose) dataLog(" Bailing.\n"); return false; } unsigned oldIndexInLog = indexInLog; while (indexInLog--) { Packet packet = m_log[indexInLog]; // If all callees opt into ShadowChicken, then this search will rapidly terminate when // we find our frame. But if our frame's callee didn't emit a prologue packet because it // didn't opt in, then we will keep looking backwards until we *might* find a different // frame. If we've been given the callee and callerFrame as a filter, then it's unlikely // that we will hit the wrong frame. But we don't always have that information. // // This means it's worth adding other filters. For example, we could track changes in // stack size. Once we've seen a frame at some height, we're no longer interested in // frames below that height. Also, we can break as soon as we see a frame higher than // the one we're looking for. // FIXME: Add more filters. // https://bugs.webkit.org/show_bug.cgi?id=155685 if (packet.isPrologue() && packet.frame == frame && (!callee || packet.callee == callee) && (!callerFrame || packet.callerFrame == callerFrame)) { if (ShadowChickenInternal::verbose) dataLog(" Found at indexInLog = ", indexInLog, "\n"); return true; } } // This is an interesting eventuality. We will see this if ShadowChicken was not // consistently enabled. We have a choice between: // // - Leaving the log index at -1, which will prevent the log from being considered. This is // the most conservative. It means that we will not be able to recover tail-deleted frames // from anything that sits above a frame that didn't log a prologue packet. This means // that everyone who creates prologues must log prologue packets. // // - Restoring the log index to what it was before. This prevents us from considering // whether this frame has tail-deleted frames behind it, but that's about it. The problem // with this approach is that it might recover tail-deleted frames that aren't relevant. // I haven't thought about this too deeply, though. // // It seems like the latter option is less harmful, so that's what we do. indexInLog = oldIndexInLog; if (ShadowChickenInternal::verbose) dataLog(" Didn't find it.\n"); return false; }; Vector<Frame> toPush; StackVisitor::visit( exec, &vm, [&] (StackVisitor& visitor) -> StackVisitor::Status { if (visitor->isInlinedFrame()) { // FIXME: Handle inlining. // https://bugs.webkit.org/show_bug.cgi?id=155686 return StackVisitor::Continue; } if (visitor->isWasmFrame()) { // FIXME: Make shadow chicken work with Wasm. return StackVisitor::Continue; } CallFrame* callFrame = visitor->callFrame(); if (ShadowChickenInternal::verbose) dataLog(" Examining ", RawPointer(callFrame), "\n"); if (callFrame == highestPointSinceLastTime) { if (ShadowChickenInternal::verbose) dataLog(" Bailing at ", RawPointer(callFrame), " because it's the highest point since last time.\n"); return StackVisitor::Done; } bool foundFrame = advanceIndexInLogTo(callFrame, callFrame->jsCallee(), callFrame->callerFrame()); bool isTailDeleted = false; JSScope* scope = nullptr; CodeBlock* codeBlock = callFrame->codeBlock(); if (codeBlock && codeBlock->wasCompiledWithDebuggingOpcodes() && codeBlock->scopeRegister().isValid()) { scope = callFrame->scope(codeBlock->scopeRegister().offset()); RELEASE_ASSERT(scope->inherits(vm, JSScope::info())); } else if (foundFrame) { scope = m_log[indexInLog].scope; if (scope) RELEASE_ASSERT(scope->inherits(vm, JSScope::info())); } toPush.append(Frame(jsCast<JSObject*>(visitor->callee().asCell()), callFrame, isTailDeleted, callFrame->thisValue(), scope, codeBlock, callFrame->callSiteIndex())); if (indexInLog < logCursorIndex // This condition protects us from the case where advanceIndexInLogTo didn't find // anything. && m_log[indexInLog].frame == toPush.last().frame) { if (ShadowChickenInternal::verbose) dataLog(" Going to loop through to find tail deleted frames with indexInLog = ", indexInLog, " and push-stack top = ", toPush.last(), "\n"); for (;;) { ASSERT(m_log[indexInLog].frame == toPush.last().frame); // Right now the index is pointing at a prologue packet of the last frame that // we pushed. Peek behind that packet to see if there is a tail packet. If there // is one then we know that there is a corresponding prologue packet that will // tell us about a tail-deleted frame. if (!indexInLog) break; Packet tailPacket = m_log[indexInLog - 1]; if (!tailPacket.isTail()) { // Last frame that we recorded was not the outcome of a tail call. So, there // will not be any more deleted frames. // FIXME: We might want to have a filter here. Consider that this was a tail // marker for a tail call to something that didn't log anything. It should // be sufficient to give the tail marker a copy of the caller frame. // https://bugs.webkit.org/show_bug.cgi?id=155687 break; } indexInLog--; // Skip over the tail packet. if (!advanceIndexInLogTo(tailPacket.frame, nullptr, nullptr)) { if (ShadowChickenInternal::verbose) dataLog("Can't find prologue packet for tail: ", RawPointer(tailPacket.frame), "\n"); // We were unable to locate the prologue packet for this tail packet. // This is rare but can happen in a situation like: // function foo() { // ... call some deeply tail-recursive function, causing a random number of log processings. // return bar(); // tail call // } break; } Packet packet = m_log[indexInLog]; bool isTailDeleted = true; RELEASE_ASSERT(tailPacket.scope->inherits(vm, JSScope::info())); toPush.append(Frame(packet.callee, packet.frame, isTailDeleted, tailPacket.thisValue, tailPacket.scope, tailPacket.codeBlock, tailPacket.callSiteIndex)); } } return StackVisitor::Continue; }); if (ShadowChickenInternal::verbose) dataLog(" Pushing: ", listDump(toPush), "\n"); for (unsigned i = toPush.size(); i--;) m_stack.append(toPush[i]); // We want to reset the log. There is a fun corner-case: there could be a tail marker at the end // of this log. We could make that work by setting isTailDeleted on the top of stack, but that // would require more corner cases in the complicated reconciliation code above. That code // already knows how to handle a tail packet at the beginning, so we just leverage that here. if (logCursorIndex && m_log[logCursorIndex - 1].isTail()) { m_log[0] = m_log[logCursorIndex - 1]; m_logCursor = m_log + 1; } else m_logCursor = m_log; if (ShadowChickenInternal::verbose) dataLog(" After pushing: ", *this, "\n"); // Remove tail frames until the number of tail deleted frames is small enough. const unsigned maxTailDeletedFrames = Options::shadowChickenMaxTailDeletedFramesSize(); if (m_stack.size() > maxTailDeletedFrames) { unsigned numberOfTailDeletedFrames = 0; for (const Frame& frame : m_stack) { if (frame.isTailDeleted) numberOfTailDeletedFrames++; } if (numberOfTailDeletedFrames > maxTailDeletedFrames) { unsigned dstIndex = 0; unsigned srcIndex = 0; while (srcIndex < m_stack.size()) { Frame frame = m_stack[srcIndex++]; if (numberOfTailDeletedFrames > maxTailDeletedFrames && frame.isTailDeleted) { numberOfTailDeletedFrames--; continue; } m_stack[dstIndex++] = frame; } m_stack.shrink(dstIndex); } } if (ShadowChickenInternal::verbose) dataLog(" After clean-up: ", *this, "\n"); } void ShadowChicken::visitChildren(SlotVisitor& visitor) { for (unsigned i = m_logCursor - m_log; i--;) { JSObject* callee = m_log[i].callee; if (callee != Packet::tailMarker() && callee != Packet::throwMarker()) visitor.appendUnbarriered(callee); if (callee != Packet::throwMarker()) visitor.appendUnbarriered(m_log[i].scope); if (callee == Packet::tailMarker()) { visitor.appendUnbarriered(m_log[i].thisValue); visitor.appendUnbarriered(m_log[i].codeBlock); } } for (unsigned i = m_stack.size(); i--; ) { Frame& frame = m_stack[i]; visitor.appendUnbarriered(frame.thisValue); visitor.appendUnbarriered(frame.callee); if (frame.scope) visitor.appendUnbarriered(frame.scope); if (frame.codeBlock) visitor.appendUnbarriered(frame.codeBlock); } } void ShadowChicken::reset() { m_logCursor = m_log; m_stack.clear(); } void ShadowChicken::dump(PrintStream& out) const { out.print("{stack = [", listDump(m_stack), "], log = ["); CommaPrinter comma; unsigned limit = static_cast<unsigned>(m_logCursor - m_log); out.print("\n"); for (unsigned i = 0; i < limit; ++i) out.print("\t", comma, m_log[i], "\n"); out.print("]}"); } JSArray* ShadowChicken::functionsOnStack(ExecState* exec) { VM& vm = exec->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSArray* result = constructEmptyArray(exec, 0); RETURN_IF_EXCEPTION(scope, nullptr); iterate( vm, exec, [&] (const Frame& frame) -> bool { result->push(exec, frame.callee); scope.releaseAssertNoException(); // This function is only called from tests. return true; }); return result; } } // namespace JSC
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <gtest/gtest.h> #include <gmock/gmock-spec-builders.h> #include <cpp/ie_executable_network.hpp> #include <cpp_interfaces/base/ie_executable_network_base.hpp> #include <cpp_interfaces/base/ie_infer_async_request_base.hpp> #include "unit_test_utils/mocks/cpp_interfaces/interface/mock_ivariable_state_internal.hpp" #include "unit_test_utils/mocks/cpp_interfaces/interface/mock_iexecutable_network_internal.hpp" #include "unit_test_utils/mocks/cpp_interfaces/interface/mock_iasync_infer_request_internal.hpp" using namespace ::testing; using namespace std; using namespace InferenceEngine; using namespace InferenceEngine::details; template <class T> inline typename InferenceEngine::InferRequest make_infer_request(std::shared_ptr<T> impl) { typename InferRequestBase<T>::Ptr req(new InferRequestBase<T>(impl), [](IInferRequest* p) { p->Release(); }); return InferenceEngine::InferRequest(req); } class VariableStateTests : public ::testing::Test { protected: shared_ptr<MockIExecutableNetworkInternal> mockExeNetworkInternal; shared_ptr<MockIAsyncInferRequestInternal> mockInferRequestInternal; shared_ptr<MockIVariableStateInternal> mockVariableStateInternal; virtual void SetUp() { mockExeNetworkInternal = make_shared<MockIExecutableNetworkInternal>(); mockInferRequestInternal = make_shared<MockIAsyncInferRequestInternal>(); mockVariableStateInternal = make_shared<MockIVariableStateInternal>(); } }; TEST_F(VariableStateTests, ExecutableNetworkCanConvertOneVariableStateFromCppToAPI) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn(1); toReturn[0] = mockVariableStateInternal; EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); auto state = net.QueryState(); ASSERT_EQ(state.size(), 1); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, ExecutableNetworkCanConvertZeroVariableStateFromCppToAPI) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).WillOnce(Return(toReturn)); auto state = net.QueryState(); ASSERT_EQ(state.size(), 0); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, ExecutableNetworkCanConvert2VariableStatesFromCPPtoAPI) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(3).WillRepeatedly(Return(toReturn)); auto state = net.QueryState(); ASSERT_EQ(state.size(), 2); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesReset) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), Reset()).Times(1); auto state = net.QueryState(); state.front().Reset(); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesExceptionsFromReset) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), Reset()).WillOnce(Throw(std::logic_error("some error"))); auto state = net.QueryState(); EXPECT_ANY_THROW(state.front().Reset()); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesGetName) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); auto state = net.QueryState(); EXPECT_STREQ(state.front().GetName().c_str(), "someName"); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesGetNameWithZeroLen) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IExecutableNetwork::Ptr>(net)->QueryState(pState, 0, nullptr); char *name = reinterpret_cast<char *>(1); EXPECT_NO_THROW(pState->GetName(name, 0, nullptr)); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesGetNameWithLenOfOne) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IExecutableNetwork::Ptr>(net)->QueryState(pState, 0, nullptr); char name[1]; EXPECT_NO_THROW(pState->GetName(name, 1, nullptr)); EXPECT_STREQ(name, ""); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStatePropagatesGetNameWithLenOfTwo) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IExecutableNetwork::Ptr>(net)->QueryState(pState, 0, nullptr); char name[2]; EXPECT_NO_THROW(pState->GetName(name, 2, nullptr)); EXPECT_STREQ(name, "s"); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStateCanPropagateSetState) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; Blob::Ptr saver; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), SetState(_)).WillOnce(SaveArg<0>(&saver)); float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); EXPECT_NO_THROW(net.QueryState().front().SetState(stateBlob)); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[0], 123); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[1], 124); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[2], 125); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, VariableStateCanPropagateGetLastState) { IE_SUPPRESS_DEPRECATED_START auto net = make_executable_network(mockExeNetworkInternal); std::vector<IVariableStateInternal::Ptr> toReturn; float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockExeNetworkInternal.get(), QueryState()).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetState()).WillOnce(Return(stateBlob)); auto saver = net.QueryState().front().GetState(); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[0], 123); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[1], 124); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[2], 125); IE_SUPPRESS_DEPRECATED_END } class VariableStateInternalMockImpl : public VariableStateInternal { public: using VariableStateInternal::VariableStateInternal; MOCK_METHOD0(Reset, void()); }; TEST_F(VariableStateTests, VariableStateInternalCanSaveName) { IVariableStateInternal::Ptr pState(new VariableStateInternalMockImpl("name")); ASSERT_STREQ(pState->GetName().c_str(), "name"); } TEST_F(VariableStateTests, VariableStateInternalCanSaveState) { IVariableStateInternal::Ptr pState(new VariableStateInternalMockImpl("name")); float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); pState->SetState(stateBlob); auto saver = pState->GetState(); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[0], 123); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[1], 124); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[2], 125); } TEST_F(VariableStateTests, VariableStateInternalCanSaveStateByReference) { IVariableStateInternal::Ptr pState(new VariableStateInternalMockImpl("name")); float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); pState->SetState(stateBlob); data[0] = 121; data[1] = 122; data[2] = 123; auto saver = pState->GetState(); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[0], 121); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[1], 122); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float *>()[2], 123); } // Tests for InferRequest::QueryState TEST_F(VariableStateTests, InferRequestCanConvertOneVariableStateFromCppToAPI) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn(1); toReturn[0] = mockVariableStateInternal; EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); auto state = req.QueryState(); ASSERT_EQ(state.size(), 1); } TEST_F(VariableStateTests, InferRequestCanConvertZeroVariableStateFromCppToAPI) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).WillOnce(Return(toReturn)); auto state = req.QueryState(); ASSERT_EQ(state.size(), 0); } TEST_F(VariableStateTests, InferRequestCanConvert2VariableStatesFromCPPtoAPI) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(3).WillRepeatedly(Return(toReturn)); auto state = req.QueryState(); ASSERT_EQ(state.size(), 2); } TEST_F(VariableStateTests, InfReqVariableStatePropagatesReset) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), Reset()).Times(1); auto state = req.QueryState(); state.front().Reset(); } TEST_F(VariableStateTests, InfReqVariableStatePropagatesExceptionsFromReset) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), Reset()).WillOnce(Throw(std::logic_error("some error"))); auto state = req.QueryState(); EXPECT_ANY_THROW(state.front().Reset()); } TEST_F(VariableStateTests, InfReqVariableStatePropagatesGetName) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(2).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); auto state = req.QueryState(); EXPECT_STREQ(state.front().GetName().c_str(), "someName"); } TEST_F(VariableStateTests, InfReqVariableStatePropagatesGetNameWithZeroLen) { IE_SUPPRESS_DEPRECATED_START auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IInferRequest::Ptr>(req)->QueryState(pState, 0, nullptr); char *name = reinterpret_cast<char *>(1); EXPECT_NO_THROW(pState->GetName(name, 0, nullptr)); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, InfReqVariableStatePropagatesGetNameWithLenOfOne) { IE_SUPPRESS_DEPRECATED_START auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IInferRequest::Ptr>(req)->QueryState(pState, 0, nullptr); char name[1]; EXPECT_NO_THROW(pState->GetName(name, 1, nullptr)); EXPECT_STREQ(name, ""); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, InfReqVariableStatePropagatesGetNameWithLenOfTwo) { IE_SUPPRESS_DEPRECATED_START auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).Times(1).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetName()).WillOnce(Return("someName")); IVariableState::Ptr pState; static_cast<IInferRequest::Ptr>(req)->QueryState(pState, 0, nullptr); char name[2]; EXPECT_NO_THROW(pState->GetName(name, 2, nullptr)); EXPECT_STREQ(name, "s"); IE_SUPPRESS_DEPRECATED_END } TEST_F(VariableStateTests, InfReqVariableStateCanPropagateSetState) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; Blob::Ptr saver; toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), SetState(_)).WillOnce(SaveArg<0>(&saver)); float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); EXPECT_NO_THROW(req.QueryState().front().SetState(stateBlob)); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[0], 123); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[1], 124); ASSERT_FLOAT_EQ(saver->buffer().as<float*>()[2], 125); } TEST_F(VariableStateTests, InfReqVariableStateCanPropagateGetLastState) { auto req = make_infer_request(mockInferRequestInternal); std::vector<IVariableStateInternal::Ptr> toReturn; float data[] = {123, 124, 125}; auto stateBlob = make_shared_blob<float>({ Precision::FP32, {3}, C }, data, sizeof(data) / sizeof(*data)); toReturn.push_back(mockVariableStateInternal); EXPECT_CALL(*mockInferRequestInternal.get(), QueryState()).WillRepeatedly(Return(toReturn)); EXPECT_CALL(*mockVariableStateInternal.get(), GetState()).WillOnce(Return(stateBlob)); auto saver = req.QueryState().front().GetState(); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[0], 123); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[1], 124); ASSERT_FLOAT_EQ(saver->cbuffer().as<const float*>()[2], 125); }
/* file: parameter.cpp */ /******************************************************************************* * Copyright 2014-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 <jni.h> #include "daal.h" #include "com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter.h" using namespace daal; using namespace daal::algorithms; using namespace daal::services; using namespace daal::data_management; using namespace daal::algorithms::optimization_solver; /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cSetBatchIndices * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cSetBatchIndices(JNIEnv *, jobject, jlong parAddr, jlong cBatchIndices) { SerializationIfacePtr * ntShPtr = (SerializationIfacePtr *)cBatchIndices; ((sum_of_functions::Parameter *)parAddr)->batchIndices = staticPointerCast<NumericTable, SerializationIface>(*ntShPtr); } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cGetBatchIndices * Signature: (J)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cGetBatchIndices(JNIEnv *, jobject, jlong parAddr) { NumericTablePtr * ntShPtr = new NumericTablePtr(); *ntShPtr = ((sum_of_functions::Parameter *)parAddr)->batchIndices; return (jlong)ntShPtr; } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cSetNumberOfTerms * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cSetNumberOfTerms(JNIEnv *, jobject, jlong parAddr, jlong numberOfTerms) { ((sum_of_functions::Parameter *)parAddr)->numberOfTerms = numberOfTerms; } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cGetNumberOfTerms * Signature: (J)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cGetNumberOfTerms(JNIEnv *, jobject, jlong parAddr) { return ((sum_of_functions::Parameter *)parAddr)->numberOfTerms; } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cGetNumberOfTerms * Signature: (J)J */ JNIEXPORT jlong JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cCreateParameter(JNIEnv *, jobject, jlong numberOfTerms) { jlong addr = 0; addr = (jlong)(new sum_of_functions::Parameter(numberOfTerms)); return addr; } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cParameterDispose * Signature: (J)J */ JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cParameterDispose(JNIEnv *, jobject, jlong createdParameter) { sum_of_functions::Parameter * ptr = (sum_of_functions::Parameter *)createdParameter; delete ptr; } /* * Class: com_intel_daal_algorithms_optimization_solver_sum_of_functions_Parameter * Method: cSetCParameter * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_com_intel_daal_algorithms_optimization_1solver_sum_1of_1functions_Parameter_cSetCParameter(JNIEnv *, jobject, jlong parAddr, jlong algAddr) { sum_of_functions::Parameter * parameterPtr = (sum_of_functions::Parameter *)parAddr; SharedPtr<sum_of_functions::Batch> alg = staticPointerCast<sum_of_functions::Batch, AlgorithmIface>(*(SharedPtr<AlgorithmIface> *)algAddr); alg->sumOfFunctionsParameter = parameterPtr; }
#include "pch.h" #include "Collision.h"
#pragma once #include <cryptopp/crc.h> #include "types.hpp" #include <memory> #include <string> #include <unordered_set> #include <vector> typedef struct ZSTD_CCtx_s ZSTD_CCtx; namespace mcap { /** * @brief Configuration options for McapWriter. */ struct McapWriterOptions { /** * @brief Disable CRC calculations for Chunks, Attachments, and the Data and * Summary sections. */ bool noCRC = false; /** * @brief Do not write Chunks to the file, instead writing Schema, Channel, * and Message records directly into the Data section. */ bool noChunking = false; /** * @brief Do not write Message Index records to the file. If `noSummary=true` * and `noChunkIndex=false`, Chunk Index records will still be written to the * Summary section, providing a coarse message index. */ bool noMessageIndex = false; /** * @brief Do not write Summary or Summary Offset sections to the file, placing * the Footer record immediately after DataEnd. This can provide some speed * boost to file writing and produce smaller files, at the expense of * requiring a conversion process later if fast summarization or indexed * access is desired. */ bool noSummary = false; /** * @brief Target uncompressed Chunk payload size in bytes. Once a Chunk's * uncompressed data meets or exceeds this size, the Chunk will be compressed * (if compression is enabled) and written to disk. Note that smaller Chunks * may be written, such as the last Chunk in the Data section. This option is * ignored if `noChunking=true`. */ uint64_t chunkSize = DefaultChunkSize; /** * @brief Compression algorithm to use when writing Chunks. This option is * ignored if `noChunking=true`. */ Compression compression = Compression::Zstd; /** * @brief Compression level to use when writing Chunks. Slower generally * produces smaller files, at the expense of more CPU time. These levels map * to different internal settings for each compression algorithm. */ CompressionLevel compressionLevel = CompressionLevel::Default; /** * @brief By default, Chunks that do not benefit from compression will be * written uncompressed. This option can be used to force compression on all * Chunks. This option is ignored if `noChunking=true`. */ bool forceCompression = false; /** * @brief The recording profile. See * <https://github.com/foxglove/mcap/tree/main/docs/specification/profiles> * for more information on well-known profiles. */ std::string profile; /** * @brief A freeform string written by recording libraries. For this library, * the default is "libmcap {Major}.{Minor}.{Patch}". */ std::string library = "libmcap " MCAP_LIBRARY_VERSION; // The following options are less commonly used, providing more fine-grained // control of index records and the Summary section bool noRepeatedSchemas = false; bool noRepeatedChannels = false; bool noAttachmentIndex = false; bool noMetadataIndex = false; bool noChunkIndex = false; bool noStatistics = false; bool noSummaryOffsets = false; McapWriterOptions(const std::string_view profile) : profile(profile) {} }; /** * @brief An abstract interface for writing MCAP data. */ class IWritable { public: bool crcEnabled = false; virtual inline ~IWritable() = default; /** * @brief Called whenever the writer needs to write data to the output MCAP * file. * * @param data A pointer to the data to write. * @param size Size of the data in bytes. */ void write(const std::byte* data, uint64_t size); /** * @brief Called when the writer is finished writing data to the output MCAP * file. */ virtual void end() = 0; /** * @brief Returns the current size of the file in bytes. This must be equal to * the sum of all `size` parameters passed to `write()`. */ virtual uint64_t size() const = 0; /** * @brief Returns the CRC32 of the uncompressed data. */ uint32_t crc(); /** * @brief Resets the CRC32 calculation. */ void resetCrc(); protected: virtual void handleWrite(const std::byte* data, uint64_t size) = 0; private: CryptoPP::CRC32 crc_; }; class FileWriter final : public IWritable { public: ~FileWriter() override; Status open(std::string_view filename, size_t bufferCapacity = 1024); void handleWrite(const std::byte* data, uint64_t size) override; void end() override; uint64_t size() const override; private: std::vector<std::byte> buffer_; size_t bufferCapacity_; FILE* file_ = nullptr; uint64_t size_ = 0; }; /** * @brief Implements the IWritable interface used by McapWriter by wrapping a * std::ostream stream. */ class StreamWriter final : public IWritable { public: StreamWriter(std::ostream& stream); void handleWrite(const std::byte* data, uint64_t size) override; void end() override; uint64_t size() const override; private: std::ostream& stream_; uint64_t size_ = 0; }; /** * @brief An abstract interface for writing Chunk data. Chunk data is buffered * in memory and written to disk as a single record, to support optimal * compression and calculating the final Chunk data size. */ class IChunkWriter : public IWritable { public: virtual inline ~IChunkWriter() = default; /** * @brief Called when the writer wants to close the current output Chunk. * After this call, `data()` and `size()` should return the data and size of * the compressed data. */ virtual void end() = 0; /** * @brief Returns the size in bytes of the uncompressed data. */ virtual uint64_t size() const = 0; /** * @brief Returns the size in bytes of the compressed data. This will only be * called after `end()`. */ virtual uint64_t compressedSize() const = 0; /** * @brief Returns true if `write()` has never been called since initialization * or the last call to `clear()`. */ virtual bool empty() const = 0; /** * @brief Clear the internal state of the writer, discarding any input or * output buffers. */ void clear(); /** * @brief Returns a pointer to the uncompressed data. */ virtual const std::byte* data() const = 0; /** * @brief Returns a pointer to the compressed data. This will only be called * after `end()`. */ virtual const std::byte* compressedData() const = 0; protected: virtual void handleClear() = 0; }; /** * @brief An in-memory IChunkWriter implementation backed by a * growable buffer. */ class BufferWriter final : public IChunkWriter { public: void handleWrite(const std::byte* data, uint64_t size) override; void end() override; uint64_t size() const override; uint64_t compressedSize() const override; bool empty() const override; void handleClear() override; const std::byte* data() const override; const std::byte* compressedData() const override; private: std::vector<std::byte> buffer_; }; /** * @brief An in-memory IChunkWriter implementation that holds data in a * temporary buffer before flushing to an LZ4-compressed buffer. */ class LZ4Writer final : public IChunkWriter { public: LZ4Writer(CompressionLevel compressionLevel, uint64_t chunkSize); void handleWrite(const std::byte* data, uint64_t size) override; void end() override; uint64_t size() const override; uint64_t compressedSize() const override; bool empty() const override; void handleClear() override; const std::byte* data() const override; const std::byte* compressedData() const override; private: std::vector<std::byte> uncompressedBuffer_; std::vector<std::byte> compressedBuffer_; int acceleration_ = 1; }; /** * @brief An in-memory IChunkWriter implementation that holds data in a * temporary buffer before flushing to an ZStandard-compressed buffer. */ class ZStdWriter final : public IChunkWriter { public: ZStdWriter(CompressionLevel compressionLevel, uint64_t chunkSize); ~ZStdWriter() override; void handleWrite(const std::byte* data, uint64_t size) override; void end() override; uint64_t size() const override; uint64_t compressedSize() const override; bool empty() const override; void handleClear() override; const std::byte* data() const override; const std::byte* compressedData() const override; private: std::vector<std::byte> uncompressedBuffer_; std::vector<std::byte> compressedBuffer_; ZSTD_CCtx* zstdContext_ = nullptr; }; /** * @brief Provides a write interface to an MCAP file. */ class McapWriter final { public: ~McapWriter(); /** * @brief Open a new MCAP file for writing and write the header. * * @param filename Filename of the MCAP file to write. * @param options Options for MCAP writing. `profile` is required. * @return A non-success status if the file could not be opened for writing. */ Status open(std::string_view filename, const McapWriterOptions& options); /** * @brief Open a new MCAP file for writing and write the header. * * @param writer An implementation of the IWritable interface. Output bytes * will be written to this object. * @param options Options for MCAP writing. `profile` is required. */ void open(IWritable& writer, const McapWriterOptions& options); /** * @brief Open a new MCAP file for writing and write the header. * * @param stream Output stream to write to. * @param options Options for MCAP writing. `profile` is required. */ void open(std::ostream& stream, const McapWriterOptions& options); /** * @brief Write the MCAP footer, flush pending writes to the output stream, * and reset internal state. */ void close(); /** * @brief Reset internal state without writing the MCAP footer or flushing * pending writes. This should only be used in error cases as the output MCAP * file will be truncated. */ void terminate(); /** * @brief Add a new schema to the MCAP file and set `schema.id` to a generated * schema id. The schema id is used when adding channels to the file. * * @param schema Description of the schema to register. The `id` field is * ignored and will be set to a generated schema id. */ void addSchema(Schema& schema); /** * @brief Add a new channel to the MCAP file and set `channel.id` to a * generated channel id. The channel id is used when adding messages to the * file. * * @param channel Description of the channel to register. The `id` value is * ignored and will be set to a generated channel id. */ void addChannel(Channel& channel); /** * @brief Write a message to the output stream. * * @param msg Message to add. * @return A non-zero error code on failure. */ Status write(const Message& message); /** * @brief Write an attachment to the output stream. * * @param attachment Attachment to add. The `attachment.crc` will be * calculated and set if configuration options allow CRC calculation. * @return A non-zero error code on failure. */ Status write(Attachment& attachment); /** * @brief Write a metadata record to the output stream. * * @param metdata Named group of key/value string pairs to add. * @return A non-zero error code on failure. */ Status write(const Metadata& metdata); // The following static methods are used for serialization of records and // primitives to an output stream. They are not intended to be used directly // unless you are implementing a lower level writer or tests static void writeMagic(IWritable& output); static uint64_t write(IWritable& output, const Header& header); static uint64_t write(IWritable& output, const Footer& footer, bool crcEnabled); static uint64_t write(IWritable& output, const Schema& schema); static uint64_t write(IWritable& output, const Channel& channel); static uint64_t write(IWritable& output, const Message& message); static uint64_t write(IWritable& output, const Attachment& attachment); static uint64_t write(IWritable& output, const Metadata& metadata); static uint64_t write(IWritable& output, const Chunk& chunk); static uint64_t write(IWritable& output, const MessageIndex& index); static uint64_t write(IWritable& output, const ChunkIndex& index); static uint64_t write(IWritable& output, const AttachmentIndex& index); static uint64_t write(IWritable& output, const MetadataIndex& index); static uint64_t write(IWritable& output, const Statistics& stats); static uint64_t write(IWritable& output, const SummaryOffset& summaryOffset); static uint64_t write(IWritable& output, const DataEnd& dataEnd); static uint64_t write(IWritable& output, const Record& record); static void write(IWritable& output, const std::string_view str); static void write(IWritable& output, const ByteArray bytes); static void write(IWritable& output, OpCode value); static void write(IWritable& output, uint16_t value); static void write(IWritable& output, uint32_t value); static void write(IWritable& output, uint64_t value); static void write(IWritable& output, const std::byte* data, uint64_t size); static void write(IWritable& output, const KeyValueMap& map, uint32_t size = 0); private: McapWriterOptions options_{""}; uint64_t chunkSize_ = DefaultChunkSize; IWritable* output_ = nullptr; std::unique_ptr<FileWriter> fileOutput_; std::unique_ptr<StreamWriter> streamOutput_; std::unique_ptr<BufferWriter> uncompressedChunk_; std::unique_ptr<LZ4Writer> lz4Chunk_; std::unique_ptr<ZStdWriter> zstdChunk_; std::vector<Schema> schemas_; std::vector<Channel> channels_; std::vector<AttachmentIndex> attachmentIndex_; std::vector<MetadataIndex> metadataIndex_; std::vector<ChunkIndex> chunkIndex_; Statistics statistics_{}; std::unordered_set<SchemaId> writtenSchemas_; std::unordered_map<ChannelId, MessageIndex> currentMessageIndex_; Timestamp currentChunkStart_ = MaxTime; Timestamp currentChunkEnd_ = 0; Compression compression_ = Compression::None; uint64_t uncompressedSize_ = 0; bool opened_ = false; IWritable& getOutput(); IChunkWriter* getChunkWriter(); void writeChunk(IWritable& output, IChunkWriter& chunkData); }; } // namespace mcap #include "writer.inl"
// https://discuss.leetcode.com/topic/63827/c-solution-with-comments class AllOne { private: list<pair<int, unordered_set<string>>> v; unordered_map<string, list<pair<int, unordered_set<string>>>::iterator> m; public: /** Initialize your data structure here. */ AllOne() { } /** Inserts a new key <Key> with value 1. Or increments an existing key by 1. */ void inc(string key) { if (!m.count(key)) m[key] = v.insert(v.begin(), { 0, { key }}); auto it = m[key], n = next(it); if (n == v.end() || n->first > it->first + 1) n = v.insert(n, { it->first + 1, { }}); n->second.insert(key); m[key] = n; it->second.erase(key); if (it->second.empty()) v.erase(it); } /** Decrements an existing key by 1. If Key's value is 1, remove it from the data structure. */ void dec(string key) { if (!m.count(key)) return; auto it = m[key], p = prev(it); m.erase(key); if (it->first > 1) { if (it == v.begin() || p->first < it->first - 1) p = v.insert(it, { it->first - 1, {} }); p->second.insert(key); m[key] = p; } it->second.erase(key); if (it->second.empty()) v.erase(it); } /** Returns one of the keys with maximal value. */ string getMaxKey() { return v.empty() ? "" : *v.back().second.begin(); } /** Returns one of the keys with Minimal value. */ string getMinKey() { return v.empty() ? "" : *v.front().second.begin(); } }; /** * Your AllOne object will be instantiated and called as such: * AllOne obj = new AllOne(); * obj.inc(key); * obj.dec(key); * string param_3 = obj.getMaxKey(); * string param_4 = obj.getMinKey(); */
// // Copyright 2012 Christian Henning // // Distributed under the Boost Software License, Version 1.0 // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // #ifndef BOOST_GIL_EXTENSION_IO_PNG_DETAIL_BASE_HPP #define BOOST_GIL_EXTENSION_IO_PNG_DETAIL_BASE_HPP #include <boost/gil/extension/io/png/tags.hpp> #include <boost/assert.hpp> #include <memory> namespace boost { namespace gil { namespace detail { struct png_ptr_wrapper { png_ptr_wrapper() : _struct( nullptr ) , _info ( nullptr ) {} png_structp _struct; png_infop _info; }; /// /// Wrapper for libpng's png_struct and png_info object. Implements value semantics. /// struct png_struct_info_wrapper { protected: using png_ptr_t = std::shared_ptr<png_ptr_wrapper>; protected: /// /// Default Constructor /// png_struct_info_wrapper( bool read = true ) : _png_ptr( new png_ptr_wrapper() , ( ( read ) ? png_ptr_read_deleter : png_ptr_write_deleter ) ) {} png_ptr_wrapper* get() { return _png_ptr.get(); } png_ptr_wrapper const* get() const { return _png_ptr.get(); } png_struct* get_struct() { return get()->_struct; } png_struct const* get_struct() const { return get()->_struct; } png_info* get_info() { return get()->_info; } png_info const* get_info() const { return get()->_info; } private: static void png_ptr_read_deleter( png_ptr_wrapper* png_ptr ) { if( png_ptr ) { if( png_ptr->_struct && png_ptr->_info ) { png_destroy_read_struct( &png_ptr->_struct , &png_ptr->_info , nullptr ); } delete png_ptr; png_ptr = nullptr; } } static void png_ptr_write_deleter( png_ptr_wrapper* png_ptr ) { if( png_ptr ) { if( png_ptr->_struct && png_ptr->_info ) { png_destroy_write_struct( &png_ptr->_struct , &png_ptr->_info ); } delete png_ptr; png_ptr = nullptr; } } private: png_ptr_t _png_ptr; }; } // namespace detail } // namespace gil } // namespace boost #endif
// --------------------------------------------------------------------- // // Copyright (c) 2014 - 2019 by the IBAMR developers // All rights reserved. // // This file is part of IBAMR. // // IBAMR is free software and is distributed under the 3-clause BSD // license. The full text of the license can be found in the file // COPYRIGHT at the top level directory of IBAMR. // // --------------------------------------------------------------------- /////////////////////////////// INCLUDES ///////////////////////////////////// #include "ibamr/IMPMethod.h" #include "ibamr/MaterialPointSpec.h" #include "ibamr/ibamr_utilities.h" #include "ibamr/namespaces.h" // IWYU pragma: keep #include "ibtk/IBTK_CHKERRQ.h" #include "ibtk/LData.h" #include "ibtk/LDataManager.h" #include "ibtk/LEInteractor.h" #include "ibtk/LIndexSetData.h" #include "ibtk/LInitStrategy.h" #include "ibtk/LMesh.h" #include "ibtk/LNode.h" #include "ibtk/LNodeSet.h" #include "ibtk/LNodeSetData.h" #include "ibtk/LSetData.h" #include "ibtk/LSiloDataWriter.h" #include "ibtk/RobinPhysBdryPatchStrategy.h" #include "ibtk/libmesh_utilities.h" #include "BasePatchHierarchy.h" #include "BasePatchLevel.h" #include "Box.h" #include "CartesianGridGeometry.h" #include "CartesianPatchGeometry.h" #include "CellIndex.h" #include "CellIterator.h" #include "CoarsenSchedule.h" #include "GriddingAlgorithm.h" #include "HierarchyDataOpsManager.h" #include "HierarchyDataOpsReal.h" #include "Index.h" #include "IntVector.h" #include "LoadBalancer.h" #include "MultiblockDataTranslator.h" #include "Patch.h" #include "PatchHierarchy.h" #include "PatchLevel.h" #include "RefineSchedule.h" #include "SideData.h" #include "SideGeometry.h" #include "SideIndex.h" #include "SideVariable.h" #include "Variable.h" #include "VariableDatabase.h" #include "tbox/Array.h" #include "tbox/Database.h" #include "tbox/MathUtilities.h" #include "tbox/PIO.h" #include "tbox/Pointer.h" #include "tbox/RestartManager.h" #include "tbox/Utilities.h" #include "libmesh/compare_types.h" #include "libmesh/tensor_value.h" #include "libmesh/type_tensor.h" #include "libmesh/type_vector.h" #include "libmesh/vector_value.h" #include "petscvec.h" IBTK_DISABLE_EXTRA_WARNINGS #include <boost/math/special_functions/round.hpp> #include <boost/multi_array.hpp> IBTK_ENABLE_EXTRA_WARNINGS #include <algorithm> #include <array> #include <cmath> #include <limits> #include <memory> #include <ostream> #include <string> #include <utility> #include <vector> using namespace libMesh; /////////////////////////////// NAMESPACE //////////////////////////////////// namespace IBAMR { /////////////////////////////// STATIC /////////////////////////////////////// namespace { static const std::string KERNEL_FCN = "IB_6"; static const int kernel_width = 3; void kernel(const double X, const double patch_x_lower, const double /*patch_x_upper*/, const double dx, const int patch_box_lower, const int /*patch_box_upper*/, int& stencil_box_lower, int& stencil_box_upper, boost::multi_array<double, 1>& phi, boost::multi_array<double, 1>& dphi) { const double X_o_dx = (X - patch_x_lower) / dx; stencil_box_lower = boost::math::round(X_o_dx) + patch_box_lower - kernel_width; stencil_box_upper = stencil_box_lower + 2 * kernel_width - 1; const double r = 1.0 - X_o_dx + ((stencil_box_lower + kernel_width - 1 - patch_box_lower) + 0.5); const double r2 = r * r; const double r3 = r * r2; const double r4 = r * r3; const double r5 = r * r4; const double r6 = r * r5; static const double K = (59.0 / 60.0) * (1.0 - std::sqrt(1.0 - (3220.0 / 3481.0))); static const double K2 = K * K; static const double alpha = 28.0; const double beta = (9.0 / 4.0) - (3.0 / 2.0) * (K + r2) + ((22.0 / 3.0) - 7.0 * K) * r - (7.0 / 3.0) * r3; const double dbeta = ((22.0 / 3.0) - 7.0 * K) - 3.0 * r - 7.0 * r2; const double gamma = (1.0 / 4.0) * (((161.0 / 36.0) - (59.0 / 6.0) * K + 5.0 * K2) * (1.0 / 2.0) * r2 + (-(109.0 / 24.0) + 5.0 * K) * (1.0 / 3.0) * r4 + (5.0 / 18.0) * r6); const double dgamma = (1.0 / 4.0) * (((161.0 / 36.0) - (59.0 / 6.0) * K + 5.0 * K2) * r + (-(109.0 / 24.0) + 5.0 * K) * (4.0 / 3.0) * r3 + (5.0 / 3.0) * r5); const double discr = beta * beta - 4.0 * alpha * gamma; phi[0] = (-beta + std::copysign(1.0, (3.0 / 2.0) - K) * std::sqrt(discr)) / (2.0 * alpha); phi[1] = -3.0 * phi[0] - (1.0 / 16.0) + (1.0 / 8.0) * (K + r2) + (1.0 / 12.0) * (3.0 * K - 1.0) * r + (1.0 / 12.0) * r3; phi[2] = 2.0 * phi[0] + (1.0 / 4.0) + (1.0 / 6.0) * (4.0 - 3.0 * K) * r - (1.0 / 6.0) * r3; phi[3] = 2.0 * phi[0] + (5.0 / 8.0) - (1.0 / 4.0) * (K + r2); phi[4] = -3.0 * phi[0] + (1.0 / 4.0) - (1.0 / 6.0) * (4.0 - 3.0 * K) * r + (1.0 / 6.0) * r3; phi[5] = phi[0] - (1.0 / 16.0) + (1.0 / 8.0) * (K + r2) - (1.0 / 12.0) * (3.0 * K - 1.0) * r - (1.0 / 12.0) * r3; dphi[0] = -(dbeta * phi[0] + dgamma) / (2.0 * alpha * phi[0] + beta); dphi[1] = -3.0 * dphi[0] + (1.0 / 12.0) * (3.0 * K - 1.0) + (1.0 / 4.0) * r + (1.0 / 4.0) * r2; dphi[2] = 2.0 * dphi[0] + (1.0 / 6.0) * (4.0 - 3.0 * K) - (1.0 / 2.0) * r2; dphi[3] = 2.0 * dphi[0] - (1.0 / 2.0) * r; dphi[4] = -3.0 * dphi[0] - (1.0 / 6.0) * (4.0 - 3.0 * K) + (1.0 / 2.0) * r2; dphi[5] = dphi[0] - (1.0 / 12.0) * (3.0 * K - 1.0) + (1.0 / 4.0) * r - (1.0 / 4.0) * r2; return; } // Version of IMPMethod restart file data. static const int IMP_METHOD_VERSION = 1; } // namespace /////////////////////////////// PUBLIC /////////////////////////////////////// IMPMethod::IMPMethod(std::string object_name, Pointer<Database> input_db, bool register_for_restart) : d_ghosts(LEInteractor::getMinimumGhostWidth(KERNEL_FCN)), d_object_name(std::move(object_name)) { // Set the object name and register it with the restart manager. d_registered_for_restart = false; if (register_for_restart) { RestartManager::getManager()->registerRestartItem(d_object_name, this); d_registered_for_restart = true; } // Initialize object with data read from the input and restart databases. bool from_restart = RestartManager::getManager()->isFromRestart(); if (from_restart) getFromRestart(); if (input_db) getFromInput(input_db, from_restart); // Get the Lagrangian Data Manager. d_l_data_manager = LDataManager::getManager(d_object_name + "::LDataManager", KERNEL_FCN, KERNEL_FCN, d_error_if_points_leave_domain, d_ghosts, d_registered_for_restart); d_ghosts = d_l_data_manager->getGhostCellWidth(); return; } // IMPMethod IMPMethod::~IMPMethod() { if (d_registered_for_restart) { RestartManager::getManager()->unregisterRestartItem(d_object_name); d_registered_for_restart = false; } return; } // ~IMPMethod void IMPMethod::registerLInitStrategy(Pointer<LInitStrategy> l_initializer) { #if !defined(NDEBUG) TBOX_ASSERT(l_initializer); #endif d_l_initializer = l_initializer; d_l_data_manager->registerLInitStrategy(d_l_initializer); return; } // registerLInitStrategy void IMPMethod::freeLInitStrategy() { d_l_initializer.setNull(); d_l_data_manager->freeLInitStrategy(); return; } // freeLInitStrategy LDataManager* IMPMethod::getLDataManager() const { return d_l_data_manager; } // getLDataManager void IMPMethod::registerLSiloDataWriter(Pointer<LSiloDataWriter> silo_writer) { #if !defined(NDEBUG) TBOX_ASSERT(silo_writer); #endif d_silo_writer = silo_writer; d_l_data_manager->registerLSiloDataWriter(d_silo_writer); return; } // registerLSiloDataWriter const IntVector<NDIM>& IMPMethod::getMinimumGhostCellWidth() const { return d_ghosts; } // getMinimumGhostCellWidth void IMPMethod::setupTagBuffer(Array<int>& tag_buffer, Pointer<GriddingAlgorithm<NDIM> > gridding_alg) const { const int finest_hier_ln = gridding_alg->getMaxLevels() - 1; const int tsize = tag_buffer.size(); tag_buffer.resizeArray(finest_hier_ln); for (int i = tsize; i < finest_hier_ln; ++i) tag_buffer[i] = 0; const int gcw = d_ghosts.max(); for (int tag_ln = 0; tag_ln < finest_hier_ln; ++tag_ln) { const int data_ln = tag_ln + 1; const int can_be_refined = data_ln < finest_hier_ln; if (!d_l_initializer->getLevelHasLagrangianData(data_ln, can_be_refined)) continue; tag_buffer[tag_ln] = std::max(tag_buffer[tag_ln], gcw); } for (int ln = finest_hier_ln - 2; ln >= 0; --ln) { tag_buffer[ln] = std::max(tag_buffer[ln], tag_buffer[ln + 1] / gridding_alg->getRatioToCoarserLevel(ln + 1).max() + 1); } return; } // setupTagBuffer void IMPMethod::preprocessIntegrateData(double current_time, double new_time, int /*num_cycles*/) { d_current_time = current_time; d_new_time = new_time; d_half_time = current_time + 0.5 * (new_time - current_time); int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); // Look-up or allocate Lagangian data. d_X_current_data.resize(finest_ln + 1); d_X_new_data.resize(finest_ln + 1); d_X_half_data.resize(finest_ln + 1); d_X0_data.resize(finest_ln + 1); d_U_current_data.resize(finest_ln + 1); d_U_new_data.resize(finest_ln + 1); d_U_half_data.resize(finest_ln + 1); d_Grad_U_current_data.resize(finest_ln + 1); d_Grad_U_new_data.resize(finest_ln + 1); d_Grad_U_half_data.resize(finest_ln + 1); d_F_current_data.resize(finest_ln + 1); d_F_new_data.resize(finest_ln + 1); d_F_half_data.resize(finest_ln + 1); d_tau_data.resize(finest_ln + 1); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; d_X_current_data[ln] = d_l_data_manager->getLData(LDataManager::POSN_DATA_NAME, ln); d_X_new_data[ln] = d_l_data_manager->createLData("X_new", ln, NDIM); d_X0_data[ln] = d_l_data_manager->getLData("X0", ln); d_U_current_data[ln] = d_l_data_manager->getLData(LDataManager::VEL_DATA_NAME, ln); d_U_new_data[ln] = d_l_data_manager->createLData("U_new", ln, NDIM); d_Grad_U_current_data[ln] = d_l_data_manager->getLData("Grad_U", ln); d_Grad_U_new_data[ln] = d_l_data_manager->createLData("Grad_U_new", ln, NDIM * NDIM); d_F_current_data[ln] = d_l_data_manager->getLData("F", ln); d_F_new_data[ln] = d_l_data_manager->createLData("F_new", ln, NDIM * NDIM); d_F_half_data[ln] = d_l_data_manager->createLData("F_half", ln, NDIM * NDIM); d_tau_data[ln] = d_l_data_manager->getLData("tau", ln); // Initialize new values to equal current values. ierr = VecCopy(d_X_current_data[ln]->getVec(), d_X_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecCopy(d_U_current_data[ln]->getVec(), d_U_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecCopy(d_Grad_U_current_data[ln]->getVec(), d_Grad_U_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecCopy(d_F_current_data[ln]->getVec(), d_F_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecCopy(d_F_current_data[ln]->getVec(), d_F_half_data[ln]->getVec()); IBTK_CHKERRQ(ierr); } // Keep track of Lagrangian data objects that need to have ghost values // filled, or that need to be reinitialized. d_X_new_needs_ghost_fill = true; d_X_half_needs_reinit = true; d_U_half_needs_reinit = true; return; } // preprocessIntegrateData void IMPMethod::postprocessIntegrateData(double /*current_time*/, double /*new_time*/, int /*num_cycles*/) { int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); // Reset time-dependent Lagrangian data. for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; ierr = VecSwap(d_X_current_data[ln]->getVec(), d_X_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecSwap(d_U_current_data[ln]->getVec(), d_U_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecSwap(d_Grad_U_current_data[ln]->getVec(), d_Grad_U_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecSwap(d_F_current_data[ln]->getVec(), d_F_new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); } d_X_current_needs_ghost_fill = true; // Deallocate Lagrangian scratch data. d_X_current_data.clear(); d_X_new_data.clear(); d_X_half_data.clear(); d_X0_data.clear(); d_U_current_data.clear(); d_U_new_data.clear(); d_U_half_data.clear(); d_Grad_U_current_data.clear(); d_Grad_U_new_data.clear(); d_Grad_U_half_data.clear(); d_F_current_data.clear(); d_F_new_data.clear(); d_F_half_data.clear(); d_tau_data.clear(); // Reset the current time step interval. d_current_time = std::numeric_limits<double>::quiet_NaN(); d_new_time = std::numeric_limits<double>::quiet_NaN(); d_half_time = std::numeric_limits<double>::quiet_NaN(); return; } // postprocessIntegrateData void IMPMethod::interpolateVelocity(const int u_data_idx, const std::vector<Pointer<CoarsenSchedule<NDIM> > >& u_synch_scheds, const std::vector<Pointer<RefineSchedule<NDIM> > >& u_ghost_fill_scheds, const double data_time) { const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); // Determine the type of data centering. Pointer<hier::Variable<NDIM> > u_var; var_db->mapIndexToVariable(u_data_idx, u_var); Pointer<SideVariable<NDIM, double> > u_sc_var = u_var; const bool sc_data = u_sc_var; TBOX_ASSERT(sc_data); // Synchronize Eulerian and Lagrangian values. std::vector<Pointer<LData> >*U_data, *Grad_U_data, *X_data; bool* X_needs_ghost_fill; getVelocityData(&U_data, &Grad_U_data, data_time); getPositionData(&X_data, &X_needs_ghost_fill, data_time); for (int ln = finest_ln; ln >= coarsest_ln; --ln) { if (ln < static_cast<int>(u_synch_scheds.size()) && u_synch_scheds[ln]) { u_synch_scheds[ln]->coarsenData(); } if (*X_needs_ghost_fill && (*X_data)[ln]) (*X_data)[ln]->beginGhostUpdate(); } for (int ln = finest_ln; ln >= coarsest_ln; --ln) { if (*X_needs_ghost_fill && (*X_data)[ln]) (*X_data)[ln]->endGhostUpdate(); } *X_needs_ghost_fill = false; // Interpolate data from the Eulerian grid to the Lagrangian mesh. Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry(); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; if (ln < static_cast<int>(u_ghost_fill_scheds.size()) && u_ghost_fill_scheds[ln]) { u_ghost_fill_scheds[ln]->fillData(data_time); } boost::multi_array_ref<double, 2>& U_array = *(*U_data)[ln]->getLocalFormVecArray(); boost::multi_array_ref<double, 2>& Grad_U_array = *(*Grad_U_data)[ln]->getLocalFormVecArray(); boost::multi_array_ref<double, 2>& X_array = *(*X_data)[ln]->getLocalFormVecArray(); Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); for (PatchLevel<NDIM>::Iterator p(level); p; p++) { Pointer<Patch<NDIM> > patch = level->getPatch(p()); Pointer<SideData<NDIM, double> > u_data = patch->getPatchData(u_data_idx); Pointer<LNodeSetData> idx_data = patch->getPatchData(d_l_data_manager->getLNodePatchDescriptorIndex()); const Box<NDIM>& patch_box = patch->getBox(); const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry(); const double* const x_lower = patch_geom->getXLower(); const double* const x_upper = patch_geom->getXUpper(); const double* const dx = patch_geom->getDx(); Box<NDIM> side_boxes[NDIM]; for (unsigned int axis = 0; axis < NDIM; ++axis) { side_boxes[axis] = SideGeometry<NDIM>::toSideBox(u_data->getGhostBox() * idx_data->getGhostBox(), axis); } for (LNodeSetData::CellIterator it(idx_data->getGhostBox()); it; it++) { const hier::Index<NDIM>& i = *it; LNodeSet* const node_set = idx_data->getItem(i); if (!node_set) continue; for (const auto& node_idx : *node_set) { const int local_idx = node_idx->getLocalPETScIndex(); const double* const X = &X_array[local_idx][0]; VectorValue<double> U; TensorValue<double> Grad_U; // Interpolate U and Grad U using a smoothed kernel // function evaluated about X. Box<NDIM> stencil_box; const int stencil_size = LEInteractor::getStencilSize(KERNEL_FCN); std::array<boost::multi_array<double, 1>, NDIM> phi, dphi; for (unsigned int d = 0; d < NDIM; ++d) { phi[d].resize(boost::extents[stencil_size]); dphi[d].resize(boost::extents[stencil_size]); } for (unsigned int component = 0; component < NDIM; ++component) { for (unsigned int d = 0; d < NDIM; ++d) { kernel(X[d], x_lower[d] + (d == component ? -0.5 * dx[d] : 0.0), x_upper[d] + (d == component ? +0.5 * dx[d] : 0.0), dx[d], patch_box.lower(d), patch_box.upper(d) + (d == component ? 1 : 0), stencil_box.lower(d), stencil_box.upper(d), phi[d], dphi[d]); } for (Box<NDIM>::Iterator b(stencil_box * side_boxes[component]); b; b++) { const hier::Index<NDIM>& i = b(); const hier::Index<NDIM> i_shift = i - stencil_box.lower(); const SideIndex<NDIM> i_s(i, component, SideIndex<NDIM>::Lower); const double u = (*u_data)(i_s); double w = 1.0; for (unsigned int d = 0; d < NDIM; ++d) { w *= phi[d][i_shift(d)]; } U(component) += u * w; for (unsigned int k = 0; k < NDIM; ++k) { double dw_dx_k = 1.0; for (unsigned int d = 0; d < NDIM; ++d) { if (d == k) { dw_dx_k *= dphi[d][i_shift(d)] / dx[d]; } else { dw_dx_k *= phi[d][i_shift(d)]; } } Grad_U(component, k) -= u * dw_dx_k; } } } for (int i = 0; i < NDIM; ++i) { U_array[local_idx][i] = U(i); for (int j = 0; j < NDIM; ++j) { Grad_U_array[local_idx][NDIM * i + j] = Grad_U(i, j); } } } } } (*U_data)[ln]->restoreArrays(); (*Grad_U_data)[ln]->restoreArrays(); (*X_data)[ln]->restoreArrays(); } d_U_half_needs_reinit = !MathUtilities<double>::equalEps(data_time, d_half_time); return; } // interpolateVelocity void IMPMethod::forwardEulerStep(const double current_time, const double new_time) { int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); const double dt = new_time - current_time; std::vector<Pointer<LData> >*U_data, *Grad_U_data; getVelocityData(&U_data, &Grad_U_data, current_time); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; // Update the positions. ierr = VecWAXPY(d_X_new_data[ln]->getVec(), dt, (*U_data)[ln]->getVec(), d_X_current_data[ln]->getVec()); IBTK_CHKERRQ(ierr); // Update the deformation gradient. const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln); const std::vector<LNode*>& local_nodes = mesh->getLocalNodes(); boost::multi_array_ref<double, 2>& F_current_array = *d_F_current_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& F_new_array = *d_F_new_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& F_half_array = *d_F_half_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& Grad_U_array = *(*Grad_U_data)[ln]->getVecArray(); TensorValue<double> F_current, F_new, F_half, Grad_U; TensorValue<double> I(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); for (const auto& node_idx : local_nodes) { const int idx = node_idx->getGlobalPETScIndex(); for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_current(i, j) = F_current_array[idx][NDIM * i + j]; Grad_U(i, j) = Grad_U_array[idx][NDIM * i + j]; } } #if (NDIM == 2) F_current(2, 2) = 1.0; #endif F_new = tensor_inverse(I - 0.50 * dt * Grad_U) * (I + 0.50 * dt * Grad_U) * F_current; F_half = tensor_inverse(I - 0.25 * dt * Grad_U) * (I + 0.25 * dt * Grad_U) * F_current; for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_new_array[idx][NDIM * i + j] = F_new(i, j); F_half_array[idx][NDIM * i + j] = F_half(i, j); } } } } d_X_new_needs_ghost_fill = true; d_X_half_needs_reinit = true; return; } // forwardEulerStep void IMPMethod::midpointStep(const double current_time, const double new_time) { int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); const double dt = new_time - current_time; std::vector<Pointer<LData> >*U_data, *Grad_U_data; getVelocityData(&U_data, &Grad_U_data, current_time + 0.5 * dt); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; // Update the positions. ierr = VecWAXPY(d_X_new_data[ln]->getVec(), dt, (*U_data)[ln]->getVec(), d_X_current_data[ln]->getVec()); IBTK_CHKERRQ(ierr); // Update the deformation gradient. const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln); const std::vector<LNode*>& local_nodes = mesh->getLocalNodes(); boost::multi_array_ref<double, 2>& F_current_array = *d_F_current_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& F_new_array = *d_F_new_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& Grad_U_array = *(*Grad_U_data)[ln]->getVecArray(); TensorValue<double> F_current, F_new, Grad_U; TensorValue<double> I(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); for (const auto& node_idx : local_nodes) { const int idx = node_idx->getGlobalPETScIndex(); for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_current(i, j) = F_current_array[idx][NDIM * i + j]; Grad_U(i, j) = Grad_U_array[idx][NDIM * i + j]; } } #if (NDIM == 2) F_current(2, 2) = 1.0; #endif F_new = tensor_inverse(I - 0.5 * dt * Grad_U) * (I + 0.5 * dt * Grad_U) * F_current; for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_new_array[idx][NDIM * i + j] = F_new(i, j); } } } } d_X_new_needs_ghost_fill = true; d_X_half_needs_reinit = true; return; } // midpointStep void IMPMethod::trapezoidalStep(const double current_time, const double new_time) { int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); const double dt = new_time - current_time; std::vector<Pointer<LData> >*U_current_data, *U_new_data, *Grad_U_current_data, *Grad_U_new_data; getVelocityData(&U_current_data, &Grad_U_current_data, current_time); getVelocityData(&U_new_data, &Grad_U_new_data, new_time); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; // Update the positions. ierr = VecWAXPY( d_X_new_data[ln]->getVec(), 0.5 * dt, (*U_current_data)[ln]->getVec(), d_X_current_data[ln]->getVec()); IBTK_CHKERRQ(ierr); ierr = VecAXPY(d_X_new_data[ln]->getVec(), 0.5 * dt, (*U_new_data)[ln]->getVec()); IBTK_CHKERRQ(ierr); // Update the deformation gradient. const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln); const std::vector<LNode*>& local_nodes = mesh->getLocalNodes(); boost::multi_array_ref<double, 2>& F_current_array = *d_F_current_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& F_new_array = *d_F_new_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& Grad_U_current_array = *(*Grad_U_current_data)[ln]->getVecArray(); boost::multi_array_ref<double, 2>& Grad_U_new_array = *(*Grad_U_new_data)[ln]->getVecArray(); TensorValue<double> F_current, F_new, Grad_U_current, Grad_U_new; TensorValue<double> I(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0); for (const auto& node_idx : local_nodes) { const int idx = node_idx->getGlobalPETScIndex(); for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_current(i, j) = F_current_array[idx][NDIM * i + j]; Grad_U_current(i, j) = Grad_U_current_array[idx][NDIM * i + j]; Grad_U_new(i, j) = Grad_U_new_array[idx][NDIM * i + j]; } } #if (NDIM == 2) F_current(2, 2) = 1.0; #endif F_new = tensor_inverse(I - 0.5 * dt * Grad_U_new) * (I + 0.5 * dt * Grad_U_current) * F_current; for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_new_array[idx][NDIM * i + j] = F_new(i, j); } } } } d_X_new_needs_ghost_fill = true; d_X_half_needs_reinit = true; return; } // trapezoidalStep void IMPMethod::computeLagrangianForce(const double data_time) { const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); std::vector<Pointer<LData> >*X_data, *F_data; bool* X_needs_ghost_fill; getPositionData(&X_data, &X_needs_ghost_fill, data_time); getDeformationGradientData(&F_data, data_time); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(ln); const std::vector<LNode*>& local_nodes = mesh->getLocalNodes(); boost::multi_array_ref<double, 2>& x_array = *(*X_data)[ln]->getVecArray(); boost::multi_array_ref<double, 2>& X_array = *d_X0_data[ln]->getVecArray(); boost::multi_array_ref<double, 2>& F_array = *(*F_data)[ln]->getVecArray(); boost::multi_array_ref<double, 2>& tau_array = *d_tau_data[ln]->getVecArray(); TensorValue<double> FF, PP, tau; VectorValue<double> X, x; for (const auto& node_idx : local_nodes) { const int idx = node_idx->getGlobalPETScIndex(); auto mp_spec = node_idx->getNodeDataItem<MaterialPointSpec>(); if (mp_spec && d_PK1_stress_fcn) { for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { FF(i, j) = F_array[idx][NDIM * i + j]; } x(i) = x_array[idx][i]; X(i) = X_array[idx][i]; } #if (NDIM == 2) FF(2, 2) = 1.0; #endif (*d_PK1_stress_fcn)(PP, FF, x, X, mp_spec->getSubdomainId(), mp_spec->getInternalVariables(), data_time, d_PK1_stress_fcn_ctx); tau = PP * FF.transpose(); } else { tau.zero(); } for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { tau_array[idx][NDIM * i + j] = tau(i, j); } } } } return; } // computeLagrangianForce void IMPMethod::spreadForce(const int f_data_idx, RobinPhysBdryPatchStrategy* f_phys_bdry_op, const std::vector<Pointer<RefineSchedule<NDIM> > >& /*f_prolongation_scheds*/, const double data_time) { const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); VariableDatabase<NDIM>* var_db = VariableDatabase<NDIM>::getDatabase(); // Determine the type of data centering. Pointer<hier::Variable<NDIM> > f_var; var_db->mapIndexToVariable(f_data_idx, f_var); Pointer<SideVariable<NDIM, double> > f_sc_var = f_var; const bool sc_data = f_sc_var; TBOX_ASSERT(sc_data); // Make a copy of the Eulerian data. const int f_copy_data_idx = var_db->registerClonedPatchDataIndex(f_var, f_data_idx); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); level->allocatePatchData(f_copy_data_idx); } Pointer<HierarchyDataOpsReal<NDIM, double> > f_data_ops = HierarchyDataOpsManager<NDIM>::getManager()->getOperationsDouble(f_var, d_hierarchy, true); f_data_ops->swapData(f_copy_data_idx, f_data_idx); f_data_ops->setToScalar(f_data_idx, 0.0, /*interior_only*/ false); // Synchronize Lagrangian values. std::vector<Pointer<LData> >* X_data; bool* X_needs_ghost_fill; getPositionData(&X_data, &X_needs_ghost_fill, data_time); for (int ln = finest_ln; ln >= coarsest_ln; --ln) { if (*X_needs_ghost_fill && (*X_data)[ln]) (*X_data)[ln]->beginGhostUpdate(); if (d_tau_data[ln]) d_tau_data[ln]->beginGhostUpdate(); } for (int ln = finest_ln; ln >= coarsest_ln; --ln) { if (*X_needs_ghost_fill && (*X_data)[ln]) (*X_data)[ln]->endGhostUpdate(); if (d_tau_data[ln]) d_tau_data[ln]->endGhostUpdate(); } *X_needs_ghost_fill = false; // Spread data from the Lagrangian mesh to the Eulerian grid. Pointer<CartesianGridGeometry<NDIM> > grid_geom = d_hierarchy->getGridGeometry(); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; boost::multi_array_ref<double, 2>& X_array = *(*X_data)[ln]->getGhostedLocalFormVecArray(); boost::multi_array_ref<double, 2>& tau_array = *d_tau_data[ln]->getGhostedLocalFormVecArray(); Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); for (PatchLevel<NDIM>::Iterator p(level); p; p++) { Pointer<Patch<NDIM> > patch = level->getPatch(p()); Pointer<SideData<NDIM, double> > f_data = patch->getPatchData(f_data_idx); Pointer<LNodeSetData> idx_data = patch->getPatchData(d_l_data_manager->getLNodePatchDescriptorIndex()); const Box<NDIM>& patch_box = patch->getBox(); Box<NDIM> side_boxes[NDIM]; for (unsigned int d = 0; d < NDIM; ++d) side_boxes[d] = SideGeometry<NDIM>::toSideBox(patch_box, d); const Pointer<CartesianPatchGeometry<NDIM> > patch_geom = patch->getPatchGeometry(); const double* const x_lower = patch_geom->getXLower(); const double* const x_upper = patch_geom->getXUpper(); const double* const dx = patch_geom->getDx(); double dV_c = 1.0; for (unsigned int d = 0; d < NDIM; ++d) dV_c *= dx[d]; for (LNodeSetData::CellIterator it(idx_data->getGhostBox()); it; it++) { const hier::Index<NDIM>& i = *it; LNodeSet* const node_set = idx_data->getItem(i); if (!node_set) continue; for (const auto& node_idx : *node_set) { auto mp_spec = node_idx->getNodeDataItem<MaterialPointSpec>(); if (!mp_spec) continue; const double wgt = mp_spec->getWeight(); const int local_idx = node_idx->getLocalPETScIndex(); const double* const X = &X_array[local_idx][0]; TensorValue<double> tau; for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { tau(i, j) = tau_array[local_idx][NDIM * i + j]; } } // Weight tau using a smooth kernel function evaluated about // X. Box<NDIM> stencil_box; const int stencil_size = LEInteractor::getStencilSize(KERNEL_FCN); std::array<boost::multi_array<double, 1>, NDIM> phi, dphi; for (unsigned int d = 0; d < NDIM; ++d) { phi[d].resize(boost::extents[stencil_size]); dphi[d].resize(boost::extents[stencil_size]); } for (unsigned int component = 0; component < NDIM; ++component) { for (unsigned int d = 0; d < NDIM; ++d) { kernel(X[d], x_lower[d] + (d == component ? -0.5 * dx[d] : 0.0), x_upper[d] + (d == component ? +0.5 * dx[d] : 0.0), dx[d], patch_box.lower(d), patch_box.upper(d) + (d == component ? 1 : 0), stencil_box.lower(d), stencil_box.upper(d), phi[d], dphi[d]); } for (Box<NDIM>::Iterator b(stencil_box * side_boxes[component]); b; b++) { const hier::Index<NDIM>& i = b(); const hier::Index<NDIM> i_shift = i - stencil_box.lower(); const SideIndex<NDIM> i_s(i, component, SideIndex<NDIM>::Lower); double f = 0.0; for (unsigned int k = 0; k < NDIM; ++k) { double dw_dx_k = 1.0; for (unsigned int d = 0; d < NDIM; ++d) { if (d == k) { dw_dx_k *= dphi[d][i_shift(d)] / dx[d]; } else { dw_dx_k *= phi[d][i_shift(d)]; } } f += tau(component, k) * dw_dx_k; } (*f_data)(i_s) += f * wgt / dV_c; } } } } if (f_phys_bdry_op) { f_phys_bdry_op->setPatchDataIndex(f_data_idx); f_phys_bdry_op->accumulateFromPhysicalBoundaryData(*patch, data_time, f_data->getGhostCellWidth()); } } } // Accumulate data. f_data_ops->swapData(f_copy_data_idx, f_data_idx); f_data_ops->add(f_data_idx, f_data_idx, f_copy_data_idx); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { Pointer<PatchLevel<NDIM> > level = d_hierarchy->getPatchLevel(ln); level->deallocatePatchData(f_copy_data_idx); } var_db->removePatchDataIndex(f_copy_data_idx); return; } // spreadForce void IMPMethod::initializePatchHierarchy(Pointer<PatchHierarchy<NDIM> > hierarchy, Pointer<GriddingAlgorithm<NDIM> > gridding_alg, int /*u_data_idx*/, const std::vector<Pointer<CoarsenSchedule<NDIM> > >& /*u_synch_scheds*/, const std::vector<Pointer<RefineSchedule<NDIM> > >& /*u_ghost_fill_scheds*/, int /*integrator_step*/, double /*init_data_time*/, bool initial_time) { // Cache pointers to the patch hierarchy and gridding algorithm. d_hierarchy = hierarchy; d_gridding_alg = gridding_alg; // Initialize various Lagrangian data objects. if (initial_time) { pout << "WARNING: IMPMethod implementation currently requires that the " "initial velocity is *zero*.\n"; } return; } // initializePatchHierarchy void IMPMethod::registerPK1StressTensorFunction(PK1StressFcnPtr PK1_stress_fcn, void* PK1_stress_fcn_ctx) { d_PK1_stress_fcn = PK1_stress_fcn; d_PK1_stress_fcn_ctx = PK1_stress_fcn_ctx; return; } // registerPK1StressTensorFunction void IMPMethod::registerLoadBalancer(Pointer<LoadBalancer<NDIM> > load_balancer, int workload_data_idx) { IBAMR_DEPRECATED_MEMBER_FUNCTION1("IMPMethod", "registerLoadBalancer"); #if !defined(NDEBUG) TBOX_ASSERT(load_balancer); #endif d_load_balancer = load_balancer; d_workload_idx = workload_data_idx; d_l_data_manager->registerLoadBalancer(load_balancer, workload_data_idx); return; } // registerLoadBalancer void IMPMethod::addWorkloadEstimate(Pointer<PatchHierarchy<NDIM> > hierarchy, const int workload_data_idx) { d_l_data_manager->addWorkloadEstimate(hierarchy, workload_data_idx); return; } // addWorkloadEstimate void IMPMethod::beginDataRedistribution(Pointer<PatchHierarchy<NDIM> > /*hierarchy*/, Pointer<GriddingAlgorithm<NDIM> > /*gridding_alg*/) { d_l_data_manager->beginDataRedistribution(); return; } // beginDataRedistribution void IMPMethod::endDataRedistribution(Pointer<PatchHierarchy<NDIM> > /*hierarchy*/, Pointer<GriddingAlgorithm<NDIM> > /*gridding_alg*/) { d_l_data_manager->endDataRedistribution(); return; } // endDataRedistribution void IMPMethod::initializeLevelData(Pointer<BasePatchHierarchy<NDIM> > hierarchy, int level_number, double init_data_time, bool can_be_refined, bool initial_time, Pointer<BasePatchLevel<NDIM> > old_level, bool allocate_data) { const int finest_hier_level = hierarchy->getFinestLevelNumber(); d_l_data_manager->setPatchHierarchy(hierarchy); d_l_data_manager->setPatchLevels(0, finest_hier_level); d_l_data_manager->initializeLevelData( hierarchy, level_number, init_data_time, can_be_refined, initial_time, old_level, allocate_data); if (initial_time && d_l_data_manager->levelContainsLagrangianData(level_number)) { d_l_data_manager->createLData("Grad_U", level_number, NDIM * NDIM, /*manage_data*/ true); Pointer<LData> F_data = d_l_data_manager->createLData("F", level_number, NDIM * NDIM, /*manage_data*/ true); Pointer<LData> tau_data = d_l_data_manager->createLData("tau", level_number, NDIM * NDIM, /*manage_data*/ true); if (d_silo_writer) { d_silo_writer->registerVariableData("F0", F_data, 0 * NDIM, NDIM, level_number); d_silo_writer->registerVariableData("F1", F_data, 1 * NDIM, NDIM, level_number); #if (NDIM == 3) d_silo_writer->registerVariableData("F2", F_data, 2 * NDIM, NDIM, level_number); #endif d_silo_writer->registerVariableData("tau0", tau_data, 0 * NDIM, NDIM, level_number); d_silo_writer->registerVariableData("tau1", tau_data, 1 * NDIM, NDIM, level_number); #if (NDIM == 3) d_silo_writer->registerVariableData("tau2", tau_data, 2 * NDIM, NDIM, level_number); #endif } // Initialize the deformation gradient and Kirchhoff stress. const Pointer<LMesh> mesh = d_l_data_manager->getLMesh(level_number); const std::vector<LNode*>& local_nodes = mesh->getLocalNodes(); boost::multi_array_ref<double, 2>& F_array = *F_data->getLocalFormVecArray(); boost::multi_array_ref<double, 2>& tau_array = *tau_data->getLocalFormVecArray(); for (const auto& node_idx : local_nodes) { const int idx = node_idx->getLocalPETScIndex(); for (int i = 0; i < NDIM; ++i) { for (int j = 0; j < NDIM; ++j) { F_array[idx][NDIM * i + j] = (i == j ? 1.0 : 0.0); tau_array[idx][NDIM * i + j] = 0.0; } } } } return; } // initializeLevelData void IMPMethod::resetHierarchyConfiguration(Pointer<BasePatchHierarchy<NDIM> > hierarchy, int coarsest_level, int finest_level) { const int finest_hier_level = hierarchy->getFinestLevelNumber(); d_l_data_manager->setPatchHierarchy(hierarchy); d_l_data_manager->setPatchLevels(0, finest_hier_level); d_l_data_manager->resetHierarchyConfiguration(hierarchy, coarsest_level, finest_level); return; } // resetHierarchyConfiguration void IMPMethod::applyGradientDetector(Pointer<BasePatchHierarchy<NDIM> > base_hierarchy, int level_number, double error_data_time, int tag_index, bool initial_time, bool uses_richardson_extrapolation_too) { Pointer<PatchHierarchy<NDIM> > hierarchy = base_hierarchy; #if !defined(NDEBUG) TBOX_ASSERT(hierarchy); TBOX_ASSERT((level_number >= 0) && (level_number <= hierarchy->getFinestLevelNumber())); TBOX_ASSERT(hierarchy->getPatchLevel(level_number)); #endif // Tag cells that contain Lagrangian nodes. d_l_data_manager->applyGradientDetector( hierarchy, level_number, error_data_time, tag_index, initial_time, uses_richardson_extrapolation_too); return; } // applyGradientDetector void IMPMethod::putToDatabase(Pointer<Database> db) { db->putInteger("IMP_METHOD_VERSION", IMP_METHOD_VERSION); db->putIntegerArray("d_ghosts", d_ghosts, NDIM); return; } // putToDatabase /////////////////////////////// PROTECTED //////////////////////////////////// void IMPMethod::getPositionData(std::vector<Pointer<LData> >** X_data, bool** X_needs_ghost_fill, double data_time) { const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); if (MathUtilities<double>::equalEps(data_time, d_current_time)) { *X_data = &d_X_current_data; *X_needs_ghost_fill = &d_X_current_needs_ghost_fill; } else if (MathUtilities<double>::equalEps(data_time, d_half_time)) { for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; if (!d_X_half_data[ln]) { d_X_half_data[ln] = d_l_data_manager->createLData("X_half", ln, NDIM); d_X_half_needs_reinit = true; } } if (d_X_half_needs_reinit) { reinitMidpointData(d_X_current_data, d_X_new_data, d_X_half_data); d_X_half_needs_reinit = false; d_X_half_needs_ghost_fill = true; } *X_data = &d_X_half_data; *X_needs_ghost_fill = &d_X_half_needs_ghost_fill; } else if (MathUtilities<double>::equalEps(data_time, d_new_time)) { *X_data = &d_X_new_data; *X_needs_ghost_fill = &d_X_new_needs_ghost_fill; } return; } // getPositionData void IMPMethod::getVelocityData(std::vector<Pointer<LData> >** U_data, std::vector<Pointer<LData> >** Grad_U_data, double data_time) { const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); if (MathUtilities<double>::equalEps(data_time, d_current_time)) { *U_data = &d_U_current_data; *Grad_U_data = &d_Grad_U_current_data; } else if (MathUtilities<double>::equalEps(data_time, d_half_time)) { for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; if (!d_U_half_data[ln]) { d_U_half_data[ln] = d_l_data_manager->createLData("U_half", ln, NDIM); d_Grad_U_half_data[ln] = d_l_data_manager->createLData("Grad_U_half", ln, NDIM * NDIM); d_U_half_needs_reinit = true; } } if (d_U_half_needs_reinit) { reinitMidpointData(d_U_current_data, d_U_new_data, d_U_half_data); reinitMidpointData(d_Grad_U_current_data, d_Grad_U_new_data, d_Grad_U_half_data); d_U_half_needs_reinit = false; } *U_data = &d_U_half_data; *Grad_U_data = &d_Grad_U_half_data; } else if (MathUtilities<double>::equalEps(data_time, d_new_time)) { *U_data = &d_U_new_data; *Grad_U_data = &d_Grad_U_new_data; } return; } // getVelocityData void IMPMethod::getDeformationGradientData(std::vector<Pointer<LData> >** F_data, double data_time) { if (MathUtilities<double>::equalEps(data_time, d_current_time)) { *F_data = &d_F_current_data; } else if (MathUtilities<double>::equalEps(data_time, d_half_time)) { *F_data = &d_F_half_data; } else if (MathUtilities<double>::equalEps(data_time, d_new_time)) { *F_data = &d_F_new_data; } return; } // getDeformationGradientData void IMPMethod::reinitMidpointData(const std::vector<Pointer<LData> >& current_data, const std::vector<Pointer<LData> >& new_data, const std::vector<Pointer<LData> >& half_data) { int ierr; const int coarsest_ln = 0; const int finest_ln = d_hierarchy->getFinestLevelNumber(); for (int ln = coarsest_ln; ln <= finest_ln; ++ln) { if (!d_l_data_manager->levelContainsLagrangianData(ln)) continue; ierr = VecAXPBYPCZ(half_data[ln]->getVec(), 0.5, 0.5, 0.0, current_data[ln]->getVec(), new_data[ln]->getVec()); IBTK_CHKERRQ(ierr); } return; } // reinitMidpointData /////////////////////////////// PRIVATE ////////////////////////////////////// void IMPMethod::getFromInput(Pointer<Database> db, bool is_from_restart) { if (!is_from_restart) { if (db->isInteger("min_ghost_cell_width")) { d_ghosts = db->getInteger("min_ghost_cell_width"); } else if (db->isDouble("min_ghost_cell_width")) { d_ghosts = static_cast<int>(std::ceil(db->getDouble("min_ghost_cell_width"))); } } if (db->keyExists("error_if_points_leave_domain")) d_error_if_points_leave_domain = db->getBool("error_if_points_leave_domain"); if (db->keyExists("do_log")) d_do_log = db->getBool("do_log"); else if (db->keyExists("enable_logging")) d_do_log = db->getBool("enable_logging"); return; } // getFromInput void IMPMethod::getFromRestart() { Pointer<Database> restart_db = RestartManager::getManager()->getRootDatabase(); Pointer<Database> db; if (restart_db->isDatabase(d_object_name)) { db = restart_db->getDatabase(d_object_name); } else { TBOX_ERROR(d_object_name << ": Restart database corresponding to " << d_object_name << " not found in restart file." << std::endl); } int ver = db->getInteger("IMP_METHOD_VERSION"); if (ver != IMP_METHOD_VERSION) { TBOX_ERROR(d_object_name << ": Restart file version different than class version." << std::endl); } db->getIntegerArray("d_ghosts", d_ghosts, NDIM); return; } // getFromRestart /////////////////////////////// NAMESPACE //////////////////////////////////// } // namespace IBAMR //////////////////////////////////////////////////////////////////////////////
#include <QApplication> #include <QDebug> #include "Meta.hpp" #include "MainWindow.hpp" int main(int argc, char *argv[]) { qInfo() << "NESZ version: " << NESZ_VERSION; QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); }
// RUN: %clang_cc1 -std=c++17 -verify %s using intptr_t = __INTPTR_TYPE__; // Test interaction of constexpr and __builtin_constant_p. template<typename T> constexpr bool bcp(T t) { return __builtin_constant_p(t); } template<typename T> constexpr bool bcp_fold(T t) { return __builtin_constant_p(((void)(intptr_t)&t, t)); } constexpr intptr_t ensure_fold_is_generally_not_enabled = // expected-error {{constant expression}} (intptr_t)&ensure_fold_is_generally_not_enabled; // expected-note {{cast}} constexpr intptr_t ptr_to_int(const void *p) { return __builtin_constant_p(1) ? (intptr_t)p : (intptr_t)p; } constexpr int *int_to_ptr(intptr_t n) { return __builtin_constant_p(1) ? (int*)n : (int*)n; } int x; // Integer and floating point constants encountered during constant expression // evaluation are considered constant. So is nullptr_t. static_assert(bcp(1)); static_assert(bcp_fold(1)); static_assert(bcp(1.0)); static_assert(bcp_fold(1.0)); static_assert(bcp(nullptr)); static_assert(bcp_fold(nullptr)); // Pointers to the start of strings are considered constant. static_assert(bcp("foo")); static_assert(bcp_fold("foo")); // Null pointers are considered constant. static_assert(bcp<int*>(nullptr)); static_assert(bcp_fold<int*>(nullptr)); static_assert(bcp<const char*>(nullptr)); static_assert(bcp_fold<const char*>(nullptr)); // Other pointers are not. static_assert(!bcp(&x)); static_assert(!bcp_fold(&x)); // Pointers cast to integers follow the rules for pointers. static_assert(bcp(ptr_to_int("foo"))); static_assert(bcp_fold(ptr_to_int("foo"))); static_assert(!bcp(ptr_to_int(&x))); static_assert(!bcp_fold(ptr_to_int(&x))); // Integers cast to pointers follow the integer rules. static_assert(bcp(int_to_ptr(0))); static_assert(bcp_fold(int_to_ptr(0))); static_assert(bcp(int_to_ptr(123))); // GCC rejects these due to not recognizing static_assert(bcp_fold(int_to_ptr(123))); // the bcp conditional in 'int_to_ptr' ... static_assert(__builtin_constant_p((int*)123)); // ... but GCC accepts this // State mutations in the operand are not permitted. // // The rule GCC uses for this is not entirely understood, but seems to depend // in some way on what local state is mentioned in the operand of // __builtin_constant_p and where. // // We approximate GCC's rule by evaluating the operand in a speculative // evaluation context; only state created within the evaluation can be // modified. constexpr int mutate1() { int n = 1; int m = __builtin_constant_p(++n); return n * 10 + m; } static_assert(mutate1() == 10); // FIXME: GCC treats this as being non-constant because of the "n = 2", even // though evaluation in the context of the enclosing constant expression // succeeds without mutating any state. constexpr int mutate2() { int n = 1; int m = __builtin_constant_p(n ? n + 1 : n = 2); return n * 10 + m; } static_assert(mutate2() == 11); constexpr int internal_mutation(int unused) { int x = 1; ++x; return x; } constexpr int mutate3() { int n = 1; int m = __builtin_constant_p(internal_mutation(0)); return n * 10 + m; } static_assert(mutate3() == 11); constexpr int mutate4() { int n = 1; int m = __builtin_constant_p(n ? internal_mutation(0) : 0); return n * 10 + m; } static_assert(mutate4() == 11); // FIXME: GCC treats this as being non-constant because of something to do with // the 'n' in the argument to internal_mutation. constexpr int mutate5() { int n = 1; int m = __builtin_constant_p(n ? internal_mutation(n) : 0); return n * 10 + m; } static_assert(mutate5() == 11); constexpr int mutate_param(bool mutate, int &param) { mutate = mutate; // Mutation of internal state is OK if (mutate) ++param; return param; } constexpr int mutate6(bool mutate) { int n = 1; int m = __builtin_constant_p(mutate_param(mutate, n)); return n * 10 + m; } // No mutation of state outside __builtin_constant_p: evaluates to true. static_assert(mutate6(false) == 11); // Mutation of state outside __builtin_constant_p: evaluates to false. static_assert(mutate6(true) == 10); // GCC strangely returns true for the address of a type_info object, despite it // not being a pointer to the start of a string literal. namespace std { struct type_info; } static_assert(__builtin_constant_p(&typeid(int)));
#include "ImageDealer.h" #include <vector> #include <algorithm> #include "stb_image.h" #include "stb_image_write.h" std::shared_ptr<RawImage> ImageDealer::GrayScale(const std::shared_ptr<RawImage> image) { auto grayImage = std::make_shared<RawImage>(); grayImage->width = image->width; grayImage->height = image->height; grayImage->numChannels = 1; grayImage->data.resize(static_cast<size_t>(grayImage->width) * grayImage->height); for(int i = 0; i < image->width; i++){ for(int j = 0; j < image->height; j++){ int indexOfPixel = j * image->width + i; int indexOfByte = indexOfPixel * image->numChannels; auto r = static_cast<int>(image->data[indexOfByte + 0]); auto g = static_cast<int>(image->data[indexOfByte + 1]); auto b = static_cast<int>(image->data[indexOfByte + 2]); float gray = 0.2989f * r + 0.5870f * g + 0.1140f * b; int graylevel = static_cast<int>(gray + 0.5); grayImage->data[indexOfPixel] = graylevel; } } return grayImage; } void ImageDealer::CalcHistogram(const std::vector<unsigned char>& grayImage, std::vector<int>& histogram) { histogram.clear(); histogram.resize(256, 0); for(size_t i = 0; i < grayImage.size(); i++){ int grayLevel = static_cast<int>(grayImage[i]); histogram[grayLevel]++; } } std::shared_ptr<RawImage> ImageDealer::Equalize(const std::shared_ptr<RawImage> grayImage, int numLevels) { // Result to return std::shared_ptr<RawImage> result = std::make_shared<RawImage>(); // Gray histogram of origin gray image std::vector<int> histogram; // Occurrence probability of each gray level std::vector<double> probabilitiesOfGrayLevel(numLevels); // Accumulative sum of the probability std::vector<double> accumulativeProbalities(numLevels); // Mapping from a gray level to another gray level std::vector<int> mapping(numLevels); // Calculate gray hisrogram first CalcHistogram(grayImage->data, histogram); // Calculate the mapping for(int i = 0; i < numLevels; i++){ probabilitiesOfGrayLevel[i] = histogram[i] * 1.0 / grayImage->data.size(); if(i == 0) accumulativeProbalities[0] = probabilitiesOfGrayLevel[0]; accumulativeProbalities[i] = accumulativeProbalities[i - 1] + probabilitiesOfGrayLevel[i]; mapping[i] = static_cast<int>(accumulativeProbalities[i] * (numLevels - 1) + 0.5); } result->Ready(*grayImage); for(int i = 0; i < result->width; i++){ for(int j = 0; j < result->height; j++){ result->SetGray(i, j, mapping[grayImage->GetGray(i, j)]); } } return result; } std::shared_ptr<RawImage> ImageDealer::Mirror(const std::shared_ptr<RawImage> image, bool verticalFlip) { auto result = std::make_shared<RawImage>(); result->Ready(*image); // Left-right mirror if(verticalFlip){ for(int j = 0; j < result->height; j++){ for(int i = 0; i < result->width; i++){ int dstIndexOfPixel = j * result->width + i; int srcIndexOfPixel = (j + 1) * result->width -1 - i; int dstIndexOfByte = dstIndexOfPixel * result->numChannels; int srcIndexOfByte = srcIndexOfPixel * result->numChannels; for(int k = 0; k < result->numChannels; k++){ result->data[dstIndexOfByte + k] = image->data[srcIndexOfByte + k]; } // result->data[dstIndexOfByte + 0] = image->data[srcIndexOfByte + 0]; // result->data[dstIndexOfByte + 1] = image->data[srcIndexOfByte + 1]; // result->data[dstIndexOfByte + 2] = image->data[srcIndexOfByte + 2]; } } } // Up-down mirror else{ for(int j = 0; j < result->width; j++){ for(int i = 0; i < result->height; i++){ int dstIndexOfPixel = i * result->width + j; int srcIndexOfPixel = (result->height - 1 - i) * result->width + j; int dstIndexOfByte = dstIndexOfPixel * result->numChannels; int srcIndexOfByte = srcIndexOfPixel * result->numChannels; for(int k = 0; k < result->numChannels; k++){ result->data[dstIndexOfByte + k] = image->data[srcIndexOfByte + k]; } // result->data[dstIndexOfByte + 0] = image->data[srcIndexOfByte + 0]; // result->data[dstIndexOfByte + 1] = image->data[srcIndexOfByte + 1]; // result->data[dstIndexOfByte + 2] = image->data[srcIndexOfByte + 2]; } } } return result; } std::shared_ptr<RawImage> ImageDealer::WeightedFilter(const std::shared_ptr<RawImage> image, std::vector<float> filter, int filterShape, bool divideBySum) { // Only deal with gray image if(image->numChannels != 1) return nullptr; // Do not deal with images with too small size if(image->data.size() < filter.size()) return nullptr; // Require filter shape to be n*n if(filter.size() != static_cast<size_t>(filterShape) * filterShape) return nullptr; auto result = std::make_shared<RawImage>(); int halfShape = filterShape / 2; if(divideBySum){ float sum = 0.0f; for(const auto num: filter) sum += num; if(sum - 0.0f < 0.000001f) return nullptr; for(auto& num: filter) num /= sum; } // Ready to receive data result->Ready(*image); // Weight for every pixel with the filter for(int j = 0; j < result->height; j++){ for(int i = 0; i < result->width; i++){ if(i < halfShape || j < halfShape){ result->SetGray(i, j, image->GetGray(i, j)); continue; } int minX = i - halfShape; int minY = j - halfShape; float sum = 0.0f; for(size_t k = 0; k < filter.size(); k++){ int offsetX = k % filterShape; int offsetY = k / filterShape; int x = minX + offsetX; int y = minY + offsetY; sum += image->GetGray(x, y) * filter[k]; } result->SetGray(i, j, static_cast<int>(sum + 0.5f)); } } return result; } std::shared_ptr<RawImage> ImageDealer::MedianFilter(const std::shared_ptr<RawImage> image, int filterShape) { // Only deal with gray image if(image->numChannels != 1) return nullptr; // Do not deal with images with too small size if(image->data.size() < static_cast<size_t>(filterShape) * filterShape) return nullptr; auto result = std::make_shared<RawImage>(); int halfShape = filterShape / 2; int filterSize = filterShape * filterShape; int halfSize = filterSize / 2; std::vector<int> buffer(filterSize); // Ready to receive data result->Ready(*image); // Find the median of pixels under the filter for(int j = 0; j < result->height; j++){ for(int i = 0; i < result->width; i++){ if(i < halfShape || j < halfShape){ result->SetGray(i, j, image->GetGray(i, j)); continue; } int minX = i - halfShape; int minY = j - halfShape; for(int k = 0; k < filterSize; k++){ int offsetX = k % filterShape; int offsetY = k / filterShape; int x = minX + offsetX; int y = minY + offsetY; buffer[k] = image->GetGray(x, y); } std::nth_element(buffer.begin(), buffer.begin() + halfSize, buffer.end()); result->SetGray(i, j, buffer[halfSize]); } } return result; } std::shared_ptr<RawImage> ImageDealer::MaxFilter(const std::shared_ptr<RawImage> image, int filterShape) { // Only deal with gray image if(image->numChannels != 1) return nullptr; // Do not deal with images with too small size if(image->data.size() < static_cast<size_t>(filterShape) * filterShape) return nullptr; auto result = std::make_shared<RawImage>(); int halfShape = filterShape / 2; int filterSize = filterShape * filterShape; // Ready to receive data result->Ready(*image); // Find the max value of pixels under the filter for(int j = 0; j < result->height; j++){ for(int i = 0; i < result->width; i++){ if(i < halfShape || j < halfShape){ result->SetGray(i, j, image->GetGray(i, j)); continue; } int minX = i - halfShape; int minY = j - halfShape; int maxValue = -1; for(int k = 0; k < filterSize; k++){ int offsetX = k % filterShape; int offsetY = k / filterShape; int x = minX + offsetX; int y = minY + offsetY; if(image->GetGray(x, y) > maxValue) maxValue = image->GetGray(x, y); } result->SetGray(i, j, maxValue); } } return result; } std::shared_ptr<RawImage> ImageDealer::LoadRawImage(const char* fileName) { std::shared_ptr<RawImage> rawImage = nullptr; int width; int height; int numChannels; auto data = stbi_load(fileName, &width, &height, &numChannels, 0); if(data){ rawImage = std::make_shared<RawImage>(); rawImage->width = width; rawImage->height = height; rawImage->numChannels = numChannels; rawImage->data.clear(); rawImage->data.resize(static_cast<size_t>(width) * height * numChannels); for(size_t i = 0; i < rawImage->data.size(); i++) rawImage->data[i] = data[i]; stbi_image_free(data); } return rawImage; }
/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 - 2021 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "src/operators/pm_from_file.h" #include <string> #include "src/operators/operator.h" #include "src/utils/https_client.h" #include "src/utils/system.h" namespace modsecurity { namespace operators { bool PmFromFile::isComment(const std::string &s) { if (s.size() == 0) { return true; } size_t pos = s.find("#"); if (pos != std::string::npos) { for (int i = 0; i < pos; i++) { if (!std::isspace(s[i])) { return false; } } } else { return false; } return true; } bool PmFromFile::init(const std::string &config, std::string *error) { std::istream *iss; if (m_param.compare(0, 8, "https://") == 0) { Utils::HttpsClient client; bool ret = client.download(m_param); if (ret == false) { error->assign(client.error); return false; } iss = new std::stringstream(client.content); } else { std::string err; std::string resource = utils::find_resource(m_param, config, &err); iss = new std::ifstream(resource, std::ios::in); if (((std::ifstream *)iss)->is_open() == false) { error->assign("Failed to open file: " + m_param + ". " + err); delete iss; return false; } } for (std::string line; std::getline(*iss, line); ) { if (isComment(line) == false) { acmp_add_pattern(m_p, line.c_str(), NULL, NULL, line.length()); } } while (m_p->is_failtree_done == 0) { acmp_prepare(m_p); } delete iss; return true; } } // namespace operators } // namespace modsecurity
#include "server.h" #include <boost/asio.hpp> #include <boost/filesystem.hpp> #include <exception> #include <fstream> #include <mutex> #include <thread> #include "3rd/simple_web_server/server_http.hpp" #include "3rd/simple_websocket_server/server_ws.hpp" #include "connection.h" #include "logger.h" namespace opentrade { using WsServer = SimpleWeb::SocketServer<SimpleWeb::WS>; using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>; typedef std::shared_ptr<WsServer::Connection> WsConnPtr; typedef std::shared_ptr<HttpServer::Response> ResponsePtr; typedef std::shared_ptr<HttpServer::Request> RequestPtr; typedef std::lock_guard<std::mutex> LockGuard; static HttpServer kHttpServer; static WsServer kWsServer; static std::unordered_map<WsConnPtr, Connection::Ptr> kSocketMap; static std::mutex kMutex; static auto kIoService = std::make_shared<boost::asio::io_service>(); void Close(WsConnPtr connection) { LockGuard lock(kMutex); auto it = kSocketMap.find(connection); if (it == kSocketMap.end()) return; it->second->Close(); kSocketMap.erase(it); } struct WsSocketWrapper : public Transport { explicit WsSocketWrapper(WsConnPtr ws) : ws_(ws) {} std::string GetAddress() const { return ws_->remote_endpoint_address(); } void Send(const std::string& msg) override { ws_->send(msg, [](const SimpleWeb::error_code& e) { if (e) { LOG_DEBUG("GATEWAY Server: Error sending message. " << "Error: " << e << ", error message: " << e.message()); } }); } private: WsConnPtr ws_; }; struct HttpWrapper : public Transport { explicit HttpWrapper(ResponsePtr res, RequestPtr req) : res_(res), req_(req) { stateless = true; } std::string GetAddress() const { return req_->remote_endpoint_address(); } void Send(const std::string& msg) override { *res_ << "HTTP/1.1 200 OK\r\n" << "Content-Length: " << msg.length() << "\r\n\r\n" << msg; } private: ResponsePtr res_; RequestPtr req_; }; void Server::Publish(Confirmation::Ptr cm) { #ifdef BACKTEST return; #endif kIoService->post([cm]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { pair.second->Send(cm); } }); } void Server::Publish(const std::string& msg, const SubAccount* acc) { #ifdef BACKTEST return; #endif kIoService->post([msg, acc]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { pair.second->Send(msg, acc); } }); } void Server::CloseConnection(User::IdType id) { kIoService->post([id]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { auto user = pair.second->user(); if (user && user->id == id) { pair.first->send_close(1011); } } }); } void Server::Trigger(const std::string& cmd) { kIoService->post([cmd]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { pair.second->OnMessageAsync(cmd); } }); } void Server::PublishTestMsg(const std::string& token, const std::string& msg, bool stopped) { kIoService->post([token, msg, stopped]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { pair.second->SendTestMsg(token, msg, stopped); } }); } void Server::Publish(const Algo& algo, const std::string& status, const std::string& body, uint32_t seq) { kIoService->post([&algo, status, body, seq]() { LockGuard lock(kMutex); for (auto& pair : kSocketMap) { pair.second->Send(algo, status, body, seq); } }); } static void ServeStatic() { kHttpServer.default_resource["GET"] = [](ResponsePtr response, RequestPtr request) { try { auto web_root_path = boost::filesystem::canonical("web"); auto path = boost::filesystem::canonical(web_root_path / request->path); // Check if path is within web_root_path if (std::distance(web_root_path.begin(), web_root_path.end()) > std::distance(path.begin(), path.end()) || !std::equal(web_root_path.begin(), web_root_path.end(), path.begin())) throw std::invalid_argument("path must be within root path"); if (boost::filesystem::is_directory(path)) path /= "index.html"; SimpleWeb::CaseInsensitiveMultimap header; // Uncomment the following line to enable Cache-Control // header.emplace("Cache-Control", "max-age=86400"); auto ifs = std::make_shared<std::ifstream>(); ifs->open(path.string(), std::ifstream::in | std::ios::binary | std::ios::ate); if (*ifs) { auto length = ifs->tellg(); ifs->seekg(0, std::ios::beg); header.emplace("Content-Length", std::to_string(length)); response->write(header); // Trick to define a recursive function within this scope (for // example purposes) class FileServer { public: static void read_and_send(ResponsePtr response, const std::shared_ptr<std::ifstream> ifs) { // Read and send 128 KB at a time static std::vector<char> buffer( 131072); // Safe when server is running on one thread std::streamsize read_length; if ((read_length = ifs->read(&buffer[0], static_cast<std::streamsize>(buffer.size())) .gcount()) > 0) { response->write(&buffer[0], read_length); if (read_length == static_cast<std::streamsize>(buffer.size())) { response->send( [response, ifs](const SimpleWeb::error_code& ec) { if (!ec) read_and_send(response, ifs); else LOG_DEBUG("Http connection interrupted"); }); } } } }; FileServer::read_and_send(response, ifs); } else { throw std::invalid_argument("could not read file"); } } catch (const std::exception& e) { response->write(SimpleWeb::StatusCode::client_error_bad_request, "Could not open path " + request->path + ": " + e.what()); } }; } void Server::Start(int port, int nthreads) { nthreads = std::min(1, nthreads); LOG_INFO("Web server nthreads=" << nthreads); kHttpServer.io_service = kIoService; kHttpServer.config.reuse_address = true; kHttpServer.config.port = port; kWsServer.io_service = kIoService; kWsServer.config.reuse_address = true; kWsServer.config.port = port + 1; auto& endpoint = kWsServer.endpoint["^/ot[/]?$"]; endpoint.on_message = [](WsConnPtr connection, std::shared_ptr<WsServer::InMessage> message) { Connection::Ptr p; { LockGuard lock(kMutex); p = kSocketMap[connection]; } if (p) p->OnMessageAsync(message->string()); }; endpoint.on_open = [](WsConnPtr connection) { LOG_DEBUG("Websocket Server: Opened connection " << connection->remote_endpoint_address()); auto p = std::make_shared<Connection>( std::make_shared<WsSocketWrapper>(connection), kIoService); { LockGuard lock(kMutex); kSocketMap[connection] = p; } }; endpoint.on_close = [](WsConnPtr connection, int status, const std::string& /*reason*/) { LOG_DEBUG("Websocket Server: Closed connection " << connection->remote_endpoint_address() << " with status code " << status); Close(connection); }; endpoint.on_error = [](WsConnPtr connection, const SimpleWeb::error_code& e) { LOG_DEBUG("Websocket Server: Error in connection " << connection->remote_endpoint_address() << ". " << "Error: " << e << ", error message: " << e.message()); Close(connection); }; // to make nginx work kHttpServer.on_upgrade = [=](std::unique_ptr<SimpleWeb::HTTP>& socket, std::shared_ptr<typename SimpleWeb::ServerBase< SimpleWeb::HTTP>::Request> request) { auto connection = std::make_shared<SimpleWeb::SocketServer<SimpleWeb::WS>::Connection>( std::move(socket)); connection->method = std::move(request->method); connection->path = std::move(request->path); connection->query_string = std::move(request->query_string); connection->http_version = std::move(request->http_version); connection->header = std::move(request->header); connection->remote_endpoint = std::move(*request->remote_endpoint); kWsServer.upgrade(connection); }; ServeStatic(); kHttpServer.resource["^/api[/]$"]["POST"] = [](ResponsePtr response, RequestPtr request) { auto sessionToken = FindInMap(request->header, "session-token"); std::make_shared<Connection>( std::make_shared<HttpWrapper>(response, request), kIoService) ->OnMessageSync(request->content.string(), sessionToken); }; kHttpServer.on_error = [](RequestPtr /*request*/, const SimpleWeb::error_code& e) { LOG_DEBUG("Http Server Error: " << e.message()); }; try { kWsServer.start(); kHttpServer.start(); LOG_INFO("http://0.0.0.0:" << port); LOG_INFO("ws://0.0.0.0:" << port << "/ot/"); LOG_INFO("htpp://0.0.0.0:" << port << "/api/"); std::vector<std::thread> threads; for (auto i = 0; i < nthreads; ++i) { threads.emplace_back([]() { kIoService->run(); }); } if (fs::exists(fs::path("start.py"))) { if (system(("nohup ./start.py " + std::to_string(port) + " &").c_str())) { // bypass compile warn } } for (auto& t : threads) t.join(); } catch (std::runtime_error& e) { LOG_ERROR("failed to start web server: " << e.what()); } } void Server::Stop() { kHttpServer.stop(); kWsServer.stop(); LockGuard lock(kMutex); for (auto& pair : kSocketMap) pair.second->Close(); kSocketMap.clear(); } } // namespace opentrade
// mk4.inl -- // $Id$ // This is part of Metakit, the homepage is http://www.equi4.com/metakit.html /** @file * Public definitions which are usually inlined */ ///////////////////////////////////////////////////////////////////////////// // Reordered inlines so they are always defined before their first use d4_inline c4_Cursor c4_RowRef::operator& () const { return _cursor; } /** Return a unique id for this property * * A property object in fact merely represents an entry in a globally * maintained symbol table. Each property is assigned a unique id, * which remains valid as long as some reference to that property * exists. In general, property id's remain unique as long as the * application runs. Do not store id's on file, since they are * not guaranteed to remain the same across program invocations. * All properties with the same name are given the same id. */ d4_inline int c4_Property::GetId() const { return _id; } ////////////////////////////////////////////////////////////////////////////////// #if !q4_LONG64 && !defined (LONG_LONG) && !HAVE_LONG_LONG d4_inline bool operator== (const t4_i64 a_, const t4_i64 b_) { return a_.l1 == b_.l1 && a_.l2 == b_.l2; } d4_inline bool operator< (const t4_i64 a_, const t4_i64 b_) { return a_.l2 < b_.l2 || a_.l2 == b_.l2 && a_.l2 < b_.l2; } #endif ////////////////////////////////////////////////////////////////////////////////// // c4_View /// Returns the number of entries in this view. d4_inline int c4_View::GetSize() const { return _seq->NumRows(); } /** Change the size of this view * Since views act like dynamic arrays, you can quickly * change their size. Increasing the size will append rows * with zero/empty values, while decreasing it will delete * the last rows. The growBy_ parameter is currently unused. */ d4_inline void c4_View::SetSize(int newSize_, int growBy_) { _seq->Resize(newSize_, growBy_); } /// Removes all entries (sets size to zero). d4_inline void c4_View::RemoveAll() { SetSize(0); } /// Return a pointer to the persistence handler, or zero d4_inline c4_Persist* c4_View::Persist() const { return _seq->Persist(); } /** * Change the value of the specified entry. If the new value has * other properties, these will be added to the underlying view. * * @param index_ the zero-based row index * @param newElem_ the row to copy to this view */ d4_inline void c4_View::SetAt(int index_, const c4_RowRef& newElem_) { _seq->SetAt(index_, &newElem_); } /** * Insert a copy of the contents of another view. This is identical to * inserting the specified number of default entries and then setting * each of them to the new element value passed as argument. */ d4_inline void c4_View::InsertAt( int index_, ///< zero-based row index const c4_RowRef& newElem_, ///< the value to insert int count_ ///< number of copies to insert, must be > 0 ) { _seq->InsertAt(index_, &newElem_, count_); } /** * Remove entries starting at the given index. Entries which have * other view references may cause these views to be deleted if their * reference counts drop to zero because of this removal. * * @param index_ the zero-based row index * @param count_ the number of entries to remove */ d4_inline void c4_View::RemoveAt(int index_, int count_) { _seq->RemoveAt(index_, count_); } /** Return the number of properties present in this view. * @return A non-negative integer */ d4_inline int c4_View::NumProperties() const { return _seq->NumHandlers(); } /** Find the index of a property, given its id * @param propId_ Unique id associated to a specific propoerty * @return The index of the property, or -1 of it was not found */ d4_inline int c4_View::FindProperty(int propId_) { return _seq->PropIndex(propId_); } /// Return a decription if there is a fixed structure, else zero d4_inline const char* c4_View::Description() const { return _seq->Description(); } /// Increase the reference count of the associated sequence d4_inline void c4_View::_IncSeqRef() { _seq->IncRef(); } /// Decrease the reference count of the associated sequence d4_inline void c4_View::_DecSeqRef() { _seq->DecRef(); } /// Destructor, decrements reference count d4_inline c4_View::~c4_View () { _DecSeqRef(); } /// Return true if the contents of both views are equal d4_inline bool operator== (const c4_View& a_, const c4_View& b_) { return a_.GetSize() == b_.GetSize() && a_.Compare(b_) == 0; } /// Return true if the contents of both views are not equal d4_inline bool operator!= (const c4_View& a_, const c4_View& b_) { return !(a_ == b_); } /// True if first view is less than second view d4_inline bool operator< (const c4_View& a_, const c4_View& b_) { return a_.Compare(b_) < 0; } /// True if first view is greater than second view d4_inline bool operator> (const c4_View& a_, const c4_View& b_) { return b_ < a_; } /// True if first view is less or equal to second view d4_inline bool operator<= (const c4_View& a_, const c4_View& b_) { return !(b_ < a_); } /// True if first view is greater or equal to second view d4_inline bool operator>= (const c4_View& a_, const c4_View& b_) { return !(a_ < b_); } ///////////////////////////////////////////////////////////////////////////// // c4_Cursor /** Constructs a new cursor. * * Cursor cannot be created without an underlying view, but you could * define a global "nullView" object and then initialize the cursor with * "&nullView[0]". This works because cursors need not point to a valid row. */ d4_inline c4_Cursor::c4_Cursor (c4_Sequence& seq_, int index_) : _seq (&seq_), _index (index_) { } /// Pre-increments the cursor. d4_inline c4_Cursor& c4_Cursor::operator++ () { ++_index; return *this; } /// Post-increments the cursor. d4_inline c4_Cursor c4_Cursor::operator++ (int) { return c4_Cursor (*_seq, _index++); } /// Pre-decrements the cursor. d4_inline c4_Cursor& c4_Cursor::operator-- () { --_index; return *this; } /// Post-decrements the cursor. d4_inline c4_Cursor c4_Cursor::operator-- (int) { return c4_Cursor (*_seq, _index--); } /// Advances by a given offset. d4_inline c4_Cursor& c4_Cursor::operator+= (int offset_) { _index += offset_; return *this; } /// Backs up by a given offset. d4_inline c4_Cursor& c4_Cursor::operator-= (int offset_) { _index -= offset_; return *this; } /// Subtracts a specified offset. d4_inline c4_Cursor c4_Cursor::operator- (int offset_) const { return c4_Cursor (*_seq, _index - offset_); } /// Returns the distance between two cursors. d4_inline int c4_Cursor::operator- (c4_Cursor cursor_) const { return _index - cursor_._index; } /// Add a specified offset. d4_inline c4_Cursor operator+ (c4_Cursor cursor_, int offset_) { return c4_Cursor (*cursor_._seq, cursor_._index + offset_); } /// Adds specified offset to cursor. d4_inline c4_Cursor operator+ (int offset_, c4_Cursor cursor_) { return cursor_ + offset_; } d4_inline bool operator== (c4_Cursor a_, c4_Cursor b_) { return a_._seq == b_._seq && a_._index == b_._index; } d4_inline bool operator!= (c4_Cursor a_, c4_Cursor b_) { return !(a_ == b_); } d4_inline bool operator< (c4_Cursor a_, c4_Cursor b_) { return a_._seq < b_._seq || a_._seq == b_._seq && a_._index < b_._index; } d4_inline bool operator> (c4_Cursor a_, c4_Cursor b_) { return b_ < a_; } d4_inline bool operator<= (c4_Cursor a_, c4_Cursor b_) { return !(b_ < a_); } d4_inline bool operator>= (c4_Cursor a_, c4_Cursor b_) { return !(a_ < b_); } ///////////////////////////////////////////////////////////////////////////// // c4_RowRef d4_inline c4_RowRef::c4_RowRef (c4_Cursor cursor_) : _cursor (cursor_) { } d4_inline c4_RowRef c4_RowRef::operator= (const c4_RowRef& rowRef_) { if (_cursor != rowRef_._cursor) _cursor._seq->SetAt(_cursor._index, &rowRef_); return *this; } d4_inline c4_View c4_RowRef::Container() const { return _cursor._seq; } d4_inline bool operator== (const c4_RowRef& a_, const c4_RowRef& b_) { return (&a_)._seq->Compare((&a_)._index, &b_) == 0; } d4_inline bool operator!= (const c4_RowRef& a_, const c4_RowRef& b_) { return !(a_ == b_); } d4_inline bool operator< (const c4_RowRef& a_, const c4_RowRef& b_) { // 25-5-1998: don't exchange a and b, this comparison is -not- symmetric return (&a_)._seq->Compare((&a_)._index, &b_) < 0; } d4_inline bool operator> (const c4_RowRef& a_, const c4_RowRef& b_) { // 25-5-1998: don't exchange a and b, this comparison is -not- symmetric return (&a_)._seq->Compare((&a_)._index, &b_) > 0; } d4_inline bool operator<= (const c4_RowRef& a_, const c4_RowRef& b_) { return !(a_ > b_); } d4_inline bool operator>= (const c4_RowRef& a_, const c4_RowRef& b_) { return !(a_ < b_); } ///////////////////////////////////////////////////////////////////////////// // c4_Bytes /// Construct an empty binary object d4_inline c4_Bytes::c4_Bytes () : _size (0), _copy (false) { _contents = 0; // moved out of intializers for DEC CXX 5.7 } /// Construct an object with contents, no copy d4_inline c4_Bytes::c4_Bytes (const void* buf_, int len_) : _size (len_), _copy (false) { _contents = (t4_byte*) buf_; // moved out of intializers for DEC CXX 5.7 } /// Returns a pointer to the contents. d4_inline const t4_byte* c4_Bytes::Contents() const { return _contents; } /// Returns the number of bytes of its contents. d4_inline int c4_Bytes::Size() const { return _size; } d4_inline void c4_Bytes::_LoseCopy() { if (_copy) delete [] (char*) _contents; } /// Returns true if the contents of both objects is not equal. d4_inline bool operator!= (const c4_Bytes& a_, const c4_Bytes& b_) { return !(a_ == b_); } /// Destructor, if a copy was made, it will be released here. d4_inline c4_Bytes::~c4_Bytes () { _LoseCopy(); } ///////////////////////////////////////////////////////////////////////////// // c4_Reference d4_inline c4_Reference::c4_Reference (const c4_RowRef& rowRef_, const c4_Property& prop_) : _cursor (&rowRef_), _property (prop_) { } d4_inline int c4_Reference::GetSize() const { return _cursor._seq->ItemSize(_cursor._index, _property.GetId()); } d4_inline bool c4_Reference::GetData(c4_Bytes& buf_) const { return _cursor._seq->Get(_cursor._index, _property.GetId(), buf_); } d4_inline void c4_Reference::SetData(const c4_Bytes& buf_) const { _cursor._seq->Set(_cursor._index, _property, buf_); } d4_inline bool operator!= (const c4_Reference& a_, const c4_Reference& b_) { return !(a_ == b_); } ///////////////////////////////////////////////////////////////////////////// // c4_IntRef d4_inline c4_IntRef::c4_IntRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// #if !q4_TINY ///////////////////////////////////////////////////////////////////////////// // c4_LongRef d4_inline c4_LongRef::c4_LongRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// // c4_FloatRef d4_inline c4_FloatRef::c4_FloatRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// // c4_DoubleRef d4_inline c4_DoubleRef::c4_DoubleRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// #endif // !q4_TINY ///////////////////////////////////////////////////////////////////////////// // c4_BytesRef d4_inline c4_BytesRef::c4_BytesRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// // c4_StringRef d4_inline c4_StringRef::c4_StringRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// // c4_ViewRef d4_inline c4_ViewRef::c4_ViewRef (const c4_Reference& value_) : c4_Reference (value_) { } ///////////////////////////////////////////////////////////////////////////// // c4_Property d4_inline c4_Property::c4_Property (char type_, int id_) : _id ((short) id_), _type (type_) { } /// Get or set this untyped property in a row d4_inline c4_Reference c4_Property::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } /// Return a view like the first, with a property appended to it d4_inline c4_View c4_Property::operator, (const c4_Property& prop_) const { return c4_View (*this), prop_; } /// Return the type of this property d4_inline char c4_Property::Type() const { return _type; } ///////////////////////////////////////////////////////////////////////////// // c4_IntProp d4_inline c4_IntProp::c4_IntProp (const char* name_) : c4_Property ('I', name_) { } d4_inline c4_IntProp::~c4_IntProp () { } d4_inline c4_IntRef c4_IntProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline t4_i32 c4_IntProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_IntProp::Set(const c4_RowRef& rowRef_, t4_i32 value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_IntProp::AsRow(t4_i32 value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_IntProp::operator[] (t4_i32 value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// #if !q4_TINY ///////////////////////////////////////////////////////////////////////////// // c4_LongProp d4_inline c4_LongProp::c4_LongProp (const char* name_) : c4_Property ('L', name_) { } d4_inline c4_LongProp::~c4_LongProp () { } d4_inline c4_LongRef c4_LongProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline t4_i64 c4_LongProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_LongProp::Set(const c4_RowRef& rowRef_, t4_i64 value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_LongProp::AsRow(t4_i64 value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_LongProp::operator[] (t4_i64 value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// // c4_FloatProp d4_inline c4_FloatProp::c4_FloatProp (const char* name_) : c4_Property ('F', name_) { } d4_inline c4_FloatProp::~c4_FloatProp () { } d4_inline c4_FloatRef c4_FloatProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline double c4_FloatProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_FloatProp::Set(const c4_RowRef& rowRef_, double value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_FloatProp::AsRow(double value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_FloatProp::operator[] (double value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// // c4_DoubleProp d4_inline c4_DoubleProp::c4_DoubleProp (const char* name_) : c4_Property ('D', name_) { } d4_inline c4_DoubleProp::~c4_DoubleProp () { } d4_inline c4_DoubleRef c4_DoubleProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline double c4_DoubleProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_DoubleProp::Set(const c4_RowRef& rowRef_, double value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_DoubleProp::AsRow(double value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_DoubleProp::operator[] (double value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// #endif // !q4_TINY ///////////////////////////////////////////////////////////////////////////// // c4_BytesProp d4_inline c4_BytesProp::c4_BytesProp (const char* name_) : c4_Property ('B', name_) { } d4_inline c4_BytesProp::~c4_BytesProp () { } d4_inline c4_BytesRef c4_BytesProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline c4_Bytes c4_BytesProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_BytesProp::Set(const c4_RowRef& rowRef_, const c4_Bytes& value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_BytesProp::AsRow(const c4_Bytes& value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_BytesProp::operator[] (const c4_Bytes& value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// // c4_StringProp d4_inline c4_StringProp::c4_StringProp (const char* name_) : c4_Property ('S', name_) { } d4_inline c4_StringProp::~c4_StringProp () { } d4_inline c4_StringRef c4_StringProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline const char* c4_StringProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_StringProp::Set(const c4_RowRef& rowRef_, const char* value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_StringProp::AsRow(const char* value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_StringProp::operator[] (const char* value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// // c4_ViewProp d4_inline c4_ViewProp::c4_ViewProp (const char* name_) : c4_Property ('V', name_) { } d4_inline c4_ViewProp::~c4_ViewProp () { } d4_inline c4_ViewRef c4_ViewProp::operator() (const c4_RowRef& rowRef_) const { return c4_Reference (rowRef_, *this); } d4_inline c4_View c4_ViewProp::Get(const c4_RowRef& rowRef_) const { return operator() (rowRef_); } d4_inline void c4_ViewProp::Set(const c4_RowRef& rowRef_, const c4_View& value_) const { operator() (rowRef_) = value_; } d4_inline c4_Row c4_ViewProp::AsRow(const c4_View& value_) const { c4_Row row; operator() (row) = value_; return row; } d4_inline c4_Row c4_ViewProp::operator[] (const c4_View& value_) const { return AsRow(value_); } ///////////////////////////////////////////////////////////////////////////// // c4_Strategy /// True if we can do I/O with this object d4_inline bool c4_Strategy::IsValid() const { return false; } ///////////////////////////////////////////////////////////////////////////// // c4_CustomViewer d4_inline c4_CustomViewer::c4_CustomViewer() { } d4_inline int c4_CustomViewer::Lookup(const c4_RowRef& r_, int& n_) { return Lookup(&r_, n_); // c4_Cursor } d4_inline bool c4_CustomViewer::InsertRows(int p_, const c4_RowRef& r_, int n_) { return InsertRows(p_, &r_, n_); // c4_Cursor } ///////////////////////////////////////////////////////////////////////////// // c4_Sequence d4_inline c4_Dependencies* c4_Sequence::GetDependencies() const { return _dependencies; } ///////////////////////////////////////////////////////////////////////////// // Reordered inlines so they are always used after their definition /// Dereferences this cursor to "almost" a row. d4_inline c4_RowRef c4_Cursor::operator* () const { return *(c4_Cursor*) this; // cast avoids a const problem with BCPP 4.52 } /// This is the same as *(cursor + offset). d4_inline c4_RowRef c4_Cursor::operator[] (int offset_) const { return *(*this + offset_); } /// Returns a reference to specified entry, for use as RHS or LHS d4_inline c4_RowRef c4_View::GetAt(int index_) const { return * c4_Cursor (*_seq, index_); } /** Element access, shorthand for GetAt * @return A reference to the specified row in the view. * This reference can be used on either side of the assignment operator. */ d4_inline c4_RowRef c4_View::operator[] ( int index_ ///< zero-based row index ) const { return GetAt(index_); } /** Element access, shorthand for GetAt * @return A reference to the specified row in the view. * This reference can be used on either side of the assignment operator. */ d4_inline c4_RowRef c4_View::ElementAt( int index_ ///< zero-based row index ) { return GetAt(index_); } /////////////////////////////////////////////////////////////////////////////
/* By Paul Hsieh (C) 2004, 2005. Covered under the Paul Hsieh * derivative license. * See: http://www.azillionmonkeys.com/qed/weblicense.html for license * details. * http://www.azillionmonkeys.com/qed/hash.html */ #include <libhashkit/common.h> #undef get16bits #if (defined(__GNUC__) && defined(__i386__)) #define get16bits(d) (*((const uint16_t *) (d))) #endif #if !defined (get16bits) #define get16bits(d) ((((uint32_t)(((const uint8_t *)(d))[1])) << 8)\ +(uint32_t)(((const uint8_t *)(d))[0]) ) #endif #ifdef HAVE_HSIEH_HASH uint32_t hashkit_hsieh(const char *key, size_t key_length, void *) { uint32_t hash = 0, tmp; int rem; if (key_length <= 0 || key == NULL) return 0; rem = key_length & 3; key_length >>= 2; /* Main loop */ for (;key_length > 0; key_length--) { hash += get16bits (key); tmp = (get16bits (key+2) << 11) ^ hash; hash = (hash << 16) ^ tmp; key += 2*sizeof (uint16_t); hash += hash >> 11; } /* Handle end cases */ switch (rem) { case 3: hash += get16bits (key); hash ^= hash << 16; hash ^= (uint32_t)key[sizeof (uint16_t)] << 18; hash += hash >> 11; break; case 2: hash += get16bits (key); hash ^= hash << 11; hash += hash >> 17; break; case 1: hash += (unsigned char)(*key); hash ^= hash << 10; hash += hash >> 1; default: break; } /* Force "avalanching" of final 127 bits */ hash ^= hash << 3; hash += hash >> 5; hash ^= hash << 4; hash += hash >> 17; hash ^= hash << 25; hash += hash >> 6; return hash; } #else uint32_t hashkit_hsieh(const char *, size_t , void *) { return 0; } #endif
// Copyright 2012 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/heap/mark-compact.h" #include <unordered_map> #include "src/base/utils/random-number-generator.h" #include "src/codegen/compilation-cache.h" #include "src/deoptimizer/deoptimizer.h" #include "src/execution/execution.h" #include "src/execution/frames-inl.h" #include "src/execution/vm-state-inl.h" #include "src/handles/global-handles.h" #include "src/heap/array-buffer-collector.h" #include "src/heap/array-buffer-tracker-inl.h" #include "src/heap/gc-tracer.h" #include "src/heap/incremental-marking-inl.h" #include "src/heap/invalidated-slots-inl.h" #include "src/heap/item-parallel-job.h" #include "src/heap/local-allocator-inl.h" #include "src/heap/mark-compact-inl.h" #include "src/heap/object-stats.h" #include "src/heap/objects-visiting-inl.h" #include "src/heap/read-only-heap.h" #include "src/heap/spaces-inl.h" #include "src/heap/sweeper.h" #include "src/heap/worklist.h" #include "src/ic/stub-cache.h" #include "src/init/v8.h" #include "src/objects/embedder-data-array-inl.h" #include "src/objects/foreign.h" #include "src/objects/hash-table-inl.h" #include "src/objects/js-objects-inl.h" #include "src/objects/maybe-object.h" #include "src/objects/slots-inl.h" #include "src/objects/transitions-inl.h" #include "src/tasks/cancelable-task.h" #include "src/utils/utils-inl.h" namespace v8 { namespace internal { const char* Marking::kWhiteBitPattern = "00"; const char* Marking::kBlackBitPattern = "11"; const char* Marking::kGreyBitPattern = "10"; const char* Marking::kImpossibleBitPattern = "01"; // The following has to hold in order for {MarkingState::MarkBitFrom} to not // produce invalid {kImpossibleBitPattern} in the marking bitmap by overlapping. STATIC_ASSERT(Heap::kMinObjectSizeInTaggedWords >= 2); // ============================================================================= // Verifiers // ============================================================================= #ifdef VERIFY_HEAP namespace { class MarkingVerifier : public ObjectVisitor, public RootVisitor { public: virtual void Run() = 0; protected: explicit MarkingVerifier(Heap* heap) : heap_(heap) {} virtual ConcurrentBitmap<AccessMode::NON_ATOMIC>* bitmap( const MemoryChunk* chunk) = 0; virtual void VerifyPointers(ObjectSlot start, ObjectSlot end) = 0; virtual void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) = 0; virtual void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) = 0; virtual bool IsMarked(HeapObject object) = 0; virtual bool IsBlackOrGrey(HeapObject object) = 0; void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) override { VerifyPointers(start, end); } void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointers(start, end); } void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override { VerifyRootPointers(start, end); } void VerifyRoots(VisitMode mode); void VerifyMarkingOnPage(const Page* page, Address start, Address end); void VerifyMarking(NewSpace* new_space); void VerifyMarking(PagedSpace* paged_space); void VerifyMarking(LargeObjectSpace* lo_space); Heap* heap_; }; void MarkingVerifier::VerifyRoots(VisitMode mode) { heap_->IterateStrongRoots(this, mode); } void MarkingVerifier::VerifyMarkingOnPage(const Page* page, Address start, Address end) { HeapObject object; Address next_object_must_be_here_or_later = start; for (Address current = start; current < end;) { object = HeapObject::FromAddress(current); // One word fillers at the end of a black area can be grey. if (IsBlackOrGrey(object) && object.map() != ReadOnlyRoots(heap_).one_pointer_filler_map()) { CHECK(IsMarked(object)); CHECK(current >= next_object_must_be_here_or_later); object.Iterate(this); next_object_must_be_here_or_later = current + object.Size(); // The object is either part of a black area of black allocation or a // regular black object CHECK( bitmap(page)->AllBitsSetInRange( page->AddressToMarkbitIndex(current), page->AddressToMarkbitIndex(next_object_must_be_here_or_later)) || bitmap(page)->AllBitsClearInRange( page->AddressToMarkbitIndex(current + kTaggedSize * 2), page->AddressToMarkbitIndex(next_object_must_be_here_or_later))); current = next_object_must_be_here_or_later; } else { current += kTaggedSize; } } } void MarkingVerifier::VerifyMarking(NewSpace* space) { Address end = space->top(); // The bottom position is at the start of its page. Allows us to use // page->area_start() as start of range on all pages. CHECK_EQ(space->first_allocatable_address(), space->first_page()->area_start()); PageRange range(space->first_allocatable_address(), end); for (auto it = range.begin(); it != range.end();) { Page* page = *(it++); Address limit = it != range.end() ? page->area_end() : end; CHECK(limit == end || !page->Contains(end)); VerifyMarkingOnPage(page, page->area_start(), limit); } } void MarkingVerifier::VerifyMarking(PagedSpace* space) { for (Page* p : *space) { VerifyMarkingOnPage(p, p->area_start(), p->area_end()); } } void MarkingVerifier::VerifyMarking(LargeObjectSpace* lo_space) { LargeObjectSpaceObjectIterator it(lo_space); for (HeapObject obj = it.Next(); !obj.is_null(); obj = it.Next()) { if (IsBlackOrGrey(obj)) { obj.Iterate(this); } } } class FullMarkingVerifier : public MarkingVerifier { public: explicit FullMarkingVerifier(Heap* heap) : MarkingVerifier(heap), marking_state_( heap->mark_compact_collector()->non_atomic_marking_state()) {} void Run() override { VerifyRoots(VISIT_ONLY_STRONG); VerifyMarking(heap_->new_space()); VerifyMarking(heap_->new_lo_space()); VerifyMarking(heap_->old_space()); VerifyMarking(heap_->code_space()); VerifyMarking(heap_->map_space()); VerifyMarking(heap_->lo_space()); VerifyMarking(heap_->code_lo_space()); } protected: ConcurrentBitmap<AccessMode::NON_ATOMIC>* bitmap( const MemoryChunk* chunk) override { return marking_state_->bitmap(chunk); } bool IsMarked(HeapObject object) override { return marking_state_->IsBlack(object); } bool IsBlackOrGrey(HeapObject object) override { return marking_state_->IsBlackOrGrey(object); } void VerifyPointers(ObjectSlot start, ObjectSlot end) override { VerifyPointersImpl(start, end); } void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointersImpl(start, end); } void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) override { VerifyPointersImpl(start, end); } void VisitCodeTarget(Code host, RelocInfo* rinfo) override { Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); VerifyHeapObjectImpl(target); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { DCHECK(RelocInfo::IsEmbeddedObjectMode(rinfo->rmode())); if (!host.IsWeakObject(rinfo->target_object())) { HeapObject object = rinfo->target_object(); VerifyHeapObjectImpl(object); } } private: V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object) { CHECK(marking_state_->IsBlackOrGrey(heap_object)); } template <typename TSlot> V8_INLINE void VerifyPointersImpl(TSlot start, TSlot end) { for (TSlot slot = start; slot < end; ++slot) { typename TSlot::TObject object = *slot; HeapObject heap_object; if (object.GetHeapObjectIfStrong(&heap_object)) { VerifyHeapObjectImpl(heap_object); } } } MarkCompactCollector::NonAtomicMarkingState* marking_state_; }; class EvacuationVerifier : public ObjectVisitor, public RootVisitor { public: virtual void Run() = 0; void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) override { VerifyPointers(start, end); } void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointers(start, end); } void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override { VerifyRootPointers(start, end); } protected: explicit EvacuationVerifier(Heap* heap) : heap_(heap) {} inline Heap* heap() { return heap_; } virtual void VerifyPointers(ObjectSlot start, ObjectSlot end) = 0; virtual void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) = 0; virtual void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) = 0; void VerifyRoots(VisitMode mode); void VerifyEvacuationOnPage(Address start, Address end); void VerifyEvacuation(NewSpace* new_space); void VerifyEvacuation(PagedSpace* paged_space); Heap* heap_; }; void EvacuationVerifier::VerifyRoots(VisitMode mode) { heap_->IterateStrongRoots(this, mode); } void EvacuationVerifier::VerifyEvacuationOnPage(Address start, Address end) { Address current = start; while (current < end) { HeapObject object = HeapObject::FromAddress(current); if (!object.IsFiller()) object.Iterate(this); current += object.Size(); } } void EvacuationVerifier::VerifyEvacuation(NewSpace* space) { PageRange range(space->first_allocatable_address(), space->top()); for (auto it = range.begin(); it != range.end();) { Page* page = *(it++); Address current = page->area_start(); Address limit = it != range.end() ? page->area_end() : space->top(); CHECK(limit == space->top() || !page->Contains(space->top())); VerifyEvacuationOnPage(current, limit); } } void EvacuationVerifier::VerifyEvacuation(PagedSpace* space) { for (Page* p : *space) { if (p->IsEvacuationCandidate()) continue; if (p->Contains(space->top())) { CodePageMemoryModificationScope memory_modification_scope(p); heap_->CreateFillerObjectAt( space->top(), static_cast<int>(space->limit() - space->top()), ClearRecordedSlots::kNo); } VerifyEvacuationOnPage(p->area_start(), p->area_end()); } } class FullEvacuationVerifier : public EvacuationVerifier { public: explicit FullEvacuationVerifier(Heap* heap) : EvacuationVerifier(heap) {} void Run() override { VerifyRoots(VISIT_ALL); VerifyEvacuation(heap_->new_space()); VerifyEvacuation(heap_->old_space()); VerifyEvacuation(heap_->code_space()); VerifyEvacuation(heap_->map_space()); } protected: V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object) { CHECK_IMPLIES(Heap::InYoungGeneration(heap_object), Heap::InToPage(heap_object)); CHECK(!MarkCompactCollector::IsOnEvacuationCandidate(heap_object)); } template <typename TSlot> void VerifyPointersImpl(TSlot start, TSlot end) { for (TSlot current = start; current < end; ++current) { typename TSlot::TObject object = *current; HeapObject heap_object; if (object.GetHeapObjectIfStrong(&heap_object)) { VerifyHeapObjectImpl(heap_object); } } } void VerifyPointers(ObjectSlot start, ObjectSlot end) override { VerifyPointersImpl(start, end); } void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointersImpl(start, end); } void VisitCodeTarget(Code host, RelocInfo* rinfo) override { Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); VerifyHeapObjectImpl(target); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { VerifyHeapObjectImpl(rinfo->target_object()); } void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) override { VerifyPointersImpl(start, end); } }; } // namespace #endif // VERIFY_HEAP // ============================================================================= // MarkCompactCollectorBase, MinorMarkCompactCollector, MarkCompactCollector // ============================================================================= using MarkCompactMarkingVisitor = MarkingVisitor<FixedArrayVisitationMode::kRegular, TraceRetainingPathMode::kEnabled, MarkCompactCollector::MarkingState>; namespace { int NumberOfAvailableCores() { static int num_cores = V8::GetCurrentPlatform()->NumberOfWorkerThreads() + 1; // This number of cores should be greater than zero and never change. DCHECK_GE(num_cores, 1); DCHECK_EQ(num_cores, V8::GetCurrentPlatform()->NumberOfWorkerThreads() + 1); return num_cores; } } // namespace int MarkCompactCollectorBase::NumberOfParallelCompactionTasks(int pages) { DCHECK_GT(pages, 0); int tasks = FLAG_parallel_compaction ? Min(NumberOfAvailableCores(), pages) : 1; if (!heap_->CanExpandOldGeneration( static_cast<size_t>(tasks * Page::kPageSize))) { // Optimize for memory usage near the heap limit. tasks = 1; } return tasks; } int MarkCompactCollectorBase::NumberOfParallelPointerUpdateTasks(int pages, int slots) { DCHECK_GT(pages, 0); // Limit the number of update tasks as task creation often dominates the // actual work that is being done. const int kMaxPointerUpdateTasks = 8; const int kSlotsPerTask = 600; const int wanted_tasks = (slots >= 0) ? Max(1, Min(pages, slots / kSlotsPerTask)) : pages; return FLAG_parallel_pointer_update ? Min(kMaxPointerUpdateTasks, Min(NumberOfAvailableCores(), wanted_tasks)) : 1; } int MarkCompactCollectorBase::NumberOfParallelToSpacePointerUpdateTasks( int pages) { DCHECK_GT(pages, 0); // No cap needed because all pages we need to process are fully filled with // interesting objects. return FLAG_parallel_pointer_update ? Min(NumberOfAvailableCores(), pages) : 1; } MarkCompactCollector::MarkCompactCollector(Heap* heap) : MarkCompactCollectorBase(heap), page_parallel_job_semaphore_(0), #ifdef DEBUG state_(IDLE), #endif was_marked_incrementally_(false), evacuation_(false), compacting_(false), black_allocation_(false), have_code_to_deoptimize_(false), marking_worklist_(heap), sweeper_(new Sweeper(heap, non_atomic_marking_state())) { old_to_new_slots_ = -1; } MarkCompactCollector::~MarkCompactCollector() { delete sweeper_; } void MarkCompactCollector::SetUp() { DCHECK_EQ(0, strcmp(Marking::kWhiteBitPattern, "00")); DCHECK_EQ(0, strcmp(Marking::kBlackBitPattern, "11")); DCHECK_EQ(0, strcmp(Marking::kGreyBitPattern, "10")); DCHECK_EQ(0, strcmp(Marking::kImpossibleBitPattern, "01")); } void MarkCompactCollector::TearDown() { AbortCompaction(); AbortWeakObjects(); if (heap()->incremental_marking()->IsMarking()) { marking_worklist()->Clear(); } } void MarkCompactCollector::AddEvacuationCandidate(Page* p) { DCHECK(!p->NeverEvacuate()); if (FLAG_trace_evacuation_candidates) { PrintIsolate( isolate(), "Evacuation candidate: Free bytes: %6zu. Free Lists length: %4d.\n", p->area_size() - p->allocated_bytes(), p->FreeListsLength()); } p->MarkEvacuationCandidate(); evacuation_candidates_.push_back(p); } static void TraceFragmentation(PagedSpace* space) { int number_of_pages = space->CountTotalPages(); intptr_t reserved = (number_of_pages * space->AreaSize()); intptr_t free = reserved - space->SizeOfObjects(); PrintF("[%s]: %d pages, %d (%.1f%%) free\n", space->name(), number_of_pages, static_cast<int>(free), static_cast<double>(free) * 100 / reserved); } bool MarkCompactCollector::StartCompaction() { if (!compacting_) { DCHECK(evacuation_candidates_.empty()); if (FLAG_gc_experiment_less_compaction && !heap_->ShouldReduceMemory()) return false; CollectEvacuationCandidates(heap()->old_space()); if (FLAG_compact_code_space) { CollectEvacuationCandidates(heap()->code_space()); } else if (FLAG_trace_fragmentation) { TraceFragmentation(heap()->code_space()); } if (FLAG_trace_fragmentation) { TraceFragmentation(heap()->map_space()); } compacting_ = !evacuation_candidates_.empty(); } return compacting_; } void MarkCompactCollector::CollectGarbage() { // Make sure that Prepare() has been called. The individual steps below will // update the state as they proceed. DCHECK(state_ == PREPARE_GC); #ifdef ENABLE_MINOR_MC heap()->minor_mark_compact_collector()->CleanupSweepToIteratePages(); #endif // ENABLE_MINOR_MC MarkLiveObjects(); ClearNonLiveReferences(); VerifyMarking(); RecordObjectStats(); StartSweepSpaces(); Evacuate(); Finish(); } #ifdef VERIFY_HEAP void MarkCompactCollector::VerifyMarkbitsAreDirty(ReadOnlySpace* space) { ReadOnlyHeapObjectIterator iterator(space); for (HeapObject object = iterator.Next(); !object.is_null(); object = iterator.Next()) { CHECK(non_atomic_marking_state()->IsBlack(object)); } } void MarkCompactCollector::VerifyMarkbitsAreClean(PagedSpace* space) { for (Page* p : *space) { CHECK(non_atomic_marking_state()->bitmap(p)->IsClean()); CHECK_EQ(0, non_atomic_marking_state()->live_bytes(p)); } } void MarkCompactCollector::VerifyMarkbitsAreClean(NewSpace* space) { for (Page* p : PageRange(space->first_allocatable_address(), space->top())) { CHECK(non_atomic_marking_state()->bitmap(p)->IsClean()); CHECK_EQ(0, non_atomic_marking_state()->live_bytes(p)); } } void MarkCompactCollector::VerifyMarkbitsAreClean(LargeObjectSpace* space) { LargeObjectSpaceObjectIterator it(space); for (HeapObject obj = it.Next(); !obj.is_null(); obj = it.Next()) { CHECK(non_atomic_marking_state()->IsWhite(obj)); CHECK_EQ(0, non_atomic_marking_state()->live_bytes( MemoryChunk::FromHeapObject(obj))); } } void MarkCompactCollector::VerifyMarkbitsAreClean() { VerifyMarkbitsAreClean(heap_->old_space()); VerifyMarkbitsAreClean(heap_->code_space()); VerifyMarkbitsAreClean(heap_->map_space()); VerifyMarkbitsAreClean(heap_->new_space()); // Read-only space should always be black since we never collect any objects // in it or linked from it. VerifyMarkbitsAreDirty(heap_->read_only_space()); VerifyMarkbitsAreClean(heap_->lo_space()); VerifyMarkbitsAreClean(heap_->code_lo_space()); VerifyMarkbitsAreClean(heap_->new_lo_space()); } #endif // VERIFY_HEAP void MarkCompactCollector::EnsureSweepingCompleted() { if (!sweeper()->sweeping_in_progress()) return; sweeper()->EnsureCompleted(); heap()->old_space()->RefillFreeList(); heap()->code_space()->RefillFreeList(); heap()->map_space()->RefillFreeList(); heap()->map_space()->SortFreeList(); heap()->tracer()->NotifySweepingCompleted(); #ifdef VERIFY_HEAP if (FLAG_verify_heap && !evacuation()) { FullEvacuationVerifier verifier(heap()); verifier.Run(); } #endif } void MarkCompactCollector::ComputeEvacuationHeuristics( size_t area_size, int* target_fragmentation_percent, size_t* max_evacuated_bytes) { // For memory reducing and optimize for memory mode we directly define both // constants. const int kTargetFragmentationPercentForReduceMemory = 20; const size_t kMaxEvacuatedBytesForReduceMemory = 12 * MB; const int kTargetFragmentationPercentForOptimizeMemory = 20; const size_t kMaxEvacuatedBytesForOptimizeMemory = 6 * MB; // For regular mode (which is latency critical) we define less aggressive // defaults to start and switch to a trace-based (using compaction speed) // approach as soon as we have enough samples. const int kTargetFragmentationPercent = 70; const size_t kMaxEvacuatedBytes = 4 * MB; // Time to take for a single area (=payload of page). Used as soon as there // exist enough compaction speed samples. const float kTargetMsPerArea = .5; if (heap()->ShouldReduceMemory()) { *target_fragmentation_percent = kTargetFragmentationPercentForReduceMemory; *max_evacuated_bytes = kMaxEvacuatedBytesForReduceMemory; } else if (heap()->ShouldOptimizeForMemoryUsage()) { *target_fragmentation_percent = kTargetFragmentationPercentForOptimizeMemory; *max_evacuated_bytes = kMaxEvacuatedBytesForOptimizeMemory; } else { const double estimated_compaction_speed = heap()->tracer()->CompactionSpeedInBytesPerMillisecond(); if (estimated_compaction_speed != 0) { // Estimate the target fragmentation based on traced compaction speed // and a goal for a single page. const double estimated_ms_per_area = 1 + area_size / estimated_compaction_speed; *target_fragmentation_percent = static_cast<int>( 100 - 100 * kTargetMsPerArea / estimated_ms_per_area); if (*target_fragmentation_percent < kTargetFragmentationPercentForReduceMemory) { *target_fragmentation_percent = kTargetFragmentationPercentForReduceMemory; } } else { *target_fragmentation_percent = kTargetFragmentationPercent; } *max_evacuated_bytes = kMaxEvacuatedBytes; } } void MarkCompactCollector::CollectEvacuationCandidates(PagedSpace* space) { DCHECK(space->identity() == OLD_SPACE || space->identity() == CODE_SPACE); int number_of_pages = space->CountTotalPages(); size_t area_size = space->AreaSize(); const bool in_standard_path = !(FLAG_manual_evacuation_candidates_selection || FLAG_stress_compaction_random || FLAG_stress_compaction || FLAG_always_compact); // Those variables will only be initialized if |in_standard_path|, and are not // used otherwise. size_t max_evacuated_bytes; int target_fragmentation_percent; size_t free_bytes_threshold; if (in_standard_path) { // We use two conditions to decide whether a page qualifies as an evacuation // candidate, or not: // * Target fragmentation: How fragmented is a page, i.e., how is the ratio // between live bytes and capacity of this page (= area). // * Evacuation quota: A global quota determining how much bytes should be // compacted. ComputeEvacuationHeuristics(area_size, &target_fragmentation_percent, &max_evacuated_bytes); free_bytes_threshold = target_fragmentation_percent * (area_size / 100); } // Pairs of (live_bytes_in_page, page). using LiveBytesPagePair = std::pair<size_t, Page*>; std::vector<LiveBytesPagePair> pages; pages.reserve(number_of_pages); DCHECK(!sweeping_in_progress()); Page* owner_of_linear_allocation_area = space->top() == space->limit() ? nullptr : Page::FromAllocationAreaAddress(space->top()); for (Page* p : *space) { if (p->NeverEvacuate() || (p == owner_of_linear_allocation_area) || !p->CanAllocate()) continue; // Invariant: Evacuation candidates are just created when marking is // started. This means that sweeping has finished. Furthermore, at the end // of a GC all evacuation candidates are cleared and their slot buffers are // released. CHECK(!p->IsEvacuationCandidate()); CHECK_NULL(p->slot_set<OLD_TO_OLD>()); CHECK_NULL(p->typed_slot_set<OLD_TO_OLD>()); CHECK(p->SweepingDone()); DCHECK(p->area_size() == area_size); if (in_standard_path) { // Only the pages with at more than |free_bytes_threshold| free bytes are // considered for evacuation. if (area_size - p->allocated_bytes() >= free_bytes_threshold) { pages.push_back(std::make_pair(p->allocated_bytes(), p)); } } else { pages.push_back(std::make_pair(p->allocated_bytes(), p)); } } int candidate_count = 0; size_t total_live_bytes = 0; const bool reduce_memory = heap()->ShouldReduceMemory(); if (FLAG_manual_evacuation_candidates_selection) { for (size_t i = 0; i < pages.size(); i++) { Page* p = pages[i].second; if (p->IsFlagSet(MemoryChunk::FORCE_EVACUATION_CANDIDATE_FOR_TESTING)) { candidate_count++; total_live_bytes += pages[i].first; p->ClearFlag(MemoryChunk::FORCE_EVACUATION_CANDIDATE_FOR_TESTING); AddEvacuationCandidate(p); } } } else if (FLAG_stress_compaction_random) { double fraction = isolate()->fuzzer_rng()->NextDouble(); size_t pages_to_mark_count = static_cast<size_t>(fraction * (pages.size() + 1)); for (uint64_t i : isolate()->fuzzer_rng()->NextSample( pages.size(), pages_to_mark_count)) { candidate_count++; total_live_bytes += pages[i].first; AddEvacuationCandidate(pages[i].second); } } else if (FLAG_stress_compaction) { for (size_t i = 0; i < pages.size(); i++) { Page* p = pages[i].second; if (i % 2 == 0) { candidate_count++; total_live_bytes += pages[i].first; AddEvacuationCandidate(p); } } } else { // The following approach determines the pages that should be evacuated. // // Sort pages from the most free to the least free, then select // the first n pages for evacuation such that: // - the total size of evacuated objects does not exceed the specified // limit. // - fragmentation of (n+1)-th page does not exceed the specified limit. std::sort(pages.begin(), pages.end(), [](const LiveBytesPagePair& a, const LiveBytesPagePair& b) { return a.first < b.first; }); for (size_t i = 0; i < pages.size(); i++) { size_t live_bytes = pages[i].first; DCHECK_GE(area_size, live_bytes); if (FLAG_always_compact || ((total_live_bytes + live_bytes) <= max_evacuated_bytes)) { candidate_count++; total_live_bytes += live_bytes; } if (FLAG_trace_fragmentation_verbose) { PrintIsolate(isolate(), "compaction-selection-page: space=%s free_bytes_page=%zu " "fragmentation_limit_kb=%zu " "fragmentation_limit_percent=%d sum_compaction_kb=%zu " "compaction_limit_kb=%zu\n", space->name(), (area_size - live_bytes) / KB, free_bytes_threshold / KB, target_fragmentation_percent, total_live_bytes / KB, max_evacuated_bytes / KB); } } // How many pages we will allocated for the evacuated objects // in the worst case: ceil(total_live_bytes / area_size) int estimated_new_pages = static_cast<int>((total_live_bytes + area_size - 1) / area_size); DCHECK_LE(estimated_new_pages, candidate_count); int estimated_released_pages = candidate_count - estimated_new_pages; // Avoid (compact -> expand) cycles. if ((estimated_released_pages == 0) && !FLAG_always_compact) { candidate_count = 0; } for (int i = 0; i < candidate_count; i++) { AddEvacuationCandidate(pages[i].second); } } if (FLAG_trace_fragmentation) { PrintIsolate(isolate(), "compaction-selection: space=%s reduce_memory=%d pages=%d " "total_live_bytes=%zu\n", space->name(), reduce_memory, candidate_count, total_live_bytes / KB); } } void MarkCompactCollector::AbortCompaction() { if (compacting_) { RememberedSet<OLD_TO_OLD>::ClearAll(heap()); for (Page* p : evacuation_candidates_) { p->ClearEvacuationCandidate(); } compacting_ = false; evacuation_candidates_.clear(); } DCHECK(evacuation_candidates_.empty()); } void MarkCompactCollector::Prepare() { was_marked_incrementally_ = heap()->incremental_marking()->IsMarking(); #ifdef DEBUG DCHECK(state_ == IDLE); state_ = PREPARE_GC; #endif DCHECK(!FLAG_never_compact || !FLAG_always_compact); // Instead of waiting we could also abort the sweeper threads here. EnsureSweepingCompleted(); if (heap()->incremental_marking()->IsSweeping()) { heap()->incremental_marking()->Stop(); } if (!was_marked_incrementally_) { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_EMBEDDER_PROLOGUE); heap_->local_embedder_heap_tracer()->TracePrologue( heap_->flags_for_embedder_tracer()); } // Don't start compaction if we are in the middle of incremental // marking cycle. We did not collect any slots. if (!FLAG_never_compact && !was_marked_incrementally_) { StartCompaction(); } PagedSpaceIterator spaces(heap()); for (PagedSpace* space = spaces.Next(); space != nullptr; space = spaces.Next()) { space->PrepareForMarkCompact(); } heap()->account_external_memory_concurrently_freed(); #ifdef VERIFY_HEAP if (!was_marked_incrementally_ && FLAG_verify_heap) { VerifyMarkbitsAreClean(); } #endif } void MarkCompactCollector::FinishConcurrentMarking( ConcurrentMarking::StopRequest stop_request) { // FinishConcurrentMarking is called for both, concurrent and parallel, // marking. It is safe to call this function when tasks are already finished. if (FLAG_parallel_marking || FLAG_concurrent_marking) { heap()->concurrent_marking()->Stop(stop_request); heap()->concurrent_marking()->FlushMemoryChunkData( non_atomic_marking_state()); } } void MarkCompactCollector::VerifyMarking() { CHECK(marking_worklist()->IsEmpty()); DCHECK(heap_->incremental_marking()->IsStopped()); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { FullMarkingVerifier verifier(heap()); verifier.Run(); } #endif #ifdef VERIFY_HEAP if (FLAG_verify_heap) { heap()->old_space()->VerifyLiveBytes(); heap()->map_space()->VerifyLiveBytes(); heap()->code_space()->VerifyLiveBytes(); } #endif } void MarkCompactCollector::Finish() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_FINISH); #ifdef DEBUG heap()->VerifyCountersBeforeConcurrentSweeping(); #endif CHECK(weak_objects_.current_ephemerons.IsEmpty()); CHECK(weak_objects_.discovered_ephemerons.IsEmpty()); weak_objects_.next_ephemerons.Clear(); sweeper()->StartSweeperTasks(); sweeper()->StartIterabilityTasks(); // Clear the marking state of live large objects. heap_->lo_space()->ClearMarkingStateOfLiveObjects(); heap_->code_lo_space()->ClearMarkingStateOfLiveObjects(); #ifdef DEBUG DCHECK(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS); state_ = IDLE; #endif heap_->isolate()->inner_pointer_to_code_cache()->Flush(); // The stub caches are not traversed during GC; clear them to force // their lazy re-initialization. This must be done after the // GC, because it relies on the new address of certain old space // objects (empty string, illegal builtin). isolate()->load_stub_cache()->Clear(); isolate()->store_stub_cache()->Clear(); if (have_code_to_deoptimize_) { // Some code objects were marked for deoptimization during the GC. Deoptimizer::DeoptimizeMarkedCode(isolate()); have_code_to_deoptimize_ = false; } } class MarkCompactCollector::RootMarkingVisitor final : public RootVisitor { public: explicit RootMarkingVisitor(MarkCompactCollector* collector) : collector_(collector) {} void VisitRootPointer(Root root, const char* description, FullObjectSlot p) final { MarkObjectByPointer(root, p); } void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) final { for (FullObjectSlot p = start; p < end; ++p) MarkObjectByPointer(root, p); } private: V8_INLINE void MarkObjectByPointer(Root root, FullObjectSlot p) { if (!(*p).IsHeapObject()) return; collector_->MarkRootObject(root, HeapObject::cast(*p)); } MarkCompactCollector* const collector_; }; // This visitor is used to visit the body of special objects held alive by // other roots. // // It is currently used for // - Code held alive by the top optimized frame. This code cannot be deoptimized // and thus have to be kept alive in an isolate way, i.e., it should not keep // alive other code objects reachable through the weak list but they should // keep alive its embedded pointers (which would otherwise be dropped). // - Prefix of the string table. class MarkCompactCollector::CustomRootBodyMarkingVisitor final : public ObjectVisitor { public: explicit CustomRootBodyMarkingVisitor(MarkCompactCollector* collector) : collector_(collector) {} void VisitPointer(HeapObject host, ObjectSlot p) final { MarkObject(host, *p); } void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) final { for (ObjectSlot p = start; p < end; ++p) { DCHECK(!HasWeakHeapObjectTag(*p)); MarkObject(host, *p); } } void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final { // At the moment, custom roots cannot contain weak pointers. UNREACHABLE(); } // VisitEmbedderPointer is defined by ObjectVisitor to call VisitPointers. void VisitCodeTarget(Code host, RelocInfo* rinfo) override { Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); MarkObject(host, target); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { MarkObject(host, rinfo->target_object()); } private: V8_INLINE void MarkObject(HeapObject host, Object object) { if (!object.IsHeapObject()) return; collector_->MarkObject(host, HeapObject::cast(object)); } MarkCompactCollector* const collector_; }; class InternalizedStringTableCleaner : public ObjectVisitor { public: InternalizedStringTableCleaner(Heap* heap, HeapObject table) : heap_(heap), pointers_removed_(0), table_(table) {} void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) override { // Visit all HeapObject pointers in [start, end). Object the_hole = ReadOnlyRoots(heap_).the_hole_value(); MarkCompactCollector::NonAtomicMarkingState* marking_state = heap_->mark_compact_collector()->non_atomic_marking_state(); for (ObjectSlot p = start; p < end; ++p) { Object o = *p; if (o.IsHeapObject()) { HeapObject heap_object = HeapObject::cast(o); if (marking_state->IsWhite(heap_object)) { pointers_removed_++; // Set the entry to the_hole_value (as deleted). p.store(the_hole); } else { // StringTable contains only old space strings. DCHECK(!Heap::InYoungGeneration(o)); MarkCompactCollector::RecordSlot(table_, p, heap_object); } } } } void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final { UNREACHABLE(); } void VisitCodeTarget(Code host, RelocInfo* rinfo) final { UNREACHABLE(); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) final { UNREACHABLE(); } int PointersRemoved() { return pointers_removed_; } private: Heap* heap_; int pointers_removed_; HeapObject table_; }; class ExternalStringTableCleaner : public RootVisitor { public: explicit ExternalStringTableCleaner(Heap* heap) : heap_(heap) {} void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override { // Visit all HeapObject pointers in [start, end). MarkCompactCollector::NonAtomicMarkingState* marking_state = heap_->mark_compact_collector()->non_atomic_marking_state(); Object the_hole = ReadOnlyRoots(heap_).the_hole_value(); for (FullObjectSlot p = start; p < end; ++p) { Object o = *p; if (o.IsHeapObject()) { HeapObject heap_object = HeapObject::cast(o); if (marking_state->IsWhite(heap_object)) { if (o.IsExternalString()) { heap_->FinalizeExternalString(String::cast(o)); } else { // The original external string may have been internalized. DCHECK(o.IsThinString()); } // Set the entry to the_hole_value (as deleted). p.store(the_hole); } } } } private: Heap* heap_; }; // Implementation of WeakObjectRetainer for mark compact GCs. All marked objects // are retained. class MarkCompactWeakObjectRetainer : public WeakObjectRetainer { public: explicit MarkCompactWeakObjectRetainer( MarkCompactCollector::NonAtomicMarkingState* marking_state) : marking_state_(marking_state) {} Object RetainAs(Object object) override { HeapObject heap_object = HeapObject::cast(object); DCHECK(!marking_state_->IsGrey(heap_object)); if (marking_state_->IsBlack(heap_object)) { return object; } else if (object.IsAllocationSite() && !(AllocationSite::cast(object).IsZombie())) { // "dead" AllocationSites need to live long enough for a traversal of new // space. These sites get a one-time reprieve. Object nested = object; while (nested.IsAllocationSite()) { AllocationSite current_site = AllocationSite::cast(nested); // MarkZombie will override the nested_site, read it first before // marking nested = current_site.nested_site(); current_site.MarkZombie(); marking_state_->WhiteToBlack(current_site); } return object; } else { return Object(); } } private: MarkCompactCollector::NonAtomicMarkingState* marking_state_; }; class RecordMigratedSlotVisitor : public ObjectVisitor { public: explicit RecordMigratedSlotVisitor( MarkCompactCollector* collector, EphemeronRememberedSet* ephemeron_remembered_set) : collector_(collector), ephemeron_remembered_set_(ephemeron_remembered_set) {} inline void VisitPointer(HeapObject host, ObjectSlot p) final { DCHECK(!HasWeakHeapObjectTag(*p)); RecordMigratedSlot(host, MaybeObject::FromObject(*p), p.address()); } inline void VisitPointer(HeapObject host, MaybeObjectSlot p) final { RecordMigratedSlot(host, *p, p.address()); } inline void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) final { while (start < end) { VisitPointer(host, start); ++start; } } inline void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final { while (start < end) { VisitPointer(host, start); ++start; } } inline void VisitEphemeron(HeapObject host, int index, ObjectSlot key, ObjectSlot value) override { DCHECK(host.IsEphemeronHashTable()); DCHECK(!Heap::InYoungGeneration(host)); VisitPointer(host, value); if (ephemeron_remembered_set_ && Heap::InYoungGeneration(*key)) { auto table = EphemeronHashTable::unchecked_cast(host); auto insert_result = ephemeron_remembered_set_->insert({table, std::unordered_set<int>()}); insert_result.first->second.insert(index); } else { VisitPointer(host, key); } } inline void VisitCodeTarget(Code host, RelocInfo* rinfo) override { DCHECK_EQ(host, rinfo->host()); DCHECK(RelocInfo::IsCodeTargetMode(rinfo->rmode())); Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); // The target is always in old space, we don't have to record the slot in // the old-to-new remembered set. DCHECK(!Heap::InYoungGeneration(target)); collector_->RecordRelocSlot(host, rinfo, target); } inline void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { DCHECK_EQ(host, rinfo->host()); DCHECK(RelocInfo::IsEmbeddedObjectMode(rinfo->rmode())); HeapObject object = HeapObject::cast(rinfo->target_object()); GenerationalBarrierForCode(host, rinfo, object); collector_->RecordRelocSlot(host, rinfo, object); } // Entries that are skipped for recording. inline void VisitExternalReference(Code host, RelocInfo* rinfo) final {} inline void VisitExternalReference(Foreign host, Address* p) final {} inline void VisitRuntimeEntry(Code host, RelocInfo* rinfo) final {} inline void VisitInternalReference(Code host, RelocInfo* rinfo) final {} protected: inline virtual void RecordMigratedSlot(HeapObject host, MaybeObject value, Address slot) { if (value->IsStrongOrWeak()) { MemoryChunk* p = MemoryChunk::FromAddress(value.ptr()); if (p->InYoungGeneration()) { DCHECK_IMPLIES( p->IsToPage(), p->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION) || p->IsLargePage()); RememberedSet<OLD_TO_NEW>::Insert<AccessMode::NON_ATOMIC>( MemoryChunk::FromHeapObject(host), slot); } else if (p->IsEvacuationCandidate()) { RememberedSet<OLD_TO_OLD>::Insert<AccessMode::NON_ATOMIC>( MemoryChunk::FromHeapObject(host), slot); } } } MarkCompactCollector* collector_; EphemeronRememberedSet* ephemeron_remembered_set_; }; class MigrationObserver { public: explicit MigrationObserver(Heap* heap) : heap_(heap) {} virtual ~MigrationObserver() = default; virtual void Move(AllocationSpace dest, HeapObject src, HeapObject dst, int size) = 0; protected: Heap* heap_; }; class ProfilingMigrationObserver final : public MigrationObserver { public: explicit ProfilingMigrationObserver(Heap* heap) : MigrationObserver(heap) {} inline void Move(AllocationSpace dest, HeapObject src, HeapObject dst, int size) final { if (dest == CODE_SPACE || (dest == OLD_SPACE && dst.IsBytecodeArray())) { PROFILE(heap_->isolate(), CodeMoveEvent(AbstractCode::cast(src), AbstractCode::cast(dst))); } heap_->OnMoveEvent(dst, src, size); } }; class HeapObjectVisitor { public: virtual ~HeapObjectVisitor() = default; virtual bool Visit(HeapObject object, int size) = 0; }; class EvacuateVisitorBase : public HeapObjectVisitor { public: void AddObserver(MigrationObserver* observer) { migration_function_ = RawMigrateObject<MigrationMode::kObserved>; observers_.push_back(observer); } protected: enum MigrationMode { kFast, kObserved }; using MigrateFunction = void (*)(EvacuateVisitorBase* base, HeapObject dst, HeapObject src, int size, AllocationSpace dest); template <MigrationMode mode> static void RawMigrateObject(EvacuateVisitorBase* base, HeapObject dst, HeapObject src, int size, AllocationSpace dest) { Address dst_addr = dst.address(); Address src_addr = src.address(); DCHECK(base->heap_->AllowedToBeMigrated(src.map(), src, dest)); DCHECK_NE(dest, LO_SPACE); DCHECK_NE(dest, CODE_LO_SPACE); if (dest == OLD_SPACE) { DCHECK_OBJECT_SIZE(size); DCHECK(IsAligned(size, kTaggedSize)); base->heap_->CopyBlock(dst_addr, src_addr, size); if (mode != MigrationMode::kFast) base->ExecuteMigrationObservers(dest, src, dst, size); dst.IterateBodyFast(dst.map(), size, base->record_visitor_); } else if (dest == CODE_SPACE) { DCHECK_CODEOBJECT_SIZE(size, base->heap_->code_space()); base->heap_->CopyBlock(dst_addr, src_addr, size); Code::cast(dst).Relocate(dst_addr - src_addr); if (mode != MigrationMode::kFast) base->ExecuteMigrationObservers(dest, src, dst, size); dst.IterateBodyFast(dst.map(), size, base->record_visitor_); } else { DCHECK_OBJECT_SIZE(size); DCHECK(dest == NEW_SPACE); base->heap_->CopyBlock(dst_addr, src_addr, size); if (mode != MigrationMode::kFast) base->ExecuteMigrationObservers(dest, src, dst, size); } src.set_map_word(MapWord::FromForwardingAddress(dst)); } EvacuateVisitorBase(Heap* heap, LocalAllocator* local_allocator, RecordMigratedSlotVisitor* record_visitor) : heap_(heap), local_allocator_(local_allocator), record_visitor_(record_visitor) { migration_function_ = RawMigrateObject<MigrationMode::kFast>; } inline bool TryEvacuateObject(AllocationSpace target_space, HeapObject object, int size, HeapObject* target_object) { #ifdef VERIFY_HEAP if (AbortCompactionForTesting(object)) return false; #endif // VERIFY_HEAP AllocationAlignment alignment = HeapObject::RequiredAlignment(object.map()); AllocationResult allocation = local_allocator_->Allocate( target_space, size, AllocationOrigin::kGC, alignment); if (allocation.To(target_object)) { MigrateObject(*target_object, object, size, target_space); if (target_space == CODE_SPACE) MemoryChunk::FromHeapObject(*target_object) ->GetCodeObjectRegistry() ->RegisterNewlyAllocatedCodeObject((*target_object).address()); return true; } return false; } inline void ExecuteMigrationObservers(AllocationSpace dest, HeapObject src, HeapObject dst, int size) { for (MigrationObserver* obs : observers_) { obs->Move(dest, src, dst, size); } } inline void MigrateObject(HeapObject dst, HeapObject src, int size, AllocationSpace dest) { migration_function_(this, dst, src, size, dest); } #ifdef VERIFY_HEAP bool AbortCompactionForTesting(HeapObject object) { if (FLAG_stress_compaction) { const uintptr_t mask = static_cast<uintptr_t>(FLAG_random_seed) & kPageAlignmentMask & ~kObjectAlignmentMask; if ((object.ptr() & kPageAlignmentMask) == mask) { Page* page = Page::FromHeapObject(object); if (page->IsFlagSet(Page::COMPACTION_WAS_ABORTED_FOR_TESTING)) { page->ClearFlag(Page::COMPACTION_WAS_ABORTED_FOR_TESTING); } else { page->SetFlag(Page::COMPACTION_WAS_ABORTED_FOR_TESTING); return true; } } } return false; } #endif // VERIFY_HEAP Heap* heap_; LocalAllocator* local_allocator_; RecordMigratedSlotVisitor* record_visitor_; std::vector<MigrationObserver*> observers_; MigrateFunction migration_function_; }; class EvacuateNewSpaceVisitor final : public EvacuateVisitorBase { public: explicit EvacuateNewSpaceVisitor( Heap* heap, LocalAllocator* local_allocator, RecordMigratedSlotVisitor* record_visitor, Heap::PretenuringFeedbackMap* local_pretenuring_feedback) : EvacuateVisitorBase(heap, local_allocator, record_visitor), buffer_(LocalAllocationBuffer::InvalidBuffer()), promoted_size_(0), semispace_copied_size_(0), local_pretenuring_feedback_(local_pretenuring_feedback), is_incremental_marking_(heap->incremental_marking()->IsMarking()) {} inline bool Visit(HeapObject object, int size) override { if (TryEvacuateWithoutCopy(object)) return true; HeapObject target_object; if (heap_->ShouldBePromoted(object.address()) && TryEvacuateObject(OLD_SPACE, object, size, &target_object)) { promoted_size_ += size; return true; } heap_->UpdateAllocationSite(object.map(), object, local_pretenuring_feedback_); HeapObject target; AllocationSpace space = AllocateTargetObject(object, size, &target); MigrateObject(HeapObject::cast(target), object, size, space); semispace_copied_size_ += size; return true; } intptr_t promoted_size() { return promoted_size_; } intptr_t semispace_copied_size() { return semispace_copied_size_; } private: inline bool TryEvacuateWithoutCopy(HeapObject object) { if (is_incremental_marking_) return false; Map map = object.map(); // Some objects can be evacuated without creating a copy. if (map.visitor_id() == kVisitThinString) { HeapObject actual = ThinString::cast(object).unchecked_actual(); if (MarkCompactCollector::IsOnEvacuationCandidate(actual)) return false; object.set_map_word(MapWord::FromForwardingAddress(actual)); return true; } // TODO(mlippautz): Handle ConsString. return false; } inline AllocationSpace AllocateTargetObject(HeapObject old_object, int size, HeapObject* target_object) { AllocationAlignment alignment = HeapObject::RequiredAlignment(old_object.map()); AllocationSpace space_allocated_in = NEW_SPACE; AllocationResult allocation = local_allocator_->Allocate( NEW_SPACE, size, AllocationOrigin::kGC, alignment); if (allocation.IsRetry()) { allocation = AllocateInOldSpace(size, alignment); space_allocated_in = OLD_SPACE; } bool ok = allocation.To(target_object); DCHECK(ok); USE(ok); return space_allocated_in; } inline AllocationResult AllocateInOldSpace(int size_in_bytes, AllocationAlignment alignment) { AllocationResult allocation = local_allocator_->Allocate( OLD_SPACE, size_in_bytes, AllocationOrigin::kGC, alignment); if (allocation.IsRetry()) { heap_->FatalProcessOutOfMemory( "MarkCompactCollector: semi-space copy, fallback in old gen"); } return allocation; } LocalAllocationBuffer buffer_; intptr_t promoted_size_; intptr_t semispace_copied_size_; Heap::PretenuringFeedbackMap* local_pretenuring_feedback_; bool is_incremental_marking_; }; template <PageEvacuationMode mode> class EvacuateNewSpacePageVisitor final : public HeapObjectVisitor { public: explicit EvacuateNewSpacePageVisitor( Heap* heap, RecordMigratedSlotVisitor* record_visitor, Heap::PretenuringFeedbackMap* local_pretenuring_feedback) : heap_(heap), record_visitor_(record_visitor), moved_bytes_(0), local_pretenuring_feedback_(local_pretenuring_feedback) {} static void Move(Page* page) { switch (mode) { case NEW_TO_NEW: page->heap()->new_space()->MovePageFromSpaceToSpace(page); page->SetFlag(Page::PAGE_NEW_NEW_PROMOTION); break; case NEW_TO_OLD: { page->heap()->new_space()->from_space().RemovePage(page); Page* new_page = Page::ConvertNewToOld(page); DCHECK(!new_page->InYoungGeneration()); new_page->SetFlag(Page::PAGE_NEW_OLD_PROMOTION); break; } } } inline bool Visit(HeapObject object, int size) override { if (mode == NEW_TO_NEW) { heap_->UpdateAllocationSite(object.map(), object, local_pretenuring_feedback_); } else if (mode == NEW_TO_OLD) { object.IterateBodyFast(record_visitor_); } return true; } intptr_t moved_bytes() { return moved_bytes_; } void account_moved_bytes(intptr_t bytes) { moved_bytes_ += bytes; } private: Heap* heap_; RecordMigratedSlotVisitor* record_visitor_; intptr_t moved_bytes_; Heap::PretenuringFeedbackMap* local_pretenuring_feedback_; }; class EvacuateOldSpaceVisitor final : public EvacuateVisitorBase { public: EvacuateOldSpaceVisitor(Heap* heap, LocalAllocator* local_allocator, RecordMigratedSlotVisitor* record_visitor) : EvacuateVisitorBase(heap, local_allocator, record_visitor) {} inline bool Visit(HeapObject object, int size) override { HeapObject target_object; if (TryEvacuateObject(Page::FromHeapObject(object)->owner_identity(), object, size, &target_object)) { DCHECK(object.map_word().IsForwardingAddress()); return true; } return false; } }; class EvacuateRecordOnlyVisitor final : public HeapObjectVisitor { public: explicit EvacuateRecordOnlyVisitor(Heap* heap) : heap_(heap) {} inline bool Visit(HeapObject object, int size) override { RecordMigratedSlotVisitor visitor(heap_->mark_compact_collector(), &heap_->ephemeron_remembered_set_); object.IterateBodyFast(&visitor); return true; } private: Heap* heap_; }; bool MarkCompactCollector::IsUnmarkedHeapObject(Heap* heap, FullObjectSlot p) { Object o = *p; if (!o.IsHeapObject()) return false; HeapObject heap_object = HeapObject::cast(o); return heap->mark_compact_collector()->non_atomic_marking_state()->IsWhite( heap_object); } void MarkCompactCollector::MarkStringTable( ObjectVisitor* custom_root_body_visitor) { StringTable string_table = heap()->string_table(); // Mark the string table itself. if (marking_state()->WhiteToBlack(string_table)) { // Explicitly mark the prefix. string_table.IteratePrefix(custom_root_body_visitor); } } void MarkCompactCollector::MarkRoots(RootVisitor* root_visitor, ObjectVisitor* custom_root_body_visitor) { // Mark the heap roots including global variables, stack variables, // etc., and all objects reachable from them. heap()->IterateStrongRoots(root_visitor, VISIT_ONLY_STRONG); // Custom marking for string table and top optimized frame. MarkStringTable(custom_root_body_visitor); ProcessTopOptimizedFrame(custom_root_body_visitor); } void MarkCompactCollector::ProcessEphemeronsUntilFixpoint() { bool work_to_do = true; int iterations = 0; int max_iterations = FLAG_ephemeron_fixpoint_iterations; while (work_to_do) { PerformWrapperTracing(); if (iterations >= max_iterations) { // Give up fixpoint iteration and switch to linear algorithm. ProcessEphemeronsLinear(); break; } // Move ephemerons from next_ephemerons into current_ephemerons to // drain them in this iteration. weak_objects_.current_ephemerons.Swap(weak_objects_.next_ephemerons); heap()->concurrent_marking()->set_ephemeron_marked(false); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON_MARKING); if (FLAG_parallel_marking) { heap_->concurrent_marking()->RescheduleTasksIfNeeded(); } work_to_do = ProcessEphemerons(); FinishConcurrentMarking( ConcurrentMarking::StopRequest::COMPLETE_ONGOING_TASKS); } CHECK(weak_objects_.current_ephemerons.IsEmpty()); CHECK(weak_objects_.discovered_ephemerons.IsEmpty()); work_to_do = work_to_do || !marking_worklist()->IsEmpty() || heap()->concurrent_marking()->ephemeron_marked() || !marking_worklist()->IsEmbedderEmpty() || !heap()->local_embedder_heap_tracer()->IsRemoteTracingDone(); ++iterations; } CHECK(marking_worklist()->IsEmpty()); CHECK(weak_objects_.current_ephemerons.IsEmpty()); CHECK(weak_objects_.discovered_ephemerons.IsEmpty()); } bool MarkCompactCollector::ProcessEphemerons() { Ephemeron ephemeron; bool ephemeron_marked = false; // Drain current_ephemerons and push ephemerons where key and value are still // unreachable into next_ephemerons. while (weak_objects_.current_ephemerons.Pop(kMainThread, &ephemeron)) { if (ProcessEphemeron(ephemeron.key, ephemeron.value)) { ephemeron_marked = true; } } // Drain marking worklist and push discovered ephemerons into // discovered_ephemerons. ProcessMarkingWorklist(); // Drain discovered_ephemerons (filled in the drain MarkingWorklist-phase // before) and push ephemerons where key and value are still unreachable into // next_ephemerons. while (weak_objects_.discovered_ephemerons.Pop(kMainThread, &ephemeron)) { if (ProcessEphemeron(ephemeron.key, ephemeron.value)) { ephemeron_marked = true; } } // Flush local ephemerons for main task to global pool. weak_objects_.ephemeron_hash_tables.FlushToGlobal(kMainThread); weak_objects_.next_ephemerons.FlushToGlobal(kMainThread); return ephemeron_marked; } void MarkCompactCollector::ProcessEphemeronsLinear() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON_LINEAR); CHECK(heap()->concurrent_marking()->IsStopped()); std::unordered_multimap<HeapObject, HeapObject, Object::Hasher> key_to_values; Ephemeron ephemeron; DCHECK(weak_objects_.current_ephemerons.IsEmpty()); weak_objects_.current_ephemerons.Swap(weak_objects_.next_ephemerons); while (weak_objects_.current_ephemerons.Pop(kMainThread, &ephemeron)) { ProcessEphemeron(ephemeron.key, ephemeron.value); if (non_atomic_marking_state()->IsWhite(ephemeron.value)) { key_to_values.insert(std::make_pair(ephemeron.key, ephemeron.value)); } } ephemeron_marking_.newly_discovered_limit = key_to_values.size(); bool work_to_do = true; while (work_to_do) { PerformWrapperTracing(); ResetNewlyDiscovered(); ephemeron_marking_.newly_discovered_limit = key_to_values.size(); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON_MARKING); // Drain marking worklist and push all discovered objects into // newly_discovered. ProcessMarkingWorklistInternal< MarkCompactCollector::MarkingWorklistProcessingMode:: kTrackNewlyDiscoveredObjects>(); } while (weak_objects_.discovered_ephemerons.Pop(kMainThread, &ephemeron)) { ProcessEphemeron(ephemeron.key, ephemeron.value); if (non_atomic_marking_state()->IsWhite(ephemeron.value)) { key_to_values.insert(std::make_pair(ephemeron.key, ephemeron.value)); } } if (ephemeron_marking_.newly_discovered_overflowed) { // If newly_discovered was overflowed just visit all ephemerons in // next_ephemerons. weak_objects_.next_ephemerons.Iterate([&](Ephemeron ephemeron) { if (non_atomic_marking_state()->IsBlackOrGrey(ephemeron.key) && non_atomic_marking_state()->WhiteToGrey(ephemeron.value)) { marking_worklist()->Push(ephemeron.value); } }); } else { // This is the good case: newly_discovered stores all discovered // objects. Now use key_to_values to see if discovered objects keep more // objects alive due to ephemeron semantics. for (HeapObject object : ephemeron_marking_.newly_discovered) { auto range = key_to_values.equal_range(object); for (auto it = range.first; it != range.second; ++it) { HeapObject value = it->second; MarkObject(object, value); } } } // Do NOT drain marking worklist here, otherwise the current checks // for work_to_do are not sufficient for determining if another iteration // is necessary. work_to_do = !marking_worklist()->IsEmpty() || !marking_worklist()->IsEmbedderEmpty() || !heap()->local_embedder_heap_tracer()->IsRemoteTracingDone(); CHECK(weak_objects_.discovered_ephemerons.IsEmpty()); } ResetNewlyDiscovered(); ephemeron_marking_.newly_discovered.shrink_to_fit(); CHECK(marking_worklist()->IsEmpty()); } void MarkCompactCollector::PerformWrapperTracing() { if (heap_->local_embedder_heap_tracer()->InUse()) { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_EMBEDDER_TRACING); { LocalEmbedderHeapTracer::ProcessingScope scope( heap_->local_embedder_heap_tracer()); HeapObject object; while (marking_worklist()->embedder()->Pop(kMainThread, &object)) { scope.TracePossibleWrapper(JSObject::cast(object)); } } heap_->local_embedder_heap_tracer()->Trace( std::numeric_limits<double>::infinity()); } } void MarkCompactCollector::ProcessMarkingWorklist() { ProcessMarkingWorklistInternal< MarkCompactCollector::MarkingWorklistProcessingMode::kDefault>(); } template <MarkCompactCollector::MarkingWorklistProcessingMode mode> void MarkCompactCollector::ProcessMarkingWorklistInternal() { HeapObject object; MarkCompactMarkingVisitor visitor(this, marking_state()); while (!(object = marking_worklist()->Pop()).is_null()) { // Left trimming may result in grey or black filler objects on the marking // worklist. Ignore these objects. if (object.IsFiller()) { // Due to copying mark bits and the fact that grey and black have their // first bit set, one word fillers are always black. DCHECK_IMPLIES( object.map() == ReadOnlyRoots(heap()).one_pointer_filler_map(), marking_state()->IsBlack(object)); // Other fillers may be black or grey depending on the color of the object // that was trimmed. DCHECK_IMPLIES( object.map() != ReadOnlyRoots(heap()).one_pointer_filler_map(), marking_state()->IsBlackOrGrey(object)); continue; } DCHECK(object.IsHeapObject()); DCHECK(heap()->Contains(object)); DCHECK(!(marking_state()->IsWhite(object))); marking_state()->GreyToBlack(object); if (mode == MarkCompactCollector::MarkingWorklistProcessingMode:: kTrackNewlyDiscoveredObjects) { AddNewlyDiscovered(object); } Map map = object.map(); MarkObject(object, map); visitor.Visit(map, object); } } bool MarkCompactCollector::ProcessEphemeron(HeapObject key, HeapObject value) { if (marking_state()->IsBlackOrGrey(key)) { if (marking_state()->WhiteToGrey(value)) { marking_worklist()->Push(value); return true; } } else if (marking_state()->IsWhite(value)) { weak_objects_.next_ephemerons.Push(kMainThread, Ephemeron{key, value}); } return false; } void MarkCompactCollector::ProcessEphemeronMarking() { DCHECK(marking_worklist()->IsEmpty()); // Incremental marking might leave ephemerons in main task's local // buffer, flush it into global pool. weak_objects_.next_ephemerons.FlushToGlobal(kMainThread); ProcessEphemeronsUntilFixpoint(); CHECK(marking_worklist()->IsEmpty()); CHECK(heap()->local_embedder_heap_tracer()->IsRemoteTracingDone()); } void MarkCompactCollector::ProcessTopOptimizedFrame(ObjectVisitor* visitor) { for (StackFrameIterator it(isolate(), isolate()->thread_local_top()); !it.done(); it.Advance()) { if (it.frame()->type() == StackFrame::INTERPRETED) { return; } if (it.frame()->type() == StackFrame::OPTIMIZED) { Code code = it.frame()->LookupCode(); if (!code.CanDeoptAt(it.frame()->pc())) { Code::BodyDescriptor::IterateBody(code.map(), code, visitor); } return; } } } void MarkCompactCollector::RecordObjectStats() { if (V8_UNLIKELY(TracingFlags::is_gc_stats_enabled())) { heap()->CreateObjectStats(); ObjectStatsCollector collector(heap(), heap()->live_object_stats_.get(), heap()->dead_object_stats_.get()); collector.Collect(); if (V8_UNLIKELY(TracingFlags::gc_stats.load(std::memory_order_relaxed) & v8::tracing::TracingCategoryObserver::ENABLED_BY_TRACING)) { std::stringstream live, dead; heap()->live_object_stats_->Dump(live); heap()->dead_object_stats_->Dump(dead); TRACE_EVENT_INSTANT2(TRACE_DISABLED_BY_DEFAULT("v8.gc_stats"), "V8.GC_Objects_Stats", TRACE_EVENT_SCOPE_THREAD, "live", TRACE_STR_COPY(live.str().c_str()), "dead", TRACE_STR_COPY(dead.str().c_str())); } if (FLAG_trace_gc_object_stats) { heap()->live_object_stats_->PrintJSON("live"); heap()->dead_object_stats_->PrintJSON("dead"); } heap()->live_object_stats_->CheckpointObjectStats(); heap()->dead_object_stats_->ClearObjectStats(); } } void MarkCompactCollector::MarkLiveObjects() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK); // The recursive GC marker detects when it is nearing stack overflow, // and switches to a different marking system. JS interrupts interfere // with the C stack limit check. PostponeInterruptsScope postpone(isolate()); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_FINISH_INCREMENTAL); IncrementalMarking* incremental_marking = heap_->incremental_marking(); if (was_marked_incrementally_) { incremental_marking->Finalize(); } else { CHECK(incremental_marking->IsStopped()); } } #ifdef DEBUG DCHECK(state_ == PREPARE_GC); state_ = MARK_LIVE_OBJECTS; #endif heap_->local_embedder_heap_tracer()->EnterFinalPause(); RootMarkingVisitor root_visitor(this); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_ROOTS); CustomRootBodyMarkingVisitor custom_root_body_visitor(this); MarkRoots(&root_visitor, &custom_root_body_visitor); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_MAIN); if (FLAG_parallel_marking) { heap_->concurrent_marking()->RescheduleTasksIfNeeded(); } ProcessMarkingWorklist(); FinishConcurrentMarking( ConcurrentMarking::StopRequest::COMPLETE_ONGOING_TASKS); ProcessMarkingWorklist(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE); DCHECK(marking_worklist()->IsEmpty()); // Mark objects reachable through the embedder heap. This phase is // opportunistic as it may not discover graphs that are only reachable // through ephemerons. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_EMBEDDER_TRACING_CLOSURE); do { // PerformWrapperTracing() also empties the work items collected by // concurrent markers. As a result this call needs to happen at least // once. PerformWrapperTracing(); ProcessMarkingWorklist(); } while (!heap_->local_embedder_heap_tracer()->IsRemoteTracingDone() || !marking_worklist()->IsEmbedderEmpty()); DCHECK(marking_worklist()->IsEmbedderEmpty()); DCHECK(marking_worklist()->IsEmpty()); } // The objects reachable from the roots are marked, yet unreachable objects // are unmarked. Mark objects reachable due to embedder heap tracing or // harmony weak maps. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_EPHEMERON); ProcessEphemeronMarking(); DCHECK(marking_worklist()->IsEmpty()); } // The objects reachable from the roots, weak maps, and embedder heap // tracing are marked. Objects pointed to only by weak global handles cannot // be immediately reclaimed. Instead, we have to mark them as pending and // mark objects reachable from them. // // First we identify nonlive weak handles and mark them as pending // destruction. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_WEAK_HANDLES); heap()->isolate()->global_handles()->IterateWeakRootsIdentifyFinalizers( &IsUnmarkedHeapObject); ProcessMarkingWorklist(); } // Process finalizers, effectively keeping them alive until the next // garbage collection. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_WEAK_ROOTS); heap()->isolate()->global_handles()->IterateWeakRootsForFinalizers( &root_visitor); ProcessMarkingWorklist(); } // Repeat ephemeron processing from the newly marked objects. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_MARK_WEAK_CLOSURE_HARMONY); ProcessEphemeronMarking(); DCHECK(marking_worklist()->IsEmbedderEmpty()); DCHECK(marking_worklist()->IsEmpty()); } { heap()->isolate()->global_handles()->IterateWeakRootsForPhantomHandles( &IsUnmarkedHeapObject); } } if (was_marked_incrementally_) { heap()->incremental_marking()->Deactivate(); } epoch_++; } void MarkCompactCollector::ClearNonLiveReferences() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_STRING_TABLE); // Prune the string table removing all strings only pointed to by the // string table. Cannot use string_table() here because the string // table is marked. StringTable string_table = heap()->string_table(); InternalizedStringTableCleaner internalized_visitor(heap(), string_table); string_table.IterateElements(&internalized_visitor); string_table.ElementsRemoved(internalized_visitor.PointersRemoved()); ExternalStringTableCleaner external_visitor(heap()); heap()->external_string_table_.IterateAll(&external_visitor); heap()->external_string_table_.CleanUpAll(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_FLUSHABLE_BYTECODE); ClearOldBytecodeCandidates(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_FLUSHED_JS_FUNCTIONS); ClearFlushedJsFunctions(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_WEAK_LISTS); // Process the weak references. MarkCompactWeakObjectRetainer mark_compact_object_retainer( non_atomic_marking_state()); heap()->ProcessAllWeakReferences(&mark_compact_object_retainer); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_MAPS); // ClearFullMapTransitions must be called before weak references are // cleared. ClearFullMapTransitions(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_WEAK_REFERENCES); ClearWeakReferences(); ClearWeakCollections(); ClearJSWeakRefs(); } MarkDependentCodeForDeoptimization(); DCHECK(weak_objects_.transition_arrays.IsEmpty()); DCHECK(weak_objects_.weak_references.IsEmpty()); DCHECK(weak_objects_.weak_objects_in_code.IsEmpty()); DCHECK(weak_objects_.js_weak_refs.IsEmpty()); DCHECK(weak_objects_.weak_cells.IsEmpty()); DCHECK(weak_objects_.bytecode_flushing_candidates.IsEmpty()); DCHECK(weak_objects_.flushed_js_functions.IsEmpty()); } void MarkCompactCollector::MarkDependentCodeForDeoptimization() { std::pair<HeapObject, Code> weak_object_in_code; while (weak_objects_.weak_objects_in_code.Pop(kMainThread, &weak_object_in_code)) { HeapObject object = weak_object_in_code.first; Code code = weak_object_in_code.second; if (!non_atomic_marking_state()->IsBlackOrGrey(object) && !code.embedded_objects_cleared()) { if (!code.marked_for_deoptimization()) { code.SetMarkedForDeoptimization("weak objects"); have_code_to_deoptimize_ = true; } code.ClearEmbeddedObjects(heap_); DCHECK(code.embedded_objects_cleared()); } } } void MarkCompactCollector::ClearPotentialSimpleMapTransition(Map dead_target) { DCHECK(non_atomic_marking_state()->IsWhite(dead_target)); Object potential_parent = dead_target.constructor_or_backpointer(); if (potential_parent.IsMap()) { Map parent = Map::cast(potential_parent); DisallowHeapAllocation no_gc_obviously; if (non_atomic_marking_state()->IsBlackOrGrey(parent) && TransitionsAccessor(isolate(), parent, &no_gc_obviously) .HasSimpleTransitionTo(dead_target)) { ClearPotentialSimpleMapTransition(parent, dead_target); } } } void MarkCompactCollector::ClearPotentialSimpleMapTransition(Map map, Map dead_target) { DCHECK(!map.is_prototype_map()); DCHECK(!dead_target.is_prototype_map()); DCHECK_EQ(map.raw_transitions(), HeapObjectReference::Weak(dead_target)); // Take ownership of the descriptor array. int number_of_own_descriptors = map.NumberOfOwnDescriptors(); DescriptorArray descriptors = map.instance_descriptors(); if (descriptors == dead_target.instance_descriptors() && number_of_own_descriptors > 0) { TrimDescriptorArray(map, descriptors); DCHECK(descriptors.number_of_descriptors() == number_of_own_descriptors); } } void MarkCompactCollector::FlushBytecodeFromSFI( SharedFunctionInfo shared_info) { DCHECK(shared_info.HasBytecodeArray()); // Retain objects required for uncompiled data. String inferred_name = shared_info.inferred_name(); int start_position = shared_info.StartPosition(); int end_position = shared_info.EndPosition(); shared_info.DiscardCompiledMetadata( isolate(), [](HeapObject object, ObjectSlot slot, HeapObject target) { RecordSlot(object, slot, target); }); // The size of the bytecode array should always be larger than an // UncompiledData object. STATIC_ASSERT(BytecodeArray::SizeFor(0) >= UncompiledDataWithoutPreparseData::kSize); // Replace bytecode array with an uncompiled data array. HeapObject compiled_data = shared_info.GetBytecodeArray(); Address compiled_data_start = compiled_data.address(); int compiled_data_size = compiled_data.Size(); MemoryChunk* chunk = MemoryChunk::FromAddress(compiled_data_start); // Clear any recorded slots for the compiled data as being invalid. RememberedSet<OLD_TO_NEW>::RemoveRange( chunk, compiled_data_start, compiled_data_start + compiled_data_size, SlotSet::PREFREE_EMPTY_BUCKETS); RememberedSet<OLD_TO_OLD>::RemoveRange( chunk, compiled_data_start, compiled_data_start + compiled_data_size, SlotSet::PREFREE_EMPTY_BUCKETS); // Swap the map, using set_map_after_allocation to avoid verify heap checks // which are not necessary since we are doing this during the GC atomic pause. compiled_data.set_map_after_allocation( ReadOnlyRoots(heap()).uncompiled_data_without_preparse_data_map(), SKIP_WRITE_BARRIER); // Create a filler object for any left over space in the bytecode array. if (!heap()->IsLargeObject(compiled_data)) { heap()->CreateFillerObjectAt( compiled_data.address() + UncompiledDataWithoutPreparseData::kSize, compiled_data_size - UncompiledDataWithoutPreparseData::kSize, ClearRecordedSlots::kNo); } // Initialize the uncompiled data. UncompiledData uncompiled_data = UncompiledData::cast(compiled_data); UncompiledData::Initialize( uncompiled_data, inferred_name, start_position, end_position, [](HeapObject object, ObjectSlot slot, HeapObject target) { RecordSlot(object, slot, target); }); // Mark the uncompiled data as black, and ensure all fields have already been // marked. DCHECK(non_atomic_marking_state()->IsBlackOrGrey(inferred_name)); non_atomic_marking_state()->WhiteToBlack(uncompiled_data); // Use the raw function data setter to avoid validity checks, since we're // performing the unusual task of decompiling. shared_info.set_function_data(uncompiled_data); DCHECK(!shared_info.is_compiled()); } void MarkCompactCollector::ClearOldBytecodeCandidates() { DCHECK(FLAG_flush_bytecode || weak_objects_.bytecode_flushing_candidates.IsEmpty()); SharedFunctionInfo flushing_candidate; while (weak_objects_.bytecode_flushing_candidates.Pop(kMainThread, &flushing_candidate)) { // If the BytecodeArray is dead, flush it, which will replace the field with // an uncompiled data object. if (!non_atomic_marking_state()->IsBlackOrGrey( flushing_candidate.GetBytecodeArray())) { FlushBytecodeFromSFI(flushing_candidate); } // Now record the slot, which has either been updated to an uncompiled data, // or is the BytecodeArray which is still alive. ObjectSlot slot = flushing_candidate.RawField(SharedFunctionInfo::kFunctionDataOffset); RecordSlot(flushing_candidate, slot, HeapObject::cast(*slot)); } } void MarkCompactCollector::ClearFlushedJsFunctions() { DCHECK(FLAG_flush_bytecode || weak_objects_.flushed_js_functions.IsEmpty()); JSFunction flushed_js_function; while (weak_objects_.flushed_js_functions.Pop(kMainThread, &flushed_js_function)) { flushed_js_function.ResetIfBytecodeFlushed(); } } void MarkCompactCollector::ClearFullMapTransitions() { TransitionArray array; while (weak_objects_.transition_arrays.Pop(kMainThread, &array)) { int num_transitions = array.number_of_entries(); if (num_transitions > 0) { Map map; // The array might contain "undefined" elements because it's not yet // filled. Allow it. if (array.GetTargetIfExists(0, isolate(), &map)) { DCHECK(!map.is_null()); // Weak pointers aren't cleared yet. Map parent = Map::cast(map.constructor_or_backpointer()); bool parent_is_alive = non_atomic_marking_state()->IsBlackOrGrey(parent); DescriptorArray descriptors = parent_is_alive ? parent.instance_descriptors() : DescriptorArray(); bool descriptors_owner_died = CompactTransitionArray(parent, array, descriptors); if (descriptors_owner_died) { TrimDescriptorArray(parent, descriptors); } } } } } bool MarkCompactCollector::CompactTransitionArray(Map map, TransitionArray transitions, DescriptorArray descriptors) { DCHECK(!map.is_prototype_map()); int num_transitions = transitions.number_of_entries(); bool descriptors_owner_died = false; int transition_index = 0; // Compact all live transitions to the left. for (int i = 0; i < num_transitions; ++i) { Map target = transitions.GetTarget(i); DCHECK_EQ(target.constructor_or_backpointer(), map); if (non_atomic_marking_state()->IsWhite(target)) { if (!descriptors.is_null() && target.instance_descriptors() == descriptors) { DCHECK(!target.is_prototype_map()); descriptors_owner_died = true; } } else { if (i != transition_index) { Name key = transitions.GetKey(i); transitions.SetKey(transition_index, key); HeapObjectSlot key_slot = transitions.GetKeySlot(transition_index); RecordSlot(transitions, key_slot, key); MaybeObject raw_target = transitions.GetRawTarget(i); transitions.SetRawTarget(transition_index, raw_target); HeapObjectSlot target_slot = transitions.GetTargetSlot(transition_index); RecordSlot(transitions, target_slot, raw_target->GetHeapObject()); } transition_index++; } } // If there are no transitions to be cleared, return. if (transition_index == num_transitions) { DCHECK(!descriptors_owner_died); return false; } // Note that we never eliminate a transition array, though we might right-trim // such that number_of_transitions() == 0. If this assumption changes, // TransitionArray::Insert() will need to deal with the case that a transition // array disappeared during GC. int trim = transitions.Capacity() - transition_index; if (trim > 0) { heap_->RightTrimWeakFixedArray(transitions, trim * TransitionArray::kEntrySize); transitions.SetNumberOfTransitions(transition_index); } return descriptors_owner_died; } void MarkCompactCollector::RightTrimDescriptorArray(DescriptorArray array, int descriptors_to_trim) { int old_nof_all_descriptors = array.number_of_all_descriptors(); int new_nof_all_descriptors = old_nof_all_descriptors - descriptors_to_trim; DCHECK_LT(0, descriptors_to_trim); DCHECK_LE(0, new_nof_all_descriptors); Address start = array.GetDescriptorSlot(new_nof_all_descriptors).address(); Address end = array.GetDescriptorSlot(old_nof_all_descriptors).address(); RememberedSet<OLD_TO_NEW>::RemoveRange(MemoryChunk::FromHeapObject(array), start, end, SlotSet::PREFREE_EMPTY_BUCKETS); RememberedSet<OLD_TO_OLD>::RemoveRange(MemoryChunk::FromHeapObject(array), start, end, SlotSet::PREFREE_EMPTY_BUCKETS); heap()->CreateFillerObjectAt(start, static_cast<int>(end - start), ClearRecordedSlots::kNo); array.set_number_of_all_descriptors(new_nof_all_descriptors); } void MarkCompactCollector::TrimDescriptorArray(Map map, DescriptorArray descriptors) { int number_of_own_descriptors = map.NumberOfOwnDescriptors(); if (number_of_own_descriptors == 0) { DCHECK(descriptors == ReadOnlyRoots(heap_).empty_descriptor_array()); return; } // TODO(ulan): Trim only if slack is greater than some percentage threshold. int to_trim = descriptors.number_of_all_descriptors() - number_of_own_descriptors; if (to_trim > 0) { descriptors.set_number_of_descriptors(number_of_own_descriptors); RightTrimDescriptorArray(descriptors, to_trim); TrimEnumCache(map, descriptors); descriptors.Sort(); if (FLAG_unbox_double_fields) { LayoutDescriptor layout_descriptor = map.layout_descriptor(); layout_descriptor = layout_descriptor.Trim(heap_, map, descriptors, number_of_own_descriptors); SLOW_DCHECK(layout_descriptor.IsConsistentWithMap(map, true)); } } DCHECK(descriptors.number_of_descriptors() == number_of_own_descriptors); map.set_owns_descriptors(true); } void MarkCompactCollector::TrimEnumCache(Map map, DescriptorArray descriptors) { int live_enum = map.EnumLength(); if (live_enum == kInvalidEnumCacheSentinel) { live_enum = map.NumberOfEnumerableProperties(); } if (live_enum == 0) return descriptors.ClearEnumCache(); EnumCache enum_cache = descriptors.enum_cache(); FixedArray keys = enum_cache.keys(); int to_trim = keys.length() - live_enum; if (to_trim <= 0) return; heap_->RightTrimFixedArray(keys, to_trim); FixedArray indices = enum_cache.indices(); to_trim = indices.length() - live_enum; if (to_trim <= 0) return; heap_->RightTrimFixedArray(indices, to_trim); } void MarkCompactCollector::ClearWeakCollections() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_WEAK_COLLECTIONS); EphemeronHashTable table; while (weak_objects_.ephemeron_hash_tables.Pop(kMainThread, &table)) { for (int i = 0; i < table.Capacity(); i++) { HeapObject key = HeapObject::cast(table.KeyAt(i)); #ifdef VERIFY_HEAP Object value = table.ValueAt(i); if (value.IsHeapObject()) { CHECK_IMPLIES( non_atomic_marking_state()->IsBlackOrGrey(key), non_atomic_marking_state()->IsBlackOrGrey(HeapObject::cast(value))); } #endif if (!non_atomic_marking_state()->IsBlackOrGrey(key)) { table.RemoveEntry(i); } } } for (auto it = heap_->ephemeron_remembered_set_.begin(); it != heap_->ephemeron_remembered_set_.end();) { if (!non_atomic_marking_state()->IsBlackOrGrey(it->first)) { it = heap_->ephemeron_remembered_set_.erase(it); } else { ++it; } } } void MarkCompactCollector::ClearWeakReferences() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_CLEAR_WEAK_REFERENCES); std::pair<HeapObject, HeapObjectSlot> slot; HeapObjectReference cleared_weak_ref = HeapObjectReference::ClearedValue(isolate()); while (weak_objects_.weak_references.Pop(kMainThread, &slot)) { HeapObject value; // The slot could have been overwritten, so we have to treat it // as MaybeObjectSlot. MaybeObjectSlot location(slot.second); if ((*location)->GetHeapObjectIfWeak(&value)) { DCHECK(!value.IsCell()); if (non_atomic_marking_state()->IsBlackOrGrey(value)) { // The value of the weak reference is alive. RecordSlot(slot.first, HeapObjectSlot(location), value); } else { if (value.IsMap()) { // The map is non-live. ClearPotentialSimpleMapTransition(Map::cast(value)); } location.store(cleared_weak_ref); } } } } void MarkCompactCollector::ClearJSWeakRefs() { if (!FLAG_harmony_weak_refs) { return; } JSWeakRef weak_ref; while (weak_objects_.js_weak_refs.Pop(kMainThread, &weak_ref)) { HeapObject target = HeapObject::cast(weak_ref.target()); if (!non_atomic_marking_state()->IsBlackOrGrey(target)) { weak_ref.set_target(ReadOnlyRoots(isolate()).undefined_value()); } else { // The value of the JSWeakRef is alive. ObjectSlot slot = weak_ref.RawField(JSWeakRef::kTargetOffset); RecordSlot(weak_ref, slot, target); } } WeakCell weak_cell; while (weak_objects_.weak_cells.Pop(kMainThread, &weak_cell)) { HeapObject target = HeapObject::cast(weak_cell.target()); if (!non_atomic_marking_state()->IsBlackOrGrey(target)) { DCHECK(!target.IsUndefined()); // The value of the WeakCell is dead. JSFinalizationGroup finalization_group = JSFinalizationGroup::cast(weak_cell.finalization_group()); if (!finalization_group.scheduled_for_cleanup()) { heap()->AddDirtyJSFinalizationGroup( finalization_group, [](HeapObject object, ObjectSlot slot, Object target) { if (target.IsHeapObject()) { RecordSlot(object, slot, HeapObject::cast(target)); } }); } // We're modifying the pointers in WeakCell and JSFinalizationGroup during // GC; thus we need to record the slots it writes. The normal write // barrier is not enough, since it's disabled before GC. weak_cell.Nullify(isolate(), [](HeapObject object, ObjectSlot slot, Object target) { if (target.IsHeapObject()) { RecordSlot(object, slot, HeapObject::cast(target)); } }); DCHECK(finalization_group.NeedsCleanup()); DCHECK(finalization_group.scheduled_for_cleanup()); } else { // The value of the WeakCell is alive. ObjectSlot slot = weak_cell.RawField(WeakCell::kTargetOffset); RecordSlot(weak_cell, slot, HeapObject::cast(*slot)); } } } void MarkCompactCollector::AbortWeakObjects() { weak_objects_.transition_arrays.Clear(); weak_objects_.ephemeron_hash_tables.Clear(); weak_objects_.current_ephemerons.Clear(); weak_objects_.next_ephemerons.Clear(); weak_objects_.discovered_ephemerons.Clear(); weak_objects_.weak_references.Clear(); weak_objects_.weak_objects_in_code.Clear(); weak_objects_.js_weak_refs.Clear(); weak_objects_.weak_cells.Clear(); weak_objects_.bytecode_flushing_candidates.Clear(); weak_objects_.flushed_js_functions.Clear(); } bool MarkCompactCollector::IsOnEvacuationCandidate(MaybeObject obj) { return Page::FromAddress(obj.ptr())->IsEvacuationCandidate(); } MarkCompactCollector::RecordRelocSlotInfo MarkCompactCollector::PrepareRecordRelocSlot(Code host, RelocInfo* rinfo, HeapObject target) { RecordRelocSlotInfo result; result.should_record = false; Page* target_page = Page::FromHeapObject(target); Page* source_page = Page::FromHeapObject(host); if (target_page->IsEvacuationCandidate() && (rinfo->host().is_null() || !source_page->ShouldSkipEvacuationSlotRecording())) { RelocInfo::Mode rmode = rinfo->rmode(); Address addr = rinfo->pc(); SlotType slot_type = SlotTypeForRelocInfoMode(rmode); if (rinfo->IsInConstantPool()) { addr = rinfo->constant_pool_entry_address(); if (RelocInfo::IsCodeTargetMode(rmode)) { slot_type = CODE_ENTRY_SLOT; } else { // Constant pools don't support compressed values at this time // (this may change, therefore use a DCHECK). DCHECK(RelocInfo::IsFullEmbeddedObject(rmode)); slot_type = OBJECT_SLOT; } } uintptr_t offset = addr - source_page->address(); DCHECK_LT(offset, static_cast<uintptr_t>(TypedSlotSet::kMaxOffset)); result.should_record = true; result.memory_chunk = source_page; result.slot_type = slot_type; result.offset = static_cast<uint32_t>(offset); } return result; } void MarkCompactCollector::RecordRelocSlot(Code host, RelocInfo* rinfo, HeapObject target) { RecordRelocSlotInfo info = PrepareRecordRelocSlot(host, rinfo, target); if (info.should_record) { RememberedSet<OLD_TO_OLD>::InsertTyped(info.memory_chunk, info.slot_type, info.offset); } } namespace { // Missing specialization MakeSlotValue<FullObjectSlot, WEAK>() will turn // attempt to store a weak reference to strong-only slot to a compilation error. template <typename TSlot, HeapObjectReferenceType reference_type> typename TSlot::TObject MakeSlotValue(HeapObject heap_object); template <> Object MakeSlotValue<ObjectSlot, HeapObjectReferenceType::STRONG>( HeapObject heap_object) { return heap_object; } template <> MaybeObject MakeSlotValue<MaybeObjectSlot, HeapObjectReferenceType::STRONG>( HeapObject heap_object) { return HeapObjectReference::Strong(heap_object); } template <> MaybeObject MakeSlotValue<MaybeObjectSlot, HeapObjectReferenceType::WEAK>( HeapObject heap_object) { return HeapObjectReference::Weak(heap_object); } #ifdef V8_COMPRESS_POINTERS template <> Object MakeSlotValue<FullObjectSlot, HeapObjectReferenceType::STRONG>( HeapObject heap_object) { return heap_object; } template <> MaybeObject MakeSlotValue<FullMaybeObjectSlot, HeapObjectReferenceType::STRONG>( HeapObject heap_object) { return HeapObjectReference::Strong(heap_object); } // The following specialization // MakeSlotValue<FullMaybeObjectSlot, HeapObjectReferenceType::WEAK>() // is not used. #endif template <AccessMode access_mode, HeapObjectReferenceType reference_type, typename TSlot> static inline SlotCallbackResult UpdateSlot(TSlot slot, typename TSlot::TObject old, HeapObject heap_obj) { static_assert( std::is_same<TSlot, FullObjectSlot>::value || std::is_same<TSlot, ObjectSlot>::value || std::is_same<TSlot, FullMaybeObjectSlot>::value || std::is_same<TSlot, MaybeObjectSlot>::value, "Only [Full]ObjectSlot and [Full]MaybeObjectSlot are expected here"); MapWord map_word = heap_obj.map_word(); if (map_word.IsForwardingAddress()) { DCHECK_IMPLIES(!Heap::InFromPage(heap_obj), MarkCompactCollector::IsOnEvacuationCandidate(heap_obj) || Page::FromHeapObject(heap_obj)->IsFlagSet( Page::COMPACTION_WAS_ABORTED)); typename TSlot::TObject target = MakeSlotValue<TSlot, reference_type>(map_word.ToForwardingAddress()); if (access_mode == AccessMode::NON_ATOMIC) { slot.store(target); } else { slot.Release_CompareAndSwap(old, target); } DCHECK(!Heap::InFromPage(target)); DCHECK(!MarkCompactCollector::IsOnEvacuationCandidate(target)); } else { DCHECK(heap_obj.map().IsMap()); } // OLD_TO_OLD slots are always removed after updating. return REMOVE_SLOT; } template <AccessMode access_mode, typename TSlot> static inline SlotCallbackResult UpdateSlot(TSlot slot) { typename TSlot::TObject obj = slot.Relaxed_Load(); HeapObject heap_obj; if (TSlot::kCanBeWeak && obj->GetHeapObjectIfWeak(&heap_obj)) { UpdateSlot<access_mode, HeapObjectReferenceType::WEAK>(slot, obj, heap_obj); } else if (obj->GetHeapObjectIfStrong(&heap_obj)) { return UpdateSlot<access_mode, HeapObjectReferenceType::STRONG>(slot, obj, heap_obj); } return REMOVE_SLOT; } template <AccessMode access_mode, typename TSlot> static inline SlotCallbackResult UpdateStrongSlot(TSlot slot) { typename TSlot::TObject obj = slot.Relaxed_Load(); DCHECK(!HAS_WEAK_HEAP_OBJECT_TAG(obj.ptr())); HeapObject heap_obj; if (obj.GetHeapObject(&heap_obj)) { return UpdateSlot<access_mode, HeapObjectReferenceType::STRONG>(slot, obj, heap_obj); } return REMOVE_SLOT; } } // namespace // Visitor for updating root pointers and to-space pointers. // It does not expect to encounter pointers to dead objects. class PointersUpdatingVisitor : public ObjectVisitor, public RootVisitor { public: PointersUpdatingVisitor() {} void VisitPointer(HeapObject host, ObjectSlot p) override { UpdateStrongSlotInternal(p); } void VisitPointer(HeapObject host, MaybeObjectSlot p) override { UpdateSlotInternal(p); } void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) override { for (ObjectSlot p = start; p < end; ++p) { UpdateStrongSlotInternal(p); } } void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final { for (MaybeObjectSlot p = start; p < end; ++p) { UpdateSlotInternal(p); } } void VisitRootPointer(Root root, const char* description, FullObjectSlot p) override { UpdateRootSlotInternal(p); } void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override { for (FullObjectSlot p = start; p < end; ++p) { UpdateRootSlotInternal(p); } } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { // This visitor nevers visits code objects. UNREACHABLE(); } void VisitCodeTarget(Code host, RelocInfo* rinfo) override { // This visitor nevers visits code objects. UNREACHABLE(); } private: static inline SlotCallbackResult UpdateRootSlotInternal(FullObjectSlot slot) { return UpdateStrongSlot<AccessMode::NON_ATOMIC>(slot); } static inline SlotCallbackResult UpdateStrongMaybeObjectSlotInternal( MaybeObjectSlot slot) { return UpdateStrongSlot<AccessMode::NON_ATOMIC>(slot); } static inline SlotCallbackResult UpdateStrongSlotInternal(ObjectSlot slot) { return UpdateStrongSlot<AccessMode::NON_ATOMIC>(slot); } static inline SlotCallbackResult UpdateSlotInternal(MaybeObjectSlot slot) { return UpdateSlot<AccessMode::NON_ATOMIC>(slot); } }; static String UpdateReferenceInExternalStringTableEntry(Heap* heap, FullObjectSlot p) { MapWord map_word = HeapObject::cast(*p).map_word(); if (map_word.IsForwardingAddress()) { String new_string = String::cast(map_word.ToForwardingAddress()); if (new_string.IsExternalString()) { MemoryChunk::MoveExternalBackingStoreBytes( ExternalBackingStoreType::kExternalString, Page::FromAddress((*p).ptr()), Page::FromHeapObject(new_string), ExternalString::cast(new_string).ExternalPayloadSize()); } return new_string; } return String::cast(*p); } void MarkCompactCollector::EvacuatePrologue() { // New space. NewSpace* new_space = heap()->new_space(); // Append the list of new space pages to be processed. for (Page* p : PageRange(new_space->first_allocatable_address(), new_space->top())) { new_space_evacuation_pages_.push_back(p); } new_space->Flip(); new_space->ResetLinearAllocationArea(); heap()->new_lo_space()->Flip(); heap()->new_lo_space()->ResetPendingObject(); // Old space. DCHECK(old_space_evacuation_pages_.empty()); old_space_evacuation_pages_ = std::move(evacuation_candidates_); evacuation_candidates_.clear(); DCHECK(evacuation_candidates_.empty()); } void MarkCompactCollector::EvacuateEpilogue() { aborted_evacuation_candidates_.clear(); // New space. heap()->new_space()->set_age_mark(heap()->new_space()->top()); // Deallocate unmarked large objects. heap()->lo_space()->FreeUnmarkedObjects(); heap()->code_lo_space()->FreeUnmarkedObjects(); heap()->new_lo_space()->FreeUnmarkedObjects(); // Old space. Deallocate evacuated candidate pages. ReleaseEvacuationCandidates(); // Give pages that are queued to be freed back to the OS. heap()->memory_allocator()->unmapper()->FreeQueuedChunks(); #ifdef DEBUG // Old-to-old slot sets must be empty after evacuation. for (Page* p : *heap()->old_space()) { DCHECK_NULL((p->slot_set<OLD_TO_OLD, AccessMode::ATOMIC>())); DCHECK_NULL((p->typed_slot_set<OLD_TO_OLD, AccessMode::ATOMIC>())); DCHECK_NULL(p->invalidated_slots<OLD_TO_OLD>()); DCHECK_NULL(p->invalidated_slots<OLD_TO_NEW>()); } #endif } class Evacuator : public Malloced { public: enum EvacuationMode { kObjectsNewToOld, kPageNewToOld, kObjectsOldToOld, kPageNewToNew, }; static inline EvacuationMode ComputeEvacuationMode(MemoryChunk* chunk) { // Note: The order of checks is important in this function. if (chunk->IsFlagSet(MemoryChunk::PAGE_NEW_OLD_PROMOTION)) return kPageNewToOld; if (chunk->IsFlagSet(MemoryChunk::PAGE_NEW_NEW_PROMOTION)) return kPageNewToNew; if (chunk->InYoungGeneration()) return kObjectsNewToOld; return kObjectsOldToOld; } // NewSpacePages with more live bytes than this threshold qualify for fast // evacuation. static intptr_t NewSpacePageEvacuationThreshold() { if (FLAG_page_promotion) return FLAG_page_promotion_threshold * MemoryChunkLayout::AllocatableMemoryInDataPage() / 100; return MemoryChunkLayout::AllocatableMemoryInDataPage() + kTaggedSize; } Evacuator(Heap* heap, RecordMigratedSlotVisitor* record_visitor) : heap_(heap), local_allocator_(heap_), local_pretenuring_feedback_(kInitialLocalPretenuringFeedbackCapacity), new_space_visitor_(heap_, &local_allocator_, record_visitor, &local_pretenuring_feedback_), new_to_new_page_visitor_(heap_, record_visitor, &local_pretenuring_feedback_), new_to_old_page_visitor_(heap_, record_visitor, &local_pretenuring_feedback_), old_space_visitor_(heap_, &local_allocator_, record_visitor), duration_(0.0), bytes_compacted_(0) {} virtual ~Evacuator() = default; void EvacuatePage(MemoryChunk* chunk); void AddObserver(MigrationObserver* observer) { new_space_visitor_.AddObserver(observer); old_space_visitor_.AddObserver(observer); } // Merge back locally cached info sequentially. Note that this method needs // to be called from the main thread. inline void Finalize(); virtual GCTracer::BackgroundScope::ScopeId GetBackgroundTracingScope() = 0; virtual GCTracer::Scope::ScopeId GetTracingScope() = 0; protected: static const int kInitialLocalPretenuringFeedbackCapacity = 256; // |saved_live_bytes| returns the live bytes of the page that was processed. virtual void RawEvacuatePage(MemoryChunk* chunk, intptr_t* saved_live_bytes) = 0; inline Heap* heap() { return heap_; } void ReportCompactionProgress(double duration, intptr_t bytes_compacted) { duration_ += duration; bytes_compacted_ += bytes_compacted; } Heap* heap_; // Locally cached collector data. LocalAllocator local_allocator_; Heap::PretenuringFeedbackMap local_pretenuring_feedback_; // Visitors for the corresponding spaces. EvacuateNewSpaceVisitor new_space_visitor_; EvacuateNewSpacePageVisitor<PageEvacuationMode::NEW_TO_NEW> new_to_new_page_visitor_; EvacuateNewSpacePageVisitor<PageEvacuationMode::NEW_TO_OLD> new_to_old_page_visitor_; EvacuateOldSpaceVisitor old_space_visitor_; // Book keeping info. double duration_; intptr_t bytes_compacted_; }; void Evacuator::EvacuatePage(MemoryChunk* chunk) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "Evacuator::EvacuatePage"); DCHECK(chunk->SweepingDone()); intptr_t saved_live_bytes = 0; double evacuation_time = 0.0; { AlwaysAllocateScope always_allocate(heap()->isolate()); TimedScope timed_scope(&evacuation_time); RawEvacuatePage(chunk, &saved_live_bytes); } ReportCompactionProgress(evacuation_time, saved_live_bytes); if (FLAG_trace_evacuation) { PrintIsolate(heap()->isolate(), "evacuation[%p]: page=%p new_space=%d " "page_evacuation=%d executable=%d contains_age_mark=%d " "live_bytes=%" V8PRIdPTR " time=%f success=%d\n", static_cast<void*>(this), static_cast<void*>(chunk), chunk->InNewSpace(), chunk->IsFlagSet(Page::PAGE_NEW_OLD_PROMOTION) || chunk->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION), chunk->IsFlagSet(MemoryChunk::IS_EXECUTABLE), chunk->Contains(heap()->new_space()->age_mark()), saved_live_bytes, evacuation_time, chunk->IsFlagSet(Page::COMPACTION_WAS_ABORTED)); } } void Evacuator::Finalize() { local_allocator_.Finalize(); heap()->tracer()->AddCompactionEvent(duration_, bytes_compacted_); heap()->IncrementPromotedObjectsSize(new_space_visitor_.promoted_size() + new_to_old_page_visitor_.moved_bytes()); heap()->IncrementSemiSpaceCopiedObjectSize( new_space_visitor_.semispace_copied_size() + new_to_new_page_visitor_.moved_bytes()); heap()->IncrementYoungSurvivorsCounter( new_space_visitor_.promoted_size() + new_space_visitor_.semispace_copied_size() + new_to_old_page_visitor_.moved_bytes() + new_to_new_page_visitor_.moved_bytes()); heap()->MergeAllocationSitePretenuringFeedback(local_pretenuring_feedback_); } class FullEvacuator : public Evacuator { public: explicit FullEvacuator(MarkCompactCollector* collector) : Evacuator(collector->heap(), &record_visitor_), record_visitor_(collector, &ephemeron_remembered_set_), collector_(collector) {} GCTracer::BackgroundScope::ScopeId GetBackgroundTracingScope() override { return GCTracer::BackgroundScope::MC_BACKGROUND_EVACUATE_COPY; } GCTracer::Scope::ScopeId GetTracingScope() override { return GCTracer::Scope::MC_EVACUATE_COPY_PARALLEL; } inline void Finalize() { Evacuator::Finalize(); for (auto it = ephemeron_remembered_set_.begin(); it != ephemeron_remembered_set_.end(); ++it) { auto insert_result = heap()->ephemeron_remembered_set_.insert({it->first, it->second}); if (!insert_result.second) { // Insertion didn't happen, there was already an item. auto set = insert_result.first->second; for (int entry : it->second) { set.insert(entry); } } } } protected: void RawEvacuatePage(MemoryChunk* chunk, intptr_t* live_bytes) override; EphemeronRememberedSet ephemeron_remembered_set_; RecordMigratedSlotVisitor record_visitor_; MarkCompactCollector* collector_; }; void FullEvacuator::RawEvacuatePage(MemoryChunk* chunk, intptr_t* live_bytes) { const EvacuationMode evacuation_mode = ComputeEvacuationMode(chunk); TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "FullEvacuator::RawEvacuatePage", "evacuation_mode", evacuation_mode); MarkCompactCollector::NonAtomicMarkingState* marking_state = collector_->non_atomic_marking_state(); *live_bytes = marking_state->live_bytes(chunk); HeapObject failed_object; switch (evacuation_mode) { case kObjectsNewToOld: LiveObjectVisitor::VisitBlackObjectsNoFail( chunk, marking_state, &new_space_visitor_, LiveObjectVisitor::kClearMarkbits); // ArrayBufferTracker will be updated during pointers updating. break; case kPageNewToOld: LiveObjectVisitor::VisitBlackObjectsNoFail( chunk, marking_state, &new_to_old_page_visitor_, LiveObjectVisitor::kKeepMarking); new_to_old_page_visitor_.account_moved_bytes( marking_state->live_bytes(chunk)); // ArrayBufferTracker will be updated during sweeping. break; case kPageNewToNew: LiveObjectVisitor::VisitBlackObjectsNoFail( chunk, marking_state, &new_to_new_page_visitor_, LiveObjectVisitor::kKeepMarking); new_to_new_page_visitor_.account_moved_bytes( marking_state->live_bytes(chunk)); // ArrayBufferTracker will be updated during sweeping. break; case kObjectsOldToOld: { const bool success = LiveObjectVisitor::VisitBlackObjects( chunk, marking_state, &old_space_visitor_, LiveObjectVisitor::kClearMarkbits, &failed_object); if (!success) { // Aborted compaction page. Actual processing happens on the main // thread for simplicity reasons. collector_->ReportAbortedEvacuationCandidate(failed_object, chunk); } else { // ArrayBufferTracker will be updated during pointers updating. } break; } } } class EvacuationItem : public ItemParallelJob::Item { public: explicit EvacuationItem(MemoryChunk* chunk) : chunk_(chunk) {} ~EvacuationItem() override = default; MemoryChunk* chunk() const { return chunk_; } private: MemoryChunk* chunk_; }; class PageEvacuationTask : public ItemParallelJob::Task { public: PageEvacuationTask(Isolate* isolate, Evacuator* evacuator) : ItemParallelJob::Task(isolate), evacuator_(evacuator), tracer_(isolate->heap()->tracer()) {} void RunInParallel(Runner runner) override { if (runner == Runner::kForeground) { TRACE_GC(tracer_, evacuator_->GetTracingScope()); ProcessItems(); } else { TRACE_BACKGROUND_GC(tracer_, evacuator_->GetBackgroundTracingScope()); ProcessItems(); } } private: void ProcessItems() { EvacuationItem* item = nullptr; while ((item = GetItem<EvacuationItem>()) != nullptr) { evacuator_->EvacuatePage(item->chunk()); item->MarkFinished(); } } Evacuator* evacuator_; GCTracer* tracer_; }; template <class Evacuator, class Collector> void MarkCompactCollectorBase::CreateAndExecuteEvacuationTasks( Collector* collector, ItemParallelJob* job, MigrationObserver* migration_observer, const intptr_t live_bytes) { // Used for trace summary. double compaction_speed = 0; if (FLAG_trace_evacuation) { compaction_speed = heap()->tracer()->CompactionSpeedInBytesPerMillisecond(); } const bool profiling = isolate()->LogObjectRelocation(); ProfilingMigrationObserver profiling_observer(heap()); const int wanted_num_tasks = NumberOfParallelCompactionTasks(job->NumberOfItems()); Evacuator** evacuators = new Evacuator*[wanted_num_tasks]; for (int i = 0; i < wanted_num_tasks; i++) { evacuators[i] = new Evacuator(collector); if (profiling) evacuators[i]->AddObserver(&profiling_observer); if (migration_observer != nullptr) evacuators[i]->AddObserver(migration_observer); job->AddTask(new PageEvacuationTask(heap()->isolate(), evacuators[i])); } job->Run(); for (int i = 0; i < wanted_num_tasks; i++) { evacuators[i]->Finalize(); delete evacuators[i]; } delete[] evacuators; if (FLAG_trace_evacuation) { PrintIsolate(isolate(), "%8.0f ms: evacuation-summary: parallel=%s pages=%d " "wanted_tasks=%d tasks=%d cores=%d live_bytes=%" V8PRIdPTR " compaction_speed=%.f\n", isolate()->time_millis_since_init(), FLAG_parallel_compaction ? "yes" : "no", job->NumberOfItems(), wanted_num_tasks, job->NumberOfTasks(), V8::GetCurrentPlatform()->NumberOfWorkerThreads() + 1, live_bytes, compaction_speed); } } bool MarkCompactCollectorBase::ShouldMovePage(Page* p, intptr_t live_bytes) { const bool reduce_memory = heap()->ShouldReduceMemory(); const Address age_mark = heap()->new_space()->age_mark(); return !reduce_memory && !p->NeverEvacuate() && (live_bytes > Evacuator::NewSpacePageEvacuationThreshold()) && !p->Contains(age_mark) && heap()->CanExpandOldGeneration(live_bytes); } void MarkCompactCollector::EvacuatePagesInParallel() { ItemParallelJob evacuation_job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); intptr_t live_bytes = 0; for (Page* page : old_space_evacuation_pages_) { live_bytes += non_atomic_marking_state()->live_bytes(page); evacuation_job.AddItem(new EvacuationItem(page)); } for (Page* page : new_space_evacuation_pages_) { intptr_t live_bytes_on_page = non_atomic_marking_state()->live_bytes(page); if (live_bytes_on_page == 0 && !page->contains_array_buffers()) continue; live_bytes += live_bytes_on_page; if (ShouldMovePage(page, live_bytes_on_page)) { if (page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK)) { EvacuateNewSpacePageVisitor<NEW_TO_OLD>::Move(page); DCHECK_EQ(heap()->old_space(), page->owner()); // The move added page->allocated_bytes to the old space, but we are // going to sweep the page and add page->live_byte_count. heap()->old_space()->DecreaseAllocatedBytes(page->allocated_bytes(), page); } else { EvacuateNewSpacePageVisitor<NEW_TO_NEW>::Move(page); } } evacuation_job.AddItem(new EvacuationItem(page)); } // Promote young generation large objects. IncrementalMarking::NonAtomicMarkingState* marking_state = heap()->incremental_marking()->non_atomic_marking_state(); for (auto it = heap()->new_lo_space()->begin(); it != heap()->new_lo_space()->end();) { LargePage* current = *it; it++; HeapObject object = current->GetObject(); DCHECK(!marking_state->IsGrey(object)); if (marking_state->IsBlack(object)) { heap_->lo_space()->PromoteNewLargeObject(current); current->SetFlag(Page::PAGE_NEW_OLD_PROMOTION); evacuation_job.AddItem(new EvacuationItem(current)); } } if (evacuation_job.NumberOfItems() == 0) return; CreateAndExecuteEvacuationTasks<FullEvacuator>(this, &evacuation_job, nullptr, live_bytes); PostProcessEvacuationCandidates(); } class EvacuationWeakObjectRetainer : public WeakObjectRetainer { public: Object RetainAs(Object object) override { if (object.IsHeapObject()) { HeapObject heap_object = HeapObject::cast(object); MapWord map_word = heap_object.map_word(); if (map_word.IsForwardingAddress()) { return map_word.ToForwardingAddress(); } } return object; } }; void MarkCompactCollector::RecordLiveSlotsOnPage(Page* page) { EvacuateRecordOnlyVisitor visitor(heap()); LiveObjectVisitor::VisitBlackObjectsNoFail(page, non_atomic_marking_state(), &visitor, LiveObjectVisitor::kKeepMarking); } template <class Visitor, typename MarkingState> bool LiveObjectVisitor::VisitBlackObjects(MemoryChunk* chunk, MarkingState* marking_state, Visitor* visitor, IterationMode iteration_mode, HeapObject* failed_object) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "LiveObjectVisitor::VisitBlackObjects"); for (auto object_and_size : LiveObjectRange<kBlackObjects>(chunk, marking_state->bitmap(chunk))) { HeapObject const object = object_and_size.first; if (!visitor->Visit(object, object_and_size.second)) { if (iteration_mode == kClearMarkbits) { marking_state->bitmap(chunk)->ClearRange( chunk->AddressToMarkbitIndex(chunk->area_start()), chunk->AddressToMarkbitIndex(object.address())); *failed_object = object; } return false; } } if (iteration_mode == kClearMarkbits) { marking_state->ClearLiveness(chunk); } return true; } template <class Visitor, typename MarkingState> void LiveObjectVisitor::VisitBlackObjectsNoFail(MemoryChunk* chunk, MarkingState* marking_state, Visitor* visitor, IterationMode iteration_mode) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "LiveObjectVisitor::VisitBlackObjectsNoFail"); if (chunk->IsLargePage()) { HeapObject object = reinterpret_cast<LargePage*>(chunk)->GetObject(); if (marking_state->IsBlack(object)) { const bool success = visitor->Visit(object, object.Size()); USE(success); DCHECK(success); } } else { for (auto object_and_size : LiveObjectRange<kBlackObjects>(chunk, marking_state->bitmap(chunk))) { HeapObject const object = object_and_size.first; DCHECK(marking_state->IsBlack(object)); const bool success = visitor->Visit(object, object_and_size.second); USE(success); DCHECK(success); } } if (iteration_mode == kClearMarkbits) { marking_state->ClearLiveness(chunk); } } template <class Visitor, typename MarkingState> void LiveObjectVisitor::VisitGreyObjectsNoFail(MemoryChunk* chunk, MarkingState* marking_state, Visitor* visitor, IterationMode iteration_mode) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "LiveObjectVisitor::VisitGreyObjectsNoFail"); if (chunk->IsLargePage()) { HeapObject object = reinterpret_cast<LargePage*>(chunk)->GetObject(); if (marking_state->IsGrey(object)) { const bool success = visitor->Visit(object, object.Size()); USE(success); DCHECK(success); } } else { for (auto object_and_size : LiveObjectRange<kGreyObjects>(chunk, marking_state->bitmap(chunk))) { HeapObject const object = object_and_size.first; DCHECK(marking_state->IsGrey(object)); const bool success = visitor->Visit(object, object_and_size.second); USE(success); DCHECK(success); } } if (iteration_mode == kClearMarkbits) { marking_state->ClearLiveness(chunk); } } template <typename MarkingState> void LiveObjectVisitor::RecomputeLiveBytes(MemoryChunk* chunk, MarkingState* marking_state) { int new_live_size = 0; for (auto object_and_size : LiveObjectRange<kAllLiveObjects>(chunk, marking_state->bitmap(chunk))) { new_live_size += object_and_size.second; } marking_state->SetLiveBytes(chunk, new_live_size); } void MarkCompactCollector::Evacuate() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE); base::MutexGuard guard(heap()->relocation_mutex()); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_PROLOGUE); EvacuatePrologue(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_COPY); EvacuationScope evacuation_scope(this); EvacuatePagesInParallel(); } UpdatePointersAfterEvacuation(); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_REBALANCE); if (!heap()->new_space()->Rebalance()) { heap()->FatalProcessOutOfMemory("NewSpace::Rebalance"); } } // Give pages that are queued to be freed back to the OS. Note that filtering // slots only handles old space (for unboxed doubles), and thus map space can // still contain stale pointers. We only free the chunks after pointer updates // to still have access to page headers. heap()->memory_allocator()->unmapper()->FreeQueuedChunks(); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_CLEAN_UP); for (Page* p : new_space_evacuation_pages_) { if (p->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION)) { p->ClearFlag(Page::PAGE_NEW_NEW_PROMOTION); sweeper()->AddPageForIterability(p); } else if (p->IsFlagSet(Page::PAGE_NEW_OLD_PROMOTION)) { p->ClearFlag(Page::PAGE_NEW_OLD_PROMOTION); DCHECK_EQ(OLD_SPACE, p->owner_identity()); sweeper()->AddPage(OLD_SPACE, p, Sweeper::REGULAR); } } new_space_evacuation_pages_.clear(); for (Page* p : old_space_evacuation_pages_) { if (p->IsFlagSet(Page::COMPACTION_WAS_ABORTED)) { sweeper()->AddPage(p->owner_identity(), p, Sweeper::REGULAR); p->ClearFlag(Page::COMPACTION_WAS_ABORTED); } } } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_EPILOGUE); EvacuateEpilogue(); } #ifdef VERIFY_HEAP if (FLAG_verify_heap && !sweeper()->sweeping_in_progress()) { FullEvacuationVerifier verifier(heap()); verifier.Run(); } #endif } class UpdatingItem : public ItemParallelJob::Item { public: ~UpdatingItem() override = default; virtual void Process() = 0; }; class PointersUpdatingTask : public ItemParallelJob::Task { public: explicit PointersUpdatingTask( Isolate* isolate, GCTracer::Scope::ScopeId scope, GCTracer::BackgroundScope::ScopeId background_scope) : ItemParallelJob::Task(isolate), tracer_(isolate->heap()->tracer()), scope_(scope), background_scope_(background_scope) {} void RunInParallel(Runner runner) override { if (runner == Runner::kForeground) { TRACE_GC(tracer_, scope_); UpdatePointers(); } else { TRACE_BACKGROUND_GC(tracer_, background_scope_); UpdatePointers(); } } private: void UpdatePointers() { UpdatingItem* item = nullptr; while ((item = GetItem<UpdatingItem>()) != nullptr) { item->Process(); item->MarkFinished(); } } GCTracer* tracer_; GCTracer::Scope::ScopeId scope_; GCTracer::BackgroundScope::ScopeId background_scope_; }; template <typename MarkingState> class ToSpaceUpdatingItem : public UpdatingItem { public: explicit ToSpaceUpdatingItem(MemoryChunk* chunk, Address start, Address end, MarkingState* marking_state) : chunk_(chunk), start_(start), end_(end), marking_state_(marking_state) {} ~ToSpaceUpdatingItem() override = default; void Process() override { if (chunk_->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION)) { // New->new promoted pages contain garbage so they require iteration using // markbits. ProcessVisitLive(); } else { ProcessVisitAll(); } } private: void ProcessVisitAll() { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "ToSpaceUpdatingItem::ProcessVisitAll"); PointersUpdatingVisitor visitor; for (Address cur = start_; cur < end_;) { HeapObject object = HeapObject::FromAddress(cur); Map map = object.map(); int size = object.SizeFromMap(map); object.IterateBodyFast(map, size, &visitor); cur += size; } } void ProcessVisitLive() { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "ToSpaceUpdatingItem::ProcessVisitLive"); // For young generation evacuations we want to visit grey objects, for // full MC, we need to visit black objects. PointersUpdatingVisitor visitor; for (auto object_and_size : LiveObjectRange<kAllLiveObjects>( chunk_, marking_state_->bitmap(chunk_))) { object_and_size.first.IterateBodyFast(&visitor); } } MemoryChunk* chunk_; Address start_; Address end_; MarkingState* marking_state_; }; template <typename MarkingState> class RememberedSetUpdatingItem : public UpdatingItem { public: explicit RememberedSetUpdatingItem(Heap* heap, MarkingState* marking_state, MemoryChunk* chunk, RememberedSetUpdatingMode updating_mode) : heap_(heap), marking_state_(marking_state), chunk_(chunk), updating_mode_(updating_mode) {} ~RememberedSetUpdatingItem() override = default; void Process() override { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "RememberedSetUpdatingItem::Process"); base::MutexGuard guard(chunk_->mutex()); CodePageMemoryModificationScope memory_modification_scope(chunk_); UpdateUntypedPointers(); UpdateTypedPointers(); } private: template <typename TSlot> inline SlotCallbackResult CheckAndUpdateOldToNewSlot(TSlot slot) { static_assert( std::is_same<TSlot, FullMaybeObjectSlot>::value || std::is_same<TSlot, MaybeObjectSlot>::value, "Only FullMaybeObjectSlot and MaybeObjectSlot are expected here"); using THeapObjectSlot = typename TSlot::THeapObjectSlot; HeapObject heap_object; if (!(*slot).GetHeapObject(&heap_object)) { return REMOVE_SLOT; } if (Heap::InFromPage(heap_object)) { MapWord map_word = heap_object.map_word(); if (map_word.IsForwardingAddress()) { HeapObjectReference::Update(THeapObjectSlot(slot), map_word.ToForwardingAddress()); } bool success = (*slot).GetHeapObject(&heap_object); USE(success); DCHECK(success); // If the object was in from space before and is after executing the // callback in to space, the object is still live. // Unfortunately, we do not know about the slot. It could be in a // just freed free space object. if (Heap::InToPage(heap_object)) { return KEEP_SLOT; } } else if (Heap::InToPage(heap_object)) { // Slots can point to "to" space if the page has been moved, or if the // slot has been recorded multiple times in the remembered set, or // if the slot was already updated during old->old updating. // In case the page has been moved, check markbits to determine liveness // of the slot. In the other case, the slot can just be kept. if (Page::FromHeapObject(heap_object) ->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION)) { // IsBlackOrGrey is required because objects are marked as grey for // the young generation collector while they are black for the full // MC.); if (marking_state_->IsBlackOrGrey(heap_object)) { return KEEP_SLOT; } else { return REMOVE_SLOT; } } return KEEP_SLOT; } else { DCHECK(!Heap::InYoungGeneration(heap_object)); } return REMOVE_SLOT; } void UpdateUntypedPointers() { if (chunk_->slot_set<OLD_TO_NEW, AccessMode::NON_ATOMIC>() != nullptr) { RememberedSet<OLD_TO_NEW>::Iterate( chunk_, [this](MaybeObjectSlot slot) { return CheckAndUpdateOldToNewSlot(slot); }, SlotSet::PREFREE_EMPTY_BUCKETS); } DCHECK_NULL(chunk_->invalidated_slots<OLD_TO_NEW>()); if ((updating_mode_ == RememberedSetUpdatingMode::ALL) && (chunk_->slot_set<OLD_TO_OLD, AccessMode::NON_ATOMIC>() != nullptr)) { InvalidatedSlotsFilter filter = InvalidatedSlotsFilter::OldToOld(chunk_); RememberedSet<OLD_TO_OLD>::Iterate( chunk_, [&filter](MaybeObjectSlot slot) { if (!filter.IsValid(slot.address())) return REMOVE_SLOT; return UpdateSlot<AccessMode::NON_ATOMIC>(slot); }, SlotSet::PREFREE_EMPTY_BUCKETS); } if ((updating_mode_ == RememberedSetUpdatingMode::ALL) && chunk_->invalidated_slots<OLD_TO_OLD>() != nullptr) { #ifdef DEBUG for (auto object_size : *chunk_->invalidated_slots<OLD_TO_OLD>()) { HeapObject object = object_size.first; int size = object_size.second; DCHECK_LE(object.SizeFromMap(object.map()), size); } #endif // The invalidated slots are not needed after old-to-old slots were // processsed. chunk_->ReleaseInvalidatedSlots<OLD_TO_OLD>(); } } void UpdateTypedPointers() { if (chunk_->typed_slot_set<OLD_TO_NEW, AccessMode::NON_ATOMIC>() != nullptr) { CHECK_NE(chunk_->owner(), heap_->map_space()); const auto check_and_update_old_to_new_slot_fn = [this](FullMaybeObjectSlot slot) { return CheckAndUpdateOldToNewSlot(slot); }; RememberedSet<OLD_TO_NEW>::IterateTyped( chunk_, [=](SlotType slot_type, Address slot) { return UpdateTypedSlotHelper::UpdateTypedSlot( heap_, slot_type, slot, check_and_update_old_to_new_slot_fn); }); } if ((updating_mode_ == RememberedSetUpdatingMode::ALL) && (chunk_->typed_slot_set<OLD_TO_OLD, AccessMode::NON_ATOMIC>() != nullptr)) { CHECK_NE(chunk_->owner(), heap_->map_space()); RememberedSet<OLD_TO_OLD>::IterateTyped( chunk_, [=](SlotType slot_type, Address slot) { // Using UpdateStrongSlot is OK here, because there are no weak // typed slots. return UpdateTypedSlotHelper::UpdateTypedSlot( heap_, slot_type, slot, UpdateStrongSlot<AccessMode::NON_ATOMIC, FullMaybeObjectSlot>); }); } } Heap* heap_; MarkingState* marking_state_; MemoryChunk* chunk_; RememberedSetUpdatingMode updating_mode_; }; UpdatingItem* MarkCompactCollector::CreateToSpaceUpdatingItem( MemoryChunk* chunk, Address start, Address end) { return new ToSpaceUpdatingItem<NonAtomicMarkingState>( chunk, start, end, non_atomic_marking_state()); } UpdatingItem* MarkCompactCollector::CreateRememberedSetUpdatingItem( MemoryChunk* chunk, RememberedSetUpdatingMode updating_mode) { return new RememberedSetUpdatingItem<NonAtomicMarkingState>( heap(), non_atomic_marking_state(), chunk, updating_mode); } // Update array buffers on a page that has been evacuated by copying objects. // Target page exclusivity in old space is guaranteed by the fact that // evacuation tasks either (a) retrieved a fresh page, or (b) retrieved all // free list items of a given page. For new space the tracker will update // using a lock. class ArrayBufferTrackerUpdatingItem : public UpdatingItem { public: enum EvacuationState { kRegular, kAborted }; explicit ArrayBufferTrackerUpdatingItem(Page* page, EvacuationState state) : page_(page), state_(state) {} ~ArrayBufferTrackerUpdatingItem() override = default; void Process() override { TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "ArrayBufferTrackerUpdatingItem::Process", "EvacuationState", state_); switch (state_) { case EvacuationState::kRegular: ArrayBufferTracker::ProcessBuffers( page_, ArrayBufferTracker::kUpdateForwardedRemoveOthers); break; case EvacuationState::kAborted: ArrayBufferTracker::ProcessBuffers( page_, ArrayBufferTracker::kUpdateForwardedKeepOthers); break; } } private: Page* const page_; const EvacuationState state_; }; int MarkCompactCollectorBase::CollectToSpaceUpdatingItems( ItemParallelJob* job) { // Seed to space pages. const Address space_start = heap()->new_space()->first_allocatable_address(); const Address space_end = heap()->new_space()->top(); int pages = 0; for (Page* page : PageRange(space_start, space_end)) { Address start = page->Contains(space_start) ? space_start : page->area_start(); Address end = page->Contains(space_end) ? space_end : page->area_end(); job->AddItem(CreateToSpaceUpdatingItem(page, start, end)); pages++; } if (pages == 0) return 0; return NumberOfParallelToSpacePointerUpdateTasks(pages); } template <typename IterateableSpace> int MarkCompactCollectorBase::CollectRememberedSetUpdatingItems( ItemParallelJob* job, IterateableSpace* space, RememberedSetUpdatingMode mode) { int pages = 0; for (MemoryChunk* chunk : *space) { const bool contains_old_to_old_slots = chunk->slot_set<OLD_TO_OLD>() != nullptr || chunk->typed_slot_set<OLD_TO_OLD>() != nullptr; const bool contains_old_to_new_slots = chunk->slot_set<OLD_TO_NEW>() != nullptr || chunk->typed_slot_set<OLD_TO_NEW>() != nullptr; const bool contains_old_to_old_invalidated_slots = chunk->invalidated_slots<OLD_TO_OLD>() != nullptr; const bool contains_old_to_new_invalidated_slots = chunk->invalidated_slots<OLD_TO_NEW>() != nullptr; if (!contains_old_to_new_slots && !contains_old_to_old_slots && !contains_old_to_old_invalidated_slots && !contains_old_to_new_invalidated_slots) continue; if (mode == RememberedSetUpdatingMode::ALL || contains_old_to_new_slots || contains_old_to_old_invalidated_slots || contains_old_to_new_invalidated_slots) { job->AddItem(CreateRememberedSetUpdatingItem(chunk, mode)); pages++; } } return pages; } int MarkCompactCollector::CollectNewSpaceArrayBufferTrackerItems( ItemParallelJob* job) { int pages = 0; for (Page* p : new_space_evacuation_pages_) { if (Evacuator::ComputeEvacuationMode(p) == Evacuator::kObjectsNewToOld) { if (p->local_tracker() == nullptr) continue; pages++; job->AddItem(new ArrayBufferTrackerUpdatingItem( p, ArrayBufferTrackerUpdatingItem::kRegular)); } } return pages; } int MarkCompactCollector::CollectOldSpaceArrayBufferTrackerItems( ItemParallelJob* job) { int pages = 0; for (Page* p : old_space_evacuation_pages_) { if (Evacuator::ComputeEvacuationMode(p) == Evacuator::kObjectsOldToOld && p->IsEvacuationCandidate()) { if (p->local_tracker() == nullptr) continue; pages++; job->AddItem(new ArrayBufferTrackerUpdatingItem( p, ArrayBufferTrackerUpdatingItem::kRegular)); } } for (auto object_and_page : aborted_evacuation_candidates_) { Page* p = object_and_page.second; if (p->local_tracker() == nullptr) continue; pages++; job->AddItem(new ArrayBufferTrackerUpdatingItem( p, ArrayBufferTrackerUpdatingItem::kAborted)); } return pages; } class EphemeronTableUpdatingItem : public UpdatingItem { public: enum EvacuationState { kRegular, kAborted }; explicit EphemeronTableUpdatingItem(Heap* heap) : heap_(heap) {} ~EphemeronTableUpdatingItem() override = default; void Process() override { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "EphemeronTableUpdatingItem::Process"); for (auto it = heap_->ephemeron_remembered_set_.begin(); it != heap_->ephemeron_remembered_set_.end();) { EphemeronHashTable table = it->first; auto& indices = it->second; if (table.map_word().IsForwardingAddress()) { // The table has moved, and RecordMigratedSlotVisitor::VisitEphemeron // inserts entries for the moved table into ephemeron_remembered_set_. it = heap_->ephemeron_remembered_set_.erase(it); continue; } DCHECK(table.map().IsMap()); DCHECK(table.Object::IsEphemeronHashTable()); for (auto iti = indices.begin(); iti != indices.end();) { // EphemeronHashTable keys must be heap objects. HeapObjectSlot key_slot( table.RawFieldOfElementAt(EphemeronHashTable::EntryToIndex(*iti))); HeapObject key = key_slot.ToHeapObject(); MapWord map_word = key.map_word(); if (map_word.IsForwardingAddress()) { key = map_word.ToForwardingAddress(); key_slot.StoreHeapObject(key); } if (!heap_->InYoungGeneration(key)) { iti = indices.erase(iti); } else { ++iti; } } if (indices.size() == 0) { it = heap_->ephemeron_remembered_set_.erase(it); } else { ++it; } } } private: Heap* const heap_; }; void MarkCompactCollector::UpdatePointersAfterEvacuation() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS); PointersUpdatingVisitor updating_visitor; { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_TO_NEW_ROOTS); heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_SWEEP_NEWSPACE); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_SLOTS_MAIN); ItemParallelJob updating_job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); int remembered_set_pages = 0; remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->old_space(), RememberedSetUpdatingMode::ALL); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->code_space(), RememberedSetUpdatingMode::ALL); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->lo_space(), RememberedSetUpdatingMode::ALL); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->code_lo_space(), RememberedSetUpdatingMode::ALL); const int remembered_set_tasks = remembered_set_pages == 0 ? 0 : NumberOfParallelPointerUpdateTasks(remembered_set_pages, old_to_new_slots_); const int to_space_tasks = CollectToSpaceUpdatingItems(&updating_job); const int num_ephemeron_table_updating_tasks = 1; const int num_tasks = Max(to_space_tasks, remembered_set_tasks + num_ephemeron_table_updating_tasks); for (int i = 0; i < num_tasks; i++) { updating_job.AddTask(new PointersUpdatingTask( isolate(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_PARALLEL, GCTracer::BackgroundScope::MC_BACKGROUND_EVACUATE_UPDATE_POINTERS)); } updating_job.AddItem(new EphemeronTableUpdatingItem(heap())); updating_job.Run(); } { // - Update pointers in map space in a separate phase to avoid data races // with Map->LayoutDescriptor edge. // - Update array buffer trackers in the second phase to have access to // byte length which is potentially a HeapNumber. TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_SLOTS_MAP_SPACE); ItemParallelJob updating_job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); int array_buffer_pages = 0; array_buffer_pages += CollectNewSpaceArrayBufferTrackerItems(&updating_job); array_buffer_pages += CollectOldSpaceArrayBufferTrackerItems(&updating_job); int remembered_set_pages = 0; remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->map_space(), RememberedSetUpdatingMode::ALL); const int remembered_set_tasks = remembered_set_pages == 0 ? 0 : NumberOfParallelPointerUpdateTasks(remembered_set_pages, old_to_new_slots_); const int num_tasks = Max(array_buffer_pages, remembered_set_tasks); if (num_tasks > 0) { for (int i = 0; i < num_tasks; i++) { updating_job.AddTask(new PointersUpdatingTask( isolate(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_PARALLEL, GCTracer::BackgroundScope::MC_BACKGROUND_EVACUATE_UPDATE_POINTERS)); } updating_job.Run(); heap()->array_buffer_collector()->FreeAllocations(); } } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_EVACUATE_UPDATE_POINTERS_WEAK); // Update pointers from external string table. heap_->UpdateReferencesInExternalStringTable( &UpdateReferenceInExternalStringTableEntry); EvacuationWeakObjectRetainer evacuation_object_retainer; heap()->ProcessWeakListRoots(&evacuation_object_retainer); } } void MarkCompactCollector::ReportAbortedEvacuationCandidate( HeapObject failed_object, MemoryChunk* chunk) { base::MutexGuard guard(&mutex_); aborted_evacuation_candidates_.push_back( std::make_pair(failed_object, static_cast<Page*>(chunk))); } void MarkCompactCollector::PostProcessEvacuationCandidates() { for (auto object_and_page : aborted_evacuation_candidates_) { HeapObject failed_object = object_and_page.first; Page* page = object_and_page.second; page->SetFlag(Page::COMPACTION_WAS_ABORTED); // Aborted compaction page. We have to record slots here, since we // might not have recorded them in first place. // Remove outdated slots. RememberedSet<OLD_TO_NEW>::RemoveRange(page, page->address(), failed_object.address(), SlotSet::PREFREE_EMPTY_BUCKETS); RememberedSet<OLD_TO_NEW>::RemoveRangeTyped(page, page->address(), failed_object.address()); // Recompute live bytes. LiveObjectVisitor::RecomputeLiveBytes(page, non_atomic_marking_state()); // Re-record slots. EvacuateRecordOnlyVisitor record_visitor(heap()); LiveObjectVisitor::VisitBlackObjectsNoFail(page, non_atomic_marking_state(), &record_visitor, LiveObjectVisitor::kKeepMarking); // Array buffers will be processed during pointer updating. } const int aborted_pages = static_cast<int>(aborted_evacuation_candidates_.size()); int aborted_pages_verified = 0; for (Page* p : old_space_evacuation_pages_) { if (p->IsFlagSet(Page::COMPACTION_WAS_ABORTED)) { // After clearing the evacuation candidate flag the page is again in a // regular state. p->ClearEvacuationCandidate(); aborted_pages_verified++; } else { DCHECK(p->IsEvacuationCandidate()); DCHECK(p->SweepingDone()); p->owner()->memory_chunk_list().Remove(p); } } DCHECK_EQ(aborted_pages_verified, aborted_pages); if (FLAG_trace_evacuation && (aborted_pages > 0)) { PrintIsolate(isolate(), "%8.0f ms: evacuation: aborted=%d\n", isolate()->time_millis_since_init(), aborted_pages); } } void MarkCompactCollector::ReleaseEvacuationCandidates() { for (Page* p : old_space_evacuation_pages_) { if (!p->IsEvacuationCandidate()) continue; PagedSpace* space = static_cast<PagedSpace*>(p->owner()); non_atomic_marking_state()->SetLiveBytes(p, 0); CHECK(p->SweepingDone()); space->ReleasePage(p); } old_space_evacuation_pages_.clear(); compacting_ = false; } void MarkCompactCollector::StartSweepSpace(PagedSpace* space) { space->ClearAllocatorState(); int will_be_swept = 0; bool unused_page_present = false; // Loop needs to support deletion if live bytes == 0 for a page. for (auto it = space->begin(); it != space->end();) { Page* p = *(it++); DCHECK(p->SweepingDone()); if (p->IsEvacuationCandidate()) { // Will be processed in Evacuate. DCHECK(!evacuation_candidates_.empty()); continue; } // One unused page is kept, all further are released before sweeping them. if (non_atomic_marking_state()->live_bytes(p) == 0) { if (unused_page_present) { if (FLAG_gc_verbose) { PrintIsolate(isolate(), "sweeping: released page: %p", static_cast<void*>(p)); } ArrayBufferTracker::FreeAll(p); space->memory_chunk_list().Remove(p); space->ReleasePage(p); continue; } unused_page_present = true; } sweeper()->AddPage(space->identity(), p, Sweeper::REGULAR); will_be_swept++; } if (FLAG_gc_verbose) { PrintIsolate(isolate(), "sweeping: space=%s initialized_for_sweeping=%d", space->name(), will_be_swept); } } void MarkCompactCollector::StartSweepSpaces() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MC_SWEEP); #ifdef DEBUG state_ = SWEEP_SPACES; #endif { { GCTracer::Scope sweep_scope(heap()->tracer(), GCTracer::Scope::MC_SWEEP_OLD); StartSweepSpace(heap()->old_space()); } { GCTracer::Scope sweep_scope(heap()->tracer(), GCTracer::Scope::MC_SWEEP_CODE); StartSweepSpace(heap()->code_space()); } { GCTracer::Scope sweep_scope(heap()->tracer(), GCTracer::Scope::MC_SWEEP_MAP); StartSweepSpace(heap()->map_space()); } sweeper()->StartSweeping(); } } void MarkCompactCollector::MarkingWorklist::PrintWorklist( const char* worklist_name, ConcurrentMarkingWorklist* worklist) { std::map<InstanceType, int> count; int total_count = 0; worklist->IterateGlobalPool([&count, &total_count](HeapObject obj) { ++total_count; count[obj.map().instance_type()]++; }); std::vector<std::pair<int, InstanceType>> rank; rank.reserve(count.size()); for (const auto& i : count) { rank.emplace_back(i.second, i.first); } std::map<InstanceType, std::string> instance_type_name; #define INSTANCE_TYPE_NAME(name) instance_type_name[name] = #name; INSTANCE_TYPE_LIST(INSTANCE_TYPE_NAME) #undef INSTANCE_TYPE_NAME std::sort(rank.begin(), rank.end(), std::greater<std::pair<int, InstanceType>>()); PrintF("Worklist %s: %d\n", worklist_name, total_count); for (auto i : rank) { PrintF(" [%s]: %d\n", instance_type_name[i.second].c_str(), i.first); } } #ifdef ENABLE_MINOR_MC namespace { #ifdef VERIFY_HEAP class YoungGenerationMarkingVerifier : public MarkingVerifier { public: explicit YoungGenerationMarkingVerifier(Heap* heap) : MarkingVerifier(heap), marking_state_( heap->minor_mark_compact_collector()->non_atomic_marking_state()) {} ConcurrentBitmap<AccessMode::NON_ATOMIC>* bitmap( const MemoryChunk* chunk) override { return marking_state_->bitmap(chunk); } bool IsMarked(HeapObject object) override { return marking_state_->IsGrey(object); } bool IsBlackOrGrey(HeapObject object) override { return marking_state_->IsBlackOrGrey(object); } void Run() override { VerifyRoots(VISIT_ALL_IN_SCAVENGE); VerifyMarking(heap_->new_space()); } protected: void VerifyPointers(ObjectSlot start, ObjectSlot end) override { VerifyPointersImpl(start, end); } void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointersImpl(start, end); } void VisitCodeTarget(Code host, RelocInfo* rinfo) override { Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); VerifyHeapObjectImpl(target); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { VerifyHeapObjectImpl(rinfo->target_object()); } void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) override { VerifyPointersImpl(start, end); } private: V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object) { CHECK_IMPLIES(Heap::InYoungGeneration(heap_object), IsMarked(heap_object)); } template <typename TSlot> V8_INLINE void VerifyPointersImpl(TSlot start, TSlot end) { for (TSlot slot = start; slot < end; ++slot) { typename TSlot::TObject object = *slot; HeapObject heap_object; // Minor MC treats weak references as strong. if (object.GetHeapObject(&heap_object)) { VerifyHeapObjectImpl(heap_object); } } } MinorMarkCompactCollector::NonAtomicMarkingState* marking_state_; }; class YoungGenerationEvacuationVerifier : public EvacuationVerifier { public: explicit YoungGenerationEvacuationVerifier(Heap* heap) : EvacuationVerifier(heap) {} void Run() override { VerifyRoots(VISIT_ALL_IN_SCAVENGE); VerifyEvacuation(heap_->new_space()); VerifyEvacuation(heap_->old_space()); VerifyEvacuation(heap_->code_space()); VerifyEvacuation(heap_->map_space()); } protected: V8_INLINE void VerifyHeapObjectImpl(HeapObject heap_object) { CHECK_IMPLIES(Heap::InYoungGeneration(heap_object), Heap::InToPage(heap_object)); } template <typename TSlot> void VerifyPointersImpl(TSlot start, TSlot end) { for (TSlot current = start; current < end; ++current) { typename TSlot::TObject object = *current; HeapObject heap_object; if (object.GetHeapObject(&heap_object)) { VerifyHeapObjectImpl(heap_object); } } } void VerifyPointers(ObjectSlot start, ObjectSlot end) override { VerifyPointersImpl(start, end); } void VerifyPointers(MaybeObjectSlot start, MaybeObjectSlot end) override { VerifyPointersImpl(start, end); } void VisitCodeTarget(Code host, RelocInfo* rinfo) override { Code target = Code::GetCodeFromTargetAddress(rinfo->target_address()); VerifyHeapObjectImpl(target); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) override { VerifyHeapObjectImpl(rinfo->target_object()); } void VerifyRootPointers(FullObjectSlot start, FullObjectSlot end) override { VerifyPointersImpl(start, end); } }; #endif // VERIFY_HEAP bool IsUnmarkedObjectForYoungGeneration(Heap* heap, FullObjectSlot p) { DCHECK_IMPLIES(Heap::InYoungGeneration(*p), Heap::InToPage(*p)); return Heap::InYoungGeneration(*p) && !heap->minor_mark_compact_collector() ->non_atomic_marking_state() ->IsGrey(HeapObject::cast(*p)); } } // namespace class YoungGenerationMarkingVisitor final : public NewSpaceVisitor<YoungGenerationMarkingVisitor> { public: YoungGenerationMarkingVisitor( MinorMarkCompactCollector::MarkingState* marking_state, MinorMarkCompactCollector::MarkingWorklist* global_worklist, int task_id) : worklist_(global_worklist, task_id), marking_state_(marking_state) {} V8_INLINE void VisitPointers(HeapObject host, ObjectSlot start, ObjectSlot end) final { VisitPointersImpl(host, start, end); } V8_INLINE void VisitPointers(HeapObject host, MaybeObjectSlot start, MaybeObjectSlot end) final { VisitPointersImpl(host, start, end); } V8_INLINE void VisitPointer(HeapObject host, ObjectSlot slot) final { VisitPointerImpl(host, slot); } V8_INLINE void VisitPointer(HeapObject host, MaybeObjectSlot slot) final { VisitPointerImpl(host, slot); } V8_INLINE void VisitCodeTarget(Code host, RelocInfo* rinfo) final { // Code objects are not expected in new space. UNREACHABLE(); } V8_INLINE void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) final { // Code objects are not expected in new space. UNREACHABLE(); } private: template <typename TSlot> V8_INLINE void VisitPointersImpl(HeapObject host, TSlot start, TSlot end) { for (TSlot slot = start; slot < end; ++slot) { VisitPointer(host, slot); } } template <typename TSlot> V8_INLINE void VisitPointerImpl(HeapObject host, TSlot slot) { typename TSlot::TObject target = *slot; if (Heap::InYoungGeneration(target)) { // Treat weak references as strong. // TODO(marja): Proper weakness handling for minor-mcs. HeapObject target_object = target.GetHeapObject(); MarkObjectViaMarkingWorklist(target_object); } } inline void MarkObjectViaMarkingWorklist(HeapObject object) { if (marking_state_->WhiteToGrey(object)) { // Marking deque overflow is unsupported for the young generation. CHECK(worklist_.Push(object)); } } MinorMarkCompactCollector::MarkingWorklist::View worklist_; MinorMarkCompactCollector::MarkingState* marking_state_; }; void MinorMarkCompactCollector::SetUp() {} void MinorMarkCompactCollector::TearDown() {} MinorMarkCompactCollector::MinorMarkCompactCollector(Heap* heap) : MarkCompactCollectorBase(heap), worklist_(new MinorMarkCompactCollector::MarkingWorklist()), main_marking_visitor_(new YoungGenerationMarkingVisitor( marking_state(), worklist_, kMainMarker)), page_parallel_job_semaphore_(0) { static_assert( kNumMarkers <= MinorMarkCompactCollector::MarkingWorklist::kMaxNumTasks, "more marker tasks than marking deque can handle"); } MinorMarkCompactCollector::~MinorMarkCompactCollector() { delete worklist_; delete main_marking_visitor_; } int MinorMarkCompactCollector::NumberOfParallelMarkingTasks(int pages) { DCHECK_GT(pages, 0); if (!FLAG_minor_mc_parallel_marking) return 1; // Pages are not private to markers but we can still use them to estimate the // amount of marking that is required. const int kPagesPerTask = 2; const int wanted_tasks = Max(1, pages / kPagesPerTask); return Min(NumberOfAvailableCores(), Min(wanted_tasks, MinorMarkCompactCollector::MarkingWorklist::kMaxNumTasks)); } void MinorMarkCompactCollector::CleanupSweepToIteratePages() { for (Page* p : sweep_to_iterate_pages_) { if (p->IsFlagSet(Page::SWEEP_TO_ITERATE)) { p->ClearFlag(Page::SWEEP_TO_ITERATE); non_atomic_marking_state()->ClearLiveness(p); } } sweep_to_iterate_pages_.clear(); } class YoungGenerationMigrationObserver final : public MigrationObserver { public: YoungGenerationMigrationObserver(Heap* heap, MarkCompactCollector* mark_compact_collector) : MigrationObserver(heap), mark_compact_collector_(mark_compact_collector) {} inline void Move(AllocationSpace dest, HeapObject src, HeapObject dst, int size) final { // Migrate color to old generation marking in case the object survived young // generation garbage collection. if (heap_->incremental_marking()->IsMarking()) { DCHECK( heap_->incremental_marking()->atomic_marking_state()->IsWhite(dst)); heap_->incremental_marking()->TransferColor(src, dst); } } protected: base::Mutex mutex_; MarkCompactCollector* mark_compact_collector_; }; class YoungGenerationRecordMigratedSlotVisitor final : public RecordMigratedSlotVisitor { public: explicit YoungGenerationRecordMigratedSlotVisitor( MarkCompactCollector* collector) : RecordMigratedSlotVisitor(collector, nullptr) {} void VisitCodeTarget(Code host, RelocInfo* rinfo) final { UNREACHABLE(); } void VisitEmbeddedPointer(Code host, RelocInfo* rinfo) final { UNREACHABLE(); } private: // Only record slots for host objects that are considered as live by the full // collector. inline bool IsLive(HeapObject object) { return collector_->non_atomic_marking_state()->IsBlack(object); } inline void RecordMigratedSlot(HeapObject host, MaybeObject value, Address slot) final { if (value->IsStrongOrWeak()) { MemoryChunk* p = MemoryChunk::FromAddress(value.ptr()); if (p->InYoungGeneration()) { DCHECK_IMPLIES( p->IsToPage(), p->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION) || p->IsLargePage()); RememberedSet<OLD_TO_NEW>::Insert<AccessMode::NON_ATOMIC>( MemoryChunk::FromHeapObject(host), slot); } else if (p->IsEvacuationCandidate() && IsLive(host)) { RememberedSet<OLD_TO_OLD>::Insert<AccessMode::NON_ATOMIC>( MemoryChunk::FromHeapObject(host), slot); } } } }; void MinorMarkCompactCollector::UpdatePointersAfterEvacuation() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS); PointersUpdatingVisitor updating_visitor; ItemParallelJob updating_job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); CollectNewSpaceArrayBufferTrackerItems(&updating_job); // Create batches of global handles. const int to_space_tasks = CollectToSpaceUpdatingItems(&updating_job); int remembered_set_pages = 0; remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->old_space(), RememberedSetUpdatingMode::OLD_TO_NEW_ONLY); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->code_space(), RememberedSetUpdatingMode::OLD_TO_NEW_ONLY); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->map_space(), RememberedSetUpdatingMode::OLD_TO_NEW_ONLY); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->lo_space(), RememberedSetUpdatingMode::OLD_TO_NEW_ONLY); remembered_set_pages += CollectRememberedSetUpdatingItems( &updating_job, heap()->code_lo_space(), RememberedSetUpdatingMode::OLD_TO_NEW_ONLY); const int remembered_set_tasks = remembered_set_pages == 0 ? 0 : NumberOfParallelPointerUpdateTasks( remembered_set_pages, old_to_new_slots_); const int num_tasks = Max(to_space_tasks, remembered_set_tasks); for (int i = 0; i < num_tasks; i++) { updating_job.AddTask(new PointersUpdatingTask( isolate(), GCTracer::Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_PARALLEL, GCTracer::BackgroundScope:: MINOR_MC_BACKGROUND_EVACUATE_UPDATE_POINTERS)); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_TO_NEW_ROOTS); heap_->IterateRoots(&updating_visitor, VISIT_ALL_IN_MINOR_MC_UPDATE); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_SLOTS); updating_job.Run(); heap()->array_buffer_collector()->FreeAllocations(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_UPDATE_POINTERS_WEAK); EvacuationWeakObjectRetainer evacuation_object_retainer; heap()->ProcessWeakListRoots(&evacuation_object_retainer); // Update pointers from external string table. heap()->UpdateYoungReferencesInExternalStringTable( &UpdateReferenceInExternalStringTableEntry); } } class MinorMarkCompactCollector::RootMarkingVisitor : public RootVisitor { public: explicit RootMarkingVisitor(MinorMarkCompactCollector* collector) : collector_(collector) {} void VisitRootPointer(Root root, const char* description, FullObjectSlot p) final { MarkObjectByPointer(p); } void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) final { for (FullObjectSlot p = start; p < end; ++p) { MarkObjectByPointer(p); } } private: V8_INLINE void MarkObjectByPointer(FullObjectSlot p) { if (!(*p).IsHeapObject()) return; collector_->MarkRootObject(HeapObject::cast(*p)); } MinorMarkCompactCollector* const collector_; }; void MinorMarkCompactCollector::CollectGarbage() { { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_SWEEPING); heap()->mark_compact_collector()->sweeper()->EnsureIterabilityCompleted(); CleanupSweepToIteratePages(); } MarkLiveObjects(); ClearNonLiveReferences(); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { YoungGenerationMarkingVerifier verifier(heap()); verifier.Run(); } #endif // VERIFY_HEAP Evacuate(); #ifdef VERIFY_HEAP if (FLAG_verify_heap) { YoungGenerationEvacuationVerifier verifier(heap()); verifier.Run(); } #endif // VERIFY_HEAP { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARKING_DEQUE); heap()->incremental_marking()->UpdateMarkingWorklistAfterScavenge(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_RESET_LIVENESS); for (Page* p : PageRange(heap()->new_space()->from_space().first_page(), nullptr)) { DCHECK(!p->IsFlagSet(Page::SWEEP_TO_ITERATE)); non_atomic_marking_state()->ClearLiveness(p); if (FLAG_concurrent_marking) { // Ensure that concurrent marker does not track pages that are // going to be unmapped. heap()->concurrent_marking()->ClearMemoryChunkData(p); } } // Since we promote all surviving large objects immediatelly, all remaining // large objects must be dead. // TODO(ulan): Don't free all as soon as we have an intermediate generation. heap()->new_lo_space()->FreeDeadObjects([](HeapObject) { return true; }); } RememberedSet<OLD_TO_NEW>::IterateMemoryChunks( heap(), [](MemoryChunk* chunk) { if (chunk->SweepingDone()) { RememberedSet<OLD_TO_NEW>::FreeEmptyBuckets(chunk); } else { RememberedSet<OLD_TO_NEW>::PreFreeEmptyBuckets(chunk); } }); heap()->account_external_memory_concurrently_freed(); } void MinorMarkCompactCollector::MakeIterable( Page* p, MarkingTreatmentMode marking_mode, FreeSpaceTreatmentMode free_space_mode) { CHECK(!p->IsLargePage()); // We have to clear the full collectors markbits for the areas that we // remove here. MarkCompactCollector* full_collector = heap()->mark_compact_collector(); Address free_start = p->area_start(); for (auto object_and_size : LiveObjectRange<kGreyObjects>(p, marking_state()->bitmap(p))) { HeapObject const object = object_and_size.first; DCHECK(non_atomic_marking_state()->IsGrey(object)); Address free_end = object.address(); if (free_end != free_start) { CHECK_GT(free_end, free_start); size_t size = static_cast<size_t>(free_end - free_start); full_collector->non_atomic_marking_state()->bitmap(p)->ClearRange( p->AddressToMarkbitIndex(free_start), p->AddressToMarkbitIndex(free_end)); if (free_space_mode == ZAP_FREE_SPACE) { ZapCode(free_start, size); } p->heap()->CreateFillerObjectAt(free_start, static_cast<int>(size), ClearRecordedSlots::kNo); } Map map = object.synchronized_map(); int size = object.SizeFromMap(map); free_start = free_end + size; } if (free_start != p->area_end()) { CHECK_GT(p->area_end(), free_start); size_t size = static_cast<size_t>(p->area_end() - free_start); full_collector->non_atomic_marking_state()->bitmap(p)->ClearRange( p->AddressToMarkbitIndex(free_start), p->AddressToMarkbitIndex(p->area_end())); if (free_space_mode == ZAP_FREE_SPACE) { ZapCode(free_start, size); } p->heap()->CreateFillerObjectAt(free_start, static_cast<int>(size), ClearRecordedSlots::kNo); } if (marking_mode == MarkingTreatmentMode::CLEAR) { non_atomic_marking_state()->ClearLiveness(p); p->ClearFlag(Page::SWEEP_TO_ITERATE); } } namespace { // Helper class for pruning the string table. class YoungGenerationExternalStringTableCleaner : public RootVisitor { public: YoungGenerationExternalStringTableCleaner( MinorMarkCompactCollector* collector) : heap_(collector->heap()), marking_state_(collector->non_atomic_marking_state()) {} void VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) override { DCHECK_EQ(static_cast<int>(root), static_cast<int>(Root::kExternalStringsTable)); // Visit all HeapObject pointers in [start, end). for (FullObjectSlot p = start; p < end; ++p) { Object o = *p; if (o.IsHeapObject()) { HeapObject heap_object = HeapObject::cast(o); if (marking_state_->IsWhite(heap_object)) { if (o.IsExternalString()) { heap_->FinalizeExternalString(String::cast(*p)); } else { // The original external string may have been internalized. DCHECK(o.IsThinString()); } // Set the entry to the_hole_value (as deleted). p.store(ReadOnlyRoots(heap_).the_hole_value()); } } } } private: Heap* heap_; MinorMarkCompactCollector::NonAtomicMarkingState* marking_state_; }; // Marked young generation objects and all old generation objects will be // retained. class MinorMarkCompactWeakObjectRetainer : public WeakObjectRetainer { public: explicit MinorMarkCompactWeakObjectRetainer( MinorMarkCompactCollector* collector) : marking_state_(collector->non_atomic_marking_state()) {} Object RetainAs(Object object) override { HeapObject heap_object = HeapObject::cast(object); if (!Heap::InYoungGeneration(heap_object)) return object; // Young generation marking only marks to grey instead of black. DCHECK(!marking_state_->IsBlack(heap_object)); if (marking_state_->IsGrey(heap_object)) { return object; } return Object(); } private: MinorMarkCompactCollector::NonAtomicMarkingState* marking_state_; }; } // namespace void MinorMarkCompactCollector::ClearNonLiveReferences() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_CLEAR); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_CLEAR_STRING_TABLE); // Internalized strings are always stored in old space, so there is no need // to clean them here. YoungGenerationExternalStringTableCleaner external_visitor(this); heap()->external_string_table_.IterateYoung(&external_visitor); heap()->external_string_table_.CleanUpYoung(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_CLEAR_WEAK_LISTS); // Process the weak references. MinorMarkCompactWeakObjectRetainer retainer(this); heap()->ProcessYoungWeakReferences(&retainer); } } void MinorMarkCompactCollector::EvacuatePrologue() { NewSpace* new_space = heap()->new_space(); // Append the list of new space pages to be processed. for (Page* p : PageRange(new_space->first_allocatable_address(), new_space->top())) { new_space_evacuation_pages_.push_back(p); } new_space->Flip(); new_space->ResetLinearAllocationArea(); heap()->new_lo_space()->Flip(); heap()->new_lo_space()->ResetPendingObject(); } void MinorMarkCompactCollector::EvacuateEpilogue() { heap()->new_space()->set_age_mark(heap()->new_space()->top()); // Give pages that are queued to be freed back to the OS. heap()->memory_allocator()->unmapper()->FreeQueuedChunks(); } UpdatingItem* MinorMarkCompactCollector::CreateToSpaceUpdatingItem( MemoryChunk* chunk, Address start, Address end) { return new ToSpaceUpdatingItem<NonAtomicMarkingState>( chunk, start, end, non_atomic_marking_state()); } UpdatingItem* MinorMarkCompactCollector::CreateRememberedSetUpdatingItem( MemoryChunk* chunk, RememberedSetUpdatingMode updating_mode) { return new RememberedSetUpdatingItem<NonAtomicMarkingState>( heap(), non_atomic_marking_state(), chunk, updating_mode); } class MarkingItem; class PageMarkingItem; class RootMarkingItem; class YoungGenerationMarkingTask; class MarkingItem : public ItemParallelJob::Item { public: ~MarkingItem() override = default; virtual void Process(YoungGenerationMarkingTask* task) = 0; }; class YoungGenerationMarkingTask : public ItemParallelJob::Task { public: YoungGenerationMarkingTask( Isolate* isolate, MinorMarkCompactCollector* collector, MinorMarkCompactCollector::MarkingWorklist* global_worklist, int task_id) : ItemParallelJob::Task(isolate), collector_(collector), marking_worklist_(global_worklist, task_id), marking_state_(collector->marking_state()), visitor_(marking_state_, global_worklist, task_id) { local_live_bytes_.reserve(isolate->heap()->new_space()->Capacity() / Page::kPageSize); } void RunInParallel(Runner runner) override { if (runner == Runner::kForeground) { TRACE_GC(collector_->heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK_PARALLEL); ProcessItems(); } else { TRACE_BACKGROUND_GC( collector_->heap()->tracer(), GCTracer::BackgroundScope::MINOR_MC_BACKGROUND_MARKING); ProcessItems(); } } void MarkObject(Object object) { if (!Heap::InYoungGeneration(object)) return; HeapObject heap_object = HeapObject::cast(object); if (marking_state_->WhiteToGrey(heap_object)) { const int size = visitor_.Visit(heap_object); IncrementLiveBytes(heap_object, size); } } private: void ProcessItems() { double marking_time = 0.0; { TimedScope scope(&marking_time); MarkingItem* item = nullptr; while ((item = GetItem<MarkingItem>()) != nullptr) { item->Process(this); item->MarkFinished(); EmptyLocalMarkingWorklist(); } EmptyMarkingWorklist(); DCHECK(marking_worklist_.IsLocalEmpty()); FlushLiveBytes(); } if (FLAG_trace_minor_mc_parallel_marking) { PrintIsolate(collector_->isolate(), "marking[%p]: time=%f\n", static_cast<void*>(this), marking_time); } } void EmptyLocalMarkingWorklist() { HeapObject object; while (marking_worklist_.Pop(&object)) { const int size = visitor_.Visit(object); IncrementLiveBytes(object, size); } } void EmptyMarkingWorklist() { HeapObject object; while (marking_worklist_.Pop(&object)) { const int size = visitor_.Visit(object); IncrementLiveBytes(object, size); } } void IncrementLiveBytes(HeapObject object, intptr_t bytes) { local_live_bytes_[Page::FromHeapObject(object)] += bytes; } void FlushLiveBytes() { for (auto pair : local_live_bytes_) { marking_state_->IncrementLiveBytes(pair.first, pair.second); } } MinorMarkCompactCollector* collector_; MinorMarkCompactCollector::MarkingWorklist::View marking_worklist_; MinorMarkCompactCollector::MarkingState* marking_state_; YoungGenerationMarkingVisitor visitor_; std::unordered_map<Page*, intptr_t, Page::Hasher> local_live_bytes_; }; class PageMarkingItem : public MarkingItem { public: explicit PageMarkingItem(MemoryChunk* chunk, std::atomic<int>* global_slots) : chunk_(chunk), global_slots_(global_slots), slots_(0) {} ~PageMarkingItem() override { *global_slots_ = *global_slots_ + slots_; } void Process(YoungGenerationMarkingTask* task) override { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "PageMarkingItem::Process"); base::MutexGuard guard(chunk_->mutex()); MarkUntypedPointers(task); MarkTypedPointers(task); } private: inline Heap* heap() { return chunk_->heap(); } void MarkUntypedPointers(YoungGenerationMarkingTask* task) { InvalidatedSlotsFilter filter = InvalidatedSlotsFilter::OldToNew(chunk_); RememberedSet<OLD_TO_NEW>::Iterate( chunk_, [this, task, &filter](MaybeObjectSlot slot) { if (!filter.IsValid(slot.address())) return REMOVE_SLOT; return CheckAndMarkObject(task, slot); }, SlotSet::PREFREE_EMPTY_BUCKETS); } void MarkTypedPointers(YoungGenerationMarkingTask* task) { RememberedSet<OLD_TO_NEW>::IterateTyped( chunk_, [=](SlotType slot_type, Address slot) { return UpdateTypedSlotHelper::UpdateTypedSlot( heap(), slot_type, slot, [this, task](FullMaybeObjectSlot slot) { return CheckAndMarkObject(task, slot); }); }); } template <typename TSlot> V8_INLINE SlotCallbackResult CheckAndMarkObject(YoungGenerationMarkingTask* task, TSlot slot) { static_assert( std::is_same<TSlot, FullMaybeObjectSlot>::value || std::is_same<TSlot, MaybeObjectSlot>::value, "Only FullMaybeObjectSlot and MaybeObjectSlot are expected here"); MaybeObject object = *slot; if (Heap::InYoungGeneration(object)) { // Marking happens before flipping the young generation, so the object // has to be in a to page. DCHECK(Heap::InToPage(object)); HeapObject heap_object; bool success = object.GetHeapObject(&heap_object); USE(success); DCHECK(success); task->MarkObject(heap_object); slots_++; return KEEP_SLOT; } return REMOVE_SLOT; } MemoryChunk* chunk_; std::atomic<int>* global_slots_; int slots_; }; void MinorMarkCompactCollector::MarkRootSetInParallel( RootMarkingVisitor* root_visitor) { std::atomic<int> slots; { ItemParallelJob job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); // Seed the root set (roots + old->new set). { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK_SEED); isolate()->global_handles()->IdentifyWeakUnmodifiedObjects( &JSObject::IsUnmodifiedApiObject); heap()->IterateRoots(root_visitor, VISIT_ALL_IN_MINOR_MC_MARK); // Create items for each page. RememberedSet<OLD_TO_NEW>::IterateMemoryChunks( heap(), [&job, &slots](MemoryChunk* chunk) { job.AddItem(new PageMarkingItem(chunk, &slots)); }); } // Add tasks and run in parallel. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK_ROOTS); const int new_space_pages = static_cast<int>(heap()->new_space()->Capacity()) / Page::kPageSize; const int num_tasks = NumberOfParallelMarkingTasks(new_space_pages); for (int i = 0; i < num_tasks; i++) { job.AddTask( new YoungGenerationMarkingTask(isolate(), this, worklist(), i)); } job.Run(); DCHECK(worklist()->IsEmpty()); } } old_to_new_slots_ = slots; } void MinorMarkCompactCollector::MarkLiveObjects() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK); PostponeInterruptsScope postpone(isolate()); RootMarkingVisitor root_visitor(this); MarkRootSetInParallel(&root_visitor); // Mark rest on the main thread. { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK_WEAK); ProcessMarkingWorklist(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_MARK_GLOBAL_HANDLES); isolate()->global_handles()->MarkYoungWeakUnmodifiedObjectsPending( &IsUnmarkedObjectForYoungGeneration); isolate()->global_handles()->IterateYoungWeakUnmodifiedRootsForFinalizers( &root_visitor); isolate() ->global_handles() ->IterateYoungWeakUnmodifiedRootsForPhantomHandles( &root_visitor, &IsUnmarkedObjectForYoungGeneration); ProcessMarkingWorklist(); } } void MinorMarkCompactCollector::ProcessMarkingWorklist() { MarkingWorklist::View marking_worklist(worklist(), kMainMarker); HeapObject object; while (marking_worklist.Pop(&object)) { DCHECK(!object.IsFiller()); DCHECK(object.IsHeapObject()); DCHECK(heap()->Contains(object)); DCHECK(non_atomic_marking_state()->IsGrey(object)); main_marking_visitor()->Visit(object); } DCHECK(marking_worklist.IsLocalEmpty()); } void MinorMarkCompactCollector::Evacuate() { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE); base::MutexGuard guard(heap()->relocation_mutex()); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_PROLOGUE); EvacuatePrologue(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_COPY); EvacuatePagesInParallel(); } UpdatePointersAfterEvacuation(); { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_REBALANCE); if (!heap()->new_space()->Rebalance()) { heap()->FatalProcessOutOfMemory("NewSpace::Rebalance"); } } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_CLEAN_UP); for (Page* p : new_space_evacuation_pages_) { if (p->IsFlagSet(Page::PAGE_NEW_NEW_PROMOTION) || p->IsFlagSet(Page::PAGE_NEW_OLD_PROMOTION)) { p->ClearFlag(Page::PAGE_NEW_NEW_PROMOTION); p->ClearFlag(Page::PAGE_NEW_OLD_PROMOTION); p->SetFlag(Page::SWEEP_TO_ITERATE); sweep_to_iterate_pages_.push_back(p); } } new_space_evacuation_pages_.clear(); } { TRACE_GC(heap()->tracer(), GCTracer::Scope::MINOR_MC_EVACUATE_EPILOGUE); EvacuateEpilogue(); } } namespace { class YoungGenerationEvacuator : public Evacuator { public: explicit YoungGenerationEvacuator(MinorMarkCompactCollector* collector) : Evacuator(collector->heap(), &record_visitor_), record_visitor_(collector->heap()->mark_compact_collector()), collector_(collector) {} GCTracer::BackgroundScope::ScopeId GetBackgroundTracingScope() override { return GCTracer::BackgroundScope::MINOR_MC_BACKGROUND_EVACUATE_COPY; } GCTracer::Scope::ScopeId GetTracingScope() override { return GCTracer::Scope::MINOR_MC_EVACUATE_COPY_PARALLEL; } protected: void RawEvacuatePage(MemoryChunk* chunk, intptr_t* live_bytes) override; YoungGenerationRecordMigratedSlotVisitor record_visitor_; MinorMarkCompactCollector* collector_; }; void YoungGenerationEvacuator::RawEvacuatePage(MemoryChunk* chunk, intptr_t* live_bytes) { TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.gc"), "YoungGenerationEvacuator::RawEvacuatePage"); MinorMarkCompactCollector::NonAtomicMarkingState* marking_state = collector_->non_atomic_marking_state(); *live_bytes = marking_state->live_bytes(chunk); switch (ComputeEvacuationMode(chunk)) { case kObjectsNewToOld: LiveObjectVisitor::VisitGreyObjectsNoFail( chunk, marking_state, &new_space_visitor_, LiveObjectVisitor::kClearMarkbits); // ArrayBufferTracker will be updated during pointers updating. break; case kPageNewToOld: LiveObjectVisitor::VisitGreyObjectsNoFail( chunk, marking_state, &new_to_old_page_visitor_, LiveObjectVisitor::kKeepMarking); new_to_old_page_visitor_.account_moved_bytes( marking_state->live_bytes(chunk)); if (!chunk->IsLargePage()) { // TODO(mlippautz): If cleaning array buffers is too slow here we can // delay it until the next GC. ArrayBufferTracker::FreeDead(static_cast<Page*>(chunk), marking_state); if (heap()->ShouldZapGarbage()) { collector_->MakeIterable(static_cast<Page*>(chunk), MarkingTreatmentMode::KEEP, ZAP_FREE_SPACE); } else if (heap()->incremental_marking()->IsMarking()) { // When incremental marking is on, we need to clear the mark bits of // the full collector. We cannot yet discard the young generation mark // bits as they are still relevant for pointers updating. collector_->MakeIterable(static_cast<Page*>(chunk), MarkingTreatmentMode::KEEP, IGNORE_FREE_SPACE); } } break; case kPageNewToNew: LiveObjectVisitor::VisitGreyObjectsNoFail( chunk, marking_state, &new_to_new_page_visitor_, LiveObjectVisitor::kKeepMarking); new_to_new_page_visitor_.account_moved_bytes( marking_state->live_bytes(chunk)); DCHECK(!chunk->IsLargePage()); // TODO(mlippautz): If cleaning array buffers is too slow here we can // delay it until the next GC. ArrayBufferTracker::FreeDead(static_cast<Page*>(chunk), marking_state); if (heap()->ShouldZapGarbage()) { collector_->MakeIterable(static_cast<Page*>(chunk), MarkingTreatmentMode::KEEP, ZAP_FREE_SPACE); } else if (heap()->incremental_marking()->IsMarking()) { // When incremental marking is on, we need to clear the mark bits of // the full collector. We cannot yet discard the young generation mark // bits as they are still relevant for pointers updating. collector_->MakeIterable(static_cast<Page*>(chunk), MarkingTreatmentMode::KEEP, IGNORE_FREE_SPACE); } break; case kObjectsOldToOld: UNREACHABLE(); } } } // namespace void MinorMarkCompactCollector::EvacuatePagesInParallel() { ItemParallelJob evacuation_job(isolate()->cancelable_task_manager(), &page_parallel_job_semaphore_); intptr_t live_bytes = 0; for (Page* page : new_space_evacuation_pages_) { intptr_t live_bytes_on_page = non_atomic_marking_state()->live_bytes(page); if (live_bytes_on_page == 0 && !page->contains_array_buffers()) continue; live_bytes += live_bytes_on_page; if (ShouldMovePage(page, live_bytes_on_page)) { if (page->IsFlagSet(MemoryChunk::NEW_SPACE_BELOW_AGE_MARK)) { EvacuateNewSpacePageVisitor<NEW_TO_OLD>::Move(page); } else { EvacuateNewSpacePageVisitor<NEW_TO_NEW>::Move(page); } } evacuation_job.AddItem(new EvacuationItem(page)); } // Promote young generation large objects. for (auto it = heap()->new_lo_space()->begin(); it != heap()->new_lo_space()->end();) { LargePage* current = *it; it++; HeapObject object = current->GetObject(); DCHECK(!non_atomic_marking_state_.IsBlack(object)); if (non_atomic_marking_state_.IsGrey(object)) { heap_->lo_space()->PromoteNewLargeObject(current); current->SetFlag(Page::PAGE_NEW_OLD_PROMOTION); evacuation_job.AddItem(new EvacuationItem(current)); } } if (evacuation_job.NumberOfItems() == 0) return; YoungGenerationMigrationObserver observer(heap(), heap()->mark_compact_collector()); CreateAndExecuteEvacuationTasks<YoungGenerationEvacuator>( this, &evacuation_job, &observer, live_bytes); } int MinorMarkCompactCollector::CollectNewSpaceArrayBufferTrackerItems( ItemParallelJob* job) { int pages = 0; for (Page* p : new_space_evacuation_pages_) { if (Evacuator::ComputeEvacuationMode(p) == Evacuator::kObjectsNewToOld) { if (p->local_tracker() == nullptr) continue; pages++; job->AddItem(new ArrayBufferTrackerUpdatingItem( p, ArrayBufferTrackerUpdatingItem::kRegular)); } } return pages; } #endif // ENABLE_MINOR_MC } // namespace internal } // namespace v8
#include <catch2/catch.hpp> #include "nucleus/memory/scoped_ptr.h" namespace nu { namespace { struct S { static I32 s_constructed; static I32 s_destructed; static void reset() { s_constructed = 0; s_destructed = 0; } int i; S() : i(0) { ++s_constructed; } explicit S(I32 i_) : i(i_) { ++s_constructed; } ~S() { ++s_destructed; } }; // static I32 S::s_constructed = 0; I32 S::s_destructed = 0; } // namespace TEST_CASE("default initialized pointers is owning a null") { S::reset(); ScopedPtr<S> p1; REQUIRE(p1.get() == nullptr); const ScopedPtr<S> p2; REQUIRE(p2.get() == nullptr); } TEST_CASE("can own a pointer") { S::reset(); { ScopedPtr<S> p1{new S{10}}; REQUIRE(p1.get()->i == 10); } REQUIRE(S::s_constructed == 1); REQUIRE(S::s_destructed == 1); } TEST_CASE("reset") { S::reset(); SECTION("can reset from a pointer") { ScopedPtr<S> p1; REQUIRE(p1.get() == nullptr); p1.reset(new S{20}); REQUIRE(p1.get()->i == 20); p1.reset(); REQUIRE(p1.get() == nullptr); REQUIRE(S::s_constructed == 1); REQUIRE(S::s_destructed == 1); } } TEST_CASE("move") { S::reset(); SECTION("can be moved by construction") { { ScopedPtr<S> p1{new S{20}}; ScopedPtr<S> p2{std::move(p1)}; REQUIRE(p2.get()->i == 20); } REQUIRE(S::s_constructed == 1); REQUIRE(S::s_destructed == 1); } } } // namespace nu
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include "graph/planner/PlannersRegister.h" #include "graph/planner/Planner.h" #include "graph/planner/SequentialPlanner.h" #include "graph/planner/match/LabelIndexSeek.h" #include "graph/planner/match/MatchPlanner.h" #include "graph/planner/match/PropIndexSeek.h" #include "graph/planner/match/ScanSeek.h" #include "graph/planner/match/StartVidFinder.h" #include "graph/planner/match/VertexIdSeek.h" #include "graph/planner/ngql/FetchEdgesPlanner.h" #include "graph/planner/ngql/FetchVerticesPlanner.h" #include "graph/planner/ngql/GoPlanner.h" #include "graph/planner/ngql/LookupPlanner.h" #include "graph/planner/ngql/MaintainPlanner.h" #include "graph/planner/ngql/PathPlanner.h" #include "graph/planner/ngql/SubgraphPlanner.h" namespace nebula { namespace graph { void PlannersRegister::registerPlanners() { registerDDL(); registerSequential(); registerMatch(); } void PlannersRegister::registerDDL() { { auto& planners = Planner::plannersMap()[Sentence::Kind::kAlterTag]; planners.emplace_back(&AlterTagPlanner::match, &AlterTagPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kAlterEdge]; planners.emplace_back(&AlterEdgePlanner::match, &AlterEdgePlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kCreateTag]; planners.emplace_back(&CreateTagPlanner::match, &CreateTagPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kCreateEdge]; planners.emplace_back(&CreateEdgePlanner::match, &CreateEdgePlanner::make); } } void PlannersRegister::registerSequential() { { auto& planners = Planner::plannersMap()[Sentence::Kind::kSequential]; planners.emplace_back(&SequentialPlanner::match, &SequentialPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kFindPath]; planners.emplace_back(&PathPlanner::match, &PathPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kGo]; planners.emplace_back(&GoPlanner::match, &GoPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kLookup]; planners.emplace_back(&LookupPlanner::match, &LookupPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kGetSubgraph]; planners.emplace_back(&SubgraphPlanner::match, &SubgraphPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kFetchVertices]; planners.emplace_back(&FetchVerticesPlanner::match, &FetchVerticesPlanner::make); } { auto& planners = Planner::plannersMap()[Sentence::Kind::kFetchEdges]; planners.emplace_back(&FetchEdgesPlanner::match, &FetchEdgesPlanner::make); } } void PlannersRegister::registerMatch() { auto& planners = Planner::plannersMap()[Sentence::Kind::kMatch]; planners.emplace_back(&MatchPlanner::match, &MatchPlanner::make); auto& startVidFinders = StartVidFinder::finders(); // MATCH(n) WHERE id(n) = value RETURN n startVidFinders.emplace_back(&VertexIdSeek::make); // MATCH(n:Tag{prop:value}) RETURN n // MATCH(n:Tag) WHERE n.prop = value RETURN n startVidFinders.emplace_back(&PropIndexSeek::make); // seek by tag or edge(index) // MATCH(n: tag) RETURN n // MATCH(s)-[:edge]->(e) RETURN e startVidFinders.emplace_back(&LabelIndexSeek::make); // Scan the start vertex directly // Now we hard code the order of match rules before CBO, // put scan rule at the last for we assume it's most inefficient startVidFinders.emplace_back(&ScanSeek::make); } } // namespace graph } // namespace nebula
/* * * Copyright (C) 2000-2021, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsign * * Author: Marco Eichelberg * * Purpose: Create and Verify DICOM Digital Signatures * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmdata/cmdlnarg.h" #include "dcmtk/oflog/oflog.h" #include "dcmtk/ofstd/ofconapp.h" #include "dcmtk/dcmdata/dcuid.h" /* for dcmtk version name */ #ifdef WITH_ZLIB #include <zlib.h> /* for zlibVersion() */ #endif #define OFFIS_CONSOLE_APPLICATION "dcmsign" static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v" OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $"; #define APPLICATION_ABSTRACT "Sign and Verify DICOM Files" #ifdef WITH_OPENSSL #include "dcmtk/dcmsign/dcsignat.h" #include "dcmtk/dcmsign/dcsighlp.h" #include "dcmtk/dcmsign/sinullpr.h" #include "dcmtk/dcmsign/sibrsapr.h" #include "dcmtk/dcmsign/siautopr.h" #include "dcmtk/dcmsign/sicreapr.h" #include "dcmtk/dcmsign/sisrpr.h" #include "dcmtk/dcmsign/sisrvpr.h" #include "dcmtk/dcmsign/simac.h" #include "dcmtk/dcmsign/simdmac.h" #include "dcmtk/dcmsign/siprivat.h" #include "dcmtk/dcmsign/sicert.h" #include "dcmtk/dcmsign/sitsfs.h" #include "dcmtk/dcmsign/sicertvf.h" #include "dcmtk/dcmsign/siexit.h" #include "dcmtk/dcmdata/dctk.h" BEGIN_EXTERN_C #include <openssl/x509.h> #include <openssl/evp.h> /* for OPENSSL_NO_EC */ END_EXTERN_C // ******************************************** enum DcmSignOperation { DSO_verify, DSO_sign, DSO_signItem, DSO_insertTimestamp, DSO_remove, DSO_removeAll }; #define SHORTCOL 4 #define LONGCOL 21 int main(int argc, char *argv[]) { DcmSignature::initializeLibrary(); // initialize dcmsign const char * opt_certfile = NULL; OFCmdUnsignedInt opt_filepad = 0; E_FileReadMode opt_readMode = ERM_autoDetect; const char * opt_ifname = NULL; E_TransferSyntax opt_ixfer = EXS_Unknown; OFCmdUnsignedInt opt_itempad = 0; const char * opt_keyfile = NULL; // private key file int opt_keyFileFormat = X509_FILETYPE_PEM; // file format for certificates and private keys const char * opt_location = NULL; // location (path) within dataset SiMAC * opt_mac = NULL; // MAC object E_EncodingType opt_oenctype = EET_ExplicitLength; const char * opt_ofname = NULL; E_GrpLenEncoding opt_oglenc = EGL_recalcGL; E_PaddingEncoding opt_opadenc = EPD_noChange; DcmSignOperation opt_operation = DSO_verify; // command to execute E_TransferSyntax opt_oxfer = EXS_Unknown; const char * opt_passwd = NULL; // password for private key SiSecurityProfile * opt_profile = NULL; // security profile const char * opt_tagFile = NULL; // text file with attribute tags DcmAttributeTag * opt_tagList = NULL; // list of attribute tags E_TransferSyntax opt_signatureXfer = EXS_Unknown; FILE * opt_dumpFile = NULL; SiTimeStampFS * opt_timeStamp = NULL; const char * opt_ts_queryfile = NULL; const char * opt_ts_responsefile = NULL; const char * opt_ts_uidfile = NULL; const char * opt_ts_policyoid = NULL; E_SignatureVerificationPolicy opt_verificationPolicy = ESVP_verifyIfPresent; E_TimestampVerificationPolicy opt_timestampPolicy = ETVP_verifyTSIfPresent; SiCertificateVerifier certVerifier; DcmDataset *dataset = NULL; SiCertificate cert; SiPrivateKey key; OFCondition sicond; DcmFileFormat fileformat; SiSignaturePurpose::E_SignaturePurposeType opt_sigPurpose = SiSignaturePurpose::ESP_none; int result = EXITCODE_NO_ERROR; OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION , APPLICATION_ABSTRACT, rcsid); OFCommandLine cmd; cmd.setOptionColumns(LONGCOL, SHORTCOL); cmd.setParamColumn(LONGCOL + SHORTCOL + 4); cmd.addParam("dcmfile-in", "DICOM input filename to be processed"); cmd.addParam("dcmfile-out", "DICOM output filename", OFCmdParam::PM_Optional); cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2); cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive); cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive); OFLog::addOptions(cmd); cmd.addGroup("input options:"); cmd.addSubGroup("input file format:"); cmd.addOption("--read-file", "+f", "read file format or data set (default)"); cmd.addOption("--read-file-only", "+fo", "read file format only"); cmd.addOption("--read-dataset", "-f", "read data set without file meta information"); cmd.addSubGroup("input transfer syntax:", LONGCOL, SHORTCOL); cmd.addOption("--read-xfer-auto", "-t=", "use TS recognition (default)"); cmd.addOption("--read-xfer-detect", "-td", "ignore TS specified in the file meta header"); cmd.addOption("--read-xfer-little", "-te", "read with explicit VR little endian TS"); cmd.addOption("--read-xfer-big", "-tb", "read with explicit VR big endian TS"); cmd.addOption("--read-xfer-implicit", "-ti", "read with implicit VR little endian TS"); cmd.addSubGroup("handling of defined length UN elements:"); cmd.addOption("--retain-un", "-uc", "retain elements as UN (default)"); cmd.addOption("--convert-un", "+uc", "convert to real VR if known"); cmd.addGroup("signature commands:", LONGCOL, SHORTCOL + 2); cmd.addOption("--verify", "verify all signatures (default)"); cmd.addOption("--sign", "+s", 2, "[p]rivate key file, [c]ertificate file: string", "create signature in main object"); cmd.addOption("--sign-item", "+si", 3, "[k]eyfile, [c]ertfile, [i]tem location: string", "create signature in sequence item"); cmd.addOption("--insert-timestamp", "+t", 3, "ts[q]file, ts[r]file [u]idfile: string", "insert certified timestamp from ts response r\n" "from timestamp query q at signature UID u"); cmd.addOption("--remove", "+r", 1, "[s]ignature UID: string", "remove signature"); cmd.addOption("--remove-all", "+ra", "remove all signatures from data set"); cmd.addGroup("general signature options:"); cmd.addSubGroup("key and certificate file format:"); cmd.addOption("--pem-keys", "-pem", "read keys/certificates as PEM file (default)"); cmd.addOption("--der-keys", "-der", "read keys/certificates as DER file"); cmd.addSubGroup("signature format:"); cmd.addOption("--format-new", "-fn", "use correct DICOM signature format (default)"); cmd.addOption("--format-old", "-fo", "use old (pre-3.5.4) DCMTK signature format"); cmd.addGroup("signature verification options (only with --verify):"); cmd.addSubGroup("signature verification:"); cmd.addOption("--verify-if-present", "+rv", "verify signatures if present, pass otherwise\n(default)"); cmd.addOption("--require-sig", "+rg", "fail if no signature at all is present"); cmd.addOption("--require-creator", "+rc", "fail if no creator RSA signature is present"); cmd.addOption("--require-auth", "+ru", "fail if no auth RSA signature is present"); cmd.addOption("--require-sr", "+rs", "fail if no SR RSA signature is present"); cmd.addSubGroup("timestamp verification:"); cmd.addOption("--verify-ts", "+tv", "verify certified timestamp if present (default)"); cmd.addOption("--ignore-ts", "-tv", "ignore certified timestamps"); cmd.addOption("--require-ts", "+tr", "fail if no certified timestamp is present"); cmd.addSubGroup("certification authority:"); cmd.addOption("--add-cert-file", "+cf", 1, "[f]ilename: string", "add trusted certificate file to cert store"); cmd.addOption("--add-ucert-file", "+uf", 1, "[f]ilename: string", "add untrusted intermediate certificate file"); cmd.addOption("--add-cert-dir", "+cd", 1, "[d]irectory: string", "add certificates in d to cert store"); cmd.addOption("--add-crl-file", "+cr", 1, "[f]ilename: string", "add certificate revocation list file\n(implies --enable-crl-vfy)"); cmd.addOption("--enable-crl-vfy", "+cl", "enable CRL verification"); cmd.addGroup("signature creation options (only with --sign or --sign-item):"); cmd.addSubGroup("private key password:"); cmd.addOption("--std-passwd", "+ps", "prompt user to type password on stdin (default)"); cmd.addOption("--use-passwd", "+pw", 1, "[p]assword: string ", "use specified password"); cmd.addOption("--null-passwd", "-pw", "use empty string as password"); cmd.addSubGroup("digital signature profile:"); cmd.addOption("--profile-none", "-pf", "don't enforce any signature profile (default)"); cmd.addOption("--profile-base", "+pb", "enforce base RSA signature profile"); cmd.addOption("--profile-creator", "+pc", "enforce creator RSA signature profile"); cmd.addOption("--profile-auth", "+pa", "enforce authorization signature profile"); cmd.addOption("--profile-sr", "+pr", "enforce SR RSA signature profile"); cmd.addOption("--profile-srv" , "+pv", "enforce SR RSA signature profile (verification)"); cmd.addSubGroup("MAC algorithm:"); cmd.addOption("--mac-ripemd160", "+mr", "use RIPEMD 160 (default)"); cmd.addOption("--mac-sha1", "+ms", "use SHA-1 (not recommended)"); cmd.addOption("--mac-md5", "+mm", "use MD5 (not recommended)"); cmd.addOption("--mac-sha256", "+m2", "use SHA-256"); cmd.addOption("--mac-sha384", "+m3", "use SHA-384"); cmd.addOption("--mac-sha512", "+m5", "use SHA-512"); cmd.addSubGroup("signature purpose:"); cmd.addOption("--list-purposes", "+lp", "show list of signature purpose codes and exit", OFCommandLine::AF_Exclusive); cmd.addOption("--no-sig-purpose", "-sp", "do not add signature purpose (default)"); cmd.addOption("--sig-purpose", "+sp", 1, "[p]urpose code: integer (1..18)", "add digital signature purpose code p"); cmd.addSubGroup("tag selection:"); cmd.addOption("--tag", "-t", 1, "[t]ag: \"gggg,eeee\" or dictionary name", "sign only specified tag\n(this option can be specified multiple times)"); cmd.addOption("--tag-file", "-tf", 1, "[f]ilename: string", "read list of tags from text file"); cmd.addGroup("timestamp creation options (only with --sign or --sign-item):"); cmd.addSubGroup("timestamp creation:"); cmd.addOption("--timestamp-off", "-ts", "do not create timestamp (default)"); cmd.addOption("--timestamp-file", "+ts", 2, "[t]sq-filename, [u]id-filename: string", "create timestamp query file t and uid file u"); cmd.addSubGroup("timestamp MAC algorithm (only with --timestamp-file):"); cmd.addOption("--ts-mac-sha256", "+tm2", "use SHA-256 (default)"); cmd.addOption("--ts-mac-sha384", "+tm3", "use SHA-384"); cmd.addOption("--ts-mac-sha512", "+tm5", "use SHA-512"); cmd.addOption("--ts-mac-ripemd160", "+tmr", "use RIPEMD 160"); cmd.addOption("--ts-mac-sha1", "+tms", "use SHA-1 (not recommended)"); cmd.addOption("--ts-mac-md5", "+tmm", "use MD5 (not recommended)"); cmd.addSubGroup("timestamp query nonce options (only with --timestamp-file):"); cmd.addOption("--ts-use-nonce", "+tn", "include random nonce (default)"); cmd.addOption("--ts-no-nonce", "-tn", "do not include nonce"); cmd.addSubGroup("timestamp certificate inclusion options (only with --timestamp-file):"); cmd.addOption("--ts-request-cert", "+tc", "request TSA certificate in timestamp (default)"); cmd.addOption("--ts-no-cert", "-tc", "do not request TSA certificate in timestamp"); cmd.addSubGroup("timestamp policy options (only with --timestamp-file):"); cmd.addOption("--ts-no-policy", "-tp", "do not specify ts policy (default)"); cmd.addOption("--ts-policy", "+tp", 1, "[p]olicy-OID: string", "request timestamp policy p"); cmd.addGroup("output options:"); cmd.addSubGroup("output transfer syntax:"); cmd.addOption("--write-xfer-same", "+t=", "write with same TS as input (default)"); cmd.addOption("--write-xfer-little", "+te", "write with explicit VR little endian TS"); cmd.addOption("--write-xfer-big", "+tb", "write with explicit VR big endian TS"); cmd.addOption("--write-xfer-implicit", "+ti", "write with implicit VR little endian TS"); cmd.addSubGroup("length encoding in sequences and items:"); cmd.addOption("--length-explicit", "+e", "write with explicit lengths (default)"); cmd.addOption("--length-undefined", "-e", "write with undefined lengths"); cmd.addSubGroup("other output options:"); cmd.addOption("--dump", "+d", 1, "[f]ilename: string", "dump byte stream fed into the MAC codec to file\n(only with --sign or --sign-item)"); /* evaluate command line */ prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION); if (app.parseCommandLine(cmd, argc, argv)) { /* check exclusive options first */ if (cmd.hasExclusiveOption()) { if (cmd.findOption("--version")) { app.printHeader(OFTrue /*print host identifier*/); COUT << OFendl << "External libraries used:"; #if !defined(WITH_ZLIB) && !defined(WITH_OPENSSL) COUT << " none" << OFendl; #else COUT << OFendl; #endif #ifdef WITH_ZLIB COUT << "- ZLIB, Version " << zlibVersion() << OFendl; #endif #ifdef WITH_OPENSSL #ifdef OPENSSL_NO_EC COUT << "- " << OPENSSL_VERSION_TEXT << ", without ECDSA support" << OFendl; #else COUT << "- " << OPENSSL_VERSION_TEXT << ", with ECDSA support" << OFendl; #endif #endif return EXITCODE_NO_ERROR; } if (cmd.findOption("--list-purposes")) { app.printHeader(OFTrue /*print host identifier*/); SiSignaturePurpose::printSignatureCodes(COUT); return EXITCODE_NO_ERROR; } } /* command line parameters */ cmd.getParam(1, opt_ifname); if (cmd.getParamCount() > 1) cmd.getParam(2, opt_ofname); OFLog::configureFromCommandLine(cmd, app); cmd.beginOptionBlock(); if (cmd.findOption("--read-file")) opt_readMode = ERM_autoDetect; if (cmd.findOption("--read-file-only")) opt_readMode = ERM_fileOnly; if (cmd.findOption("--read-dataset")) opt_readMode = ERM_dataset; cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--read-xfer-auto")) opt_ixfer = EXS_Unknown; if (cmd.findOption("--read-xfer-detect")) dcmAutoDetectDatasetXfer.set(OFTrue); if (cmd.findOption("--read-xfer-little")) { app.checkDependence("--read-xfer-little", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_LittleEndianExplicit; } if (cmd.findOption("--read-xfer-big")) { app.checkDependence("--read-xfer-big", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_BigEndianExplicit; } if (cmd.findOption("--read-xfer-implicit")) { app.checkDependence("--read-xfer-implicit", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_LittleEndianImplicit; } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--retain-un")) dcmEnableUnknownVRConversion.set(OFFalse); if (cmd.findOption("--convert-un")) dcmEnableUnknownVRConversion.set(OFTrue); cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--verify")) { opt_operation = DSO_verify; } if (cmd.findOption("--sign")) { opt_operation = DSO_sign; if (opt_ofname == NULL) app.printError("parameter dcmfile-out required for --sign"); app.checkValue(cmd.getValue(opt_keyfile)); app.checkValue(cmd.getValue(opt_certfile)); } if (cmd.findOption("--sign-item")) { opt_operation = DSO_signItem; if (opt_ofname == NULL) app.printError("parameter dcmfile-out required for --sign-item"); app.checkValue(cmd.getValue(opt_keyfile)); app.checkValue(cmd.getValue(opt_certfile)); app.checkValue(cmd.getValue(opt_location)); } if (cmd.findOption("--insert-timestamp")) { opt_operation = DSO_insertTimestamp; if (opt_ofname == NULL) app.printError("parameter dcmfile-out required for --insert-timestamp"); app.checkValue(cmd.getValue(opt_ts_queryfile)); app.checkValue(cmd.getValue(opt_ts_responsefile)); app.checkValue(cmd.getValue(opt_ts_uidfile)); opt_timeStamp = new SiTimeStampFS(); opt_timeStamp->setTSQFilename(opt_ts_queryfile); opt_timeStamp->setTSRFilename(opt_ts_responsefile); opt_timeStamp->setUIDFilename(opt_ts_uidfile); } if (cmd.findOption("--remove")) { opt_operation = DSO_remove; if (opt_ofname == NULL) app.printError("parameter dcmfile-out required for --remove"); app.checkValue(cmd.getValue(opt_location)); } if (cmd.findOption("--remove-all")) { opt_operation = DSO_removeAll; if (opt_ofname == NULL) app.printError("parameter dcmfile-out required for --remove-all"); } cmd.endOptionBlock(); if ((opt_operation == DSO_verify) && opt_ofname) app.printError("parameter dcmfile-out not allowed for --verify"); cmd.beginOptionBlock(); if (cmd.findOption("--pem-keys")) opt_keyFileFormat = X509_FILETYPE_PEM; if (cmd.findOption("--der-keys")) opt_keyFileFormat = X509_FILETYPE_ASN1; cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--verify-if-present")) { app.checkDependence("--verify-if-present", "--verify", (opt_operation == DSO_verify)); opt_verificationPolicy = ESVP_verifyIfPresent; } if (cmd.findOption("--require-sig")) { app.checkDependence("--require-sig", "--verify", (opt_operation == DSO_verify)); opt_verificationPolicy = ESVP_requireSignature; } if (cmd.findOption("--require-creator")) { app.checkDependence("--require-creator", "--verify", (opt_operation == DSO_verify)); opt_verificationPolicy = ESVP_requireCreatorRSASignature; } if (cmd.findOption("--require-auth")) { app.checkDependence("--require-auth", "--verify", (opt_operation == DSO_verify)); opt_verificationPolicy = ESVP_requireAuthorizationRSASignature; } if (cmd.findOption("--require-sr")) { app.checkDependence("--require-sr", "--verify", (opt_operation == DSO_verify)); opt_verificationPolicy = ESVP_requireSRRSASignature; } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--verify-ts")) { app.checkDependence("--verify-ts", "--verify", (opt_operation == DSO_verify)); opt_timestampPolicy = ETVP_verifyTSIfPresent; } if (cmd.findOption("--ignore-ts")) { app.checkDependence("--ignore-ts", "--verify", (opt_operation == DSO_verify)); opt_timestampPolicy = ETVP_ignoreTS; } if (cmd.findOption("--require-ts")) { app.checkDependence("--require-ts", "--verify", (opt_operation == DSO_verify)); opt_timestampPolicy = ETVP_requireTS; } cmd.endOptionBlock(); if (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_First)) { app.checkDependence("--add-cert-file", "--verify", (opt_operation == DSO_verify)); const char *current = NULL; do { app.checkValue(cmd.getValue(current)); if (certVerifier.addTrustedCertificateFile(current, opt_keyFileFormat).bad()) { DCMSIGN_WARN("unable to load certificate file '" << current << "', ignoring"); } } while (cmd.findOption("--add-cert-file", 0, OFCommandLine::FOM_Next)); } if (cmd.findOption("--add-ucert-file", 0, OFCommandLine::FOM_First)) { app.checkDependence("--add-ucert-file", "--verify", (opt_operation == DSO_verify)); const char *current = NULL; do { app.checkValue(cmd.getValue(current)); if (certVerifier.addUntrustedCertificateFile(current, opt_keyFileFormat).bad()) { DCMSIGN_WARN("unable to load certificate file '" << current << "', ignoring"); } } while (cmd.findOption("--add-ucert-file", 0, OFCommandLine::FOM_Next)); } if (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_First)) { app.checkDependence("--add-cert-dir", "--verify", (opt_operation == DSO_verify)); const char *current = NULL; do { app.checkValue(cmd.getValue(current)); if (certVerifier.addTrustedCertificateDir(current, opt_keyFileFormat).bad()) { DCMSIGN_WARN("unable to load certificates from directory '" << current << "', ignoring"); } } while (cmd.findOption("--add-cert-dir", 0, OFCommandLine::FOM_Next)); } if (cmd.findOption("--add-crl-file", 0, OFCommandLine::FOM_First)) { app.checkDependence("--add-crl-file", "--verify", (opt_operation == DSO_verify)); const char *current = NULL; do { app.checkValue(cmd.getValue(current)); if (certVerifier.addCertificateRevocationList(current, opt_keyFileFormat).bad()) { DCMSIGN_WARN("unable to load CRL file '" << current << "', ignoring"); } } while (cmd.findOption("--add-crl-file", 0, OFCommandLine::FOM_Next)); } if (cmd.findOption("--enable-crl-vfy")) { app.checkDependence("--enable-crl-vfy", "--verify", (opt_operation == DSO_verify)); certVerifier.setCRLverification(OFTrue); } cmd.beginOptionBlock(); if (cmd.findOption("--std-passwd")) { app.checkDependence("--std-passwd", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_passwd = NULL; } if (cmd.findOption("--use-passwd")) { app.checkDependence("--use-passwd", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); app.checkValue(cmd.getValue(opt_passwd)); } if (cmd.findOption("--null-passwd")) { app.checkDependence("--null-passwd", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_passwd = ""; } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--profile-none")) { app.checkDependence("--profile-none", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_profile = new SiNullProfile(); } if (cmd.findOption("--profile-base")) { // the RSA base profile can be used on dataset and item level app.checkDependence("--profile-base", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_profile = new SiBaseRSAProfile(); } if (cmd.findOption("--profile-creator")) { // the creator RSA profile only makes sense when applied on main dataset level app.checkDependence("--profile-creator", "--sign", (opt_operation == DSO_sign)); opt_profile = new SiCreatorProfile(); } if (cmd.findOption("--profile-auth")) { // the authorization RSA profile only makes sense when applied on main dataset level app.checkDependence("--profile-auth", "--sign", (opt_operation == DSO_sign)); opt_profile = new SiAuthorizationProfile(); DCMSIGN_WARN( "The Authorization RSA Digital Signature Profile requires that any\n" "attributes whose values are verifiable by the technician or physician\n" "(e.g., their values are displayed to the technician or physician) must\n" "be included in the signature. Please assure this using --tag options." ); } if (cmd.findOption("--profile-sr")) { // the SR RSA profile only makes sense when applied on main dataset level app.checkDependence("--profile-sr", "--sign", (opt_operation == DSO_sign)); opt_profile = new SiStructuredReportingProfile(); } if (cmd.findOption("--profile-srv")) { // the SR RSA profile only makes sense when applied on main dataset level app.checkDependence("--profile-srv", "--sign", (opt_operation == DSO_sign)); opt_profile = new SiStructuredReportingVerificationProfile(); } cmd.endOptionBlock(); if (opt_profile == NULL) opt_profile = new SiNullProfile(); cmd.beginOptionBlock(); if (cmd.findOption("--mac-ripemd160")) { app.checkDependence("--mac-ripemd160", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_RIPEMD160); } if (cmd.findOption("--mac-sha1")) { app.checkDependence("--mac-sha1", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_SHA1); } if (cmd.findOption("--mac-md5")) { app.checkDependence("--mac-md5", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_MD5); } if (cmd.findOption("--mac-sha256")) { app.checkDependence("--mac-sha256", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_SHA256); } if (cmd.findOption("--mac-sha384")) { app.checkDependence("--mac-sha384", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_SHA384); } if (cmd.findOption("--mac-sha512")) { app.checkDependence("--mac-sha512", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_mac = new SiMDMAC(EMT_SHA512); } cmd.endOptionBlock(); if (opt_mac == NULL) opt_mac = new SiMDMAC(EMT_RIPEMD160); cmd.beginOptionBlock(); if (cmd.findOption("--no-sig-purpose")) { app.checkDependence("--no-sig-purpose", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_sigPurpose = SiSignaturePurpose::ESP_none; } if (cmd.findOption("--sig-purpose")) { app.checkDependence("--sig-purpose", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); OFCmdUnsignedInt val = 0; app.checkValue(cmd.getValueAndCheckMinMax(val, 1, 18)); opt_sigPurpose = SiSignaturePurpose::lookup(OFstatic_cast(size_t, val)); if (opt_sigPurpose == SiSignaturePurpose::ESP_none) { // should never happen DCMSIGN_WARN("unknown digital signature purpose code, ignoring."); } } cmd.endOptionBlock(); if (cmd.findOption("--tag-file")) { app.checkValue(cmd.getValue(opt_tagFile)); opt_tagList = new DcmAttributeTag(DCM_DataElementsSigned); result = DcmSignatureHelper::parseTextFile(opt_tagFile, *opt_tagList); if (result > 0) { DCMSIGN_FATAL("Error while reading tag file '" << opt_tagFile << "', giving up."); goto cleanup; } } if (cmd.findOption("--tag", 0, OFCommandLine::FOM_First)) { const char *current=NULL; if (opt_tagList == NULL) opt_tagList = new DcmAttributeTag(DCM_DataElementsSigned); do { app.checkValue(cmd.getValue(current)); if (! DcmSignatureHelper::addTag(current, *opt_tagList)) { DCMSIGN_FATAL("unknown attribute tag '" << current << "'"); result = EXITCODE_COMMANDLINE_SYNTAX_ERROR; goto cleanup; } } while (cmd.findOption("--tag", 0, OFCommandLine::FOM_Next)); } cmd.beginOptionBlock(); if (cmd.findOption("--format-new")) dcmEnableOldSignatureFormat.set(OFFalse); if (cmd.findOption("--format-old")) dcmEnableOldSignatureFormat.set(OFTrue); cmd.endOptionBlock(); // timestamp command line options cmd.beginOptionBlock(); if (cmd.findOption("--timestamp-off")) { app.checkDependence("--timestamp-off", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); opt_timeStamp = NULL; } if (cmd.findOption("--timestamp-file")) { app.checkDependence("--timestamp-file", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); app.checkValue(cmd.getValue(opt_ts_queryfile)); app.checkValue(cmd.getValue(opt_ts_uidfile)); opt_timeStamp = new SiTimeStampFS(); opt_timeStamp->setTSQFilename(opt_ts_queryfile); opt_timeStamp->setUIDFilename(opt_ts_uidfile); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--ts-mac-sha256")) { app.checkDependence("--ts-mac-sha256", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_SHA256); } if (cmd.findOption("--ts-mac-sha384")) { app.checkDependence("--ts-mac-sha384", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_SHA384); } if (cmd.findOption("--ts-mac-sha512")) { app.checkDependence("--ts-mac-sha512", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_SHA512); } if (cmd.findOption("--ts-mac-ripemd160")) { app.checkDependence("--ts-mac-ripemd160", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_RIPEMD160); } if (cmd.findOption("--ts-mac-sha1")) { app.checkDependence("--ts-mac-sha1", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_SHA1); } if (cmd.findOption("--ts-mac-md5")) { app.checkDependence("--ts-mac-md5", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setMAC(EMT_MD5); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--ts-use-nonce")) { app.checkDependence("--ts-use-nonce", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setNonce(OFTrue); } if (cmd.findOption("--ts-no-nonce")) { app.checkDependence("--ts-no-nonce", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setNonce(OFFalse); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--ts-request-cert")) { app.checkDependence("--ts-request-cert", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setCertificateRequested(OFTrue); } if (cmd.findOption("--ts-no-cert")) { app.checkDependence("--ts-no-cert", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setCertificateRequested(OFFalse); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--ts-no-policy")) { app.checkDependence("--ts-no-policy", "--timestamp-file", (opt_timeStamp != NULL)); opt_timeStamp->setPolicyOID(NULL); } if (cmd.findOption("--ts-policy")) { app.checkDependence("--ts-policy", "--timestamp-file", (opt_timeStamp != NULL)); app.checkValue(cmd.getValue(opt_ts_policyoid)); opt_timeStamp->setPolicyOID(opt_ts_policyoid); } cmd.endOptionBlock(); // output command line options cmd.beginOptionBlock(); if (cmd.findOption("--write-xfer-same")) opt_oxfer = EXS_Unknown; if (cmd.findOption("--write-xfer-little")) opt_oxfer = EXS_LittleEndianExplicit; if (cmd.findOption("--write-xfer-big")) opt_oxfer = EXS_BigEndianExplicit; if (cmd.findOption("--write-xfer-implicit")) opt_oxfer = EXS_LittleEndianImplicit; cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--length-explicit")) opt_oenctype = EET_ExplicitLength; if (cmd.findOption("--length-undefined")) opt_oenctype = EET_UndefinedLength; cmd.endOptionBlock(); if (cmd.findOption("--dump")) { app.checkDependence("--dump", "--sign or --sign-item", (opt_operation == DSO_sign) || (opt_operation == DSO_signItem)); const char *fileName = NULL; app.checkValue(cmd.getValue(fileName)); opt_dumpFile = fopen(fileName, "wb"); if (opt_dumpFile == NULL) { DCMSIGN_FATAL("unable to create dump file '" << fileName << "'"); result = EXITCODE_CANNOT_WRITE_SUPPORT_FILE; goto cleanup; } } } /* print resource identifier */ DCMSIGN_DEBUG(rcsid << OFendl); /* make sure data dictionary is loaded */ if (!dcmDataDict.isDictionaryLoaded()) { DCMSIGN_WARN("no data dictionary loaded, " << "check environment variable: " << DCM_DICT_ENVIRONMENT_VARIABLE); } // open input file if ((opt_ifname == NULL) || (strlen(opt_ifname) == 0)) { DCMSIGN_FATAL("invalid filename: <empty string>"); result = EXITCODE_NO_INPUT_FILES; goto cleanup; } DCMSIGN_INFO("open input file " << opt_ifname); sicond = fileformat.loadFile(opt_ifname, opt_ixfer, EGL_noChange, DCM_MaxReadLength, opt_readMode); if (sicond.bad()) { DCMSIGN_FATAL(sicond.text() << ": reading file: " << opt_ifname); result = EXITCODE_CANNOT_READ_INPUT_FILE; goto cleanup; } dataset = fileformat.getDataset(); if (opt_certfile) { sicond = cert.loadCertificate(opt_certfile, opt_keyFileFormat); if (sicond != EC_Normal) { DCMSIGN_FATAL(sicond.text() << ": while loading certificate file '" << opt_certfile << "'"); result = EXITCODE_CANNOT_READ_INPUT_FILE; goto cleanup; } } if (opt_keyfile) { if (opt_passwd) key.setPrivateKeyPasswd(opt_passwd); sicond = key.loadPrivateKey(opt_keyfile, opt_keyFileFormat); if (sicond != EC_Normal) { DCMSIGN_FATAL(sicond.text() << ": while loading private key file '" << opt_keyfile << "'"); result = EXITCODE_CANNOT_READ_INPUT_FILE; goto cleanup; } } // need to load all data into memory before signing the document, // otherwise the pixel data would be empty for compressed images fileformat.loadAllDataIntoMemory(); // select transfer syntax in which digital signatures are created opt_signatureXfer = dataset->getOriginalXfer(); // use Little Endian Explicit for uncompressed files if ((opt_signatureXfer == EXS_LittleEndianImplicit) || (opt_signatureXfer == EXS_BigEndianExplicit)) opt_signatureXfer = EXS_LittleEndianExplicit; // now do the real work switch (opt_operation) { case DSO_verify: DCMSIGN_INFO("verifying all signatures."); result = DcmSignatureHelper::do_verify(dataset, certVerifier, opt_verificationPolicy, opt_timestampPolicy); if (result != 0) goto cleanup; break; case DSO_sign: DCMSIGN_INFO("create signature in main object."); result = DcmSignatureHelper::do_sign(dataset, key, cert, opt_mac, opt_profile, opt_tagList, opt_signatureXfer, opt_dumpFile, opt_sigPurpose, opt_timeStamp); if (result != 0) goto cleanup; break; case DSO_signItem: DCMSIGN_INFO("create signature in sequence item."); result = DcmSignatureHelper::do_sign_item(dataset, key, cert, opt_mac, opt_profile, opt_tagList, opt_location, opt_signatureXfer, opt_dumpFile, opt_sigPurpose, opt_timeStamp); if (result != 0) goto cleanup; break; case DSO_insertTimestamp: DCMSIGN_INFO("inserting certified timestamp."); result = DcmSignatureHelper::do_insert_ts(dataset, opt_timeStamp); if (result != 0) goto cleanup; break; case DSO_remove: DCMSIGN_INFO("removing signature from sequence item."); result = DcmSignatureHelper::do_remove(dataset, opt_location); if (result != 0) goto cleanup; break; case DSO_removeAll: DCMSIGN_INFO("removing all signatures."); result = DcmSignatureHelper::do_remove_all(dataset); if (result != 0) goto cleanup; break; } if (opt_dumpFile) { if (0 != fclose(opt_dumpFile)) { DCMSIGN_FATAL("Error while closing dump file, content may be incomplete."); } opt_dumpFile = NULL; } if (opt_ofname) { DCMSIGN_INFO("create output file " << opt_ofname); if (opt_oxfer == EXS_Unknown) opt_oxfer = dataset->getOriginalXfer(); DcmXfer opt_oxferSyn(opt_oxfer); if (dataset->chooseRepresentation(opt_oxfer, NULL).bad() || (! dataset->canWriteXfer(opt_oxfer))) { DCMSIGN_FATAL("No conversion to transfer syntax " << opt_oxferSyn.getXferName() << " possible!"); result = EXITCODE_CANNOT_WRITE_OUTPUT_FILE; goto cleanup; } sicond = fileformat.saveFile(opt_ofname, opt_oxfer, opt_oenctype, opt_oglenc, opt_opadenc, OFstatic_cast(Uint32, opt_filepad), OFstatic_cast(Uint32, opt_itempad)); if (sicond.bad()) { DCMSIGN_FATAL(sicond.text() << ": writing file: " << opt_ofname); result = EXITCODE_CANNOT_WRITE_OUTPUT_FILE; goto cleanup; } } cleanup: delete opt_timeStamp; delete opt_mac; delete opt_profile; delete opt_tagList; DcmSignature::cleanupLibrary(); return result; } #else /* WITH_OPENSSL */ int main(int, char *[]) { CERR << rcsid << OFendl << APPLICATION_ABSTRACT << OFendl << OFendl << OFFIS_CONSOLE_APPLICATION " requires the OpenSSL library." << OFendl << "This " OFFIS_CONSOLE_APPLICATION " has been configured and compiled without OpenSSL." << OFendl << "Please reconfigure your system and recompile if appropriate." << OFendl; return EXITCODE_NOOPENSSL; } #endif /* WITH_OPENSSL */
// 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. // // This file contains the definitions of the installer functions that build // the WorkItemList used to install the application. #include "chrome/installer/setup/install_worker.h" #include <oaidl.h> #include <shlobj.h> #include <time.h> #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "base/version.h" #include "base/win/registry.h" #include "base/win/windows_version.h" #include "chrome/common/chrome_constants.h" #include "chrome/installer/setup/install.h" #include "chrome/installer/setup/setup_constants.h" #include "chrome/installer/util/conditional_work_item_list.h" #include "chrome/installer/util/create_reg_key_work_item.h" #include "chrome/installer/util/google_update_constants.h" #include "chrome/installer/util/helper.h" #include "chrome/installer/util/installation_state.h" #include "chrome/installer/util/installer_state.h" #include "chrome/installer/util/install_util.h" #include "chrome/installer/util/l10n_string_util.h" #include "chrome/installer/util/product.h" #include "chrome/installer/util/set_reg_value_work_item.h" #include "chrome/installer/util/shell_util.h" #include "chrome/installer/util/util_constants.h" #include "chrome/installer/util/work_item_list.h" #include "chrome_frame/chrome_tab.h" using base::win::RegKey; namespace installer { // Local helper to call AddRegisterComDllWorkItems for all DLLs in a set of // products managed by a given package. void AddRegisterComDllWorkItemsForPackage(const InstallerState& installer_state, const Version* old_version, const Version& new_version, WorkItemList* work_item_list) { // First collect the list of DLLs to be registered from each product. std::vector<FilePath> com_dll_list; installer_state.AddComDllList(&com_dll_list); // Then, if we got some, attempt to unregister the DLLs from the old // version directory and then re-register them in the new one. // Note that if we are migrating the install directory then we will not // successfully unregister the old DLLs. // TODO(robertshield): See whether we need to fix the migration case. // TODO(robertshield): If we ever remove a DLL from a product, this will // not unregister it on update. We should build the unregistration list from // saved state instead of assuming it is the same as the registration list. if (!com_dll_list.empty()) { if (old_version) { FilePath old_dll_path(installer_state.target_path().AppendASCII( old_version->GetString())); installer::AddRegisterComDllWorkItems(old_dll_path, com_dll_list, installer_state.system_install(), false, // Unregister true, // May fail work_item_list); } FilePath dll_path(installer_state.target_path().AppendASCII( new_version.GetString())); installer::AddRegisterComDllWorkItems(dll_path, com_dll_list, installer_state.system_install(), true, // Register false, // Must succeed. work_item_list); } } void AddInstallerCopyTasks(const InstallerState& installer_state, const FilePath& setup_path, const FilePath& archive_path, const FilePath& temp_path, const Version& new_version, WorkItemList* install_list) { DCHECK(install_list); FilePath installer_dir(installer_state.GetInstallerDirectory(new_version)); install_list->AddCreateDirWorkItem(installer_dir); FilePath exe_dst(installer_dir.Append(setup_path.BaseName())); FilePath archive_dst(installer_dir.Append(archive_path.BaseName())); install_list->AddCopyTreeWorkItem(setup_path.value(), exe_dst.value(), temp_path.value(), WorkItem::ALWAYS); // In the past, we copied rather than moved for system level installs so that // the permissions of %ProgramFiles% would be picked up. Now that |temp_path| // is in %ProgramFiles% for system level installs (and in %LOCALAPPDATA% // otherwise), there is no need to do this for the archive. Setup.exe, on // the other hand, is created elsewhere so it must always be copied. install_list->AddMoveTreeWorkItem(archive_path.value(), archive_dst.value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } // This method adds work items to create (or update) Chrome uninstall entry in // either the Control Panel->Add/Remove Programs list or in the Omaha client // state key if running under an MSI installer. void AddUninstallShortcutWorkItems(const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, WorkItemList* install_list, const Product& product) { HKEY reg_root = installer_state.root_key(); BrowserDistribution* browser_dist = product.distribution(); DCHECK(browser_dist); // When we are installed via an MSI, we need to store our uninstall strings // in the Google Update client state key. We do this even for non-MSI // managed installs to avoid breaking the edge case whereby an MSI-managed // install is updated by a non-msi installer (which would confuse the MSI // machinery if these strings were not also updated). The UninstallString // value placed in the client state key is also used by the mini_installer to // locate the setup.exe instance used for binary patching. // Do not quote the command line for the MSI invocation. FilePath install_path(installer_state.target_path()); FilePath installer_path(installer_state.GetInstallerDirectory(new_version)); installer_path = installer_path.Append(setup_path.BaseName()); CommandLine uninstall_arguments(CommandLine::NO_PROGRAM); AppendUninstallCommandLineFlags(installer_state, product, &uninstall_arguments); // The Chrome uninstallation command serves as the master uninstall command // for Chrome + all other products (i.e. Chrome Frame) that do not have an // uninstall entry in the Add/Remove Programs dialog. We skip this processing // in case of uninstall since this means that Chrome Frame is being // uninstalled, so there's no need to do any looping. if (product.is_chrome() && installer_state.operation() != InstallerState::UNINSTALL) { const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product& p = *products[i]; if (!p.is_chrome() && !p.ShouldCreateUninstallEntry()) p.AppendProductFlags(&uninstall_arguments); } } std::wstring update_state_key(browser_dist->GetStateKey()); install_list->AddCreateRegKeyWorkItem(reg_root, update_state_key); install_list->AddSetRegValueWorkItem(reg_root, update_state_key, installer::kUninstallStringField, installer_path.value(), true); install_list->AddSetRegValueWorkItem(reg_root, update_state_key, installer::kUninstallArgumentsField, uninstall_arguments.GetCommandLineString(), true); // MSI installations will manage their own uninstall shortcuts. if (!installer_state.is_msi() && product.ShouldCreateUninstallEntry()) { // We need to quote the command line for the Add/Remove Programs dialog. CommandLine quoted_uninstall_cmd(installer_path); DCHECK_EQ(quoted_uninstall_cmd.GetCommandLineString()[0], '"'); quoted_uninstall_cmd.AppendArguments(uninstall_arguments, false); std::wstring uninstall_reg = browser_dist->GetUninstallRegPath(); install_list->AddCreateRegKeyWorkItem(reg_root, uninstall_reg); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, installer::kUninstallDisplayNameField, browser_dist->GetAppShortCutName(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, installer::kUninstallStringField, quoted_uninstall_cmd.GetCommandLineString(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"InstallLocation", install_path.value(), true); // DisplayIcon, NoModify and NoRepair std::wstring chrome_icon = ShellUtil::GetChromeIcon( product.distribution(), install_path.Append(installer::kChromeExe).value()); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"DisplayIcon", chrome_icon, true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"NoModify", static_cast<DWORD>(1), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"NoRepair", static_cast<DWORD>(1), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"Publisher", browser_dist->GetPublisherName(), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"Version", ASCIIToWide(new_version.GetString()), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"DisplayVersion", ASCIIToWide(new_version.GetString()), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"InstallDate", InstallUtil::GetCurrentDate(), false); const std::vector<uint16>& version_components = new_version.components(); if (version_components.size() == 4) { // Our version should be in major.minor.build.rev. install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"VersionMajor", static_cast<DWORD>(version_components[2]), true); install_list->AddSetRegValueWorkItem(reg_root, uninstall_reg, L"VersionMinor", static_cast<DWORD>(version_components[3]), true); } } } // Add uninstall-related work items for multi-install scenarios. void AddMultiUninstallWorkItems(const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, WorkItemList* install_list) { DCHECK(installer_state.is_multi_install()); // The mini_installer needs a reliable way to locate setup.exe for diff // updates. For single-installs, the product's ClientState key is consulted // (Chrome's or Chrome Frame's). For multi-installs, the binaries' key is // used. const HKEY reg_root = installer_state.root_key(); std::wstring binaries_state_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); FilePath installer_path( installer_state.GetInstallerDirectory(new_version) .Append(setup_path.BaseName())); install_list->AddCreateRegKeyWorkItem(reg_root, binaries_state_key); install_list->AddSetRegValueWorkItem(reg_root, binaries_state_key, installer::kUninstallStringField, installer_path.value(), true); } // Create Version key for a product (if not already present) and sets the new // product version as the last step. void AddVersionKeyWorkItems(HKEY root, BrowserDistribution* dist, const Version& new_version, bool add_language_identifier, WorkItemList* list) { // Create Version key for each distribution (if not already present) and set // the new product version as the last step. std::wstring version_key(dist->GetVersionKey()); list->AddCreateRegKeyWorkItem(root, version_key); std::wstring product_name(dist->GetAppShortCutName()); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegNameField, product_name, true); // overwrite name also list->AddSetRegValueWorkItem(root, version_key, google_update::kRegOopcrashesField, static_cast<DWORD>(1), false); // set during first install if (add_language_identifier) { // Write the language identifier of the current translation. Omaha's set of // languages is a superset of Chrome's set of translations with this one // exception: what Chrome calls "en-us", Omaha calls "en". sigh. std::wstring language(GetCurrentTranslation()); if (LowerCaseEqualsASCII(language, "en-us")) language.resize(2); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegLangField, language, false); // do not overwrite language } list->AddSetRegValueWorkItem(root, version_key, google_update::kRegVersionField, ASCIIToWide(new_version.GetString()), true); // overwrite version } void AddProductSpecificWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, WorkItemList* list) { const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product& p = *products[i]; if (p.is_chrome_frame()) { AddChromeFrameWorkItems(original_state, installer_state, setup_path, new_version, p, list); } } } // Mirror oeminstall the first time anything is installed multi. There is no // need to update the value on future install/update runs since this value never // changes. Note that the value is removed by Google Update after EULA // acceptance is processed. void AddOemInstallWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(installer_state.is_multi_install()); const bool system_install = installer_state.system_install(); if (!original_state.GetProductState(system_install, BrowserDistribution::CHROME_BINARIES)) { const HKEY root_key = installer_state.root_key(); std::wstring multi_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); // Copy the value from Chrome unless Chrome isn't installed or being // installed. BrowserDistribution::Type source_type; if (installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER)) { source_type = BrowserDistribution::CHROME_BROWSER; } else if (!installer_state.products().empty()) { // Pick a product, any product. source_type = installer_state.products()[0]->distribution()->GetType(); } else { // Nothing is being installed? Entirely unexpected, so do no harm. LOG(ERROR) << "No products found in AddOemInstallWorkItems"; return; } const ProductState* source_product = original_state.GetNonVersionedProductState(system_install, source_type); std::wstring oem_install; if (source_product->GetOemInstall(&oem_install)) { VLOG(1) << "Mirroring oeminstall=\"" << oem_install << "\" from " << BrowserDistribution::GetSpecificDistribution(source_type) ->GetAppShortCutName(); install_list->AddCreateRegKeyWorkItem(root_key, multi_key); // Always overwrite an old value. install_list->AddSetRegValueWorkItem(root_key, multi_key, google_update::kRegOemInstallField, oem_install, true); } else { // Clear any old value. install_list->AddDeleteRegValueWorkItem( root_key, multi_key, google_update::kRegOemInstallField); } } } // Mirror eulaaccepted the first time anything is installed multi. There is no // need to update the value on future install/update runs since // GoogleUpdateSettings::SetEULAConsent will modify the value for both the // relevant product and for the binaries. void AddEulaAcceptedWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(installer_state.is_multi_install()); const bool system_install = installer_state.system_install(); if (!original_state.GetProductState(system_install, BrowserDistribution::CHROME_BINARIES)) { const HKEY root_key = installer_state.root_key(); std::wstring multi_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); // Copy the value from the product with the greatest value. bool have_eula_accepted = false; BrowserDistribution::Type product_type; DWORD eula_accepted; const Products& products = installer_state.products(); for (size_t i = 0, count = products.size(); i != count; ++i) { DWORD dword_value = 0; BrowserDistribution::Type this_type = products[i]->distribution()->GetType(); const ProductState* product_state = original_state.GetNonVersionedProductState( system_install, this_type); if (product_state->GetEulaAccepted(&dword_value) && (!have_eula_accepted || dword_value > eula_accepted)) { have_eula_accepted = true; eula_accepted = dword_value; product_type = this_type; } } if (have_eula_accepted) { VLOG(1) << "Mirroring eulaaccepted=" << eula_accepted << " from " << BrowserDistribution::GetSpecificDistribution(product_type) ->GetAppShortCutName(); install_list->AddCreateRegKeyWorkItem(root_key, multi_key); install_list->AddSetRegValueWorkItem( root_key, multi_key, google_update::kRegEULAAceptedField, eula_accepted, true); } else { // Clear any old value. install_list->AddDeleteRegValueWorkItem( root_key, multi_key, google_update::kRegEULAAceptedField); } } } // Adds work items that make registry adjustments for Google Update. void AddGoogleUpdateWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { // Is a multi-install product being installed or over-installed? if (installer_state.operation() != InstallerState::MULTI_INSTALL && installer_state.operation() != InstallerState::MULTI_UPDATE) { VLOG(1) << "AddGoogleUpdateWorkItems noop: " << installer_state.operation(); return; } const bool system_install = installer_state.system_install(); const HKEY root_key = installer_state.root_key(); std::wstring multi_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); // For system-level installs, make sure the ClientStateMedium key for the // binaries exists. if (system_install) { install_list->AddCreateRegKeyWorkItem( root_key, installer_state.multi_package_binaries_distribution()-> GetStateMediumKey().c_str()); } // Creating the ClientState key for binaries, if we're migrating to multi then // copy over Chrome's brand code if it has one. Chrome Frame currently never // has a brand code. if (installer_state.state_type() != BrowserDistribution::CHROME_BINARIES) { const ProductState* chrome_product_state = original_state.GetNonVersionedProductState( system_install, BrowserDistribution::CHROME_BROWSER); const std::wstring& brand(chrome_product_state->brand()); if (!brand.empty()) { install_list->AddCreateRegKeyWorkItem(root_key, multi_key); // Write Chrome's brand code to the multi key. Never overwrite the value // if one is already present (although this shouldn't happen). install_list->AddSetRegValueWorkItem(root_key, multi_key, google_update::kRegBrandField, brand, false); } } AddOemInstallWorkItems(original_state, installer_state, install_list); AddEulaAcceptedWorkItems(original_state, installer_state, install_list); AddUsageStatsWorkItems(original_state, installer_state, install_list); // TODO(grt): check for other keys/values we should put in the package's // ClientState and/or Clients key. } void AddUsageStatsWorkItems(const InstallationState& original_state, const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(installer_state.operation() == InstallerState::MULTI_INSTALL || installer_state.operation() == InstallerState::MULTI_UPDATE); HKEY root_key = installer_state.root_key(); bool value_found = false; DWORD usagestats = 0; const Products& products = installer_state.products(); // Search for an existing usagestats value for any product. for (Products::const_iterator scan = products.begin(), end = products.end(); !value_found && scan != end; ++scan) { BrowserDistribution* dist = (*scan)->distribution(); const ProductState* product_state = original_state.GetNonVersionedProductState( installer_state.system_install(), dist->GetType()); value_found = product_state->GetUsageStats(&usagestats); } // If a value was found, write it in the appropriate location for the // binaries and remove all values from the products. if (value_found) { std::wstring state_key( installer_state.multi_package_binaries_distribution()->GetStateKey()); install_list->AddCreateRegKeyWorkItem(root_key, state_key); // Overwrite any existing value so that overinstalls (where Omaha writes a // new value into a product's state key) pick up the correct value. install_list->AddSetRegValueWorkItem(root_key, state_key, google_update::kRegUsageStatsField, usagestats, true); for (Products::const_iterator scan = products.begin(), end = products.end(); scan != end; ++scan) { BrowserDistribution* dist = (*scan)->distribution(); if (installer_state.system_install()) { install_list->AddDeleteRegValueWorkItem( root_key, dist->GetStateMediumKey(), google_update::kRegUsageStatsField); // Previous versions of Chrome also wrote a value in HKCU even for // system-level installs, so clean that up. install_list->AddDeleteRegValueWorkItem( HKEY_CURRENT_USER, dist->GetStateKey(), google_update::kRegUsageStatsField); } install_list->AddDeleteRegValueWorkItem(root_key, dist->GetStateKey(), google_update::kRegUsageStatsField); } } } // This is called when an MSI installation is run. It may be that a user is // attempting to install the MSI on top of a non-MSI managed installation. // If so, try and remove any existing uninstallation shortcuts, as we want the // uninstall to be managed entirely by the MSI machinery (accessible via the // Add/Remove programs dialog). void AddDeleteUninstallShortcutsForMSIWorkItems( const InstallerState& installer_state, const Product& product, const FilePath& temp_path, WorkItemList* work_item_list) { DCHECK(installer_state.is_msi()) << "This must only be called for MSI installations!"; // First attempt to delete the old installation's ARP dialog entry. HKEY reg_root = installer_state.root_key(); std::wstring uninstall_reg(product.distribution()->GetUninstallRegPath()); WorkItem* delete_reg_key = work_item_list->AddDeleteRegKeyWorkItem( reg_root, uninstall_reg); delete_reg_key->set_ignore_failure(true); // Then attempt to delete the old installation's start menu shortcut. FilePath uninstall_link; if (installer_state.system_install()) { PathService::Get(base::DIR_COMMON_START_MENU, &uninstall_link); } else { PathService::Get(base::DIR_START_MENU, &uninstall_link); } if (uninstall_link.empty()) { LOG(ERROR) << "Failed to get location for shortcut."; } else { uninstall_link = uninstall_link.Append( product.distribution()->GetAppShortCutName()); uninstall_link = uninstall_link.Append( product.distribution()->GetUninstallLinkName() + L".lnk"); VLOG(1) << "Deleting old uninstall shortcut (if present): " << uninstall_link.value(); WorkItem* delete_link = work_item_list->AddDeleteTreeWorkItem( uninstall_link, temp_path); delete_link->set_ignore_failure(true); delete_link->set_log_message( "Failed to delete old uninstall shortcut."); } } // After a successful copying of all the files, this function is called to // do a few post install tasks: // - Handle the case of in-use-update by updating "opv" (old version) key or // deleting it if not required. // - Register any new dlls and unregister old dlls. // - If this is an MSI install, ensures that the MSI marker is set, and sets // it if not. // If these operations are successful, the function returns true, otherwise // false. bool AppendPostInstallTasks(const InstallerState& installer_state, const FilePath& setup_path, const FilePath& new_chrome_exe, const Version* current_version, const Version& new_version, const FilePath& temp_path, WorkItemList* post_install_task_list) { DCHECK(post_install_task_list); HKEY root = installer_state.root_key(); const Products& products = installer_state.products(); // Append work items that will only be executed if this was an update. // We update the 'opv' value with the current version that is active, // the 'cpv' value with the critical update version (if present), and the // 'cmd' value with the rename command to run. { scoped_ptr<WorkItemList> in_use_update_work_items( WorkItem::CreateConditionalWorkItemList( new ConditionRunIfFileExists(new_chrome_exe))); in_use_update_work_items->set_log_message("InUseUpdateWorkItemList"); // |critical_version| will be valid only if this in-use update includes a // version considered critical relative to the version being updated. Version critical_version(installer_state.DetermineCriticalVersion( current_version, new_version)); FilePath installer_path(installer_state.GetInstallerDirectory(new_version) .Append(setup_path.BaseName())); CommandLine rename(installer_path); rename.AppendSwitch(switches::kRenameChromeExe); if (installer_state.system_install()) rename.AppendSwitch(switches::kSystemLevel); if (installer_state.verbose_logging()) rename.AppendSwitch(switches::kVerboseLogging); std::wstring version_key; for (size_t i = 0; i < products.size(); ++i) { BrowserDistribution* dist = products[i]->distribution(); version_key = dist->GetVersionKey(); if (current_version != NULL) { in_use_update_work_items->AddSetRegValueWorkItem(root, version_key, google_update::kRegOldVersionField, ASCIIToWide(current_version->GetString()), true); } if (critical_version.IsValid()) { in_use_update_work_items->AddSetRegValueWorkItem(root, version_key, google_update::kRegCriticalVersionField, ASCIIToWide(critical_version.GetString()), true); } else { in_use_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCriticalVersionField); } // Adding this registry entry for all products is overkill. // However, as it stands, we don't have a way to know which distribution // will check the key and run the command, so we add it for all. The // first to run it will perform the operation and clean up the other // values. CommandLine product_rename_cmd(rename); products[i]->AppendRenameFlags(&product_rename_cmd); in_use_update_work_items->AddSetRegValueWorkItem( root, version_key, google_update::kRegRenameCmdField, product_rename_cmd.GetCommandLineString(), true); } if (current_version != NULL && installer_state.is_multi_install()) { BrowserDistribution* dist = installer_state.multi_package_binaries_distribution(); version_key = dist->GetVersionKey(); in_use_update_work_items->AddSetRegValueWorkItem( root, version_key, google_update::kRegOldVersionField, ASCIIToWide(current_version->GetString()), true); if (critical_version.IsValid()) { in_use_update_work_items->AddSetRegValueWorkItem( root, version_key, google_update::kRegCriticalVersionField, ASCIIToWide(critical_version.GetString()), true); } else { in_use_update_work_items->AddDeleteRegValueWorkItem( root, version_key, google_update::kRegCriticalVersionField); } // TODO(tommi): We should move the rename command here. We also need to // update upgrade_utils::SwapNewChromeExeIfPresent. } if (installer_state.FindProduct(BrowserDistribution::CHROME_FRAME)) { AddCopyIELowRightsPolicyWorkItems(installer_state, in_use_update_work_items.get()); } post_install_task_list->AddWorkItem(in_use_update_work_items.release()); } // Append work items that will be executed if this was NOT an in-use update. { scoped_ptr<WorkItemList> regular_update_work_items( WorkItem::CreateConditionalWorkItemList( new Not(new ConditionRunIfFileExists(new_chrome_exe)))); regular_update_work_items->set_log_message("RegularUpdateWorkItemList"); // Since this was not an in-use-update, delete 'opv', 'cpv', and 'cmd' keys. for (size_t i = 0; i < products.size(); ++i) { BrowserDistribution* dist = products[i]->distribution(); std::wstring version_key(dist->GetVersionKey()); regular_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegOldVersionField); regular_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCriticalVersionField); regular_update_work_items->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegRenameCmdField); } if (installer_state.FindProduct(BrowserDistribution::CHROME_FRAME)) { AddDeleteOldIELowRightsPolicyWorkItems(installer_state, regular_update_work_items.get()); } post_install_task_list->AddWorkItem(regular_update_work_items.release()); } AddRegisterComDllWorkItemsForPackage(installer_state, current_version, new_version, post_install_task_list); // If we're told that we're an MSI install, make sure to set the marker // in the client state key so that future updates do the right thing. if (installer_state.is_msi()) { for (size_t i = 0; i < products.size(); ++i) { const Product* product = products[i]; AddSetMsiMarkerWorkItem(installer_state, product->distribution(), true, post_install_task_list); // We want MSI installs to take over the Add/Remove Programs shortcut. // Make a best-effort attempt to delete any shortcuts left over from // previous non-MSI installations for the same type of install (system or // per user). AddDeleteUninstallShortcutsForMSIWorkItems(installer_state, *product, temp_path, post_install_task_list); } if (installer_state.is_multi_install()) { AddSetMsiMarkerWorkItem(installer_state, installer_state.multi_package_binaries_distribution(), true, post_install_task_list); } } return true; } void AddInstallWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const FilePath& archive_path, const FilePath& src_path, const FilePath& temp_path, const Version& new_version, scoped_ptr<Version>* current_version, WorkItemList* install_list) { DCHECK(install_list); const FilePath& target_path = installer_state.target_path(); // A temp directory that work items need and the actual install directory. install_list->AddCreateDirWorkItem(temp_path); install_list->AddCreateDirWorkItem(target_path); if (current_version != NULL && current_version->get() != NULL) { // Delete the archive from an existing install to save some disk space. We // make this an unconditional work item since there's no need to roll this // back; if installation fails we'll be moved to the "-full" channel anyway. FilePath old_installer_dir( installer_state.GetInstallerDirectory(**current_version)); FilePath old_archive(old_installer_dir.Append(archive_path.BaseName())); install_list->AddDeleteTreeWorkItem(old_archive, temp_path) ->set_ignore_failure(true); } // Delete any new_chrome.exe if present (we will end up creating a new one // if required) and then copy chrome.exe FilePath new_chrome_exe(target_path.Append(installer::kChromeNewExe)); install_list->AddDeleteTreeWorkItem(new_chrome_exe, temp_path); if (installer_state.IsChromeFrameRunning(original_state)) { VLOG(1) << "Chrome Frame in use. Copying to new_chrome.exe"; install_list->AddCopyTreeWorkItem( src_path.Append(installer::kChromeExe).value(), new_chrome_exe.value(), temp_path.value(), WorkItem::ALWAYS); } else { install_list->AddCopyTreeWorkItem( src_path.Append(installer::kChromeExe).value(), target_path.Append(installer::kChromeExe).value(), temp_path.value(), WorkItem::NEW_NAME_IF_IN_USE, new_chrome_exe.value()); } // Extra executable for 64 bit systems. // NOTE: We check for "not disabled" so that if the API call fails, we play it // safe and copy the executable anyway. // NOTE: the file wow_helper.exe is only needed for Vista and below. if (base::win::OSInfo::GetInstance()->wow64_status() != base::win::OSInfo::WOW64_DISABLED && base::win::GetVersion() <= base::win::VERSION_VISTA) { install_list->AddMoveTreeWorkItem( src_path.Append(installer::kWowHelperExe).value(), target_path.Append(installer::kWowHelperExe).value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } // Install kVisualElementsManifest if it is present in |src_path|. No need to // make this a conditional work item as if the file is not there now, it will // never be. if (file_util::PathExists( src_path.Append(installer::kVisualElementsManifest))) { install_list->AddMoveTreeWorkItem( src_path.Append(installer::kVisualElementsManifest).value(), target_path.Append(installer::kVisualElementsManifest).value(), temp_path.value(), WorkItem::ALWAYS_MOVE); } else { // We do not want to have an old VisualElementsManifest pointing to an old // version directory. Delete it as there wasn't a new one to replace it. install_list->AddDeleteTreeWorkItem( target_path.Append(installer::kVisualElementsManifest), temp_path); } // For the component build to work with the installer, we need to drop a // config file and a manifest by chrome.exe. These files are only found in // the archive if this is a component build. #if defined(COMPONENT_BUILD) static const FilePath::CharType kChromeExeConfig[] = FILE_PATH_LITERAL("chrome.exe.config"); static const FilePath::CharType kChromeExeManifest[] = FILE_PATH_LITERAL("chrome.exe.manifest"); install_list->AddMoveTreeWorkItem( src_path.Append(kChromeExeConfig).value(), target_path.Append(kChromeExeConfig).value(), temp_path.value(), WorkItem::ALWAYS_MOVE); install_list->AddMoveTreeWorkItem( src_path.Append(kChromeExeManifest).value(), target_path.Append(kChromeExeManifest).value(), temp_path.value(), WorkItem::ALWAYS_MOVE); #endif // defined(COMPONENT_BUILD) // In the past, we copied rather than moved for system level installs so that // the permissions of %ProgramFiles% would be picked up. Now that |temp_path| // is in %ProgramFiles% for system level installs (and in %LOCALAPPDATA% // otherwise), there is no need to do this. // Note that we pass true for check_duplicates to avoid failing on in-use // repair runs if the current_version is the same as the new_version. bool check_for_duplicates = (current_version != NULL && current_version->get() != NULL && current_version->get()->Equals(new_version)); install_list->AddMoveTreeWorkItem( src_path.AppendASCII(new_version.GetString()).value(), target_path.AppendASCII(new_version.GetString()).value(), temp_path.value(), check_for_duplicates ? WorkItem::CHECK_DUPLICATES : WorkItem::ALWAYS_MOVE); // Delete any old_chrome.exe if present (ignore failure if it's in use). install_list->AddDeleteTreeWorkItem( target_path.Append(installer::kChromeOldExe), temp_path) ->set_ignore_failure(true); // Copy installer in install directory and // add shortcut in Control Panel->Add/Remove Programs. AddInstallerCopyTasks(installer_state, setup_path, archive_path, temp_path, new_version, install_list); const HKEY root = installer_state.root_key(); // Only set "lang" for user-level installs since for system-level, the install // language may not be related to a given user's runtime language. const bool add_language_identifier = !installer_state.system_install(); const Products& products = installer_state.products(); for (size_t i = 0; i < products.size(); ++i) { const Product* product = products[i]; AddUninstallShortcutWorkItems(installer_state, setup_path, new_version, install_list, *product); AddVersionKeyWorkItems(root, product->distribution(), new_version, add_language_identifier, install_list); AddDelegateExecuteWorkItems(installer_state, src_path, new_version, *product, install_list); } if (installer_state.is_multi_install()) { AddMultiUninstallWorkItems(installer_state, setup_path, new_version, install_list); AddVersionKeyWorkItems(root, installer_state.multi_package_binaries_distribution(), new_version, add_language_identifier, install_list); } // Add any remaining work items that involve special settings for // each product. AddProductSpecificWorkItems(original_state, installer_state, setup_path, new_version, install_list); // Copy over brand, usagestats, and other values. AddGoogleUpdateWorkItems(original_state, installer_state, install_list); AddQuickEnableWorkItems(installer_state, original_state, &setup_path, &new_version, install_list); // Append the tasks that run after the installation. AppendPostInstallTasks(installer_state, setup_path, new_chrome_exe, current_version->get(), new_version, temp_path, install_list); } void AddRegisterComDllWorkItems(const FilePath& dll_folder, const std::vector<FilePath>& dll_list, bool system_level, bool do_register, bool ignore_failures, WorkItemList* work_item_list) { DCHECK(work_item_list); if (dll_list.empty()) { VLOG(1) << "No COM DLLs to register"; } else { std::vector<FilePath>::const_iterator dll_iter(dll_list.begin()); for (; dll_iter != dll_list.end(); ++dll_iter) { FilePath dll_path = dll_folder.Append(*dll_iter); WorkItem* work_item = work_item_list->AddSelfRegWorkItem( dll_path.value(), do_register, !system_level); DCHECK(work_item); work_item->set_ignore_failure(ignore_failures); } } } void AddSetMsiMarkerWorkItem(const InstallerState& installer_state, BrowserDistribution* dist, bool set, WorkItemList* work_item_list) { DCHECK(work_item_list); DWORD msi_value = set ? 1 : 0; WorkItem* set_msi_work_item = work_item_list->AddSetRegValueWorkItem( installer_state.root_key(), dist->GetStateKey(), google_update::kRegMSIField, msi_value, true); DCHECK(set_msi_work_item); set_msi_work_item->set_ignore_failure(true); set_msi_work_item->set_log_message("Could not write MSI marker!"); } void AddChromeFrameWorkItems(const InstallationState& original_state, const InstallerState& installer_state, const FilePath& setup_path, const Version& new_version, const Product& product, WorkItemList* list) { DCHECK(product.is_chrome_frame()); if (!installer_state.is_multi_install()) { VLOG(1) << "Not adding GCF specific work items for single install."; return; } std::wstring version_key(product.distribution()->GetVersionKey()); bool ready_mode = product.HasOption(kOptionReadyMode); HKEY root = installer_state.root_key(); const bool is_install = (installer_state.operation() != InstallerState::UNINSTALL); bool update_chrome_uninstall_command = false; BrowserDistribution* dist = installer_state.multi_package_binaries_distribution(); if (ready_mode) { // If GCF is being installed in ready mode, we write an entry to the // multi-install state key. If the value already exists, we will not // overwrite it since the user might have opted out. list->AddCreateRegKeyWorkItem(root, dist->GetStateKey()); list->AddSetRegValueWorkItem(root, dist->GetStateKey(), kChromeFrameReadyModeField, static_cast<int64>(is_install ? 1 : 0), // The value we want to set. is_install ? false : true); // Overwrite existing value. if (is_install) { FilePath installer_path(installer_state .GetInstallerDirectory(new_version).Append(setup_path.BaseName())); CommandLine basic_cl(installer_path); basic_cl.AppendSwitch(switches::kChromeFrame); basic_cl.AppendSwitch(switches::kMultiInstall); if (installer_state.system_install()) basic_cl.AppendSwitch(switches::kSystemLevel); CommandLine temp_opt_out(basic_cl); temp_opt_out.AppendSwitch(switches::kChromeFrameReadyModeTempOptOut); CommandLine end_temp_opt_out(basic_cl); end_temp_opt_out.AppendSwitch( switches::kChromeFrameReadyModeEndTempOptOut); CommandLine opt_out(installer_path); AppendUninstallCommandLineFlags(installer_state, product, &opt_out); // Force Uninstall silences the prompt to reboot to complete uninstall. opt_out.AppendSwitch(switches::kForceUninstall); CommandLine opt_in(basic_cl); opt_in.AppendSwitch(switches::kChromeFrameReadyModeOptIn); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFTempOptOutCmdField, temp_opt_out.GetCommandLineString(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFEndTempOptOutCmdField, end_temp_opt_out.GetCommandLineString(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFOptOutCmdField, opt_out.GetCommandLineString(), true); list->AddSetRegValueWorkItem(root, version_key, google_update::kRegCFOptInCmdField, opt_in.GetCommandLineString(), true); } else { // If Chrome is not also being uninstalled, we need to update its command // line so that it doesn't include uninstalling Chrome Frame now. update_chrome_uninstall_command = (installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER) == NULL); } } else { // It doesn't matter here if we're installing or uninstalling Chrome Frame. // If ready mode isn't specified on the command line for installs, we need // to delete the ready mode flag from the registry if it exists - this // constitutes an opt-in for the user. If we're uninstalling CF and ready // mode isn't specified on the command line, that means that CF wasn't // installed with ready mode enabled (the --ready-mode switch should be set // in the registry) so deleting the value should have no effect. // In both cases (install/uninstall), we need to make sure that Chrome's // uninstallation command line does not include the --chrome-frame switch // so that uninstalling Chrome will no longer uninstall Chrome Frame. list->AddDeleteRegValueWorkItem(root, dist->GetStateKey(), kChromeFrameReadyModeField); const Product* chrome = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (chrome) { // Chrome is already a part of this installation run, so we can assume // that the uninstallation arguments will be updated correctly. } else { // Chrome is not a part of this installation run, so we have to explicitly // check if Chrome is installed, and if so, update its uninstallation // command lines. const ProductState* chrome_state = original_state.GetProductState( installer_state.system_install(), BrowserDistribution::CHROME_BROWSER); update_chrome_uninstall_command = (chrome_state != NULL) && chrome_state->is_multi_install(); } } if (!ready_mode || !is_install) { list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFTempOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFEndTempOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFOptOutCmdField); list->AddDeleteRegValueWorkItem(root, version_key, google_update::kRegCFOptInCmdField); } if (update_chrome_uninstall_command) { // Chrome is not a part of this installation run, so we have to explicitly // check if Chrome is installed, and if so, update its uninstallation // command lines. const ProductState* chrome_state = original_state.GetProductState( installer_state.system_install(), BrowserDistribution::CHROME_BROWSER); if (chrome_state != NULL) { DCHECK(chrome_state->is_multi_install()); Product chrome(BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BROWSER)); chrome.InitializeFromUninstallCommand(chrome_state->uninstall_command()); AddUninstallShortcutWorkItems(installer_state, setup_path, chrome_state->version(), list, chrome); } else { NOTREACHED() << "What happened to Chrome?"; } } } void AddDelegateExecuteWorkItems(const InstallerState& installer_state, const FilePath& src_path, const Version& new_version, const Product& product, WorkItemList* list) { string16 handler_class_uuid; string16 type_lib_uuid; string16 type_lib_version; string16 interface_uuid; BrowserDistribution* distribution = product.distribution(); if (!distribution->GetDelegateExecuteHandlerData( &handler_class_uuid, &type_lib_uuid, &type_lib_version, &interface_uuid)) { VLOG(1) << "No DelegateExecute verb handler processing to do for " << distribution->GetAppShortCutName(); return; } HKEY root = installer_state.root_key(); const bool is_install = (installer_state.operation() != InstallerState::UNINSTALL); string16 delegate_execute_path(L"Software\\Classes\\CLSID\\"); delegate_execute_path.append(handler_class_uuid); string16 typelib_path(L"Software\\Classes\\TypeLib\\"); typelib_path.append(type_lib_uuid); string16 interface_path(L"Software\\Classes\\Interface\\"); interface_path.append(interface_uuid); // Add work items to register the handler iff it is present. Remove its // registration otherwise since builds after r132190 included it when it // wasn't strictly necessary. // TODO(grt): remove the extra check for the .exe when it's ever-present; // see also shell_util.cc's GetProgIdEntries. if (is_install && file_util::PathExists(src_path.AppendASCII(new_version.GetString()) .Append(kDelegateExecuteExe))) { VLOG(1) << "Adding registration items for DelegateExecute verb handler."; // The path to the exe (in the version directory). FilePath delegate_execute( installer_state.target_path().AppendASCII(new_version.GetString())); delegate_execute = delegate_execute.Append(kDelegateExecuteExe); // Command-line featuring the quoted path to the exe. string16 command(1, L'"'); command.append(delegate_execute.value()).append(1, L'"'); // Register the CommandExecuteImpl class at // Software\Classes\CLSID\{5C65F4B0-3651-4514-B207-D10CB699B14B} list->AddCreateRegKeyWorkItem(root, delegate_execute_path); list->AddSetRegValueWorkItem(root, delegate_execute_path, L"", L"CommandExecuteImpl Class", true); string16 subkey(delegate_execute_path); subkey.append(L"\\LocalServer32"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", command, true); list->AddSetRegValueWorkItem(root, subkey, L"ServerExecutable", delegate_execute.value(), true); subkey.assign(delegate_execute_path).append(L"\\Programmable"); list->AddCreateRegKeyWorkItem(root, subkey); subkey.assign(delegate_execute_path).append(L"\\TypeLib"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", type_lib_uuid, true); subkey.assign(delegate_execute_path).append(L"\\Version"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", type_lib_version, true); // Register the DelegateExecuteLib type library at // Software\Classes\TypeLib\{4E805ED8-EBA0-4601-9681-12815A56EBFD} list->AddCreateRegKeyWorkItem(root, typelib_path); string16 version_key(typelib_path); version_key.append(1, L'\\').append(type_lib_version); list->AddCreateRegKeyWorkItem(root, version_key); list->AddSetRegValueWorkItem(root, version_key, L"", L"DelegateExecuteLib", true); subkey.assign(version_key).append(L"\\FLAGS"); const DWORD flags = LIBFLAG_FRESTRICTED | LIBFLAG_FCONTROL; list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", flags, true); subkey.assign(version_key).append(L"\\0"); list->AddCreateRegKeyWorkItem(root, subkey); subkey.append(L"\\win32"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", delegate_execute.value(), true); subkey.assign(version_key).append(L"\\HELPDIR"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", delegate_execute.DirName().value(), true); // Register to ICommandExecuteImpl interface at // Software\Classes\Interface\{0BA0D4E9-2259-4963-B9AE-A839F7CB7544} list->AddCreateRegKeyWorkItem(root, interface_path); list->AddSetRegValueWorkItem(root, interface_path, L"", L"ICommandExecuteImpl", true); subkey.assign(interface_path).append(L"\\ProxyStubClsid32"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", kPSOAInterfaceUuid, true); subkey.assign(interface_path).append(L"\\TypeLib"); list->AddCreateRegKeyWorkItem(root, subkey); list->AddSetRegValueWorkItem(root, subkey, L"", type_lib_uuid, true); list->AddSetRegValueWorkItem(root, subkey, L"Version", type_lib_version, true); } else { VLOG(1) << "Adding unregistration items for DelegateExecute verb handler."; list->AddDeleteRegKeyWorkItem(root, delegate_execute_path); list->AddDeleteRegKeyWorkItem(root, typelib_path); list->AddDeleteRegKeyWorkItem(root, interface_path); } } namespace { enum ElevationPolicyId { CURRENT_ELEVATION_POLICY, OLD_ELEVATION_POLICY, }; // Although the UUID of the ChromeFrame class is used for the "current" value, // this is done only as a convenience; there is no need for the GUID of the Low // Rights policies to match the ChromeFrame class's GUID. Hence, it is safe to // use this completely unrelated GUID for the "old" policies. const wchar_t kIELowRightsPolicyOldGuid[] = L"{6C288DD7-76FB-4721-B628-56FAC252E199}"; const wchar_t kElevationPolicyKeyPath[] = L"SOFTWARE\\Microsoft\\Internet Explorer\\Low Rights\\ElevationPolicy\\"; void GetIELowRightsElevationPolicyKeyPath(ElevationPolicyId policy, std::wstring* key_path) { DCHECK(policy == CURRENT_ELEVATION_POLICY || policy == OLD_ELEVATION_POLICY); key_path->assign(kElevationPolicyKeyPath, arraysize(kElevationPolicyKeyPath) - 1); if (policy == CURRENT_ELEVATION_POLICY) { wchar_t cf_clsid[64]; int len = StringFromGUID2(__uuidof(ChromeFrame), &cf_clsid[0], arraysize(cf_clsid)); key_path->append(&cf_clsid[0], len - 1); } else { key_path->append(kIELowRightsPolicyOldGuid, arraysize(kIELowRightsPolicyOldGuid)- 1); } } } // namespace void AddDeleteOldIELowRightsPolicyWorkItems( const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(install_list); std::wstring key_path; GetIELowRightsElevationPolicyKeyPath(OLD_ELEVATION_POLICY, &key_path); install_list->AddDeleteRegKeyWorkItem(installer_state.root_key(), key_path); } // Adds work items to copy the chrome_launcher IE low rights elevation policy // from the primary policy GUID to the "old" policy GUID. Take care not to // perform the copy if there is already an old policy present, as the ones under // the main kElevationPolicyGuid would then correspond to an intermediate // version (current_version < pv < new_version). void AddCopyIELowRightsPolicyWorkItems(const InstallerState& installer_state, WorkItemList* install_list) { DCHECK(install_list); std::wstring current_key_path; std::wstring old_key_path; GetIELowRightsElevationPolicyKeyPath(CURRENT_ELEVATION_POLICY, &current_key_path); GetIELowRightsElevationPolicyKeyPath(OLD_ELEVATION_POLICY, &old_key_path); // Do not clobber existing old policies. install_list->AddCopyRegKeyWorkItem(installer_state.root_key(), current_key_path, old_key_path, WorkItem::IF_NOT_PRESENT); } void AppendUninstallCommandLineFlags(const InstallerState& installer_state, const Product& product, CommandLine* uninstall_cmd) { DCHECK(uninstall_cmd); uninstall_cmd->AppendSwitch(installer::switches::kUninstall); // Append the product-specific uninstall flags. product.AppendProductFlags(uninstall_cmd); if (installer_state.is_msi()) { uninstall_cmd->AppendSwitch(installer::switches::kMsi); // See comment in uninstall.cc where we check for the kDeleteProfile switch. if (product.is_chrome_frame()) { uninstall_cmd->AppendSwitch(installer::switches::kDeleteProfile); } } if (installer_state.system_install()) uninstall_cmd->AppendSwitch(installer::switches::kSystemLevel); if (installer_state.verbose_logging()) uninstall_cmd->AppendSwitch(installer::switches::kVerboseLogging); } void RefreshElevationPolicy() { const wchar_t kIEFrameDll[] = L"ieframe.dll"; const char kIERefreshPolicy[] = "IERefreshElevationPolicy"; HMODULE ieframe = LoadLibrary(kIEFrameDll); if (ieframe) { typedef HRESULT (__stdcall *IERefreshPolicy)(); IERefreshPolicy ie_refresh_policy = reinterpret_cast<IERefreshPolicy>( GetProcAddress(ieframe, kIERefreshPolicy)); if (ie_refresh_policy) { ie_refresh_policy(); } else { VLOG(1) << kIERefreshPolicy << " not supported."; } FreeLibrary(ieframe); } else { VLOG(1) << "Cannot load " << kIEFrameDll; } } void AddQuickEnableWorkItems(const InstallerState& installer_state, const InstallationState& machine_state, const FilePath* setup_path, const Version* new_version, WorkItemList* work_item_list) { DCHECK(setup_path || installer_state.operation() == InstallerState::UNINSTALL); DCHECK(new_version || installer_state.operation() == InstallerState::UNINSTALL); DCHECK(work_item_list); const bool system_install = installer_state.system_install(); bool have_multi_chrome = false; bool have_chrome_frame = false; // STEP 1: Figure out the state of the machine before the operation. const ProductState* product_state = NULL; // Is multi-install Chrome already on the machine? product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_BROWSER); if (product_state != NULL && product_state->is_multi_install()) have_multi_chrome = true; // Is Chrome Frame !ready-mode already on the machine? product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_FRAME); if (product_state != NULL && !product_state->uninstall_command().HasSwitch( switches::kChromeFrameReadyMode)) have_chrome_frame = true; // STEP 2: Now take into account the current operation. const Product* product = NULL; if (installer_state.operation() == InstallerState::UNINSTALL) { // Forget about multi-install Chrome if it is being uninstalled. product = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (product != NULL && installer_state.is_multi_install()) have_multi_chrome = false; // Forget about Chrome Frame if it is being uninstalled. Note that we don't // bother to check !HasOption(kOptionReadyMode) since have_chrome_frame // should have been false for that case in the first place. It's odd if it // wasn't, but the right thing to do in that case is to proceed with the // thought that CF will not be installed in any sense when we reach the // finish line. if (installer_state.FindProduct(BrowserDistribution::CHROME_FRAME) != NULL) have_chrome_frame = false; } else { // Check if we're installing multi-install Chrome. product = installer_state.FindProduct(BrowserDistribution::CHROME_BROWSER); if (product != NULL && installer_state.is_multi_install()) have_multi_chrome = true; // Check if we're installing Chrome Frame !ready-mode. product = installer_state.FindProduct(BrowserDistribution::CHROME_FRAME); if (product != NULL && !product->HasOption(kOptionReadyMode)) have_chrome_frame = true; } // STEP 3: Decide what to do based on the final state of things. enum QuickEnableOperation { DO_NOTHING, ADD_COMMAND, REMOVE_COMMAND } operation = DO_NOTHING; FilePath binaries_setup_path; if (have_chrome_frame) { // Chrome Frame !ready-mode is or will be installed. Unconditionally remove // the quick-enable-cf command from the binaries. We do this even if // multi-install Chrome isn't installed since we don't want them left // behind in any case. operation = REMOVE_COMMAND; } else if (have_multi_chrome) { // Chrome Frame isn't (to be) installed or is (to be) installed only in // ready-mode, while multi-install Chrome is (to be) installed. Add the // quick-enable-cf command to the binaries. operation = ADD_COMMAND; // The path to setup.exe contains the version of the Chrome binaries, so it // takes a little work to get it right. if (installer_state.operation() == InstallerState::UNINSTALL) { // Chrome Frame is being uninstalled. Use the path to the currently // installed Chrome setup.exe. product_state = machine_state.GetProductState(system_install, BrowserDistribution::CHROME_BROWSER); DCHECK(product_state); binaries_setup_path = product_state->uninstall_command().GetProgram(); } else { // Chrome is being installed, updated, or otherwise being operated on. // Use the path to the given |setup_path| in the normal location of // multi-install Chrome of the given |version|. DCHECK(installer_state.is_multi_install()); binaries_setup_path = installer_state.GetInstallerDirectory(*new_version).Append( setup_path->BaseName()); } } // STEP 4: Take action. if (operation != DO_NOTHING) { // Get the path to the quick-enable-cf command for the binaries. BrowserDistribution* binaries = BrowserDistribution::GetSpecificDistribution( BrowserDistribution::CHROME_BINARIES); std::wstring cmd_key(binaries->GetVersionKey()); cmd_key.append(1, L'\\').append(google_update::kRegCommandsKey) .append(1, L'\\').append(kCmdQuickEnableCf); if (operation == ADD_COMMAND) { DCHECK(!binaries_setup_path.empty()); CommandLine cmd_line(binaries_setup_path); cmd_line.AppendSwitch(switches::kMultiInstall); if (installer_state.system_install()) cmd_line.AppendSwitch(switches::kSystemLevel); if (installer_state.verbose_logging()) cmd_line.AppendSwitch(switches::kVerboseLogging); cmd_line.AppendSwitch(switches::kChromeFrameQuickEnable); AppCommand cmd(cmd_line.GetCommandLineString(), true, true); cmd.AddWorkItems(installer_state.root_key(), cmd_key, work_item_list); } else { DCHECK(operation == REMOVE_COMMAND); work_item_list->AddDeleteRegKeyWorkItem(installer_state.root_key(), cmd_key)->set_log_message( "removing quick-enable-cf command"); } } } } // namespace installer
/****************************************************************************** * Project: PROJ.4 * Purpose: Implementation of the airy (Airy) projection. * Author: Gerald Evenden (1995) * Thomas Knudsen (2016) - revise/add regression tests * ****************************************************************************** * Copyright (c) 1995, Gerald Evenden * * 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. *****************************************************************************/ #define PJ_LIB__ #include "proj.h" #include <errno.h> #include "proj_internal.h" PROJ_HEAD(airy, "Airy") "\n\tMisc Sph, no inv\n\tno_cut lat_b="; namespace { // anonymous namespace enum Mode { N_POLE = 0, S_POLE = 1, EQUIT = 2, OBLIQ = 3 }; } // anonymous namespace namespace { // anonymous namespace struct pj_opaque { double p_halfpi; double sinph0; double cosph0; double Cb; enum Mode mode; int no_cut; /* do not cut at hemisphere limit */ }; } // anonymous namespace # define EPS 1.e-10 static PJ_XY s_forward (PJ_LP lp, PJ *P) { /* Spheroidal, forward */ PJ_XY xy = {0.0,0.0}; struct pj_opaque *Q = static_cast<struct pj_opaque*>(P->opaque); double sinlam, coslam, cosphi, sinphi, t, s, Krho, cosz; sinlam = sin(lp.lam); coslam = cos(lp.lam); switch (Q->mode) { case EQUIT: case OBLIQ: sinphi = sin(lp.phi); cosphi = cos(lp.phi); cosz = cosphi * coslam; if (Q->mode == OBLIQ) cosz = Q->sinph0 * sinphi + Q->cosph0 * cosz; if (!Q->no_cut && cosz < -EPS) { proj_errno_set(P, PJD_ERR_TOLERANCE_CONDITION); return xy; } if (fabs(s = 1. - cosz) > EPS) { t = 0.5 * (1. + cosz); Krho = -log(t)/s - Q->Cb / t; } else Krho = 0.5 - Q->Cb; xy.x = Krho * cosphi * sinlam; if (Q->mode == OBLIQ) xy.y = Krho * (Q->cosph0 * sinphi - Q->sinph0 * cosphi * coslam); else xy.y = Krho * sinphi; break; case S_POLE: case N_POLE: lp.phi = fabs(Q->p_halfpi - lp.phi); if (!Q->no_cut && (lp.phi - EPS) > M_HALFPI) { proj_errno_set(P, PJD_ERR_TOLERANCE_CONDITION); return xy; } if ((lp.phi *= 0.5) > EPS) { t = tan(lp.phi); Krho = -2.*(log(cos(lp.phi)) / t + t * Q->Cb); xy.x = Krho * sinlam; xy.y = Krho * coslam; if (Q->mode == N_POLE) xy.y = -xy.y; } else xy.x = xy.y = 0.; } return xy; } PJ *PROJECTION(airy) { double beta; struct pj_opaque *Q = static_cast<struct pj_opaque*>(pj_calloc (1, sizeof (struct pj_opaque))); if (nullptr==Q) return pj_default_destructor (P, ENOMEM); P->opaque = Q; Q->no_cut = pj_param(P->ctx, P->params, "bno_cut").i; beta = 0.5 * (M_HALFPI - pj_param(P->ctx, P->params, "rlat_b").f); if (fabs(beta) < EPS) Q->Cb = -0.5; else { Q->Cb = 1./tan(beta); Q->Cb *= Q->Cb * log(cos(beta)); } if (fabs(fabs(P->phi0) - M_HALFPI) < EPS) if (P->phi0 < 0.) { Q->p_halfpi = -M_HALFPI; Q->mode = S_POLE; } else { Q->p_halfpi = M_HALFPI; Q->mode = N_POLE; } else { if (fabs(P->phi0) < EPS) Q->mode = EQUIT; else { Q->mode = OBLIQ; Q->sinph0 = sin(P->phi0); Q->cosph0 = cos(P->phi0); } } P->fwd = s_forward; P->es = 0.; return P; }
/* Copyright 2020 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/core/common_runtime/device.h" #include "tensorflow/core/common_runtime/device_factory.h" #include "tensorflow/core/kernels/mlir_generated/base_binary_ops_test.h" #include "tensorflow/core/kernels/mlir_generated/base_ops_test.h" namespace tensorflow { namespace { // Test fixture `BinaryOpsTest` that sets the TF device is expected by the TEST // macros below. class BinaryOpsTest : public BinaryOpsTestBase { protected: void SetUp() override { std::unique_ptr<tensorflow::Device> device_gpu( tensorflow::DeviceFactory::NewDevice("GPU", {}, "/job:a/replica:0/task:0")); SetDevice(tensorflow::DEVICE_GPU, std::move(device_gpu)); } }; /// Test `tf.AddV2`. template <typename T> T baseline_add(T lhs, T rhs) { return lhs + rhs; } GENERATE_DEFAULT_TESTS(AddV2, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_add) GENERATE_DEFAULT_TESTS(AddV2, /*test_name=*/Float, float, float, baseline_add) GENERATE_DEFAULT_TESTS(AddV2, /*test_name=*/Double, double, double, baseline_add) GENERATE_DEFAULT_TESTS(AddV2, /*test_name=*/Int64, int64, int64, baseline_add) /// Test `tf.Atan2`. // Prevent the undefined case (0, 0) with non-zero rhs values. GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Atan2, /*test_name=*/FloatRhsNonZero, float, float, test::DefaultInput<float>(), test::DefaultInputNonZero<float>(), std::atan2); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Atan2, /*test_name=*/DoubleRhsNonZero, double, double, test::DefaultInput<double>(), test::DefaultInputNonZero<double>(), std::atan2); // Prevent the undefined case (0, 0) with non-zero lhs values. GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Atan2, /*test_name=*/FloatLhsNonZero, float, float, test::DefaultInputNonZero<float>(), test::DefaultInput<float>(), std::atan2); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Atan2, /*test_name=*/DoubleLhsNonZero, double, double, test::DefaultInputNonZero<double>(), test::DefaultInput<double>(), std::atan2); // Test some particularly interesting cases. TEST_F(BinaryOpsTest, Atan2FloatSpecialCases) { TestEqualShapes<float, float, float, float>( "Atan2", /*shape=*/{20}, test::InputAsVector<float>({1, 1, 1, 0, -1, -1, -1, 0}), test::InputAsVector<float>({1, 0, -1, -1, -1, 0, 1, 1}), std::atan2, test::OpsTestConfig().ExpectStrictlyEqual()); } TEST_F(BinaryOpsTest, Atan2DoubleSpecialCases) { TestEqualShapes<double, double, double, double>( "Atan2", /*shape=*/{20}, test::InputAsVector<double>({1, 1, 1, 0, -1, -1, -1, 0}), test::InputAsVector<double>({1, 0, -1, -1, -1, 0, 1, 1}), std::atan2, test::OpsTestConfig().ExpectStrictlyEqual()); } /// Test `tf.BitwiseAnd`. template <typename T> T baseline_bitwise_and(T lhs, T rhs) { return lhs & rhs; } GENERATE_DEFAULT_TESTS(BitwiseAnd, /*test_name=*/Int8, int8, int8, baseline_bitwise_and) GENERATE_DEFAULT_TESTS(BitwiseAnd, /*test_name=*/Int16, int16, int16, baseline_bitwise_and) GENERATE_DEFAULT_TESTS(BitwiseAnd, /*test_name=*/Int32, int32, int32, baseline_bitwise_and) GENERATE_DEFAULT_TESTS(BitwiseAnd, /*test_name=*/Int64, int64, int64, baseline_bitwise_and) /// Test `tf.BitwiseOr`. template <typename T> T baseline_bitwise_or(T lhs, T rhs) { return lhs | rhs; } GENERATE_DEFAULT_TESTS(BitwiseOr, /*test_name=*/Int8, int8, int8, baseline_bitwise_or) GENERATE_DEFAULT_TESTS(BitwiseOr, /*test_name=*/Int16, int16, int16, baseline_bitwise_or) GENERATE_DEFAULT_TESTS(BitwiseOr, /*test_name=*/Int32, int32, int32, baseline_bitwise_or) GENERATE_DEFAULT_TESTS(BitwiseOr, /*test_name=*/Int64, int64, int64, baseline_bitwise_or) /// Test `tf.BitwiseXor`. template <typename T> T baseline_bitwise_xor(T lhs, T rhs) { return lhs ^ rhs; } GENERATE_DEFAULT_TESTS(BitwiseXor, /*test_name=*/Int8, int8, int8, baseline_bitwise_xor) GENERATE_DEFAULT_TESTS(BitwiseXor, /*test_name=*/Int16, int16, int16, baseline_bitwise_xor) GENERATE_DEFAULT_TESTS(BitwiseXor, /*test_name=*/Int32, int32, int32, baseline_bitwise_xor) GENERATE_DEFAULT_TESTS(BitwiseXor, /*test_name=*/Int64, int64, int64, baseline_bitwise_xor) /// Test `tf.Complex`. template <typename T> std::complex<T> baseline_complex(T lhs, T rhs) { return std::complex<T>(lhs, rhs); } GENERATE_DEFAULT_TESTS_2(Complex, /*test_name=*/C64, float, float, std::complex<float>, std::complex<float>, test::DefaultInput<float>(), test::DefaultInput<float>(), baseline_complex, test::OpsTestConfig().ExpectStrictlyEqual().AddTout()) GENERATE_DEFAULT_TESTS_2(Complex, /*test_name=*/C128, double, double, std::complex<double>, std::complex<double>, test::DefaultInput<double>(), test::DefaultInput<double>(), baseline_complex, test::OpsTestConfig().ExpectStrictlyEqual().AddTout()) /// Test `tf.Div`. template <typename T> T baseline_div(T lhs, T rhs) { return lhs / rhs; } GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Div, /*test_name=*/Half, Eigen::half, Eigen::half, test::DefaultInput<Eigen::half>(), test::DefaultInputNonZero<Eigen::half>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Div, /*test_name=*/Float, float, float, test::DefaultInput<float>(), test::DefaultInputNonZero<float>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Div, /*test_name=*/Double, double, double, test::DefaultInput<double>(), test::DefaultInputNonZero<double>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Div, /*test_name=*/Int16, int16, int16, test::DefaultInput<int16>(), test::DefaultInputNonZero<int16>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( Div, /*test_name=*/Int64, int64, int64, test::DefaultInput<int64>(), test::DefaultInputNonZero<int64>(), baseline_div); /// Test `tf.Equal`. template <typename T> bool baseline_equal(T lhs, T rhs) { return lhs == rhs; } GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Half, Eigen::half, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Float, float, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Double, double, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Bool, bool, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Int8, int8, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Int16, int16, bool, baseline_equal) GENERATE_DEFAULT_TESTS(Equal, /*test_name=*/Int64, int64, bool, baseline_equal) /// Test `tf.FloorDiv`. template <typename T> T baseline_floor_div(T lhs, T rhs) { return std::floor(lhs / rhs); } template <> Eigen::half baseline_floor_div(Eigen::half lhs, Eigen::half rhs) { return static_cast<Eigen::half>(std::floor(static_cast<float>(lhs / rhs))); } GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( FloorDiv, /*test_name=*/Half, Eigen::half, Eigen::half, test::DefaultInput<Eigen::half>(), test::DefaultInputNonZero<Eigen::half>(), baseline_floor_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( FloorDiv, /*test_name=*/Float, float, float, test::DefaultInput<float>(), test::DefaultInputNonZero<float>(), baseline_floor_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( FloorDiv, /*test_name=*/Double, double, double, test::DefaultInput<double>(), test::DefaultInputNonZero<double>(), baseline_floor_div); /// Test `tf.Greater`. template <typename T> bool baseline_greater(T lhs, T rhs) { return lhs > rhs; } GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Half, Eigen::half, bool, baseline_greater) GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Float, float, bool, baseline_greater) GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Double, double, bool, baseline_greater) GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Int8, int8, bool, baseline_greater) GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Int16, int16, bool, baseline_greater) GENERATE_DEFAULT_TESTS(Greater, /*test_name=*/Int64, int64, bool, baseline_greater) /// Test `tf.GreaterEqual`. template <typename T> bool baseline_greater_equal(T lhs, T rhs) { return lhs >= rhs; } GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Half, Eigen::half, bool, baseline_greater_equal) GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Float, float, bool, baseline_greater_equal) GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Double, double, bool, baseline_greater_equal) GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Int8, int8, bool, baseline_greater_equal) GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Int16, int16, bool, baseline_greater_equal) GENERATE_DEFAULT_TESTS(GreaterEqual, /*test_name=*/Int64, int64, bool, baseline_greater_equal) /// Test `tf.LeftShift`. template <typename T> T baseline_left_shift(T lhs, T rhs) { return lhs << rhs; } GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( LeftShift, /*test_name=*/Int8, int8, int8, test::DefaultInput<int8>(), test::DefaultInputLessThanBitwidth<int8>(), baseline_left_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( LeftShift, /*test_name=*/Int16, int16, int16, test::DefaultInput<int16>(), test::DefaultInputLessThanBitwidth<int16>(), baseline_left_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( LeftShift, /*test_name=*/Int32, int32, int32, test::DefaultInput<int32>(), test::DefaultInputLessThanBitwidth<int32>(), baseline_left_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( LeftShift, /*test_name=*/Int64, int64, int64, test::DefaultInput<int64>(), test::DefaultInputLessThanBitwidth<int64>(), baseline_left_shift) /// Test `tf.Less`. template <typename T> bool baseline_less(T lhs, T rhs) { return lhs < rhs; } GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Half, Eigen::half, bool, baseline_less) GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Float, float, bool, baseline_less) GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Double, double, bool, baseline_less) GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Int8, int8, bool, baseline_less) GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Int16, int16, bool, baseline_less) GENERATE_DEFAULT_TESTS(Less, /*test_name=*/Int64, int64, bool, baseline_less) /// Test `tf.LessEqual`. template <typename T> bool baseline_less_equal(T lhs, T rhs) { return lhs <= rhs; } GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Half, Eigen::half, bool, baseline_less_equal) GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Float, float, bool, baseline_less_equal) GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Double, double, bool, baseline_less_equal) GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Int8, int8, bool, baseline_less_equal) GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Int16, int16, bool, baseline_less_equal) GENERATE_DEFAULT_TESTS(LessEqual, /*test_name=*/Int64, int64, bool, baseline_less_equal) /// Test `tf.LogicalAnd`. bool baseline_logical_and(bool lhs, bool rhs) { return lhs && rhs; } GENERATE_DEFAULT_TESTS_2(LogicalAnd, /*test_name=*/Bool, /*T=*/bool, /*BaselineT=*/bool, /*OutT=*/bool, /*BaselineOutT=*/bool, test::DefaultInput<bool>(), test::DefaultInput<bool>(), baseline_logical_and, test::OpsTestConfig().ExpectStrictlyEqual().NoT()) /// Test `tf.LogicalOr`. bool baseline_logical_or(bool lhs, bool rhs) { return lhs || rhs; } GENERATE_DEFAULT_TESTS_2(LogicalOr, /*test_name=*/Bool, /*T=*/bool, /*BaselineT=*/bool, /*OutT=*/bool, /*BaselineOutT=*/bool, test::DefaultInput<bool>(), test::DefaultInput<bool>(), baseline_logical_or, test::OpsTestConfig().ExpectStrictlyEqual().NoT()) /// Test `tf.Maximum`. template <typename T> T baseline_maximum(T lhs, T rhs) { if (std::isnan(lhs) || std::isnan(rhs)) { return lhs + rhs; } return std::max(lhs, rhs); } GENERATE_DEFAULT_TESTS(Maximum, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_maximum) GENERATE_DEFAULT_TESTS(Maximum, /*test_name=*/Float, float, float, baseline_maximum) GENERATE_DEFAULT_TESTS(Maximum, /*test_name=*/Double, double, double, baseline_maximum) GENERATE_DEFAULT_TESTS(Maximum, /*test_name=*/Int64, int64, int64, baseline_maximum) /// Test `tf.Minmum`. template <typename T> T baseline_minimum(T lhs, T rhs) { if (std::isnan(lhs) || std::isnan(rhs)) { return lhs + rhs; } return std::min(lhs, rhs); } GENERATE_DEFAULT_TESTS(Minimum, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_minimum) GENERATE_DEFAULT_TESTS(Minimum, /*test_name=*/Float, float, float, baseline_minimum) GENERATE_DEFAULT_TESTS(Minimum, /*test_name=*/Double, double, double, baseline_minimum) GENERATE_DEFAULT_TESTS(Minimum, /*test_name=*/Int64, int64, int64, baseline_minimum) /// Test `tf.Mul`. template <typename T> T baseline_mul(T lhs, T rhs) { return lhs * rhs; } GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_mul) GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Float, float, float, baseline_mul) GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Double, double, double, baseline_mul) GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Int8, int8, int8, baseline_mul) GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Int16, int16, int16, baseline_mul) GENERATE_DEFAULT_TESTS(Mul, /*test_name=*/Int64, int64, int64, baseline_mul) /// Test `tf.NotEqual`. template <typename T> bool baseline_not_equal(T lhs, T rhs) { return lhs != rhs; } GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Half, Eigen::half, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Float, float, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Double, double, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Bool, bool, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Int8, int8, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Int16, int16, bool, baseline_not_equal) GENERATE_DEFAULT_TESTS(NotEqual, /*test_name=*/Int64, int64, bool, baseline_not_equal) /// Test `tf.Pow`. template <typename T> T baseline_pow(T lhs, T rhs) { return std::pow(lhs, rhs); } template <typename T, std::enable_if_t< llvm::is_one_of<T, Eigen::half, float, double>::value, bool> = true> absl::InlinedVector<T, 10> PowInput() { return test::InputAsVector<T, double>({0.0, 0.1, 0.2, 0.3, 1.0, 2.0, 3.0}); } template <typename T, std::enable_if_t<llvm::is_one_of<T, int8, int16, int32, int64>::value, bool> = true> absl::InlinedVector<T, 10> PowInput() { return test::InputAsVector<T, double>({-2, -1, -1, 1, 1, 3}); } template <> Eigen::half baseline_pow(Eigen::half lhs, Eigen::half rhs) { return static_cast<Eigen::half>( std::pow(static_cast<float>(lhs), static_cast<float>(rhs))); } GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES(Pow, /*test_name=*/Half, Eigen::half, Eigen::half, PowInput<Eigen::half>(), PowInput<Eigen::half>(), baseline_pow) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES(Pow, /*test_name=*/Float, float, float, PowInput<float>(), PowInput<float>(), baseline_pow) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES(Pow, /*test_name=*/Double, double, double, PowInput<double>(), PowInput<double>(), baseline_pow) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES(Pow, /*test_name=*/Int64, int64, int64, PowInput<int64>(), PowInput<int64>(), baseline_pow) /// Test `tf.RealDiv`. GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RealDiv, /*test_name=*/Half, Eigen::half, Eigen::half, test::DefaultInput<Eigen::half>(), test::DefaultInputNonZero<Eigen::half>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RealDiv, /*test_name=*/Float, float, float, test::DefaultInput<float>(), test::DefaultInputNonZero<float>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RealDiv, /*test_name=*/Double, double, double, test::DefaultInput<double>(), test::DefaultInputNonZero<double>(), baseline_div); /// Test `tf.RightShift`. template <typename T> T baseline_right_shift(T lhs, T rhs) { return lhs >> rhs; } GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RightShift, /*test_name=*/Int8, int8, int8, test::DefaultInput<int8>(), test::DefaultInputLessThanBitwidth<int8>(), baseline_right_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RightShift, /*test_name=*/Int16, int16, int16, test::DefaultInput<int16>(), test::DefaultInputLessThanBitwidth<int16>(), baseline_right_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RightShift, /*test_name=*/Int32, int32, int32, test::DefaultInput<int32>(), test::DefaultInputLessThanBitwidth<int32>(), baseline_right_shift) GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( RightShift, /*test_name=*/Int64, int64, int64, test::DefaultInput<int64>(), test::DefaultInputLessThanBitwidth<int64>(), baseline_right_shift) /// Test `tf.SquaredDifference`. template <typename T> T baseline_squared_difference(T lhs, T rhs) { return (lhs - rhs) * (lhs - rhs); } GENERATE_DEFAULT_TESTS(SquaredDifference, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_squared_difference) GENERATE_DEFAULT_TESTS(SquaredDifference, /*test_name=*/Float, float, float, baseline_squared_difference) GENERATE_DEFAULT_TESTS(SquaredDifference, /*test_name=*/Double, double, double, baseline_squared_difference) GENERATE_DEFAULT_TESTS(SquaredDifference, /*test_name=*/Int64, int64, int64, baseline_squared_difference) /// Test `tf.Sub`. template <typename T> T baseline_sub(T lhs, T rhs) { return lhs - rhs; } GENERATE_DEFAULT_TESTS(Sub, /*test_name=*/Half, Eigen::half, Eigen::half, baseline_sub) GENERATE_DEFAULT_TESTS(Sub, /*test_name=*/Float, float, float, baseline_sub) GENERATE_DEFAULT_TESTS(Sub, /*test_name=*/Double, double, double, baseline_sub) GENERATE_DEFAULT_TESTS(Sub, /*test_name=*/Int64, int64, int64, baseline_sub) /// Test `tf.TruncateDiv`. GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( TruncateDiv, /*test_name=*/Int16, int16, int16, test::DefaultInput<int16>(), test::DefaultInputNonZero<int16>(), baseline_div); GENERATE_DEFAULT_TESTS_WITH_SPECIFIC_INPUT_VALUES( TruncateDiv, /*test_name=*/Int64, int64, int64, test::DefaultInput<int64>(), test::DefaultInputNonZero<int64>(), baseline_div); } // namespace } // namespace tensorflow
/* * tinflate.c -- tiny inflate library * * Written by Andrew Church <achurch@achurch.org> * * Re-written for C++ by LAK132 <https://github.com/LAK132> * * This source code is public domain. */ #include "lak/tinflate.hpp" namespace tinf { static constexpr uint32_t crc32_table[256] = { 0x00000000UL, 0x77073096UL, 0xEE0E612CUL, 0x990951BAUL, 0x076DC419UL, 0x706AF48FUL, 0xE963A535UL, 0x9E6495A3UL, 0x0EDB8832UL, 0x79DCB8A4UL, 0xE0D5E91EUL, 0x97D2D988UL, 0x09B64C2BUL, 0x7EB17CBDUL, 0xE7B82D07UL, 0x90BF1D91UL, 0x1DB71064UL, 0x6AB020F2UL, 0xF3B97148UL, 0x84BE41DEUL, 0x1ADAD47DUL, 0x6DDDE4EBUL, 0xF4D4B551UL, 0x83D385C7UL, 0x136C9856UL, 0x646BA8C0UL, 0xFD62F97AUL, 0x8A65C9ECUL, 0x14015C4FUL, 0x63066CD9UL, 0xFA0F3D63UL, 0x8D080DF5UL, 0x3B6E20C8UL, 0x4C69105EUL, 0xD56041E4UL, 0xA2677172UL, 0x3C03E4D1UL, 0x4B04D447UL, 0xD20D85FDUL, 0xA50AB56BUL, 0x35B5A8FAUL, 0x42B2986CUL, 0xDBBBC9D6UL, 0xACBCF940UL, 0x32D86CE3UL, 0x45DF5C75UL, 0xDCD60DCFUL, 0xABD13D59UL, 0x26D930ACUL, 0x51DE003AUL, 0xC8D75180UL, 0xBFD06116UL, 0x21B4F4B5UL, 0x56B3C423UL, 0xCFBA9599UL, 0xB8BDA50FUL, 0x2802B89EUL, 0x5F058808UL, 0xC60CD9B2UL, 0xB10BE924UL, 0x2F6F7C87UL, 0x58684C11UL, 0xC1611DABUL, 0xB6662D3DUL, 0x76DC4190UL, 0x01DB7106UL, 0x98D220BCUL, 0xEFD5102AUL, 0x71B18589UL, 0x06B6B51FUL, 0x9FBFE4A5UL, 0xE8B8D433UL, 0x7807C9A2UL, 0x0F00F934UL, 0x9609A88EUL, 0xE10E9818UL, 0x7F6A0DBBUL, 0x086D3D2DUL, 0x91646C97UL, 0xE6635C01UL, 0x6B6B51F4UL, 0x1C6C6162UL, 0x856530D8UL, 0xF262004EUL, 0x6C0695EDUL, 0x1B01A57BUL, 0x8208F4C1UL, 0xF50FC457UL, 0x65B0D9C6UL, 0x12B7E950UL, 0x8BBEB8EAUL, 0xFCB9887CUL, 0x62DD1DDFUL, 0x15DA2D49UL, 0x8CD37CF3UL, 0xFBD44C65UL, 0x4DB26158UL, 0x3AB551CEUL, 0xA3BC0074UL, 0xD4BB30E2UL, 0x4ADFA541UL, 0x3DD895D7UL, 0xA4D1C46DUL, 0xD3D6F4FBUL, 0x4369E96AUL, 0x346ED9FCUL, 0xAD678846UL, 0xDA60B8D0UL, 0x44042D73UL, 0x33031DE5UL, 0xAA0A4C5FUL, 0xDD0D7CC9UL, 0x5005713CUL, 0x270241AAUL, 0xBE0B1010UL, 0xC90C2086UL, 0x5768B525UL, 0x206F85B3UL, 0xB966D409UL, 0xCE61E49FUL, 0x5EDEF90EUL, 0x29D9C998UL, 0xB0D09822UL, 0xC7D7A8B4UL, 0x59B33D17UL, 0x2EB40D81UL, 0xB7BD5C3BUL, 0xC0BA6CADUL, 0xEDB88320UL, 0x9ABFB3B6UL, 0x03B6E20CUL, 0x74B1D29AUL, 0xEAD54739UL, 0x9DD277AFUL, 0x04DB2615UL, 0x73DC1683UL, 0xE3630B12UL, 0x94643B84UL, 0x0D6D6A3EUL, 0x7A6A5AA8UL, 0xE40ECF0BUL, 0x9309FF9DUL, 0x0A00AE27UL, 0x7D079EB1UL, 0xF00F9344UL, 0x8708A3D2UL, 0x1E01F268UL, 0x6906C2FEUL, 0xF762575DUL, 0x806567CBUL, 0x196C3671UL, 0x6E6B06E7UL, 0xFED41B76UL, 0x89D32BE0UL, 0x10DA7A5AUL, 0x67DD4ACCUL, 0xF9B9DF6FUL, 0x8EBEEFF9UL, 0x17B7BE43UL, 0x60B08ED5UL, 0xD6D6A3E8UL, 0xA1D1937EUL, 0x38D8C2C4UL, 0x4FDFF252UL, 0xD1BB67F1UL, 0xA6BC5767UL, 0x3FB506DDUL, 0x48B2364BUL, 0xD80D2BDAUL, 0xAF0A1B4CUL, 0x36034AF6UL, 0x41047A60UL, 0xDF60EFC3UL, 0xA867DF55UL, 0x316E8EEFUL, 0x4669BE79UL, 0xCB61B38CUL, 0xBC66831AUL, 0x256FD2A0UL, 0x5268E236UL, 0xCC0C7795UL, 0xBB0B4703UL, 0x220216B9UL, 0x5505262FUL, 0xC5BA3BBEUL, 0xB2BD0B28UL, 0x2BB45A92UL, 0x5CB36A04UL, 0xC2D7FFA7UL, 0xB5D0CF31UL, 0x2CD99E8BUL, 0x5BDEAE1DUL, 0x9B64C2B0UL, 0xEC63F226UL, 0x756AA39CUL, 0x026D930AUL, 0x9C0906A9UL, 0xEB0E363FUL, 0x72076785UL, 0x05005713UL, 0x95BF4A82UL, 0xE2B87A14UL, 0x7BB12BAEUL, 0x0CB61B38UL, 0x92D28E9BUL, 0xE5D5BE0DUL, 0x7CDCEFB7UL, 0x0BDBDF21UL, 0x86D3D2D4UL, 0xF1D4E242UL, 0x68DDB3F8UL, 0x1FDA836EUL, 0x81BE16CDUL, 0xF6B9265BUL, 0x6FB077E1UL, 0x18B74777UL, 0x88085AE6UL, 0xFF0F6A70UL, 0x66063BCAUL, 0x11010B5CUL, 0x8F659EFFUL, 0xF862AE69UL, 0x616BFFD3UL, 0x166CCF45UL, 0xA00AE278UL, 0xD70DD2EEUL, 0x4E048354UL, 0x3903B3C2UL, 0xA7672661UL, 0xD06016F7UL, 0x4969474DUL, 0x3E6E77DBUL, 0xAED16A4AUL, 0xD9D65ADCUL, 0x40DF0B66UL, 0x37D83BF0UL, 0xA9BCAE53UL, 0xDEBB9EC5UL, 0x47B2CF7FUL, 0x30B5FFE9UL, 0xBDBDF21CUL, 0xCABAC28AUL, 0x53B39330UL, 0x24B4A3A6UL, 0xBAD03605UL, 0xCDD70693UL, 0x54DE5729UL, 0x23D967BFUL, 0xB3667A2EUL, 0xC4614AB8UL, 0x5D681B02UL, 0x2A6F2B94UL, 0xB40BBE37UL, 0xC30C8EA1UL, 0x5A05DF1BUL, 0x2D02EF8DUL}; const char *error_name(error_t error) { switch (error) { case error_t::OK: return "Ok"; case error_t::NO_DATA: return "No data"; case error_t::INVALID_PARAMETER: return "Invalid parameter"; case error_t::CUSTOM_DICTIONARY: return "Custom dictionary"; case error_t::INVALID_STATE: return "Invalid state"; case error_t::INVALID_BLOCK_CODE: return "Invalid block code"; case error_t::OUT_OF_DATA: return "Out of data"; case error_t::OUTPUT_FULL: return "Output buffer full"; case error_t::CORRUPT_STREAM: return "Corrupt stream"; case error_t::HUFFMAN_TABLE_GEN_FAILED: return "Huffman table gen failed"; case error_t::INVALID_SYMBOL: return "Invalid symbol"; case error_t::INVALID_DISTANCE: return "Invalid distance"; case error_t::NO_SYMBOLS: return "No symbols"; case error_t::TOO_MANY_SYMBOLS: return "Too many symbols"; case error_t::INCOMPLETE_TREE: return "Incomplete tree"; default: return "Not a tinflate error"; } } error_t tinflate(lak::span<const byte_t> compressed, lak::array<byte_t> *output, uint32_t *crc) { decompression_state_t state; return tinflate(compressed, output, state, crc); } error_t tinflate(lak::span<const byte_t> compressed, lak::array<byte_t> *output, decompression_state_t &state, uint32_t *crc) { auto &buffer = *output; byte_t *head = buffer.data() + buffer.size(); auto double_size = [&]() { size_t offset = head - buffer.data(); buffer.resize(buffer.size() * 2); head = buffer.data() + offset; }; if (buffer.empty()) { buffer.resize(0x100); head = buffer.data(); } else { double_size(); } error_t err = error_t::OK; while (err == error_t::OK && (state.state != tinf::state_t::HEADER || !state.final)) { err = tinflate(compressed, lak::span(buffer), &head, state, crc); while (err == tinf::error_t::OUTPUT_FULL) { double_size(); err = tinflate(compressed, lak::span(buffer), &head, state, crc); } } buffer.resize(head - buffer.data()); return err; } error_t tinflate(lak::span<const byte_t> compressed, lak::span<byte_t> output, byte_t **head, uint32_t *crc) { decompression_state_t state; return tinflate(compressed, output, head, state, crc); } error_t tinflate(lak::span<const byte_t> compressed, lak::span<byte_t> output, byte_t **head, decompression_state_t &state, uint32_t *crc) { state.data = compressed; if (error_t er = tinflate_header(state); er != error_t::OK) return er; do { error_t res = tinflate_block(output, head, state); if (res != error_t::OK) return res; } while (state.state != tinf::state_t::HEADER || !state.final); if (crc) *crc = state.crc; return error_t::OK; } error_t tinflate_header(decompression_state_t &state) { if (state.data.empty()) return error_t::OUT_OF_DATA; if (state.state == state_t::INITIAL || state.state == state_t::PARTIAL_ZLIB_HEADER) { uint16_t zlibHeader; if (state.data.size() == 0) { return error_t::OUT_OF_DATA; } if (state.state == state_t::INITIAL && state.data.size() == 1) { state.first_byte = uint8_t(state.data[0]); state.state = state_t::PARTIAL_ZLIB_HEADER; return error_t::OUT_OF_DATA; } if (state.state == state_t::PARTIAL_ZLIB_HEADER) { zlibHeader = (state.first_byte << 8) | uint8_t(state.data[0]); } else { zlibHeader = (uint8_t(state.data[0]) << 8) | uint8_t(state.data[1]); } if ((zlibHeader & 0x8F00) == 0x0800 && (zlibHeader % 31) == 0) { if (zlibHeader & 0x0020) return error_t::CUSTOM_DICTIONARY; const unsigned int increment = (state.state == state_t::PARTIAL_ZLIB_HEADER ? 1 : 2); if (increment > state.data.size()) return error_t::OUT_OF_DATA; state.data = state.data.subspan(increment); } else if (state.state == state_t::PARTIAL_ZLIB_HEADER) { state.bit_accum = state.first_byte; state.num_bits = 8; } state.state = state_t::HEADER; } return error_t::OK; } error_t tinflate_block(lak::span<byte_t> output, byte_t **head, decompression_state_t &state) { uint32_t icrc = ~state.crc; if (*head < output.begin()) *head = output.begin(); if (*head >= output.end()) return error_t::OUTPUT_FULL; auto push = [&](const byte_t val) -> bool { if (*head >= output.end()) return false; *((*head)++) = val; icrc = crc32_table[(icrc & 0xFF) ^ uint8_t(val)] ^ ((icrc >> 8) & 0xFF'FFFFUL); return true; }; auto out_of_data = [&state, &icrc]() -> error_t { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::OUT_OF_DATA; }; static const uint8_t codelen_order[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const uint8_t codelen_order_anaconda[19] = { 18, 17, 16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}; #define SET_STATE(STATE) \ state.state = state_t::STATE; \ [[fallthrough]]; \ case state_t::STATE: switch (state.state) { case state_t::HEADER: if (state.anaconda) { if (state.get_bits(4, &state.block_type)) return out_of_data(); state.final = state.block_type >> 3; state.block_type &= 0x7; if (state.block_type == 7) state.block_type = 0; else if (state.block_type == 5) state.block_type = 1; else if (state.block_type == 6) state.block_type = 2; else state.block_type = 3; } else { if (state.get_bits(3, &state.block_type)) return out_of_data(); state.final = state.block_type & 0x1; state.block_type >>= 1; } if (state.block_type == 3) { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::INVALID_BLOCK_CODE; } if (state.block_type == 0) { state.num_bits = 0; SET_STATE(UNCOMPRESSED_LEN) if (state.get_bits(16, &state.len)) return out_of_data(); SET_STATE(UNCOMPRESSED_ILEN) if (!state.anaconda) { if (state.get_bits(16, &state.ilen)) return out_of_data(); if (state.ilen != (~state.len & 0xFFFF)) { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::CORRUPT_STREAM; } } state.nread = 0; SET_STATE(UNCOMPRESSED_DATA) while (state.nread < state.len) { if (state.data.empty()) return out_of_data(); if (!push(state.data[0])) return error_t::OUTPUT_FULL; state.data = state.data.subspan(1); ++state.nread; } state.crc = ~icrc & 0xFFFF'FFFFUL; state.state = state_t::HEADER; return error_t::OK; } if (state.block_type == 2) { SET_STATE(LITERAL_COUNT) if (state.get_bits(5, &state.literal_count)) return out_of_data(); state.literal_count += 257; SET_STATE(DISTANCE_COUNT) if (state.get_bits(5, &state.distance_count)) return out_of_data(); state.distance_count += 1; SET_STATE(CODELEN_COUNT) if (state.get_bits(4, &state.codelen_count)) return out_of_data(); state.codelen_count += 4; state.counter = 0; SET_STATE(READ_CODE_LENGTHS) if (state.anaconda) { for (; state.counter < state.codelen_count; ++state.counter) if (state.get_bits( 3, &state.codelen_len[codelen_order_anaconda[state.counter]])) return out_of_data(); for (; state.counter < 19; ++state.counter) state.codelen_len[codelen_order_anaconda[state.counter]] = 0; } else { for (; state.counter < state.codelen_count; ++state.counter) if (state.get_bits( 3, &state.codelen_len[codelen_order[state.counter]])) return out_of_data(); for (; state.counter < 19; ++state.counter) state.codelen_len[codelen_order[state.counter]] = 0; } if (gen_huffman_table( 19, state.codelen_len, false, state.codelen_table) != error_t::OK) { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::HUFFMAN_TABLE_GEN_FAILED; } state.repeat_count = 0; state.last_value = 0; state.counter = 0; SET_STATE(READ_LENGTHS) while (state.counter < state.literal_count + state.distance_count) { if (state.repeat_count == 0) { if (state.get_huff(state.codelen_table, &state.symbol)) return out_of_data(); if (state.symbol < 16) { state.last_value = state.symbol; state.repeat_count = 1; } else if (state.symbol == 16) { SET_STATE(READ_LENGTHS_16) if (state.get_bits(2, &state.repeat_count)) return out_of_data(); state.repeat_count += 3; } else if (state.symbol == 17) { state.last_value = 0; SET_STATE(READ_LENGTHS_17) if (state.get_bits(3, &state.repeat_count)) return out_of_data(); state.repeat_count += 3; } else if (state.symbol) { state.last_value = 0; SET_STATE(READ_LENGTHS_18) if (state.get_bits(7, &state.repeat_count)) return out_of_data(); state.repeat_count += 11; } } if (state.counter < state.literal_count) state.literal_len[state.counter] = (uint8_t)state.last_value; else state.distance_len[state.counter - state.literal_count] = (uint8_t)state.last_value; ++state.counter; --state.repeat_count; state.state = state_t::READ_LENGTHS; } if (gen_huffman_table(state.literal_count, state.literal_len, false, state.literal_table) != error_t::OK || gen_huffman_table(state.distance_count, state.distance_len, true, state.distance_table) != error_t::OK) { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::HUFFMAN_TABLE_GEN_FAILED; } } else { int32_t next_free = 2; int32_t i; for (i = 0; i < 0x7E; ++i) { state.literal_table[i] = int16_t(~next_free); next_free += 2; } for (; i < 0x96; ++i) state.literal_table[i] = (int16_t)i + (256 - 0x7E); for (; i < 0xFE; ++i) { state.literal_table[i] = int16_t(~next_free); next_free += 2; } for (; i < 0x18E; ++i) state.literal_table[i] = (int16_t)i + (0 - 0xFE); for (; i < 0x196; ++i) state.literal_table[i] = (int16_t)i + (280 - 0x18E); for (; i < 0x1CE; ++i) { state.literal_table[i] = int16_t(~next_free); next_free += 2; } for (; i < 0x23E; ++i) state.literal_table[i] = (int16_t)i + (144 - 0x1CE); for (i = 0; i < 0x1E; ++i) state.distance_table[i] = int16_t(~(i * 2 + 2)); for (i = 0x1E; i < 0x3E; ++i) state.distance_table[i] = int16_t(i - 0x1E); } for (;;) { SET_STATE(READ_SYMBOL) if (state.get_huff(state.literal_table, &state.symbol)) return out_of_data(); if (state.symbol < 256) { SET_STATE(PUSH_SYMBOL) if (!push((byte_t)state.symbol)) return error_t::OUTPUT_FULL; continue; } if (state.symbol == 256) break; if (state.symbol <= 264) { state.repeat_length = (state.symbol - 257) + 3; } else if (state.symbol <= 284) { SET_STATE(READ_LENGTH) const uint32_t lengthBits = (state.symbol - 261) / 4; if (state.get_bits(lengthBits, &state.repeat_length)) return out_of_data(); state.repeat_length += 3 + ((4 + ((state.symbol - 265) & 3)) << lengthBits); } else if (state.symbol == 285) { state.repeat_length = 258; } else { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::INVALID_SYMBOL; } SET_STATE(READ_DISTANCE) if (state.get_huff(state.distance_table, &state.symbol)) return out_of_data(); if (state.symbol <= 3) { state.distance = state.symbol + 1; } else if (state.symbol <= 29) { SET_STATE(READ_DISTANCE_EXTRA) const uint32_t distance_bits = (state.symbol - 2) / 2; if (state.get_bits(distance_bits, &state.distance)) return out_of_data(); state.distance += 1 + ((2 + (state.symbol & 1)) << distance_bits); } else { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::INVALID_SYMBOL; } if (state.distance > static_cast<uintptr_t>(*head - output.begin())) { state.crc = ~icrc & 0xFFFF'FFFFUL; return error_t::INVALID_DISTANCE; // There wasn't enough data in the back buffer. } SET_STATE(WRITE_REPEAT) for (; state.repeat_length > 0; --state.repeat_length) if (!push(*((*head) - state.distance))) return error_t::OUTPUT_FULL; state.repeat_length = 0; } break; case state_t::INITIAL: [[fallthrough]]; case state_t::PARTIAL_ZLIB_HEADER: [[fallthrough]]; default: return error_t::INVALID_STATE; } #undef SET_STATE state.crc = ~icrc & 0xFFFF'FFFFUL; state.state = state_t::HEADER; return error_t::OK; } error_t gen_huffman_table(uint32_t symbols, const uint8_t *lengths, bool allow_no_symbols, int16_t *table) { uint16_t length_count[16] = {0}; uint16_t total_count = 0; uint16_t first_code[16]; for (uint32_t i = 0; i < symbols; ++i) if (lengths[i] > 0) ++length_count[lengths[i]]; for (uint32_t i = 1; i < 16; ++i) total_count += length_count[i]; if (total_count == 0) { return allow_no_symbols ? error_t::OK : error_t::NO_SYMBOLS; } else if (total_count == 1) { for (uint32_t i = 0; i < symbols; ++i) if (lengths[i] != 0) table[0] = table[1] = (uint16_t)i; return error_t::OK; } first_code[0] = 0; for (uint32_t i = 1; i < 16; ++i) { first_code[i] = (first_code[i - 1] + length_count[i - 1]) << 1; if (first_code[i] + length_count[i] > (uint16_t)1 << i) return error_t::TOO_MANY_SYMBOLS; } if (first_code[15] + length_count[15] != (uint16_t)1 << 15) return error_t::INCOMPLETE_TREE; for (uint32_t index = 0, i = 1; i < 16; ++i) { uint32_t code_limit = 1U << i; uint32_t next_code = first_code[i] + length_count[i]; uint32_t next_index = index + (code_limit - first_code[i]); for (uint32_t j = 0; j < symbols; ++j) if (lengths[j] == i) table[index++] = (uint16_t)j; for (uint32_t j = next_code; j < code_limit; ++j) { table[index++] = int16_t(~next_index); next_index += 2; } } return error_t::OK; } }
#include <iostream> #include <cxxopts.hpp> #include <libnotify/notify.h> int main(int argc, char *argv[]) { notify_init("Sample"); NotifyNotification *n = notify_notification_new( "Hello world", "some message text... bla bla", 0); notify_notification_set_timeout(n, 10000); // 10 seconds if (!notify_notification_show(n, 0)) { std::cerr << "show has failed" << std::endl; return -1; } return 0; } // g++ hello_world.cc -o hello_world `pkg-config --cflags --libs libnotify
//========= Copyright � 1996-2005, Valve Corporation, All rights reserved. ============// // // Purpose: Client DLL VGUI2 Viewport // // $Workfile: $ // $Date: $ // //----------------------------------------------------------------------------- // $Log: $ // // $NoKeywords: $ //=============================================================================// #include "cbase.h" // vgui panel includes #include <vgui_controls/Panel.h> #include <vgui/ISurface.h> #include <keyvalues.h> #include <vgui/Cursor.h> #include <vgui/IScheme.h> #include <vgui/IVGui.h> #include <vgui/ILocalize.h> #include <vgui/vgui.h> // client dll/engine defines #include "hud.h" #include <voice_status.h> // cstrike specific dialogs #include "clientmode_csnormal.h" #include "IGameUIFuncs.h" // viewport definitions #include <baseviewport.h> #include "counterstrikeviewport.h" #include "cs_gamerules.h" // #include "c_user_message_register.h" #include "vguicenterprint.h" #include "text_message.h" #include "teammenu_scaleform.h" #include "chooseclass_scaleform.h" #include "Scaleform/HUD/sfhudinfopanel.h" #include "Scaleform/HUD/sfhudwinpanel.h" #include "Scaleform/loadingscreen_scaleform.h" #if defined( CSTRIKE15 ) #include "basepanel.h" #endif static void OpenPanelWithCheck( const char *panelToOpen, const char *panelToCheck ) { IViewPortPanel *checkPanel = GetViewPortInterface()->FindPanelByName( panelToCheck ); if ( !checkPanel || !checkPanel->IsVisible() ) { GetViewPortInterface()->ShowPanel( panelToOpen, true ); } } void PrintBuyTimeOverMessage( void ) { CHudElement *pElement = GetHud().FindElement( "SFHudInfoPanel" ); if ( pElement ) { char strBuyTime[16]; int nBuyTime = ( int )CSGameRules()->GetBuyTimeLength(); Q_snprintf( strBuyTime, sizeof( strBuyTime ), "%d", nBuyTime ); wchar_t buffer[128]; wchar_t buytime[16]; g_pVGuiLocalize->ConvertANSIToUnicode( strBuyTime, buytime, sizeof( buytime ) ); if ( nBuyTime == 0 ) g_pVGuiLocalize->ConstructString( buffer, sizeof( buffer ), g_pVGuiLocalize->Find( "#SFUI_BuyMenu_YoureOutOfTime" ), 0 ); else g_pVGuiLocalize->ConstructString( buffer, sizeof( buffer ), g_pVGuiLocalize->Find( "#SFUI_BuyMenu_OutOfTime" ), 1, buytime ); ((SFHudInfoPanel *)pElement)->SetPriorityText( buffer ); } } CON_COMMAND_F( teammenu, "Show team selection window", FCVAR_SERVER_CAN_EXECUTE ) { C_CSPlayer *pPlayer = C_CSPlayer::GetLocalCSPlayer(); if( pPlayer && pPlayer->CanShowTeamMenu() ) { ( ( CounterStrikeViewport * )GetViewPortInterface() )->SetChoseTeamAndClass( true ); GetViewPortInterface()->ShowPanel( PANEL_TEAM, true ); } } CON_COMMAND_F( buymenu, "Show or hide main buy menu", FCVAR_SERVER_CAN_EXECUTE ) { bool bShowIt = true; C_CSPlayer *pPlayer = C_CSPlayer::GetLocalCSPlayer(); if ( args.ArgC() == 2 ) { bShowIt = atoi( args[ 1 ] ) == 1; } if( pPlayer && bShowIt ) { if ( pPlayer->m_lifeState != LIFE_ALIVE && pPlayer->State_Get() != STATE_ACTIVE ) return; extern ConVar mp_buy_anywhere; extern ConVar mp_buy_during_immunity; static ConVarRef sv_buy_status_override_ref( "sv_buy_status_override" ); // UNUSED: int nGuardianTeam = CSGameRules()->IsHostageRescueMap() ? TEAM_TERRORIST : TEAM_CT; if ( CSGameRules()->IsPlayingCooperativeGametype() ) { if ( CSGameRules()->IsWarmupPeriod() == false && CSGameRules()->m_flGuardianBuyUntilTime < gpGlobals->curtime ) { int nTeam = CSGameRules()->IsHostageRescueMap() ? TEAM_TERRORIST : TEAM_CT; int iBuyStatus = sv_buy_status_override_ref.GetInt(); if ( iBuyStatus > 0 && (( nTeam == TEAM_CT && iBuyStatus != 1 ) || ( nTeam == TEAM_TERRORIST && iBuyStatus != 2 )) ) GetCenterPrint()->Print( "#SFUI_BuyMenu_CantBuy" ); else GetCenterPrint()->Print( "#SFUI_BuyMenu_CantBuyTilNextWave" ); } else { CSGameRules()->OpenBuyMenu( pPlayer->GetUserID() ); } } else if ( CSGameRules()->IsPlayingCoopMission() && sv_buy_status_override_ref.GetInt() == 3 ) { GetCenterPrint()->Print( "#SFUI_BuyMenu_CantBuy" ); } else if ( !pPlayer->IsInBuyPeriod() ) { PrintBuyTimeOverMessage(); } else if ( !pPlayer->IsInBuyZone() ) { GetCenterPrint()->Print( "#SFUI_BuyMenu_NotInBuyZone" ); } else { CSGameRules()->OpenBuyMenu( pPlayer->GetUserID() ); } } else if( pPlayer && !bShowIt ) { // Hide the menu CSGameRules()->CloseBuyMenu( pPlayer->GetUserID() ); } } //CON_COMMAND_F( spec_help, "Show spectator help screen", FCVAR_CLIENTCMD_CAN_EXECUTE ) //{ // if ( GetViewPortInterface() ) // GetViewPortInterface()->ShowPanel( PANEL_INFO, true ); //} CON_COMMAND_F( spec_menu, "Activates spectator menu", FCVAR_CLIENTCMD_CAN_EXECUTE ) { bool bShowIt = true; C_CSPlayer *pPlayer = C_CSPlayer::GetLocalCSPlayer(); if ( pPlayer && !pPlayer->IsObserver() ) return; if ( args.ArgC() == 2 ) { bShowIt = atoi( args[ 1 ] ) == 1; } if ( GetViewPortInterface() ) GetViewPortInterface()->ShowPanel( PANEL_SPECMENU, bShowIt ); } CON_COMMAND_F( spec_gui, "Shows or hides the spectator bar", FCVAR_CLIENTCMD_CAN_EXECUTE ) { bool bShowIt = true; C_CSPlayer *pPlayer = C_CSPlayer::GetLocalCSPlayer(); if ( pPlayer && !pPlayer->IsObserver() ) return; if ( args.ArgC() == 2 ) { bShowIt = atoi( args[ 1 ] ) == 1; } if ( bShowIt && GetViewPortInterface() && GetViewPortInterface()->GetActivePanel() ) { // if the team screen is up, it takes precedence - don't show the spectator GUI if ( !V_strcmp( GetViewPortInterface()->GetActivePanel()->GetName(), PANEL_TEAM ) ) return; } if ( GetViewPortInterface() ) GetViewPortInterface()->ShowPanel( PANEL_SPECGUI, bShowIt ); } CON_COMMAND_F( togglescores, "Toggles score panel", FCVAR_CLIENTCMD_CAN_EXECUTE ) { if ( !GetViewPortInterface() ) return; IViewPortPanel *scoreboard = GetViewPortInterface()->FindPanelByName( PANEL_SCOREBOARD ); if ( !scoreboard ) return; if ( scoreboard->IsVisible() ) { GetViewPortInterface()->ShowPanel( scoreboard, false ); GetClientVoiceMgr()->StopSquelchMode(); } else { // Disallow bringing the Scoreboard up while we are paused if ( BasePanel() && BasePanel()->IsScaleformPauseMenuActive() ) return; GetViewPortInterface()->ShowPanel( scoreboard, true ); } } CON_COMMAND_F( hidescores, "Forcibly hide score panel", FCVAR_CLIENTCMD_CAN_EXECUTE ) { if ( !GetViewPortInterface() ) return; IViewPortPanel *scoreboard = GetViewPortInterface()->FindPanelByName( PANEL_SCOREBOARD ); if ( !scoreboard ) return; if ( scoreboard->IsVisible() ) { GetViewPortInterface()->ShowPanel( scoreboard, false ); GetClientVoiceMgr()->StopSquelchMode(); } } //----------------------------------------------------------------------------- // Purpose: called when the VGUI subsystem starts up // Creates the sub panels and initialises them //----------------------------------------------------------------------------- void CounterStrikeViewport::Start( IGameUIFuncs *pGameUIFuncs, IGameEventManager2 * pGameEventManager ) { BaseClass::Start( pGameUIFuncs, pGameEventManager ); SetChoseTeamAndClass( false ); } void CounterStrikeViewport::ApplySchemeSettings( vgui::IScheme *pScheme ) { BaseClass::ApplySchemeSettings( pScheme ); ListenForGameEvent( "cs_win_panel_match" ); GetHud().InitColors( pScheme ); SetPaintBackgroundEnabled( false ); } IViewPortPanel* CounterStrikeViewport::CreatePanelByName( const char *szPanelName ) { IViewPortPanel* newpanel = NULL; // overwrite MOD specific panel creation if ( Q_strcmp( PANEL_TEAM, szPanelName ) == 0 ) { newpanel = new CCSTeamMenuScaleform( this ); } else { // create a generic base panel, don't add twice newpanel = BaseClass::CreatePanelByName( szPanelName ); } return newpanel; } void CounterStrikeViewport::CreateDefaultPanels( void ) { AddNewPanel( CreatePanelByName( PANEL_TEAM ), "PANEL_TEAM" ); AddNewPanel( CreatePanelByName( PANEL_BUY ), "PANEL_BUY" ); BaseClass::CreateDefaultPanels(); } int CounterStrikeViewport::GetDeathMessageStartHeight( void ) { int x = YRES( 2 ); return x; } void CounterStrikeViewport::FireGameEvent( IGameEvent * event ) { const char * type = event->GetName(); if ( Q_strcmp( type, "game_newmap" ) == 0 || Q_strcmp( type, "cs_win_panel_match" ) == 0 ) { SetChoseTeamAndClass( false ); } BaseClass::FireGameEvent( event ); } void CounterStrikeViewport::UpdateAllPanels( void ) { bool bSomethingIsVisible = false; ACTIVE_SPLITSCREEN_PLAYER_GUARD_VGUI( vgui::ipanel()->GetMessageContextId( GetVPanel() ) ); for ( int i = 0; i < m_UnorderedPanels.Count(); ++i ) { IViewPortPanel *p = m_UnorderedPanels[i]; if ( p->IsVisible() ) { bSomethingIsVisible = true; p->Update(); if ( m_pActivePanel == NULL ) { // if a visible panel exists, then there should be an activePanel. m_pActivePanel = p; } } } // see if we need to show a special ui instead of the hud // [jason] Do not rearrange viewport panels while the Pause menu is opened - it takes precedence over all viewports if ( !bSomethingIsVisible && !BasePanel()->IsScaleformPauseMenuActive() ) { C_CSPlayer *pCSPlayer = C_CSPlayer::GetLocalCSPlayer(); const char* UIToShow = NULL; if ( !pCSPlayer ) { UIToShow = PANEL_SPECGUI; } else if ( pCSPlayer->GetObserverMode() != OBS_MODE_NONE ) { if ( pCSPlayer->State_Get() != STATE_PICKINGTEAM && ( pCSPlayer->GetTeamNumber() == TEAM_UNASSIGNED ) && !pCSPlayer->IsHLTV() ) { // not a member of a team and not a spectator. show the team select screen. if ( !CLoadingScreenScaleform::IsOpen() && ( (GetActivePanel() && !V_strcmp( GetActivePanel()->GetName(), PANEL_TEAM )) || !GetActivePanel() ) ) { // don't show the team panel if the team panel is already up UIToShow = PANEL_TEAM; } } else { SFHudWinPanel * pWinPanel = GET_HUDELEMENT( SFHudWinPanel ); if ( pWinPanel && !pWinPanel->IsVisible() ) { UIToShow = PANEL_SPECGUI; } } } if ( UIToShow ) { ShowPanel( UIToShow, true ); } } } /* ========================== HUD_ChatInputPosition Sets the location of the input for chat text ========================== */ //MIKETODO: positioning of chat text ( and other engine output ) /* #include "Exports.h" void CL_DLLEXPORT HUD_ChatInputPosition( int *x, int *y ) { RecClChatInputPosition( x, y ); if ( GetViewPortInterface() ) { GetViewPortInterface()->ChatInputPosition( x, y ); } } EXPOSE_SINGLE_INTERFACE( CounterStrikeViewport, IClientVGUI, CLIENTVGUI_INTERFACE_VERSION ); */
/****************************************************************************** * Copyright 2015-2020 Xilinx, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ /* ------------------------------------------------------------------------------- *********************************************** H E A D E R F I L E S *** ------------------------------------------------------------------------------- */ #include "encryption.h" #include "bootimage.h" #include "encryptutils.h" #include "options.h" #include "bifoptions.h" #include "encryptutils.h" #include <openssl/rand.h> /* ------------------------------------------------------------------------------- ***************************************************** F U N C T I O N S *** ------------------------------------------------------------------------------- */ /******************************************************************************/ void EncryptionContext::GenerateEncryptionKeyFile(const std::string & baseFileName, Options & options) { LOG_TRACE("Generating the AES key file"); std::string devicePartName = options.GetDevicePartName(); if (devicePartName != "") { SetDeviceName(devicePartName); } else { LOG_ERROR("Partname must be specified with -p <partname> option in command line for generating a key file"); } if (GetAesSeed() == NULL) { aesSeed = new uint32_t[WORDS_PER_AES_KEY]; } GenerateAesSeed(); if (GetAesLabel() == NULL) { aesLabel = new uint8_t[aesLabelBytes]; } RAND_bytes(aesLabel, aesLabelBytes); if (GetAesContext() == NULL) { aesContext = new uint8_t[aesContextBytes]; } RAND_bytes(aesContext, aesContextBytes); bool useOptionalKey = options.bifOptions->GetAesOptKeyFlag(); /* The extra 1 Key pair is for Secure Header */ CounterModeKDF(options.bifOptions->GetEncryptionBlocksList().size() + useOptionalKey + 1, baseFileName, options.GetZynqMpEncrDump()); WriteEncryptionKeyFile(baseFileName, useOptionalKey, options.bifOptions->GetEncryptionBlocksList().size() + 1); } /******************************************************************************/ void EncryptionContext::SetDeviceName(const std::string& deviceName0) { deviceName = deviceName0; } /******************************************************************************/ void EncryptionContext::PackHex(const std::string& hexString, uint8_t* hexData) { uint32_t hexStringLength = (uint32_t)hexString.size(); if (hexStringLength & 1) { LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - does not have even no. of hex digits", hexString.c_str()); LOG_ERROR("Error parsing encryption key"); } for (uint32_t i = 0; i < hexStringLength; i += 2) { std::string byte = hexString.substr(i, 2); if (!isxdigit(byte[0]) || !isxdigit(byte[1])) { LOG_DEBUG(DEBUG_STAMP, "Hex String - %s - is has a non hex digit", hexString.c_str()); LOG_ERROR("Error parsing encryption key"); } *hexData++ = (uint8_t)strtoul(byte.c_str(), NULL, 16); } } /******************************************************************************/ void EncryptionContext::SetAesKeyString(const std::string& key) { uint8_t hexData[256]; if (key.size() != (WORDS_PER_AES_KEY * 8)) { LOG_DEBUG(DEBUG_STAMP, "AES key size - %d", key.size()); LOG_ERROR("An AES key must be 256 bits long - %s", key.c_str()); } PackHex(key, hexData); SetAesKey(hexData); } /******************************************************************************/ std::string EncryptionContext::ConvertKeyIvToString(uint8_t * keyIv, uint8_t size) { std::stringstream keyIvString; for (uint32_t i = 0; i < size; i++) { keyIvString << std::setfill('0') << std::setw(2) << std::hex << uint32_t(keyIv[i]); } return keyIvString.str(); } /******************************************************************************/ void EncryptionContext::SetAesFileName(std::string file) { aesFilename = file; } /******************************************************************************/ void EncryptionContext::SetMetalKeyFile(std::string file) { metalFile = file; } /******************************************************************************/ void EncryptionContext::SetBHKekIVFile(std::string file) { bhKekIVFile = file; } /******************************************************************************/ std::string EncryptionContext::GetAesFileName() { return aesFilename; } /******************************************************************************/ std::string EncryptionContext::GetMetalKeyFile(void) { return metalFile; } /******************************************************************************/ std::string EncryptionContext::GetBHKekIVFile(void) { return bhKekIVFile; } /******************************************************************************/ void EncryptionContext::GenerateAesSeed(void) { uint8_t seed[BYTES_PER_AES_KEY]; RAND_bytes(seed, WORDS_PER_AES_KEY * sizeof(uint32_t)); SetAesSeed(seed); LOG_INFO("AES Seed generated successfully"); } /******************************************************************************/ void EncryptionContext::SetRandomSeed() { /* Start the pseudo random sequence based on the passage of time so that we never get the same pseudo random sequence twice. This is done by XOR'ing the current time (which increments in seconds) with the number of CPU clocks (either microseconds or CPU clock ticks). This will create a number that will never repeat again (the date), but will be different every time this function is called (based on CPU clocks). */ static int temp_var = 0; clock_t currentClocks = clock(); time_t currentTime = time(NULL); uint32_t randomSeed = (uint32_t)(currentTime ^ currentClocks); randomSeed += temp_var++; srand(randomSeed); } /******************************************************************************/ static uint32_t GetRandomValue(uint32_t maxValue) { uint32_t returnValue; do { returnValue = (rand() / (int)(((unsigned)RAND_MAX + 1) / maxValue)); } while (returnValue > maxValue); return returnValue; } /******************************************************************************/ void EncryptionContext::GetRandomData(uint8_t* randomData, uint32_t randomDataByteLength) { uint8_t randomSequenceNibble; uint8_t randomSequenceByte; uint8_t lastRandomSequenceByte; uint32_t randomByteLocation; uint32_t byteCount; uint32_t index; // Zero out the return buffer; for (index = 0; index < randomDataByteLength; index += 1) { randomData[index] = 0; } // Get pseudo random byte values to fill the return buffer. byteCount = randomDataByteLength; while (byteCount > 0) { // Never get the same byte value twice in a row. lastRandomSequenceByte = 0; do { // Combine two pseudo random nibbles into a byte. randomSequenceByte = 0; // Exclude a byte value of zero. while (randomSequenceByte == 0) { for (index = 0; index < 2; index += 1) { // Get a pseudo random nibble between 0x0 and 0xF. randomSequenceNibble = (uint8_t)GetRandomValue(0x10); // Combine the two nibbles together into a bytes. randomSequenceByte <<= 4; randomSequenceByte |= randomSequenceNibble; } } } while (lastRandomSequenceByte == randomSequenceByte); lastRandomSequenceByte = randomSequenceByte; /* Set the pseudo random bytes values in random byte location order by getting a random byte location index of a byte location that hasn't been set yet */ do { randomByteLocation = GetRandomValue(randomDataByteLength); } while (randomData[randomByteLocation] != 0); // Set the pseudo random byte value into the return buffer. randomData[randomByteLocation] = randomSequenceByte; // Prepare for the next byte loop interation. byteCount -= 1; } } /******************************************************************************/ uint32_t EncryptionContext::GetTotalEncryptionBlocks(Binary::Length_t partitionSize, std::vector<uint32_t> encrBlocks, uint32_t defEncrBlockSize, Binary::Length_t* lastBlock) { uint32_t defEncrBlocksCount = 0; /* Calculate the Size of partition covered with given blocks */ Binary::Length_t encrBlocksSize = 0; for (uint32_t itr = 0; itr < encrBlocks.size(); itr++) { encrBlocksSize += encrBlocks[itr]; } /* Calculate the number encryption blocks with the def block size given using (*), else would be a single block */ if (partitionSize > encrBlocksSize) { if (defEncrBlockSize != 0) { defEncrBlocksCount = ((partitionSize - encrBlocksSize) / defEncrBlockSize); bool lastBlockExists = (((partitionSize - encrBlocksSize) % defEncrBlockSize) == 0 ? 0 : 1); if (lastBlockExists) { defEncrBlocksCount++; *lastBlock = (partitionSize - encrBlocksSize - ((defEncrBlocksCount - 1)*defEncrBlockSize)); } } else { defEncrBlocksCount = 1; *lastBlock = partitionSize - encrBlocksSize; } } uint32_t totalencrBlocks = defEncrBlocksCount + encrBlocks.size(); LOG_TRACE("Total no. of blocks to encrypt - %d", totalencrBlocks); return totalencrBlocks; } /******************************************************************************/ void EncryptionContext::CheckForSameAesKeyFiles(std::vector<std::string> aesKeyFileVec) { uint32_t count = 0; for (uint32_t i = 0; i < aesKeyFileVec.size(); i++) { if (aesFilename.compare(aesKeyFileVec[i]) == 0) { count++; } } if (count > 1) { LOG_ERROR("Same .nky file is used to provide keys across multiple partitions.\n Reuse of keys or key/IV pairs, both of which can create security vulnerability."); } } /******************************************************************************/ void EncryptionContext::CheckForExtraKeyIVPairs(uint32_t totalencrBlocks, std::string name) { static bool extraKeys = false; static bool extraIvs = false; if (totalencrBlocks + 1 < aesKeyVec.size()) { extraKeys = true; aesKeyVec.resize(totalencrBlocks + 1); } if (totalencrBlocks + 1 < aesIvVec.size()) { extraIvs = true; aesIvVec.resize(totalencrBlocks + 1); } if (extraKeys && extraIvs) { LOG_WARNING("AES Key file has more Keys/IVs than the number of blocks to be encrypted in %s. \n Extra keys/Ivs will be ignored.", name.c_str()); } else if (extraKeys) { LOG_WARNING("AES Key file has more Keys than the number of blocks to be encrypted in %s. \n Extra Keys will be ignored.", name.c_str()); } else if (extraIvs) { LOG_WARNING("AES Key file has more IVs than the number of blocks to be encrypted in %s. \n Extra Ivs will be ignored.", name.c_str()); } } /******************************************************************************/ void EncryptionContext::CheckForRepeatedKeyIVPairs(std::vector<std::string> aesKeyFileVec, bool maskKey0IV0) { static std::vector<std::vector<std::string> > aesKeyMasterVec; static std::vector<std::vector<std::string> > aesIvMasterVec; aesKeyMasterVec.push_back(aesKeyVec); aesIvMasterVec.push_back(aesIvVec); bool repeatedKey = false; bool repeatedIV = false; for (uint32_t i = 0; i < aesKeyVec.size(); i++) { for (uint32_t j = i + 1; j < aesKeyVec.size(); j++) { if (aesKeyVec[i] == aesKeyVec[j]) { repeatedKey = true; } if (aesIvVec[i] == aesIvVec[j]) { repeatedIV = true; } if (repeatedKey && repeatedIV) { LOG_MSG(" Key : %s", aesKeyVec[i].c_str()); LOG_MSG(" IV : %s", aesIvVec[i].c_str()); LOG_ERROR("Repeated usage of Key/IV pair is observed in %s.\n Reuse of Key/IV pair creates security vulnerability.", aesFilename.c_str()); } else { repeatedKey = repeatedIV = false; } } } if (maskKey0IV0) { aesKeyMasterVec[aesKeyMasterVec.size() - 1].erase(aesKeyMasterVec[aesKeyMasterVec.size() - 1].begin()); aesIvMasterVec[aesIvMasterVec.size() - 1].erase(aesIvMasterVec[aesIvMasterVec.size() - 1].begin()); } for (uint32_t i = 0; i < aesKeyMasterVec.size(); i++) { uint32_t j = aesKeyMasterVec.size() - 1; if (i != j) { for (uint32_t x = 0; x < aesKeyMasterVec[i].size(); x++) { for (uint32_t y = 0; y < aesKeyMasterVec[j].size(); y++) { if (aesKeyMasterVec[i][x] == aesKeyMasterVec[j][y]) { repeatedKey = true; } if (aesIvMasterVec[i][x] == aesIvMasterVec[j][y]) { repeatedIV = true; } if (repeatedKey && repeatedIV) { LOG_MSG(" Key : %s", aesKeyMasterVec[i][x].c_str()); LOG_MSG(" IV : %s", aesIvMasterVec[j][y].c_str()); LOG_ERROR("Repeated usage of Key/IV pair is observed in %s, %s.\n Reuse of Key/IV pair creates security vulnerability.", aesKeyFileVec[i].c_str(), aesKeyFileVec[j].c_str()); } else { repeatedKey = repeatedIV = false; } } } } } } /******************************************************************************/ void AesGcmEncryptionContext::AesGcm256Encrypt(unsigned char* gcm_pt, int pt_len, unsigned char* gcm_key, unsigned char* gcm_iv, unsigned char* gcm_aad, int aad_len, unsigned char* gcm_ct, int& ct_len, unsigned char* gcm_tag) { EVP_CIPHER_CTX *ctx; int outlen, tmplen; ctx = EVP_CIPHER_CTX_new(); /* Set cipher type and mode */ EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL); /* Set IV length to 96 bits or 12 bytes */ EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL); /* Initialise key and IV */ EVP_EncryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv); /* Specify any AAD only if it is non-zero length*/ if ((gcm_aad) && aad_len) { EVP_EncryptUpdate(ctx, NULL, &outlen, gcm_aad, aad_len); } /* Encrypt plaintext */ EVP_EncryptUpdate(ctx, gcm_ct, &outlen, gcm_pt, pt_len); /* Finalise GCM */ EVP_EncryptFinal_ex(ctx, gcm_ct + outlen, &tmplen); /* Get GCM tag */ EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, gcm_tag); EVP_CIPHER_CTX_free(ctx); ct_len = outlen + tmplen; } /******************************************************************************/ void AesGcmEncryptionContext::AesGcm256Decrypt(unsigned char* gcm_pt, int& pt_len, unsigned char* gcm_key, unsigned char* gcm_iv, unsigned char* gcm_aad, int aad_len, unsigned char* gcm_ct, int ct_len, unsigned char* gcm_tag) { EVP_CIPHER_CTX *ctx; int outlen, tmplen; ctx = EVP_CIPHER_CTX_new(); /* Select cipher */ EVP_DecryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, NULL, NULL); /* Set IV length, omit for 96 bits */ EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, 12, NULL); /* Specify key and IV */ EVP_DecryptInit_ex(ctx, NULL, NULL, gcm_key, gcm_iv); #if 1 /* Set expected tag value. A restriction in OpenSSL 1.0.1c and earlier required the tag before any AAD or ciphertext */ EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, gcm_tag); #endif /* Specify any AAD only if it is non-zero length*/ if ((gcm_aad) && aad_len > 0) { EVP_DecryptUpdate(ctx, NULL, &outlen, gcm_aad, aad_len); } /* Decrypt plaintext */ EVP_DecryptUpdate(ctx, gcm_pt, &outlen, gcm_ct, ct_len); #if 0 /* Set expected tag value. Works in OpenSSL 1.0.1d and later */ EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, gcm_tag); #endif /* Finalise: GCM */ (void)EVP_DecryptFinal_ex(ctx, gcm_pt + outlen, &tmplen); EVP_CIPHER_CTX_free(ctx); pt_len = outlen + tmplen; }
/*************************************************************************/ /* marshalls.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "marshalls.h" #include "core/os/keyboard.h" #include "core/print_string.h" #include "core/reference.h" #include <limits.h> #include <stdio.h> void EncodedObjectAsID::_bind_methods() { ClassDB::bind_method(D_METHOD("set_object_id", "id"), &EncodedObjectAsID::set_object_id); ClassDB::bind_method(D_METHOD("get_object_id"), &EncodedObjectAsID::get_object_id); ADD_PROPERTY(PropertyInfo(Variant::INT, "object_id"), "set_object_id", "get_object_id"); } void EncodedObjectAsID::set_object_id(ObjectID p_id) { id = p_id; } ObjectID EncodedObjectAsID::get_object_id() const { return id; } EncodedObjectAsID::EncodedObjectAsID() : id(0) { } #define _S(a) ((int32_t)a) #define ERR_FAIL_ADD_OF(a, b, err) ERR_FAIL_COND_V(_S(b) < 0 || _S(a) < 0 || _S(a) > INT_MAX - _S(b), err) #define ERR_FAIL_MUL_OF(a, b, err) ERR_FAIL_COND_V(_S(a) < 0 || _S(b) <= 0 || _S(a) > INT_MAX / _S(b), err) #define ENCODE_MASK 0xFF #define ENCODE_FLAG_64 1 << 16 #define ENCODE_FLAG_OBJECT_AS_ID 1 << 16 static Error _decode_string(const uint8_t *&buf, int &len, int *r_len, String &r_string) { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t strlen = decode_uint32(buf); int32_t pad = 0; // Handle padding if (strlen % 4) { pad = 4 - strlen % 4; } buf += 4; len -= 4; // Ensure buffer is big enough ERR_FAIL_ADD_OF(strlen, pad, ERR_FILE_EOF); ERR_FAIL_COND_V(strlen < 0 || strlen + pad > len, ERR_FILE_EOF); String str; ERR_FAIL_COND_V(str.parse_utf8((const char *)buf, strlen), ERR_INVALID_DATA); r_string = str; // Add padding strlen += pad; // Update buffer pos, left data count, and return size buf += strlen; len -= strlen; if (r_len) { (*r_len) += 4 + strlen; } return OK; } Error decode_variant(Variant &r_variant, const uint8_t *p_buffer, int p_len, int *r_len, bool p_allow_objects) { const uint8_t *buf = p_buffer; int len = p_len; if (len < 4) { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); } uint32_t type = decode_uint32(buf); ERR_FAIL_COND_V((type & ENCODE_MASK) >= Variant::VARIANT_MAX, ERR_INVALID_DATA); buf += 4; len -= 4; if (r_len) *r_len = 4; switch (type & ENCODE_MASK) { case Variant::NIL: { r_variant = Variant(); } break; case Variant::BOOL: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); bool val = decode_uint32(buf); r_variant = val; if (r_len) (*r_len) += 4; } break; case Variant::INT: { if (type & ENCODE_FLAG_64) { ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA); int64_t val = decode_uint64(buf); r_variant = val; if (r_len) (*r_len) += 8; } else { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t val = decode_uint32(buf); r_variant = val; if (r_len) (*r_len) += 4; } } break; case Variant::REAL: { if (type & ENCODE_FLAG_64) { ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA); double val = decode_double(buf); r_variant = val; if (r_len) (*r_len) += 8; } else { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); float val = decode_float(buf); r_variant = val; if (r_len) (*r_len) += 4; } } break; case Variant::STRING: { String str; Error err = _decode_string(buf, len, r_len, str); if (err) return err; r_variant = str; } break; // math types case Variant::VECTOR2: { ERR_FAIL_COND_V(len < 4 * 2, ERR_INVALID_DATA); Vector2 val; val.x = decode_float(&buf[0]); val.y = decode_float(&buf[4]); r_variant = val; if (r_len) (*r_len) += 4 * 2; } break; // 5 case Variant::RECT2: { ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA); Rect2 val; val.position.x = decode_float(&buf[0]); val.position.y = decode_float(&buf[4]); val.size.x = decode_float(&buf[8]); val.size.y = decode_float(&buf[12]); r_variant = val; if (r_len) (*r_len) += 4 * 4; } break; case Variant::VECTOR3: { ERR_FAIL_COND_V(len < 4 * 3, ERR_INVALID_DATA); Vector3 val; val.x = decode_float(&buf[0]); val.y = decode_float(&buf[4]); val.z = decode_float(&buf[8]); r_variant = val; if (r_len) (*r_len) += 4 * 3; } break; case Variant::TRANSFORM2D: { ERR_FAIL_COND_V(len < 4 * 6, ERR_INVALID_DATA); Transform2D val; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { val.elements[i][j] = decode_float(&buf[(i * 2 + j) * 4]); } } r_variant = val; if (r_len) (*r_len) += 4 * 6; } break; case Variant::PLANE: { ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA); Plane val; val.normal.x = decode_float(&buf[0]); val.normal.y = decode_float(&buf[4]); val.normal.z = decode_float(&buf[8]); val.d = decode_float(&buf[12]); r_variant = val; if (r_len) (*r_len) += 4 * 4; } break; case Variant::QUAT: { ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA); Quat val; val.x = decode_float(&buf[0]); val.y = decode_float(&buf[4]); val.z = decode_float(&buf[8]); val.w = decode_float(&buf[12]); r_variant = val; if (r_len) (*r_len) += 4 * 4; } break; case Variant::AABB: { ERR_FAIL_COND_V(len < 4 * 6, ERR_INVALID_DATA); AABB val; val.position.x = decode_float(&buf[0]); val.position.y = decode_float(&buf[4]); val.position.z = decode_float(&buf[8]); val.size.x = decode_float(&buf[12]); val.size.y = decode_float(&buf[16]); val.size.z = decode_float(&buf[20]); r_variant = val; if (r_len) (*r_len) += 4 * 6; } break; case Variant::BASIS: { ERR_FAIL_COND_V(len < 4 * 9, ERR_INVALID_DATA); Basis val; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { val.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } r_variant = val; if (r_len) (*r_len) += 4 * 9; } break; case Variant::TRANSFORM: { ERR_FAIL_COND_V(len < 4 * 12, ERR_INVALID_DATA); Transform val; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { val.basis.elements[i][j] = decode_float(&buf[(i * 3 + j) * 4]); } } val.origin[0] = decode_float(&buf[36]); val.origin[1] = decode_float(&buf[40]); val.origin[2] = decode_float(&buf[44]); r_variant = val; if (r_len) (*r_len) += 4 * 12; } break; // misc types case Variant::COLOR: { ERR_FAIL_COND_V(len < 4 * 4, ERR_INVALID_DATA); Color val; val.r = decode_float(&buf[0]); val.g = decode_float(&buf[4]); val.b = decode_float(&buf[8]); val.a = decode_float(&buf[12]); r_variant = val; if (r_len) (*r_len) += 4 * 4; } break; case Variant::NODE_PATH: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t strlen = decode_uint32(buf); if (strlen & 0x80000000) { //new format ERR_FAIL_COND_V(len < 12, ERR_INVALID_DATA); Vector<StringName> names; Vector<StringName> subnames; uint32_t namecount = strlen &= 0x7FFFFFFF; uint32_t subnamecount = decode_uint32(buf + 4); uint32_t flags = decode_uint32(buf + 8); len -= 12; buf += 12; if (flags & 2) // Obsolete format with property separate from subpath subnamecount++; uint32_t total = namecount + subnamecount; if (r_len) (*r_len) += 12; for (uint32_t i = 0; i < total; i++) { String str; Error err = _decode_string(buf, len, r_len, str); if (err) return err; if (i < namecount) names.push_back(str); else subnames.push_back(str); } r_variant = NodePath(names, subnames, flags & 1); } else { //old format, just a string ERR_FAIL_V(ERR_INVALID_DATA); } } break; /*case Variant::RESOURCE: { ERR_EXPLAIN("Can't marshallize resources"); ERR_FAIL_V(ERR_INVALID_DATA); //no, i'm sorry, no go } break;*/ case Variant::_RID: { r_variant = RID(); } break; case Variant::OBJECT: { if (type & ENCODE_FLAG_OBJECT_AS_ID) { //this _is_ allowed ERR_FAIL_COND_V(len < 8, ERR_INVALID_DATA); ObjectID val = decode_uint64(buf); if (r_len) (*r_len) += 8; if (val == 0) { r_variant = (Object *)NULL; } else { Ref<EncodedObjectAsID> obj_as_id; obj_as_id.instance(); obj_as_id->set_object_id(val); r_variant = obj_as_id; } } else { ERR_FAIL_COND_V(!p_allow_objects, ERR_UNAUTHORIZED); String str; Error err = _decode_string(buf, len, r_len, str); if (err) return err; if (str == String()) { r_variant = (Object *)NULL; } else { Object *obj = ClassDB::instance(str); ERR_FAIL_COND_V(!obj, ERR_UNAVAILABLE); ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; if (r_len) { (*r_len) += 4; } for (int i = 0; i < count; i++) { str = String(); err = _decode_string(buf, len, r_len, str); if (err) return err; Variant value; int used; err = decode_variant(value, buf, len, &used, p_allow_objects); if (err) return err; buf += used; len -= used; if (r_len) { (*r_len) += used; } obj->set(str, value); } if (Object::cast_to<Reference>(obj)) { REF ref = REF(Object::cast_to<Reference>(obj)); r_variant = ref; } else { r_variant = obj; } } } } break; case Variant::DICTIONARY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); // bool shared = count&0x80000000; count &= 0x7FFFFFFF; buf += 4; len -= 4; if (r_len) { (*r_len) += 4; } Dictionary d; for (int i = 0; i < count; i++) { Variant key, value; int used; Error err = decode_variant(key, buf, len, &used, p_allow_objects); ERR_FAIL_COND_V(err, err); buf += used; len -= used; if (r_len) { (*r_len) += used; } err = decode_variant(value, buf, len, &used, p_allow_objects); ERR_FAIL_COND_V(err, err); buf += used; len -= used; if (r_len) { (*r_len) += used; } d[key] = value; } r_variant = d; } break; case Variant::ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); // bool shared = count&0x80000000; count &= 0x7FFFFFFF; buf += 4; len -= 4; if (r_len) { (*r_len) += 4; } Array varr; for (int i = 0; i < count; i++) { int used = 0; Variant v; Error err = decode_variant(v, buf, len, &used, p_allow_objects); ERR_FAIL_COND_V(err, err); buf += used; len -= used; varr.push_back(v); if (r_len) { (*r_len) += used; } } r_variant = varr; } break; // arrays case Variant::POOL_BYTE_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_COND_V(count < 0 || count > len, ERR_INVALID_DATA); PoolVector<uint8_t> data; if (count) { data.resize(count); PoolVector<uint8_t>::Write w = data.write(); for (int32_t i = 0; i < count; i++) { w[i] = buf[i]; } w = PoolVector<uint8_t>::Write(); } r_variant = data; if (r_len) { if (count % 4) (*r_len) += 4 - count % 4; (*r_len) += 4 + count; } } break; case Variant::POOL_INT_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_MUL_OF(count, 4, ERR_INVALID_DATA); ERR_FAIL_COND_V(count < 0 || count * 4 > len, ERR_INVALID_DATA); PoolVector<int> data; if (count) { //const int*rbuf=(const int*)buf; data.resize(count); PoolVector<int>::Write w = data.write(); for (int32_t i = 0; i < count; i++) { w[i] = decode_uint32(&buf[i * 4]); } w = PoolVector<int>::Write(); } r_variant = Variant(data); if (r_len) { (*r_len) += 4 + count * sizeof(int); } } break; case Variant::POOL_REAL_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_MUL_OF(count, 4, ERR_INVALID_DATA); ERR_FAIL_COND_V(count < 0 || count * 4 > len, ERR_INVALID_DATA); PoolVector<float> data; if (count) { //const float*rbuf=(const float*)buf; data.resize(count); PoolVector<float>::Write w = data.write(); for (int32_t i = 0; i < count; i++) { w[i] = decode_float(&buf[i * 4]); } w = PoolVector<float>::Write(); } r_variant = data; if (r_len) { (*r_len) += 4 + count * sizeof(float); } } break; case Variant::POOL_STRING_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); PoolVector<String> strings; buf += 4; len -= 4; if (r_len) (*r_len) += 4; //printf("string count: %i\n",count); for (int32_t i = 0; i < count; i++) { String str; Error err = _decode_string(buf, len, r_len, str); if (err) return err; strings.push_back(str); } r_variant = strings; } break; case Variant::POOL_VECTOR2_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_MUL_OF(count, 4 * 2, ERR_INVALID_DATA); ERR_FAIL_COND_V(count < 0 || count * 4 * 2 > len, ERR_INVALID_DATA); PoolVector<Vector2> varray; if (r_len) { (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector2>::Write w = varray.write(); for (int32_t i = 0; i < count; i++) { w[i].x = decode_float(buf + i * 4 * 2 + 4 * 0); w[i].y = decode_float(buf + i * 4 * 2 + 4 * 1); } int adv = 4 * 2 * count; if (r_len) (*r_len) += adv; len -= adv; buf += adv; } r_variant = varray; } break; case Variant::POOL_VECTOR3_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_MUL_OF(count, 4 * 3, ERR_INVALID_DATA); ERR_FAIL_COND_V(count < 0 || count * 4 * 3 > len, ERR_INVALID_DATA); PoolVector<Vector3> varray; if (r_len) { (*r_len) += 4; } if (count) { varray.resize(count); PoolVector<Vector3>::Write w = varray.write(); for (int32_t i = 0; i < count; i++) { w[i].x = decode_float(buf + i * 4 * 3 + 4 * 0); w[i].y = decode_float(buf + i * 4 * 3 + 4 * 1); w[i].z = decode_float(buf + i * 4 * 3 + 4 * 2); } int adv = 4 * 3 * count; if (r_len) (*r_len) += adv; len -= adv; buf += adv; } r_variant = varray; } break; case Variant::POOL_COLOR_ARRAY: { ERR_FAIL_COND_V(len < 4, ERR_INVALID_DATA); int32_t count = decode_uint32(buf); buf += 4; len -= 4; ERR_FAIL_MUL_OF(count, 4 * 4, ERR_INVALID_DATA); ERR_FAIL_COND_V(count < 0 || count * 4 * 4 > len, ERR_INVALID_DATA); PoolVector<Color> carray; if (r_len) { (*r_len) += 4; } if (count) { carray.resize(count); PoolVector<Color>::Write w = carray.write(); for (int32_t i = 0; i < count; i++) { w[i].r = decode_float(buf + i * 4 * 4 + 4 * 0); w[i].g = decode_float(buf + i * 4 * 4 + 4 * 1); w[i].b = decode_float(buf + i * 4 * 4 + 4 * 2); w[i].a = decode_float(buf + i * 4 * 4 + 4 * 3); } int adv = 4 * 4 * count; if (r_len) (*r_len) += adv; len -= adv; buf += adv; } r_variant = carray; } break; default: { ERR_FAIL_V(ERR_BUG); } } return OK; } static void _encode_string(const String &p_string, uint8_t *&buf, int &r_len) { CharString utf8 = p_string.utf8(); if (buf) { encode_uint32(utf8.length(), buf); buf += 4; copymem(buf, utf8.get_data(), utf8.length()); buf += utf8.length(); } r_len += 4 + utf8.length(); while (r_len % 4) { r_len++; //pad if (buf) { *(buf++) = 0; } } } Error encode_variant(const Variant &p_variant, uint8_t *r_buffer, int &r_len, bool p_full_objects) { uint8_t *buf = r_buffer; r_len = 0; uint32_t flags = 0; switch (p_variant.get_type()) { case Variant::INT: { int64_t val = p_variant; if (val > (int64_t)INT_MAX || val < (int64_t)INT_MIN) { flags |= ENCODE_FLAG_64; } } break; case Variant::REAL: { double d = p_variant; float f = d; if (double(f) != d) { flags |= ENCODE_FLAG_64; //always encode real as double } } break; case Variant::OBJECT: { if (!p_full_objects) { flags |= ENCODE_FLAG_OBJECT_AS_ID; } } break; default: {} // nothing to do at this stage } if (buf) { encode_uint32(p_variant.get_type() | flags, buf); buf += 4; } r_len += 4; switch (p_variant.get_type()) { case Variant::NIL: { //nothing to do } break; case Variant::BOOL: { if (buf) { encode_uint32(p_variant.operator bool(), buf); } r_len += 4; } break; case Variant::INT: { if (flags & ENCODE_FLAG_64) { //64 bits if (buf) { encode_uint64(p_variant.operator int64_t(), buf); } r_len += 8; } else { if (buf) { encode_uint32(p_variant.operator int32_t(), buf); } r_len += 4; } } break; case Variant::REAL: { if (flags & ENCODE_FLAG_64) { if (buf) { encode_double(p_variant.operator double(), buf); } r_len += 8; } else { if (buf) { encode_float(p_variant.operator float(), buf); } r_len += 4; } } break; case Variant::NODE_PATH: { NodePath np = p_variant; if (buf) { encode_uint32(uint32_t(np.get_name_count()) | 0x80000000, buf); //for compatibility with the old format encode_uint32(np.get_subname_count(), buf + 4); uint32_t np_flags = 0; if (np.is_absolute()) np_flags |= 1; encode_uint32(np_flags, buf + 8); buf += 12; } r_len += 12; int total = np.get_name_count() + np.get_subname_count(); for (int i = 0; i < total; i++) { String str; if (i < np.get_name_count()) str = np.get_name(i); else str = np.get_subname(i - np.get_name_count()); CharString utf8 = str.utf8(); int pad = 0; if (utf8.length() % 4) pad = 4 - utf8.length() % 4; if (buf) { encode_uint32(utf8.length(), buf); buf += 4; copymem(buf, utf8.get_data(), utf8.length()); buf += pad + utf8.length(); } r_len += 4 + utf8.length() + pad; } } break; case Variant::STRING: { _encode_string(p_variant, buf, r_len); } break; // math types case Variant::VECTOR2: { if (buf) { Vector2 v2 = p_variant; encode_float(v2.x, &buf[0]); encode_float(v2.y, &buf[4]); } r_len += 2 * 4; } break; // 5 case Variant::RECT2: { if (buf) { Rect2 r2 = p_variant; encode_float(r2.position.x, &buf[0]); encode_float(r2.position.y, &buf[4]); encode_float(r2.size.x, &buf[8]); encode_float(r2.size.y, &buf[12]); } r_len += 4 * 4; } break; case Variant::VECTOR3: { if (buf) { Vector3 v3 = p_variant; encode_float(v3.x, &buf[0]); encode_float(v3.y, &buf[4]); encode_float(v3.z, &buf[8]); } r_len += 3 * 4; } break; case Variant::TRANSFORM2D: { if (buf) { Transform2D val = p_variant; for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { copymem(&buf[(i * 2 + j) * 4], &val.elements[i][j], sizeof(float)); } } } r_len += 6 * 4; } break; case Variant::PLANE: { if (buf) { Plane p = p_variant; encode_float(p.normal.x, &buf[0]); encode_float(p.normal.y, &buf[4]); encode_float(p.normal.z, &buf[8]); encode_float(p.d, &buf[12]); } r_len += 4 * 4; } break; case Variant::QUAT: { if (buf) { Quat q = p_variant; encode_float(q.x, &buf[0]); encode_float(q.y, &buf[4]); encode_float(q.z, &buf[8]); encode_float(q.w, &buf[12]); } r_len += 4 * 4; } break; case Variant::AABB: { if (buf) { AABB aabb = p_variant; encode_float(aabb.position.x, &buf[0]); encode_float(aabb.position.y, &buf[4]); encode_float(aabb.position.z, &buf[8]); encode_float(aabb.size.x, &buf[12]); encode_float(aabb.size.y, &buf[16]); encode_float(aabb.size.z, &buf[20]); } r_len += 6 * 4; } break; case Variant::BASIS: { if (buf) { Basis val = p_variant; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { copymem(&buf[(i * 3 + j) * 4], &val.elements[i][j], sizeof(float)); } } } r_len += 9 * 4; } break; case Variant::TRANSFORM: { if (buf) { Transform val = p_variant; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { copymem(&buf[(i * 3 + j) * 4], &val.basis.elements[i][j], sizeof(float)); } } encode_float(val.origin.x, &buf[36]); encode_float(val.origin.y, &buf[40]); encode_float(val.origin.z, &buf[44]); } r_len += 12 * 4; } break; // misc types case Variant::COLOR: { if (buf) { Color c = p_variant; encode_float(c.r, &buf[0]); encode_float(c.g, &buf[4]); encode_float(c.b, &buf[8]); encode_float(c.a, &buf[12]); } r_len += 4 * 4; } break; /*case Variant::RESOURCE: { ERR_EXPLAIN("Can't marshallize resources"); ERR_FAIL_V(ERR_INVALID_DATA); //no, i'm sorry, no go } break;*/ case Variant::_RID: { } break; case Variant::OBJECT: { if (p_full_objects) { Object *obj = p_variant; if (!obj) { if (buf) { encode_uint32(0, buf); buf += 4; } r_len += 4; } else { _encode_string(obj->get_class(), buf, r_len); List<PropertyInfo> props; obj->get_property_list(&props); int pc = 0; for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; pc++; } if (buf) { encode_uint32(pc, buf); buf += 4; } r_len += 4; for (List<PropertyInfo>::Element *E = props.front(); E; E = E->next()) { if (!(E->get().usage & PROPERTY_USAGE_STORAGE)) continue; _encode_string(E->get().name, buf, r_len); int len; Error err = encode_variant(obj->get(E->get().name), buf, len, p_full_objects); if (err) return err; ERR_FAIL_COND_V(len % 4, ERR_BUG); r_len += len; if (buf) buf += len; } } } else { if (buf) { Object *obj = p_variant; ObjectID id = 0; if (obj && ObjectDB::instance_validate(obj)) { id = obj->get_instance_id(); } encode_uint64(id, buf); } r_len += 8; } } break; case Variant::DICTIONARY: { Dictionary d = p_variant; if (buf) { encode_uint32(uint32_t(d.size()), buf); buf += 4; } r_len += 4; List<Variant> keys; d.get_key_list(&keys); for (List<Variant>::Element *E = keys.front(); E; E = E->next()) { /* CharString utf8 = E->->utf8(); if (buf) { encode_uint32(utf8.length()+1,buf); buf+=4; copymem(buf,utf8.get_data(),utf8.length()+1); } r_len+=4+utf8.length()+1; while (r_len%4) r_len++; //pad */ int len; encode_variant(E->get(), buf, len, p_full_objects); ERR_FAIL_COND_V(len % 4, ERR_BUG); r_len += len; if (buf) buf += len; Variant *v = d.getptr(E->get()); ERR_FAIL_COND_V(!v, ERR_BUG); encode_variant(*v, buf, len, p_full_objects); ERR_FAIL_COND_V(len % 4, ERR_BUG); r_len += len; if (buf) buf += len; } } break; case Variant::ARRAY: { Array v = p_variant; if (buf) { encode_uint32(uint32_t(v.size()), buf); buf += 4; } r_len += 4; for (int i = 0; i < v.size(); i++) { int len; encode_variant(v.get(i), buf, len, p_full_objects); ERR_FAIL_COND_V(len % 4, ERR_BUG); r_len += len; if (buf) buf += len; } } break; // arrays case Variant::POOL_BYTE_ARRAY: { PoolVector<uint8_t> data = p_variant; int datalen = data.size(); int datasize = sizeof(uint8_t); if (buf) { encode_uint32(datalen, buf); buf += 4; PoolVector<uint8_t>::Read r = data.read(); copymem(buf, &r[0], datalen * datasize); buf += datalen * datasize; } r_len += 4 + datalen * datasize; while (r_len % 4) { r_len++; if (buf) *(buf++) = 0; } } break; case Variant::POOL_INT_ARRAY: { PoolVector<int> data = p_variant; int datalen = data.size(); int datasize = sizeof(int32_t); if (buf) { encode_uint32(datalen, buf); buf += 4; PoolVector<int>::Read r = data.read(); for (int i = 0; i < datalen; i++) encode_uint32(r[i], &buf[i * datasize]); } r_len += 4 + datalen * datasize; } break; case Variant::POOL_REAL_ARRAY: { PoolVector<real_t> data = p_variant; int datalen = data.size(); int datasize = sizeof(real_t); if (buf) { encode_uint32(datalen, buf); buf += 4; PoolVector<real_t>::Read r = data.read(); for (int i = 0; i < datalen; i++) encode_float(r[i], &buf[i * datasize]); } r_len += 4 + datalen * datasize; } break; case Variant::POOL_STRING_ARRAY: { PoolVector<String> data = p_variant; int len = data.size(); if (buf) { encode_uint32(len, buf); buf += 4; } r_len += 4; for (int i = 0; i < len; i++) { CharString utf8 = data.get(i).utf8(); if (buf) { encode_uint32(utf8.length() + 1, buf); buf += 4; copymem(buf, utf8.get_data(), utf8.length() + 1); buf += utf8.length() + 1; } r_len += 4 + utf8.length() + 1; while (r_len % 4) { r_len++; //pad if (buf) *(buf++) = 0; } } } break; case Variant::POOL_VECTOR2_ARRAY: { PoolVector<Vector2> data = p_variant; int len = data.size(); if (buf) { encode_uint32(len, buf); buf += 4; } r_len += 4; if (buf) { for (int i = 0; i < len; i++) { Vector2 v = data.get(i); encode_float(v.x, &buf[0]); encode_float(v.y, &buf[4]); buf += 4 * 2; } } r_len += 4 * 2 * len; } break; case Variant::POOL_VECTOR3_ARRAY: { PoolVector<Vector3> data = p_variant; int len = data.size(); if (buf) { encode_uint32(len, buf); buf += 4; } r_len += 4; if (buf) { for (int i = 0; i < len; i++) { Vector3 v = data.get(i); encode_float(v.x, &buf[0]); encode_float(v.y, &buf[4]); encode_float(v.z, &buf[8]); buf += 4 * 3; } } r_len += 4 * 3 * len; } break; case Variant::POOL_COLOR_ARRAY: { PoolVector<Color> data = p_variant; int len = data.size(); if (buf) { encode_uint32(len, buf); buf += 4; } r_len += 4; if (buf) { for (int i = 0; i < len; i++) { Color c = data.get(i); encode_float(c.r, &buf[0]); encode_float(c.g, &buf[4]); encode_float(c.b, &buf[8]); encode_float(c.a, &buf[12]); buf += 4 * 4; } } r_len += 4 * 4 * len; } break; default: { ERR_FAIL_V(ERR_BUG); } } return OK; }
#include <stdio.h> #include <stdlib.h> void imprimir(int vetor[], int max){ for(int i=0; i< max; i++) printf("%i\n", vetor[i]); } void selection_sort (int vetor[], int max) { int i, j, min, aux; for (i = 0; i < (max - 1); i++) { min = i; for (j = i+1; j < max; j++) { if (vetor[j] < vetor[min]) { min = j; } } if (i != min) { aux = vetor[i]; vetor[i] = vetor[min]; vetor[min] = aux; printf("Passo %i\n", (i + 1)); imprimir(vetor, max); printf("\n"); } } } main () { int max = 10; int vetor[max] = {9,1,8,2,10,3,7,4,6,5}; selection_sort(vetor, max); imprimir(vetor, max); return 0; }
#include "drawlowresvolume.h" #include "viewer.h" #include "volume.h" #include "staticfunctions.h" #include "shaderfactory.h" #include "shaderfactoryrgb.h" #include "global.h" #include "mainwindowui.h" #include <QDomDocument> void DrawLowresVolume::activateBounds() {m_boundingBox.activateBounds();} bool DrawLowresVolume::raised() { return showing; } void DrawLowresVolume::raise() { showing = true; m_boundingBox.activateBounds(); load3dTexture(); if (MainWindowUI::mainWindowUI()->actionHiresMode->isChecked()) MainWindowUI::mainWindowUI()->actionHiresMode->setChecked(false); } void DrawLowresVolume::lower() { showing = false; m_boundingBox.deactivateBounds(); if (m_dataTex) glDeleteTextures(1, &m_dataTex); m_dataTex = 0; if (!MainWindowUI::mainWindowUI()->actionHiresMode->isChecked()) MainWindowUI::mainWindowUI()->actionHiresMode->setChecked(true); } void DrawLowresVolume::setCurrentVolume(int vnum) { m_currentVolume = vnum; } QImage DrawLowresVolume::histogramImage1D() { return m_histogramImage1D; } QImage DrawLowresVolume::histogramImage2D() { return m_histogramImage2D; } int* DrawLowresVolume::histogram2D() { return m_Volume->getLowres2dHistogram(m_currentVolume); } Vec DrawLowresVolume::volumeSize() { return m_virtualTextureSize; } Vec DrawLowresVolume::volumeMin() { return m_dataMin; } Vec DrawLowresVolume::volumeMax() { return m_dataMax; } void DrawLowresVolume::subvolumeBounds(Vec& bmin, Vec& bmax) { m_boundingBox.bounds(bmin, bmax); // Vec bsize = bmax-bmin; // // if ((int)bsize.x%2) // bmax.x = bmin.x + bsize.x; // else // bmax.x = bmin.x + bsize.x-1; // // if ((int)bsize.y%2) // bmax.y = bmin.y + bsize.y; // else // bmax.y = bmin.y + bsize.y-1; // // if ((int)bsize.z%2) // bmax.z = bmin.z + bsize.z; // else // bmax.z = bmin.z + bsize.z-1; } void DrawLowresVolume::setSubvolumeBounds(Vec obmin, Vec obmax) { Vec bmin = StaticFunctions::clampVec(m_dataMin, m_dataMax, obmin); Vec bmax = StaticFunctions::clampVec(m_dataMin, m_dataMax, obmax); //m_boundingBox.setBounds(bmin, bmax); m_boundingBox.setPositions(bmin, bmax); } DrawLowresVolume::DrawLowresVolume(Viewer *viewer, Volume *volume) : QObject() { m_progObj = 0; showing = true; m_currentVolume = 0; m_Viewer = viewer; m_Volume = volume; m_virtualTextureSize = m_virtualTextureMin = m_virtualTextureMax = Vec(0,0,0); m_dataMin = m_dataMax = Vec(0,0,0); m_histImageData1D = new unsigned char[256*256*4]; m_histImageData2D = new unsigned char[256*256*4]; m_histogramImage1D = QImage(256, 256, QImage::Format_RGB32); m_histogramImage2D = QImage(256, 256, QImage::Format_RGB32); m_dataTex = 0; // glGenTextures(1, &m_dataTex); } DrawLowresVolume::~DrawLowresVolume() { delete [] m_histImageData1D; delete [] m_histImageData2D; m_virtualTextureSize = m_virtualTextureMin = m_virtualTextureMax = Vec(0,0,0); m_dataMin = m_dataMax = Vec(0,0,0); if (m_dataTex) glDeleteTextures(1, &m_dataTex); m_dataTex = 0; } void DrawLowresVolume::init() {} void DrawLowresVolume::generateHistogramImage() { if (m_Volume->pvlVoxelType(0) > 0) return; int *hist2D = m_Volume->getLowres2dHistogram(m_currentVolume); if (hist2D) { for (int i=0; i<256*256; i++) { m_histImageData2D[4*i + 3] = 255; m_histImageData2D[4*i + 0] = hist2D[i]; m_histImageData2D[4*i + 1] = hist2D[i]; m_histImageData2D[4*i + 2] = hist2D[i]; } } m_histogramImage2D = QImage(m_histImageData2D, 256, 256, QImage::Format_ARGB32); m_histogramImage2D = m_histogramImage2D.mirrored(); int *hist1D = m_Volume->getLowres1dHistogram(m_currentVolume); memset(m_histImageData1D, 0, 4*256*256); if (hist1D) { for (int i=0; i<256; i++) { for (int j=0; j<256; j++) { int idx = 256*j + i; m_histImageData1D[4*idx + 3] = 255; } int h = hist1D[i]; for (int j=0; j<h; j++) { int idx = 256*j + i; m_histImageData1D[4*idx + 0] = 255*j/h; m_histImageData1D[4*idx + 1] = 255*j/h; m_histImageData1D[4*idx + 2] = 255*j/h; } } } m_histogramImage1D = QImage(m_histImageData1D, 256, 256, QImage::Format_ARGB32); m_histogramImage1D = m_histogramImage1D.mirrored(); } void DrawLowresVolume::load3dTexture() { if (!m_dataTex) glGenTextures(1, &m_dataTex); Vec textureSize = m_Volume->getLowresTextureVolumeSize(); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_3D, m_dataTex); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); if (Global::interpolationType(Global::TextureInterpolation)) // linear { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } if (Global::volumeType() == Global::DummyVolume) { glTexImage3D(GL_TEXTURE_3D, 0, // single resolution 1, textureSize.x, textureSize.y, textureSize.z, 0, // no border GL_RED, GL_UNSIGNED_BYTE, NULL); } else { int nvol = 1; if (Global::volumeType() == Global::DoubleVolume) nvol = 2; if (Global::volumeType() == Global::TripleVolume) nvol = 3; if (Global::volumeType() == Global::QuadVolume) nvol = 4; if (Global::volumeType() == Global::RGBVolume) nvol = 3; if (Global::volumeType() == Global::RGBAVolume) nvol = 4; int format = GL_RED; if (nvol == 2) format = GL_LUMINANCE_ALPHA; else if (nvol == 3) format = GL_RGB; else if (nvol == 4) format = GL_RGBA; int internalFormat = nvol; int vtype = GL_UNSIGNED_BYTE; if (m_Volume->pvlVoxelType(0) > 0) { if (nvol == 1) internalFormat = GL_LUMINANCE16; if (nvol == 2) internalFormat = GL_LUMINANCE16_ALPHA16; if (nvol == 3) internalFormat = GL_RGB16; if (nvol == 4) internalFormat = GL_RGBA16; if (nvol == 1) format = GL_LUMINANCE; if (nvol == 2) format = GL_LUMINANCE_ALPHA; if (nvol == 3) format = GL_RGB; if (nvol == 4) format = GL_RGBA; vtype = GL_UNSIGNED_SHORT; } glTexImage3D(GL_TEXTURE_3D, 0, // single resolution internalFormat, textureSize.x, textureSize.y, textureSize.z, 0, // no border format, vtype, m_Volume->getLowresTextureVolume()); } m_Viewer->setSceneBoundingBox(m_dataMin, m_dataMax); m_Viewer->showEntireScene(); } void DrawLowresVolume::loadVolume() { generateHistogramImage(); Vec textureSize = m_Volume->getLowresTextureVolumeSize(); Vec fullVolSize = m_Volume->getFullVolumeSize(); Vec lowVolSize = m_Volume->getLowresVolumeSize(); Vec vscale = VECDIVIDE(fullVolSize, lowVolSize); m_virtualTextureSize = VECPRODUCT(textureSize,vscale); m_virtualTextureMin = Vec(0, 0, 0); m_virtualTextureMax = fullVolSize-Vec(1,1,1); m_dataMin = Vec(0,0,0); m_dataMax = fullVolSize-Vec(1,1,1); m_boundingBox.setBounds(m_dataMin, m_dataMax); // Vec voxelScaling = Global::voxelScaling(); // m_boundingBox.setBounds(VECPRODUCT(m_dataMin,voxelScaling), // VECPRODUCT(m_dataMax,voxelScaling)); raise(); load3dTexture(); } void DrawLowresVolume::updateScaling() { // Vec voxelScaling = Global::voxelScaling(); // m_boundingBox.setBounds(VECPRODUCT(m_dataMin,voxelScaling), // VECPRODUCT(m_dataMax,voxelScaling)); } void DrawLowresVolume::createShaders() { QString shaderString; int nvol = 1; if (Global::volumeType() == Global::DoubleVolume) nvol = 2; if (Global::volumeType() == Global::TripleVolume) nvol = 3; if (Global::volumeType() == Global::QuadVolume) nvol = 4; // no emissivity in lowres window if (Global::volumeType() == Global::RGBVolume) shaderString = ShaderFactoryRGB::genDefaultShaderString(false, true); else if (Global::volumeType() == Global::RGBAVolume) shaderString = ShaderFactoryRGB::genDefaultShaderString(false, true); else shaderString = ShaderFactory::genDefaultShaderString((m_Volume->pvlVoxelType(0) > 0), // 16-bit data false, nvol); m_progObj = glCreateProgramObjectARB(); if (! ShaderFactory::loadShader(m_progObj, shaderString)) exit(0); m_parm[0] = glGetUniformLocationARB(m_progObj, "lutTex"); m_parm[1] = glGetUniformLocationARB(m_progObj, "dataTex"); if (Global::volumeType() != Global::RGBVolume && Global::volumeType() != Global::RGBAVolume) m_parm[2] = glGetUniformLocationARB(m_progObj, "tfSet"); else m_parm[2] = glGetUniformLocationARB(m_progObj, "layerSpacing"); m_parm[3] = glGetUniformLocationARB(m_progObj, "delta"); } //-------------------------------------------------------- void DrawLowresVolume::enableTextureUnits() { m_Viewer->enableTextureUnits(); glActiveTexture(GL_TEXTURE1); glEnable(GL_TEXTURE_3D); } void DrawLowresVolume::disableTextureUnits() { m_Viewer->disableTextureUnits(); glActiveTexture(GL_TEXTURE4); glDisable(GL_TEXTURE_RECTANGLE_ARB); glActiveTexture(GL_TEXTURE1); glDisable(GL_TEXTURE_3D); } void DrawLowresVolume::draw(float stepsize, int posx, int posy) { m_boundingBox.draw(); Vec pn; Vec minvert, maxvert; int maxidx, layers; float maxlen, zdepth; pn = m_Viewer->camera()->viewDirection(); StaticFunctions::getMinMaxBrickVertices(m_Viewer->camera(), m_dataMin, m_dataMax, zdepth, minvert, maxvert, maxidx); maxlen = zdepth; layers = maxlen/stepsize; disableTextureUnits(); glUseProgramObjectARB(0); glLineWidth(2); glColor4f(0.9f, 0.9f, 0.9f, 0.9f); glPolygonMode(GL_FRONT_AND_BACK,GL_LINE); StaticFunctions::drawEnclosingCube(m_dataMin, m_dataMax); glPolygonMode(GL_FRONT_AND_BACK,GL_FILL); glLineWidth(1); if (!m_progObj) createShaders(); //if (m_progObj > 0) { glUseProgramObjectARB(m_progObj); glUniform1iARB(m_parm[0], 0); glUniform1iARB(m_parm[1], 1); if (Global::volumeType() == Global::RGBVolume || Global::volumeType() == Global::RGBAVolume) { float frc = Global::stepsizeStill(); glUniform1fARB(m_parm[2], frc); } Vec textureSize = m_Volume->getLowresTextureVolumeSize(); Vec delta = Vec(1.0/textureSize.x, 1.0/textureSize.y, 1.0/textureSize.z); glUniform3fARB(m_parm[3], delta.x, delta.y, delta.z); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); enableTextureUnits(); drawSlices(pn, maxvert, minvert, layers, stepsize); disableTextureUnits(); glUseProgramObjectARB(0); glDisable(GL_BLEND); } Vec bbmin, bbmax; int minX, maxX, minY, maxY, minZ, maxZ; Vec textureSize = m_Volume->getLowresTextureVolumeSize(); m_boundingBox.bounds(bbmin, bbmax); minX = bbmin.x; maxX = bbmax.x; minY = bbmin.y; maxY = bbmax.y; minZ = bbmin.z; maxZ = bbmax.z; Vec vscl = Global::voxelScaling(); m_Viewer->startScreenCoordinatesSystem(); glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); // blend on top int screenWidth = m_Viewer->size().width(); int screenHeight = m_Viewer->size().height(); glColor4f(0, 0, 0, 0.8f); glBegin(GL_QUADS); glVertex2f(0, posy-55); glVertex2f(0, screenHeight); glVertex2f(screenWidth, screenHeight); glVertex2f(screenWidth, posy-55); glEnd(); //m_Viewer->stopScreenCoordinatesSystem(); //------------- // calculate font scale based on dpi float fscl = 120.0/Global::dpi(); //------------- glDisable(GL_DEPTH_TEST); QFont tfont = QFont("Helvetica", 8*fscl); tfont.setStyleStrategy(QFont::PreferAntialias); //glActiveTexture(GL_TEXTURE0); //glEnable(GL_TEXTURE_2D); glColor3f(0.6f,0.6f,0.6f); StaticFunctions::renderText(posx, posy-24*fscl, QString("LowRes : stepsize = %1 : %2 %3 %4"). \ arg(stepsize). \ arg(vscl.x).arg(vscl.y).arg(vscl.z), tfont, Qt::transparent, Qt::lightGray); tfont.setPointSize(10*fscl); glColor3f(0.8f,0.8f,0.8f); StaticFunctions::renderText(posx, posy-13*fscl, QString("Bounds : %1-%2, %3-%4, %5-%6"). \ arg(minX).arg(maxX).arg(minY).arg(maxY).arg(minZ).arg(maxZ), tfont, Qt::transparent, Qt::lightGray); tfont.setPointSize(12*fscl); glColor3f(1,1,1); StaticFunctions::renderText(posx, posy, QString("Selected SubVolume Size : %1x%2x%3 - (%4x%5x%6)"). \ arg(maxX-minX+1).arg(maxY-minY+1).arg(maxZ-minZ+1). \ arg((int)textureSize.x). \ arg((int)textureSize.y). \ arg((int)textureSize.z), tfont, Qt::transparent, Qt::lightGray); //glDisable(GL_TEXTURE_2D); m_Viewer->stopScreenCoordinatesSystem(); } int DrawLowresVolume::drawpoly(Vec po, Vec pn, Vec *subvol, Vec subdim, Vec subcorner) { Vec poly[100]; int edges = 0; edges += StaticFunctions::intersectType1(po, pn, subvol[0], subvol[1], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[0], subvol[3], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[2], subvol[1], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[2], subvol[3], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[4], subvol[5], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[4], subvol[7], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[6], subvol[5], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[6], subvol[7], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[0], subvol[4], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[1], subvol[5], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[2], subvol[6], poly[edges]); edges += StaticFunctions::intersectType1(po, pn, subvol[3], subvol[7], poly[edges]); if (!edges) return 0; Vec cen; int i; for(i=0; i<edges; i++) cen += poly[i]; cen/=edges; float angle[6]; Vec vaxis, vperp; vaxis = poly[0]-cen; vaxis.normalize(); vperp = vaxis^(poly[1]-cen); vperp = vperp^vaxis; vperp.normalize(); angle[0] = 1; for(i=1; i<edges; i++) { Vec v; v = poly[i]-cen; v.normalize(); angle[i] = vaxis*v; if (vperp*v < 0) angle[i] = -2 - angle[i]; } // sort angle int order[] = {0, 1, 2, 3, 4, 5 }; for(i=edges-1; i>=0; i--) for(int j=1; j<=i; j++) { if (angle[order[i]] < angle[order[j]]) { int tmp = order[i]; order[i] = order[j]; order[j] = tmp; } } //---- apply bounding box limits int tedges; Vec tpoly[100]; for(i=0; i<edges; i++) tpoly[i] = poly[order[i]]; for(i=0; i<edges; i++) poly[i] = tpoly[i]; Vec bbmin, bbmax; m_boundingBox.bounds(bbmin, bbmax); for (int bp=0; bp<6; bp++) { Vec cpo, cpn; switch (bp) { case 0 : { cpo = Vec(bbmin.x, 0, 0); cpn = Vec(-1, 0, 0); break; } case 1 : { cpo = Vec(bbmax.x, 0, 0); cpn = Vec(1, 0, 0); break; } case 2 : { cpo = Vec(0, bbmin.y, 0); cpn = Vec(0, -1, 0); break; } case 3 : { cpo = Vec(0, bbmax.y, 0); cpn = Vec(0, 1, 0); break; } case 4 : { cpo = Vec(0, 0, bbmin.z); cpn = Vec(0, 0, -1); break; } case 5 : { cpo = Vec(0, 0, bbmax.z); cpn = Vec(0, 0, 1); break; } } tedges = 0; for(i=0; i<edges; i++) { Vec v0, v1, Rnew; Vec Rd; v0 = poly[i]; if (i<edges-1) v1 = poly[i+1]; else v1 = poly[0]; Rd = v0-v1; Rd.normalize(); int ret = StaticFunctions::intersectType2(cpo, cpn, v0, v1); if (ret) { tpoly[tedges] = v0; tedges ++; if (ret == 2) { tpoly[tedges] = v1; tedges ++; } } } edges = tedges; for(i=0; i<tedges; i++) poly[i] = tpoly[i]; } //---- clipping applied glBegin(GL_POLYGON); for(i=0; i<edges; i++) { Vec tx, tc; tx = poly[i]-subcorner; tc = VECDIVIDE(tx,subdim); glTexCoord3f(tc.x, tc.y, tc.z); glVertex3f(poly[i].x, poly[i].y, poly[i].z); } glEnd(); return 1; } void DrawLowresVolume::drawSlices(Vec pn, Vec minvert, Vec maxvert, int layers, float stepsize) { float xmin, xmax, ymin, ymax, zmin, zmax; Vec subdim, subcorner, subvol[8]; xmin = m_dataMin.x + 1; ymin = m_dataMin.y + 1; zmin = m_dataMin.z + 1; xmax = m_dataMax.x - 1; ymax = m_dataMax.y - 1; zmax = m_dataMax.z - 1; subvol[0] = Vec(xmin, ymin, zmin); subvol[1] = Vec(xmax, ymin, zmin); subvol[2] = Vec(xmax, ymax, zmin); subvol[3] = Vec(xmin, ymax, zmin); subvol[4] = Vec(xmin, ymin, zmax); subvol[5] = Vec(xmax, ymin, zmax); subvol[6] = Vec(xmax, ymax, zmax); subvol[7] = Vec(xmin, ymax, zmax); subcorner = m_virtualTextureMin, subdim = m_virtualTextureSize - Vec(1,1,1); Vec step = stepsize*pn; Vec po = minvert+layers*step; for(int s=0; s<layers; s++) { po -= step; drawpoly(po, pn, subvol, subdim, subcorner); } } bool DrawLowresVolume::keyPressEvent(QKeyEvent *event) { return m_boundingBox.keyPressEvent(event); } void DrawLowresVolume::load(const char *flnm) { QDomDocument document; QFile f(flnm); if (f.open(QIODevice::ReadOnly)) { document.setContent(&f); f.close(); } QDomElement main = document.documentElement(); QDomNodeList dlist = main.childNodes(); Vec svmin = m_dataMin; Vec svmax = m_dataMax; for(int i=0; i<dlist.count(); i++) { if (dlist.at(i).nodeName() == "volmin") { QString str = dlist.at(i).toElement().text(); m_dataMin = StaticFunctions::getVec(str); } else if (dlist.at(i).nodeName() == "volmax") { QString str = dlist.at(i).toElement().text(); m_dataMax = StaticFunctions::getVec(str); } else if (dlist.at(i).nodeName() == "subvolmin") { QString str = dlist.at(i).toElement().text(); svmin = StaticFunctions::getVec(str); } else if (dlist.at(i).nodeName() == "subvolmax") { QString str = dlist.at(i).toElement().text(); svmax = StaticFunctions::getVec(str); } } // Vec voxelScaling = Global::voxelScaling(); // m_boundingBox.setBounds(VECPRODUCT(m_dataMin,voxelScaling), // VECPRODUCT(m_dataMax,voxelScaling)); m_boundingBox.setBounds(m_dataMin, m_dataMax); // svmin = VECPRODUCT(svmin, voxelScaling); // svmax = VECPRODUCT(svmax, voxelScaling); m_boundingBox.setPositions(svmin, svmax); } void DrawLowresVolume::save(const char *flnm) { QDomDocument doc; QFile fin(flnm); if (fin.open(QIODevice::ReadOnly)) { doc.setContent(&fin); fin.close(); } QDomElement topElement = doc.documentElement(); QString str; { QDomElement de0 = doc.createElement("volmin"); if (Global::volumeType() != Global::DummyVolume) str = QString("%1 %2 %3"). \ arg(m_dataMin.x).\ arg(m_dataMin.y).\ arg(m_dataMin.z); else str = QString("%1 %2 %3"). \ arg(m_dataMin.z).\ arg(m_dataMin.y).\ arg(m_dataMin.x); QDomText tn0 = doc.createTextNode(str); de0.appendChild(tn0); topElement.appendChild(de0); QDomElement de1 = doc.createElement("volmax"); if (Global::volumeType() != Global::DummyVolume) str = QString("%1 %2 %3"). \ arg(m_dataMax.x).\ arg(m_dataMax.y).\ arg(m_dataMax.z); else str = QString("%1 %2 %3"). \ arg(m_dataMax.z).\ arg(m_dataMax.y).\ arg(m_dataMax.x); QDomText tn1 = doc.createTextNode(str); de1.appendChild(tn1); topElement.appendChild(de1); } { Vec bbmin, bbmax; m_boundingBox.bounds(bbmin, bbmax); QDomElement de0 = doc.createElement("subvolmin"); if (Global::volumeType() != Global::DummyVolume) str = QString("%1 %2 %3"). \ arg(bbmin.x).\ arg(bbmin.y).\ arg(bbmin.z); else str = QString("%1 %2 %3"). \ arg(bbmin.z).\ arg(bbmin.y).\ arg(bbmin.x); QDomText tn0 = doc.createTextNode(str); de0.appendChild(tn0); topElement.appendChild(de0); QDomElement de1 = doc.createElement("subvolmax"); if (Global::volumeType() != Global::DummyVolume) str = QString("%1 %2 %3"). \ arg(bbmax.x).\ arg(bbmax.y).\ arg(bbmax.z); else str = QString("%1 %2 %3"). \ arg(bbmax.z).\ arg(bbmax.y).\ arg(bbmax.x); QDomText tn1 = doc.createTextNode(str); de1.appendChild(tn1); topElement.appendChild(de1); } QFile fout(flnm); if (fout.open(QIODevice::WriteOnly)) { QTextStream out(&fout); doc.save(out, 2); fout.close(); } } void DrawLowresVolume::switchInterpolation() { glActiveTexture(GL_TEXTURE1); if (Global::interpolationType(Global::TextureInterpolation)) // linear { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: OVR.OpenVR.IVRApplications #include "OVR/OpenVR/IVRApplications.hpp" // Including type: System.MulticastDelegate #include "System/MulticastDelegate.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: OVR::OpenVR namespace OVR::OpenVR { // Forward declaring type: EVRApplicationProperty struct EVRApplicationProperty; // Forward declaring type: EVRApplicationError struct EVRApplicationError; } // Forward declaring namespace: System namespace System { // Forward declaring type: IAsyncResult class IAsyncResult; // Forward declaring type: AsyncCallback class AsyncCallback; } // Completed forward declares // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Forward declaring type: _GetApplicationPropertyBool class _GetApplicationPropertyBool; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool); DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool*, "OVR.OpenVR", "IVRApplications/_GetApplicationPropertyBool"); // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Size: 0x70 #pragma pack(push, 1) // Autogenerated type: OVR.OpenVR.IVRApplications/OVR.OpenVR._GetApplicationPropertyBool // [TokenAttribute] Offset: FFFFFFFF // [UnmanagedFunctionPointerAttribute] Offset: EB2F74 class IVRApplications::_GetApplicationPropertyBool : public System::MulticastDelegate { public: // public System.Void .ctor(System.Object object, System.IntPtr method) // Offset: 0x1753910 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static IVRApplications::_GetApplicationPropertyBool* New_ctor(::Il2CppObject* object, System::IntPtr method) { static auto ___internal__logger = ::Logger::get().WithContext("OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<IVRApplications::_GetApplicationPropertyBool*, creationType>(object, method))); } // public System.Boolean Invoke(System.String pchAppKey, OVR.OpenVR.EVRApplicationProperty eProperty, ref OVR.OpenVR.EVRApplicationError peError) // Offset: 0x1746110 bool Invoke(::Il2CppString* pchAppKey, OVR::OpenVR::EVRApplicationProperty eProperty, ByRef<OVR::OpenVR::EVRApplicationError> peError); // public System.IAsyncResult BeginInvoke(System.String pchAppKey, OVR.OpenVR.EVRApplicationProperty eProperty, ref OVR.OpenVR.EVRApplicationError peError, System.AsyncCallback callback, System.Object object) // Offset: 0x1753920 System::IAsyncResult* BeginInvoke(::Il2CppString* pchAppKey, OVR::OpenVR::EVRApplicationProperty eProperty, ByRef<OVR::OpenVR::EVRApplicationError> peError, System::AsyncCallback* callback, ::Il2CppObject* object); // public System.Boolean EndInvoke(ref OVR.OpenVR.EVRApplicationError peError, System.IAsyncResult result) // Offset: 0x17539DC bool EndInvoke(ByRef<OVR::OpenVR::EVRApplicationError> peError, System::IAsyncResult* result); }; // OVR.OpenVR.IVRApplications/OVR.OpenVR._GetApplicationPropertyBool #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::Invoke // Il2CppName: Invoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::*)(::Il2CppString*, OVR::OpenVR::EVRApplicationProperty, ByRef<OVR::OpenVR::EVRApplicationError>)>(&OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::Invoke)> { static const MethodInfo* get() { static auto* pchAppKey = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* eProperty = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRApplicationProperty")->byval_arg; static auto* peError = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRApplicationError")->this_arg; return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool*), "Invoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pchAppKey, eProperty, peError}); } }; // Writing MetadataGetter for method: OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::BeginInvoke // Il2CppName: BeginInvoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IAsyncResult* (OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::*)(::Il2CppString*, OVR::OpenVR::EVRApplicationProperty, ByRef<OVR::OpenVR::EVRApplicationError>, System::AsyncCallback*, ::Il2CppObject*)>(&OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::BeginInvoke)> { static const MethodInfo* get() { static auto* pchAppKey = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* eProperty = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRApplicationProperty")->byval_arg; static auto* peError = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRApplicationError")->this_arg; static auto* callback = &::il2cpp_utils::GetClassFromName("System", "AsyncCallback")->byval_arg; static auto* object = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool*), "BeginInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{pchAppKey, eProperty, peError, callback, object}); } }; // Writing MetadataGetter for method: OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::EndInvoke // Il2CppName: EndInvoke template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::*)(ByRef<OVR::OpenVR::EVRApplicationError>, System::IAsyncResult*)>(&OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool::EndInvoke)> { static const MethodInfo* get() { static auto* peError = &::il2cpp_utils::GetClassFromName("OVR.OpenVR", "EVRApplicationError")->this_arg; static auto* result = &::il2cpp_utils::GetClassFromName("System", "IAsyncResult")->byval_arg; return ::il2cpp_utils::FindMethod(classof(OVR::OpenVR::IVRApplications::_GetApplicationPropertyBool*), "EndInvoke", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{peError, result}); } };
#include "LoadSaveLightEffect.h" #include "Soldier_Control.h" #include "Weapons.h" #include "Handle_Items.h" #include "WorldDef.h" #include "Tile_Animation.h" #include "LightEffects.h" #include "Isometric_Utils.h" #include "Explosion_Control.h" #include "Random.h" #include "Lighting.h" #include "Game_Clock.h" #include "OppList.h" #include "Tactical_Save.h" #include "Campaign_Types.h" #include "FileMan.h" #include "SaveLoadGame.h" #include "ContentManager.h" #include "GameInstance.h" #include <algorithm> #define NUM_LIGHT_EFFECT_SLOTS 25 // GLOBAL FOR LIGHT LISTING static LIGHTEFFECT gLightEffectData[NUM_LIGHT_EFFECT_SLOTS]; static UINT32 guiNumLightEffects = 0; #define BASE_FOR_EACH_LIGHTEFFECT(type, iter) \ for (type* iter = gLightEffectData, \ * const iter##__end = gLightEffectData + guiNumLightEffects; \ iter != iter##__end; \ ++iter) \ if (!iter->fAllocated) continue; else #define FOR_EACH_LIGHTEFFECT(iter) BASE_FOR_EACH_LIGHTEFFECT( LIGHTEFFECT, iter) #define CFOR_EACH_LIGHTEFFECT(iter) BASE_FOR_EACH_LIGHTEFFECT(const LIGHTEFFECT, iter) static LIGHTEFFECT* GetFreeLightEffect(void) { for (LIGHTEFFECT* l = gLightEffectData; l != gLightEffectData + guiNumLightEffects; ++l) { if (!l->fAllocated) return l; } if (guiNumLightEffects < NUM_LIGHT_EFFECT_SLOTS) { return &gLightEffectData[guiNumLightEffects++]; } return NULL; } static void UpdateLightingSprite(LIGHTEFFECT* pLight) { CHAR8 LightName[20]; // Build light.... sprintf( LightName, "Light%d", pLight->bRadius ); // Delete old one if one exists... if (pLight->light != NULL) { LightSpriteDestroy(pLight->light); pLight->light = NULL; } // Effect light..... LIGHT_SPRITE* const l = LightSpriteCreate(LightName); pLight->light = l; if (l == NULL) { // Could not light! return; } LightSpritePower(l, TRUE); LightSpritePosition(l, CenterX(pLight->sGridNo) / CELL_X_SIZE, CenterY(pLight->sGridNo) / CELL_Y_SIZE); } LIGHTEFFECT* NewLightEffect(const INT16 sGridNo, const INT8 bType) { UINT8 ubDuration=0; UINT8 ubStartRadius=0; LIGHTEFFECT* const l = GetFreeLightEffect(); if (l == NULL) return NULL; *l = LIGHTEFFECT{}; // Set some values... l->sGridNo = sGridNo; l->bType = bType; l->light = NULL; l->uiTimeOfLastUpdate = GetWorldTotalSeconds(); switch( bType ) { case LIGHT_FLARE_MARK_1: ubDuration = 6; ubStartRadius = 6; break; } l->ubDuration = ubDuration; l->bRadius = ubStartRadius; l->bAge = 0; l->fAllocated = TRUE; UpdateLightingSprite(l); // Handle sight here.... AllTeamsLookForAll( FALSE ); return l; } void DecayLightEffects( UINT32 uiTime ) { // age all active tear gas clouds, deactivate those that are just dispersing FOR_EACH_LIGHTEFFECT(l) { // ATE: Do this every so ofte, to acheive the effect we want... if (uiTime - l->uiTimeOfLastUpdate <= 350) continue; const UINT16 usNumUpdates = (uiTime - l->uiTimeOfLastUpdate) / 350; l->uiTimeOfLastUpdate = uiTime; BOOLEAN fDelete = FALSE; for (UINT32 i = 0; i < usNumUpdates; ++i) { l->bAge++; // if this cloud remains effective (duration not reached) if (l->bAge >= l->ubDuration) { fDelete = TRUE; break; } // calculate the new cloud radius // cloud expands by 1 every turn outdoors, and every other turn indoors if (l->bAge % 2) l->bRadius--; if (l->bRadius == 0) { fDelete = TRUE; break; } UpdateLightingSprite(l); } if (fDelete) { l->fAllocated = FALSE; if (l->light != NULL) LightSpriteDestroy(l->light); } // Handle sight here.... AllTeamsLookForAll(FALSE); } } void LoadLightEffectsFromLoadGameFile(HWFILE const hFile) { std::fill_n(gLightEffectData, NUM_LIGHT_EFFECT_SLOTS, LIGHTEFFECT{}); //Load the Number of Light Effects hFile->read(&guiNumLightEffects, sizeof(UINT32)); //if there are lights saved. if( guiNumLightEffects != 0 ) { //loop through and apply the light effects to the map for (UINT32 uiCount = 0; uiCount < guiNumLightEffects; ++uiCount) { ExtractLightEffectFromFile(hFile, &gLightEffectData[uiCount]); } } //loop through and apply the light effects to the map FOR_EACH_LIGHTEFFECT(l) { UpdateLightingSprite(l); } } void SaveLightEffectsToMapTempFile(INT16 const sMapX, INT16 const sMapY, INT8 const bMapZ) { UINT32 uiNumLightEffects=0; //get the name of the map ST::string const zMapName = GetMapTempFileName( SF_LIGHTING_EFFECTS_TEMP_FILE_EXISTS, sMapX, sMapY, bMapZ ); //delete file the file. GCM->tempFiles()->deleteFile( zMapName ); //loop through and count the number of Light effects CFOR_EACH_LIGHTEFFECT(l) { ++uiNumLightEffects; } //if there are no Light effects if( uiNumLightEffects == 0 ) { //set the fact that there are no Light effects for this sector ReSetSectorFlag( sMapX, sMapY, bMapZ, SF_LIGHTING_EFFECTS_TEMP_FILE_EXISTS ); return; } AutoSGPFile hFile(GCM->tempFiles()->openForWriting(zMapName, true)); //Save the Number of Light Effects hFile->write(&uiNumLightEffects, sizeof(UINT32)); //loop through and save the number of Light effects CFOR_EACH_LIGHTEFFECT(l) { InjectLightEffectIntoFile(hFile, l); } SetSectorFlag( sMapX, sMapY, bMapZ, SF_LIGHTING_EFFECTS_TEMP_FILE_EXISTS ); } void LoadLightEffectsFromMapTempFile(INT16 const sMapX, INT16 const sMapY, INT8 const bMapZ) { UINT32 uiCnt=0; ST::string const zMapName = GetMapTempFileName( SF_LIGHTING_EFFECTS_TEMP_FILE_EXISTS, sMapX, sMapY, bMapZ ); AutoSGPFile hFile(GCM->tempFiles()->openForReading(zMapName)); //Clear out the old list ResetLightEffects(); //Load the Number of Light Effects hFile->read(&guiNumLightEffects, sizeof(UINT32)); //loop through and load the list for( uiCnt=0; uiCnt<guiNumLightEffects;uiCnt++) { ExtractLightEffectFromFile(hFile, &gLightEffectData[uiCnt]); } //loop through and apply the light effects to the map FOR_EACH_LIGHTEFFECT(l) { UpdateLightingSprite(l); } } void ResetLightEffects() { //Clear out the old list std::fill_n(gLightEffectData, NUM_LIGHT_EFFECT_SLOTS, LIGHTEFFECT{}); guiNumLightEffects = 0; }
// 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. #include "arrow/python/numpy_interop.h" #include "arrow/python/numpy_convert.h" #include <cstdint> #include <memory> #include <string> #include <vector> #include "arrow/buffer.h" #include "arrow/tensor.h" #include "arrow/type.h" #include "arrow/python/common.h" #include "arrow/python/pyarrow.h" #include "arrow/python/type_traits.h" namespace arrow { namespace py { bool is_contiguous(PyObject* array) { if (PyArray_Check(array)) { return (PyArray_FLAGS(reinterpret_cast<PyArrayObject*>(array)) & (NPY_ARRAY_C_CONTIGUOUS | NPY_ARRAY_F_CONTIGUOUS)) != 0; } else { return false; } } NumPyBuffer::NumPyBuffer(PyObject* ao) : Buffer(nullptr, 0) { PyAcquireGIL lock; arr_ = ao; Py_INCREF(ao); if (PyArray_Check(ao)) { PyArrayObject* ndarray = reinterpret_cast<PyArrayObject*>(ao); data_ = reinterpret_cast<const uint8_t*>(PyArray_DATA(ndarray)); size_ = PyArray_SIZE(ndarray) * PyArray_DESCR(ndarray)->elsize; capacity_ = size_; if (PyArray_FLAGS(ndarray) & NPY_ARRAY_WRITEABLE) { is_mutable_ = true; } } } NumPyBuffer::~NumPyBuffer() { PyAcquireGIL lock; Py_XDECREF(arr_); } #define TO_ARROW_TYPE_CASE(NPY_NAME, FACTORY) \ case NPY_##NPY_NAME: \ *out = FACTORY(); \ break; Status GetTensorType(PyObject* dtype, std::shared_ptr<DataType>* out) { if (!PyArray_DescrCheck(dtype)) { return Status::TypeError("Did not pass numpy.dtype object"); } PyArray_Descr* descr = reinterpret_cast<PyArray_Descr*>(dtype); int type_num = fix_numpy_type_num(descr->type_num); switch (type_num) { TO_ARROW_TYPE_CASE(BOOL, uint8); TO_ARROW_TYPE_CASE(INT8, int8); TO_ARROW_TYPE_CASE(INT16, int16); TO_ARROW_TYPE_CASE(INT32, int32); TO_ARROW_TYPE_CASE(INT64, int64); TO_ARROW_TYPE_CASE(UINT8, uint8); TO_ARROW_TYPE_CASE(UINT16, uint16); TO_ARROW_TYPE_CASE(UINT32, uint32); TO_ARROW_TYPE_CASE(UINT64, uint64); TO_ARROW_TYPE_CASE(FLOAT16, float16); TO_ARROW_TYPE_CASE(FLOAT32, float32); TO_ARROW_TYPE_CASE(FLOAT64, float64); default: { return Status::NotImplemented("Unsupported numpy type ", descr->type_num); } } return Status::OK(); } Status GetNumPyType(const DataType& type, int* type_num) { #define NUMPY_TYPE_CASE(ARROW_NAME, NPY_NAME) \ case Type::ARROW_NAME: \ *type_num = NPY_##NPY_NAME; \ break; switch (type.id()) { NUMPY_TYPE_CASE(UINT8, UINT8); NUMPY_TYPE_CASE(INT8, INT8); NUMPY_TYPE_CASE(UINT16, UINT16); NUMPY_TYPE_CASE(INT16, INT16); NUMPY_TYPE_CASE(UINT32, UINT32); NUMPY_TYPE_CASE(INT32, INT32); NUMPY_TYPE_CASE(UINT64, UINT64); NUMPY_TYPE_CASE(INT64, INT64); NUMPY_TYPE_CASE(HALF_FLOAT, FLOAT16); NUMPY_TYPE_CASE(FLOAT, FLOAT32); NUMPY_TYPE_CASE(DOUBLE, FLOAT64); default: { return Status::NotImplemented("Unsupported tensor type: ", type.ToString()); } } #undef NUMPY_TYPE_CASE return Status::OK(); } Status NumPyDtypeToArrow(PyObject* dtype, std::shared_ptr<DataType>* out) { if (!PyArray_DescrCheck(dtype)) { return Status::TypeError("Did not pass numpy.dtype object"); } PyArray_Descr* descr = reinterpret_cast<PyArray_Descr*>(dtype); return NumPyDtypeToArrow(descr, out); } Status NumPyDtypeToArrow(PyArray_Descr* descr, std::shared_ptr<DataType>* out) { int type_num = fix_numpy_type_num(descr->type_num); switch (type_num) { TO_ARROW_TYPE_CASE(BOOL, boolean); TO_ARROW_TYPE_CASE(INT8, int8); TO_ARROW_TYPE_CASE(INT16, int16); TO_ARROW_TYPE_CASE(INT32, int32); TO_ARROW_TYPE_CASE(INT64, int64); TO_ARROW_TYPE_CASE(UINT8, uint8); TO_ARROW_TYPE_CASE(UINT16, uint16); TO_ARROW_TYPE_CASE(UINT32, uint32); TO_ARROW_TYPE_CASE(UINT64, uint64); TO_ARROW_TYPE_CASE(FLOAT16, float16); TO_ARROW_TYPE_CASE(FLOAT32, float32); TO_ARROW_TYPE_CASE(FLOAT64, float64); TO_ARROW_TYPE_CASE(STRING, binary); TO_ARROW_TYPE_CASE(UNICODE, utf8); case NPY_DATETIME: { auto date_dtype = reinterpret_cast<PyArray_DatetimeDTypeMetaData*>(descr->c_metadata); switch (date_dtype->meta.base) { case NPY_FR_s: *out = timestamp(TimeUnit::SECOND); break; case NPY_FR_ms: *out = timestamp(TimeUnit::MILLI); break; case NPY_FR_us: *out = timestamp(TimeUnit::MICRO); break; case NPY_FR_ns: *out = timestamp(TimeUnit::NANO); break; case NPY_FR_D: *out = date32(); break; case NPY_FR_GENERIC: return Status::NotImplemented("Unbound or generic datetime64 time unit"); default: return Status::NotImplemented("Unsupported datetime64 time unit"); } } break; default: { return Status::NotImplemented("Unsupported numpy type ", descr->type_num); } } return Status::OK(); } #undef TO_ARROW_TYPE_CASE Status NdarrayToTensor(MemoryPool* pool, PyObject* ao, std::shared_ptr<Tensor>* out) { if (!PyArray_Check(ao)) { return Status::TypeError("Did not pass ndarray object"); } PyArrayObject* ndarray = reinterpret_cast<PyArrayObject*>(ao); // TODO(wesm): What do we want to do with non-contiguous memory and negative strides? int ndim = PyArray_NDIM(ndarray); // This is also holding the GIL, so don't already draw it. std::shared_ptr<Buffer> data = std::make_shared<NumPyBuffer>(ao); std::vector<int64_t> shape(ndim); std::vector<int64_t> strides(ndim); { PyAcquireGIL lock; npy_intp* array_strides = PyArray_STRIDES(ndarray); npy_intp* array_shape = PyArray_SHAPE(ndarray); for (int i = 0; i < ndim; ++i) { if (array_strides[i] < 0) { return Status::Invalid("Negative ndarray strides not supported"); } shape[i] = array_shape[i]; strides[i] = array_strides[i]; } std::shared_ptr<DataType> type; RETURN_NOT_OK( GetTensorType(reinterpret_cast<PyObject*>(PyArray_DESCR(ndarray)), &type)); *out = std::make_shared<Tensor>(type, data, shape, strides); return Status::OK(); } } Status TensorToNdarray(const std::shared_ptr<Tensor>& tensor, PyObject* base, PyObject** out) { PyAcquireGIL lock; int type_num; RETURN_NOT_OK(GetNumPyType(*tensor->type(), &type_num)); PyArray_Descr* dtype = PyArray_DescrNewFromType(type_num); RETURN_IF_PYERROR(); const int ndim = tensor->ndim(); std::vector<npy_intp> npy_shape(ndim); std::vector<npy_intp> npy_strides(ndim); for (int i = 0; i < ndim; ++i) { npy_shape[i] = tensor->shape()[i]; npy_strides[i] = tensor->strides()[i]; } const void* immutable_data = nullptr; if (tensor->data()) { immutable_data = tensor->data()->data(); } // Remove const =( void* mutable_data = const_cast<void*>(immutable_data); int array_flags = 0; if (tensor->is_row_major()) { array_flags |= NPY_ARRAY_C_CONTIGUOUS; } if (tensor->is_column_major()) { array_flags |= NPY_ARRAY_F_CONTIGUOUS; } if (tensor->is_mutable()) { array_flags |= NPY_ARRAY_WRITEABLE; } PyObject* result = PyArray_NewFromDescr(&PyArray_Type, dtype, ndim, npy_shape.data(), npy_strides.data(), mutable_data, array_flags, nullptr); RETURN_IF_PYERROR() if (base == Py_None || base == nullptr) { base = py::wrap_tensor(tensor); } else { Py_XINCREF(base); } PyArray_SetBaseObject(reinterpret_cast<PyArrayObject*>(result), base); *out = result; return Status::OK(); } } // namespace py } // namespace arrow
/* David Wolak 3/16/18 CPL Sorry! Project This file holds the function definitions for everything in the control.h, everything here puts all the parts together. It moves the pawns, gets player inputs, draws cards, and updates the score. It also is reponsible for seeing if someone has won. */ #include <cstdio> #include "controlBoard.h" controller::controller()//Al the controller needs to do is open the file and read from it to start going { readFile(); } void controller::readFile()//Reads the player amount, board size, and the chance cards { int input = 0;//Used as a temp input ifstream inFile; inFile.open("settings.txt"); if(inFile.is_open())//If the file opens { inFile >> sizeBoard;//The first line is the board size if((sizeBoard < 4) || (sizeBoard > 80) || (sizeBoard%4 != 0))//If the board size is divisable by 4, bigger then 4, and smaller then 81 then it is valid { cout<<"***"<<endl;//If one of the critiea for the board side is wrong it errors and aborts the program cout<<"Critical Error: Settings file contains invalid board size"<<endl; cout<<"Aborting Program"<<endl; cout<<"***"<<endl; exit(1);//Aborts the program }else{//If the board size is valid then it creates the board gameBoard.createList(sizeBoard); } inFile >> playerAmt;//Next it gets the amount of players if(playerAmt > 4 || playerAmt < 1)//Only 1-4 players is allowed(yes one person is on purpose) { cout<<"***"<<endl;//If the amount of players is invalid it errors and aborts cout<<"Critical Error: Settings file contains invalid amount of players"<<endl; cout<<"Aborting Program"<<endl; cout<<"***"<<endl; exit(1);//Aborts the program }else{//Otherwise it makes a positoin tracker for that amount of players positions.createTracker(playerAmt,sizeBoard); } while(inFile >> input)//This loop is for reading in the chance cards { cout<<input<<endl; if(input < 1 || (input > 12 && input !=20))//The cards have to be either 20(meaning sorry card) or between 1-12 or else it will abort { cout<<"***"<<endl; cout<<"Critical Error: Settings file contains invalid chance card"<<endl; cout<<"Aborting Program"<<endl; cout<<"***"<<endl; exit(1);//Aborts the program }else{//If the card amount is valid it inputs it into the tree used to hold the chance cards, if(input == 20)//If its 20 it makes it a sorry card { cards.insert(20,true); }else{ cards.insert(input,false); } } } }else{//If no file is detected it aborts the set up cout<<"***"<<endl; cout<<"Crtical Error: No settings file detected"<<endl; cout<<"***"<<endl; exit(1);//Aborts the program } } int controller::menu()//Displays a menu and gets a valid input that it returns { int answer = 0; do{ cout<<"1. Roll Dice and move"<<endl; cout<<"2. Display Board"<<endl; cout<<"3. Display Scores"<<endl; cout<<"4. Skip Turn"<<endl; cout<<"5. Quit"<<endl; try{//Throws a int if the answer is invalid cin>>answer; if(answer > 5 || answer < 1) throw 10; }catch(int e){ cout<<"***"<<endl; cout<<"Error: Invalid input try again"<<endl; cout<<"***"<<endl; } }while(answer > 5 || answer < 1); return answer; } int controller::operator-(int color)//Overloaded operator allows a color to be moved { return this->move(color); } int controller::operator+(int color) { return this->move(color); } ostream & operator << (ostream &out,tracker & positions)//These two overloaded operators can output the scores or the board depending on what is being attched { positions.display(); return out; } ostream & operator <<(ostream &out,board & gameBoard) { gameBoard.displayBoard(); return out; } int controller::move(int color)//This actually moves a color around the board { int choice = 0;//Used to hold what the user wants to do int dice = 0;//Is used to hold a dice value char answer;//Used to hold players input int answerI = 0;//Is also used as a input from the players cout<<"Current Player: ";//This switch statement displays who is currently playing switch(color){ case 1: cout<<"Green"<<endl; break; case 2: cout<<"Yellow"<<endl; break; case 3: cout<<"Red"<<endl; break; case 4: cout<<"Blue"<<endl; break; } do{//This do while will keep going until the player wants to do something other then abort choice = menu(); if(choice == 2) { displayBoard(); }else if(choice == 3){ displayScore(); } }while(choice == 2 || choice == 3); if(choice == 4)//If player wants to skip there turn this run exiting the program { cout<<"Skipping your turn!"<<endl; return 0 ; }else if(choice == 5){//If the player wants to quit the game this runs which quits the program return 5; }else{//If the player doesnt want to quit then they must want to move dice = (rand()%6)+1;//Rolls the dice cout<<"You rolled a "<<dice<<endl;//Shows player what they rolled cout<<"Would you like to move that far?(Y/N)"<<endl;//Players have a option of if they want to move or if they want to skip there turn. do{//This loop gets the answer to do you want to move try{//Catches invalid answers and gives a error messae cout<<"If you would like to do this type Y, otherwise type N:"; cin>>answer; answer = toupper(answer); if(answer != 'Y' && answer != 'N') { throw 10; } cin.clear(); }catch(int e){ cout<<"***"<<endl; cout<<"Error: Invalid input detected"<<endl; cout<<"***"<<endl; } }while(answer != 'Y' && answer != 'N');//Unless the answer is Y or N the loop will contuine if(answer == 'Y')//If they want to move { cout<<"What pawn would you like to move?Input answer as a number from 1 to 3:"<<endl; do{//Gets a input form the player about what pawn they want to move try{ cin>>answerI; if(answerI > 5 || answerI < 1)//If the answer is invalid it throws a int which causes a error message to display throw 20; }catch(int e){ cout<<"***"<<endl; cout<<"Error: Number is out of range try again"<<endl; cout<<"***"<<endl; } }while(answerI > 3 || answerI < 1);//Keeps going until a good answer is given movePiece(color,answerI,dice);//This acutally move the piece with the right color, pawn, and with the amount to move }else{//If the player doesnt want to move cout<<"Looks like your going to skip your turn then"<<endl; } } return 0; } int controller::drawCard()//This function draws a card and actually moves the pawn { int card = cards.drawTop();//Gets a card from the top of the deck int amount = 0; switch(card)//Amount stores the value of move much the player is going to move since different cards move different amounts { case 1: amount = 1; break; case 2: amount = 2; break; case 3: amount = 3; break; case 4: amount = -4; break; case 5: amount = 5; break; case 6: amount = -6; break; case 7://Requires more steps ugh amount = 7; break; case 8: amount = 8; break; case 9: amount = -9; break; case 10: amount = 10; break; case 11: amount = 11; break; case 12: amount = 12; break; case 20://Sorry card! amount = 0; break; } return amount; } bool controller::winCheck(int color)//Checks if a color has won, to win you have to get a pawn to one pawn before your home { int home = 0;//Stores the home value fo the color int winCon = 0;//Holds where the pawn needs to be to win bool win;//Stores if they won home = homeCalculation(color);//Gets the home of the piece if(home == 0)//If the home is zero instead of win condition being -1 it has to be set to the number { winCon = sizeBoard - 1; }else{ winCon = home - 1; } win = positions.winCheck(color-1,winCon);//Gives the score tracker the info to check if it won return win; } void controller::displayScore()//Wrapper to display the scores { positions.display(); } void controller::displayBoard()//Wrapper to display the board and everyones positions { gameBoard.displayBoard(); } int controller::homeCalculation(int color)//Calculations the home value, this is done to prevent security issue with getting private data members { switch(color) { case 1://Just does the calculations for each color for where their home should be. Then returns that calculated value return 0; case 2: return sizeBoard/4; case 3: return sizeBoard/2; case 4: return ((sizeBoard/2)+(sizeBoard/1)); default: return 0; } } int controller::colorGetter(char color)//Given a char with the color it can return a int, this is because the score tracker users char arrays to organize everything while the rest uses ints so this lets the two pieces function together easier { if(color == 'G') { return 1; }else if(color == 'Y'){ return 2; }else if(color == 'R'){ return 3; }else if(color == 'B'){ return 4; }else{ return 0; } } int controller::pawnGetter(char pawn)//Does the same thing as color getter for the reason reasons but with pawns { if(pawn == '1') { return 1; }else if(pawn == '2'){ return 2; }else if(pawn == '3'){ return 3; }else return 0; } void controller::movePiece(int color, int pawn,int amount)//This is the biggest function, it acutally moves the pawns and draws the cards { char name[2];//Which pawn is used int card = 0;//Which if any card is drawn snprintf(name,2,"%d",pawn);//Converts a int into a char switch(color) { case 1: name[1] = 'G'; break; case 2: name[1] = 'Y'; break; case 3: name[1] = 'R'; break; case 4: name[1] = 'B'; break; } name[2] = '\0';//snprintf doesnt null terminate so it has to be done manually doubleNode * temp;//The place the piece is going to go doubleNode * currentPiece;//The place the node is currently at currentPiece = gameBoard.findPiece(name);//Finds the node that is about to be moved int pos = 0;//Gets the position of the nodes if(currentPiece)//If the piece is on the board it gets its current position pos = currentPiece->tileNumber(); if(currentPiece->tileNumber() == homeCalculation(color))//If the piece is still on its home tile { if(amount != 1 && amount != 2)//The player needs to have rolled a one or two in order to move out of home { cout<<"You need to roll a one or two to move out of spawn not a "<<amount<<"!"<<endl;//If a 1 or 2 hasnt been rolled then the player isnt allowed to move from home and the function exits return; } } if((pos%10-1) == 0)//If the current position is going to be on a draw card slot it does it, the -1 is so that the chance cards can never be on the pawns homes. They could be sent back one spot into a instant win { card = drawCard();//Draws a card from the deck cout<<"You landed on a chance card! You draw a card from the deck....."<<endl; cout<<"Its a "<<card<<"!"<<endl; if(card == 20){//this means its a sorry card cout<<"Sorry! "<<name[1]<<color<<" you just got kicked off!"<<endl; gameBoard.movePiece(NULL,currentPiece->tileNumber());//Clears the pawn off the board positions.movePiece(color,pawn,0);//Moves the pawn back to 0 on the score tracker return;//Exits the function }else{//just moving it around amount += card;//Otherwise it recalculates how far the pawn is going to move } } int newMove = pos+amount+1;//Calculates how far the pawn is going to move from its current slot while(newMove < 0)//If it goes back past slot 1 it recalcualtes where it will land { newMove += sizeBoard; } temp = gameBoard.getPosition(newMove);//Gets the tile of where the player is going to move if(temp->currentPiece() != NULL)//is SOMETHING there { char * name2 = new char[strlen(temp->currentPiece())];//If something is there it gets the name of the pawn there strcpy(name2,temp->currentPiece()); if(name[1] != name2[1]){//If this is not a players piece it will kick off the other players pawn gameBoard.movePiece(name,amount+pos);//Moves the current players pawn there int color2 = colorGetter(name2[1]);//Gets the color of the player who got kicked off int pawn2 = pawnGetter(name2[0]);//Gets the pawn number of the player who got kicked off cout<<"Sorry! "<<name2[1]<<color2<<" you got just kicked off!"<<endl; int move = amount+pos;//Figures out how much to move while(move < 0)//Same as above, its possible to go negative { move += sizeBoard; } gameBoard.movePiece(name,move);//Moves the new person onto the tile positions.movePiece(color,pawn,move);//Updates current players positions positions.movePiece(color2,pawn2,0);//Updates Sorry! persons positions gameBoard.movePiece(name,amount+pos); positions.movePiece(color,pawn,pos+amount); }else{//If players piece wants to move to a tile where they already are cout<<"You already have a piece there!"<<endl; } }else{//If nothing is there it just moves the pawn and updates the score tracker gameBoard.movePiece(name,newMove); positions.movePiece(color,pawn,newMove); } } /* void controller::display()//Wrapper to display all the posistions { positions.display(); }*/
/* * Copyright (C) 2020 Sony Interactive Entertainment Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "WKPagePrivatePlayStation.h" #include "NativeWebKeyboardEvent.h" #include "NativeWebMouseEvent.h" #include "NativeWebWheelEvent.h" #include "WebEventFactory.h" #include "WebPageProxy.h" #include <wpe/wpe.h> void WKPageSetSize(WKPageRef pageRef, WKSize size) { notImplemented(); } void WKPageHandleKeyboardEvent(WKPageRef pageRef, WKKeyboardEvent event) { using WebKit::NativeWebKeyboardEvent; wpe_input_keyboard_event wpeEvent; wpeEvent.time = 0; wpeEvent.key_code = event.virtualKeyCode; wpeEvent.hardware_key_code = event.virtualKeyCode; wpeEvent.modifiers = 0; // TODO: Handle modifiers. switch (event.type) { case kWKEventKeyDown: wpeEvent.pressed = true; break; case kWKEventKeyUp: wpeEvent.pressed = false; break; default: ASSERT_NOT_REACHED(); return; } NativeWebKeyboardEvent::HandledByInputMethod handledByInputMethod = NativeWebKeyboardEvent::HandledByInputMethod::No; Optional<Vector<WebCore::CompositionUnderline>> preeditUnderlines; Optional<WebKit::EditingRange> preeditSelectionRange; WebKit::toImpl(pageRef)->handleKeyboardEvent(NativeWebKeyboardEvent(&wpeEvent, "", handledByInputMethod, WTFMove(preeditUnderlines), WTFMove(preeditSelectionRange))); } void WKPageHandleMouseEvent(WKPageRef pageRef, WKMouseEvent event) { using WebKit::NativeWebMouseEvent; wpe_input_pointer_event wpeEvent; switch (event.type) { case kWKEventMouseDown: case kWKEventMouseUp: wpeEvent.type = wpe_input_pointer_event_type_button; break; case kWKEventMouseMove: wpeEvent.type = wpe_input_pointer_event_type_motion; break; default: ASSERT_NOT_REACHED(); return; } switch (event.button) { case kWKEventMouseButtonLeftButton: wpeEvent.button = 1; break; case kWKEventMouseButtonMiddleButton: wpeEvent.button = 3; break; case kWKEventMouseButtonRightButton: wpeEvent.button = 2; break; case kWKEventMouseButtonNoButton: wpeEvent.button = 0; break; default: ASSERT_NOT_REACHED(); return; } wpeEvent.time = 0; wpeEvent.x = event.position.x; wpeEvent.y = event.position.y; wpeEvent.state = 0; wpeEvent.modifiers = 0; // TODO: Handle modifiers. const float deviceScaleFactor = 1; WebKit::toImpl(pageRef)->handleMouseEvent(NativeWebMouseEvent(&wpeEvent, deviceScaleFactor)); } void WKPageHandleWheelEvent(WKPageRef pageRef, WKWheelEvent event) { using WebKit::WebWheelEvent; using WebKit::NativeWebWheelEvent; wpe_input_axis_2d_event wpeEvent; wpeEvent.base.type = (wpe_input_axis_event_type)(wpe_input_axis_event_type_motion_smooth | wpe_input_axis_event_type_mask_2d); wpeEvent.base.time = 0; wpeEvent.base.x = event.position.x; wpeEvent.base.y = event.position.y; wpeEvent.base.axis = 0; wpeEvent.base.value = 0; wpeEvent.base.modifiers = 0; // TODO: Handle modifiers. wpeEvent.x_axis = event.delta.width; wpeEvent.x_axis = event.delta.height; const float deviceScaleFactor = 1; WebKit::toImpl(pageRef)->handleWheelEvent(NativeWebWheelEvent(&wpeEvent.base, deviceScaleFactor, WebWheelEvent::Phase::PhaseNone, WebWheelEvent::Phase::PhaseNone)); }
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/kernels/internal/reference/quantize.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" namespace tflite { namespace ops { namespace micro { namespace quantize { void* Init(TfLiteContext* context, const char* buffer, size_t length) { return nullptr; } void Free(TfLiteContext* context, void* buffer) {} TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { TF_LITE_ENSURE_EQ(context, NumInputs(node), 1); TF_LITE_ENSURE_EQ(context, NumOutputs(node), 1); TfLiteTensor* input = &context->tensors[node->inputs->data[0]]; TfLiteTensor* output = &context->tensors[node->outputs->data[0]]; // TODO(b/128934713): Add support for fixed-point per-channel quantization. // Currently this only support affine per-layer quantization. TF_LITE_ENSURE_EQ(context, output->quantization.type, kTfLiteAffineQuantization); const auto* affine_quantization = reinterpret_cast<TfLiteAffineQuantization*>(output->quantization.params); TF_LITE_ENSURE(context, affine_quantization); TF_LITE_ENSURE(context, affine_quantization->scale); TF_LITE_ENSURE(context, affine_quantization->scale->size == 1); TF_LITE_ENSURE(context, input->type == kTfLiteFloat32 || input->type == kTfLiteInt16); TF_LITE_ENSURE(context, output->type == kTfLiteUInt8 || output->type == kTfLiteInt8); return kTfLiteOk; } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { TfLiteTensor* input = &context->tensors[node->inputs->data[0]]; TfLiteTensor* output = &context->tensors[node->outputs->data[0]]; tflite::QuantizationParams op_params; op_params.zero_point = output->params.zero_point; op_params.scale = static_cast<double>(output->params.scale); if (input->type == kTfLiteFloat32) { switch (output->type) { case kTfLiteInt8: reference_ops::AffineQuantize( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); break; case kTfLiteUInt8: reference_ops::AffineQuantize( op_params, GetTensorShape(input), GetTensorData<float>(input), GetTensorShape(output), GetTensorData<uint8_t>(output)); break; default: context->ReportError(context, "Input %s, output %s not supported.", TfLiteTypeGetName(input->type), TfLiteTypeGetName(output->type)); return kTfLiteError; } } else if (input->type == kTfLiteInt16) { switch (output->type) { case kTfLiteInt8: reference_ops::AffineQuantize( op_params, GetTensorShape(input), GetTensorData<int16_t>(input), GetTensorShape(output), GetTensorData<int8_t>(output)); break; default: context->ReportError(context, "Input %s, output %s not supported.", TfLiteTypeGetName(input->type), TfLiteTypeGetName(output->type)); return kTfLiteError; } } else { context->ReportError(context, "Input %s, output %s not supported.", TfLiteTypeGetName(input->type), TfLiteTypeGetName(output->type)); return kTfLiteError; } return kTfLiteOk; } } // namespace quantize // This Op (QUANTIZE) quantizes the input and produces quantized output. // AffineQuantize takes scale and zero point and quantizes the float value to // quantized output, in int8 or uint8 format. TfLiteRegistration* Register_QUANTIZE() { static TfLiteRegistration r = {}; r.init = quantize::Init; r.free = quantize::Free; r.prepare = quantize::Prepare; r.invoke = quantize::Eval; return &r; } } // namespace micro } // namespace ops } // namespace tflite
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <pwd.h> #include <sys/types.h> #include <nan.h> using namespace v8; void WhoAmI(const Nan::FunctionCallbackInfo<Value>& info) { char buf[BUFSIZ]; int r = getlogin_r(buf, BUFSIZ); if (r != 0) { strerror_r(r, buf, BUFSIZ); Nan::ThrowError(buf); return; } info.GetReturnValue().Set(Nan::New(buf).ToLocalChecked()); } void GetHomeDirectory(const Nan::FunctionCallbackInfo<Value>& info) { char* buf = (char*) malloc(sizeof(char) * BUFSIZ); if (buf == NULL) { Nan::ThrowError("out of memory"); return; } int r = getlogin_r(buf, BUFSIZ); if (r != 0) { strerror_r(r, buf, BUFSIZ); Nan::ThrowError(buf); free(buf); return; } struct passwd* pw = getpwnam((const char*) buf); if (pw == NULL) { strerror_r(errno, buf, BUFSIZ); Nan::ThrowError(buf); free(buf); return; } info.GetReturnValue().Set(Nan::New(pw->pw_dir).ToLocalChecked()); free(buf); }
#include "Timer.hpp" using namespace SmartIotInternals; Timer::Timer() : _initialTime(0) , _interval(0) , _tickAtBeginning(false) , _active(true) { } void Timer::setInterval(uint32_t interval, bool tickAtBeginning) { _interval = interval; _tickAtBeginning = tickAtBeginning; this->reset(); } uint32_t SmartIotInternals::Timer::getInterval() { return _interval; } bool Timer::check() const { if (!_active) return false; if (_tickAtBeginning && _initialTime == 0) return true; if (millis() - _initialTime >= _interval) return true; return false; } void Timer::reset() { if (_tickAtBeginning) { _initialTime = 0; } else { this->tick(); } } void Timer::tick() { _initialTime = millis(); } void Timer::activate() { _active = true; } void Timer::deactivate() { _active = false; reset(); } bool Timer::isActive() const { return _active; }
/****************************************************************************** * Copyright 2018 The Apollo 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. *****************************************************************************/ /** * @file **/ #include "modules/planning/scenarios/stop_sign/unprotected/stop_sign_unprotected_scenario.h" #include "modules/perception/proto/perception_obstacle.pb.h" #include "modules/planning/proto/planning_config.pb.h" #include "cyber/common/log.h" #include "modules/common/time/time.h" #include "modules/common/vehicle_state/vehicle_state_provider.h" #include "modules/planning/common/frame.h" #include "modules/planning/common/planning_context.h" #include "modules/planning/common/planning_gflags.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_creep.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_intersection_cruise.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_pre_stop.h" #include "modules/planning/scenarios/stop_sign/unprotected/stage_stop.h" namespace apollo { namespace planning { namespace scenario { namespace stop_sign { using common::TrajectoryPoint; using hdmap::HDMapUtil; using hdmap::StopSignInfo; using hdmap::StopSignInfoConstPtr; using StopSignLaneVehicles = std::unordered_map<std::string, std::vector<std::string>>; apollo::common::util::Factory< ScenarioConfig::StageType, Stage, Stage* (*)(const ScenarioConfig::StageConfig& stage_config)> StopSignUnprotectedScenario::s_stage_factory_; void StopSignUnprotectedScenario::Init() { if (init_) { return; } Scenario::Init(); if (!GetScenarioConfig()) { AERROR << "fail to get scenario specific config"; return; } const std::string stop_sign_overlap_id = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.object_id; if (stop_sign_overlap_id.empty()) { return; } hdmap::StopSignInfoConstPtr stop_sign = HDMapUtil::BaseMap().GetStopSignById( hdmap::MakeMapId(stop_sign_overlap_id)); if (!stop_sign) { AERROR << "Could not find stop sign: " << stop_sign_overlap_id; return; } context_.watch_vehicles.clear(); GetAssociatedLanes(*stop_sign); init_ = true; } void StopSignUnprotectedScenario::RegisterStages() { if (!s_stage_factory_.Empty()) { s_stage_factory_.Clear(); } s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_PRE_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStagePreStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_STOP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStageStop(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_CREEP, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStageCreep(config); }); s_stage_factory_.Register( ScenarioConfig::STOP_SIGN_UNPROTECTED_INTERSECTION_CRUISE, [](const ScenarioConfig::StageConfig& config) -> Stage* { return new StopSignUnprotectedStageIntersectionCruise(config); }); } std::unique_ptr<Stage> StopSignUnprotectedScenario::CreateStage( const ScenarioConfig::StageConfig& stage_config) { if (s_stage_factory_.Empty()) { RegisterStages(); } auto ptr = s_stage_factory_.CreateObjectOrNull(stage_config.stage_type(), stage_config); if (ptr) { ptr->SetContext(&context_); } return ptr; } bool StopSignUnprotectedScenario::IsTransferable( const Scenario& current_scenario, const Frame& frame) { if (PlanningContext::GetScenarioInfo() ->next_stop_sign_overlap.object_id.empty()) { return false; } const auto& reference_line_info = frame.reference_line_info().front(); const double adc_front_edge_s = reference_line_info.AdcSlBoundary().end_s(); const double stop_sign_overlap_start_s = PlanningContext::GetScenarioInfo()->next_stop_sign_overlap.start_s; const double adc_distance_to_stop_sign = stop_sign_overlap_start_s - adc_front_edge_s; ADEBUG << "adc_distance_to_stop_sign[" << adc_distance_to_stop_sign << "] stop_sign_overlap_start_s[" << stop_sign_overlap_start_s << "]"; switch (current_scenario.scenario_type()) { case ScenarioConfig::LANE_FOLLOW: case ScenarioConfig::CHANGE_LANE: case ScenarioConfig::SIDE_PASS: case ScenarioConfig::APPROACH: return (adc_distance_to_stop_sign > 0 && adc_distance_to_stop_sign <= config_.stop_sign_unprotected_config() .start_stop_sign_scenario_distance()); case ScenarioConfig::STOP_SIGN_PROTECTED: return false; case ScenarioConfig::STOP_SIGN_UNPROTECTED: return (current_scenario.GetStatus() != Scenario::ScenarioStatus::STATUS_DONE); case ScenarioConfig::TRAFFIC_LIGHT_PROTECTED: case ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_LEFT_TURN: case ScenarioConfig::TRAFFIC_LIGHT_UNPROTECTED_RIGHT_TURN: default: break; } return false; } /* * read scenario specific configs and set in context_ for stages to read */ bool StopSignUnprotectedScenario::GetScenarioConfig() { if (!config_.has_stop_sign_unprotected_config()) { AERROR << "miss scenario specific config"; return false; } context_.scenario_config.CopyFrom(config_.stop_sign_unprotected_config()); return true; } /* * get all the lanes associated/guarded by a stop sign */ int StopSignUnprotectedScenario::GetAssociatedLanes( const StopSignInfo& stop_sign_info) { context_.associated_lanes.clear(); std::vector<StopSignInfoConstPtr> associated_stop_signs; HDMapUtil::BaseMap().GetStopSignAssociatedStopSigns(stop_sign_info.id(), &associated_stop_signs); for (const auto stop_sign : associated_stop_signs) { if (stop_sign == nullptr) { continue; } const auto& associated_lane_ids = stop_sign->OverlapLaneIds(); for (const auto& lane_id : associated_lane_ids) { const auto lane = HDMapUtil::BaseMap().GetLaneById(lane_id); if (lane == nullptr) { continue; } for (const auto& stop_sign_overlap : lane->stop_signs()) { auto over_lap_info = stop_sign_overlap->GetObjectOverlapInfo(stop_sign.get()->id()); if (over_lap_info != nullptr) { context_.associated_lanes.push_back( std::make_pair(lane, stop_sign_overlap)); ADEBUG << "stop_sign: " << stop_sign_info.id().id() << "; associated_lane: " << lane_id.id() << "; associated_stop_sign: " << stop_sign.get()->id().id(); } } } } return 0; } } // namespace stop_sign } // namespace scenario } // namespace planning } // namespace apollo
// 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 "base/macros.h" #include "chrome/common/extensions/manifest_tests/chrome_manifest_test.h" #include "extensions/common/extension.h" #include "extensions/common/manifest_constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace extensions { class ThemeColorMatchesManifestTest : public ChromeManifestTest {}; TEST_F(ThemeColorMatchesManifestTest, ThemeColor) { Testcase testcases[] = { Testcase("theme_color.json", std::string(), extensions::Manifest::INTERNAL, Extension::FROM_BOOKMARK), }; RunTestcases(testcases, arraysize(testcases), EXPECT_TYPE_SUCCESS); Testcase failure_testcases[] = { Testcase("theme_color_wrong_type.json", extensions::manifest_errors::kInvalidAppThemeColor), }; RunTestcases(failure_testcases, arraysize(failure_testcases), EXPECT_TYPE_ERROR); Testcase warning_testcases[] = { Testcase("theme_color.json", extensions::manifest_errors::kInvalidThemeColorAppType), }; RunTestcases(warning_testcases, arraysize(warning_testcases), EXPECT_TYPE_WARNING); } } // namespace extensions
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/cognito-idp/model/AdminConfirmSignUpResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CognitoIdentityProvider::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; AdminConfirmSignUpResult::AdminConfirmSignUpResult() { } AdminConfirmSignUpResult::AdminConfirmSignUpResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } AdminConfirmSignUpResult& AdminConfirmSignUpResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { AWS_UNREFERENCED_PARAM(result); return *this; }
#include "booru-org-test.h" #include <QStringList> #include <QtTest> #include "models/image.h" #include "tags/tag.h" void BooruOrgTest::testHtml() { QList<Image*> images = getImages("Gelbooru (0.1)", "rm.booru.org", "regex", "rating:safe", "results.html"); // Convert results QStringList md5s; md5s.reserve(images.count()); for (Image *img : images) { md5s.append(img->md5()); } // Check results md5s = md5s.mid(0, 3); QStringList expected = QStringList() << "88407041cfd2d8358dda2f8699bfe98d84a7cf74" << "e0c2ddaf9403901cc1e293bcd369806d1deffd95" << "44f0f9560431d1b61ba1e9c401fdb3cc75920b38"; QCOMPARE(images.count(), 20); QCOMPARE(md5s, expected); } void BooruOrgTest::testPageTags() { QList<Tag> tags = getPageTags("Gelbooru (0.1)", "rm.booru.org", "regex", "rating:safe", "results.html"); QCOMPARE(tags.count(), 5); QCOMPARE(tags[0].text(), QString("barasuishou")); QCOMPARE(tags[0].count(), 4825); QCOMPARE(tags[1].text(), QString("image")); QCOMPARE(tags[1].count(), 94810); QCOMPARE(tags[2].text(), QString("rozen_maiden")); QCOMPARE(tags[2].count(), 125996); } QTEST_MAIN(BooruOrgTest)
/* * Copyright (c) 2017 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if HAS_FEATURE_AVX namespace { DEF_SEM(DoVZEROUPPER) { _Pragma("unroll") for (unsigned i = 0; i < IF_64BIT_ELSE(16, 8); ++i) { auto &vec = state.vec[i]; vec.ymm.dqwords.elems[1] = 0; IF_AVX512(vec.zmm.dqwords.elems[2] = 0;) IF_AVX512(vec.zmm.dqwords.elems[3] = 0;) } return memory; } } // namespace namespace { template<typename D, typename S1, size_t KL, size_t VL> DEF_SEM(VPBROADCASTB, D dst, S1 src1) { auto src_vec = UReadV8(src1); auto dst_vec = UClearV8(UReadV8(dst)); auto num_groups = NumVectorElems(dst_vec); auto src_byte = UExtractV8(src_vec, 0); for (std::size_t i = 0; i < num_groups; ++i) { dst_vec = UInsertV8(dst_vec, i, src_byte); } UWriteV8(dst, dst_vec); return memory; } } // namespace DEF_ISEL(VZEROUPPER) = DoVZEROUPPER; DEF_ISEL(VPBROADCASTB_YMMqq_XMMb) = VPBROADCASTB<VV256W, V128, 32, 256>; #endif // HAS_FEATURE_AVX
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <lbann-dev@llnl.gov> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_LAYERS_MISC_DIST_EMBEDDING_HPP_INCLUDED #define LBANN_LAYERS_MISC_DIST_EMBEDDING_HPP_INCLUDED #include "lbann/base.hpp" #include "lbann/layers/layer.hpp" #if defined(LBANN_HAS_SHMEM) || defined(LBANN_HAS_NVSHMEM) #include "lbann/layers/data_type_layer.hpp" #include "lbann/models/model.hpp" #include "lbann/optimizers/sgd.hpp" #include "lbann/weights/weights_helpers.hpp" #include "lbann/utils/memory.hpp" namespace lbann { /** @brief Embedding layer with distributed weights. * * This is similar to the embedding layer, which takes integer * indices and returns embedding vectors from a lookup table. * However, the embedding vectors are distributed between processes * and one-sided inter-process communication is performed with * OpenSHMEM (on CPU) or NVSHMEM (on GPU). * * The main benefit of this model-parallel approach is to handle * cases where the embedding vectors don't fit on one process. It * should also have better scaling properties when the mini-batch * size is very large. * * To take advantage of sparse gradients, the distributed embedding * layer provides the option to bypass the optimizer (which currently * only supports dense gradients) and perform sparse SGD directly on * the embedding weights. If enabled, SGD occurs during the layers * "update" phase (i.e. in the virtual update_compute function). * Otherwise, the layer converts sparse gradients to a dense tensor * and passes it into the usual optimizer. This is a hack and will be * deprecated once the optimizer class supports sparse gradients. * * @warning This is experimental. * * @todo Sparse SGD with optimizer class */ template <typename TensorDataType, data_layout Layout, El::Device Device> class dist_embedding_layer : public data_type_layer<TensorDataType> { static_assert(Layout == data_layout::DATA_PARALLEL, "distributed embedding layer only supports data parallel layout"); public: dist_embedding_layer( size_t num_embeddings, size_t embedding_dim, bool sparse_sgd, DataType learning_rate, bool barrier_in_forward_prop); dist_embedding_layer(const dist_embedding_layer& other); dist_embedding_layer& operator=(const dist_embedding_layer& other); ~dist_embedding_layer(); dist_embedding_layer* copy() const override; std::string get_type() const override; data_layout get_data_layout() const override; El::Device get_device_allocation() const override; description get_description() const override; /** @name Serialization */ ///@{ template <typename ArchiveT> void serialize(ArchiveT& ar); ///@} protected: friend class cereal::access; dist_embedding_layer(); void setup_dims(DataReaderMetaData& dr_metadata) override; void setup_data(size_t max_mini_batch_size) override; void fp_compute() override; void bp_compute() override; bool update_compute() override; public: /** Metadata for an embedding vector from a remote process. * * This should be treated as an internal implementation detail. It * is only in public scope so it is available to CUDA kernels in an * anonymous namespace. */ struct vector_metadata { size_t source_rank{0}; size_t source_index{0}; size_t target_rank{0}; size_t target_index{0}; bool is_active{false}; }; private: using LocalMat = El::Matrix<TensorDataType, Device>; /** @brief Non-blocking barrier * @todo Handle case with non-default CUDA stream. * @todo Move to comm header. */ static void nb_barrier( lbann_comm& comm, const El::mpi::Comm& c, Al::request& req); void attach_embeddings_to_shmem_buffer(); void apply_sparse_sgd_step( size_t num_gradients, LocalMat& local_embeddings); /** SHMEM buffer for embedding vectors. * * If the embedding weights matrix is not already attached to a * SHMEM buffer, then this layer allocates a SHMEM buffer and * attaches it. In this case, the layer is responsible for managing * the buffer. */ TensorDataType* m_embeddings_buffer{nullptr}; /** Allocated size of @c m_embeddings_buffer. */ size_t m_embeddings_buffer_size{0}; /** SHMEM buffer to communicate embedding vectors. */ TensorDataType* m_workspace_buffer{nullptr}; /** Allocated size of @c m_workspace_buffer. */ size_t m_workspace_buffer_size{0}; /** SHMEM buffer to communicate metadata for embedding vectors. */ vector_metadata* m_metadata_buffer{nullptr}; /** Allocated size of @c m_metadata_buffer. */ size_t m_metadata_buffer_size{0}; /** Request to synchronize non-blocking barriers. * * Careful synchronization is required to ensure the correctness of * asynchronous, one-sided communication via SHMEM buffers. After * any modification to a SHMEM buffer (local or remote), a * non-blocking barrier is launched to signal that the local * process has finished its work. Before the next access to the * SHMEM buffer, the non-blocking barrier is synchronized to make * sure that all remote processes have finished their work and that * the buffers are safe to access. */ Al::request m_nb_barrier_request; /** Size of dictionary of embeddings. */ size_t m_num_embeddings; /** Size of embedding vectors. */ size_t m_embedding_dim; /** Perform sparse SGD during backprop. * * Bypasses optimizer class. */ bool m_sparse_sgd; /** SGD learning rate. */ DataType m_learning_rate; /** Perform a blocking barrier at the beginning of forward prop. * * This layer performs synchronization with non-blocking barriers * to ensure the correctness of asynchronous communication. * However, gradient checking changes the embedding values without * performing any synchronization. The quickest fix is to do a * blocking barrier at the beginning of forward prop to make sure * that all the embeddings are ready to be accessed. * * @todo Think of a way to avoid this synchronization. */ bool m_barrier_in_forward_prop; }; // --------------------------------------------- // Implementation // --------------------------------------------- template <typename TensorDataType, data_layout Layout, El::Device Device> dist_embedding_layer<TensorDataType,Layout,Device>::dist_embedding_layer( size_t num_embeddings, size_t embedding_dim, bool sparse_sgd, DataType learning_rate, bool barrier_in_forward_prop) : data_type_layer<TensorDataType>(nullptr), m_num_embeddings{num_embeddings}, m_embedding_dim{embedding_dim}, m_sparse_sgd{sparse_sgd}, m_learning_rate{learning_rate}, m_barrier_in_forward_prop{barrier_in_forward_prop} { // Learning rate is only used for sparse SGD if (!m_sparse_sgd) { m_learning_rate = -1.0; } } template <typename TensorDataType, data_layout Layout, El::Device Device> dist_embedding_layer<TensorDataType,Layout,Device>::dist_embedding_layer() : dist_embedding_layer(1, 1, false, El::To<DataType>(1), false) {} template <typename TensorDataType, data_layout Layout, El::Device Device> dist_embedding_layer<TensorDataType,Layout,Device>::dist_embedding_layer( const dist_embedding_layer& other) : data_type_layer<TensorDataType>(other) { LBANN_ERROR("copy constructor is invalid for dist_embedding_layer"); } template <typename TensorDataType, data_layout Layout, El::Device Device> dist_embedding_layer<TensorDataType,Layout,Device>& dist_embedding_layer<TensorDataType,Layout,Device>::operator=( const dist_embedding_layer& other) { LBANN_ERROR("copy assignment operator is invalid for dist_embedding_layer"); } template <typename TensorDataType, data_layout Layout, El::Device Device> dist_embedding_layer<TensorDataType,Layout,Device>* dist_embedding_layer<TensorDataType,Layout,Device>::copy() const { return new dist_embedding_layer(*this); } template <typename TensorDataType, data_layout Layout, El::Device Device> std::string dist_embedding_layer<TensorDataType,Layout,Device>::get_type() const { return "distributed embedding"; } template <typename TensorDataType, data_layout Layout, El::Device Device> data_layout dist_embedding_layer<TensorDataType,Layout,Device>::get_data_layout() const { return Layout; } template <typename TensorDataType, data_layout Layout, El::Device Device> El::Device dist_embedding_layer<TensorDataType,Layout,Device>::get_device_allocation() const { return Device; } template <typename TensorDataType, data_layout Layout, El::Device Device> description dist_embedding_layer<TensorDataType,Layout,Device>::get_description() const { auto desc = data_type_layer<TensorDataType>::get_description(); desc.add("Num embeddings", m_num_embeddings); desc.add("Embedding dim", m_embedding_dim); desc.add("Using sparse SGD", m_sparse_sgd); desc.add("SGD learning rate", m_learning_rate); return desc; } template <typename TensorDataType, data_layout Layout, El::Device Device> void dist_embedding_layer<TensorDataType,Layout,Device>::setup_dims(DataReaderMetaData& dr_metadata) { data_type_layer<TensorDataType>::setup_dims(dr_metadata); auto dims = this->get_input_dims(); dims.push_back(static_cast<int>(m_embedding_dim)); this->set_output_dims(dims); } template <typename TensorDataType, data_layout Layout, El::Device Device> void dist_embedding_layer<TensorDataType,Layout,Device>::setup_data(size_t max_mini_batch_size) { data_type_layer<TensorDataType>::setup_data(max_mini_batch_size); // Synchronize non-blocking barrier // Note: Make sure SHMEM buffers are safe to reset. auto& comm = *this->get_comm(); comm.wait(m_nb_barrier_request); // Construct default weights if needed // Note: Randomly drawn from normal distribution with mean 0 and // standard deviation 1. if (!this->has_weights()) { auto w = std::make_shared<data_type_weights<TensorDataType>>(comm); auto init = make_unique<normal_initializer<TensorDataType>>(0,1); auto opt = this->m_model->template create_optimizer<TensorDataType>(); w->set_name(this->get_name() + "_weights"); w->set_initializer(std::move(init)); w->set_optimizer(std::move(opt)); this->add_weights(w); this->m_model->add_weights(std::move(w)); } if (this->num_weights() != 1) { LBANN_ERROR("attempted to setup ", this->get_type()," layer \"",this->get_name(),"\" ", "with an invalid number of weights ", "(expected 1, found ",this->num_weights(),")"); } // Configure embedding weights auto& embeddings = this->get_weights(0); { auto dist = this->get_prev_activations().DistData(); dist.colDist = El::STAR; dist.rowDist = El::VC; embeddings.set_dims({m_embedding_dim}, {m_num_embeddings}); embeddings.set_matrix_distribution(dist); } // Destroy embedding optimizer and create dummy weights // Note: This layer manually performs sparse SGD on embedding // weights during backprop, so the embedding optimizer isn't needed. // However, the layer must send gradients to some optimizer to // prevent the model from optimizing the layer out of compute graph // during backprop. We get around this by creating dummy weights // with no entries. if (m_sparse_sgd) { embeddings.set_optimizer(nullptr); auto w = std::make_shared<data_type_weights<TensorDataType>>(comm); auto opt = make_unique<sgd<TensorDataType>>(0.); w->set_name(this->get_name() + "_dummy_weights"); w->set_optimizer(std::move(opt)); w->set_dims(1); w->set_matrix_distribution(embeddings.get_matrix_distribution()); w->setup(); this->add_weights(w); this->m_model->add_weights(std::move(w)); } // Setup embedding weights embeddings.setup(); attach_embeddings_to_shmem_buffer(); // Non-blocking barrier // Note: Embeddings have been initialized nb_barrier(comm, comm.get_trainer_comm(), m_nb_barrier_request); } template <typename TensorDataType, data_layout Layout, El::Device Device> bool dist_embedding_layer<TensorDataType,Layout,Device>::update_compute() { // Apply sparse SGD if needed if (m_sparse_sgd) { const size_t input_size = this->get_input_size(); const size_t mini_batch_size = this->get_prev_activations().Width(); using ValuesGetter = weights_details::SafeWeightsAccessor<TensorDataType>; auto& embeddings = ValuesGetter::mutable_values(this->get_weights(0)); auto& local_embeddings = dynamic_cast<LocalMat&>(embeddings.Matrix()); apply_sparse_sgd_step(input_size * mini_batch_size, local_embeddings); } // Non-blocking barrier // Note: Embeddings are up-to-date. auto& comm = *this->get_comm(); comm.wait(m_nb_barrier_request); nb_barrier(comm, comm.get_trainer_comm(), m_nb_barrier_request); return true; } template <typename TensorDataType, data_layout Layout, El::Device Device> void dist_embedding_layer<TensorDataType,Layout,Device>::nb_barrier( lbann_comm& comm, const El::mpi::Comm& c, Al::request& req) { static El::Matrix<float,Device> buffer; buffer.SetMemoryMode(0); // Don't use memory pool buffer.Resize(1, 1); comm.nb_allreduce(buffer, c, req); } // --------------------------------------------- // Explicit template instantiation // --------------------------------------------- #ifdef LBANN_HAS_SHMEM extern template class dist_embedding_layer< float, data_layout::DATA_PARALLEL, El::Device::CPU>; #endif // LBANN_HAS_SHMEM #if defined(LBANN_HAS_GPU) && defined(LBANN_HAS_NVSHMEM) extern template class dist_embedding_layer< float, data_layout::DATA_PARALLEL, El::Device::GPU>; #endif // defined(LBANN_HAS_GPU) && defined(LBANN_HAS_NVSHMEM) } // namespace lbann #endif // defined(LBANN_HAS_SHMEM) || defined(LBANN_HAS_NVSHMEM) // --------------------------------------------- // Builder function // --------------------------------------------- namespace lbann { LBANN_DEFINE_LAYER_BUILDER(dist_embedding); } // namespace lbann #endif // LBANN_LAYERS_MISC_DIST_EMBEDDING_HPP_INCLUDED
#include "ui/downloadlink.h" #include <QFileDialog> #include <QStandardPaths> namespace Ui { DownloadLink::DownloadLink(const QString& urlp, const QString& filename, Api::Requester *request, QWidget *parent) : QLabel(filename, parent) { QFont font; font.setPixelSize(16); font.setFamily("whitney"); setFont(font); url = QString(urlp); requester = request; this->setCursor(Qt::PointingHandCursor); this->setStyleSheet("color: #00AFF4;"); } void DownloadLink::mouseReleaseEvent(QMouseEvent *) { QString downloadsFolder = QStandardPaths::writableLocation(QStandardPaths::DownloadLocation) + "/"; if (downloadsFolder.isEmpty()) { QDir dir("download/"); if (!dir.exists()) dir.mkpath("."); downloadsFolder = "download/"; } downloadsFolder = QFileDialog::getExistingDirectory(this, "Download", downloadsFolder) + "/"; if (downloadsFolder != "/") requester->getFile(url, downloadsFolder + url.left(url.lastIndexOf('/') + 1)); } }