text
stringlengths
5
1.04M
#include "nodeevents.h" #include "yaml-cpp/eventhandler.h" #include "yaml-cpp/mark.h" #include "yaml-cpp/node/detail/node.h" #include "yaml-cpp/node/detail/node_iterator.h" #include "yaml-cpp/node/node.h" #include "yaml-cpp/node/type.h" namespace YAML { void NodeEvents::AliasManager::RegisterReference(const detail::node& node) { m_anchorByIdentity.insert(std::make_pair(node.ref(), _CreateNewAnchor())); } anchor_t NodeEvents::AliasManager::LookupAnchor( const detail::node& node) const { AnchorByIdentity::const_iterator it = m_anchorByIdentity.find(node.ref()); if (it == m_anchorByIdentity.end()) return 0; return it->second; } NodeEvents::NodeEvents(const Node& node) : m_pMemory(node.m_pMemory), m_root(node.m_pNode) { if (m_root) Setup(*m_root); } void NodeEvents::Setup(const detail::node& node) { int& refCount = m_refCount[node.ref()]; refCount++; if (refCount > 1) return; if (node.type() == NodeType::Sequence) { for (detail::const_node_iterator it = node.begin(); it != node.end(); ++it) Setup(**it); } else if (node.type() == NodeType::Map) { for (detail::const_node_iterator it = node.begin(); it != node.end(); ++it) { Setup(*it->first); Setup(*it->second); } } } void NodeEvents::Emit(EventHandler& handler) { AliasManager am; handler.OnDocumentStart(Mark()); if (m_root) Emit(*m_root, handler, am); handler.OnDocumentEnd(); } void NodeEvents::Emit(const detail::node& node, EventHandler& handler, AliasManager& am) const { anchor_t anchor = NullAnchor; if (IsAliased(node)) { anchor = am.LookupAnchor(node); if (anchor) { handler.OnAlias(Mark(), anchor); return; } am.RegisterReference(node); anchor = am.LookupAnchor(node); } switch (node.type()) { case NodeType::Undefined: break; case NodeType::Null: handler.OnNull(Mark(), anchor); break; case NodeType::Scalar: handler.OnScalar(Mark(), node.tag(), anchor, node.scalar()); break; case NodeType::Sequence: handler.OnSequenceStart(Mark(), node.tag(), anchor); for (detail::const_node_iterator it = node.begin(); it != node.end(); ++it) Emit(**it, handler, am); handler.OnSequenceEnd(); break; case NodeType::Map: handler.OnMapStart(Mark(), node.tag(), anchor); for (detail::const_node_iterator it = node.begin(); it != node.end(); ++it) { Emit(*it->first, handler, am); Emit(*it->second, handler, am); } handler.OnMapEnd(); break; } } bool NodeEvents::IsAliased(const detail::node& node) const { RefCount::const_iterator it = m_refCount.find(node.ref()); return it != m_refCount.end() && it->second > 1; } }
/* ** JNetLib ** Copyright (C) 2000-2001 Nullsoft, Inc. ** Author: Justin Frankel ** File: testbnc.cpp - JNL network bounce test code ** License: see jnetlib.h */ #ifdef _WIN32 #include <windows.h> #else #define Sleep(x) usleep((x)*1000) #endif #include <stdio.h> #include "jnetlib.h" int main(int argc, char *argv[]) { JNL_Connection *cons[32]={0,}; JNL_Connection *outcons[32]={0,}; int n_cons=0; if (argc != 4 || !atoi(argv[1]) || !atoi(argv[3]) || !argv[2][0]) { printf("usage: redir localport host remoteport\n"); exit(1); } JNL::open_socketlib(); JNL_AsyncDNS dns; JNL_Listen l((short)atoi(argv[1])); printf("running...\n"); while (!l.is_error()) { Sleep(10); if (n_cons<32) { JNL_Connection *con=l.get_connect(); if (con) { int x; for (x = 0; x < 32; x ++) { if (!cons[x]) { outcons[x]=new JNL_Connection(); outcons[x]->connect(argv[2],atoi(argv[3])); cons[x]=con; char host[256]; JNL::addr_to_ipstr(cons[x]->get_remote(),host,sizeof(host)); n_cons++; printf("Connection %d (%s) opened (%d).\n",x,host,n_cons); break; } } } } int x; for (x = 0; x < 32; x ++) { if (cons[x]) { cons[x]->run(); outcons[x]->run(); int cerr=(cons[x]->get_state() == JNL_Connection::STATE_ERROR || cons[x]->get_state()==JNL_Connection::STATE_CLOSED); int oerr=(outcons[x]->get_state() == JNL_Connection::STATE_ERROR || outcons[x]->get_state()==JNL_Connection::STATE_CLOSED); if ((!outcons[x]->send_bytes_in_queue() && !cons[x]->recv_bytes_available() && cerr) || (!cons[x]->send_bytes_in_queue() && !outcons[x]->recv_bytes_available() && oerr) || (cerr && oerr)) { char host[256]; JNL::addr_to_ipstr(cons[x]->get_remote(),host,sizeof(host)); delete cons[x]; delete outcons[x]; outcons[x]=0; cons[x]=0; n_cons--; printf("Connection %d (%s) closed (%d)\n",x,host,n_cons); } else { char buf[4096]; int l; l=outcons[x]->send_bytes_available(); if (l > 4096) l=4096; if (l) l=cons[x]->recv_bytes(buf,l); if (l) outcons[x]->send(buf,l); l=cons[x]->send_bytes_available(); if (l > 4096) l=4096; if (l) l=outcons[x]->recv_bytes(buf,l); if (l) cons[x]->send(buf,l); } } } } JNL::close_socketlib(); return 0; }
#ifndef SCENEGAME_HPP_ #define SCENEGAME_HPP_ #include <iostream> #include <stdexcept> #include <vector> #include <map> #include "useGlm.hpp" #include "ASceneMenu.hpp" #include "AEntity.hpp" #include "ACharacter.hpp" #include "Bomb.hpp" #include "Score.hpp" #include "Spawner.hpp" #include "ABaseUI.hpp" #include "TextUI.hpp" #include "Model.hpp" #define NO_LEVEL -1 // value is no level loaded #define LEVEL_INTRO_DURATION 2 #define BLUR_SHADER_VS "shaders/blur_vs.glsl" #define BLUR_SHADER_FS "shaders/blur_fs.glsl" #define PP_VAO_WIDTH 4 #define PP_V_ARRAY_SIZE 24 class Player; class AEnemy; class Spawner; namespace GameState { /** * @brief All possible game states (INTRO, PLAY, PAUSE, GAME_OVER, ...) */ enum Enum { INTRO, PLAY, PAUSE, GAME_OVER, WIN, }; } // namespace GameState namespace EntityType { /** * @brief All possible entity states */ enum Enum { PLAYER, BOARD, BOARD_FLAG, ENEMY, }; } // namespace EntityType /** * @brief This is the game Scene. In this scene, you can play to the game and load levels */ class SceneGame : public ASceneMenu { private: SceneGame(); // Members typedef AEntity*(*entityFuncPtr)(SceneGame &); /** * @brief Contains a type of entity and a function to create it */ struct Entity { EntityType::Enum entityType; /**< The type of the entity */ entityFuncPtr entity; /**< The function to create the entity */ }; std::vector<SettingsJson *> _mapsList; /**< */ /** * @brief All 3D models of enemies that can be drew on different menus */ struct DrawForMenu { Model * player; /**< 3D model to draw player */ Model * flower; /**< 3D model to draw flower */ Model * robot; /**< 3D model to draw robot */ Model * fly; /**< 3D model to draw fly */ Model * frog; /**< 3D model to draw frog */ Model * crispy; /**< 3D model to draw crispy */ Model * follow; /**< 3D model to draw follow */ DrawForMenu(); }; DrawForMenu _menuModels; /**< All 3D elements to draw */ bool _alarm; /**< If we want to ring alarm */ Model *_terrain; /**< The terrain element */ // post processing stuff Shader *_blurShader; /**< PostProcess blur shader */ static std::array<float, PP_V_ARRAY_SIZE> const _ppVertices; /**< Vertices data */ uint32_t _ppShVbo; /**< PostProcess vbo */ uint32_t _ppShVao; /**< PostProcess vao */ uint32_t _blurFbo[2]; /**< PostProcess blur framebuffer */ uint32_t _blurTexColor[2]; /**< PostProcess blur texture */ uint32_t _rbo; /**< renderBufferObject to store depth and stencil buffers */ uint32_t _blurMaskTex; /**< The blur mask texture */ // Methods bool _loadLevel(int32_t levelId); bool _unloadLevel(); bool _initJsonLevel(int32_t levelId); bool _initPostProcess(); void _drawBoard(); protected: /** * @brief All UI elements (bonus, text, ...) */ struct AllUI { ABaseUI * introText; /**< TextUI for introText */ ABaseUI * timeLeftImg; /**< ImageUI for timeLeftImg */ ABaseUI * timeLeftImgActive; /**< ImageUI for timeLeftImgActive */ ABaseUI * timeLeftText; /**< TextUI for timeLeftText */ ABaseUI * scoreImg; /**< ImageUI for scoreImg */ ABaseUI * scoreImgActive; /**< ImageUI for scoreImgActive */ ABaseUI * scoreText; /**< TextUI for scoreText */ ABaseUI * lifeImg; /**< ImageUI for lifeImg */ ABaseUI * lifeImgActive; /**< ImageUI for lifeImgActive */ ABaseUI * lifeText; /**< TextUI for lifeText */ ABaseUI * levelNameText; /**< TextUI for levelNameText */ ABaseUI * enemiesCounterText; /**< TextUI for enemiesCounterText */ ABaseUI * speedImg; /**< ImageUI for speedImg */ ABaseUI * speedImgActive; /**< ImageUI for speedImgActive */ ABaseUI * speedText; /**< TextUI for speedText */ ABaseUI * bonusBombImg; /**< ImageUI for bonusBombImg */ ABaseUI * bonusBombImgActive; /**< ImageUI for bonusBombImgActive */ ABaseUI * bonusBombText; /**< TextUI for bonusBombText */ ABaseUI * bonusFlameImg; /**< ImageUI for bonusFlameImg */ ABaseUI * bonusFlameImgActive; /**< ImageUI for bonusFlameImgActive */ ABaseUI * bonusFlameText; /**< TextUI for bonusFlameText */ ABaseUI * bonusFlampassImg; /**< ImageUI for bonusFlampassImg */ ABaseUI * bonusFlampassImgActive; /**< ImageUI for bonusFlampassImgActive */ ABaseUI * bonusWallpassImg; /**< ImageUI for bonusWallpassImg */ ABaseUI * bonusWallpassImgActive; /**< ImageUI for bonusWallpassImgActive */ ABaseUI * bonusDetonatorImg; /**< ImageUI for bonusDetonatorImg */ ABaseUI * bonusDetonatorImgActive; /**< ImageUI for bonusDetonatorImgActive */ ABaseUI * bonusBombpassImg; /**< ImageUI for bonusBombpassImg */ ABaseUI * bonusBombpassImgActive; /**< ImageUI for bonusBombpassImgActive */ ABaseUI * bonusShieldImg; /**< ImageUI for bonusShieldImg */ ABaseUI * bonusShieldImgActive; /**< ImageUI for bonusShieldImgActive */ ABaseUI * bonusShieldText; /**< TextUI for bonusShieldText */ }; AllUI allUI; /**< All UI elements */ bool _loadHelp; /**< true if you want to load help menu */ void _initGameInfos(); void _loadGameInfos(); void _updateGameInfos(); bool _initBonus(); std::vector<CamPoint> _getIntroAnim() const; std::vector<CamPoint> _getGameOverAnim() const; std::vector<CamPoint> _getVictoryAnim() const; public: // Members static std::map<std::string, Entity> entitiesCall; /**< All entity type & functions */ std::vector< std::vector< bool > > floor; /**< True if there is a floor here */ std::vector< std::vector< std::vector<AEntity *> > > board; /**< The base board with all static elements */ std::vector< std::vector< std::vector<AEntity *> > > boardFly; /**< The fly board with all static flying elements */ Player *player; /**< The player */ std::vector<AEnemy *> enemies; /**< All enemies */ /** * @brief Bonus Information about spawn (number of bonus & chance to spawn) */ struct BonusValues { int64_t chance; /**< Chance to have a bonus */ int64_t nb; /**< Number of bonus on the level */ }; std::unordered_map<std::string, BonusValues> bonus; /**< All bonus information about spawn */ std::vector<Spawner *> spawners; /**< All spawners */ int flags; /**< Number of flags on the level */ glm::uvec2 size; /**< Level size */ int32_t level; /**< The current level ID (-1 for no level) */ GameState::Enum state; /**< Actual game state (PLAY, PAUSE, GAME_OVER, ...) */ uint32_t levelEnemies; /**< Number of enemies in the level */ uint32_t levelCrispies; /**< Number of crispies wall in the level */ float levelTime; /**< Time to do the level */ float time; /**< Time remaining to do the level */ Score score; /**< Score object */ int64_t enemiesToKill; /**< Enemy to kill to enable end element & finish the level */ int64_t enemiesKilled; /**< Number of enemies killed */ std::string musicLevel; /**< The level music */ /** * @brief Stats about number of entites, bombs, ... */ struct EntitiesCount { int enemy; /**< Number of enemy on the game */ int staticElements; /**< Number of staticElements on the game */ int players; /**< Number of players on the game */ int total; /**< Number of total on the game */ }; EntitiesCount entitiesCount; /**< Stats about number of entites, bombs, ... */ // Constructors SceneGame(Gui * gui, float const &dtTime); virtual ~SceneGame(); SceneGame(SceneGame const &src); // Operators SceneGame &operator=(SceneGame const &rhs); friend std::ostream& operator<<(std::ostream& os, const SceneGame& myClass); // Methods std::string print() const; bool clearFromBoard(AEntity *entity, glm::vec2 pos); bool positionInGame(glm::vec3 pos, glm::vec3 sz = glm::vec3(1, 1, 1)); bool updateBlurMaskTex(std::vector<uint8_t> const &aMaskData); void blurFilterBefore(); void blurFilterAfter(); // SceneGame methods virtual bool init(); virtual bool update(); virtual bool postUpdate(); virtual void load(); virtual void unload(); virtual bool draw(); bool updateForMenu(); bool drawGame(); bool drawForMenu(); bool drawVictory(); bool drawGameOver(); bool drawEndGame(); bool loadLevel(int32_t levelId); bool insertEntity(std::string const & name, glm::ivec2 pos, bool isFly = false, uint64_t wallGenPercent = 0); // getter uint32_t getNbLevel() const; std::string getLevelName(int32_t levelId) const; std::string getLevelImg(int32_t levelId) const; SettingsJson &getSettingsLevel() const; static std::vector<std::string> getAllEntityNames(); // Exceptions /** * @brief SceneGame exception */ class SceneGameException : public std::runtime_error { public: SceneGameException(); /** * @brief Construct a new Scene Game Exception object * * @param whatArg Error message */ explicit SceneGameException(const char* whatArg); }; }; #endif // SCENEGAME_HPP_
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout 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 SPROUT_FUNCTIONAL_POLYMORPHIC_BIT_XOR_HPP #define SPROUT_FUNCTIONAL_POLYMORPHIC_BIT_XOR_HPP #include <sprout/config.hpp> #include <sprout/functional/bit_xor.hpp> namespace sprout { // // bit_xor_t // bit_xor_ // typedef sprout::bit_xor<> bit_xor_t; namespace { SPROUT_STATIC_CONSTEXPR sprout::bit_xor_t bit_xor_ = {}; } // anonymous-namespace } // namespace sprout #endif // #ifndef SPROUT_FUNCTIONAL_POLYMORPHIC_BIT_XOR_HPP
// Copyright 2014 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/assembler-inl.h" #include "src/callable.h" #include "src/compiler/code-generator-impl.h" #include "src/compiler/code-generator.h" #include "src/compiler/gap-resolver.h" #include "src/compiler/node-matchers.h" #include "src/compiler/osr.h" #include "src/heap/heap-inl.h" #include "src/mips/macro-assembler-mips.h" #include "src/optimized-compilation-info.h" namespace v8 { namespace internal { namespace compiler { #define __ tasm()-> // TODO(plind): consider renaming these macros. #define TRACE_MSG(msg) \ PrintF("code_gen: \'%s\' in function %s at line %d\n", msg, __FUNCTION__, \ __LINE__) #define TRACE_UNIMPL() \ PrintF("UNIMPLEMENTED code_generator_mips: %s at line %d\n", __FUNCTION__, \ __LINE__) // Adds Mips-specific methods to convert InstructionOperands. class MipsOperandConverter final : public InstructionOperandConverter { public: MipsOperandConverter(CodeGenerator* gen, Instruction* instr) : InstructionOperandConverter(gen, instr) {} FloatRegister OutputSingleRegister(size_t index = 0) { return ToSingleRegister(instr_->OutputAt(index)); } FloatRegister InputSingleRegister(size_t index) { return ToSingleRegister(instr_->InputAt(index)); } FloatRegister ToSingleRegister(InstructionOperand* op) { // Single (Float) and Double register namespace is same on MIPS, // both are typedefs of FPURegister. return ToDoubleRegister(op); } Register InputOrZeroRegister(size_t index) { if (instr_->InputAt(index)->IsImmediate()) { DCHECK_EQ(0, InputInt32(index)); return zero_reg; } return InputRegister(index); } DoubleRegister InputOrZeroDoubleRegister(size_t index) { if (instr_->InputAt(index)->IsImmediate()) return kDoubleRegZero; return InputDoubleRegister(index); } DoubleRegister InputOrZeroSingleRegister(size_t index) { if (instr_->InputAt(index)->IsImmediate()) return kDoubleRegZero; return InputSingleRegister(index); } Operand InputImmediate(size_t index) { Constant constant = ToConstant(instr_->InputAt(index)); switch (constant.type()) { case Constant::kInt32: return Operand(constant.ToInt32()); case Constant::kFloat32: return Operand::EmbeddedNumber(constant.ToFloat32()); case Constant::kFloat64: return Operand::EmbeddedNumber(constant.ToFloat64().value()); case Constant::kInt64: case Constant::kExternalReference: case Constant::kHeapObject: // TODO(plind): Maybe we should handle ExtRef & HeapObj here? // maybe not done on arm due to const pool ?? break; case Constant::kDelayedStringConstant: return Operand::EmbeddedStringConstant( constant.ToDelayedStringConstant()); case Constant::kRpoNumber: UNREACHABLE(); // TODO(titzer): RPO immediates on mips? break; } UNREACHABLE(); } Operand InputOperand(size_t index) { InstructionOperand* op = instr_->InputAt(index); if (op->IsRegister()) { return Operand(ToRegister(op)); } return InputImmediate(index); } MemOperand MemoryOperand(size_t* first_index) { const size_t index = *first_index; switch (AddressingModeField::decode(instr_->opcode())) { case kMode_None: break; case kMode_MRI: *first_index += 2; return MemOperand(InputRegister(index + 0), InputInt32(index + 1)); case kMode_MRR: // TODO(plind): r6 address mode, to be implemented ... UNREACHABLE(); } UNREACHABLE(); } MemOperand MemoryOperand(size_t index = 0) { return MemoryOperand(&index); } MemOperand ToMemOperand(InstructionOperand* op) const { DCHECK_NOT_NULL(op); DCHECK(op->IsStackSlot() || op->IsFPStackSlot()); return SlotToMemOperand(AllocatedOperand::cast(op)->index()); } MemOperand SlotToMemOperand(int slot) const { FrameOffset offset = frame_access_state()->GetFrameOffset(slot); return MemOperand(offset.from_stack_pointer() ? sp : fp, offset.offset()); } }; static inline bool HasRegisterInput(Instruction* instr, size_t index) { return instr->InputAt(index)->IsRegister(); } namespace { class OutOfLineRecordWrite final : public OutOfLineCode { public: OutOfLineRecordWrite(CodeGenerator* gen, Register object, Register index, Register value, Register scratch0, Register scratch1, RecordWriteMode mode) : OutOfLineCode(gen), object_(object), index_(index), value_(value), scratch0_(scratch0), scratch1_(scratch1), mode_(mode), must_save_lr_(!gen->frame_access_state()->has_frame()), zone_(gen->zone()) {} void SaveRegisters(RegList registers) { DCHECK_LT(0, NumRegs(registers)); RegList regs = 0; for (int i = 0; i < Register::kNumRegisters; ++i) { if ((registers >> i) & 1u) { regs |= Register::from_code(i).bit(); } } __ MultiPush(regs | ra.bit()); } void RestoreRegisters(RegList registers) { DCHECK_LT(0, NumRegs(registers)); RegList regs = 0; for (int i = 0; i < Register::kNumRegisters; ++i) { if ((registers >> i) & 1u) { regs |= Register::from_code(i).bit(); } } __ MultiPop(regs | ra.bit()); } void Generate() final { if (mode_ > RecordWriteMode::kValueIsPointer) { __ JumpIfSmi(value_, exit()); } __ CheckPageFlag(value_, scratch0_, MemoryChunk::kPointersToHereAreInterestingMask, eq, exit()); __ Addu(scratch1_, object_, index_); RememberedSetAction const remembered_set_action = mode_ > RecordWriteMode::kValueIsMap ? EMIT_REMEMBERED_SET : OMIT_REMEMBERED_SET; SaveFPRegsMode const save_fp_mode = frame()->DidAllocateDoubleRegisters() ? kSaveFPRegs : kDontSaveFPRegs; if (must_save_lr_) { // We need to save and restore ra if the frame was elided. __ Push(ra); } __ CallRecordWriteStub(object_, scratch1_, remembered_set_action, save_fp_mode); if (must_save_lr_) { __ Pop(ra); } } private: Register const object_; Register const index_; Register const value_; Register const scratch0_; Register const scratch1_; RecordWriteMode const mode_; bool must_save_lr_; Zone* zone_; }; #define CREATE_OOL_CLASS(ool_name, tasm_ool_name, T) \ class ool_name final : public OutOfLineCode { \ public: \ ool_name(CodeGenerator* gen, T dst, T src1, T src2) \ : OutOfLineCode(gen), dst_(dst), src1_(src1), src2_(src2) {} \ \ void Generate() final { __ tasm_ool_name(dst_, src1_, src2_); } \ \ private: \ T const dst_; \ T const src1_; \ T const src2_; \ } CREATE_OOL_CLASS(OutOfLineFloat32Max, Float32MaxOutOfLine, FPURegister); CREATE_OOL_CLASS(OutOfLineFloat32Min, Float32MinOutOfLine, FPURegister); CREATE_OOL_CLASS(OutOfLineFloat64Max, Float64MaxOutOfLine, DoubleRegister); CREATE_OOL_CLASS(OutOfLineFloat64Min, Float64MinOutOfLine, DoubleRegister); #undef CREATE_OOL_CLASS Condition FlagsConditionToConditionCmp(FlagsCondition condition) { switch (condition) { case kEqual: return eq; case kNotEqual: return ne; case kSignedLessThan: return lt; case kSignedGreaterThanOrEqual: return ge; case kSignedLessThanOrEqual: return le; case kSignedGreaterThan: return gt; case kUnsignedLessThan: return lo; case kUnsignedGreaterThanOrEqual: return hs; case kUnsignedLessThanOrEqual: return ls; case kUnsignedGreaterThan: return hi; case kUnorderedEqual: case kUnorderedNotEqual: break; default: break; } UNREACHABLE(); } Condition FlagsConditionToConditionTst(FlagsCondition condition) { switch (condition) { case kNotEqual: return ne; case kEqual: return eq; default: break; } UNREACHABLE(); } FPUCondition FlagsConditionToConditionCmpFPU(bool& predicate, FlagsCondition condition) { switch (condition) { case kEqual: predicate = true; return EQ; case kNotEqual: predicate = false; return EQ; case kUnsignedLessThan: predicate = true; return OLT; case kUnsignedGreaterThanOrEqual: predicate = false; return OLT; case kUnsignedLessThanOrEqual: predicate = true; return OLE; case kUnsignedGreaterThan: predicate = false; return OLE; case kUnorderedEqual: case kUnorderedNotEqual: predicate = true; break; default: predicate = true; break; } UNREACHABLE(); } #define UNSUPPORTED_COND(opcode, condition) \ StdoutStream{} << "Unsupported " << #opcode << " condition: \"" << condition \ << "\""; \ UNIMPLEMENTED(); void EmitWordLoadPoisoningIfNeeded(CodeGenerator* codegen, InstructionCode opcode, Instruction* instr, MipsOperandConverter& i) { const MemoryAccessMode access_mode = static_cast<MemoryAccessMode>(MiscField::decode(opcode)); if (access_mode == kMemoryAccessPoisoned) { Register value = i.OutputRegister(); codegen->tasm()->And(value, value, kSpeculationPoisonRegister); } } } // namespace #define ASSEMBLE_ATOMIC_LOAD_INTEGER(asm_instr) \ do { \ __ asm_instr(i.OutputRegister(), i.MemoryOperand()); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_STORE_INTEGER(asm_instr) \ do { \ __ sync(); \ __ asm_instr(i.InputOrZeroRegister(2), i.MemoryOperand()); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_BINOP(bin_instr) \ do { \ Label binop; \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ sync(); \ __ bind(&binop); \ __ Ll(i.OutputRegister(0), MemOperand(i.TempRegister(0), 0)); \ __ bin_instr(i.TempRegister(1), i.OutputRegister(0), \ Operand(i.InputRegister(2))); \ __ Sc(i.TempRegister(1), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&binop, eq, i.TempRegister(1), Operand(zero_reg)); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC64_LOGIC_BINOP(bin_instr) \ do { \ if (IsMipsArchVariant(kMips32r6)) { \ Label binop; \ __ sync(); \ __ bind(&binop); \ __ llwp(i.TempRegister(0), i.TempRegister(1), i.InputRegister(2)); \ __ bin_instr(i.TempRegister(0), i.TempRegister(1), i.TempRegister(0), \ i.TempRegister(1), i.InputRegister(0), i.InputRegister(1)); \ __ scwp(i.TempRegister(0), i.TempRegister(1), i.InputRegister(2)); \ __ BranchShort(&binop, eq, i.TempRegister(1), Operand(zero_reg)); \ __ sync(); \ } else { \ UNREACHABLE(); \ } \ } while (0) #define ASSEMBLE_ATOMIC64_ARITH_BINOP(bin_instr) \ do { \ if (IsMipsArchVariant(kMips32r6)) { \ Label binop; \ __ sync(); \ __ bind(&binop); \ __ llwp(i.TempRegister(0), i.TempRegister(1), i.InputRegister(2)); \ __ bin_instr(i.TempRegister(0), i.TempRegister(1), i.TempRegister(0), \ i.TempRegister(1), i.InputRegister(0), i.InputRegister(1), \ i.TempRegister(2), i.TempRegister(3)); \ __ scwp(i.TempRegister(0), i.TempRegister(1), i.InputRegister(2)); \ __ BranchShort(&binop, eq, i.TempRegister(1), Operand(zero_reg)); \ __ sync(); \ } else { \ UNREACHABLE(); \ } \ } while (0) #define ASSEMBLE_ATOMIC_BINOP_EXT(sign_extend, size, bin_instr) \ do { \ Label binop; \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ andi(i.TempRegister(3), i.TempRegister(0), 0x3); \ __ Subu(i.TempRegister(0), i.TempRegister(0), Operand(i.TempRegister(3))); \ __ sll(i.TempRegister(3), i.TempRegister(3), 3); \ __ sync(); \ __ bind(&binop); \ __ Ll(i.TempRegister(1), MemOperand(i.TempRegister(0), 0)); \ __ ExtractBits(i.OutputRegister(0), i.TempRegister(1), i.TempRegister(3), \ size, sign_extend); \ __ bin_instr(i.TempRegister(2), i.OutputRegister(0), \ Operand(i.InputRegister(2))); \ __ InsertBits(i.TempRegister(1), i.TempRegister(2), i.TempRegister(3), \ size); \ __ Sc(i.TempRegister(1), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&binop, eq, i.TempRegister(1), Operand(zero_reg)); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_EXCHANGE_INTEGER() \ do { \ Label exchange; \ __ sync(); \ __ bind(&exchange); \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ Ll(i.OutputRegister(0), MemOperand(i.TempRegister(0), 0)); \ __ mov(i.TempRegister(1), i.InputRegister(2)); \ __ Sc(i.TempRegister(1), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&exchange, eq, i.TempRegister(1), Operand(zero_reg)); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_EXCHANGE_INTEGER_EXT(sign_extend, size) \ do { \ Label exchange; \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ andi(i.TempRegister(1), i.TempRegister(0), 0x3); \ __ Subu(i.TempRegister(0), i.TempRegister(0), Operand(i.TempRegister(1))); \ __ sll(i.TempRegister(1), i.TempRegister(1), 3); \ __ sync(); \ __ bind(&exchange); \ __ Ll(i.TempRegister(2), MemOperand(i.TempRegister(0), 0)); \ __ ExtractBits(i.OutputRegister(0), i.TempRegister(2), i.TempRegister(1), \ size, sign_extend); \ __ InsertBits(i.TempRegister(2), i.InputRegister(2), i.TempRegister(1), \ size); \ __ Sc(i.TempRegister(2), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&exchange, eq, i.TempRegister(2), Operand(zero_reg)); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER() \ do { \ Label compareExchange; \ Label exit; \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ sync(); \ __ bind(&compareExchange); \ __ Ll(i.OutputRegister(0), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&exit, ne, i.InputRegister(2), \ Operand(i.OutputRegister(0))); \ __ mov(i.TempRegister(2), i.InputRegister(3)); \ __ Sc(i.TempRegister(2), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&compareExchange, eq, i.TempRegister(2), \ Operand(zero_reg)); \ __ bind(&exit); \ __ sync(); \ } while (0) #define ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER_EXT(sign_extend, size) \ do { \ Label compareExchange; \ Label exit; \ __ Addu(i.TempRegister(0), i.InputRegister(0), i.InputRegister(1)); \ __ andi(i.TempRegister(1), i.TempRegister(0), 0x3); \ __ Subu(i.TempRegister(0), i.TempRegister(0), Operand(i.TempRegister(1))); \ __ sll(i.TempRegister(1), i.TempRegister(1), 3); \ __ sync(); \ __ bind(&compareExchange); \ __ Ll(i.TempRegister(2), MemOperand(i.TempRegister(0), 0)); \ __ ExtractBits(i.OutputRegister(0), i.TempRegister(2), i.TempRegister(1), \ size, sign_extend); \ __ BranchShort(&exit, ne, i.InputRegister(2), \ Operand(i.OutputRegister(0))); \ __ InsertBits(i.TempRegister(2), i.InputRegister(3), i.TempRegister(1), \ size); \ __ Sc(i.TempRegister(2), MemOperand(i.TempRegister(0), 0)); \ __ BranchShort(&compareExchange, eq, i.TempRegister(2), \ Operand(zero_reg)); \ __ bind(&exit); \ __ sync(); \ } while (0) #define ASSEMBLE_IEEE754_BINOP(name) \ do { \ FrameScope scope(tasm(), StackFrame::MANUAL); \ __ PrepareCallCFunction(0, 2, kScratchReg); \ __ MovToFloatParameters(i.InputDoubleRegister(0), \ i.InputDoubleRegister(1)); \ __ CallCFunction(ExternalReference::ieee754_##name##_function(), 0, 2); \ /* Move the result in the double result register. */ \ __ MovFromFloatResult(i.OutputDoubleRegister()); \ } while (0) #define ASSEMBLE_IEEE754_UNOP(name) \ do { \ FrameScope scope(tasm(), StackFrame::MANUAL); \ __ PrepareCallCFunction(0, 1, kScratchReg); \ __ MovToFloatParameter(i.InputDoubleRegister(0)); \ __ CallCFunction(ExternalReference::ieee754_##name##_function(), 0, 1); \ /* Move the result in the double result register. */ \ __ MovFromFloatResult(i.OutputDoubleRegister()); \ } while (0) void CodeGenerator::AssembleDeconstructFrame() { __ mov(sp, fp); __ Pop(ra, fp); } void CodeGenerator::AssemblePrepareTailCall() { if (frame_access_state()->has_frame()) { __ lw(ra, MemOperand(fp, StandardFrameConstants::kCallerPCOffset)); __ lw(fp, MemOperand(fp, StandardFrameConstants::kCallerFPOffset)); } frame_access_state()->SetFrameAccessToSP(); } void CodeGenerator::AssemblePopArgumentsAdaptorFrame(Register args_reg, Register scratch1, Register scratch2, Register scratch3) { DCHECK(!AreAliased(args_reg, scratch1, scratch2, scratch3)); Label done; // Check if current frame is an arguments adaptor frame. __ lw(scratch1, MemOperand(fp, StandardFrameConstants::kContextOffset)); __ Branch(&done, ne, scratch1, Operand(StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR))); // Load arguments count from current arguments adaptor frame (note, it // does not include receiver). Register caller_args_count_reg = scratch1; __ lw(caller_args_count_reg, MemOperand(fp, ArgumentsAdaptorFrameConstants::kLengthOffset)); __ SmiUntag(caller_args_count_reg); ParameterCount callee_args_count(args_reg); __ PrepareForTailCall(callee_args_count, caller_args_count_reg, scratch2, scratch3); __ bind(&done); } namespace { void AdjustStackPointerForTailCall(TurboAssembler* tasm, FrameAccessState* state, int new_slot_above_sp, bool allow_shrinkage = true) { int current_sp_offset = state->GetSPToFPSlotCount() + StandardFrameConstants::kFixedSlotCountAboveFp; int stack_slot_delta = new_slot_above_sp - current_sp_offset; if (stack_slot_delta > 0) { tasm->Subu(sp, sp, stack_slot_delta * kPointerSize); state->IncreaseSPDelta(stack_slot_delta); } else if (allow_shrinkage && stack_slot_delta < 0) { tasm->Addu(sp, sp, -stack_slot_delta * kPointerSize); state->IncreaseSPDelta(stack_slot_delta); } } } // namespace void CodeGenerator::AssembleTailCallBeforeGap(Instruction* instr, int first_unused_stack_slot) { AdjustStackPointerForTailCall(tasm(), frame_access_state(), first_unused_stack_slot, false); } void CodeGenerator::AssembleTailCallAfterGap(Instruction* instr, int first_unused_stack_slot) { AdjustStackPointerForTailCall(tasm(), frame_access_state(), first_unused_stack_slot); } // Check that {kJavaScriptCallCodeStartRegister} is correct. void CodeGenerator::AssembleCodeStartRegisterCheck() { __ ComputeCodeStartAddress(kScratchReg); __ Assert(eq, AbortReason::kWrongFunctionCodeStart, kJavaScriptCallCodeStartRegister, Operand(kScratchReg)); } // Check if the code object is marked for deoptimization. If it is, then it // jumps to the CompileLazyDeoptimizedCode builtin. In order to do this we need // to: // 1. read from memory the word that contains that bit, which can be found in // the flags in the referenced {CodeDataContainer} object; // 2. test kMarkedForDeoptimizationBit in those flags; and // 3. if it is not zero then it jumps to the builtin. void CodeGenerator::BailoutIfDeoptimized() { int offset = Code::kCodeDataContainerOffset - Code::kHeaderSize; __ lw(kScratchReg, MemOperand(kJavaScriptCallCodeStartRegister, offset)); __ lw(kScratchReg, FieldMemOperand(kScratchReg, CodeDataContainer::kKindSpecificFlagsOffset)); __ And(kScratchReg, kScratchReg, Operand(1 << Code::kMarkedForDeoptimizationBit)); // Ensure we're not serializing (otherwise we'd need to use an indirection to // access the builtin below). DCHECK(!isolate()->ShouldLoadConstantsFromRootList()); Handle<Code> code = isolate()->builtins()->builtin_handle( Builtins::kCompileLazyDeoptimizedCode); __ Jump(code, RelocInfo::CODE_TARGET, ne, kScratchReg, Operand(zero_reg)); } void CodeGenerator::GenerateSpeculationPoisonFromCodeStartRegister() { // Calculate a mask which has all bits set in the normal case, but has all // bits cleared if we are speculatively executing the wrong PC. // difference = (current - expected) | (expected - current) // poison = ~(difference >> (kBitsPerPointer - 1)) __ ComputeCodeStartAddress(kScratchReg); __ Move(kSpeculationPoisonRegister, kScratchReg); __ subu(kSpeculationPoisonRegister, kSpeculationPoisonRegister, kJavaScriptCallCodeStartRegister); __ subu(kJavaScriptCallCodeStartRegister, kJavaScriptCallCodeStartRegister, kScratchReg); __ or_(kSpeculationPoisonRegister, kSpeculationPoisonRegister, kJavaScriptCallCodeStartRegister); __ sra(kSpeculationPoisonRegister, kSpeculationPoisonRegister, kBitsPerPointer - 1); __ nor(kSpeculationPoisonRegister, kSpeculationPoisonRegister, kSpeculationPoisonRegister); } void CodeGenerator::AssembleRegisterArgumentPoisoning() { __ And(kJSFunctionRegister, kJSFunctionRegister, kSpeculationPoisonRegister); __ And(kContextRegister, kContextRegister, kSpeculationPoisonRegister); __ And(sp, sp, kSpeculationPoisonRegister); } // Assembles an instruction after register allocation, producing machine code. CodeGenerator::CodeGenResult CodeGenerator::AssembleArchInstruction( Instruction* instr) { MipsOperandConverter i(this, instr); InstructionCode opcode = instr->opcode(); ArchOpcode arch_opcode = ArchOpcodeField::decode(opcode); switch (arch_opcode) { case kArchCallCodeObject: { if (instr->InputAt(0)->IsImmediate()) { __ Call(i.InputCode(0), RelocInfo::CODE_TARGET); } else { Register reg = i.InputRegister(0); DCHECK_IMPLIES( HasCallDescriptorFlag(instr, CallDescriptor::kFixedTargetRegister), reg == kJavaScriptCallCodeStartRegister); __ Call(reg, reg, Code::kHeaderSize - kHeapObjectTag); } RecordCallPosition(instr); frame_access_state()->ClearSPDelta(); break; } case kArchCallWasmFunction: { if (instr->InputAt(0)->IsImmediate()) { Constant constant = i.ToConstant(instr->InputAt(0)); Address wasm_code = static_cast<Address>(constant.ToInt32()); __ Call(wasm_code, constant.rmode()); } else { __ Call(i.InputRegister(0)); } RecordCallPosition(instr); frame_access_state()->ClearSPDelta(); break; } case kArchTailCallCodeObjectFromJSFunction: case kArchTailCallCodeObject: { if (arch_opcode == kArchTailCallCodeObjectFromJSFunction) { AssemblePopArgumentsAdaptorFrame(kJavaScriptCallArgCountRegister, i.TempRegister(0), i.TempRegister(1), i.TempRegister(2)); } if (instr->InputAt(0)->IsImmediate()) { __ Jump(i.InputCode(0), RelocInfo::CODE_TARGET); } else { Register reg = i.InputRegister(0); DCHECK_IMPLIES( HasCallDescriptorFlag(instr, CallDescriptor::kFixedTargetRegister), reg == kJavaScriptCallCodeStartRegister); __ Addu(reg, reg, Code::kHeaderSize - kHeapObjectTag); __ Jump(reg); } frame_access_state()->ClearSPDelta(); frame_access_state()->SetFrameAccessToDefault(); break; } case kArchTailCallWasm: { if (instr->InputAt(0)->IsImmediate()) { Constant constant = i.ToConstant(instr->InputAt(0)); Address wasm_code = static_cast<Address>(constant.ToInt32()); __ Jump(wasm_code, constant.rmode()); } else { __ Jump(i.InputRegister(0)); } frame_access_state()->ClearSPDelta(); frame_access_state()->SetFrameAccessToDefault(); break; } case kArchTailCallAddress: { CHECK(!instr->InputAt(0)->IsImmediate()); Register reg = i.InputRegister(0); DCHECK_IMPLIES( HasCallDescriptorFlag(instr, CallDescriptor::kFixedTargetRegister), reg == kJavaScriptCallCodeStartRegister); __ Jump(reg); frame_access_state()->ClearSPDelta(); frame_access_state()->SetFrameAccessToDefault(); break; } case kArchCallJSFunction: { Register func = i.InputRegister(0); if (FLAG_debug_code) { // Check the function's context matches the context argument. __ lw(kScratchReg, FieldMemOperand(func, JSFunction::kContextOffset)); __ Assert(eq, AbortReason::kWrongFunctionContext, cp, Operand(kScratchReg)); } static_assert(kJavaScriptCallCodeStartRegister == a2, "ABI mismatch"); __ lw(a2, FieldMemOperand(func, JSFunction::kCodeOffset)); __ Addu(a2, a2, Code::kHeaderSize - kHeapObjectTag); __ Call(a2); RecordCallPosition(instr); frame_access_state()->ClearSPDelta(); frame_access_state()->SetFrameAccessToDefault(); break; } case kArchPrepareCallCFunction: { int const num_parameters = MiscField::decode(instr->opcode()); __ PrepareCallCFunction(num_parameters, kScratchReg); // Frame alignment requires using FP-relative frame addressing. frame_access_state()->SetFrameAccessToFP(); break; } case kArchSaveCallerRegisters: { fp_mode_ = static_cast<SaveFPRegsMode>(MiscField::decode(instr->opcode())); DCHECK(fp_mode_ == kDontSaveFPRegs || fp_mode_ == kSaveFPRegs); // kReturnRegister0 should have been saved before entering the stub. int bytes = __ PushCallerSaved(fp_mode_, kReturnRegister0); DCHECK_EQ(0, bytes % kPointerSize); DCHECK_EQ(0, frame_access_state()->sp_delta()); frame_access_state()->IncreaseSPDelta(bytes / kPointerSize); DCHECK(!caller_registers_saved_); caller_registers_saved_ = true; break; } case kArchRestoreCallerRegisters: { DCHECK(fp_mode_ == static_cast<SaveFPRegsMode>(MiscField::decode(instr->opcode()))); DCHECK(fp_mode_ == kDontSaveFPRegs || fp_mode_ == kSaveFPRegs); // Don't overwrite the returned value. int bytes = __ PopCallerSaved(fp_mode_, kReturnRegister0); frame_access_state()->IncreaseSPDelta(-(bytes / kPointerSize)); DCHECK_EQ(0, frame_access_state()->sp_delta()); DCHECK(caller_registers_saved_); caller_registers_saved_ = false; break; } case kArchPrepareTailCall: AssemblePrepareTailCall(); break; case kArchCallCFunction: { int const num_parameters = MiscField::decode(instr->opcode()); if (instr->InputAt(0)->IsImmediate()) { ExternalReference ref = i.InputExternalReference(0); __ CallCFunction(ref, num_parameters); } else { Register func = i.InputRegister(0); __ CallCFunction(func, num_parameters); } frame_access_state()->SetFrameAccessToDefault(); // Ideally, we should decrement SP delta to match the change of stack // pointer in CallCFunction. However, for certain architectures (e.g. // ARM), there may be more strict alignment requirement, causing old SP // to be saved on the stack. In those cases, we can not calculate the SP // delta statically. frame_access_state()->ClearSPDelta(); if (caller_registers_saved_) { // Need to re-sync SP delta introduced in kArchSaveCallerRegisters. // Here, we assume the sequence to be: // kArchSaveCallerRegisters; // kArchCallCFunction; // kArchRestoreCallerRegisters; int bytes = __ RequiredStackSizeForCallerSaved(fp_mode_, kReturnRegister0); frame_access_state()->IncreaseSPDelta(bytes / kPointerSize); } break; } case kArchJmp: AssembleArchJump(i.InputRpo(0)); break; case kArchBinarySearchSwitch: AssembleArchBinarySearchSwitch(instr); break; case kArchLookupSwitch: AssembleArchLookupSwitch(instr); break; case kArchTableSwitch: AssembleArchTableSwitch(instr); break; case kArchDebugAbort: DCHECK(i.InputRegister(0) == a0); if (!frame_access_state()->has_frame()) { // We don't actually want to generate a pile of code for this, so just // claim there is a stack frame, without generating one. FrameScope scope(tasm(), StackFrame::NONE); __ Call(isolate()->builtins()->builtin_handle(Builtins::kAbortJS), RelocInfo::CODE_TARGET); } else { __ Call(isolate()->builtins()->builtin_handle(Builtins::kAbortJS), RelocInfo::CODE_TARGET); } __ stop("kArchDebugAbort"); break; case kArchDebugBreak: __ stop("kArchDebugBreak"); break; case kArchComment: __ RecordComment(reinterpret_cast<const char*>(i.InputInt32(0))); break; case kArchNop: case kArchThrowTerminator: // don't emit code for nops. break; case kArchDeoptimize: { int deopt_state_id = BuildTranslation(instr, -1, 0, OutputFrameStateCombine::Ignore()); CodeGenResult result = AssembleDeoptimizerCall(deopt_state_id, current_source_position_); if (result != kSuccess) return result; break; } case kArchRet: AssembleReturn(instr->InputAt(0)); break; case kArchStackPointer: __ mov(i.OutputRegister(), sp); break; case kArchFramePointer: __ mov(i.OutputRegister(), fp); break; case kArchParentFramePointer: if (frame_access_state()->has_frame()) { __ lw(i.OutputRegister(), MemOperand(fp, 0)); } else { __ mov(i.OutputRegister(), fp); } break; case kArchTruncateDoubleToI: __ TruncateDoubleToI(isolate(), zone(), i.OutputRegister(), i.InputDoubleRegister(0), DetermineStubCallMode()); break; case kArchStoreWithWriteBarrier: { RecordWriteMode mode = static_cast<RecordWriteMode>(MiscField::decode(instr->opcode())); Register object = i.InputRegister(0); Register index = i.InputRegister(1); Register value = i.InputRegister(2); Register scratch0 = i.TempRegister(0); Register scratch1 = i.TempRegister(1); auto ool = new (zone()) OutOfLineRecordWrite(this, object, index, value, scratch0, scratch1, mode); __ Addu(kScratchReg, object, index); __ sw(value, MemOperand(kScratchReg)); __ CheckPageFlag(object, scratch0, MemoryChunk::kPointersFromHereAreInterestingMask, ne, ool->entry()); __ bind(ool->exit()); break; } case kArchStackSlot: { FrameOffset offset = frame_access_state()->GetFrameOffset(i.InputInt32(0)); Register base_reg = offset.from_stack_pointer() ? sp : fp; __ Addu(i.OutputRegister(), base_reg, Operand(offset.offset())); int alignment = i.InputInt32(1); DCHECK(alignment == 0 || alignment == 4 || alignment == 8 || alignment == 16); if (FLAG_debug_code && alignment > 0) { // Verify that the output_register is properly aligned __ And(kScratchReg, i.OutputRegister(), Operand(kPointerSize - 1)); __ Assert(eq, AbortReason::kAllocationIsNotDoubleAligned, kScratchReg, Operand(zero_reg)); } if (alignment == 2 * kPointerSize) { Label done; __ Addu(kScratchReg, base_reg, Operand(offset.offset())); __ And(kScratchReg, kScratchReg, Operand(alignment - 1)); __ BranchShort(&done, eq, kScratchReg, Operand(zero_reg)); __ Addu(i.OutputRegister(), i.OutputRegister(), kPointerSize); __ bind(&done); } else if (alignment > 2 * kPointerSize) { Label done; __ Addu(kScratchReg, base_reg, Operand(offset.offset())); __ And(kScratchReg, kScratchReg, Operand(alignment - 1)); __ BranchShort(&done, eq, kScratchReg, Operand(zero_reg)); __ li(kScratchReg2, alignment); __ Subu(kScratchReg2, kScratchReg2, Operand(kScratchReg)); __ Addu(i.OutputRegister(), i.OutputRegister(), kScratchReg2); __ bind(&done); } break; } case kArchWordPoisonOnSpeculation: __ And(i.OutputRegister(), i.InputRegister(0), kSpeculationPoisonRegister); break; case kIeee754Float64Acos: ASSEMBLE_IEEE754_UNOP(acos); break; case kIeee754Float64Acosh: ASSEMBLE_IEEE754_UNOP(acosh); break; case kIeee754Float64Asin: ASSEMBLE_IEEE754_UNOP(asin); break; case kIeee754Float64Asinh: ASSEMBLE_IEEE754_UNOP(asinh); break; case kIeee754Float64Atan: ASSEMBLE_IEEE754_UNOP(atan); break; case kIeee754Float64Atanh: ASSEMBLE_IEEE754_UNOP(atanh); break; case kIeee754Float64Atan2: ASSEMBLE_IEEE754_BINOP(atan2); break; case kIeee754Float64Cos: ASSEMBLE_IEEE754_UNOP(cos); break; case kIeee754Float64Cosh: ASSEMBLE_IEEE754_UNOP(cosh); break; case kIeee754Float64Cbrt: ASSEMBLE_IEEE754_UNOP(cbrt); break; case kIeee754Float64Exp: ASSEMBLE_IEEE754_UNOP(exp); break; case kIeee754Float64Expm1: ASSEMBLE_IEEE754_UNOP(expm1); break; case kIeee754Float64Log: ASSEMBLE_IEEE754_UNOP(log); break; case kIeee754Float64Log1p: ASSEMBLE_IEEE754_UNOP(log1p); break; case kIeee754Float64Log10: ASSEMBLE_IEEE754_UNOP(log10); break; case kIeee754Float64Log2: ASSEMBLE_IEEE754_UNOP(log2); break; case kIeee754Float64Pow: { __ Call(BUILTIN_CODE(isolate(), MathPowInternal), RelocInfo::CODE_TARGET); break; } case kIeee754Float64Sin: ASSEMBLE_IEEE754_UNOP(sin); break; case kIeee754Float64Sinh: ASSEMBLE_IEEE754_UNOP(sinh); break; case kIeee754Float64Tan: ASSEMBLE_IEEE754_UNOP(tan); break; case kIeee754Float64Tanh: ASSEMBLE_IEEE754_UNOP(tanh); break; case kMipsAdd: __ Addu(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsAddOvf: __ AddOverflow(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1), kScratchReg); break; case kMipsSub: __ Subu(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsSubOvf: __ SubOverflow(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1), kScratchReg); break; case kMipsMul: __ Mul(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsMulOvf: __ MulOverflow(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1), kScratchReg); break; case kMipsMulHigh: __ Mulh(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsMulHighU: __ Mulhu(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsDiv: __ Div(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); if (IsMipsArchVariant(kMips32r6)) { __ selnez(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1)); } else { __ Movz(i.OutputRegister(), i.InputRegister(1), i.InputRegister(1)); } break; case kMipsDivU: __ Divu(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); if (IsMipsArchVariant(kMips32r6)) { __ selnez(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1)); } else { __ Movz(i.OutputRegister(), i.InputRegister(1), i.InputRegister(1)); } break; case kMipsMod: __ Mod(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsModU: __ Modu(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsAnd: __ And(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsOr: __ Or(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsNor: if (instr->InputAt(1)->IsRegister()) { __ Nor(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); } else { DCHECK_EQ(0, i.InputOperand(1).immediate()); __ Nor(i.OutputRegister(), i.InputRegister(0), zero_reg); } break; case kMipsXor: __ Xor(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsClz: __ Clz(i.OutputRegister(), i.InputRegister(0)); break; case kMipsCtz: { Register src = i.InputRegister(0); Register dst = i.OutputRegister(); __ Ctz(dst, src); } break; case kMipsPopcnt: { Register src = i.InputRegister(0); Register dst = i.OutputRegister(); __ Popcnt(dst, src); } break; case kMipsShl: if (instr->InputAt(1)->IsRegister()) { __ sllv(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1)); } else { int32_t imm = i.InputOperand(1).immediate(); __ sll(i.OutputRegister(), i.InputRegister(0), imm); } break; case kMipsShr: if (instr->InputAt(1)->IsRegister()) { __ srlv(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1)); } else { int32_t imm = i.InputOperand(1).immediate(); __ srl(i.OutputRegister(), i.InputRegister(0), imm); } break; case kMipsSar: if (instr->InputAt(1)->IsRegister()) { __ srav(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1)); } else { int32_t imm = i.InputOperand(1).immediate(); __ sra(i.OutputRegister(), i.InputRegister(0), imm); } break; case kMipsShlPair: { Register second_output = instr->OutputCount() >= 2 ? i.OutputRegister(1) : i.TempRegister(0); if (instr->InputAt(2)->IsRegister()) { __ ShlPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), kScratchReg, kScratchReg2); } else { uint32_t imm = i.InputOperand(2).immediate(); __ ShlPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), imm, kScratchReg); } } break; case kMipsShrPair: { Register second_output = instr->OutputCount() >= 2 ? i.OutputRegister(1) : i.TempRegister(0); if (instr->InputAt(2)->IsRegister()) { __ ShrPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), kScratchReg, kScratchReg2); } else { uint32_t imm = i.InputOperand(2).immediate(); __ ShrPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), imm, kScratchReg); } } break; case kMipsSarPair: { Register second_output = instr->OutputCount() >= 2 ? i.OutputRegister(1) : i.TempRegister(0); if (instr->InputAt(2)->IsRegister()) { __ SarPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), kScratchReg, kScratchReg2); } else { uint32_t imm = i.InputOperand(2).immediate(); __ SarPair(i.OutputRegister(0), second_output, i.InputRegister(0), i.InputRegister(1), imm, kScratchReg); } } break; case kMipsExt: __ Ext(i.OutputRegister(), i.InputRegister(0), i.InputInt8(1), i.InputInt8(2)); break; case kMipsIns: if (instr->InputAt(1)->IsImmediate() && i.InputInt8(1) == 0) { __ Ins(i.OutputRegister(), zero_reg, i.InputInt8(1), i.InputInt8(2)); } else { __ Ins(i.OutputRegister(), i.InputRegister(0), i.InputInt8(1), i.InputInt8(2)); } break; case kMipsRor: __ Ror(i.OutputRegister(), i.InputRegister(0), i.InputOperand(1)); break; case kMipsTst: __ And(kScratchReg, i.InputRegister(0), i.InputOperand(1)); break; case kMipsCmp: // Pseudo-instruction used for cmp/branch. No opcode emitted here. break; case kMipsMov: // TODO(plind): Should we combine mov/li like this, or use separate instr? // - Also see x64 ASSEMBLE_BINOP & RegisterOrOperandType if (HasRegisterInput(instr, 0)) { __ mov(i.OutputRegister(), i.InputRegister(0)); } else { __ li(i.OutputRegister(), i.InputOperand(0)); } break; case kMipsLsa: DCHECK(instr->InputAt(2)->IsImmediate()); __ Lsa(i.OutputRegister(), i.InputRegister(0), i.InputRegister(1), i.InputInt8(2)); break; case kMipsCmpS: { FPURegister left = i.InputOrZeroSingleRegister(0); FPURegister right = i.InputOrZeroSingleRegister(1); bool predicate; FPUCondition cc = FlagsConditionToConditionCmpFPU(predicate, instr->flags_condition()); if ((left == kDoubleRegZero || right == kDoubleRegZero) && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ CompareF32(cc, left, right); } break; case kMipsAddS: // TODO(plind): add special case: combine mult & add. __ add_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsSubS: __ sub_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsMulS: // TODO(plind): add special case: right op is -1.0, see arm port. __ mul_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsDivS: __ div_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsModS: { // TODO(bmeurer): We should really get rid of this special instruction, // and generate a CallAddress instruction instead. FrameScope scope(tasm(), StackFrame::MANUAL); __ PrepareCallCFunction(0, 2, kScratchReg); __ MovToFloatParameters(i.InputDoubleRegister(0), i.InputDoubleRegister(1)); // TODO(balazs.kilvady): implement mod_two_floats_operation(isolate()) __ CallCFunction(ExternalReference::mod_two_doubles_operation(), 0, 2); // Move the result in the double result register. __ MovFromFloatResult(i.OutputSingleRegister()); break; } case kMipsAbsS: __ abs_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; case kMipsSqrtS: { __ sqrt_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsMaxS: __ max_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsMinS: __ min_s(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsCmpD: { FPURegister left = i.InputOrZeroDoubleRegister(0); FPURegister right = i.InputOrZeroDoubleRegister(1); bool predicate; FPUCondition cc = FlagsConditionToConditionCmpFPU(predicate, instr->flags_condition()); if ((left == kDoubleRegZero || right == kDoubleRegZero) && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ CompareF64(cc, left, right); } break; case kMipsAddPair: __ AddPair(i.OutputRegister(0), i.OutputRegister(1), i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), i.InputRegister(3), kScratchReg, kScratchReg2); break; case kMipsSubPair: __ SubPair(i.OutputRegister(0), i.OutputRegister(1), i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), i.InputRegister(3), kScratchReg, kScratchReg2); break; case kMipsMulPair: { __ MulPair(i.OutputRegister(0), i.OutputRegister(1), i.InputRegister(0), i.InputRegister(1), i.InputRegister(2), i.InputRegister(3), kScratchReg, kScratchReg2); } break; case kMipsAddD: // TODO(plind): add special case: combine mult & add. __ add_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsSubD: __ sub_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsMaddS: __ Madd_s(i.OutputFloatRegister(), i.InputFloatRegister(0), i.InputFloatRegister(1), i.InputFloatRegister(2), kScratchDoubleReg); break; case kMipsMaddD: __ Madd_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1), i.InputDoubleRegister(2), kScratchDoubleReg); break; case kMipsMsubS: __ Msub_s(i.OutputFloatRegister(), i.InputFloatRegister(0), i.InputFloatRegister(1), i.InputFloatRegister(2), kScratchDoubleReg); break; case kMipsMsubD: __ Msub_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1), i.InputDoubleRegister(2), kScratchDoubleReg); break; case kMipsMulD: // TODO(plind): add special case: right op is -1.0, see arm port. __ mul_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsDivD: __ div_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsModD: { // TODO(bmeurer): We should really get rid of this special instruction, // and generate a CallAddress instruction instead. FrameScope scope(tasm(), StackFrame::MANUAL); __ PrepareCallCFunction(0, 2, kScratchReg); __ MovToFloatParameters(i.InputDoubleRegister(0), i.InputDoubleRegister(1)); __ CallCFunction(ExternalReference::mod_two_doubles_operation(), 0, 2); // Move the result in the double result register. __ MovFromFloatResult(i.OutputDoubleRegister()); break; } case kMipsAbsD: __ abs_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; case kMipsNegS: __ Neg_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; case kMipsNegD: __ Neg_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; case kMipsSqrtD: { __ sqrt_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsMaxD: __ max_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsMinD: __ min_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0), i.InputDoubleRegister(1)); break; case kMipsFloat64RoundDown: { __ Floor_d_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsFloat32RoundDown: { __ Floor_s_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; } case kMipsFloat64RoundTruncate: { __ Trunc_d_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsFloat32RoundTruncate: { __ Trunc_s_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; } case kMipsFloat64RoundUp: { __ Ceil_d_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsFloat32RoundUp: { __ Ceil_s_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; } case kMipsFloat64RoundTiesEven: { __ Round_d_d(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; } case kMipsFloat32RoundTiesEven: { __ Round_s_s(i.OutputSingleRegister(), i.InputSingleRegister(0)); break; } case kMipsFloat32Max: { FPURegister dst = i.OutputSingleRegister(); FPURegister src1 = i.InputSingleRegister(0); FPURegister src2 = i.InputSingleRegister(1); auto ool = new (zone()) OutOfLineFloat32Max(this, dst, src1, src2); __ Float32Max(dst, src1, src2, ool->entry()); __ bind(ool->exit()); break; } case kMipsFloat64Max: { DoubleRegister dst = i.OutputDoubleRegister(); DoubleRegister src1 = i.InputDoubleRegister(0); DoubleRegister src2 = i.InputDoubleRegister(1); auto ool = new (zone()) OutOfLineFloat64Max(this, dst, src1, src2); __ Float64Max(dst, src1, src2, ool->entry()); __ bind(ool->exit()); break; } case kMipsFloat32Min: { FPURegister dst = i.OutputSingleRegister(); FPURegister src1 = i.InputSingleRegister(0); FPURegister src2 = i.InputSingleRegister(1); auto ool = new (zone()) OutOfLineFloat32Min(this, dst, src1, src2); __ Float32Min(dst, src1, src2, ool->entry()); __ bind(ool->exit()); break; } case kMipsFloat64Min: { DoubleRegister dst = i.OutputDoubleRegister(); DoubleRegister src1 = i.InputDoubleRegister(0); DoubleRegister src2 = i.InputDoubleRegister(1); auto ool = new (zone()) OutOfLineFloat64Min(this, dst, src1, src2); __ Float64Min(dst, src1, src2, ool->entry()); __ bind(ool->exit()); break; } case kMipsCvtSD: { __ cvt_s_d(i.OutputSingleRegister(), i.InputDoubleRegister(0)); break; } case kMipsCvtDS: { __ cvt_d_s(i.OutputDoubleRegister(), i.InputSingleRegister(0)); break; } case kMipsCvtDW: { FPURegister scratch = kScratchDoubleReg; __ mtc1(i.InputRegister(0), scratch); __ cvt_d_w(i.OutputDoubleRegister(), scratch); break; } case kMipsCvtSW: { FPURegister scratch = kScratchDoubleReg; __ mtc1(i.InputRegister(0), scratch); __ cvt_s_w(i.OutputDoubleRegister(), scratch); break; } case kMipsCvtSUw: { FPURegister scratch = kScratchDoubleReg; __ Cvt_d_uw(i.OutputDoubleRegister(), i.InputRegister(0), scratch); __ cvt_s_d(i.OutputDoubleRegister(), i.OutputDoubleRegister()); break; } case kMipsCvtDUw: { FPURegister scratch = kScratchDoubleReg; __ Cvt_d_uw(i.OutputDoubleRegister(), i.InputRegister(0), scratch); break; } case kMipsFloorWD: { FPURegister scratch = kScratchDoubleReg; __ Floor_w_d(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsCeilWD: { FPURegister scratch = kScratchDoubleReg; __ Ceil_w_d(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsRoundWD: { FPURegister scratch = kScratchDoubleReg; __ Round_w_d(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsTruncWD: { FPURegister scratch = kScratchDoubleReg; // Other arches use round to zero here, so we follow. __ Trunc_w_d(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsFloorWS: { FPURegister scratch = kScratchDoubleReg; __ floor_w_s(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsCeilWS: { FPURegister scratch = kScratchDoubleReg; __ ceil_w_s(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsRoundWS: { FPURegister scratch = kScratchDoubleReg; __ round_w_s(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); break; } case kMipsTruncWS: { FPURegister scratch = kScratchDoubleReg; __ trunc_w_s(scratch, i.InputDoubleRegister(0)); __ mfc1(i.OutputRegister(), scratch); // Avoid INT32_MAX as an overflow indicator and use INT32_MIN instead, // because INT32_MIN allows easier out-of-bounds detection. __ Addu(kScratchReg, i.OutputRegister(), 1); __ Slt(kScratchReg2, kScratchReg, i.OutputRegister()); __ Movn(i.OutputRegister(), kScratchReg, kScratchReg2); break; } case kMipsTruncUwD: { FPURegister scratch = kScratchDoubleReg; __ Trunc_uw_d(i.OutputRegister(), i.InputDoubleRegister(0), scratch); break; } case kMipsTruncUwS: { FPURegister scratch = kScratchDoubleReg; __ Trunc_uw_s(i.OutputRegister(), i.InputDoubleRegister(0), scratch); // Avoid UINT32_MAX as an overflow indicator and use 0 instead, // because 0 allows easier out-of-bounds detection. __ Addu(kScratchReg, i.OutputRegister(), 1); __ Movz(i.OutputRegister(), zero_reg, kScratchReg); break; } case kMipsFloat64ExtractLowWord32: __ FmoveLow(i.OutputRegister(), i.InputDoubleRegister(0)); break; case kMipsFloat64ExtractHighWord32: __ FmoveHigh(i.OutputRegister(), i.InputDoubleRegister(0)); break; case kMipsFloat64InsertLowWord32: __ FmoveLow(i.OutputDoubleRegister(), i.InputRegister(1)); break; case kMipsFloat64InsertHighWord32: __ FmoveHigh(i.OutputDoubleRegister(), i.InputRegister(1)); break; case kMipsFloat64SilenceNaN: __ FPUCanonicalizeNaN(i.OutputDoubleRegister(), i.InputDoubleRegister(0)); break; // ... more basic instructions ... case kMipsSeb: __ Seb(i.OutputRegister(), i.InputRegister(0)); break; case kMipsSeh: __ Seh(i.OutputRegister(), i.InputRegister(0)); break; case kMipsLbu: __ lbu(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsLb: __ lb(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsSb: __ sb(i.InputOrZeroRegister(2), i.MemoryOperand()); break; case kMipsLhu: __ lhu(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsUlhu: __ Ulhu(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsLh: __ lh(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsUlh: __ Ulh(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsSh: __ sh(i.InputOrZeroRegister(2), i.MemoryOperand()); break; case kMipsUsh: __ Ush(i.InputOrZeroRegister(2), i.MemoryOperand(), kScratchReg); break; case kMipsLw: __ lw(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsUlw: __ Ulw(i.OutputRegister(), i.MemoryOperand()); EmitWordLoadPoisoningIfNeeded(this, opcode, instr, i); break; case kMipsSw: __ sw(i.InputOrZeroRegister(2), i.MemoryOperand()); break; case kMipsUsw: __ Usw(i.InputOrZeroRegister(2), i.MemoryOperand()); break; case kMipsLwc1: { __ lwc1(i.OutputSingleRegister(), i.MemoryOperand()); break; } case kMipsUlwc1: { __ Ulwc1(i.OutputSingleRegister(), i.MemoryOperand(), kScratchReg); break; } case kMipsSwc1: { size_t index = 0; MemOperand operand = i.MemoryOperand(&index); FPURegister ft = i.InputOrZeroSingleRegister(index); if (ft == kDoubleRegZero && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ swc1(ft, operand); break; } case kMipsUswc1: { size_t index = 0; MemOperand operand = i.MemoryOperand(&index); FPURegister ft = i.InputOrZeroSingleRegister(index); if (ft == kDoubleRegZero && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ Uswc1(ft, operand, kScratchReg); break; } case kMipsLdc1: __ Ldc1(i.OutputDoubleRegister(), i.MemoryOperand()); break; case kMipsUldc1: __ Uldc1(i.OutputDoubleRegister(), i.MemoryOperand(), kScratchReg); break; case kMipsSdc1: { FPURegister ft = i.InputOrZeroDoubleRegister(2); if (ft == kDoubleRegZero && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ Sdc1(ft, i.MemoryOperand()); break; } case kMipsUsdc1: { FPURegister ft = i.InputOrZeroDoubleRegister(2); if (ft == kDoubleRegZero && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } __ Usdc1(ft, i.MemoryOperand(), kScratchReg); break; } case kMipsPush: if (instr->InputAt(0)->IsFPRegister()) { LocationOperand* op = LocationOperand::cast(instr->InputAt(0)); switch (op->representation()) { case MachineRepresentation::kFloat32: __ swc1(i.InputFloatRegister(0), MemOperand(sp, -kFloatSize)); __ Subu(sp, sp, Operand(kFloatSize)); frame_access_state()->IncreaseSPDelta(kFloatSize / kPointerSize); break; case MachineRepresentation::kFloat64: __ Sdc1(i.InputDoubleRegister(0), MemOperand(sp, -kDoubleSize)); __ Subu(sp, sp, Operand(kDoubleSize)); frame_access_state()->IncreaseSPDelta(kDoubleSize / kPointerSize); break; default: { UNREACHABLE(); break; } } } else { __ Push(i.InputRegister(0)); frame_access_state()->IncreaseSPDelta(1); } break; case kMipsPeek: { // The incoming value is 0-based, but we need a 1-based value. int reverse_slot = i.InputInt32(0) + 1; int offset = FrameSlotToFPOffset(frame()->GetTotalFrameSlotCount() - reverse_slot); if (instr->OutputAt(0)->IsFPRegister()) { LocationOperand* op = LocationOperand::cast(instr->OutputAt(0)); if (op->representation() == MachineRepresentation::kFloat64) { __ Ldc1(i.OutputDoubleRegister(), MemOperand(fp, offset)); } else { DCHECK_EQ(op->representation(), MachineRepresentation::kFloat32); __ lwc1(i.OutputSingleRegister(0), MemOperand(fp, offset)); } } else { __ lw(i.OutputRegister(0), MemOperand(fp, offset)); } break; } case kMipsStackClaim: { __ Subu(sp, sp, Operand(i.InputInt32(0))); frame_access_state()->IncreaseSPDelta(i.InputInt32(0) / kPointerSize); break; } case kMipsStoreToStackSlot: { if (instr->InputAt(0)->IsFPRegister()) { LocationOperand* op = LocationOperand::cast(instr->InputAt(0)); if (op->representation() == MachineRepresentation::kFloat64) { __ Sdc1(i.InputDoubleRegister(0), MemOperand(sp, i.InputInt32(1))); } else if (op->representation() == MachineRepresentation::kFloat32) { __ swc1(i.InputSingleRegister(0), MemOperand(sp, i.InputInt32(1))); } else { DCHECK_EQ(MachineRepresentation::kSimd128, op->representation()); CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ st_b(i.InputSimd128Register(0), MemOperand(sp, i.InputInt32(1))); } } else { __ sw(i.InputRegister(0), MemOperand(sp, i.InputInt32(1))); } break; } case kMipsByteSwap32: { __ ByteSwapSigned(i.OutputRegister(0), i.InputRegister(0), 4); break; } case kWord32AtomicLoadInt8: ASSEMBLE_ATOMIC_LOAD_INTEGER(lb); break; case kWord32AtomicLoadUint8: ASSEMBLE_ATOMIC_LOAD_INTEGER(lbu); break; case kWord32AtomicLoadInt16: ASSEMBLE_ATOMIC_LOAD_INTEGER(lh); break; case kWord32AtomicLoadUint16: ASSEMBLE_ATOMIC_LOAD_INTEGER(lhu); break; case kWord32AtomicLoadWord32: ASSEMBLE_ATOMIC_LOAD_INTEGER(lw); break; case kWord32AtomicStoreWord8: ASSEMBLE_ATOMIC_STORE_INTEGER(sb); break; case kWord32AtomicStoreWord16: ASSEMBLE_ATOMIC_STORE_INTEGER(sh); break; case kWord32AtomicStoreWord32: ASSEMBLE_ATOMIC_STORE_INTEGER(sw); break; case kWord32AtomicExchangeInt8: ASSEMBLE_ATOMIC_EXCHANGE_INTEGER_EXT(true, 8); break; case kWord32AtomicExchangeUint8: ASSEMBLE_ATOMIC_EXCHANGE_INTEGER_EXT(false, 8); break; case kWord32AtomicExchangeInt16: ASSEMBLE_ATOMIC_EXCHANGE_INTEGER_EXT(true, 16); break; case kWord32AtomicExchangeUint16: ASSEMBLE_ATOMIC_EXCHANGE_INTEGER_EXT(false, 16); break; case kWord32AtomicExchangeWord32: ASSEMBLE_ATOMIC_EXCHANGE_INTEGER(); break; case kWord32AtomicCompareExchangeInt8: ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER_EXT(true, 8); break; case kWord32AtomicCompareExchangeUint8: ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER_EXT(false, 8); break; case kWord32AtomicCompareExchangeInt16: ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER_EXT(true, 16); break; case kWord32AtomicCompareExchangeUint16: ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER_EXT(false, 16); break; case kWord32AtomicCompareExchangeWord32: ASSEMBLE_ATOMIC_COMPARE_EXCHANGE_INTEGER(); break; #define ATOMIC_BINOP_CASE(op, inst) \ case kWord32Atomic##op##Int8: \ ASSEMBLE_ATOMIC_BINOP_EXT(true, 8, inst); \ break; \ case kWord32Atomic##op##Uint8: \ ASSEMBLE_ATOMIC_BINOP_EXT(false, 8, inst); \ break; \ case kWord32Atomic##op##Int16: \ ASSEMBLE_ATOMIC_BINOP_EXT(true, 16, inst); \ break; \ case kWord32Atomic##op##Uint16: \ ASSEMBLE_ATOMIC_BINOP_EXT(false, 16, inst); \ break; \ case kWord32Atomic##op##Word32: \ ASSEMBLE_ATOMIC_BINOP(inst); \ break; ATOMIC_BINOP_CASE(Add, Addu) ATOMIC_BINOP_CASE(Sub, Subu) ATOMIC_BINOP_CASE(And, And) ATOMIC_BINOP_CASE(Or, Or) ATOMIC_BINOP_CASE(Xor, Xor) #undef ATOMIC_BINOP_CASE case kMipsWord32AtomicPairLoad: { if (IsMipsArchVariant(kMips32r6)) { Register second_output = instr->OutputCount() == 2 ? i.OutputRegister(1) : i.TempRegister(0); __ llwp(i.OutputRegister(0), second_output, i.InputRegister(0)); __ sync(); } else { UNREACHABLE(); } break; } case kMipsWord32AtomicPairStore: { if (IsMipsArchVariant(kMips32r6)) { Label store; __ sync(); __ bind(&store); __ llwp(i.TempRegister(0), i.TempRegister(1), i.InputRegister(0)); __ Move(i.TempRegister(0), i.InputRegister(2)); __ scwp(i.InputRegister(1), i.TempRegister(0), i.InputRegister(0)); __ BranchShort(&store, eq, i.TempRegister(0), Operand(zero_reg)); __ sync(); } else { UNREACHABLE(); } break; } #define ATOMIC64_BINOP_ARITH_CASE(op, instr) \ case kMipsWord32AtomicPair##op: \ ASSEMBLE_ATOMIC64_ARITH_BINOP(instr); \ break; ATOMIC64_BINOP_ARITH_CASE(Add, AddPair) ATOMIC64_BINOP_ARITH_CASE(Sub, SubPair) #undef ATOMIC64_BINOP_ARITH_CASE #define ATOMIC64_BINOP_LOGIC_CASE(op, instr) \ case kMipsWord32AtomicPair##op: \ ASSEMBLE_ATOMIC64_LOGIC_BINOP(instr); \ break; ATOMIC64_BINOP_LOGIC_CASE(And, AndPair) ATOMIC64_BINOP_LOGIC_CASE(Or, OrPair) ATOMIC64_BINOP_LOGIC_CASE(Xor, XorPair) #undef ATOMIC64_BINOP_LOGIC_CASE case kMipsWord32AtomicPairExchange: case kMipsWord32AtomicPairCompareExchange: break; case kMipsS128Zero: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(i.OutputSimd128Register(), i.OutputSimd128Register(), i.OutputSimd128Register()); break; } case kMipsI32x4Splat: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fill_w(i.OutputSimd128Register(), i.InputRegister(0)); break; } case kMipsI32x4ExtractLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ copy_s_w(i.OutputRegister(), i.InputSimd128Register(0), i.InputInt8(1)); break; } case kMipsI32x4ReplaceLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src = i.InputSimd128Register(0); Simd128Register dst = i.OutputSimd128Register(); if (src != dst) { __ move_v(dst, src); } __ insert_w(dst, i.InputInt8(1), i.InputRegister(2)); break; } case kMipsI32x4Add: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ addv_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4Sub: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subv_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Splat: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ FmoveLow(kScratchReg, i.InputSingleRegister(0)); __ fill_w(i.OutputSimd128Register(), kScratchReg); break; } case kMipsF32x4ExtractLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ copy_u_w(kScratchReg, i.InputSimd128Register(0), i.InputInt8(1)); __ FmoveLow(i.OutputSingleRegister(), kScratchReg); break; } case kMipsF32x4ReplaceLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src = i.InputSimd128Register(0); Simd128Register dst = i.OutputSimd128Register(); if (src != dst) { __ move_v(dst, src); } __ FmoveLow(kScratchReg, i.InputSingleRegister(2)); __ insert_w(dst, i.InputInt8(1), kScratchReg); break; } case kMipsF32x4SConvertI32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ffint_s_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsF32x4UConvertI32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ffint_u_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsI32x4Mul: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ mulv_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4MaxS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_s_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4MinS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_s_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4Eq: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ceq_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4Ne: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); __ ceq_w(dst, i.InputSimd128Register(0), i.InputSimd128Register(1)); __ nor_v(dst, dst, dst); break; } case kMipsI32x4Shl: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ slli_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt5(1)); break; } case kMipsI32x4ShrS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srai_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt5(1)); break; } case kMipsI32x4ShrU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srli_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt5(1)); break; } case kMipsI32x4MaxU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_u_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4MinU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_u_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsS128Select: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); DCHECK(i.OutputSimd128Register() == i.InputSimd128Register(0)); __ bsel_v(i.OutputSimd128Register(), i.InputSimd128Register(2), i.InputSimd128Register(1)); break; } case kMipsF32x4Abs: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ bclri_w(i.OutputSimd128Register(), i.InputSimd128Register(0), 31); break; } case kMipsF32x4Neg: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ bnegi_w(i.OutputSimd128Register(), i.InputSimd128Register(0), 31); break; } case kMipsF32x4RecipApprox: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ frcp_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsF32x4RecipSqrtApprox: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ frsqrt_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsF32x4Add: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fadd_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Sub: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fsub_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Mul: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fmul_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Max: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fmax_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Min: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fmin_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Eq: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fceq_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Ne: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fcne_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Lt: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fclt_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsF32x4Le: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fcle_w(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI32x4SConvertF32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ftrunc_s_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsI32x4UConvertF32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ftrunc_u_w(i.OutputSimd128Register(), i.InputSimd128Register(0)); break; } case kMipsI32x4Neg: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ subv_w(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI32x4GtS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_s_w(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI32x4GeS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_s_w(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI32x4GtU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_u_w(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI32x4GeU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_u_w(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI16x8Splat: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fill_h(i.OutputSimd128Register(), i.InputRegister(0)); break; } case kMipsI16x8ExtractLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ copy_s_h(i.OutputRegister(), i.InputSimd128Register(0), i.InputInt8(1)); break; } case kMipsI16x8ReplaceLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src = i.InputSimd128Register(0); Simd128Register dst = i.OutputSimd128Register(); if (src != dst) { __ move_v(dst, src); } __ insert_h(dst, i.InputInt8(1), i.InputRegister(2)); break; } case kMipsI16x8Neg: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ subv_h(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI16x8Shl: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ slli_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt4(1)); break; } case kMipsI16x8ShrS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srai_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt4(1)); break; } case kMipsI16x8ShrU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srli_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt4(1)); break; } case kMipsI16x8Add: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ addv_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8AddSaturateS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ adds_s_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8Sub: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subv_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8SubSaturateS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subs_s_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8Mul: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ mulv_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8MaxS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_s_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8MinS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_s_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8Eq: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ceq_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8Ne: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); __ ceq_h(dst, i.InputSimd128Register(0), i.InputSimd128Register(1)); __ nor_v(dst, dst, dst); break; } case kMipsI16x8GtS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_s_h(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI16x8GeS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_s_h(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI16x8AddSaturateU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ adds_u_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8SubSaturateU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subs_u_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8MaxU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_u_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8MinU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_u_h(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI16x8GtU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_u_h(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI16x8GeU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_u_h(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI8x16Splat: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ fill_b(i.OutputSimd128Register(), i.InputRegister(0)); break; } case kMipsI8x16ExtractLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ copy_s_b(i.OutputRegister(), i.InputSimd128Register(0), i.InputInt8(1)); break; } case kMipsI8x16ReplaceLane: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src = i.InputSimd128Register(0); Simd128Register dst = i.OutputSimd128Register(); if (src != dst) { __ move_v(dst, src); } __ insert_b(dst, i.InputInt8(1), i.InputRegister(2)); break; } case kMipsI8x16Neg: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ subv_b(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI8x16Shl: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ slli_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt3(1)); break; } case kMipsI8x16ShrS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srai_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt3(1)); break; } case kMipsI8x16Add: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ addv_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16AddSaturateS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ adds_s_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16Sub: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subv_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16SubSaturateS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subs_s_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16Mul: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ mulv_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16MaxS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_s_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16MinS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_s_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16Eq: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ceq_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16Ne: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); __ ceq_b(dst, i.InputSimd128Register(0), i.InputSimd128Register(1)); __ nor_v(dst, dst, dst); break; } case kMipsI8x16GtS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_s_b(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI8x16GeS: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_s_b(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI8x16ShrU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ srli_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputInt3(1)); break; } case kMipsI8x16AddSaturateU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ adds_u_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16SubSaturateU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ subs_u_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16MaxU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ max_u_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16MinU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ min_u_b(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsI8x16GtU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ clt_u_b(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsI8x16GeU: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ cle_u_b(i.OutputSimd128Register(), i.InputSimd128Register(1), i.InputSimd128Register(0)); break; } case kMipsS128And: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ and_v(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsS128Or: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ or_v(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsS128Xor: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(1)); break; } case kMipsS128Not: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ nor_v(i.OutputSimd128Register(), i.InputSimd128Register(0), i.InputSimd128Register(0)); break; } case kMipsS1x4AnyTrue: case kMipsS1x8AnyTrue: case kMipsS1x16AnyTrue: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Register dst = i.OutputRegister(); Label all_false; __ BranchMSA(&all_false, MSA_BRANCH_V, all_zero, i.InputSimd128Register(0), USE_DELAY_SLOT); __ li(dst, 0); // branch delay slot __ li(dst, -1); __ bind(&all_false); break; } case kMipsS1x4AllTrue: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Register dst = i.OutputRegister(); Label all_true; __ BranchMSA(&all_true, MSA_BRANCH_W, all_not_zero, i.InputSimd128Register(0), USE_DELAY_SLOT); __ li(dst, -1); // branch delay slot __ li(dst, 0); __ bind(&all_true); break; } case kMipsS1x8AllTrue: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Register dst = i.OutputRegister(); Label all_true; __ BranchMSA(&all_true, MSA_BRANCH_H, all_not_zero, i.InputSimd128Register(0), USE_DELAY_SLOT); __ li(dst, -1); // branch delay slot __ li(dst, 0); __ bind(&all_true); break; } case kMipsS1x16AllTrue: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Register dst = i.OutputRegister(); Label all_true; __ BranchMSA(&all_true, MSA_BRANCH_B, all_not_zero, i.InputSimd128Register(0), USE_DELAY_SLOT); __ li(dst, -1); // branch delay slot __ li(dst, 0); __ bind(&all_true); break; } case kMipsMsaLd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ld_b(i.OutputSimd128Register(), i.MemoryOperand()); break; } case kMipsMsaSt: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ st_b(i.InputSimd128Register(2), i.MemoryOperand()); break; } case kMipsS32x4InterleaveRight: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [5, 1, 4, 0] __ ilvr_w(dst, src1, src0); break; } case kMipsS32x4InterleaveLeft: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [7, 3, 6, 2] __ ilvl_w(dst, src1, src0); break; } case kMipsS32x4PackEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [6, 4, 2, 0] __ pckev_w(dst, src1, src0); break; } case kMipsS32x4PackOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [7, 5, 3, 1] __ pckod_w(dst, src1, src0); break; } case kMipsS32x4InterleaveEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [6, 2, 4, 0] __ ilvev_w(dst, src1, src0); break; } case kMipsS32x4InterleaveOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [7, 6, 5, 4], src0 = [3, 2, 1, 0] // dst = [7, 3, 5, 1] __ ilvod_w(dst, src1, src0); break; } case kMipsS32x4Shuffle: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); int32_t shuffle = i.InputInt32(2); if (src0 == src1) { // Unary S32x4 shuffles are handled with shf.w instruction unsigned lane = shuffle & 0xFF; if (FLAG_debug_code) { // range of all four lanes, for unary instruction, // should belong to the same range, which can be one of these: // [0, 3] or [4, 7] if (lane >= 4) { int32_t shuffle_helper = shuffle; for (int i = 0; i < 4; ++i) { lane = shuffle_helper & 0xFF; CHECK_GE(lane, 4); shuffle_helper >>= 8; } } } uint32_t i8 = 0; for (int i = 0; i < 4; i++) { lane = shuffle & 0xFF; if (lane >= 4) { lane -= 4; } DCHECK_GT(4, lane); i8 |= lane << (2 * i); shuffle >>= 8; } __ shf_w(dst, src0, i8); } else { // For binary shuffles use vshf.w instruction if (dst == src0) { __ move_v(kSimd128ScratchReg, src0); src0 = kSimd128ScratchReg; } else if (dst == src1) { __ move_v(kSimd128ScratchReg, src1); src1 = kSimd128ScratchReg; } __ li(kScratchReg, i.InputInt32(2)); __ insert_w(dst, 0, kScratchReg); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ ilvr_b(dst, kSimd128RegZero, dst); __ ilvr_h(dst, kSimd128RegZero, dst); __ vshf_w(dst, src1, src0); } break; } case kMipsS16x8InterleaveRight: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [11, 3, 10, 2, 9, 1, 8, 0] __ ilvr_h(dst, src1, src0); break; } case kMipsS16x8InterleaveLeft: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [15, 7, 14, 6, 13, 5, 12, 4] __ ilvl_h(dst, src1, src0); break; } case kMipsS16x8PackEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [14, 12, 10, 8, 6, 4, 2, 0] __ pckev_h(dst, src1, src0); break; } case kMipsS16x8PackOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [15, 13, 11, 9, 7, 5, 3, 1] __ pckod_h(dst, src1, src0); break; } case kMipsS16x8InterleaveEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [14, 6, 12, 4, 10, 2, 8, 0] __ ilvev_h(dst, src1, src0); break; } case kMipsS16x8InterleaveOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [15, ... 11, 10, 9, 8], src0 = [7, ... 3, 2, 1, 0] // dst = [15, 7, ... 11, 3, 9, 1] __ ilvod_h(dst, src1, src0); break; } case kMipsS16x4Reverse: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); // src = [7, 6, 5, 4, 3, 2, 1, 0], dst = [4, 5, 6, 7, 0, 1, 2, 3] // shf.df imm field: 0 1 2 3 = 00011011 = 0x1B __ shf_h(i.OutputSimd128Register(), i.InputSimd128Register(0), 0x1B); break; } case kMipsS16x2Reverse: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); // src = [7, 6, 5, 4, 3, 2, 1, 0], dst = [6, 7, 4, 5, 3, 2, 0, 1] // shf.df imm field: 2 3 0 1 = 10110001 = 0xB1 __ shf_h(i.OutputSimd128Register(), i.InputSimd128Register(0), 0xB1); break; } case kMipsS8x16InterleaveRight: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [23, 7, ... 17, 1, 16, 0] __ ilvr_b(dst, src1, src0); break; } case kMipsS8x16InterleaveLeft: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [31, 15, ... 25, 9, 24, 8] __ ilvl_b(dst, src1, src0); break; } case kMipsS8x16PackEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [30, 28, ... 6, 4, 2, 0] __ pckev_b(dst, src1, src0); break; } case kMipsS8x16PackOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [31, 29, ... 7, 5, 3, 1] __ pckod_b(dst, src1, src0); break; } case kMipsS8x16InterleaveEven: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [30, 14, ... 18, 2, 16, 0] __ ilvev_b(dst, src1, src0); break; } case kMipsS8x16InterleaveOdd: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); // src1 = [31, ... 19, 18, 17, 16], src0 = [15, ... 3, 2, 1, 0] // dst = [31, 15, ... 19, 3, 17, 1] __ ilvod_b(dst, src1, src0); break; } case kMipsS8x16Concat: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); DCHECK(dst == i.InputSimd128Register(0)); __ sldi_b(dst, i.InputSimd128Register(1), i.InputInt4(2)); break; } case kMipsS8x16Shuffle: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(), src0 = i.InputSimd128Register(0), src1 = i.InputSimd128Register(1); if (dst == src0) { __ move_v(kSimd128ScratchReg, src0); src0 = kSimd128ScratchReg; } else if (dst == src1) { __ move_v(kSimd128ScratchReg, src1); src1 = kSimd128ScratchReg; } __ li(kScratchReg, i.InputInt32(2)); __ insert_w(dst, 0, kScratchReg); __ li(kScratchReg, i.InputInt32(3)); __ insert_w(dst, 1, kScratchReg); __ li(kScratchReg, i.InputInt32(4)); __ insert_w(dst, 2, kScratchReg); __ li(kScratchReg, i.InputInt32(5)); __ insert_w(dst, 3, kScratchReg); __ vshf_b(dst, src1, src0); break; } case kMipsS8x8Reverse: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); // src = [15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] // dst = [8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7] // [A B C D] => [B A D C]: shf.w imm: 2 3 0 1 = 10110001 = 0xB1 // C: [7, 6, 5, 4] => A': [4, 5, 6, 7]: shf.b imm: 00011011 = 0x1B __ shf_w(kSimd128ScratchReg, i.InputSimd128Register(0), 0xB1); __ shf_b(i.OutputSimd128Register(), kSimd128ScratchReg, 0x1B); break; } case kMipsS8x4Reverse: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); // src = [15, 14, ... 3, 2, 1, 0], dst = [12, 13, 14, 15, ... 0, 1, 2, 3] // shf.df imm field: 0 1 2 3 = 00011011 = 0x1B __ shf_b(i.OutputSimd128Register(), i.InputSimd128Register(0), 0x1B); break; } case kMipsS8x2Reverse: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); // src = [15, 14, ... 3, 2, 1, 0], dst = [14, 15, 12, 13, ... 2, 3, 0, 1] // shf.df imm field: 2 3 0 1 = 10110001 = 0xB1 __ shf_b(i.OutputSimd128Register(), i.InputSimd128Register(0), 0xB1); break; } case kMipsI32x4SConvertI16x8Low: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src = i.InputSimd128Register(0); __ ilvr_h(kSimd128ScratchReg, src, src); __ slli_w(dst, kSimd128ScratchReg, 16); __ srai_w(dst, dst, 16); break; } case kMipsI32x4SConvertI16x8High: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src = i.InputSimd128Register(0); __ ilvl_h(kSimd128ScratchReg, src, src); __ slli_w(dst, kSimd128ScratchReg, 16); __ srai_w(dst, dst, 16); break; } case kMipsI32x4UConvertI16x8Low: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ ilvr_h(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI32x4UConvertI16x8High: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ ilvl_h(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI16x8SConvertI8x16Low: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src = i.InputSimd128Register(0); __ ilvr_b(kSimd128ScratchReg, src, src); __ slli_h(dst, kSimd128ScratchReg, 8); __ srai_h(dst, dst, 8); break; } case kMipsI16x8SConvertI8x16High: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src = i.InputSimd128Register(0); __ ilvl_b(kSimd128ScratchReg, src, src); __ slli_h(dst, kSimd128ScratchReg, 8); __ srai_h(dst, dst, 8); break; } case kMipsI16x8SConvertI32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); __ sat_s_w(kSimd128ScratchReg, src0, 15); __ sat_s_w(kSimd128RegZero, src1, 15); // kSimd128RegZero as scratch __ pckev_h(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsI16x8UConvertI32x4: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); __ sat_u_w(kSimd128ScratchReg, src0, 15); __ sat_u_w(kSimd128RegZero, src1, 15); // kSimd128RegZero as scratch __ pckev_h(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsI16x8UConvertI8x16Low: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ ilvr_b(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI16x8UConvertI8x16High: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ xor_v(kSimd128RegZero, kSimd128RegZero, kSimd128RegZero); __ ilvl_b(i.OutputSimd128Register(), kSimd128RegZero, i.InputSimd128Register(0)); break; } case kMipsI8x16SConvertI16x8: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); __ sat_s_h(kSimd128ScratchReg, src0, 7); __ sat_s_h(kSimd128RegZero, src1, 7); // kSimd128RegZero as scratch __ pckev_b(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsI8x16UConvertI16x8: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register dst = i.OutputSimd128Register(); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); __ sat_u_h(kSimd128ScratchReg, src0, 7); __ sat_u_h(kSimd128RegZero, src1, 7); // kSimd128RegZero as scratch __ pckev_b(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsF32x4AddHoriz: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); Simd128Register dst = i.OutputSimd128Register(); __ shf_w(kSimd128ScratchReg, src0, 0xB1); // 2 3 0 1 : 10110001 : 0xB1 __ shf_w(kSimd128RegZero, src1, 0xB1); // kSimd128RegZero as scratch __ fadd_w(kSimd128ScratchReg, kSimd128ScratchReg, src0); __ fadd_w(kSimd128RegZero, kSimd128RegZero, src1); __ pckev_w(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsI32x4AddHoriz: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); Simd128Register dst = i.OutputSimd128Register(); __ hadd_s_d(kSimd128ScratchReg, src0, src0); __ hadd_s_d(kSimd128RegZero, src1, src1); // kSimd128RegZero as scratch __ pckev_w(dst, kSimd128RegZero, kSimd128ScratchReg); break; } case kMipsI16x8AddHoriz: { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); Simd128Register src0 = i.InputSimd128Register(0); Simd128Register src1 = i.InputSimd128Register(1); Simd128Register dst = i.OutputSimd128Register(); __ hadd_s_w(kSimd128ScratchReg, src0, src0); __ hadd_s_w(kSimd128RegZero, src1, src1); // kSimd128RegZero as scratch __ pckev_h(dst, kSimd128RegZero, kSimd128ScratchReg); break; } } return kSuccess; } // NOLINT(readability/fn_size) void AssembleBranchToLabels(CodeGenerator* gen, TurboAssembler* tasm, Instruction* instr, FlagsCondition condition, Label* tlabel, Label* flabel, bool fallthru) { #undef __ #define __ tasm-> Condition cc = kNoCondition; // MIPS does not have condition code flags, so compare and branch are // implemented differently than on the other arch's. The compare operations // emit mips pseudo-instructions, which are handled here by branch // instructions that do the actual comparison. Essential that the input // registers to compare pseudo-op are not modified before this branch op, as // they are tested here. MipsOperandConverter i(gen, instr); if (instr->arch_opcode() == kMipsTst) { cc = FlagsConditionToConditionTst(condition); __ Branch(tlabel, cc, kScratchReg, Operand(zero_reg)); } else if (instr->arch_opcode() == kMipsAddOvf || instr->arch_opcode() == kMipsSubOvf) { // Overflow occurs if overflow register is negative switch (condition) { case kOverflow: __ Branch(tlabel, lt, kScratchReg, Operand(zero_reg)); break; case kNotOverflow: __ Branch(tlabel, ge, kScratchReg, Operand(zero_reg)); break; default: UNSUPPORTED_COND(instr->arch_opcode(), condition); break; } } else if (instr->arch_opcode() == kMipsMulOvf) { // Overflow occurs if overflow register is not zero switch (condition) { case kOverflow: __ Branch(tlabel, ne, kScratchReg, Operand(zero_reg)); break; case kNotOverflow: __ Branch(tlabel, eq, kScratchReg, Operand(zero_reg)); break; default: UNSUPPORTED_COND(kMipsMulOvf, condition); break; } } else if (instr->arch_opcode() == kMipsCmp) { cc = FlagsConditionToConditionCmp(condition); __ Branch(tlabel, cc, i.InputRegister(0), i.InputOperand(1)); } else if (instr->arch_opcode() == kMipsCmpS || instr->arch_opcode() == kMipsCmpD) { bool predicate; FlagsConditionToConditionCmpFPU(predicate, condition); if (predicate) { __ BranchTrueF(tlabel); } else { __ BranchFalseF(tlabel); } } else { PrintF("AssembleArchBranch Unimplemented arch_opcode: %d\n", instr->arch_opcode()); UNIMPLEMENTED(); } if (!fallthru) __ Branch(flabel); // no fallthru to flabel. #undef __ #define __ tasm()-> } // Assembles branches after an instruction. void CodeGenerator::AssembleArchBranch(Instruction* instr, BranchInfo* branch) { Label* tlabel = branch->true_label; Label* flabel = branch->false_label; AssembleBranchToLabels(this, tasm(), instr, branch->condition, tlabel, flabel, branch->fallthru); } void CodeGenerator::AssembleBranchPoisoning(FlagsCondition condition, Instruction* instr) { // TODO(jarin) Handle float comparisons (kUnordered[Not]Equal). if (condition == kUnorderedEqual || condition == kUnorderedNotEqual) { return; } MipsOperandConverter i(this, instr); condition = NegateFlagsCondition(condition); switch (instr->arch_opcode()) { case kMipsCmp: { __ LoadZeroOnCondition(kSpeculationPoisonRegister, i.InputRegister(0), i.InputOperand(1), FlagsConditionToConditionCmp(condition)); } return; case kMipsTst: { switch (condition) { case kEqual: __ LoadZeroIfConditionZero(kSpeculationPoisonRegister, kScratchReg); break; case kNotEqual: __ LoadZeroIfConditionNotZero(kSpeculationPoisonRegister, kScratchReg); break; default: UNREACHABLE(); } } return; case kMipsAddOvf: case kMipsSubOvf: { // Overflow occurs if overflow register is negative __ Slt(kScratchReg2, kScratchReg, zero_reg); switch (condition) { case kOverflow: __ LoadZeroIfConditionNotZero(kSpeculationPoisonRegister, kScratchReg2); break; case kNotOverflow: __ LoadZeroIfConditionZero(kSpeculationPoisonRegister, kScratchReg2); break; default: UNSUPPORTED_COND(instr->arch_opcode(), condition); } } return; case kMipsMulOvf: { // Overflow occurs if overflow register is not zero switch (condition) { case kOverflow: __ LoadZeroIfConditionNotZero(kSpeculationPoisonRegister, kScratchReg); break; case kNotOverflow: __ LoadZeroIfConditionZero(kSpeculationPoisonRegister, kScratchReg); break; default: UNSUPPORTED_COND(instr->arch_opcode(), condition); } } return; case kMipsCmpS: case kMipsCmpD: { bool predicate; FlagsConditionToConditionCmpFPU(predicate, condition); if (predicate) { __ LoadZeroIfFPUCondition(kSpeculationPoisonRegister); } else { __ LoadZeroIfNotFPUCondition(kSpeculationPoisonRegister); } } return; default: UNREACHABLE(); break; } } void CodeGenerator::AssembleArchDeoptBranch(Instruction* instr, BranchInfo* branch) { AssembleArchBranch(instr, branch); } void CodeGenerator::AssembleArchJump(RpoNumber target) { if (!IsNextInAssemblyOrder(target)) __ Branch(GetLabel(target)); } void CodeGenerator::AssembleArchTrap(Instruction* instr, FlagsCondition condition) { class OutOfLineTrap final : public OutOfLineCode { public: OutOfLineTrap(CodeGenerator* gen, Instruction* instr) : OutOfLineCode(gen), instr_(instr), gen_(gen) {} void Generate() final { MipsOperandConverter i(gen_, instr_); TrapId trap_id = static_cast<TrapId>(i.InputInt32(instr_->InputCount() - 1)); GenerateCallToTrap(trap_id); } private: void GenerateCallToTrap(TrapId trap_id) { if (trap_id == TrapId::kInvalid) { // We cannot test calls to the runtime in cctest/test-run-wasm. // Therefore we emit a call to C here instead of a call to the runtime. // We use the context register as the scratch register, because we do // not have a context here. __ PrepareCallCFunction(0, 0, cp); __ CallCFunction( ExternalReference::wasm_call_trap_callback_for_testing(), 0); __ LeaveFrame(StackFrame::WASM_COMPILED); auto call_descriptor = gen_->linkage()->GetIncomingDescriptor(); int pop_count = static_cast<int>(call_descriptor->StackParameterCount()); __ Drop(pop_count); __ Ret(); } else { gen_->AssembleSourcePosition(instr_); // A direct call to a wasm runtime stub defined in this module. // Just encode the stub index. This will be patched at relocation. __ Call(static_cast<Address>(trap_id), RelocInfo::WASM_STUB_CALL); ReferenceMap* reference_map = new (gen_->zone()) ReferenceMap(gen_->zone()); gen_->RecordSafepoint(reference_map, Safepoint::kSimple, 0, Safepoint::kNoLazyDeopt); if (FLAG_debug_code) { __ stop(GetAbortReason(AbortReason::kUnexpectedReturnFromWasmTrap)); } } } Instruction* instr_; CodeGenerator* gen_; }; auto ool = new (zone()) OutOfLineTrap(this, instr); Label* tlabel = ool->entry(); AssembleBranchToLabels(this, tasm(), instr, condition, tlabel, nullptr, true); } // Assembles boolean materializations after an instruction. void CodeGenerator::AssembleArchBoolean(Instruction* instr, FlagsCondition condition) { MipsOperandConverter i(this, instr); Label done; // Materialize a full 32-bit 1 or 0 value. The result register is always the // last output of the instruction. Label false_value; DCHECK_NE(0u, instr->OutputCount()); Register result = i.OutputRegister(instr->OutputCount() - 1); Condition cc = kNoCondition; // MIPS does not have condition code flags, so compare and branch are // implemented differently than on the other arch's. The compare operations // emit mips pseudo-instructions, which are checked and handled here. if (instr->arch_opcode() == kMipsTst) { cc = FlagsConditionToConditionTst(condition); if (cc == eq) { __ Sltu(result, kScratchReg, 1); } else { __ Sltu(result, zero_reg, kScratchReg); } return; } else if (instr->arch_opcode() == kMipsAddOvf || instr->arch_opcode() == kMipsSubOvf) { // Overflow occurs if overflow register is negative __ slt(result, kScratchReg, zero_reg); } else if (instr->arch_opcode() == kMipsMulOvf) { // Overflow occurs if overflow register is not zero __ Sgtu(result, kScratchReg, zero_reg); } else if (instr->arch_opcode() == kMipsCmp) { cc = FlagsConditionToConditionCmp(condition); switch (cc) { case eq: case ne: { Register left = i.InputRegister(0); Operand right = i.InputOperand(1); if (instr->InputAt(1)->IsImmediate()) { if (is_int16(-right.immediate())) { if (right.immediate() == 0) { if (cc == eq) { __ Sltu(result, left, 1); } else { __ Sltu(result, zero_reg, left); } } else { __ Addu(result, left, -right.immediate()); if (cc == eq) { __ Sltu(result, result, 1); } else { __ Sltu(result, zero_reg, result); } } } else { if (is_uint16(right.immediate())) { __ Xor(result, left, right); } else { __ li(kScratchReg, right); __ Xor(result, left, kScratchReg); } if (cc == eq) { __ Sltu(result, result, 1); } else { __ Sltu(result, zero_reg, result); } } } else { __ Xor(result, left, right); if (cc == eq) { __ Sltu(result, result, 1); } else { __ Sltu(result, zero_reg, result); } } } break; case lt: case ge: { Register left = i.InputRegister(0); Operand right = i.InputOperand(1); __ Slt(result, left, right); if (cc == ge) { __ xori(result, result, 1); } } break; case gt: case le: { Register left = i.InputRegister(1); Operand right = i.InputOperand(0); __ Slt(result, left, right); if (cc == le) { __ xori(result, result, 1); } } break; case lo: case hs: { Register left = i.InputRegister(0); Operand right = i.InputOperand(1); __ Sltu(result, left, right); if (cc == hs) { __ xori(result, result, 1); } } break; case hi: case ls: { Register left = i.InputRegister(1); Operand right = i.InputOperand(0); __ Sltu(result, left, right); if (cc == ls) { __ xori(result, result, 1); } } break; default: UNREACHABLE(); } return; } else if (instr->arch_opcode() == kMipsCmpD || instr->arch_opcode() == kMipsCmpS) { FPURegister left = i.InputOrZeroDoubleRegister(0); FPURegister right = i.InputOrZeroDoubleRegister(1); if ((left == kDoubleRegZero || right == kDoubleRegZero) && !__ IsDoubleZeroRegSet()) { __ Move(kDoubleRegZero, 0.0); } bool predicate; FlagsConditionToConditionCmpFPU(predicate, condition); if (!IsMipsArchVariant(kMips32r6)) { __ li(result, Operand(1)); if (predicate) { __ Movf(result, zero_reg); } else { __ Movt(result, zero_reg); } } else { __ mfc1(result, kDoubleCompareReg); if (predicate) { __ And(result, result, 1); // cmp returns all 1's/0's, use only LSB. } else { __ Addu(result, result, 1); // Toggle result for not equal. } } return; } else { PrintF("AssembleArchBoolean Unimplemented arch_opcode is : %d\n", instr->arch_opcode()); TRACE_UNIMPL(); UNIMPLEMENTED(); } } void CodeGenerator::AssembleArchBinarySearchSwitch(Instruction* instr) { MipsOperandConverter i(this, instr); Register input = i.InputRegister(0); std::vector<std::pair<int32_t, Label*>> cases; for (size_t index = 2; index < instr->InputCount(); index += 2) { cases.push_back({i.InputInt32(index + 0), GetLabel(i.InputRpo(index + 1))}); } AssembleArchBinarySearchSwitchRange(input, i.InputRpo(1), cases.data(), cases.data() + cases.size()); } void CodeGenerator::AssembleArchLookupSwitch(Instruction* instr) { MipsOperandConverter i(this, instr); Register input = i.InputRegister(0); for (size_t index = 2; index < instr->InputCount(); index += 2) { __ li(kScratchReg, Operand(i.InputInt32(index + 0))); __ Branch(GetLabel(i.InputRpo(index + 1)), eq, input, Operand(kScratchReg)); } AssembleArchJump(i.InputRpo(1)); } void CodeGenerator::AssembleArchTableSwitch(Instruction* instr) { MipsOperandConverter i(this, instr); Register input = i.InputRegister(0); size_t const case_count = instr->InputCount() - 2; __ Branch(GetLabel(i.InputRpo(1)), hs, input, Operand(case_count)); __ GenerateSwitchTable(input, case_count, [&i, this](size_t index) { return GetLabel(i.InputRpo(index + 2)); }); } void CodeGenerator::FinishFrame(Frame* frame) { auto call_descriptor = linkage()->GetIncomingDescriptor(); const RegList saves_fpu = call_descriptor->CalleeSavedFPRegisters(); if (saves_fpu != 0) { frame->AlignSavedCalleeRegisterSlots(); } if (saves_fpu != 0) { int count = base::bits::CountPopulation(saves_fpu); DCHECK_EQ(kNumCalleeSavedFPU, count); frame->AllocateSavedCalleeRegisterSlots(count * (kDoubleSize / kPointerSize)); } const RegList saves = call_descriptor->CalleeSavedRegisters(); if (saves != 0) { int count = base::bits::CountPopulation(saves); DCHECK_EQ(kNumCalleeSaved, count + 1); frame->AllocateSavedCalleeRegisterSlots(count); } } void CodeGenerator::AssembleConstructFrame() { auto call_descriptor = linkage()->GetIncomingDescriptor(); if (frame_access_state()->has_frame()) { if (call_descriptor->IsCFunctionCall()) { __ Push(ra, fp); __ mov(fp, sp); } else if (call_descriptor->IsJSFunctionCall()) { __ Prologue(); if (call_descriptor->PushArgumentCount()) { __ Push(kJavaScriptCallArgCountRegister); } } else { __ StubPrologue(info()->GetOutputStackFrameType()); if (call_descriptor->IsWasmFunctionCall()) { __ Push(kWasmInstanceRegister); } else if (call_descriptor->IsWasmImportWrapper()) { // WASM import wrappers are passed a tuple in the place of the instance. // Unpack the tuple into the instance and the target callable. // This must be done here in the codegen because it cannot be expressed // properly in the graph. __ lw(kJSFunctionRegister, FieldMemOperand(kWasmInstanceRegister, Tuple2::kValue2Offset)); __ lw(kWasmInstanceRegister, FieldMemOperand(kWasmInstanceRegister, Tuple2::kValue1Offset)); __ Push(kWasmInstanceRegister); } } } int shrink_slots = frame()->GetTotalFrameSlotCount() - call_descriptor->CalculateFixedFrameSize(); if (info()->is_osr()) { // TurboFan OSR-compiled functions cannot be entered directly. __ Abort(AbortReason::kShouldNotDirectlyEnterOsrFunction); // Unoptimized code jumps directly to this entrypoint while the unoptimized // frame is still on the stack. Optimized code uses OSR values directly from // the unoptimized frame. Thus, all that needs to be done is to allocate the // remaining stack slots. if (FLAG_code_comments) __ RecordComment("-- OSR entrypoint --"); osr_pc_offset_ = __ pc_offset(); shrink_slots -= osr_helper()->UnoptimizedFrameSlots(); ResetSpeculationPoison(); } const RegList saves = call_descriptor->CalleeSavedRegisters(); const RegList saves_fpu = call_descriptor->CalleeSavedFPRegisters(); const int returns = frame()->GetReturnSlotCount(); // Skip callee-saved and return slots, which are pushed below. shrink_slots -= base::bits::CountPopulation(saves); shrink_slots -= 2 * base::bits::CountPopulation(saves_fpu); shrink_slots -= returns; if (shrink_slots > 0) { __ Subu(sp, sp, Operand(shrink_slots * kPointerSize)); } // Save callee-saved FPU registers. if (saves_fpu != 0) { __ MultiPushFPU(saves_fpu); } if (saves != 0) { // Save callee-saved registers. __ MultiPush(saves); DCHECK_EQ(kNumCalleeSaved, base::bits::CountPopulation(saves) + 1); } if (returns != 0) { // Create space for returns. __ Subu(sp, sp, Operand(returns * kPointerSize)); } } void CodeGenerator::AssembleReturn(InstructionOperand* pop) { auto call_descriptor = linkage()->GetIncomingDescriptor(); int pop_count = static_cast<int>(call_descriptor->StackParameterCount()); const int returns = frame()->GetReturnSlotCount(); if (returns != 0) { __ Addu(sp, sp, Operand(returns * kPointerSize)); } // Restore GP registers. const RegList saves = call_descriptor->CalleeSavedRegisters(); if (saves != 0) { __ MultiPop(saves); } // Restore FPU registers. const RegList saves_fpu = call_descriptor->CalleeSavedFPRegisters(); if (saves_fpu != 0) { __ MultiPopFPU(saves_fpu); } MipsOperandConverter g(this, nullptr); if (call_descriptor->IsCFunctionCall()) { AssembleDeconstructFrame(); } else if (frame_access_state()->has_frame()) { // Canonicalize JSFunction return sites for now unless they have an variable // number of stack slot pops. if (pop->IsImmediate() && g.ToConstant(pop).ToInt32() == 0) { if (return_label_.is_bound()) { __ Branch(&return_label_); return; } else { __ bind(&return_label_); AssembleDeconstructFrame(); } } else { AssembleDeconstructFrame(); } } if (pop->IsImmediate()) { DCHECK_EQ(Constant::kInt32, g.ToConstant(pop).type()); pop_count += g.ToConstant(pop).ToInt32(); } else { Register pop_reg = g.ToRegister(pop); __ sll(pop_reg, pop_reg, kPointerSizeLog2); __ Addu(sp, sp, Operand(pop_reg)); } if (pop_count != 0) { __ DropAndRet(pop_count); } else { __ Ret(); } } void CodeGenerator::FinishCode() {} void CodeGenerator::AssembleMove(InstructionOperand* source, InstructionOperand* destination) { MipsOperandConverter g(this, nullptr); // Dispatch on the source and destination operand kinds. Not all // combinations are possible. if (source->IsRegister()) { DCHECK(destination->IsRegister() || destination->IsStackSlot()); Register src = g.ToRegister(source); if (destination->IsRegister()) { __ mov(g.ToRegister(destination), src); } else { __ sw(src, g.ToMemOperand(destination)); } } else if (source->IsStackSlot()) { DCHECK(destination->IsRegister() || destination->IsStackSlot()); MemOperand src = g.ToMemOperand(source); if (destination->IsRegister()) { __ lw(g.ToRegister(destination), src); } else { Register temp = kScratchReg; __ lw(temp, src); __ sw(temp, g.ToMemOperand(destination)); } } else if (source->IsConstant()) { Constant src = g.ToConstant(source); if (destination->IsRegister() || destination->IsStackSlot()) { Register dst = destination->IsRegister() ? g.ToRegister(destination) : kScratchReg; switch (src.type()) { case Constant::kInt32: if (RelocInfo::IsWasmReference(src.rmode())) { __ li(dst, Operand(src.ToInt32(), src.rmode())); } else { __ li(dst, Operand(src.ToInt32())); } break; case Constant::kFloat32: __ li(dst, Operand::EmbeddedNumber(src.ToFloat32())); break; case Constant::kInt64: UNREACHABLE(); break; case Constant::kFloat64: __ li(dst, Operand::EmbeddedNumber(src.ToFloat64().value())); break; case Constant::kExternalReference: __ li(dst, src.ToExternalReference()); break; case Constant::kDelayedStringConstant: __ li(dst, src.ToDelayedStringConstant()); break; case Constant::kHeapObject: { Handle<HeapObject> src_object = src.ToHeapObject(); RootIndex index; if (IsMaterializableFromRoot(src_object, &index)) { __ LoadRoot(dst, index); } else { __ li(dst, src_object); } break; } case Constant::kRpoNumber: UNREACHABLE(); // TODO(titzer): loading RPO numbers on mips. break; } if (destination->IsStackSlot()) __ sw(dst, g.ToMemOperand(destination)); } else if (src.type() == Constant::kFloat32) { if (destination->IsFPStackSlot()) { MemOperand dst = g.ToMemOperand(destination); if (bit_cast<int32_t>(src.ToFloat32()) == 0) { __ sw(zero_reg, dst); } else { __ li(kScratchReg, Operand(bit_cast<int32_t>(src.ToFloat32()))); __ sw(kScratchReg, dst); } } else { DCHECK(destination->IsFPRegister()); FloatRegister dst = g.ToSingleRegister(destination); __ Move(dst, src.ToFloat32()); } } else { DCHECK_EQ(Constant::kFloat64, src.type()); DoubleRegister dst = destination->IsFPRegister() ? g.ToDoubleRegister(destination) : kScratchDoubleReg; __ Move(dst, src.ToFloat64().value()); if (destination->IsFPStackSlot()) { __ Sdc1(dst, g.ToMemOperand(destination)); } } } else if (source->IsFPRegister()) { MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (rep == MachineRepresentation::kSimd128) { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); MSARegister src = g.ToSimd128Register(source); if (destination->IsSimd128Register()) { MSARegister dst = g.ToSimd128Register(destination); __ move_v(dst, src); } else { DCHECK(destination->IsSimd128StackSlot()); __ st_b(src, g.ToMemOperand(destination)); } } else { FPURegister src = g.ToDoubleRegister(source); if (destination->IsFPRegister()) { FPURegister dst = g.ToDoubleRegister(destination); __ Move(dst, src); } else { DCHECK(destination->IsFPStackSlot()); MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (rep == MachineRepresentation::kFloat64) { __ Sdc1(src, g.ToMemOperand(destination)); } else if (rep == MachineRepresentation::kFloat32) { __ swc1(src, g.ToMemOperand(destination)); } else { UNREACHABLE(); } } } } else if (source->IsFPStackSlot()) { DCHECK(destination->IsFPRegister() || destination->IsFPStackSlot()); MemOperand src = g.ToMemOperand(source); MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (destination->IsFPRegister()) { if (rep == MachineRepresentation::kFloat64) { __ Ldc1(g.ToDoubleRegister(destination), src); } else if (rep == MachineRepresentation::kFloat32) { __ lwc1(g.ToDoubleRegister(destination), src); } else { DCHECK_EQ(MachineRepresentation::kSimd128, rep); CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); __ ld_b(g.ToSimd128Register(destination), src); } } else { FPURegister temp = kScratchDoubleReg; if (rep == MachineRepresentation::kFloat64) { __ Ldc1(temp, src); __ Sdc1(temp, g.ToMemOperand(destination)); } else if (rep == MachineRepresentation::kFloat32) { __ lwc1(temp, src); __ swc1(temp, g.ToMemOperand(destination)); } else { DCHECK_EQ(MachineRepresentation::kSimd128, rep); CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); MSARegister temp = kSimd128ScratchReg; __ ld_b(temp, src); __ st_b(temp, g.ToMemOperand(destination)); } } } else { UNREACHABLE(); } } void CodeGenerator::AssembleSwap(InstructionOperand* source, InstructionOperand* destination) { MipsOperandConverter g(this, nullptr); // Dispatch on the source and destination operand kinds. Not all // combinations are possible. if (source->IsRegister()) { // Register-register. Register temp = kScratchReg; Register src = g.ToRegister(source); if (destination->IsRegister()) { Register dst = g.ToRegister(destination); __ Move(temp, src); __ Move(src, dst); __ Move(dst, temp); } else { DCHECK(destination->IsStackSlot()); MemOperand dst = g.ToMemOperand(destination); __ mov(temp, src); __ lw(src, dst); __ sw(temp, dst); } } else if (source->IsStackSlot()) { DCHECK(destination->IsStackSlot()); Register temp_0 = kScratchReg; Register temp_1 = kScratchReg2; MemOperand src = g.ToMemOperand(source); MemOperand dst = g.ToMemOperand(destination); __ lw(temp_0, src); __ lw(temp_1, dst); __ sw(temp_0, dst); __ sw(temp_1, src); } else if (source->IsFPRegister()) { if (destination->IsFPRegister()) { MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (rep == MachineRepresentation::kSimd128) { CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); MSARegister temp = kSimd128ScratchReg; MSARegister src = g.ToSimd128Register(source); MSARegister dst = g.ToSimd128Register(destination); __ move_v(temp, src); __ move_v(src, dst); __ move_v(dst, temp); } else { FPURegister temp = kScratchDoubleReg; FPURegister src = g.ToDoubleRegister(source); FPURegister dst = g.ToDoubleRegister(destination); __ Move(temp, src); __ Move(src, dst); __ Move(dst, temp); } } else { DCHECK(destination->IsFPStackSlot()); MemOperand dst = g.ToMemOperand(destination); MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (rep == MachineRepresentation::kFloat64) { FPURegister temp = kScratchDoubleReg; FPURegister src = g.ToDoubleRegister(source); __ Move(temp, src); __ Ldc1(src, dst); __ Sdc1(temp, dst); } else if (rep == MachineRepresentation::kFloat32) { FPURegister temp = kScratchDoubleReg; FPURegister src = g.ToFloatRegister(source); __ Move(temp, src); __ lwc1(src, dst); __ swc1(temp, dst); } else { DCHECK_EQ(MachineRepresentation::kSimd128, rep); CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); MSARegister temp = kSimd128ScratchReg; MSARegister src = g.ToSimd128Register(source); __ move_v(temp, src); __ ld_b(src, dst); __ st_b(temp, dst); } } } else if (source->IsFPStackSlot()) { DCHECK(destination->IsFPStackSlot()); Register temp_0 = kScratchReg; FPURegister temp_1 = kScratchDoubleReg; MemOperand src0 = g.ToMemOperand(source); MemOperand dst0 = g.ToMemOperand(destination); MachineRepresentation rep = LocationOperand::cast(source)->representation(); if (rep == MachineRepresentation::kFloat64) { MemOperand src1(src0.rm(), src0.offset() + kIntSize); MemOperand dst1(dst0.rm(), dst0.offset() + kIntSize); __ Ldc1(temp_1, dst0); // Save destination in temp_1. __ lw(temp_0, src0); // Then use temp_0 to copy source to destination. __ sw(temp_0, dst0); __ lw(temp_0, src1); __ sw(temp_0, dst1); __ Sdc1(temp_1, src0); } else if (rep == MachineRepresentation::kFloat32) { __ lwc1(temp_1, dst0); // Save destination in temp_1. __ lw(temp_0, src0); // Then use temp_0 to copy source to destination. __ sw(temp_0, dst0); __ swc1(temp_1, src0); } else { DCHECK_EQ(MachineRepresentation::kSimd128, rep); MemOperand src1(src0.rm(), src0.offset() + kIntSize); MemOperand dst1(dst0.rm(), dst0.offset() + kIntSize); MemOperand src2(src0.rm(), src0.offset() + 2 * kIntSize); MemOperand dst2(dst0.rm(), dst0.offset() + 2 * kIntSize); MemOperand src3(src0.rm(), src0.offset() + 3 * kIntSize); MemOperand dst3(dst0.rm(), dst0.offset() + 3 * kIntSize); CpuFeatureScope msa_scope(tasm(), MIPS_SIMD); MSARegister temp_1 = kSimd128ScratchReg; __ ld_b(temp_1, dst0); // Save destination in temp_1. __ lw(temp_0, src0); // Then use temp_0 to copy source to destination. __ sw(temp_0, dst0); __ lw(temp_0, src1); __ sw(temp_0, dst1); __ lw(temp_0, src2); __ sw(temp_0, dst2); __ lw(temp_0, src3); __ sw(temp_0, dst3); __ st_b(temp_1, src0); } } else { // No other combinations are possible. UNREACHABLE(); } } void CodeGenerator::AssembleJumpTable(Label** targets, size_t target_count) { // On 32-bit MIPS we emit the jump tables inline. UNREACHABLE(); } #undef __ } // namespace compiler } // namespace internal } // namespace v8
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #pragma once #include "ngraph/axis_set.hpp" #include "ngraph/op/op.hpp" #include "ngraph/op/util/attr_types.hpp" #include "ngraph/op/util/broadcast_base.hpp" namespace ngraph { namespace op { namespace v3 { /// \brief Operation which "adds" axes to an input tensor, replicating elements from the /// input as needed along the new axes. class NGRAPH_API Broadcast : public util::BroadcastBase { public: static constexpr NodeTypeInfo type_info{"Broadcast", 3}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a broadcast operation. Broadcast() = default; /// \brief Constructs a broadcast operation. /// /// \param arg The input tensor to be broadcast. /// \param target_shape The shape of the output tensor. /// \param axes_mapping The axis positions (0-based) in the result that correspond /// to input axes. 'Arg' tensor is broadcast along the /// remaining axes. /// E.g., Input Shape - [3, 4], Target Shape - [3, 5, 4, 4] /// axes_mapping - [0, 2] => Broadcast along axes 1 and 3. /// axes_mapping - [0, 3] => Broadcast along axes 1 and 2. /// \param broadcast_spec Broadcast specification to use for determining broadcast /// axes. 'axes_mapping' should not be provided if mode other /// than explicit (none) is used. Broadcast(const Output<Node>& arg, const Output<Node>& target_shape, const Output<Node>& axes_mapping, const BroadcastModeSpec& broadcast_spec = BroadcastType::EXPLICIT); /// \brief Constructs a broadcast operation. /// /// \param arg The input tensor to be broadcast. /// \param target_shape The shape of the output tensor. /// \param broadcast_spec Broadcast specification to use for determining broadcast /// axes Broadcast(const Output<Node>& arg, const Output<Node>& target_shape, const BroadcastModeSpec& broadcast_spec = BroadcastType::NUMPY); bool visit_attributes(AttributeVisitor& visitor) override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; // \return Broadcast Specification. const BroadcastModeSpec& get_broadcast_spec() const { return m_mode; } void set_broadcast_spec(const BroadcastModeSpec& broadcast_spec) { m_mode = broadcast_spec; } void validate_and_infer_types() override; /// \return true and the AxisSet if broadcast axes can be fully determined. std::pair<bool, AxisSet> get_broadcast_axes() const override; bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override; }; } // namespace v3 namespace v1 { /// \brief Operation which "adds" axes to an input tensor, replicating elements from the /// input as needed along the new axes. class NGRAPH_API Broadcast : public util::BroadcastBase { public: static constexpr NodeTypeInfo type_info{"Broadcast", 1}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a broadcast operation. Broadcast() = default; /// \brief Constructs a broadcast operation. /// /// \param arg The input tensor to be broadcast. /// \param target_shape The shape of the output tensor. /// \param axes_mapping The axis positions (0-based) in the result that correspond /// to input axes. 'Arg' tensor is broadcast along the /// remaining axes. /// E.g., Input Shape - [3, 4], Target Shape - [3, 5, 4, 4] /// axes_mapping - [0, 2] => Broadcast along axes 1 and 3. /// axes_mapping - [0, 3] => Broadcast along axes 1 and 2. /// \param broadcast_spec Broadcast specification to use for determining broadcast /// axes. 'axes_mapping' is ignored if broadcast_spec is not /// NONE Broadcast(const Output<Node>& arg, const Output<Node>& target_shape, const Output<Node>& axes_mapping, const AutoBroadcastSpec& broadcast_spec = AutoBroadcastSpec()); /// \brief Constructs a broadcast operation. /// /// \param arg The input tensor to be broadcast. /// \param target_shape The shape of the output tensor. /// \param broadcast_spec Broadcast specification to use for determining broadcast /// axes Broadcast(const Output<Node>& arg, const Output<Node>& target_shape, const AutoBroadcastSpec& broadcast_spec = AutoBroadcastSpec(AutoBroadcastType::NUMPY)); bool visit_attributes(AttributeVisitor& visitor) override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; /// \return Broadcast Specification. const AutoBroadcastSpec& get_broadcast_spec() const { return m_broadcast_spec; } void set_broadcast_spec(const AutoBroadcastSpec& broadcast_spec) { m_broadcast_spec = broadcast_spec; } void validate_and_infer_types() override; bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override; protected: AutoBroadcastSpec m_broadcast_spec; }; } // namespace v1 namespace v0 { NGRAPH_SUPPRESS_DEPRECATED_START /// \brief Operation which "adds" axes to an input tensor, replicating elements from the /// input as needed along the new axes. class NGRAPH_DEPRECATED( "This operation is deprecated and will be removed soon. " "Use v1::Broadcast instead of it.") NGRAPH_API Broadcast : public Op { public: static constexpr NodeTypeInfo type_info{"Broadcast", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Constructs a broadcast operation. Broadcast() = default; /// \brief Constructs a broadcast operation. /// /// \param arg The input tensor to be broadcast. /// \param shape The shape of the output tensor. /// \param broadcast_axes The axis positions (0-based) in the result that are being /// broadcast. The remaining axes in shape must be the same as /// the shape of arg. Broadcast(const Output<Node>& arg, const Shape& shape, const AxisSet& broadcast_axes); bool visit_attributes(AttributeVisitor& visitor) override; void validate_and_infer_types() override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; /// \return A set containing the indices of the broadcast axes (0-based). const AxisSet& get_broadcast_axes() const { return m_broadcast_axes; } void set_broadcast_axes(const AxisSet& broadcast_axes) { m_broadcast_axes = broadcast_axes; } const Shape& get_broadcast_shape() const { return m_shape; } void set_broadcast_shape(const Shape& shape) { m_shape = shape; } bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override; protected: Broadcast(const OutputVector& args, const Shape& shape, const AxisSet& broadcast_axes); virtual void infer_shape() {} Shape m_shape; AxisSet m_broadcast_axes; }; /// \brief Broadcast arg to the same shape as like_arg. class NGRAPH_DEPRECATED( "This operation is deprecated and will be removed soon. Please don't use it.") NGRAPH_API BroadcastLike : public v0::Broadcast { public: static constexpr NodeTypeInfo type_info{"BroadcastLike", 0}; const NodeTypeInfo& get_type_info() const override { return type_info; } /// \brief Broadcast arg to the same shape as like_arg. BroadcastLike() = default; /// \brief Broadcast arg to the same shape as like_arg. /// /// Once the shape of like_arg is known, this op will be replaced with an equivalent /// Broadcast op. /// /// \param arg The argument to be broadcast. /// \param like_arg Provides the shape for the result. /// \param initial_broadcast_axes indicates which axes will be broadcast. If empty, /// arg must be scalar and all axes are broadcast. BroadcastLike(const Output<Node>& arg, const Output<Node>& like_arg, const AxisSet& initial_broadcast_axes); bool visit_attributes(AttributeVisitor& visitor) override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; void infer_shape() override; const AxisSet& get_initial_broadcast_axes() const { return m_initial_broadcast_axes; } void set_initial_broadcast_axes(const AxisSet& initial_broadcast_axes) { m_initial_broadcast_axes = initial_broadcast_axes; } protected: AxisSet m_initial_broadcast_axes; }; NGRAPH_SUPPRESS_DEPRECATED_END } // namespace v0 NGRAPH_SUPPRESS_DEPRECATED_START using v0::Broadcast; using v0::BroadcastLike; NGRAPH_SUPPRESS_DEPRECATED_END } }
// Copyright 2019 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 "sandboxed_api/sandbox2/mounts.h" #include <unistd.h> #include <utility> #include "gmock/gmock.h" #include "gtest/gtest.h" #include "absl/strings/match.h" #include "absl/strings/str_cat.h" #include "sandboxed_api/testing.h" #include "sandboxed_api/util/file_helpers.h" #include "sandboxed_api/util/path.h" #include "sandboxed_api/util/status_matchers.h" #include "sandboxed_api/util/temp_file.h" namespace sandbox2 { namespace { namespace file = ::sapi::file; using ::sapi::CreateNamedTempFileAndClose; using ::sapi::CreateTempDir; using ::sapi::GetTestSourcePath; using ::sapi::GetTestTempPath; using ::sapi::IsOk; using ::sapi::StatusIs; using ::testing::Eq; using ::testing::UnorderedElementsAreArray; constexpr size_t kTmpfsSize = 1024; TEST(MountTreeTest, TestInvalidFilenames) { Mounts mounts; EXPECT_THAT(mounts.AddFile(""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFile("a"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt("/a", ""), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt("", "/a"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt("/a", "a"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFile("/"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt("/a", "/"), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(MountTreeTest, TestAddFile) { Mounts mounts; EXPECT_THAT(mounts.AddFile("/a"), IsOk()); EXPECT_THAT(mounts.AddFile("/b"), IsOk()); EXPECT_THAT(mounts.AddFile("/c/d"), IsOk()); EXPECT_THAT(mounts.AddFile("/c/e"), IsOk()); EXPECT_THAT(mounts.AddFile("/c/dd/e"), IsOk()); EXPECT_THAT(mounts.AddFileAt("/a", "/f"), IsOk()); } TEST(MountTreeTest, TestAddDir) { Mounts mounts; EXPECT_THAT(mounts.AddDirectoryAt("/a", "/a"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt("/c/d", "/c/d"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt("/c/d/e", "/c/d/e"), IsOk()); } TEST(MountTreeTest, TestAddTmpFs) { Mounts mounts; EXPECT_THAT(mounts.AddTmpfs("/a", kTmpfsSize), IsOk()); EXPECT_THAT(mounts.AddTmpfs("/a/b", kTmpfsSize), IsOk()); EXPECT_THAT(mounts.AddFile("/a/b/c"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt("/a/b/d", "/a/b/d"), IsOk()); } TEST(MountTreeTest, TestMultipleInsertionFileSymlink) { Mounts mounts; SAPI_ASSERT_OK_AND_ASSIGN(std::string path, CreateNamedTempFileAndClose( file::JoinPath(GetTestTempPath(), "testdir_"))); SAPI_ASSERT_OK_AND_ASSIGN(std::string symlink_path, CreateNamedTempFileAndClose( file::JoinPath(GetTestTempPath(), "testdir_"))); ASSERT_THAT(unlink(symlink_path.c_str()), Eq(0)); ASSERT_THAT(symlink(path.c_str(), symlink_path.c_str()), Eq(0)); EXPECT_THAT(mounts.AddFileAt(path, "/a"), IsOk()); EXPECT_THAT(mounts.AddFileAt(path, "/a"), IsOk()); EXPECT_THAT(mounts.AddFileAt(symlink_path, "/a"), IsOk()); } TEST(MountTreeTest, TestMultipleInsertionDirSymlink) { Mounts mounts; SAPI_ASSERT_OK_AND_ASSIGN( std::string path, CreateTempDir(file::JoinPath(GetTestTempPath(), "testdir_"))); SAPI_ASSERT_OK_AND_ASSIGN(std::string symlink_path, CreateNamedTempFileAndClose( file::JoinPath(GetTestTempPath(), "testdir_"))); ASSERT_THAT(unlink(symlink_path.c_str()), Eq(0)); ASSERT_THAT(symlink(path.c_str(), symlink_path.c_str()), Eq(0)); EXPECT_THAT(mounts.AddDirectoryAt(path, "/a"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt(path, "/a"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt(symlink_path, "/a"), IsOk()); EXPECT_THAT(mounts.AddDirectoryAt(symlink_path, "/a"), IsOk()); } TEST(MountTreeTest, TestMultipleInsertion) { Mounts mounts; EXPECT_THAT(mounts.AddFile("/c/d"), IsOk()); EXPECT_THAT(mounts.AddFile("/c"), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(mounts.AddFileAt("/f", "/c"), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(mounts.AddDirectoryAt("/f", "/c"), IsOk()); EXPECT_THAT(mounts.AddFile("/c/d/e"), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(mounts.AddFileAt("/f", "/c/d/e"), StatusIs(absl::StatusCode::kFailedPrecondition)); EXPECT_THAT(mounts.AddDirectoryAt("/f", "/c/d/e"), StatusIs(absl::StatusCode::kFailedPrecondition)); } TEST(MountTreeTest, TestEvilNullByte) { Mounts mounts; // create the filename with a null byte this way as g4 fix forces newlines // otherwise. std::string filename = "/a/b"; filename[2] = '\0'; EXPECT_THAT(mounts.AddFile(filename), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt(filename, "/a"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddFileAt("/a", filename), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddDirectoryAt(filename, "/a"), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddDirectoryAt("/a", filename), StatusIs(absl::StatusCode::kInvalidArgument)); EXPECT_THAT(mounts.AddTmpfs(filename, kTmpfsSize), StatusIs(absl::StatusCode::kInvalidArgument)); } TEST(MountTreeTest, TestMinimalDynamicBinary) { Mounts mounts; EXPECT_THAT(mounts.AddMappingsForBinary( GetTestSourcePath("sandbox2/testcases/minimal_dynamic")), IsOk()); EXPECT_THAT(mounts.AddFile("/lib/x86_64-linux-gnu/libc.so.6"), IsOk()); } TEST(MountTreeTest, TestList) { struct TestCase { const char *path; const bool is_ro; }; // clang-format off const TestCase test_cases[] = { // NOTE: Directories have a trailing '/'; files don't. {"/a/b", true}, {"/a/c/", true}, {"/a/c/d/e/f/g", true}, {"/h", true}, {"/i/j/k", false}, {"/i/l/", false}, }; // clang-format on Mounts mounts; // Create actual directories and files on disk and selectively add for (const auto &test_case : test_cases) { const auto inside_path = test_case.path; const std::string outside_path = absl::StrCat("/some/dir/", inside_path); if (absl::EndsWith(outside_path, "/")) { ASSERT_THAT( mounts.AddDirectoryAt(file::CleanPath(outside_path), file::CleanPath(inside_path), test_case.is_ro), IsOk()); } else { ASSERT_THAT( mounts.AddFileAt(file::CleanPath(outside_path), file::CleanPath(inside_path), test_case.is_ro), IsOk()); } } ASSERT_THAT(mounts.AddTmpfs(file::CleanPath("/d"), 1024 * 1024), IsOk()); std::vector<std::string> outside_entries; std::vector<std::string> inside_entries; mounts.RecursivelyListMounts(&outside_entries, &inside_entries); // clang-format off EXPECT_THAT( inside_entries, UnorderedElementsAreArray({ "R /a/b", "R /a/c/", "R /a/c/d/e/f/g", "R /h", "W /i/j/k", "W /i/l/", "/d", })); EXPECT_THAT( outside_entries, UnorderedElementsAreArray({ absl::StrCat("/some/dir/", "a/b"), absl::StrCat("/some/dir/", "a/c/"), absl::StrCat("/some/dir/", "a/c/d/e/f/g"), absl::StrCat("/some/dir/", "h"), absl::StrCat("/some/dir/", "i/j/k"), absl::StrCat("/some/dir/", "i/l/"), absl::StrCat("tmpfs: size=", 1024*1024), })); // clang-format on } } // namespace } // namespace sandbox2
/**************************************************************************** ** ** Copyright (C) 2021 Intel Corporation ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** of this software and associated documentation files (the "Software"), to deal ** in the Software without restriction, including without limitation the rights ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** copies of the Software, and to permit persons to whom the Software is ** furnished to do so, subject to the following conditions: ** ** The above copyright notice and this permission notice shall be included in ** all copies or substantial portions of the Software. ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ** THE SOFTWARE. ** ****************************************************************************/ #include <QtTest> #include <limits> #include <cbor.h> Q_DECLARE_METATYPE(CborError) template <size_t N> QByteArray raw(const char (&data)[N]) { return QByteArray::fromRawData(data, N - 1); } void addIntegers() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<quint64>("expectedRaw"); QTest::addColumn<qint64>("expectedValue"); QTest::addColumn<bool>("isNegative"); QTest::addColumn<bool>("inInt64Range"); // unsigned integers QTest::newRow("0") << raw("\x00") << Q_UINT64_C(0) << Q_INT64_C(0) << false << true; QTest::newRow("1") << raw("\x01") << Q_UINT64_C(1) << Q_INT64_C(1) << false << true; QTest::newRow("10") << raw("\x0a") << Q_UINT64_C(10) << Q_INT64_C(10) << false << true; QTest::newRow("23") << raw("\x17") << Q_UINT64_C(23) << Q_INT64_C(23) << false << true; QTest::newRow("24") << raw("\x18\x18") << Q_UINT64_C(24) << Q_INT64_C(24) << false << true; QTest::newRow("UINT8_MAX") << raw("\x18\xff") << Q_UINT64_C(255) << Q_INT64_C(255) << false << true; QTest::newRow("UINT8_MAX+1") << raw("\x19\x01\x00") << Q_UINT64_C(256) << Q_INT64_C(256) << false << true; QTest::newRow("UINT16_MAX") << raw("\x19\xff\xff") << Q_UINT64_C(65535) << Q_INT64_C(65535) << false << true; QTest::newRow("UINT16_MAX+1") << raw("\x1a\0\1\x00\x00") << Q_UINT64_C(65536) << Q_INT64_C(65536) << false << true; QTest::newRow("UINT32_MAX") << raw("\x1a\xff\xff\xff\xff") << Q_UINT64_C(4294967295) << Q_INT64_C(4294967295) << false << true; QTest::newRow("UINT32_MAX+1") << raw("\x1b\0\0\0\1\0\0\0\0") << Q_UINT64_C(4294967296) << Q_INT64_C(4294967296) << false << true; QTest::newRow("INT64_MAX") << raw("\x1b" "\x7f\xff\xff\xff" "\xff\xff\xff\xff") << quint64(std::numeric_limits<qint64>::max()) << std::numeric_limits<qint64>::max() << false << true; QTest::newRow("UINT64_MAX") << raw("\x1b" "\xff\xff\xff\xff" "\xff\xff\xff\xff") << std::numeric_limits<quint64>::max() << qint64(-123456) << false << false; // negative integers QTest::newRow("-1") << raw("\x20") << Q_UINT64_C(0) << Q_INT64_C(-1) << true << true; QTest::newRow("-2") << raw("\x21") << Q_UINT64_C(1) << Q_INT64_C(-2) << true << true; QTest::newRow("-24") << raw("\x37") << Q_UINT64_C(23) << Q_INT64_C(-24) << true << true; QTest::newRow("-25") << raw("\x38\x18") << Q_UINT64_C(24) << Q_INT64_C(-25) << true << true; QTest::newRow("-UINT8_MAX") << raw("\x38\xff") << Q_UINT64_C(255) << Q_INT64_C(-256) << true << true; QTest::newRow("-UINT8_MAX-1") << raw("\x39\x01\x00") << Q_UINT64_C(256) << Q_INT64_C(-257) << true << true; QTest::newRow("-UINT16_MAX") << raw("\x39\xff\xff") << Q_UINT64_C(65535) << Q_INT64_C(-65536) << true << true; QTest::newRow("-UINT16_MAX-1") << raw("\x3a\0\1\x00\x00") << Q_UINT64_C(65536) << Q_INT64_C(-65537) << true << true; QTest::newRow("-UINT32_MAX") << raw("\x3a\xff\xff\xff\xff") << Q_UINT64_C(4294967295) << Q_INT64_C(-4294967296) << true << true; QTest::newRow("-UINT32_MAX-1") << raw("\x3b\0\0\0\1\0\0\0\0") << Q_UINT64_C(4294967296) << Q_INT64_C(-4294967297) << true << true; QTest::newRow("INT64_MIN+1") << raw("\x3b\x7f\xff\xff\xff""\xff\xff\xff\xfe") << quint64(std::numeric_limits<qint64>::max() - 1) << (std::numeric_limits<qint64>::min() + 1) << true << true; QTest::newRow("INT64_MIN") << raw("\x3b\x7f\xff\xff\xff""\xff\xff\xff\xff") << quint64(std::numeric_limits<qint64>::max()) << std::numeric_limits<qint64>::min() << true << true; QTest::newRow("INT64_MIN-1") << raw("\x3b\x80\0\0\0""\0\0\0\0") << Q_UINT64_C(9223372036854775808) << qint64(-123456) << true << false; QTest::newRow("-UINT64_MAX") << raw("\x3b" "\xff\xff\xff\xff" "\xff\xff\xff\xfe") << (std::numeric_limits<quint64>::max() - 1) << qint64(-123456) << true << false; QTest::newRow("-UINT64_MAX+1") << raw("\x3b" "\xff\xff\xff\xff" "\xff\xff\xff\xff") << std::numeric_limits<quint64>::max() << qint64(-123456) << true << false; } void addColumns() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<QString>("expected"); QTest::addColumn<int>("n"); // some aux integer, not added in all columns } void addFixedData() { // unsigned integers QTest::newRow("0") << raw("\x00") << "0"; QTest::newRow("1") << raw("\x01") << "1"; QTest::newRow("10") << raw("\x0a") << "10"; QTest::newRow("23") << raw("\x17") << "23"; QTest::newRow("24") << raw("\x18\x18") << "24"; QTest::newRow("UINT8_MAX") << raw("\x18\xff") << "255"; QTest::newRow("UINT8_MAX+1") << raw("\x19\x01\x00") << "256"; QTest::newRow("UINT16_MAX") << raw("\x19\xff\xff") << "65535"; QTest::newRow("UINT16_MAX+1") << raw("\x1a\0\1\x00\x00") << "65536"; QTest::newRow("UINT32_MAX") << raw("\x1a\xff\xff\xff\xff") << "4294967295"; QTest::newRow("UINT32_MAX+1") << raw("\x1b\0\0\0\1\0\0\0\0") << "4294967296"; QTest::newRow("UINT64_MAX") << raw("\x1b" "\xff\xff\xff\xff" "\xff\xff\xff\xff") << QString::number(std::numeric_limits<uint64_t>::max()); // negative integers QTest::newRow("-1") << raw("\x20") << "-1"; QTest::newRow("-2") << raw("\x21") << "-2"; QTest::newRow("-24") << raw("\x37") << "-24"; QTest::newRow("-25") << raw("\x38\x18") << "-25"; QTest::newRow("-UINT8_MAX") << raw("\x38\xff") << "-256"; QTest::newRow("-UINT8_MAX-1") << raw("\x39\x01\x00") << "-257"; QTest::newRow("-UINT16_MAX") << raw("\x39\xff\xff") << "-65536"; QTest::newRow("-UINT16_MAX-1") << raw("\x3a\0\1\x00\x00") << "-65537"; QTest::newRow("-UINT32_MAX") << raw("\x3a\xff\xff\xff\xff") << "-4294967296"; QTest::newRow("-UINT32_MAX-1") << raw("\x3b\0\0\0\1\0\0\0\0") << "-4294967297"; QTest::newRow("INT64_MIN+1") << raw("\x3b\x7f\xff\xff\xff""\xff\xff\xff\xfe") << QString::number(std::numeric_limits<int64_t>::min() + 1); QTest::newRow("INT64_MIN") << raw("\x3b\x7f\xff\xff\xff""\xff\xff\xff\xff") << QString::number(std::numeric_limits<int64_t>::min()); QTest::newRow("INT64_MIN-1") << raw("\x3b\x80\0\0\0""\0\0\0\0") << "-9223372036854775809"; QTest::newRow("-UINT64_MAX") << raw("\x3b" "\xff\xff\xff\xff" "\xff\xff\xff\xfe") << '-' + QString::number(std::numeric_limits<uint64_t>::max()); QTest::newRow("-UINT64_MAX+1") << raw("\x3b" "\xff\xff\xff\xff" "\xff\xff\xff\xff") << "-18446744073709551616"; // overlongs QTest::newRow("0*1") << raw("\x18\x00") << "0_0"; QTest::newRow("0*2") << raw("\x19\x00\x00") << "0_1"; QTest::newRow("0*4") << raw("\x1a\0\0\0\0") << "0_2"; QTest::newRow("0*8") << raw("\x1b\0\0\0\0\0\0\0\0") << "0_3"; QTest::newRow("-1*1") << raw("\x38\x00") << "-1_0"; QTest::newRow("-1*2") << raw("\x39\x00\x00") << "-1_1"; QTest::newRow("-1*4") << raw("\x3a\0\0\0\0") << "-1_2"; QTest::newRow("-1*8") << raw("\x3b\0\0\0\0\0\0\0\0") << "-1_3"; QTest::newRow("simple0") << raw("\xe0") << "simple(0)"; QTest::newRow("simple19") << raw("\xf3") << "simple(19)"; QTest::newRow("false") << raw("\xf4") << "false"; QTest::newRow("true") << raw("\xf5") << "true"; QTest::newRow("null") << raw("\xf6") << "null"; QTest::newRow("undefined") << raw("\xf7") << "undefined"; QTest::newRow("simple32") << raw("\xf8\x20") << "simple(32)"; QTest::newRow("simple255") << raw("\xf8\xff") << "simple(255)"; // floating point QTest::newRow("0.f16") << raw("\xf9\0\0") << "0.f16"; QTest::newRow("0.f") << raw("\xfa\0\0\0\0") << "0.f"; QTest::newRow("0.") << raw("\xfb\0\0\0\0\0\0\0\0") << "0."; QTest::newRow("-1.f16") << raw("\xf9\xbc\x00") << "-1.f16"; QTest::newRow("-1.f") << raw("\xfa\xbf\x80\0\0") << "-1.f"; QTest::newRow("-1.") << raw("\xfb\xbf\xf0\0\0\0\0\0\0") << "-1."; QTest::newRow("65504.f16") << raw("\xf9\x7b\xff") << "65504.f16"; QTest::newRow("16777215.f") << raw("\xfa\x4b\x7f\xff\xff") << "16777215.f"; QTest::newRow("16777215.") << raw("\xfb\x41\x6f\xff\xff\xe0\0\0\0") << "16777215."; QTest::newRow("-16777215.f") << raw("\xfa\xcb\x7f\xff\xff") << "-16777215.f"; QTest::newRow("-16777215.") << raw("\xfb\xc1\x6f\xff\xff\xe0\0\0\0") << "-16777215."; QTest::newRow("0.5f16") << raw("\xf9\x38\0") << "0.5f16"; QTest::newRow("0.5f") << raw("\xfa\x3f\0\0\0") << "0.5f"; QTest::newRow("0.5") << raw("\xfb\x3f\xe0\0\0\0\0\0\0") << "0.5"; QTest::newRow("2.f16^11-1") << raw("\xf9\x67\xff") << "2047.f16"; QTest::newRow("2.f^24-1") << raw("\xfa\x4b\x7f\xff\xff") << "16777215.f"; QTest::newRow("2.^53-1") << raw("\xfb\x43\x3f\xff\xff""\xff\xff\xff\xff") << "9007199254740991."; QTest::newRow("2.f^64-epsilon") << raw("\xfa\x5f\x7f\xff\xff") << "18446742974197923840.f"; QTest::newRow("2.^64-epsilon") << raw("\xfb\x43\xef\xff\xff""\xff\xff\xff\xff") << "18446744073709549568."; QTest::newRow("2.f^64") << raw("\xfa\x5f\x80\0\0") << "1.8446744073709552e+19f"; QTest::newRow("2.^64") << raw("\xfb\x43\xf0\0\0\0\0\0\0") << "1.8446744073709552e+19"; QTest::newRow("nan_f16") << raw("\xf9\x7e\x00") << "nan"; QTest::newRow("nan_f") << raw("\xfa\x7f\xc0\0\0") << "nan"; QTest::newRow("nan") << raw("\xfb\x7f\xf8\0\0\0\0\0\0") << "nan"; QTest::newRow("-inf_f16") << raw("\xf9\xfc\x00") << "-inf"; QTest::newRow("-inf_f") << raw("\xfa\xff\x80\0\0") << "-inf"; QTest::newRow("-inf") << raw("\xfb\xff\xf0\0\0\0\0\0\0") << "-inf"; QTest::newRow("+inf_f16") << raw("\xf9\x7c\x00") << "inf"; QTest::newRow("+inf_f") << raw("\xfa\x7f\x80\0\0") << "inf"; QTest::newRow("+inf") << raw("\xfb\x7f\xf0\0\0\0\0\0\0") << "inf"; } void addNonChunkedStringsData() { // byte strings QTest::newRow("emptybytestring") << raw("\x40") << "h''"; QTest::newRow("bytestring1") << raw("\x41 ") << "h'20'"; QTest::newRow("bytestring1-nul") << raw("\x41\0") << "h'00'"; QTest::newRow("bytestring5") << raw("\x45Hello") << "h'48656c6c6f'"; QTest::newRow("bytestring24") << raw("\x58\x18""123456789012345678901234") << "h'313233343536373839303132333435363738393031323334'"; QTest::newRow("bytestring256") << raw("\x59\1\0") + QByteArray(256, '3') << "h'" + QString(256 * 2, '3') + '\''; // text strings QTest::newRow("emptytextstring") << raw("\x60") << "\"\""; QTest::newRow("textstring1") << raw("\x61 ") << "\" \""; QTest::newRow("textstring1-nul") << raw("\x61\0") << "\"\\u0000\""; QTest::newRow("textstring5") << raw("\x65Hello") << "\"Hello\""; QTest::newRow("textstring24") << raw("\x78\x18""123456789012345678901234") << "\"123456789012345678901234\""; QTest::newRow("textstring256") << raw("\x79\1\0") + QByteArray(256, '3') << '"' + QString(256, '3') + '"'; // some strings with UTF-8 content // we had a bug in the pretty dumper - see issue #54 QTest::newRow("textstringutf8-2char") << raw("\x62\xc2\xa0") << "\"\\u00A0\""; QTest::newRow("textstringutf8-2char2") << raw("\x64\xc2\xa0\xc2\xa9") << "\"\\u00A0\\u00A9\""; QTest::newRow("textstringutf8-3char") << raw("\x63\xe2\x88\x80") << "\"\\u2200\""; QTest::newRow("textstringutf8-4char") << raw("\x64\xf0\x90\x88\x83") << "\"\\uD800\\uDE03\""; // strings with overlong length QTest::newRow("emptybytestring*1") << raw("\x58\x00") << "h''_0"; QTest::newRow("emptytextstring*1") << raw("\x78\x00") << "\"\"_0"; QTest::newRow("emptybytestring*2") << raw("\x59\x00\x00") << "h''_1"; QTest::newRow("emptytextstring*2") << raw("\x79\x00\x00") << "\"\"_1"; QTest::newRow("emptybytestring*4") << raw("\x5a\0\0\0\0") << "h''_2"; QTest::newRow("emptytextstring*4") << raw("\x7a\0\0\0\0") << "\"\"_2"; QTest::newRow("emptybytestring*8") << raw("\x5b\0\0\0\0\0\0\0\0") << "h''_3"; QTest::newRow("emptytextstring*8") << raw("\x7b\0\0\0\0\0\0\0\0") << "\"\"_3"; QTest::newRow("bytestring5*1") << raw("\x58\x05Hello") << "h'48656c6c6f'_0"; QTest::newRow("textstring5*1") << raw("\x78\x05Hello") << "\"Hello\"_0"; QTest::newRow("bytestring5*2") << raw("\x59\0\5Hello") << "h'48656c6c6f'_1"; QTest::newRow("textstring5*2") << raw("\x79\0\x05Hello") << "\"Hello\"_1"; QTest::newRow("bytestring5*4") << raw("\x5a\0\0\0\5Hello") << "h'48656c6c6f'_2"; QTest::newRow("textstring5*4") << raw("\x7a\0\0\0\x05Hello") << "\"Hello\"_2"; QTest::newRow("bytestring5*8") << raw("\x5b\0\0\0\0\0\0\0\5Hello") << "h'48656c6c6f'_3"; QTest::newRow("textstring5*8") << raw("\x7b\0\0\0\0\0\0\0\x05Hello") << "\"Hello\"_3"; } void addStringsData() { addNonChunkedStringsData(); // strings with undefined length QTest::newRow("_emptybytestring") << raw("\x5f\xff") << "(_ )"; QTest::newRow("_emptytextstring") << raw("\x7f\xff") << "(_ )"; QTest::newRow("_emptybytestring2") << raw("\x5f\x40\xff") << "(_ h'')"; QTest::newRow("_emptytextstring2") << raw("\x7f\x60\xff") << "(_ \"\")"; QTest::newRow("_emptybytestring2*1") << raw("\x5f\x58\x00\xff") << "(_ h''_0)"; QTest::newRow("_emptytextstring2*1") << raw("\x7f\x78\x00\xff") << "(_ \"\"_0)"; QTest::newRow("_emptybytestring3") << raw("\x5f\x40\x40\xff") << "(_ h'', h'')"; QTest::newRow("_emptytextstring3") << raw("\x7f\x60\x60\xff") << "(_ \"\", \"\")"; QTest::newRow("_emptybytestring3*2") << raw("\x5f\x59\x00\x00\x40\xff") << "(_ h''_1, h'')"; QTest::newRow("_emptytextstring3*2") << raw("\x7f\x79\x00\x00\x60\xff") << "(_ \"\"_1, \"\")"; QTest::newRow("_bytestring5x2") << raw("\x5f\x43Hel\x42lo\xff") << "(_ h'48656c', h'6c6f')"; QTest::newRow("_textstring5x2") << raw("\x7f\x63Hel\x62lo\xff") << "(_ \"Hel\", \"lo\")"; QTest::newRow("_bytestring5x2*8*4") << raw("\x5f\x5b\0\0\0\0\0\0\0\3Hel\x5a\0\0\0\2lo\xff") << "(_ h'48656c'_3, h'6c6f'_2)"; QTest::newRow("_textstring5x2*8*4") << raw("\x7f\x7b\0\0\0\0\0\0\0\3Hel\x7a\0\0\0\2lo\xff") << "(_ \"Hel\"_3, \"lo\"_2)"; QTest::newRow("_bytestring5x5") << raw("\x5f\x41H\x41""e\x41l\x41l\x41o\xff") << "(_ h'48', h'65', h'6c', h'6c', h'6f')"; QTest::newRow("_textstring5x5") << raw("\x7f\x61H\x61""e\x61l\x61l\x61o\xff") << "(_ \"H\", \"e\", \"l\", \"l\", \"o\")"; QTest::newRow("_bytestring5x6") << raw("\x5f\x41H\x41""e\x40\x41l\x41l\x41o\xff") << "(_ h'48', h'65', h'', h'6c', h'6c', h'6f')"; QTest::newRow("_textstring5x6") << raw("\x7f\x61H\x61""e\x61l\x60\x61l\x61o\xff") << "(_ \"H\", \"e\", \"l\", \"\", \"l\", \"o\")"; } void addTagsData() { // since parseOne() works recursively for tags, we can't test lone tags QTest::newRow("tag0") << raw("\xc0\x00") << "0(0)"; QTest::newRow("tag1") << raw("\xc1\x00") << "1(0)"; QTest::newRow("tag24") << raw("\xd8\x18\x00") << "24(0)"; QTest::newRow("tag255") << raw("\xd8\xff\x00") << "255(0)"; QTest::newRow("tag256") << raw("\xd9\1\0\x00") << "256(0)"; QTest::newRow("tag65535") << raw("\xd9\xff\xff\x00") << "65535(0)"; QTest::newRow("tag65536") << raw("\xda\0\1\0\0\x00") << "65536(0)"; QTest::newRow("tagUINT32_MAX-1") << raw("\xda\xff\xff\xff\xff\x00") << "4294967295(0)"; QTest::newRow("tagUINT32_MAX") << raw("\xdb\0\0\0\1\0\0\0\0\x00") << "4294967296(0)"; QTest::newRow("tagUINT64_MAX") << raw("\xdb" "\xff\xff\xff\xff" "\xff\xff\xff\xff" "\x00") << QString::number(std::numeric_limits<uint64_t>::max()) + "(0)"; // overlong tags QTest::newRow("tag0*1") << raw("\xd8\0\x00") << "0_0(0)"; QTest::newRow("tag0*2") << raw("\xd9\0\0\x00") << "0_1(0)"; QTest::newRow("tag0*4") << raw("\xda\0\0\0\0\x00") << "0_2(0)"; QTest::newRow("tag0*8") << raw("\xdb\0\0\0\0\0\0\0\0\x00") << "0_3(0)"; // tag other things QTest::newRow("unixtime") << raw("\xc1\x1a\x55\x4b\xbf\xd3") << "1(1431027667)"; QTest::newRow("rfc3339date") << raw("\xc0\x78\x19" "2015-05-07 12:41:07-07:00") << "0(\"2015-05-07 12:41:07-07:00\")"; QTest::newRow("tag6+false") << raw("\xc6\xf4") << "6(false)"; QTest::newRow("tag25+true") << raw("\xd8\x19\xf5") << "25(true)"; QTest::newRow("tag256+null") << raw("\xd9\1\0\xf6") << "256(null)"; QTest::newRow("tag65536+simple32") << raw("\xda\0\1\0\0\xf8\x20") << "65536(simple(32))"; QTest::newRow("float+unixtime") << raw("\xc1\xfa\x4e\xaa\x97\x80") << "1(1431027712.f)"; QTest::newRow("double+unixtime") << raw("\xc1\xfb" "\x41\xd5\x52\xef" "\xf4\xc7\xce\xfe") << "1(1431027667.1220088)"; } void addEmptyContainersData() { QTest::newRow("emptyarray") << raw("\x80") << "[]" << 0; QTest::newRow("emptymap") << raw("\xa0") << "{}" << 0; QTest::newRow("_emptyarray") << raw("\x9f\xff") << "[_ ]" << -1; QTest::newRow("_emptymap") << raw("\xbf\xff") << "{_ }" << -1; } void addMapMixedData() { QTest::newRow("map-0-24") << raw("\xa1\0\x18\x18") << "{0: 24}" << 1; QTest::newRow("map-0*1-24") << raw("\xa1\x18\0\x18\x18") << "{0_0: 24}" << 1; QTest::newRow("map-0*1-24*2") << raw("\xa1\x18\0\x19\0\x18") << "{0_0: 24_1}" << 1; QTest::newRow("map-0*4-24*2") << raw("\xa1\x1a\0\0\0\0\x19\0\x18") << "{0_2: 24_1}" << 1; QTest::newRow("map-24-0") << raw("\xa1\x18\x18\0") << "{24: 0}" << 1; QTest::newRow("map-24-0*1") << raw("\xa1\x18\x18\x18\0") << "{24: 0_0}" << 1; QTest::newRow("map-255-65535") << raw("\xa1\x18\xff\x19\xff\xff") << "{255: 65535}" << 1; QTest::newRow("_map-0-24") << raw("\xbf\0\x18\x18\xff") << "{_ 0: 24}" << 1; QTest::newRow("_map-0*1-24") << raw("\xbf\x18\0\x18\x18\xff") << "{_ 0_0: 24}" << 1; QTest::newRow("_map-0*1-24*2") << raw("\xbf\x18\0\x19\0\x18\xff") << "{_ 0_0: 24_1}" << 1; QTest::newRow("_map-0*4-24*2") << raw("\xbf\x1a\0\0\0\0\x19\0\x18\xff") << "{_ 0_2: 24_1}" << 1; QTest::newRow("_map-24-0") << raw("\xbf\x18\x18\0\xff") << "{_ 24: 0}" << 1; QTest::newRow("_map-24-0*1") << raw("\xbf\x18\x18\x18\0\xff") << "{_ 24: 0_0}" << 1; QTest::newRow("_map-255-65535") << raw("\xbf\x18\xff\x19\xff\xff\xff") << "{_ 255: 65535}" << 1; } void addChunkedStringData() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<QString>("concatenated"); QTest::addColumn<QStringList>("chunks"); // non-chunked: QTest::newRow("emptybytestring") << raw("\x40") << "h''" << QStringList{"h''"}; QTest::newRow("bytestring1") << raw("\x41 ") << "h'20'" << QStringList{"h'20'"}; QTest::newRow("emptytextstring") << raw("\x60") << "\"\"" << QStringList{"\"\""}; QTest::newRow("textstring1") << raw("\x61 ") << "\" \"" << QStringList{"\" \""}; // empty chunked: QTest::newRow("_emptybytestring") << raw("\x5f\xff") << "h''" << QStringList{}; QTest::newRow("_emptytextstring") << raw("\x7f\xff") << "\"\"" << QStringList{}; QTest::newRow("_emptybytestring2") << raw("\x5f\x40\xff") << "h''" << QStringList{"h''"}; QTest::newRow("_emptytextstring2") << raw("\x7f\x60\xff") << "\"\"" << QStringList{"\"\""}; QTest::newRow("_emptybytestring3") << raw("\x5f\x40\x40\xff") << "h''" << QStringList{"h''", "h''"}; QTest::newRow("_emptytextstring3") << raw("\x7f\x60\x60\xff") << "\"\"" << QStringList{"\"\"", "\"\""}; // regular chunks QTest::newRow("_bytestring1") << raw("\x5f\x41 \xff") << "h'20'" << QStringList{"h'20'"}; QTest::newRow("_bytestring2") << raw("\x5f\x41 \x41z\xff") << "h'207a'" << QStringList{"h'20'", "h'7a'"}; QTest::newRow("_bytestring3") << raw("\x5f\x41 \x58\x18""123456789012345678901234\x41z\xff") << "h'203132333435363738393031323334353637383930313233347a'" << QStringList{"h'20'", "h'313233343536373839303132333435363738393031323334'", "h'7a'"}; QTest::newRow("_textstring1") << raw("\x7f\x61 \xff") << "\" \"" << QStringList{"\" \""}; QTest::newRow("_textstring2") << raw("\x7f\x61 \x61z\xff") << "\" z\"" << QStringList{"\" \"", "\"z\""}; QTest::newRow("_textstring3") << raw("\x7f\x61 \x78\x18""123456789012345678901234\x61z\xff") << "\" 123456789012345678901234z\"" << QStringList{"\" \"", "\"123456789012345678901234\"", "\"z\""}; } void addValidationColumns() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<int>("flags"); // future QTest::addColumn<CborError>("expectedError"); } void addValidationData(size_t minInvalid = ~size_t(0)) { // illegal numbers are future extension points QTest::newRow("illegal-number-in-unsigned-1") << raw("\x81\x1c") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-unsigned-2") << raw("\x81\x1d") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-unsigned-3") << raw("\x81\x1e") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-unsigned-4") << raw("\x81\x1f") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-negative-1") << raw("\x81\x3c") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-negative-2") << raw("\x81\x3d") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-negative-3") << raw("\x81\x3e") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-negative-4") << raw("\x81\x3f") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-bytearray-length-1") << raw("\x81\x5c") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-bytearray-length-2") << raw("\x81\x5d") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-bytearray-length-3") << raw("\x81\x5e") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-string-length-1") << raw("\x81\x7c") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-string-length-2") << raw("\x81\x7d") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-string-length-3") << raw("\x81\x7e") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-array-length-1") << raw("\x81\x9c") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-array-length-2") << raw("\x81\x9d") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-array-length-3") << raw("\x81\x9e") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-map-length-1") << raw("\x81\xbc") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-map-length-2") << raw("\x81\xbd") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-map-length-3") << raw("\x81\xbe") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-tag-1") << raw("\x81\xdc") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-tag-2") << raw("\x81\xdd") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-tag-3") << raw("\x81\xde") << 0 << CborErrorIllegalNumber; QTest::newRow("illegal-number-in-tag-4") << raw("\x81\xdf") << 0 << CborErrorIllegalNumber; QTest::newRow("unsigned-too-short-1-0") << raw("\x81\x18") << 0 << CborErrorUnexpectedEOF; // requires 1 byte, 0 given QTest::newRow("unsigned-too-short-2-0") << raw("\x81\x19") << 0 << CborErrorUnexpectedEOF; // requires 2 bytes, 0 given QTest::newRow("unsigned-too-short-2-1") << raw("\x81\x19\x01") << 0 << CborErrorUnexpectedEOF; // etc QTest::newRow("unsigned-too-short-4-0") << raw("\x81\x1a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("unsigned-too-short-4-3") << raw("\x81\x1a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("unsigned-too-short-8-0") << raw("\x81\x1b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("unsigned-too-short-8-7") << raw("\x81\x1b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-1-0") << raw("\x81\x38") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-2-0") << raw("\x81\x39") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-2-1") << raw("\x81\x39\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-4-0") << raw("\x81\x3a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-4-3") << raw("\x81\x3a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-8-0") << raw("\x81\x3b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("negative-length-too-short-8-7") << raw("\x81\x3b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-1-0") << raw("\x81\x58") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-2-0") << raw("\x81\x59") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-2-1") << raw("\x81\x59\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-4-0") << raw("\x81\x5a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-4-3") << raw("\x81\x5a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-8-0") << raw("\x81\x5b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-length-too-short-8-7") << raw("\x81\x5b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-1-0") << raw("\x81\x78") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-2-0") << raw("\x81\x79") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-2-1") << raw("\x81\x79\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-4-0") << raw("\x81\x7a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-4-3") << raw("\x81\x7a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-8-0") << raw("\x81\x7b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-length-too-short-8-7") << raw("\x81\x7b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-1-0") << raw("\x81\x5f\x58") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-2-0") << raw("\x81\x5f\x59") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-2-1") << raw("\x81\x5f\x59\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-4-0") << raw("\x81\x5f\x5a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-4-3") << raw("\x81\x5f\x5a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-8-0") << raw("\x81\x5f\x5b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-length-too-short-8-7") << raw("\x81\x5f\x5b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-1-0") << raw("\x81\x7f\x78") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-2-0") << raw("\x81\x7f\x79") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-2-1") << raw("\x81\x7f\x79\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-4-0") << raw("\x81\x7f\x7a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-4-3") << raw("\x81\x7f\x7a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-8-0") << raw("\x81\x7f\x7b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-length-too-short-8-7") << raw("\x81\x7f\x7b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-1-0") << raw("\x81\x5f\x40\x58") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-2-0") << raw("\x81\x5f\x40\x59") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-2-1") << raw("\x81\x5f\x40\x59\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-4-0") << raw("\x81\x5f\x40\x5a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-4-3") << raw("\x81\x5f\x40\x5a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-8-0") << raw("\x81\x5f\x40\x5b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-2-length-too-short-8-7") << raw("\x81\x5f\x40\x5b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-1-0") << raw("\x81\x7f\x60\x78") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-2-0") << raw("\x81\x7f\x60\x79") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-2-1") << raw("\x81\x7f\x60\x79\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-4-0") << raw("\x81\x7f\x60\x7a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-4-3") << raw("\x81\x7f\x60\x7a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-8-0") << raw("\x81\x7f\x60\x7b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-2-length-too-short-8-7") << raw("\x81\x7f\x60\x7b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-1-0") << raw("\x81\x98") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-2-0") << raw("\x81\x99") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-2-1") << raw("\x81\x99\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-4-0") << raw("\x81\x9a") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-4-3") << raw("\x81\x9a\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-8-0") << raw("\x81\x9b") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-length-too-short-8-7") << raw("\x81\x9b\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-1-0") << raw("\x81\xb8") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-2-0") << raw("\x81\xb9") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-2-1") << raw("\x81\xb9\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-4-0") << raw("\x81\xba") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-4-3") << raw("\x81\xba\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-8-0") << raw("\x81\xbb") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-length-too-short-8-7") << raw("\x81\xbb\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-1-0") << raw("\x81\xd8") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-2-0") << raw("\x81\xd9") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-2-1") << raw("\x81\xd9\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-4-0") << raw("\x81\xda") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-4-3") << raw("\x81\xda\x01\x02\x03") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-8-0") << raw("\x81\xdb") << 0 << CborErrorUnexpectedEOF; QTest::newRow("tag-too-short-8-7") << raw("\x81\xdb\1\2\3\4\5\6\7") << 0 << CborErrorUnexpectedEOF; QTest::newRow("fp16-too-short1") << raw("\x81\xf9") << 0 << CborErrorUnexpectedEOF; QTest::newRow("fp16-too-short2") << raw("\x81\xf9\x00") << 0 << CborErrorUnexpectedEOF; QTest::newRow("float-too-short1") << raw("\x81\xfa") << 0 << CborErrorUnexpectedEOF; QTest::newRow("float-too-short2") << raw("\x81\xfa\0\0\0") << 0 << CborErrorUnexpectedEOF; QTest::newRow("double-too-short1") << raw("\x81\xfb") << 0 << CborErrorUnexpectedEOF; QTest::newRow("double-too-short2") << raw("\x81\xfb\0\0\0\0\0\0\0") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-too-short1") << raw("\x81\x42z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-too-short2") << raw("\x81\x58\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-too-short3") << raw("\x81\x5a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-too-short4") << raw("\x81\x5b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-too-short1") << raw("\x81\x62z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-too-short2") << raw("\x81\x78\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-too-short3") << raw("\x81\x7a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-too-short4") << raw("\x81\x7b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short1") << raw("\x81\x5f\x42z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short2") << raw("\x81\x5f\x58\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short3") << raw("\x81\x5f\x5a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short4") << raw("\x81\x5f\x5b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short1") << raw("\x81\x7f\x62z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short2") << raw("\x81\x7f\x78\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short3") << raw("\x81\x7f\x7a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short4") << raw("\x81\x7f\x7b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short1x2") << raw("\x81\x5f\x40\x42z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short2x2") << raw("\x81\x5f\x40\x58\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short3x2") << raw("\x81\x5f\x40\x5a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-chunked-too-short4x2") << raw("\x81\x5f\x40\x5b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short1x2") << raw("\x81\x7f\x60\x62z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short2x2") << raw("\x81\x7f\x60\x78\x02z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short3x2") << raw("\x81\x7f\x60\x7a\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-chunked-too-short4x2") << raw("\x81\x7f\x60\x7b\0\0\0\0\0\0\0\2z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-no-break1") << raw("\x81\x5f") << 0 << CborErrorUnexpectedEOF; QTest::newRow("bytearray-no-break2") << raw("\x81\x5f\x40") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-no-break1") << raw("\x81\x7f") << 0 << CborErrorUnexpectedEOF; QTest::newRow("string-no-break2") << raw("\x81\x7f\x60") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-no-break1") << raw("\x81\x9f") << 0 << CborErrorUnexpectedEOF; QTest::newRow("array-no-break2") << raw("\x81\x9f\0") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-no-break1") << raw("\x81\xbf") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-no-break2") << raw("\x81\xbf\0\0") << 0 << CborErrorUnexpectedEOF; QTest::newRow("map-break-after-key") << raw("\x81\xbf\0\xff") << 0 << CborErrorUnexpectedBreak; QTest::newRow("map-break-after-second-key") << raw("\x81\xbf\x64xyzw\x04\x00\xff") << 0 << CborErrorUnexpectedBreak; QTest::newRow("map-break-after-value-tag") << raw("\x81\xbf\0\xc0\xff") << 0 << CborErrorUnexpectedBreak; QTest::newRow("map-break-after-value-tag2") << raw("\x81\xbf\0\xd8\x20\xff") << 0 << CborErrorUnexpectedBreak; // check for pointer additions wrapping over the limit of the address space auto wraparoundError = [minInvalid](uint64_t encodedSize) { if (encodedSize > minInvalid) return CborErrorDataTooLarge; return CborErrorUnexpectedEOF; }; constexpr uint64_t FourGB = UINT32_MAX + UINT64_C(1); // on 32-bit systems, this is a -1 QTest::newRow("bytearray-wraparound1") << raw("\x81\x5a\xff\xff\xff\xff") << 0 << wraparoundError(UINT32_MAX); QTest::newRow("string-wraparound1") << raw("\x81\x7a\xff\xff\xff\xff") << 0 << wraparoundError(UINT32_MAX); // on 32-bit systems, a 4GB addition could be dropped QTest::newRow("bytearray-wraparound2") << raw("\x81\x5b\0\0\0\1\0\0\0\0") << 0 << wraparoundError(FourGB); QTest::newRow("string-wraparound2") << raw("\x81\x7b\0\0\0\1\0\0\0\0") << 0 << wraparoundError(FourGB); // on 64-bit systems, this could be a -1 QTest::newRow("bytearray-wraparound3") << raw("\x81\x5b\xff\xff\xff\xff\xff\xff\xff\xff") << 0 << wraparoundError(UINT64_MAX); QTest::newRow("string-wraparound3") << raw("\x81\x7b\xff\xff\xff\xff\xff\xff\xff\xff") << 0 << wraparoundError(UINT64_MAX); // ditto on chunks QTest::newRow("bytearray-chunk-wraparound1") << raw("\x81\x5f\x5a\xff\xff\xff\xff") << 0 << wraparoundError(UINT32_MAX); QTest::newRow("string-chunk-wraparound1") << raw("\x81\x7f\x7a\xff\xff\xff\xff") << 0 << wraparoundError(UINT32_MAX); // on 32-bit systems, a 4GB addition could be dropped QTest::newRow("bytearray-chunk-wraparound2") << raw("\x81\x5f\x5b\0\0\0\1\0\0\0\0") << 0 << wraparoundError(FourGB); QTest::newRow("string-chunk-wraparound2") << raw("\x81\x7f\x7b\0\0\0\1\0\0\0\0") << 0 << wraparoundError(FourGB); // on 64-bit systems, this could be a -1 QTest::newRow("bytearray-chunk-wraparound3") << raw("\x81\x5f\x5b\xff\xff\xff\xff\xff\xff\xff\xff") << 0 << wraparoundError(UINT64_MAX); QTest::newRow("string-chunk-wraparound3") << raw("\x81\x7f\x7b\xff\xff\xff\xff\xff\xff\xff\xff") << 0 << wraparoundError(UINT64_MAX); QTest::newRow("eof-after-array") << raw("\x81") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-array2") << raw("\x81\x78\x20") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-array-element") << raw("\x81\x82\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-object") << raw("\x81\xa1") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-object2") << raw("\x81\xb8\x20") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-object-key") << raw("\x81\xa1\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-object-value") << raw("\x81\xa2\x01\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-tag") << raw("\x81\xc0") << 0 << CborErrorUnexpectedEOF; QTest::newRow("eof-after-tag2") << raw("\x81\xd8\x20") << 0 << CborErrorUnexpectedEOF; // major type 7 has future types QTest::newRow("future-type-28") << raw("\x81\xfc") << 0 << CborErrorUnknownType; QTest::newRow("future-type-29") << raw("\x81\xfd") << 0 << CborErrorUnknownType; QTest::newRow("future-type-30") << raw("\x81\xfe") << 0 << CborErrorUnknownType; QTest::newRow("unexpected-break") << raw("\x81\xff") << 0 << CborErrorUnexpectedBreak; QTest::newRow("illegal-simple-0") << raw("\x81\xf8\0") << 0 << CborErrorIllegalSimpleType; QTest::newRow("illegal-simple-31") << raw("\x81\xf8\x1f") << 0 << CborErrorIllegalSimpleType; // not only too big (UINT_MAX or UINT_MAX+1 in size), but also incomplete if (sizeof(size_t) < sizeof(uint64_t)) { QTest::newRow("bytearray-too-big1") << raw("\x81\x5b\0\0\0\1\0\0\0\0") << 0 << CborErrorDataTooLarge; QTest::newRow("string-too-big1") << raw("\x81\x7b\0\0\0\1\0\0\0\0") << 0 << CborErrorDataTooLarge; } QTest::newRow("array-too-big1") << raw("\x81\x9a\xff\xff\xff\xff\0\0\0\0") << 0 << CborErrorDataTooLarge; QTest::newRow("array-too-big2") << raw("\x81\x9b\0\0\0\1\0\0\0\0") << 0 << CborErrorDataTooLarge; QTest::newRow("object-too-big1") << raw("\x81\xba\xff\xff\xff\xff\0\0\0\0") << 0 << CborErrorDataTooLarge; QTest::newRow("object-too-big2") << raw("\x81\xbb\0\0\0\1\0\0\0\0") << 0 << CborErrorDataTooLarge; QTest::newRow("no-break-for-array0") << raw("\x81\x9f") << 0 << CborErrorUnexpectedEOF; QTest::newRow("no-break-for-array1") << raw("\x81\x9f\x01") << 0 << CborErrorUnexpectedEOF; QTest::newRow("no-break-string0") << raw("\x81\x7f") << 0 << CborErrorUnexpectedEOF; QTest::newRow("no-break-string1") << raw("\x81\x7f\x61Z") << 0 << CborErrorUnexpectedEOF; QTest::newRow("nested-indefinite-length-bytearrays") << raw("\x81\x5f\x5f\xff\xff") << 0 << CborErrorIllegalNumber; QTest::newRow("nested-indefinite-length-strings") << raw("\x81\x7f\x7f\xff\xff") << 0 << CborErrorIllegalNumber; QTest::newRow("string-chunk-unsigned") << raw("\x81\x7f\0\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-negative") << raw("\x81\x7f\x20\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-bytearray") << raw("\x81\x7f\x40\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-array") << raw("\x81\x7f\x80\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-map") << raw("\x81\x7f\xa0\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-tag") << raw("\x81\x7f\xc0\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-tagged-string") << raw("\x81\x7f\xc0\x60\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-simple0") << raw("\x81\x7f\xe0\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-false") << raw("\x81\x7f\xf4\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-true") << raw("\x81\x7f\xf5\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-null") << raw("\x81\x7f\xf6\xff") << 0 << CborErrorIllegalType; QTest::newRow("string-chunk-undefined") << raw("\x81\x7f\xf7\xff") << 0 << CborErrorIllegalType; QTest::newRow("bytearray-chunk-string") << raw("\x81\x5f\x60\xff") << 0 << CborErrorIllegalType; QTest::newRow("bytearray-chunk-tagged-bytearray") << raw("\x81\x7f\xc0\x40\xff") << 0 << CborErrorIllegalType; // RFC 7049 Section 2.2.2 "Indefinite-Length Byte Strings and Text Strings" says // Text strings with indefinite lengths act the same as byte strings // with indefinite lengths, except that all their chunks MUST be // definite-length text strings. Note that this implies that the bytes // of a single UTF-8 character cannot be spread between chunks: a new // chunk can only be started at a character boundary. // This test technically tests the dumper, not the parser. QTest::newRow("string-utf8-chunk-split") << raw("\x81\x7f\x61\xc2\x61\xa0\xff") << 0 << CborErrorInvalidUtf8TextString; }
/*** KNOWLEDGE IS POWER ***/ #include<bits/stdc++.h> using namespace std; //=======================================// struct Node { char data ; struct Node *left, *right ; } ; Node* newNode(char val) // Assigning value to a newly created node { Node *temp = new Node ; temp->left = temp->right = NULL ; temp->data = val ; return temp ; }; bool isOperator(char c) { if(c == '+' || c == '-' || c == '*' || c == '/' || c == '^') { return true ; } return false ; } //=======================================// //========== NON-RECURSIVE ==========// void inorder_withoutRec(Node* t) { Node* temp = t ; stack<Node*> s ; while(temp) { s.push(temp) ; temp = temp->left ; } while(!s.empty()) { temp = s.top() ; s.pop() ; cout << " " << temp->data ; temp = temp->right ; while(temp) { s.push(temp) ; temp = temp->left ; } } } void preorder_withoutRec(Node* t) { Node* temp = t ; stack<Node*> s ; while(temp) { cout << " " << temp->data ; s.push(temp) ; temp = temp->left ; } while(!s.empty()) { temp = s.top() ; s.pop() ; temp = temp->right ; while(temp) { cout << " " << temp->data ; s.push(temp) ; temp = temp->left ; } } } void postorder_withoutRec(Node* t) { Node *t1, *temp = t ; stack<Node*> s, s1 ; while(temp) { s.push(temp) ; s1.push(NULL) ; temp = temp->left ; } while(!s.empty()) { temp = s.top() ; s.pop() ; t1 = s1.top() ; s1.pop() ; if(t1 == NULL) { s.push(temp) ; s1.push((Node*)1) ; temp = temp->right ; while(temp) { s.push(temp) ; s1.push(NULL) ; temp = temp->left ; } } else { cout << " " << temp->data ; } } } //=======================================// //========== PRINTING ==========// // Preoder void printPreorder(Node* node) { if(node != NULL) { // Printing the data of node cout << node->data << " " ; // Using recursion to left and right printPreorder(node->left) ; printPreorder(node->right) ; } } // Postorder void printPostorder(Node* node) { if(node != NULL) { // Using recursion first on left and then on right printPostorder(node->left) ; printPostorder(node->right) ; // Now print the data of node cout << node->data << " "; } } // Inorder/infix void printInorder(Node* node) { if(node != NULL) { // Using recursion on the left printInorder(node->left) ; // then printing the data of node cout << node->data << " " ; // Now using recursion on the left printInorder(node->right) ; } } //=======================================// //============ CONSTRUCTION OF TREE ============// class ExpressionTree{ public: stack<Node*> st ; Node *t, *t1, *t2 ; Node *top ; void constructTree(string exp) { // stack<Node*> st ; // Node *t, *t1, *t2 ; // Traverse through every character of input expression for(int i = 0 ; i < (int)exp.length() ; i++) { // If operand is character push into stack if (!isOperator(exp[i])) { t = newNode(exp[i]) ; st.push(t) ; } else { t = newNode(exp[i]) ; t1 = st.top() ; st.pop() ; t2 = st.top() ; st.pop() ; // Adding them as children t->right = t1 ; t->left = t2 ; // Adding to stack st.push(t); } } // only element will be root of expression tree top = st.top() ; } void constructTreePre(string exp) { reverse(exp.begin() , exp.end()) ; // stack<Node*> st ; // Node *t, *t1, *t2 ; // Traverse through every character of input expression for(int i = 0 ; i < (int)exp.length() ; i++) { // If operand is character push into stack if (!isOperator(exp[i])) { t = newNode(exp[i]) ; st.push(t) ; } else { t = newNode(exp[i]) ; t1 = st.top() ; st.pop() ; t2 = st.top() ; st.pop() ; // Adding them as children t->left = t1 ; t->right = t2 ; // Adding to stack st.push(t); } } // only element will be root of expression tree top = st.top() ; } }; //------------------------ MENU ------------------------// void menu( ) { cout << "Choose Your Operation:\n" ; cout << "1.Enter a prefix expression\n" ; cout << "2.Enter a postfix expression\n" ; cout << "3.Exit Program\n" ; cout << "Enter you choice: " ; } void prefixmenu() { cout << "Choose Your Operation:\n" ; cout << "1.Get the postfix expression with recursion\n" ; cout << "2.Get the infix expression with recursion\n" ; cout << "3.Get the postfix expression without recursion\n" ; cout << "4.Get the infix expression without recursion\n" ; } void postmenu() { cout << "Choose Your Operation:\n" ; cout << "1.Get the prefix expression with recursion\n" ; cout << "2.Get the infix expression with recursion\n" ; cout << "3.Get the prefix expression without recursion\n" ; cout << "4.Get the infix expression without recursion\n" ; } //------------------------ END MENU ------------------------// int main( ) { while(true) { menu() ; ExpressionTree tree ; int choice ; cin >> choice ; if(choice == 1) // Prefix to Postfix || Infix { cout << "Enter Your Prefix Expression: " ; string exp ; cin >> exp ; tree.constructTreePre(exp) ; prefixmenu() ; int choice2 ; cin >> choice2 ; if(choice2 == 1) { cout << "The postfix expression is:\n" ; printPostorder(tree.top) ; cout << "\n" ; } else if(choice2 == 2) { cout << "The infix expression is:\n" ; printInorder(tree.top) ; cout << "\n" ; } else if(choice2 == 3) { cout << "The postfix expression without recursion is:\n" ; postorder_withoutRec(tree.top) ; cout << "\n" ; } else if(choice2 == 4) { cout << "The infix expression without recursion is:\n" ; inorder_withoutRec(tree.top) ; cout << "\n" ; } } else if(choice == 2) { cout << "Enter Your Postfix Expression: " ; string exp ; cin >> exp ; tree.constructTree(exp) ; postmenu() ; int choice2 ; cin >> choice2 ; if(choice2 == 1) { cout << "The prefix expression is:\n" ; printPreorder(tree.top) ; cout << "\n" ; } else if(choice2 == 2) { cout << "The infix expression is:\n" ; printInorder(tree.top) ; cout << "\n" ; } else if(choice2 == 3) { cout << "The prefix expression without recursion is:\n" ; preorder_withoutRec(tree.top) ; cout << "\n" ; } else if(choice2 == 4) { cout << "The infix expression without recursion is:\n" ; inorder_withoutRec(tree.top) ; cout << "\n" ; } } else if(choice == 3) { cout << "Thank you!" ; break ; } else { cout << "Invalid choice, please try again" ; } } return 0 ; } /*** END ***/
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 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 //============================================================================== #define NT2_UNIT_MODULE "nt2 boost.simd.arithmetic toolbox - sqr_abs/scalar Mode" ////////////////////////////////////////////////////////////////////////////// // unit test behavior of boost.simd.arithmetic components in scalar mode ////////////////////////////////////////////////////////////////////////////// /// created by jt the 30/11/2010 /// #include <nt2/arithmetic/include/functions/sqr_abs.hpp> #include <nt2/include/constants/i.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/dispatch/functor/meta/call.hpp> #include <nt2/sdk/unit/tests.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/constant/constant.hpp> NT2_TEST_CASE_TPL ( sqr_abs_real__1_0, BOOST_SIMD_REAL_TYPES) { using nt2::sqr_abs; using nt2::tag::sqr_abs_; typedef typename boost::dispatch::meta::as_integer<T>::type iT; typedef typename boost::dispatch::meta::call<sqr_abs_(T)>::type r_t; typedef typename nt2::meta::scalar_of<r_t>::type sr_t; typedef typename nt2::meta::scalar_of<r_t>::type ssr_t; typedef typename std::complex<T> cT; typedef T wished_r_t; // return type conformity test NT2_TEST( (boost::is_same < r_t, wished_r_t >::value) ); std::cout << std::endl; double ulpd; ulpd=0.0; // std::cout << nt2::type_id(nt2::I<T>()) << std::endl; // specific values tests NT2_TEST_ULP_EQUAL(sqr_abs(cT(1)), T(1), 0); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Inf<T>())), nt2::Inf<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Minf<T>())), nt2::Inf<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Mone<T>())), nt2::One<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Nan<T>())), nt2::Nan<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::One<T>())), nt2::One<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Valmax<T>())), nt2::Inf<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Valmin<T>())), nt2::Inf<T>()); NT2_TEST_EQUAL(sqr_abs(cT(nt2::Zero<T>())), nt2::Zero<T>()); std::complex < T > a(1, 0); NT2_TEST_EQUAL(sqr_abs(a), nt2::One<T>()); std::complex < T > b(1, 2); NT2_TEST_EQUAL(sqr_abs(b), nt2::Five<T>()); } // end of test for floating_
#ifndef BOOST_MPL_LIST_AUX_O1_SIZE_HPP_INCLUDED #define BOOST_MPL_LIST_AUX_O1_SIZE_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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/mpl for documentation. // $Id: O1_size.hpp 49267 2008-10-11 06:19:02Z agurtovoy $ // $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $ // $Revision: 49267 $ #include <boost/mpl/O1_size_fwd.hpp> #include <boost/mpl/list/aux_/tag.hpp> namespace riakboost{} namespace boost = riakboost; namespace riakboost{ namespace mpl { template<> struct O1_size_impl< aux::list_tag > { template< typename List > struct apply : List::size { }; }; }} #endif // BOOST_MPL_LIST_AUX_O1_SIZE_HPP_INCLUDED
/* Copyright (C) 2015-2018 Hans-Kristian Arntzen <maister@archlinux.us> * * 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. */ #pragma once #include "glfft_common.hpp" #include "glfft_interface.hpp" #include <string> #include <unordered_map> #include <utility> namespace GLFFT { struct WisdomPass { struct { unsigned Nx; unsigned Ny; unsigned radix; Mode mode; Target input_target; Target output_target; FFTOptions::Type type; } pass; double cost; bool operator==(const WisdomPass &other) const { return std::memcmp(&pass, &other.pass, sizeof(pass)) == 0; } }; } // namespace GLFFT namespace std { template <> struct hash<GLFFT::WisdomPass> { std::size_t operator()(const GLFFT::WisdomPass &params) const { std::size_t h = 0; hash<uint8_t> hasher; for (std::size_t i = 0; i < sizeof(params.pass); i++) { h ^= hasher(reinterpret_cast<const uint8_t *>(&params.pass)[i]); } return h; } }; } // namespace std namespace GLFFT { // Adds information which depends on the GPU vendor. // This can speed up learning process, since there will be fewer "obviously wrong" settings to test. struct FFTStaticWisdom { enum Tristate { On = 1, Off = 0, DontCare = -1 }; unsigned min_workgroup_size = 1; unsigned min_workgroup_size_shared = 1; unsigned max_workgroup_size = 128; // GLES 3.1 mandates support for this. unsigned min_vector_size = 2; unsigned max_vector_size = 4; Tristate shared_banked = DontCare; }; class FFTWisdom { public: std::pair<double, FFTOptions::Performance> learn_optimal_options(Context *ctx, unsigned Nx, unsigned Ny, unsigned radix, Mode mode, Target input_target, Target output_target, const FFTOptions::Type &type); void learn_optimal_options_exhaustive(Context *ctx, unsigned Nx, unsigned Ny, Type type, Target input_target, Target output_target, const FFTOptions::Type &fft_type); const std::pair<const WisdomPass, FFTOptions::Performance> *find_optimal_options( unsigned Nx, unsigned Ny, unsigned radix, Mode mode, Target input_target, Target output_target, const FFTOptions::Type &base_options) const; const FFTOptions::Performance &find_optimal_options_or_default(unsigned Nx, unsigned Ny, unsigned radix, Mode mode, Target input_target, Target output_target, const FFTOptions &base_options) const; void set_static_wisdom(FFTStaticWisdom static_wisdom) { this->static_wisdom = static_wisdom; } static FFTStaticWisdom get_static_wisdom_from_renderer(Context *context); static FFTOptions::Performance get_static_performance_options_from_renderer(Context *context); void set_bench_params(unsigned warmup, unsigned iterations, unsigned dispatches, double timeout) { params.warmup = warmup; params.iterations = iterations; params.dispatches = dispatches; params.timeout = timeout; } // Serialization interface. std::string archive() const; void extract(const char *json); private: std::unordered_map<WisdomPass, FFTOptions::Performance> library; std::pair<double, FFTOptions::Performance> study(Context *context, const WisdomPass &pass, FFTOptions::Type options) const; double bench(Context *cmd, Resource *output, Resource *input, const WisdomPass &pass, const FFTOptions &options, const std::shared_ptr<ProgramCache> &cache) const; FFTStaticWisdom static_wisdom; struct { unsigned warmup = 2; unsigned iterations = 20; unsigned dispatches = 50; double timeout = 1.0; } params; }; } // namespace GLFFT
/* * Copyright (c) 2015, Peter Thorson. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the WebSocket++ Project 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 PETER THORSON 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 WEBSOCKETPP_VERSION_HPP #define WEBSOCKETPP_VERSION_HPP /// Namespace for the WebSocket++ project namespace websocketpp { /* other places where version information is kept - readme.md - changelog.md - Doxyfile - CMakeLists.txt */ /// Library major version number static int const major_version = 0; /// Library minor version number static int const minor_version = 8; /// Library patch version number static int const patch_version = 1; /// Library pre-release flag /** * This is a textual flag indicating the type and number for pre-release * versions (dev, alpha, beta, rc). This will be blank for release versions. */ static char const prerelease_flag[] = ""; /// Default user agent string static char const user_agent[] = "WebSocket++/0.8.1"; } // namespace websocketpp #endif // WEBSOCKETPP_VERSION_HPP
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "OnlineSubsystemIOSPrivatePCH.h" #include "OnlineTurnBasedInterfaceIOS.h" #include "TurnBasedEventListener.h" #include "OnlineIdentityInterface.h" #include "OnlineSubsystem.h" #include "OnlineAsyncTaskManager.h" #include "RepLayout.h" #include "TurnBasedMatchInterface.h" DEFINE_LOG_CATEGORY_STATIC(LogTurnBasedInterfaceIOS, Verbose, All); #define INCLUDE_LOCAL_PLAYER (true) #define DO_NOT_INCLUDE_LOCAL_PLAYER (false) FTurnBasedMatchIOS::FTurnBasedMatchIOS(GKTurnBasedMatch* _Match, NSArray* PlayerArray) : FTurnBasedMatch() , Match([_Match retain]) { if (!Match) { UE_LOG(LogTurnBasedInterfaceIOS, Error, TEXT("GKTurnBasedMatch required to create a FTurnBasedMatchIOS")); } for (GKPlayer* player in PlayerArray) { PlayerAliasArray.Add(UTF8_TO_TCHAR(player.displayName.UTF8String)); } } FTurnBasedMatchIOS::~FTurnBasedMatchIOS() { [Match release]; } int32 FTurnBasedMatchIOS::GetNumberOfPlayers() const { return Match.participants.count; } bool FTurnBasedMatchIOS::GetPlayerDisplayName(int32 PlayerIndex, FString& Name) const { if (PlayerIndex >= PlayerAliasArray.Num() || PlayerIndex < 0) { return FTurnBasedMatch::GetPlayerDisplayName(PlayerIndex, Name); } Name = PlayerAliasArray[PlayerIndex]; return true; } void FTurnBasedMatchIOS::ReloadMatchData(FDownloadMatchDataSignature DownloadCallback) { [Match loadMatchDataWithCompletionHandler : ^ (NSData* data, NSError* error) { if (DownloadCallback.IsBound()) { DownloadCallback.Execute(GetMatchID(), error == nil); } }]; } bool FTurnBasedMatchIOS::HasMatchData() const { return Match.matchData != nil && Match.matchData.length != 0; } bool FTurnBasedMatchIOS::GetMatchData(TArray<uint8>& OutMatchData) const { if (!HasMatchData()) { return false; } int32 dataSize = Match.matchData.length; OutMatchData.Empty(dataSize); OutMatchData.AddUninitialized(dataSize - OutMatchData.Num()); FMemory::Memcpy(OutMatchData.GetData(), Match.matchData.bytes, dataSize); return true; } void FTurnBasedMatchIOS::SetMatchData(const TArray<uint8>& NewMatchData, FUploadMatchDataSignature UploadCallback) { [Match saveCurrentTurnWithMatchData : [NSData dataWithBytes : NewMatchData.GetData() length : NewMatchData.Num()] completionHandler : ^ (NSError* error) { UploadCallback.Execute(GetMatchID(), error == nil); }]; } FString FTurnBasedMatchIOS::GetMatchID() const { if (!Match) { return FTurnBasedMatch::GetMatchID(); } return FString::Printf(TEXT("%s"), UTF8_TO_TCHAR(Match.matchID.UTF8String)); } int32 FTurnBasedMatchIOS::GetLocalPlayerIndex() const { IOnlineSubsystem* OSS = IOnlineSubsystem::Get(); IOnlineIdentityPtr IdentityInterface = OSS ? OSS->GetIdentityInterface() : NULL; if (!IdentityInterface.IsValid()) { UE_LOG(LogTurnBasedInterfaceIOS, Warning, TEXT("No Online Identity")); return 0; } TSharedPtr<const FUniqueNetId> NetID = IdentityInterface->GetUniquePlayerId(0); NSString* playerID = [NSString stringWithFormat : @"%s", TCHAR_TO_UTF8(*(NetID->ToString()))]; int32 PlayerIndex = 0; NSArray* participantArray = Match.participants; for (GKTurnBasedParticipant* participant in participantArray) { NSString* PlayerIDString = nil; #ifdef __IPHONE_8_0 if ([GKTurnBasedParticipant respondsToSelector:@selector(player)] == YES) { PlayerIDString = participant.player.playerID; } else #endif { #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0 PlayerIDString = participant.playerID; #endif } if ([playerID isEqualToString : PlayerIDString]) { return PlayerIndex; } ++PlayerIndex; } return PlayerIndex; } int32 FTurnBasedMatchIOS::GetCurrentPlayerIndex() const { GKTurnBasedParticipant* currentParticipant = Match.currentParticipant; if (!currentParticipant) { return 0; } return[Match.participants indexOfObject : currentParticipant]; } EMPMatchOutcome::Outcome FTurnBasedMatchIOS::GetMatchOutcomeForPlayer(int32 PlayerIndex) const { if (PlayerIndex >= Match.participants.count) { return EMPMatchOutcome::None; } GKTurnBasedParticipant* participant = Match.participants[PlayerIndex]; GKTurnBasedMatchOutcome GKOutcome = participant.matchOutcome; return GetMatchOutcomeFromGKTurnBasedMatchOutcome(GKOutcome); } int32 FTurnBasedMatchIOS::GetPlayerIndexForPlayer(NSString* PlayerID) const { int32 playerIndex = 0; for (GKTurnBasedParticipant* participant in Match.participants) { NSString* PlayerIDString = nil; #ifdef __IPHONE_8_0 if ([GKTurnBasedParticipant respondsToSelector:@selector(player)] == YES) { PlayerIDString = participant.player.playerID; } else #endif { #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0 PlayerIDString = participant.playerID; #endif } if ([PlayerIDString isEqualToString : PlayerID]) { return playerIndex; } } UE_LOG(LogTurnBasedInterfaceIOS, Warning, TEXT("Failed to find participant %s in match"), PlayerID.UTF8String); return 0; } bool FTurnBasedMatchIOS::IsGKTurnBasedMatch(GKTurnBasedMatch* Comparison) const { if (!Comparison || !Match) { return false; } return[Comparison.matchID isEqualToString : Match.matchID]; } void FTurnBasedMatchIOS::EndTurnWithMatchData(const TArray<uint8>& MatchData, int32 TurnTimeoutInSeconds, FUploadMatchDataSignature UploadCallback) { NSArray* participantArray = GetNextParticipantArray(INCLUDE_LOCAL_PLAYER); [Match endTurnWithNextParticipants : participantArray turnTimeout : TurnTimeoutInSeconds matchData : [NSData dataWithBytes : MatchData.GetData() length : MatchData.Num()] completionHandler : ^ (NSError* error) { if (UploadCallback.IsBound()) { UploadCallback.Execute(GetMatchID(), error == nil); } }]; } void FTurnBasedMatchIOS::QuitMatch(EMPMatchOutcome::Outcome Outcome, int32 TurnTimeoutInSeconds, FQuitMatchSignature QuitMatchCallback) { int32 localPlayerIndex = GetLocalPlayerIndex(); if (localPlayerIndex < Match.participants.count) { GKTurnBasedParticipant* localParticipant = Match.participants[localPlayerIndex]; if (localParticipant.matchOutcome != GKTurnBasedMatchOutcomeNone) { return; } } GKTurnBasedMatchOutcome GKOutcome = GetGKTurnBasedMatchOutcomeFromMatchOutcome(Outcome); if (localPlayerIndex == GetCurrentPlayerIndex()) { QuitMatchInTurn(GKOutcome, TurnTimeoutInSeconds, QuitMatchCallback); } else { QuitMatchOutOfTurn(GKOutcome, QuitMatchCallback); } } void FTurnBasedMatchIOS::QuitMatchInTurn(GKTurnBasedMatchOutcome Outcome, int32 TurnTimeoutInSeconds, FQuitMatchSignature QuitMatchCallback) { FString MatchID = GetMatchID(); NSArray* participantArray = GetNextParticipantArray(DO_NOT_INCLUDE_LOCAL_PLAYER); [Match participantQuitInTurnWithOutcome : Outcome nextParticipants : participantArray turnTimeout : TurnTimeoutInSeconds matchData : Match.matchData completionHandler : ^ (NSError* error) { if (QuitMatchCallback.IsBound()) { QuitMatchCallback.Execute(MatchID, error == nil); } }]; } void FTurnBasedMatchIOS::QuitMatchOutOfTurn(GKTurnBasedMatchOutcome Outcome, FQuitMatchSignature QuitMatchCallback) { FString MatchID = GetMatchID(); [Match participantQuitOutOfTurnWithOutcome : Outcome withCompletionHandler : ^ (NSError* error) { if (QuitMatchCallback.IsBound()) { QuitMatchCallback.Execute(MatchID, error == nil); } }]; } NSArray* FTurnBasedMatchIOS::GetNextParticipantArray(bool IncludeLocalPlayer) const { NSArray* participantArray = Match.participants; int32 localPlayerIndex = GetLocalPlayerIndex(); int32 nextPlayerIndex = (localPlayerIndex + 1) % participantArray.count; NSMutableArray* nextParticipantArray = [NSMutableArray array]; while (nextPlayerIndex != localPlayerIndex) { [nextParticipantArray addObject : [participantArray objectAtIndex : nextPlayerIndex]]; nextPlayerIndex = (nextPlayerIndex + 1) % participantArray.count; } if (IncludeLocalPlayer) { [nextParticipantArray addObject : [participantArray objectAtIndex : localPlayerIndex]]; } return nextParticipantArray; } GKTurnBasedMatchOutcome FTurnBasedMatchIOS::GetGKTurnBasedMatchOutcomeFromMatchOutcome(EMPMatchOutcome::Outcome Outcome) const { switch (Outcome) { default: case EMPMatchOutcome::None: return GKTurnBasedMatchOutcomeNone; case EMPMatchOutcome::Quit: return GKTurnBasedMatchOutcomeQuit; case EMPMatchOutcome::Won: return GKTurnBasedMatchOutcomeWon; case EMPMatchOutcome::Lost: return GKTurnBasedMatchOutcomeLost; case EMPMatchOutcome::Tied: return GKTurnBasedMatchOutcomeTied; case EMPMatchOutcome::TimeExpired: return GKTurnBasedMatchOutcomeTimeExpired; case EMPMatchOutcome::First: return GKTurnBasedMatchOutcomeFirst; case EMPMatchOutcome::Second: return GKTurnBasedMatchOutcomeSecond; case EMPMatchOutcome::Third: return GKTurnBasedMatchOutcomeThird; case EMPMatchOutcome::Fourth: return GKTurnBasedMatchOutcomeFourth; } } EMPMatchOutcome::Outcome FTurnBasedMatchIOS::GetMatchOutcomeFromGKTurnBasedMatchOutcome(GKTurnBasedMatchOutcome GKOutcome) const { switch (GKOutcome) { default: case GKTurnBasedMatchOutcomeNone: return EMPMatchOutcome::None; case GKTurnBasedMatchOutcomeQuit: return EMPMatchOutcome::Quit; case GKTurnBasedMatchOutcomeWon: return EMPMatchOutcome::Won; case GKTurnBasedMatchOutcomeLost: return EMPMatchOutcome::Lost; case GKTurnBasedMatchOutcomeTied: return EMPMatchOutcome::Tied; case GKTurnBasedMatchOutcomeTimeExpired: return EMPMatchOutcome::TimeExpired; case GKTurnBasedMatchOutcomeFirst: return EMPMatchOutcome::First; case GKTurnBasedMatchOutcomeSecond: return EMPMatchOutcome::Second; case GKTurnBasedMatchOutcomeThird: return EMPMatchOutcome::Third; case GKTurnBasedMatchOutcomeFourth: return EMPMatchOutcome::Fourth; } } void FTurnBasedMatchIOS::SetGKMatch(GKTurnBasedMatch* GKMatch) { [Match release]; Match = [GKMatch retain]; } void FTurnBasedMatchIOS::EndMatch(FEndMatchSignature EndMatchCallback, EMPMatchOutcome::Outcome LocalPlayerOutcome, EMPMatchOutcome::Outcome OtherPlayersOutcome) { FString MatchID = GetMatchID(); for (int32 i = 0; i < Match.participants.count; ++i) { GKTurnBasedParticipant* participant = Match.participants[i]; GKTurnBasedMatchOutcome GKOutcome = participant.matchOutcome; if (GKOutcome == GKTurnBasedMatchOutcomeNone) { if (GetLocalPlayerIndex() == i) { participant.matchOutcome = GetGKTurnBasedMatchOutcomeFromMatchOutcome(LocalPlayerOutcome); } else { participant.matchOutcome = GetGKTurnBasedMatchOutcomeFromMatchOutcome(OtherPlayersOutcome); } } } [Match endMatchInTurnWithMatchData : Match.matchData completionHandler : ^ (NSError* error) { if (EndMatchCallback.IsBound()) { EndMatchCallback.Execute(MatchID, error == nil); } }]; } FOnlineTurnBasedIOS::FOnlineTurnBasedIOS() : IOnlineTurnBased() , FTurnBasedMatchmakerDelegate() , Matchmaker(*this) , MatchmakerDelegate(nullptr) , EventListener(nil) , EventDelegate(nullptr) , NumberOfMatchesBeingLoaded(0) { EventListener = [[FTurnBasedEventListenerIOS alloc] initWithOwner:*this]; } FOnlineTurnBasedIOS::~FOnlineTurnBasedIOS() { [EventListener release]; } void FOnlineTurnBasedIOS::SetMatchmakerDelegate(FTurnBasedMatchmakerDelegatePtr Delegate) { MatchmakerDelegate = Delegate; } void FOnlineTurnBasedIOS::ShowMatchmaker(const FTurnBasedMatchRequest& MatchRequest) { Matchmaker.ShowWithMatchRequest(MatchRequest); } void FOnlineTurnBasedIOS::SetEventDelegate(FTurnBasedEventDelegateWeakPtr Delegate) { EventDelegate = Delegate; if (!EventListener && Delegate.IsValid()) { EventListener = [[FTurnBasedEventListenerIOS alloc] initWithOwner:*this]; } else if (EventListener && !Delegate.IsValid()) { [EventListener release]; EventListener = nil; } } FTurnBasedEventDelegateWeakPtr FOnlineTurnBasedIOS::GetEventDelegate() const { return EventDelegate; } void FOnlineTurnBasedIOS::LoadAllMatches(FLoadTurnBasedMatchesSignature MatchesLoadedCallback) { if (NumberOfMatchesBeingLoaded > 0) { UE_LOG(LogTurnBasedInterfaceIOS, Warning, TEXT("Requesting load all matches whilst we are still loading matches")); return; } [GKTurnBasedMatch loadMatchesWithCompletionHandler : ^ (NSArray* matches, NSError* error) { MatchArray.Empty(); NumberOfMatchesBeingLoaded = matches.count; for (GKTurnBasedMatch* match in matches) { NSArray* playerIdentifierArray = FOnlineTurnBasedIOS::GetPlayerIdentifierArrayForMatch(match); [GKPlayer loadPlayersForIdentifiers : playerIdentifierArray withCompletionHandler : ^ (NSArray *players, NSError *nameLoadError) { if (!nameLoadError) { MatchArray.Add(MakeShareable(new FTurnBasedMatchIOS(match, players))); } --NumberOfMatchesBeingLoaded; if (NumberOfMatchesBeingLoaded == 0) { TArray<FString> MatchIDArray; for (TArray<FTurnBasedMatchRef>::TConstIterator It = MatchArray.CreateConstIterator(); It; ++It) { MatchIDArray.Add((*It)->GetMatchID()); } MatchesLoadedCallback.ExecuteIfBound(MatchIDArray, error == nil); } }]; } }]; } void FOnlineTurnBasedIOS::LoadMatchWithID(FString MatchID, FLoadTurnBasedMatchWithIDSignature MatchLoadedCallback) { NSString* IDString = [NSString stringWithUTF8String : TCHAR_TO_UTF8(*MatchID)]; [GKTurnBasedMatch loadMatchWithID : IDString withCompletionHandler : ^ (GKTurnBasedMatch* match, NSError* error) { if (!error) { NSArray* playerIdentifierArray = FOnlineTurnBasedIOS::GetPlayerIdentifierArrayForMatch(match); [GKPlayer loadPlayersForIdentifiers : playerIdentifierArray withCompletionHandler : ^ (NSArray *players, NSError *nameLoadError) { if (!nameLoadError) { FTurnBasedMatchPtr PreviousMatchPtr = GetMatchWithID(MatchID); if (PreviousMatchPtr.IsValid()) { MatchArray.Remove(PreviousMatchPtr.ToSharedRef()); } FTurnBasedMatchRef NewMatch = MakeShareable(new FTurnBasedMatchIOS(match, players)); MatchArray.Add(NewMatch); MatchLoadedCallback.ExecuteIfBound(NewMatch->GetMatchID(), true); } else { MatchLoadedCallback.ExecuteIfBound(TEXT(""), false); } }]; } else { MatchLoadedCallback.ExecuteIfBound(TEXT(""), false); } }]; } FTurnBasedMatchPtr FOnlineTurnBasedIOS::GetMatchWithID(FString MatchID) const { for (TArray<FTurnBasedMatchRef>::TConstIterator It = MatchArray.CreateConstIterator(); It; ++It) { FTurnBasedMatch& Match = (*It).Get(); if (Match.GetMatchID().Compare(MatchID) == 0) { return *It; } } return nullptr; } void FOnlineTurnBasedIOS::RemoveMatch(FTurnBasedMatchRef Match, FRemoveMatchSignature RemoveMatchCallback) { FTurnBasedMatchIOS& MatchIOS = static_cast<FTurnBasedMatchIOS&>(Match.Get()); FString MatchID = MatchIOS.GetMatchID(); [MatchIOS.GetGKMatch() removeWithCompletionHandler:^ (NSError* error) { MatchArray.Remove(Match); if (RemoveMatchCallback.IsBound()) { RemoveMatchCallback.Execute(MatchID, error == nil); } }]; } void FOnlineTurnBasedIOS::OnMatchmakerCancelled() { if (MatchmakerDelegate.IsValid()) { MatchmakerDelegate.Pin()->OnMatchmakerCancelled(); } } void FOnlineTurnBasedIOS::OnMatchmakerFailed() { if (!MatchmakerDelegate.IsValid()) { MatchmakerDelegate.Pin()->OnMatchmakerFailed(); } } void FOnlineTurnBasedIOS::OnMatchFound(FTurnBasedMatchRef Match) { MatchArray.Add(Match); if (MatchmakerDelegate.IsValid()) { dispatch_async(dispatch_get_main_queue(), ^ { [FIOSAsyncTask CreateTaskWithBlock : ^ bool(void) { MatchmakerDelegate.Pin()->OnMatchFound(Match); return true; }]; }); } } void FOnlineTurnBasedIOS::OnMatchEnded(FString MatchID) { dispatch_async(dispatch_get_main_queue(), ^ { [FIOSAsyncTask CreateTaskWithBlock : ^ bool(void) { if (TurnBasedMatchInterfaceObject) { ITurnBasedMatchInterface::Execute_OnMatchEnded(TurnBasedMatchInterfaceObject, MatchID); } if (EventDelegate.IsValid()) { EventDelegate.Pin()->OnMatchEnded(MatchID); } return true; }]; }); } void FOnlineTurnBasedIOS::OnMatchReceivedTurnEvent(FString MatchID, bool BecameActive, void* Match) { GKTurnBasedMatch* IOSTurnBasedMatch = (GKTurnBasedMatch*)Match; NSArray* playerIdentifierArray = FOnlineTurnBasedIOS::GetPlayerIdentifierArrayForMatch(IOSTurnBasedMatch); [GKPlayer loadPlayersForIdentifiers : playerIdentifierArray withCompletionHandler : ^ (NSArray *players, NSError *nameLoadError) { if (!nameLoadError) { FTurnBasedMatchPtr PreviousMatchPtr = GetMatchWithID(MatchID); if (PreviousMatchPtr.IsValid()) { MatchArray.Remove(PreviousMatchPtr.ToSharedRef()); } FTurnBasedMatchRef NewMatch = MakeShareable(new FTurnBasedMatchIOS(IOSTurnBasedMatch, players)); MatchArray.Add(NewMatch); dispatch_async(dispatch_get_main_queue(), ^ { [FIOSAsyncTask CreateTaskWithBlock : ^ bool(void) { if (TurnBasedMatchInterfaceObject) { TArray<uint8> MatchData; if (GetMatchWithID(MatchID)->GetMatchData(MatchData)) { FRepLayout RepLayout; RepLayout.InitFromObjectClass(TurnBasedMatchInterfaceObject->GetClass()); FBitReader Reader(MatchData.GetData(), MATCH_DATA_SIZE); RepLayout.SerializeObjectReplicatedProperties(TurnBasedMatchInterfaceObject, Reader); } ITurnBasedMatchInterface::Execute_OnMatchReceivedTurn(TurnBasedMatchInterfaceObject, MatchID, BecameActive); } if (EventDelegate.IsValid()) { EventDelegate.Pin()->OnMatchReceivedTurnEvent(MatchID, BecameActive, Match); } return true; }]; }); } }]; } NSArray* FOnlineTurnBasedIOS::GetPlayerIdentifierArrayForMatch(GKTurnBasedMatch* match) { NSMutableArray* result = [NSMutableArray array]; for (GKTurnBasedParticipant* participant in match.participants) { NSString* PlayerIDString = nil; #ifdef __IPHONE_8_0 if ([GKTurnBasedParticipant respondsToSelector:@selector(player)] == YES) { PlayerIDString = participant.player.playerID; } else #endif { #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_8_0 PlayerIDString = participant.playerID; #endif } if (!PlayerIDString) { break; } [result addObject : PlayerIDString]; } return result; } void FOnlineTurnBasedIOS::RegisterTurnBasedMatchInterfaceObject(UObject* Object) { if (Object != nullptr && Object->GetClass()->ImplementsInterface(UTurnBasedMatchInterface::StaticClass())) { TurnBasedMatchInterfaceObject = Object; } }
#include <MLoggingPCH.h> #include <Logger/LoggerImpl/LoggerImpl.h> #include <Logger/MLogger.h> namespace MLog { MLoggerImpl::MLoggerImpl(make_enabler) { state_ = false; } MLoggerImpl::~MLoggerImpl() = default; MLoggerImpl* MLoggerImpl::getInstance() { static std::once_flag initFlag; static std::unique_ptr<MLoggerImpl> instance = nullptr; std::call_once(initFlag, [&]() {instance = std::make_unique<MLoggerImpl>(make_enabler{}); }); return instance.get(); } void MLoggerImpl::logNow(Log&& log) { *log.target << log.level << ":: " << log.message << '\n'; if (log.callback != nullptr) { log.callback(); } } void MLoggerImpl::run() { state_ = true; this_ = std::async(std::launch::async, &MLoggerImpl::extract, this); } void MLoggerImpl::extract() { bool toLog; do { Log aLog; toLog = waitAndPop(aLog); if (toLog) logNow(std::move(aLog)); // Exit when the logger is stopped // And no elements left in the queue } while (toLog || state_); } bool MLoggerImpl::waitAndPop(Log& log) { std::unique_lock guard(lock_); cv_.wait(guard, [&]() {return !logs_.empty() || !state_; }); if ((logs_.empty() && !state_) || logs_.empty()) return false; log = std::move(logs_.front()); logs_.pop(); return true; } void MLoggerImpl::stop() { state_ = false; this_.wait(); } bool MLoggerImpl::isRunning() { return state_; } void MLoggerImpl::add(Log&& log_) { if (!MLog::getState()) { throw MLog::MLoggerIsNotStarted(); } if (MLog::getMode() == launch::seq) logNow(std::move(log_)); else { std::lock_guard<std::mutex> guard(lock_); logs_.push(std::move(log_)); cv_.notify_one(); } } }
#include "HomeControlMagic.h" #include "helperFunctions.h" #include "Endpoints/EndpointZero.h" #include "debugDefines.h" #include "printWrapper.h" #ifdef ARDUINO #include "arduinoWrapper/ArduinoConfig.h" #include "arduinoWrapper/ArduinoNetworkInterface.h" #include "arduinoWrapper/ArduinoWrapper.h" #elif LINUX #include "linuxWrapper/src/LinuxWrapper.hpp" #include <math.h> #include <stdlib.h> #include <string.h> #elif defined STM #include "STMWrapper.h" #endif static HomeControlMagic* hcm_ptr; static char* s_topic_buffer_ptr; static char* s_common_buffer_ptr; void callback(const char* topic, const uint8_t* payload, const unsigned int length) { #ifdef HCM_DEBUG print(F("got in callback")); print(F("topic: "), topic); print(F("payload: ")); for(uint8_t i = 0; i < length; i++) { print((char)payload[i]); } print(""); #endif // check for server announce if(lineContains(topic, "broadcast", length)) { if(lineContains((char*)payload, "serverannounce", length)) { hcm_ptr->announce(); return; } } // it is not server announce uint8_t start_position = lineContains(topic, "/", length); uint8_t diff = lineContains(topic + start_position, "/", length) - 1; char endpoint_id[diff + 1]; memcpy(endpoint_id, topic + start_position, diff); endpoint_id[diff] = '\0'; Endpoint* end_ptr = hcm_ptr->getEndpoint(endpoint_id); if(end_ptr != NULL) { end_ptr->incomingMessage(topic, payload, length); } } HomeControlMagic::HomeControlMagic(const char* deviceName) : m_number_of_endpoints(0) , m_name(deviceName) , m_broker_was_connected(false) , m_id(nullptr) { // pointer that is used from callback to set messages hcm_ptr = this; EndpointZero* epZ = new EndpointZero(hcm_ptr); epZ->setId("0"); m_endpoints_pointers[m_number_of_endpoints++] = epZ; } HomeControlMagic::~HomeControlMagic() { delete m_id; delete m_name; } void HomeControlMagic::setup() { s_topic_buffer_ptr = wrapperGetTopicBuffer(); s_common_buffer_ptr = wrapperGetMessageBuffer(); m_id = getUniqueId(); strcpy(m_base_topic, "d/"); strcat(m_base_topic, m_id); strcat(m_base_topic, "/"); wrapperSetCallback(callback); } void HomeControlMagic::doMagic() { /* On arduino this is calling loop for pubsubclient and network. Network is calling debugLed loop */ wrapperLoop(); if(wrapperIsMqttConnected()) { if(!m_broker_was_connected) { m_broker_was_connected = true; announce(); } } else { m_broker_was_connected = false; } } void HomeControlMagic::setTopic(char* topic, char* endpoint_id) { strcat(s_topic_buffer_ptr, m_base_topic); strcat(s_topic_buffer_ptr, endpoint_id); strcat(s_topic_buffer_ptr, "/"); strcat(s_topic_buffer_ptr, topic); } /* * Use with s_common_buffer_ptr. Get it by calling getMessageBufferPtr() */ void HomeControlMagic::sendStringMessage(char* topic, char* endpoint_id) { setTopic(topic, endpoint_id); #ifdef HCM_DEBUG print(s_topic_buffer_ptr); print(s_common_buffer_ptr); #endif wrapperPublish(); } void HomeControlMagic::sendMessage(char* topic, bool message, char* endpoint_id) { setTopic(topic, endpoint_id); #ifdef HCM_DEBUG print(s_topic_buffer_ptr); #endif if(message) { s_common_buffer_ptr[0] = '1'; } else { s_common_buffer_ptr[0] = '0'; } #ifdef HCM_DEBUG print(s_common_buffer_ptr); #endif wrapperPublish(); } void HomeControlMagic::sendMessage(char* topic, uint16_t message, char* endpoint_id) { setTopic(topic, endpoint_id); #ifdef HCM_DEBUG print(s_topic_buffer_ptr); #endif itoa(message, s_common_buffer_ptr, 10); #ifdef HCM_DEBUG print(s_common_buffer_ptr); #endif wrapperPublish(); } void HomeControlMagic::sendMessage(char* topic, double message, char* endpoint_id) { setTopic(topic, endpoint_id); #ifdef HCM_DEBUG print(s_topic_buffer_ptr); #endif dtostrf(message, 4, 2, s_common_buffer_ptr); #ifdef HCM_DEBUG print(s_common_buffer_ptr); #endif wrapperPublish(); } void HomeControlMagic::sendConfig(char* config, char* endpoint_name, char* endpoint_id) { setTopic("conf", endpoint_id); strcat(s_common_buffer_ptr, "e="); strcat(s_common_buffer_ptr, config); if(endpoint_name != nullptr) { // TODO: replace name with just n strcat(s_common_buffer_ptr, ";name="); strcat(s_common_buffer_ptr, endpoint_name); } strcat(s_common_buffer_ptr, ";"); #ifdef HCM_DEBUG print(s_topic_buffer_ptr); print(s_common_buffer_ptr); #endif wrapperPublish(); } void HomeControlMagic::announce() { strcat(s_common_buffer_ptr, m_name); sendStringMessage("announce", "0"); strcat(s_common_buffer_ptr, "online"); sendStringMessage("online", "0"); sendFeedback(); } Endpoint* HomeControlMagic::getEndpoint(char* endpoint_id) { for(int i = 0; i < m_number_of_endpoints; ++i) { if(strcmp(m_endpoints_pointers[i]->getId(), endpoint_id) == 0) { return m_endpoints_pointers[i]; } } return NULL; } uint8_t HomeControlMagic::getNumberOfEndpoints() { return m_number_of_endpoints; } void HomeControlMagic::addEndpoint(Endpoint* endpoint_ptr) { m_endpoints_pointers[m_number_of_endpoints++] = endpoint_ptr; itoa(m_number_of_endpoints - 1, s_common_buffer_ptr, 10); #ifdef HCM_DEBUG print(F("id to set: "), s_common_buffer_ptr); #endif endpoint_ptr->setId(s_common_buffer_ptr); wrapperClearMessageBuffer(); } void HomeControlMagic::addEndpoint(Endpoint* endpoint_ptr, char* endpoint_id) { m_endpoints_pointers[m_number_of_endpoints++] = endpoint_ptr; #ifdef HCM_DEBUG print(F("id to set: "), s_common_buffer_ptr); #endif endpoint_ptr->setId(endpoint_id); } void HomeControlMagic::sendConfigs() { for(uint8_t i = 0; i < m_number_of_endpoints; i++) { m_endpoints_pointers[i]->sendConfig(); } } void HomeControlMagic::sendFeedback() { for(uint8_t i = 0; i < m_number_of_endpoints; i++) { m_endpoints_pointers[i]->sendFeedbackMessage(); } } char* HomeControlMagic::getMessageBufferPtr() { return s_common_buffer_ptr; }
#include "toolbar.h" #include "tapp.h" #include "pane.h" #include "floatingpanelcommand.h" #include "tools/toolhandle.h" #include "tools/tool.h" #include "tools/toolcommandids.h" #include "toonzqt/menubarcommand.h" #include "menubarcommandids.h" #include "toonz/txshleveltypes.h" #include "toonz/txshlevelhandle.h" #include "toonz/tframehandle.h" #include "toonz/txsheethandle.h" #include "toonz/txshcell.h" #include "toonz/txshsimplelevel.h" #include "toonz/tcolumnhandle.h" #include "toonz/preferences.h" #include "toonz/tscenehandle.h" // TnzBase includes #include "tenv.h" #include <QPainter> #include <QAction> #include <QToolButton> #include <QVBoxLayout> #include <QObject> TEnv::IntVar ShowAllToolsToggle("ShowAllToolsToggle", 0); namespace { struct { const char *toolName; bool collapsable; QAction *action; } buttonLayout[] = {{T_Edit, false, 0}, {T_Selection, false, 0}, {"Separator_1", false, 0}, {T_Brush, false, 0}, {T_Geometric, false, 0}, {T_Type, true, 0}, {T_Fill, false, 0}, {T_PaintBrush, false, 0}, {"Separator_2", false, 0}, {T_Eraser, false, 0}, {T_Tape, false, 0}, {T_Finger, false, 0}, {"Separator_3", false, 0}, {T_StylePicker, false, 0}, {T_RGBPicker, false, 0}, {T_Ruler, false, 0}, {"Separator_4", false, 0}, {T_ControlPointEditor, false, 0}, {T_Pinch, true, 0}, {T_Pump, true, 0}, {T_Magnet, true, 0}, {T_Bender, true, 0}, {T_Iron, true, 0}, {T_Cutter, true, 0}, {"Separator_5", true, 0}, {T_Skeleton, true, 0}, {T_Tracker, true, 0}, {T_Hook, true, 0}, {T_Plastic, true, 0}, {"Separator_6", false, 0}, {T_Zoom, false, 0}, {T_Rotate, true, 0}, {T_Hand, false, 0}, {0, false, 0}}; } // namespace //============================================================================= // Toolbar //----------------------------------------------------------------------------- Toolbar::Toolbar(QWidget *parent, bool isVertical) : QToolBar(parent), m_isExpanded(ShowAllToolsToggle != 0) { // Fondamentale per lo style sheet setObjectName("toolBar"); setMovable(false); if (isVertical) setOrientation(Qt::Vertical); else setOrientation(Qt::Horizontal); setIconSize(QSize(20, 20)); setToolButtonStyle(Qt::ToolButtonIconOnly); m_expandButton = new QToolButton(this); m_expandButton->setObjectName("expandButton"); m_expandButton->setCheckable(true); m_expandButton->setChecked(m_isExpanded); m_expandButton->setArrowType((isVertical) ? Qt::DownArrow : Qt::RightArrow); m_expandAction = addWidget(m_expandButton); connect(m_expandButton, SIGNAL(toggled(bool)), this, SLOT(setIsExpanded(bool))); updateToolbar(); } //----------------------------------------------------------------------------- /*! Layout the tool buttons according to the state of the expandButton */ void Toolbar::updateToolbar() { TApp *app = TApp::instance(); TFrameHandle *frameHandle = app->getCurrentFrame(); if (frameHandle->isPlaying()) return; TXshLevelHandle *currlevel = app->getCurrentLevel(); TXshLevel *level = currlevel ? currlevel->getLevel() : 0; int levelType = level ? level->getType() : NO_XSHLEVEL; TColumnHandle *colHandle = app->getCurrentColumn(); int colIndex = colHandle->getColumnIndex(); int rowIndex = frameHandle->getFrameIndex(); if (Preferences::instance()->isAutoCreateEnabled() && Preferences::instance()->isAnimationSheetEnabled()) { // If in an empty cell, find most recent level if (levelType == NO_XSHLEVEL) { TXsheetHandle *xshHandle = app->getCurrentXsheet(); TXsheet *xsh = xshHandle->getXsheet(); if (colIndex >= 0 && !xsh->isColumnEmpty(colIndex)) { int r0, r1; xsh->getCellRange(colIndex, r0, r1); if (0 <= r0 && r0 <= r1) { // level type depends on previous occupied cell for (int r = std::min(r1, rowIndex); r >= r0; r--) { TXshCell cell = xsh->getCell(r, colIndex); if (cell.isEmpty()) continue; levelType = cell.m_level->getType(); rowIndex = r; break; } if (levelType == NO_XSHLEVEL) { TXshCell cell = xsh->getCell(r0, colIndex); levelType = cell.m_level->getType(); rowIndex = r0; } } } } } m_toolbarLevel = levelType; TTool::ToolTargetType targetType = TTool::NoTarget; switch (m_toolbarLevel) { case OVL_XSHLEVEL: targetType = TTool::RasterImage; break; case TZP_XSHLEVEL: targetType = TTool::ToonzImage; break; case PLI_XSHLEVEL: default: targetType = TTool::VectorImage; break; case MESH_XSHLEVEL: targetType = TTool::MeshImage; break; } // Hide action for now for (int idx = 0; buttonLayout[idx].toolName; idx++) { if (buttonLayout[idx].action) removeAction(buttonLayout[idx].action); } removeAction(m_expandAction); int levelBasedDisplay = Preferences::instance()->getLevelBasedToolsDisplay(); bool actionEnabled = false; ToolHandle *toolHandle = TApp::instance()->getCurrentTool(); for (int idx = 0; buttonLayout[idx].toolName; idx++) { TTool *tool = TTool::getTool(buttonLayout[idx].toolName, targetType); if (tool) tool->updateEnabled(rowIndex, colIndex); bool isSeparator = !strncmp(buttonLayout[idx].toolName, "Separator", 9); bool enable = !levelBasedDisplay ? true : (!tool ? actionEnabled : tool->isEnabled()); // Plastic tool should always be available so you can create a mesh if (!enable && !strncmp(buttonLayout[idx].toolName, T_Plastic, 9) && (m_toolbarLevel & LEVELCOLUMN_XSHLEVEL)) enable = true; if (!m_isExpanded && buttonLayout[idx].collapsable) continue; if (!buttonLayout[idx].action) { if (isSeparator) buttonLayout[idx].action = addSeparator(); else buttonLayout[idx].action = CommandManager::instance()->getAction(buttonLayout[idx].toolName); } if (levelBasedDisplay != 2) buttonLayout[idx].action->setEnabled(enable); else if (!enable) continue; actionEnabled = addAction(buttonLayout[idx].action) || actionEnabled; if (isSeparator) actionEnabled = false; } addAction(m_expandAction); if (m_isExpanded) { m_expandButton->setArrowType( (orientation() == Qt::Vertical) ? Qt::UpArrow : Qt::LeftArrow); m_expandButton->setToolTip(tr("Collapse toolbar")); } else { m_expandButton->setArrowType( (orientation() == Qt::Vertical) ? Qt::DownArrow : Qt::RightArrow); m_expandButton->setToolTip(tr("Expand toolbar")); } update(); } //---------------------------------------------------------------------------- void Toolbar::setIsExpanded(bool expand) { m_isExpanded = expand; ShowAllToolsToggle = (expand) ? 1 : 0; updateToolbar(); } //----------------------------------------------------------------------------- Toolbar::~Toolbar() {} //----------------------------------------------------------------------------- bool Toolbar::addAction(QAction *act) { if (!act) return false; QToolBar::addAction(act); return true; } //----------------------------------------------------------------------------- void Toolbar::showEvent(QShowEvent *e) { TColumnHandle *columnHandle = TApp::instance()->getCurrentColumn(); connect(columnHandle, SIGNAL(columnIndexSwitched()), this, SLOT(updateToolbar())); TFrameHandle *frameHandle = TApp::instance()->getCurrentFrame(); connect(frameHandle, SIGNAL(frameSwitched()), this, SLOT(updateToolbar())); connect(frameHandle, SIGNAL(frameTypeChanged()), this, SLOT(updateToolbar())); TXsheetHandle *xsheetHandle = TApp::instance()->getCurrentXsheet(); connect(xsheetHandle, SIGNAL(xsheetChanged()), this, SLOT(updateToolbar())); connect(TApp::instance()->getCurrentTool(), SIGNAL(toolSwitched()), SLOT(onToolChanged())); TXshLevelHandle *levelHandle = TApp::instance()->getCurrentLevel(); connect(levelHandle, SIGNAL(xshLevelSwitched(TXshLevel *)), this, SLOT(updateToolbar())); connect(TApp::instance()->getCurrentScene(), SIGNAL(preferenceChanged(const QString &)), this, SLOT(onPreferenceChanged(const QString &))); } //----------------------------------------------------------------------------- void Toolbar::hideEvent(QHideEvent *e) { disconnect(TApp::instance()->getCurrentLevel(), 0, this, 0); disconnect(TApp::instance()->getCurrentTool(), SIGNAL(toolSwitched()), this, SLOT(onToolChanged())); disconnect(TApp::instance()->getCurrentColumn(), SIGNAL(columnIndexSwitched()), this, SLOT(updateToolbar())); disconnect(TApp::instance()->getCurrentFrame(), SIGNAL(frameSwitched()), this, SLOT(updateToolbar())); disconnect(TApp::instance()->getCurrentFrame(), SIGNAL(frameTypeChanged()), this, SLOT(updateToolbar())); disconnect(TApp::instance()->getCurrentXsheet(), SIGNAL(xsheetChanged()), this, SLOT(updateToolbar())); disconnect(TApp::instance()->getCurrentScene(), SIGNAL(preferenceChanged(const QString &)), this, SLOT(onPreferenceChanged(const QString &))); } //----------------------------------------------------------------------------- void Toolbar::onToolChanged() { ToolHandle *toolHandle = TApp::instance()->getCurrentTool(); TTool *tool = toolHandle->getTool(); std::string toolName = tool->getName(); QAction *act = CommandManager::instance()->getAction(toolName.c_str()); if (!act || act->isChecked()) return; act->setChecked(true); } //----------------------------------------------------------------------------- void Toolbar::onPreferenceChanged(const QString &prefName) { if (prefName == "ToolbarDisplay" || prefName.isEmpty()) updateToolbar(); } //============================================================================= OpenFloatingPanel openToolbarPane(MI_OpenToolbar, "ToolBar", "");
#ifndef __FLAGS_FLAGS_HPP__ #define __FLAGS_FLAGS_HPP__ #include <stdlib.h> // For abort. #include <map> #include <string> #include <typeinfo> // For typeid. #include <tr1/functional> #include <stout/option.hpp> #include <stout/stringify.hpp> #include <stout/try.hpp> #include "flags/flag.hpp" #include "flags/loader.hpp" #include "flags/parse.hpp" // An abstraction for application/library "flags". An example is // probably best: // ------------------------------------------------------------- // class MyFlags : public virtual FlagsBase // Use 'virtual' for composition! // { // public: // Flags() // { // add(&debug, // "debug", // "Help string for debug", // false); // // add(&name, // "name", // "Help string for name"); // } // bool debug; // Option<string> name; // }; // // ... // // map<string, Option<string> > values; // values["no-debug"] = None(); // --no-debug // values["debug"] = None(); // --debug // values["debug"] = Option<string>::some("true"); // --debug=true // values["debug"] = Option<string>::some("false"); // --debug=false // values["name"] = Option<string>::some("frank"); // --name=frank // // MyFlags flags; // flags.load(values); // flags.name.isSome() ... // flags.debug ... // ------------------------------------------------------------- // // You can also compose flags provided that each has used "virtual // inheritance": // ------------------------------------------------------------- // Flags<MyFlags1, MyFlags2> flags; // flags.add(...); // Any other flags you want to throw in there. // flags.load(values); // flags.flag_from_myflags1 ... // flags.flag_from_myflags2 ... // ------------------------------------------------------------- // // "Fail early, fail often": // // You can not add duplicate flags, this is checked for you at compile // time for composite flags (e.g., Flag<MyFlags1, MyFlags2>) and also // checked at runtime for any other flags added via inheritance or // Flags::add(...). // // Flags that can not be loaded (e.g., attempting to use the 'no-' // prefix for a flag that is not boolean) will print a message to // standard error and abort the process. // TODO(benh): Provide a boolean which specifies whether or not to // abort on duplicates or load errors. // TODO(benh): Make prefix for environment variables configurable // (e.g., "MESOS_"). namespace flags { class FlagsBase { public: virtual ~FlagsBase() {} virtual void load(const std::map<std::string, Option<std::string> >& values); virtual void load(const std::map<std::string, std::string>& values); typedef std::map<std::string, Flag>::const_iterator const_iterator; const_iterator begin() const { return flags.begin(); } const_iterator end() const { return flags.end(); } protected: template <typename Flags, typename T1, typename T2> void add(T1 Flags::*t1, const std::string& name, const std::string& help, const T2& t2); template <typename Flags, typename T> void add(Option<T> Flags::*option, const std::string& name, const std::string& help); void add(const Flag& flag); private: std::map<std::string, Flag> flags; }; // Need to declare/define some explicit subclasses of FlagsBase so // that we can overload the 'Flags::operator FlagsN () const' // functions for each possible type. class _Flags1 : public virtual FlagsBase {}; class _Flags2 : public virtual FlagsBase {}; class _Flags3 : public virtual FlagsBase {}; class _Flags4 : public virtual FlagsBase {}; class _Flags5 : public virtual FlagsBase {}; // TODO(benh): Add some "type constraints" for template paramters to // make sure they are all of type FlagsBase. template <typename Flags1 = _Flags1, typename Flags2 = _Flags2, typename Flags3 = _Flags3, typename Flags4 = _Flags4, typename Flags5 = _Flags5> class Flags : public virtual Flags1, public virtual Flags2, public virtual Flags3, public virtual Flags4, public virtual Flags5 { public: template <typename T1, typename T2> void add(T1* t1, const std::string& name, const std::string& help, const T2& t2); template <typename T> void add(Option<T>* option, const std::string& name, const std::string& help); }; template <typename Flags, typename T1, typename T2> void FlagsBase::add( T1 Flags::*t1, const std::string& name, const std::string& help, const T2& t2) { Flags* flags = dynamic_cast<Flags*>(this); if (flags == NULL) { std::cerr << "Attempted to add flag '" << name << "' with incompatible type" << std::endl; abort(); } else { flags->*t1 = t2; // Set the default. } Flag flag; flag.name = name; flag.help = help; flag.boolean = typeid(T1) == typeid(bool); flag.loader = std::tr1::bind( &MemberLoader<Flags, T1>::load, std::tr1::placeholders::_1, t1, std::tr1::function<Try<T1>(const std::string&)>( std::tr1::bind(&parse<T1>, std::tr1::placeholders::_1)), name, std::tr1::placeholders::_2); // Update the help string to include the default value. flag.help += help.size() > 0 && help.find_last_of("\n\r") != help.size() - 1 ? " (default: " // On same line, add space. : "(default: "; // On newline. flag.help += stringify(t2); flag.help += ")"; flag.help += ")"; add(flag); } template <typename Flags, typename T> void FlagsBase::add( Option<T> Flags::*option, const std::string& name, const std::string& help) { Flags* flags = dynamic_cast<Flags*>(this); if (flags == NULL) { std::cerr << "Attempted to add flag '" << name << "' with incompatible type" << std::endl; abort(); } Flag flag; flag.name = name; flag.help = help; flag.boolean = typeid(T) == typeid(bool); flag.loader = std::tr1::bind( &OptionMemberLoader<Flags, T>::load, std::tr1::placeholders::_1, option, std::tr1::function<Try<T>(const std::string&)>( std::tr1::bind(&parse<T>, std::tr1::placeholders::_1)), name, std::tr1::placeholders::_2); add(flag); } inline void FlagsBase::add(const Flag& flag) { if (flags.count(flag.name) > 0) { std::cerr << "Attempted to add duplicate flag '" << flag.name << "'" << std::endl; abort(); } flags[flag.name] = flag; } inline void FlagsBase::load(const std::map<std::string, Option<std::string> >& values) { std::map<std::string, Option<std::string> >::const_iterator iterator; for (iterator = values.begin(); iterator != values.end(); ++iterator) { const std::string& name = iterator->first; const Option<std::string>& value = iterator->second; if (flags.count(name) > 0) { if (value.isSome()) { flags[name].loader(this, value.get()); // --name=value } else if (flags[name].boolean) { flags[name].loader(this, "true"); // --name } else { std::cerr << "Failed to load non-boolean flag via '" << name << "'" << std::endl; abort(); } } else if (name.find("no-") == 0 && flags.count(name.substr(3)) > 0) { if (flags[name.substr(3)].boolean) { if (value.isNone()) { flags[name.substr(3)].loader(this, "false"); // --no-name } else { std::cerr << "Failed to load boolean flag '" << name.substr(3) << "' via '" << name << "' with value '" << value.get() << "'" << std::endl; abort(); } } else { std::cerr << "Failed to load non-boolean flag '" << name.substr(3) << "' via '" << name << "'" << std::endl; abort(); } } } } inline void FlagsBase::load(const std::map<std::string, std::string>& _values) { std::map<std::string, Option<std::string> > values; std::map<std::string, std::string>::const_iterator iterator; for (iterator = _values.begin(); iterator != _values.end(); ++iterator) { const std::string& name = iterator->first; const std::string& value = iterator->second; values[name] = Option<std::string>::some(value); } load(values); } template <typename Flags1, typename Flags2, typename Flags3, typename Flags4, typename Flags5> template <typename T1, typename T2> void Flags<Flags1, Flags2, Flags3, Flags4, Flags5>::add( T1* t1, const std::string& name, const std::string& help, const T2& t2) { *t1 = t2; // Set the default. Flag flag; flag.name = name; flag.help = help; flag.boolean = typeid(T1) == typeid(bool); flag.loader = std::tr1::bind( &Loader<T1>::load, t1, std::tr1::function<Try<T1>(const std::string&)>( std::tr1::bind(&parse<T1>, std::tr1::placeholders::_1)), name, std::tr1::placeholders::_2); // Use _2 because ignore FlagsBase*. // Update the help string to include the default value. flag.help += help.size() > 0 && help.find_last_of("\n\r") != help.size() - 1 ? " (default: " // On same line, add space. : "(default: "; // On newline. flag.help += stringify(t2); flag.help += ")"; FlagsBase::add(flag); } template <typename Flags1, typename Flags2, typename Flags3, typename Flags4, typename Flags5> template <typename T> void Flags<Flags1, Flags2, Flags3, Flags4, Flags5>::add( Option<T>* option, const std::string& name, const std::string& help) { Flag flag; flag.name = name; flag.help = help; flag.boolean = typeid(T) == typeid(bool); flag.loader = std::tr1::bind( &OptionLoader<T>::load, option, std::tr1::function<Try<T>(const std::string&)>( std::tr1::bind(&parse<T>, std::tr1::placeholders::_1)), name, std::tr1::placeholders::_2); // Use _2 because ignore FlagsBase*. FlagsBase::add(flag); } } // namespace flags { #endif // __FLAGS_FLAGS_HPP__
// Copyright (c) 2011-2016 The Helveticum Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/helveticum-config.h" #endif #include "rpcconsole.h" #include "ui_debugwindow.h" #include "bantablemodel.h" #include "clientmodel.h" #include "guiutil.h" #include "platformstyle.h" #include "chainparams.h" #include "netbase.h" #include "rpc/server.h" #include "rpc/client.h" #include "util.h" #include <openssl/crypto.h> #include <univalue.h> #ifdef ENABLE_WALLET #include <db_cxx.h> #endif #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QSignalMapper> #include <QThread> #include <QTime> #include <QTimer> #include <QStringList> #if QT_VERSION < 0x050000 #include <QUrl> #endif // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const int INITIAL_TRAFFIC_GRAPH_MINS = 30; const QSize FONT_RANGE(4, 40); const char fontSizeSettingsKey[] = "consoleFontSize"; const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; namespace { // don't add private key handling cmd's to the history const QStringList historyFilter = QStringList() << "importprivkey" << "importmulti" << "signmessagewithprivkey" << "signrawtransaction" << "walletpassphrase" << "walletpassphrasechange" << "encryptwallet"; } /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public Q_SLOTS: void request(const QString &command); Q_SIGNALS: void reply(int category, const QString &command); }; /** Class for handling RPC timers * (used for e.g. re-locking the wallet after a timeout) */ class QtRPCTimerBase: public QObject, public RPCTimerBase { Q_OBJECT public: QtRPCTimerBase(std::function<void(void)>& _func, int64_t millis): func(_func) { timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(timeout())); timer.start(millis); } ~QtRPCTimerBase() {} private Q_SLOTS: void timeout() { func(); } private: QTimer timer; std::function<void(void)> func; }; class QtRPCTimerInterface: public RPCTimerInterface { public: ~QtRPCTimerInterface() {} const char *Name() { return "Qt"; } RPCTimerBase* NewTimer(std::function<void(void)>& func, int64_t millis) { return new QtRPCTimerBase(func, millis); } }; #include "rpcconsole.moc" /** * Split shell command line into a list of arguments and optionally execute the command(s). * Aims to emulate \c bash and friends. * * - Command nesting is possible with parenthesis; for example: validateaddress(getnewaddress()) * - Arguments are delimited with whitespace or comma * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] result stringified Result from the executed command(chain) * @param[in] strCommand Command line to split * @param[in] fExecute set true if you want the command to be executed * @param[out] pstrFilteredOut Command line, filtered to remove any sensitive data */ bool RPCConsole::RPCParseCommandLine(std::string &strResult, const std::string &strCommand, const bool fExecute, std::string * const pstrFilteredOut) { std::vector< std::vector<std::string> > stack; stack.push_back(std::vector<std::string>()); enum CmdParseState { STATE_EATING_SPACES, STATE_EATING_SPACES_IN_ARG, STATE_EATING_SPACES_IN_BRACKETS, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED, STATE_COMMAND_EXECUTED, STATE_COMMAND_EXECUTED_INNER } state = STATE_EATING_SPACES; std::string curarg; UniValue lastResult; unsigned nDepthInsideSensitive = 0; size_t filter_begin_pos = 0, chpos; std::vector<std::pair<size_t, size_t>> filter_ranges; auto add_to_current_stack = [&](const std::string& strArg) { if (stack.back().empty() && (!nDepthInsideSensitive) && historyFilter.contains(QString::fromStdString(strArg), Qt::CaseInsensitive)) { nDepthInsideSensitive = 1; filter_begin_pos = chpos; } // Make sure stack is not empty before adding something if (stack.empty()) { stack.push_back(std::vector<std::string>()); } stack.back().push_back(strArg); }; auto close_out_params = [&]() { if (nDepthInsideSensitive) { if (!--nDepthInsideSensitive) { assert(filter_begin_pos); filter_ranges.push_back(std::make_pair(filter_begin_pos, chpos)); filter_begin_pos = 0; } } stack.pop_back(); }; std::string strCommandTerminated = strCommand; if (strCommandTerminated.back() != '\n') strCommandTerminated += "\n"; for (chpos = 0; chpos < strCommandTerminated.size(); ++chpos) { char ch = strCommandTerminated[chpos]; switch(state) { case STATE_COMMAND_EXECUTED_INNER: case STATE_COMMAND_EXECUTED: { bool breakParsing = true; switch(ch) { case '[': curarg.clear(); state = STATE_COMMAND_EXECUTED_INNER; break; default: if (state == STATE_COMMAND_EXECUTED_INNER) { if (ch != ']') { // append char to the current argument (which is also used for the query command) curarg += ch; break; } if (curarg.size() && fExecute) { // if we have a value query, query arrays with index and objects with a string key UniValue subelement; if (lastResult.isArray()) { for(char argch: curarg) if (!std::isdigit(argch)) throw std::runtime_error("Invalid result query"); subelement = lastResult[atoi(curarg.c_str())]; } else if (lastResult.isObject()) subelement = find_value(lastResult, curarg); else throw std::runtime_error("Invalid result query"); //no array or object: abort lastResult = subelement; } state = STATE_COMMAND_EXECUTED; break; } // don't break parsing when the char is required for the next argument breakParsing = false; // pop the stack and return the result to the current command arguments close_out_params(); // don't stringify the json in case of a string to avoid doublequotes if (lastResult.isStr()) curarg = lastResult.get_str(); else curarg = lastResult.write(2); // if we have a non empty result, use it as stack argument otherwise as general result if (curarg.size()) { if (stack.size()) add_to_current_stack(curarg); else strResult = curarg; } curarg.clear(); // assume eating space state state = STATE_EATING_SPACES; } if (breakParsing) break; } case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES_IN_ARG: case STATE_EATING_SPACES_IN_BRACKETS: case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case '(': case ')': case '\n': if (state == STATE_EATING_SPACES_IN_ARG) throw std::runtime_error("Invalid Syntax"); if (state == STATE_ARGUMENT) { if (ch == '(' && stack.size() && stack.back().size() > 0) { if (nDepthInsideSensitive) { ++nDepthInsideSensitive; } stack.push_back(std::vector<std::string>()); } // don't allow commands after executed commands on baselevel if (!stack.size()) throw std::runtime_error("Invalid Syntax"); add_to_current_stack(curarg); curarg.clear(); state = STATE_EATING_SPACES_IN_BRACKETS; } if ((ch == ')' || ch == '\n') && stack.size() > 0) { if (fExecute) { // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. JSONRPCRequest req; req.params = RPCConvertValues(stack.back()[0], std::vector<std::string>(stack.back().begin() + 1, stack.back().end())); req.strMethod = stack.back()[0]; lastResult = tableRPC.execute(req); } state = STATE_COMMAND_EXECUTED; curarg.clear(); } break; case ' ': case ',': case '\t': if(state == STATE_EATING_SPACES_IN_ARG && curarg.empty() && ch == ',') throw std::runtime_error("Invalid Syntax"); else if(state == STATE_ARGUMENT) // Space ends argument { add_to_current_stack(curarg); curarg.clear(); } if ((state == STATE_EATING_SPACES_IN_BRACKETS || state == STATE_ARGUMENT) && ch == ',') { state = STATE_EATING_SPACES_IN_ARG; break; } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } if (pstrFilteredOut) { if (STATE_COMMAND_EXECUTED == state) { assert(!stack.empty()); close_out_params(); } *pstrFilteredOut = strCommand; for (auto i = filter_ranges.rbegin(); i != filter_ranges.rend(); ++i) { pstrFilteredOut->replace(i->first, i->second - i->first, "(…)"); } } switch(state) // final state { case STATE_COMMAND_EXECUTED: if (lastResult.isStr()) strResult = lastResult.get_str(); else strResult = lastResult.write(2); case STATE_ARGUMENT: case STATE_EATING_SPACES: return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { try { std::string result; std::string executableCommand = command.toStdString() + "\n"; if(!RPCConsole::RPCExecuteCommandLine(result, executableCommand)) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } Q_EMIT reply(RPCConsole::CMD_REPLY, QString::fromStdString(result)); } catch (UniValue& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch (const std::runtime_error&) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object Q_EMIT reply(RPCConsole::CMD_ERROR, QString::fromStdString(objError.write())); } } catch (const std::exception& e) { Q_EMIT reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(const PlatformStyle *_platformStyle, QWidget *parent) : QWidget(parent), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0), platformStyle(_platformStyle), peersTableContextMenu(0), banTableContextMenu(0), consoleFontSize(0) { ui->setupUi(this); GUIUtil::restoreWindowGeometry("nRPCConsoleWindow", this->size(), this); ui->openDebugLogfileButton->setToolTip(ui->openDebugLogfileButton->toolTip().arg(tr(PACKAGE_NAME))); if (platformStyle->getImagesOnButtons()) { ui->openDebugLogfileButton->setIcon(platformStyle->SingleColorIcon(":/icons/export")); } ui->clearButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->fontBiggerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontbigger")); ui->fontSmallerButton->setIcon(platformStyle->SingleColorIcon(":/icons/fontsmaller")); // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); connect(ui->fontBiggerButton, SIGNAL(clicked()), this, SLOT(fontBigger())); connect(ui->fontSmallerButton, SIGNAL(clicked()), this, SLOT(fontSmaller())); connect(ui->btnClearTrafficGraph, SIGNAL(clicked()), ui->trafficGraph, SLOT(clear())); // set library version labels #ifdef ENABLE_WALLET ui->berkeleyDBVersion->setText(DbEnv::version(0, 0, 0)); #else ui->label_berkeleyDBVersion->hide(); ui->berkeleyDBVersion->hide(); #endif // Register RPC timer interface rpcTimerInterface = new QtRPCTimerInterface(); // avoid accidentally overwriting an existing, non QTThread // based timer interface RPCSetTimerInterfaceIfUnset(rpcTimerInterface); setTrafficGraphRange(INITIAL_TRAFFIC_GRAPH_MINS); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); QSettings settings; consoleFontSize = settings.value(fontSizeSettingsKey, QFontInfo(QFont()).pointSize()).toInt(); clear(); } RPCConsole::~RPCConsole() { GUIUtil::saveWindowGeometry("nRPCConsoleWindow", this); RPCUnsetTimerInterface(rpcTimerInterface); delete rpcTimerInterface; delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; case Qt::Key_Return: case Qt::Key_Enter: // forward these events to lineEdit if(obj == autoCompleter->popup()) { QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QWidget::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { clientModel = model; ui->trafficGraph->setClientModel(model); if (model && clientModel->getPeerTableModel() && clientModel->getBanTableModel()) { // Keep up to date with client setNumConnections(model->getNumConnections()); connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); setNumBlocks(model->getNumBlocks(), model->getLastBlockDate(), model->getVerificationProgress(NULL), false); connect(model, SIGNAL(numBlocksChanged(int,QDateTime,double,bool)), this, SLOT(setNumBlocks(int,QDateTime,double,bool))); updateNetworkState(); connect(model, SIGNAL(networkActiveChanged(bool)), this, SLOT(setNetworkActive(bool))); updateTrafficStats(model->getTotalBytesRecv(), model->getTotalBytesSent()); connect(model, SIGNAL(bytesChanged(quint64,quint64)), this, SLOT(updateTrafficStats(quint64, quint64))); connect(model, SIGNAL(mempoolSizeChanged(long,size_t)), this, SLOT(setMempoolSize(long,size_t))); // set up peer table ui->peerWidget->setModel(model->getPeerTableModel()); ui->peerWidget->verticalHeader()->hide(); ui->peerWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->peerWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->peerWidget->setSelectionMode(QAbstractItemView::ExtendedSelection); ui->peerWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->peerWidget->setColumnWidth(PeerTableModel::Address, ADDRESS_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Subversion, SUBVERSION_COLUMN_WIDTH); ui->peerWidget->setColumnWidth(PeerTableModel::Ping, PING_COLUMN_WIDTH); ui->peerWidget->horizontalHeader()->setStretchLastSection(true); // create peer table context menu actions QAction* disconnectAction = new QAction(tr("&Disconnect"), this); QAction* banAction1h = new QAction(tr("Ban for") + " " + tr("1 &hour"), this); QAction* banAction24h = new QAction(tr("Ban for") + " " + tr("1 &day"), this); QAction* banAction7d = new QAction(tr("Ban for") + " " + tr("1 &week"), this); QAction* banAction365d = new QAction(tr("Ban for") + " " + tr("1 &year"), this); // create peer table context menu peersTableContextMenu = new QMenu(this); peersTableContextMenu->addAction(disconnectAction); peersTableContextMenu->addAction(banAction1h); peersTableContextMenu->addAction(banAction24h); peersTableContextMenu->addAction(banAction7d); peersTableContextMenu->addAction(banAction365d); // Add a signal mapping to allow dynamic context menu arguments. // We need to use int (instead of int64_t), because signal mapper only supports // int or objects, which is okay because max bantime (1 year) is < int_max. QSignalMapper* signalMapper = new QSignalMapper(this); signalMapper->setMapping(banAction1h, 60*60); signalMapper->setMapping(banAction24h, 60*60*24); signalMapper->setMapping(banAction7d, 60*60*24*7); signalMapper->setMapping(banAction365d, 60*60*24*365); connect(banAction1h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction24h, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction7d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(banAction365d, SIGNAL(triggered()), signalMapper, SLOT(map())); connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(banSelectedNode(int))); // peer table context menu signals connect(ui->peerWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showPeersTableContextMenu(const QPoint&))); connect(disconnectAction, SIGNAL(triggered()), this, SLOT(disconnectSelectedNode())); // peer table signal handling - update peer details when selecting new node connect(ui->peerWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), this, SLOT(peerSelected(const QItemSelection &, const QItemSelection &))); // peer table signal handling - update peer details when new nodes are added to the model connect(model->getPeerTableModel(), SIGNAL(layoutChanged()), this, SLOT(peerLayoutChanged())); // peer table signal handling - cache selected node ids connect(model->getPeerTableModel(), SIGNAL(layoutAboutToBeChanged()), this, SLOT(peerLayoutAboutToChange())); // set up ban table ui->banlistWidget->setModel(model->getBanTableModel()); ui->banlistWidget->verticalHeader()->hide(); ui->banlistWidget->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->banlistWidget->setSelectionBehavior(QAbstractItemView::SelectRows); ui->banlistWidget->setSelectionMode(QAbstractItemView::SingleSelection); ui->banlistWidget->setContextMenuPolicy(Qt::CustomContextMenu); ui->banlistWidget->setColumnWidth(BanTableModel::Address, BANSUBNET_COLUMN_WIDTH); ui->banlistWidget->setColumnWidth(BanTableModel::Bantime, BANTIME_COLUMN_WIDTH); ui->banlistWidget->horizontalHeader()->setStretchLastSection(true); // create ban table context menu action QAction* unbanAction = new QAction(tr("&Unban"), this); // create ban table context menu banTableContextMenu = new QMenu(this); banTableContextMenu->addAction(unbanAction); // ban table context menu signals connect(ui->banlistWidget, SIGNAL(customContextMenuRequested(const QPoint&)), this, SLOT(showBanTableContextMenu(const QPoint&))); connect(unbanAction, SIGNAL(triggered()), this, SLOT(unbanSelectedNode())); // ban table signal handling - clear peer details when clicking a peer in the ban table connect(ui->banlistWidget, SIGNAL(clicked(const QModelIndex&)), this, SLOT(clearSelectedNode())); // ban table signal handling - ensure ban table is shown or hidden (if empty) connect(model->getBanTableModel(), SIGNAL(layoutChanged()), this, SLOT(showOrHideBanTableIfRequired())); showOrHideBanTableIfRequired(); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientUserAgent->setText(model->formatSubVersion()); ui->dataDir->setText(model->dataDir()); ui->startupTime->setText(model->formatClientStartupTime()); ui->networkName->setText(QString::fromStdString(Params().NetworkIDString())); //Setup autocomplete and attach it QStringList wordList; std::vector<std::string> commandList = tableRPC.listCommands(); for (size_t i = 0; i < commandList.size(); ++i) { wordList << commandList[i].c_str(); wordList << ("help " + commandList[i]).c_str(); } wordList.sort(); autoCompleter = new QCompleter(wordList, this); autoCompleter->setModelSorting(QCompleter::CaseSensitivelySortedModel); ui->lineEdit->setCompleter(autoCompleter); autoCompleter->popup()->installEventFilter(this); // Start thread to execute RPC commands. startExecutor(); } if (!model) { // Client model is being set to 0, this means shutdown() is about to be called. // Make sure we clean up the executor thread Q_EMIT stopExecutor(); thread.wait(); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::fontBigger() { setFontSize(consoleFontSize+1); } void RPCConsole::fontSmaller() { setFontSize(consoleFontSize-1); } void RPCConsole::setFontSize(int newSize) { QSettings settings; //don't allow a insane font size if (newSize < FONT_RANGE.width() || newSize > FONT_RANGE.height()) return; // temp. store the console content QString str = ui->messagesWidget->toHtml(); // replace font tags size in current content str.replace(QString("font-size:%1pt").arg(consoleFontSize), QString("font-size:%1pt").arg(newSize)); // store the new font size consoleFontSize = newSize; settings.setValue(fontSizeSettingsKey, consoleFontSize); // clear console (reset icon sizes, default stylesheet) and re-add the content float oldPosFactor = 1.0 / ui->messagesWidget->verticalScrollBar()->maximum() * ui->messagesWidget->verticalScrollBar()->value(); clear(false); ui->messagesWidget->setHtml(str); ui->messagesWidget->verticalScrollBar()->setValue(oldPosFactor * ui->messagesWidget->verticalScrollBar()->maximum()); } void RPCConsole::clear(bool clearHistory) { ui->messagesWidget->clear(); if(clearHistory) { history.clear(); historyPtr = 0; } ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), platformStyle->SingleColorImage(ICON_MAPPING[i].source).scaled(QSize(consoleFontSize*2, consoleFontSize*2), Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet QFontInfo fixedFontInfo(GUIUtil::fixedPitchFont()); ui->messagesWidget->document()->setDefaultStyleSheet( QString( "table { }" "td.time { color: #808080; font-size: %2; padding-top: 3px; } " "td.message { font-family: %1; font-size: %2; white-space:pre-wrap; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " ".secwarning { color: red; }" "b { color: #006060; } " ).arg(fixedFontInfo.family(), QString("%1pt").arg(consoleFontSize)) ); #ifdef Q_OS_MAC QString clsKey = "(⌘)-L"; #else QString clsKey = "Ctrl-L"; #endif message(CMD_REPLY, (tr("Welcome to the %1 RPC console.").arg(tr(PACKAGE_NAME)) + "<br>" + tr("Use up and down arrows to navigate history, and %1 to clear screen.").arg("<b>"+clsKey+"</b>") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")) + "<br><span class=\"secwarning\">" + tr("WARNING: Scammers have been active, telling users to type commands here, stealing their wallet contents. Do not use this console without fully understanding the ramification of a command.") + "</span>", true); } void RPCConsole::keyPressEvent(QKeyEvent *event) { if(windowType() != Qt::Widget && event->key() == Qt::Key_Escape) { close(); } } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, false); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::updateNetworkState() { QString connections = QString::number(clientModel->getNumConnections()) + " ("; connections += tr("In:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_IN)) + " / "; connections += tr("Out:") + " " + QString::number(clientModel->getNumConnections(CONNECTIONS_OUT)) + ")"; if(!clientModel->getNetworkActive()) { connections += " (" + tr("Network activity disabled") + ")"; } ui->numberOfConnections->setText(connections); } void RPCConsole::setNumConnections(int count) { if (!clientModel) return; updateNetworkState(); } void RPCConsole::setNetworkActive(bool networkActive) { updateNetworkState(); } void RPCConsole::setNumBlocks(int count, const QDateTime& blockDate, double nVerificationProgress, bool headers) { if (!headers) { ui->numberOfBlocks->setText(QString::number(count)); ui->lastBlockTime->setText(blockDate.toString()); } } void RPCConsole::setMempoolSize(long numberOfTxs, size_t dynUsage) { ui->mempoolNumberTxs->setText(QString::number(numberOfTxs)); if (dynUsage < 1000000) ui->mempoolSize->setText(QString::number(dynUsage/1000.0, 'f', 2) + " KB"); else ui->mempoolSize->setText(QString::number(dynUsage/1000000.0, 'f', 2) + " MB"); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); if(!cmd.isEmpty()) { std::string strFilteredCmd; try { std::string dummy; if (!RPCParseCommandLine(dummy, cmd.toStdString(), false, &strFilteredCmd)) { // Failed to parse command, so we cannot even filter it for the history throw std::runtime_error("Invalid command line"); } } catch (const std::exception& e) { QMessageBox::critical(this, "Error", QString("Error: ") + QString::fromStdString(e.what())); return; } ui->lineEdit->clear(); cmdBeforeBrowsing = QString(); message(CMD_REQUEST, QString::fromStdString(strFilteredCmd)); Q_EMIT cmdRequest(cmd); cmd = QString::fromStdString(strFilteredCmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { // store current text when start browsing through the history if (historyPtr == history.size()) { cmdBeforeBrowsing = ui->lineEdit->text(); } historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); else if (!cmdBeforeBrowsing.isNull()) { cmd = cmdBeforeBrowsing; } ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(&thread); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), &thread, SLOT(quit())); // - queue executor for deletion (in execution thread) connect(&thread, SIGNAL(finished()), executor, SLOT(deleteLater()), Qt::DirectConnection); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread.start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if (ui->tabWidget->widget(index) == ui->tab_console) ui->lineEdit->setFocus(); else if (ui->tabWidget->widget(index) != ui->tab_peers) clearSelectedNode(); } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_sldGraphRange_valueChanged(int value) { const int multiplier = 5; // each position on the slider represents 5 min int mins = value * multiplier; setTrafficGraphRange(mins); } QString RPCConsole::FormatBytes(quint64 bytes) { if(bytes < 1024) return QString(tr("%1 B")).arg(bytes); if(bytes < 1024 * 1024) return QString(tr("%1 KB")).arg(bytes / 1024); if(bytes < 1024 * 1024 * 1024) return QString(tr("%1 MB")).arg(bytes / 1024 / 1024); return QString(tr("%1 GB")).arg(bytes / 1024 / 1024 / 1024); } void RPCConsole::setTrafficGraphRange(int mins) { ui->trafficGraph->setGraphRangeMins(mins); ui->lblGraphRange->setText(GUIUtil::formatDurationStr(mins * 60)); } void RPCConsole::updateTrafficStats(quint64 totalBytesIn, quint64 totalBytesOut) { ui->lblBytesIn->setText(FormatBytes(totalBytesIn)); ui->lblBytesOut->setText(FormatBytes(totalBytesOut)); } void RPCConsole::peerSelected(const QItemSelection &selected, const QItemSelection &deselected) { Q_UNUSED(deselected); if (!clientModel || !clientModel->getPeerTableModel() || selected.indexes().isEmpty()) return; const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.indexes().first().row()); if (stats) updateNodeDetail(stats); } void RPCConsole::peerLayoutAboutToChange() { QModelIndexList selected = ui->peerWidget->selectionModel()->selectedIndexes(); cachedNodeids.clear(); for(int i = 0; i < selected.size(); i++) { const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(selected.at(i).row()); cachedNodeids.append(stats->nodeStats.nodeid); } } void RPCConsole::peerLayoutChanged() { if (!clientModel || !clientModel->getPeerTableModel()) return; const CNodeCombinedStats *stats = NULL; bool fUnselect = false; bool fReselect = false; if (cachedNodeids.empty()) // no node selected yet return; // find the currently selected row int selectedRow = -1; QModelIndexList selectedModelIndex = ui->peerWidget->selectionModel()->selectedIndexes(); if (!selectedModelIndex.isEmpty()) { selectedRow = selectedModelIndex.first().row(); } // check if our detail node has a row in the table (it may not necessarily // be at selectedRow since its position can change after a layout change) int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.first()); if (detailNodeRow < 0) { // detail node disappeared from table (node disconnected) fUnselect = true; } else { if (detailNodeRow != selectedRow) { // detail node moved position fUnselect = true; fReselect = true; } // get fresh stats on the detail node. stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); } if (fUnselect && selectedRow >= 0) { clearSelectedNode(); } if (fReselect) { for(int i = 0; i < cachedNodeids.size(); i++) { ui->peerWidget->selectRow(clientModel->getPeerTableModel()->getRowByNodeId(cachedNodeids.at(i))); } } if (stats) updateNodeDetail(stats); } void RPCConsole::updateNodeDetail(const CNodeCombinedStats *stats) { // update the detail ui with latest node information QString peerAddrDetails(QString::fromStdString(stats->nodeStats.addrName) + " "); peerAddrDetails += tr("(node id: %1)").arg(QString::number(stats->nodeStats.nodeid)); if (!stats->nodeStats.addrLocal.empty()) peerAddrDetails += "<br />" + tr("via %1").arg(QString::fromStdString(stats->nodeStats.addrLocal)); ui->peerHeading->setText(peerAddrDetails); ui->peerServices->setText(GUIUtil::formatServicesStr(stats->nodeStats.nServices)); ui->peerLastSend->setText(stats->nodeStats.nLastSend ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastSend) : tr("never")); ui->peerLastRecv->setText(stats->nodeStats.nLastRecv ? GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nLastRecv) : tr("never")); ui->peerBytesSent->setText(FormatBytes(stats->nodeStats.nSendBytes)); ui->peerBytesRecv->setText(FormatBytes(stats->nodeStats.nRecvBytes)); ui->peerConnTime->setText(GUIUtil::formatDurationStr(GetSystemTimeInSeconds() - stats->nodeStats.nTimeConnected)); ui->peerPingTime->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingTime)); ui->peerPingWait->setText(GUIUtil::formatPingTime(stats->nodeStats.dPingWait)); ui->peerMinPing->setText(GUIUtil::formatPingTime(stats->nodeStats.dMinPing)); ui->timeoffset->setText(GUIUtil::formatTimeOffset(stats->nodeStats.nTimeOffset)); ui->peerVersion->setText(QString("%1").arg(QString::number(stats->nodeStats.nVersion))); ui->peerSubversion->setText(QString::fromStdString(stats->nodeStats.cleanSubVer)); ui->peerDirection->setText(stats->nodeStats.fInbound ? tr("Inbound") : tr("Outbound")); ui->peerHeight->setText(QString("%1").arg(QString::number(stats->nodeStats.nStartingHeight))); ui->peerWhitelisted->setText(stats->nodeStats.fWhitelisted ? tr("Yes") : tr("No")); // This check fails for example if the lock was busy and // nodeStateStats couldn't be fetched. if (stats->fNodeStateStatsAvailable) { // Ban score is init to 0 ui->peerBanScore->setText(QString("%1").arg(stats->nodeStateStats.nMisbehavior)); // Sync height is init to -1 if (stats->nodeStateStats.nSyncHeight > -1) ui->peerSyncHeight->setText(QString("%1").arg(stats->nodeStateStats.nSyncHeight)); else ui->peerSyncHeight->setText(tr("Unknown")); // Common height is init to -1 if (stats->nodeStateStats.nCommonHeight > -1) ui->peerCommonHeight->setText(QString("%1").arg(stats->nodeStateStats.nCommonHeight)); else ui->peerCommonHeight->setText(tr("Unknown")); } ui->detailWidget->show(); } void RPCConsole::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); } void RPCConsole::showEvent(QShowEvent *event) { QWidget::showEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // start PeerTableModel auto refresh clientModel->getPeerTableModel()->startAutoRefresh(); } void RPCConsole::hideEvent(QHideEvent *event) { QWidget::hideEvent(event); if (!clientModel || !clientModel->getPeerTableModel()) return; // stop PeerTableModel auto refresh clientModel->getPeerTableModel()->stopAutoRefresh(); } void RPCConsole::showPeersTableContextMenu(const QPoint& point) { QModelIndex index = ui->peerWidget->indexAt(point); if (index.isValid()) peersTableContextMenu->exec(QCursor::pos()); } void RPCConsole::showBanTableContextMenu(const QPoint& point) { QModelIndex index = ui->banlistWidget->indexAt(point); if (index.isValid()) banTableContextMenu->exec(QCursor::pos()); } void RPCConsole::disconnectSelectedNode() { if(!g_connman) return; // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Find the node, disconnect it and clear the selected node if(g_connman->DisconnectNode(id)) clearSelectedNode(); } } void RPCConsole::banSelectedNode(int bantime) { if (!clientModel || !g_connman) return; // Get selected peer addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->peerWidget, PeerTableModel::NetNodeId); for(int i = 0; i < nodes.count(); i++) { // Get currently selected peer address NodeId id = nodes.at(i).data().toLongLong(); // Get currently selected peer address int detailNodeRow = clientModel->getPeerTableModel()->getRowByNodeId(id); if(detailNodeRow < 0) return; // Find possible nodes, ban it and clear the selected node const CNodeCombinedStats *stats = clientModel->getPeerTableModel()->getNodeStats(detailNodeRow); if(stats) { g_connman->Ban(stats->nodeStats.addr, BanReasonManuallyAdded, bantime); } } clearSelectedNode(); clientModel->getBanTableModel()->refresh(); } void RPCConsole::unbanSelectedNode() { if (!clientModel) return; // Get selected ban addresses QList<QModelIndex> nodes = GUIUtil::getEntryData(ui->banlistWidget, BanTableModel::Address); for(int i = 0; i < nodes.count(); i++) { // Get currently selected ban address QString strNode = nodes.at(i).data().toString(); CSubNet possibleSubnet; LookupSubNet(strNode.toStdString().c_str(), possibleSubnet); if (possibleSubnet.IsValid() && g_connman) { g_connman->Unban(possibleSubnet); clientModel->getBanTableModel()->refresh(); } } } void RPCConsole::clearSelectedNode() { ui->peerWidget->selectionModel()->clearSelection(); cachedNodeids.clear(); ui->detailWidget->hide(); ui->peerHeading->setText(tr("Select a peer to view detailed information.")); } void RPCConsole::showOrHideBanTableIfRequired() { if (!clientModel) return; bool visible = clientModel->getBanTableModel()->shouldShow(); ui->banlistWidget->setVisible(visible); ui->banHeading->setVisible(visible); } void RPCConsole::setTabFocus(enum TabTypes tabType) { ui->tabWidget->setCurrentIndex(tabType); }
//-------------------------------------------------------------------------- // File and Version Information: // $Id: MatDBInfo.cc 516 2010-01-15 08:22:00Z stroili $ // // Description: // Class MatDBInfo. // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Author List: // Dave Brown LBL // // Copyright Information: // Copyright (C) 1999 Lawrence Berkeley Laboratory // //------------------------------------------------------------------------ #include "MatEnv/MatDBInfo.hh" #include "MatEnv/DetMaterial.hh" #include <string> #include <map> namespace MatEnv { MatDBInfo::MatDBInfo() : _genMatFactory(0) {;} MatDBInfo::~MatDBInfo() { // delete the materials std::map< std::string*, DetMaterial*, PtrLess >::iterator iter = _matList.begin(); for (; iter != _matList.end(); ++iter) { delete iter->first; delete iter->second; } _matList.clear(); } void MatDBInfo::declareMaterial( const std::string& db_name, const std::string& detMatName ) { _matNameMap[detMatName] = db_name; materialNames().push_back( detMatName ); return; } const DetMaterial* MatDBInfo::findDetMaterial( const std::string& matName ) const { if (_genMatFactory == 0) that()->_genMatFactory = RecoMatFactory::getInstance(); DetMaterial* theMat; std::map< std::string*, DetMaterial*, PtrLess >::const_iterator pos; if ((pos = _matList.find((std::string*)&matName)) != _matList.end()) { theMat = pos->second; } else { // first, look for aliases std::string theName; std::map< std::string, std::string >::const_iterator matNamePos; if ((matNamePos = _matNameMap.find(matName)) != _matNameMap.end()) { theName = matNamePos->second; theMat = createMaterial<DetMaterial>( theName, matName); } else { //then , try to find the material name directly theMat = createMaterial<DetMaterial>( matName, matName); // if we created a new material directly, add it to the list if(theMat != 0)that()->declareMaterial(matName,matName); } } if(theMat == 0){ ErrMsg( error ) << "MatDBInfo: Cannot find requested material " << matName << "." << endmsg; } return theMat; } }
/* * Copyright 2020 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 "ecclesia/lib/redfish/raw.h" #include <cstddef> #include <cstdint> #include <cstdlib> #include <memory> #include <string> #include <utility> #include "absl/base/thread_annotations.h" #include "absl/memory/memory.h" #include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "absl/types/optional.h" #include "absl/types/span.h" #include "absl/types/variant.h" #include "ecclesia/lib/logging/logging.h" #include "ecclesia/lib/redfish/interface.h" #include "ecclesia/lib/redfish/libredfish_adapter.h" extern "C" { #include "redfishPayload.h" #include "redfishRawAsync.h" #include "redfishService.h" } // extern "C" namespace libredfish { namespace { // Redfish version for the service root. constexpr char kRedfishServiceVersionRoot[] = "/redfish/v1"; struct RedfishPayloadDeleter { void operator()(redfishPayload *payload) { if (payload) cleanupPayload(payload); } }; using PayloadUniquePtr = std::unique_ptr<redfishPayload, RedfishPayloadDeleter>; struct RedfishServiceDeleter { void operator()(redfishService *service) { if (service) cleanupServiceEnumerator(service); } }; using ServiceUniquePtr = std::unique_ptr<redfishService, RedfishServiceDeleter>; struct FreeDeleter { inline void operator()(void *ptr) const { free(ptr); } }; using MallocChar = std::unique_ptr<char, FreeDeleter>; class JsonValue { public: explicit JsonValue(int val) : json_(json_integer(val)) {} explicit JsonValue(bool val) : json_(json_boolean(val)) {} explicit JsonValue(const char *val) : json_(json_string(val)) {} explicit JsonValue(std::string val) : json_(json_string(val.data())) {} explicit JsonValue(double val) : json_(json_real(val)) {} JsonValue(const JsonValue &) = delete; JsonValue &operator=(const JsonValue &) = delete; ~JsonValue() { json_decref(json_); } json_t *get() { return json_; } private: json_t *json_; }; // RawPayload provides a wrapper for interacting with responses from a // Redfish query. The provided methods will either provide additional info or // allow data to be extracted. RawPayload is an interface containing the union // interface of all types exported by RedfishVariant. class RawPayload { // ConstructorPasskey for implementing the Passkey Idiom in order to restrict // access to RawPayload's ctor while still allowing it to be used with // std::make_shared. class ConstructorPasskey { private: ConstructorPasskey() {} friend RawPayload; }; public: // This constructor is effectively private due to the ConstructorPasskey. // NewShared should be used instead to construct new instances of RawPayload. RawPayload(PayloadUniquePtr payload, ConstructorPasskey) : payload_(std::move(ecclesia::DieIfNull(payload))) {} static std::shared_ptr<RawPayload> NewShared(PayloadUniquePtr payload) { if (!payload) return nullptr; return std::make_shared<RawPayload>(std::move(payload), ConstructorPasskey{}); } RawPayload(const RawPayload &) = delete; RawPayload &operator=(const RawPayload &) = delete; std::string DebugString() { MallocChar output(payloadToString(payload_.get(), /*prettyprint=*/true)); if (!output) return "(null output)"; std::string ret(output.get()); return ret; } absl::optional<std::string> GetUri() { MallocChar output(getPayloadUri(payload_.get())); if (!output) return absl::nullopt; std::string ret(output.get()); if (ret.empty()) return absl::nullopt; return ret; } std::shared_ptr<RawPayload> GetNode(const std::string &node_name) { PayloadUniquePtr payload( getPayloadByNodeName(payload_.get(), node_name.c_str())); if (!payload) return nullptr; return RawPayload::NewShared(std::move(payload)); } // Returns true if the current payload is a Collection or Array. bool IsIndexable() { return isPayloadCollection(payload_.get()) || isPayloadArray(payload_.get()); } size_t Size() { if (isPayloadCollection(payload_.get())) return getCollectionSize(payload_.get()); if (isPayloadArray(payload_.get())) return getArraySize(payload_.get()); return 0; } bool Empty() { return Size() == 0; } std::shared_ptr<RawPayload> GetIndex(int index) { return RawPayload::NewShared( PayloadUniquePtr(getPayloadByIndex(payload_.get(), index))); } bool GetValue(std::string *val) { MallocChar raw_ret(getPayloadStringValue(payload_.get())); if (!raw_ret) return false; *val = std::string(raw_ret.get()); return true; } bool GetValue(int32_t *val) { // The current libredfish API cannot distinguish between the field being // not of type int and whether the int32 value is 0. *val = getPayloadIntValue(payload_.get()); return true; } bool GetValue(int64_t *val) { // The current libredfish API cannot distinguish between the field being // not of type int and whether the int64 value is 0. *val = getPayloadLongLongValue(payload_.get()); return true; } bool GetValue(bool *val) { bool is_bool; *val = getPayloadBoolValue(payload_.get(), &is_bool); if (!is_bool) return false; return true; } bool GetValue(double *val) { bool is_double; *val = getPayloadDoubleValue(payload_.get(), &is_double); if (!is_double) return false; return true; } private: PayloadUniquePtr payload_; }; class RawVariantImpl : public RedfishVariant::ImplIntf { public: RawVariantImpl() : payload_(nullptr) {} explicit RawVariantImpl(std::shared_ptr<RawPayload> payload) : payload_(std::move(payload)) {} std::unique_ptr<RedfishObject> AsObject() const override; std::unique_ptr<RedfishIterable> AsIterable() const override; bool GetValue(std::string *val) const override { if (!payload_) return false; return payload_->GetValue(val); } bool GetValue(int32_t *val) const override { if (!payload_) return false; return payload_->GetValue(val); } bool GetValue(int64_t *val) const override { if (!payload_) return false; return payload_->GetValue(val); } bool GetValue(double *val) const override { if (!payload_) return false; return payload_->GetValue(val); } bool GetValue(bool *val) const override { if (!payload_) return false; return payload_->GetValue(val); } std::string DebugString() const override { if (!payload_) return "(null payload)"; return payload_->DebugString(); } private: std::shared_ptr<RawPayload> payload_; }; class RawObject : public RedfishObject { public: explicit RawObject(std::shared_ptr<RawPayload> payload) : payload_(std::move(payload)) {} RawObject(const RawObject &) = delete; RawObject &operator=(const RawObject &) = delete; RedfishVariant operator[](const std::string &node_name) const override { return RedfishVariant( absl::make_unique<RawVariantImpl>(payload_->GetNode(node_name))); } absl::optional<std::string> GetUri() override { return payload_->GetUri(); } std::string DebugString() override { return payload_->DebugString(); } private: std::shared_ptr<RawPayload> payload_; }; class RawIterable : public RedfishIterable { public: explicit RawIterable(std::shared_ptr<RawPayload> payload) : payload_(std::move(payload)) {} RawIterable(const RawIterable &) = delete; RawObject &operator=(const RawIterable &) = delete; size_t Size() override { return payload_->Size(); } bool Empty() override { return payload_->Empty(); } RedfishVariant operator[](int index) const override { return RedfishVariant( absl::make_unique<RawVariantImpl>(payload_->GetIndex(index))); } private: std::shared_ptr<RawPayload> payload_; }; std::unique_ptr<RedfishObject> RawVariantImpl::AsObject() const { if (!payload_) return nullptr; return absl::make_unique<RawObject>(payload_); } std::unique_ptr<RedfishIterable> RawVariantImpl::AsIterable() const { if (!payload_) return nullptr; if (!payload_->IsIndexable()) return nullptr; return absl::make_unique<RawIterable>(payload_); } // RawIntf provides an interaface wrapper for the redfishService C type. class RawIntf : public RedfishInterface { public: explicit RawIntf(ServiceUniquePtr service, TrustedEndpoint trusted) : service_(std::move(service)), trusted_(trusted) {} RawIntf(const RawIntf &) = delete; RawIntf operator=(const RawIntf &) = delete; bool IsTrusted() const override { absl::ReaderMutexLock lock(&service_mutex_); return trusted_ == kTrusted; } void UpdateEndpoint(absl::string_view endpoint, TrustedEndpoint trusted) override { absl::WriterMutexLock lock(&service_mutex_); updateServiceHost(service_.get(), endpoint.data()); trusted_ = trusted; } RedfishVariant GetRoot() override { // Ideally we would use getRedfishServiceRoot from libredfish, but for some // reason it stores some state which breaks if the connection goes down // and cannot be fixed. As a workaround, just manually get root assuming // we will always be using kRedfishServiceVersionRoot. // See https://github.com/DMTF/libredfish/issues/133 return GetUri(kRedfishServiceVersionRoot); } RedfishVariant GetUri(absl::string_view uri) override { absl::ReaderMutexLock lock(&service_mutex_); if (!service_) { return RedfishVariant(); } return RedfishVariant( absl::make_unique<RawVariantImpl>(RawPayload::NewShared( PayloadUniquePtr(getPayloadByUri(service_.get(), uri.data()))))); } RedfishVariant PostUri( absl::string_view uri, absl::Span<const std::pair<std::string, ValueVariant>> kv_span) override { absl::ReaderMutexLock lock(&service_mutex_); if (!service_) { return RedfishVariant(); } json_t *post_payload = json_object(); for (const auto &kv_pair : kv_span) { absl::visit( [&](auto val) { JsonValue jValue(val); json_object_set(post_payload, kv_pair.first.data(), jValue.get()); }, kv_pair.second); } MallocChar content(json_dumps(post_payload, 0)); json_decref(post_payload); json_t *value = postUriFromService(service_.get(), uri.data(), content.get(), 0, NULL); if (!value) { return RedfishVariant(); } return RedfishVariant( absl::make_unique<RawVariantImpl>(RawPayload::NewShared( PayloadUniquePtr(createRedfishPayload(value, service_.get()))))); } RedfishVariant PostUri(absl::string_view uri, absl::string_view data) override { absl::ReaderMutexLock lock(&service_mutex_); if (!service_) { return RedfishVariant(); } json_t *value = postUriFromService(service_.get(), uri.data(), data.begin(), 0, NULL); if (!value) { return RedfishVariant(); } return RedfishVariant( absl::make_unique<RawVariantImpl>(RawPayload::NewShared( PayloadUniquePtr(createRedfishPayload(value, service_.get()))))); } private: mutable absl::Mutex service_mutex_; ServiceUniquePtr service_ ABSL_GUARDED_BY(service_mutex_); TrustedEndpoint trusted_ ABSL_GUARDED_BY(service_mutex_); }; } // namespace // Constructor method for creating a RawIntf. std::unique_ptr<RedfishInterface> NewRawInterface( const std::string &endpoint, libredfish::RedfishInterface::TrustedEndpoint trusted, std::unique_ptr<ecclesia::HttpClient> client) { serviceHttpHandler handler{}; if (client) { handler = NewLibredfishAdapter(std::move(client)); } // createServiceEnumerator only returns NULL if calloc fails, regardless of // whether the endpoint is valid or reachable. // Handler is consumed even on failure. ServiceUniquePtr service( createServiceEnumeratorExt(endpoint.c_str(), nullptr, nullptr, 0, &handler)); return absl::make_unique<RawIntf>(std::move(service), trusted); } // Constructor method for creating a RawInterface with auth session. std::unique_ptr<RedfishInterface> NewRawSessionAuthInterface( const PasswordArgs &connectionArgs) { enumeratorAuthentication auth; auth.authType = REDFISH_AUTH_SESSION; std::string username_buf = connectionArgs.username; std::string password_buf = connectionArgs.password; auth.authCodes.userPass.username = &username_buf[0]; auth.authCodes.userPass.password = &password_buf[0]; ServiceUniquePtr service(createServiceEnumerator( connectionArgs.endpoint.c_str(), nullptr, &auth, 0)); return absl::make_unique<RawIntf>(std::move(service), RedfishInterface::kTrusted); } std::unique_ptr<RedfishInterface> NewRawBasicAuthInterface( const PasswordArgs &connectionArgs) { enumeratorAuthentication auth; auth.authType = REDFISH_AUTH_BASIC; std::string username_buf = connectionArgs.username; std::string password_buf = connectionArgs.password; auth.authCodes.userPass.username = username_buf.data(); auth.authCodes.userPass.password = password_buf.data(); ServiceUniquePtr service(createServiceEnumerator( connectionArgs.endpoint.c_str(), nullptr, &auth, 0)); return absl::make_unique<RawIntf>(std::move(service), RedfishInterface::kTrusted); } std::unique_ptr<RedfishInterface> NewRawTlsAuthInterface( const TlsArgs &connectionArgs) { enumeratorAuthentication auth; auth.authType = REDFISH_AUTH_TLS; auth.authCodes.authTls.verifyPeer = connectionArgs.verify_peer; auth.authCodes.authTls.verifyHostname = connectionArgs.verify_hostname; auth.authCodes.authTls.caCertFile = connectionArgs.ca_cert_file.has_value() ? connectionArgs.ca_cert_file->c_str() : nullptr; auth.authCodes.authTls.clientCertFile = connectionArgs.cert_file.c_str(); auth.authCodes.authTls.clientKeyFile = connectionArgs.key_file.c_str(); ServiceUniquePtr service(createServiceEnumerator( connectionArgs.endpoint.c_str(), nullptr, &auth, 0)); return absl::make_unique<RawIntf>(std::move(service), RedfishInterface::kTrusted); } } // namespace libredfish
/* * Copyright 2020 Weibo 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. * * @author ZhongXiu Hao <nmred.hao@gmail.com> */ #include "router.h" #include "service_info_puller.h" namespace service_router { DEFINE_int32(router_default_heartbeat_interval, 1000, "Service router default heartbeat interval call"); DEFINE_int32(router_default_pull_interval, 1000, "Service router default pull interval call"); ServerWithHeartbeat::ServerWithHeartbeat(const Server& server, folly::EventBase* evb, Router* router, RouterDb* db) : server_(server), evb_(evb), router_(router), db_(db) { timeout_ = folly::AsyncTimeout::make(*evb_, [&]() noexcept { if (!is_pause_) { std::time_t now = common::currentTimeInMs(); server_.setUpdateTime(static_cast<uint64_t>(now)); } router_->registerServer(server_); addHeartbeat(); VLOG(5) << "Callback heartbeat server:" << server_; }); addHeartbeat(); } void ServerWithHeartbeat::addHeartbeat() { ServiceRouterConfig router_config = db_->getRouterConfig(server_.getServiceName()); // heartbeat 间隔是 router ttl 的 2 / 3 int heartbeat_interval = static_cast<int>(2 * router_config.getTtlInMs() / 3); if (heartbeat_interval < FLAGS_router_default_heartbeat_interval) { heartbeat_interval = FLAGS_router_default_heartbeat_interval; } VLOG(5) << "Add heartbeat server:" << server_ << " interval:" << heartbeat_interval; evb_->runInEventBaseThread([heartbeat_interval, this]() { timeout_->scheduleTimeout(std::chrono::milliseconds(heartbeat_interval)); }); } void ServerWithHeartbeat::setStatus(const ServerStatus& status) { server_.setStatus(status); if (status == ServerStatus::AVAILABLE) { resume(); } else { pause(); } } ServiceConfigPull::ServiceConfigPull(RouterDb* db, RegistryInterface* registry) : db_(db), registry_(registry) {} void ServiceConfigPull::pull(const std::string& service_name) { registry_->getConfig(service_name); } void ServiceConfigPull::subscribe(const std::string& service_name, ServiceInfoPuller<ServiceConfigPull>* puller) { registry_->subscribeConfig(service_name, [puller, this](const std::string& name, const ServiceConfig& service_config) { db_->updateConfig(name, service_config); VLOG(5) << "Service config update, value:" << service_config; puller->post(); }); } ServiceDiscoverPull::ServiceDiscoverPull(RouterDb* db, RegistryInterface* registry) : db_(db), registry_(registry) {} void ServiceDiscoverPull::pull(const std::string& service_name) { registry_->discover(service_name); } void ServiceDiscoverPull::subscribe(const std::string& service_name, ServiceInfoPuller<ServiceDiscoverPull>* puller) { VLOG(2) << "subscribe service discover."; registry_->subscribe(service_name, [puller, this](const std::string& name, const std::vector<Server>& list) { db_->updateServers(name, list); VLOG(2) << "Service list discover update, list size:" << list.size(); puller->post(); }); } } // namespace service_router
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <unistd.h> #include <iostream> #include <fstream> #include <stdexcept> #include <wordexp.h> #include <fcntl.h> #include <bcm_host.h> #include <GLES/gl.h> #include <EGL/egl.h> #include <EGL/eglext.h> #include <boost/program_options.hpp> namespace opts = boost::program_options; #include "asset_dir.h" #include "model_board/model_board.h" #include "version.h" /* OpenGL rotation matrix that converts board coordinates * into ground coordinates (x=north, y=east, z=down). It is * column-major so do matrix[COL][ROW]. */ float matrix[4][4]; // Acceleration vector in units of g (9.8 m/s^2). float acceleration[3]; // Magnetic field vector where each component is approximately between -1 and 1. float magnetic_field[3]; // 0 = Screen faces south, 90 = West, 180 = North, 270 = East // TODO: read screen_orientation from environment float screen_orientation = 0; uint32_t screen_width, screen_height; EGLDisplay display; EGLSurface surface; EGLContext context; static inline VC_RECT_T rect_width_height(int width, int height) { VC_RECT_T r; r.x = r.y = 0; r.width = width; r.height = height; return r; } static void nice_bcm_host_init() { int fd = open("/dev/vchiq", O_RDWR | O_LARGEFILE); if (fd == -1) { char buffer[256]; char * msg = strerror_r(errno, buffer, sizeof(buffer) - 1); if (msg) { std::cerr << "Warning: Could not open /dev/vchiq: " << msg << "." << std::endl; } else { std::cerr << "Warning: Could not open /dev/vchiq." << std::endl; } } else { close(fd); } bcm_host_init(); } // Sets the display, OpenGL|ES context and screen stuff static void opengl_init(void) { EGLBoolean result; EGLint num_config; static EGL_DISPMANX_WINDOW_T nativewindow; DISPMANX_ELEMENT_HANDLE_T dispman_element; DISPMANX_DISPLAY_HANDLE_T dispman_display; DISPMANX_UPDATE_HANDLE_T dispman_update; static const EGLint attribute_list[] = { EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; EGLConfig config; // get an EGL display connection display = eglGetDisplay(EGL_DEFAULT_DISPLAY); if (display == EGL_NO_DISPLAY) { throw std::runtime_error("Failed to get display. eglGetDisplay failed."); } // initialize the EGL display connection result = eglInitialize(display, NULL, NULL); if (result == EGL_FALSE) { throw std::runtime_error("Failed to initialize display. eglInitialize failed."); } // get an appropriate EGL frame buffer configuration result = eglChooseConfig(display, attribute_list, &config, 1, &num_config); if (result == EGL_FALSE) { throw std::runtime_error("Failed to choose config. eglChooseConfig failed."); } // create an EGL rendering context context = eglCreateContext(display, config, EGL_NO_CONTEXT, NULL); if (context == EGL_NO_CONTEXT) { throw std::runtime_error("Failed to create context. eglCreateContext failed."); } // create an EGL window surface int32_t success = graphics_get_display_size(0 /* LCD */, &screen_width, &screen_height); if (success < 0) { throw std::runtime_error("Failed to get display size."); } VC_RECT_T dst_rect = rect_width_height(screen_width, screen_height); VC_RECT_T src_rect = rect_width_height(screen_width<<16, screen_height<<16); dispman_display = vc_dispmanx_display_open(0 /* LCD */); dispman_update = vc_dispmanx_update_start(0); dispman_element = vc_dispmanx_element_add (dispman_update, dispman_display, 0/*layer*/, &dst_rect, 0/*src*/, &src_rect, DISPMANX_PROTECTION_NONE, 0 /*alpha*/, 0/*clamp*/, (DISPMANX_TRANSFORM_T)0/*transform*/); nativewindow.element = dispman_element; nativewindow.width = screen_width; nativewindow.height = screen_height; vc_dispmanx_update_submit_sync(dispman_update); surface = eglCreateWindowSurface(display, config, &nativewindow, NULL); if(surface == EGL_NO_SURFACE) { fprintf(stderr, "eglCreateWindowSurface returned ELG_NO_SURFACE. " "Try closing other OpenGL programs.\n"); exit(1); } // connect the context to the surface result = eglMakeCurrent(display, surface, surface, context); if (result == EGL_FALSE) { throw std::runtime_error("Failed to connect to the surface."); } glClearColor(0, 0, 0, 0.5); // set background colors glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear buffers glShadeModel(GL_FLAT); // Enable back face culling. glEnable(GL_CULL_FACE); } // Description: Sets the OpenGL|ES model to default values static void projection_init() { float nearp = 1, farp = 500.0f, hht, hwd; glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); glViewport(0, 0, (GLsizei)screen_width, (GLsizei)screen_height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); hht = nearp * tan(45.0 / 2.0 / 180.0 * M_PI); hwd = hht * screen_width / screen_height; glFrustumf(-hwd, hwd, -hht, hht, nearp, farp); } static void textures_init(void) { // Enable alpha blending so what we see through transparent // parts of the model is the same as the background. glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_TEXTURE_2D); } static void redraw_scene() { // Start with a clear screen glClear(GL_COLOR_BUFFER_BIT); // Move the camera back so we can see the board. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0, 0, -30); // Convert screen coords (right, up, out) to ground coords (north, east, down). glRotatef(90, 1, 0, 0); glRotatef(-90, 0, 0, 1); glRotatef(-screen_orientation, 0, 0, 1); // Convert ground coords to board coordinates. glMultMatrixf(matrix[0]); model_board_redraw(acceleration, magnetic_field); eglSwapBuffers(display, surface); } static void opengl_deinit(void) { // clear screen glClear(GL_COLOR_BUFFER_BIT); eglSwapBuffers(display, surface); // Release OpenGL resources eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroySurface(display, surface); eglDestroyContext(display, context); eglTerminate(display); } /* The matrix expected on the standrd input is a * ROW-major matrix that converts a vector from board coordinates * to ground coordinates. */ static void read_input(void) { // Set the translation part to be the identity. matrix[3][0] = matrix[3][1] = matrix[3][2] = 0; matrix[0][3] = matrix[1][3] = matrix[2][3] = 0; matrix[3][3] = 1; while(1) { // Read the rotation matrix from the standard input. // The input values are ROW-major but we need to make a // COLUMN-major matrix for OpenGL. int result = scanf("%f %f %f %f %f %f %f %f %f %f %f %f %f %f %f", &matrix[0][0], &matrix[1][0], &matrix[2][0], &matrix[0][1], &matrix[1][1], &matrix[2][1], &matrix[0][2], &matrix[1][2], &matrix[2][2], &acceleration[0], &acceleration[1], &acceleration[2], &magnetic_field[0], &magnetic_field[1], &magnetic_field[2]); // Read to the end of the line so that we don't get stuck forever on one invalid line. while(getc(stdin) != '\n'); if (result >= 9) { break; // Success } fprintf(stderr, "unrecognized input: only regonized %d items.\n", result); } } static void read_args(int argc, char *argv[]) { try { opts::options_description generic("Generic options"); generic.add_options() ("help,h", "produce help message") ("version,v", "print version number") ; opts::options_description config("Configuration"); config.add_options() ("screen-angle,a", opts::value<float>(&screen_orientation)->default_value(0), "specifies your screen orientation. " "0 = screen faces South, 90 = West, 180 = North, 270 = East\n") ; opts::options_description cmdline_options; cmdline_options.add(generic); cmdline_options.add(config); // Read options from command line. opts::variables_map options; opts::store(opts::command_line_parser(argc, argv).options(cmdline_options).run(), options); // Read options form config file, ~/.ahrs-visualizer { wordexp_t expansion_result; wordexp("~/.ahrs-visualizer", &expansion_result, 0); std::ifstream file(expansion_result.we_wordv[0]); opts::store(opts::parse_config_file(file, config), options); } opts::notify(options); if(options.count("help")) { std::cout << cmdline_options; std::cout << "For more information, run: man ahrs-visualizer" << std::endl; exit(0); } if (options.count("version")) { std::cout << VERSION << std::endl; exit(0); } } catch(const opts::multiple_occurrences & error) { std::cerr << "Error: " << error.what() << " of " << error.get_option_name() << " option." << std::endl; exit(1); } } int main(int argc, char *argv[]) { try { read_args(argc, argv); asset_dir_init(); nice_bcm_host_init(); opengl_init(); projection_init(); textures_init(); model_board_init(); while(1) { read_input(); redraw_scene(); } opengl_deinit(); bcm_host_deinit(); return 0; } catch(const std::exception & error) { std::cerr << "Error: " << error.what() << std::endl; exit(9); } }
/* * Copyright 2012 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkLightingImageFilter.h" #include "SkBitmap.h" #include "SkColorPriv.h" #include "SkDevice.h" #include "SkPoint3.h" #include "SkReadBuffer.h" #include "SkTypes.h" #include "SkWriteBuffer.h" #if SK_SUPPORT_GPU #include "GrContext.h" #include "GrDrawContext.h" #include "GrFragmentProcessor.h" #include "GrInvariantOutput.h" #include "GrPaint.h" #include "SkGr.h" #include "effects/GrSingleTextureEffect.h" #include "glsl/GrGLSLFragmentProcessor.h" #include "glsl/GrGLSLFragmentShaderBuilder.h" #include "glsl/GrGLSLProgramDataManager.h" #include "glsl/GrGLSLUniformHandler.h" class GrGLDiffuseLightingEffect; class GrGLSpecularLightingEffect; // For brevity typedef GrGLSLProgramDataManager::UniformHandle UniformHandle; #endif namespace { const SkScalar gOneThird = SkIntToScalar(1) / 3; const SkScalar gTwoThirds = SkIntToScalar(2) / 3; const SkScalar gOneHalf = 0.5f; const SkScalar gOneQuarter = 0.25f; #if SK_SUPPORT_GPU void setUniformPoint3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { GR_STATIC_ASSERT(sizeof(SkPoint3) == 3 * sizeof(float)); pdman.set3fv(uni, 1, &point.fX); } void setUniformNormal3(const GrGLSLProgramDataManager& pdman, UniformHandle uni, const SkPoint3& point) { setUniformPoint3(pdman, uni, point); } #endif // Shift matrix components to the left, as we advance pixels to the right. inline void shiftMatrixLeft(int m[9]) { m[0] = m[1]; m[3] = m[4]; m[6] = m[7]; m[1] = m[2]; m[4] = m[5]; m[7] = m[8]; } static inline void fast_normalize(SkPoint3* vector) { // add a tiny bit so we don't have to worry about divide-by-zero SkScalar magSq = vector->dot(*vector) + SK_ScalarNearlyZero; SkScalar scale = sk_float_rsqrt(magSq); vector->fX *= scale; vector->fY *= scale; vector->fZ *= scale; } class DiffuseLightingType { public: DiffuseLightingType(SkScalar kd) : fKD(kd) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkScalar colorScale = SkScalarMul(fKD, normal.dot(surfaceTolight)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(255, SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKD; }; static SkScalar max_component(const SkPoint3& p) { return p.x() > p.y() ? (p.x() > p.z() ? p.x() : p.z()) : (p.y() > p.z() ? p.y() : p.z()); } class SpecularLightingType { public: SpecularLightingType(SkScalar ks, SkScalar shininess) : fKS(ks), fShininess(shininess) {} SkPMColor light(const SkPoint3& normal, const SkPoint3& surfaceTolight, const SkPoint3& lightColor) const { SkPoint3 halfDir(surfaceTolight); halfDir.fZ += SK_Scalar1; // eye position is always (0, 0, 1) fast_normalize(&halfDir); SkScalar colorScale = SkScalarMul(fKS, SkScalarPow(normal.dot(halfDir), fShininess)); colorScale = SkScalarClampMax(colorScale, SK_Scalar1); SkPoint3 color = lightColor.makeScale(colorScale); return SkPackARGB32(SkClampMax(SkScalarRoundToInt(max_component(color)), 255), SkClampMax(SkScalarRoundToInt(color.fX), 255), SkClampMax(SkScalarRoundToInt(color.fY), 255), SkClampMax(SkScalarRoundToInt(color.fZ), 255)); } private: SkScalar fKS; SkScalar fShininess; }; inline SkScalar sobel(int a, int b, int c, int d, int e, int f, SkScalar scale) { return SkScalarMul(SkIntToScalar(-a + b - 2 * c + 2 * d -e + f), scale); } inline SkPoint3 pointToNormal(SkScalar x, SkScalar y, SkScalar surfaceScale) { SkPoint3 vector = SkPoint3::Make(SkScalarMul(-x, surfaceScale), SkScalarMul(-y, surfaceScale), SK_Scalar1); fast_normalize(&vector); return vector; } inline SkPoint3 topLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(0, 0, m[4], m[5], m[7], m[8], gTwoThirds), sobel(0, 0, m[4], m[7], m[5], m[8], gTwoThirds), surfaceScale); } inline SkPoint3 topNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[5], m[6], m[8], gOneThird), sobel(m[3], m[6], m[4], m[7], m[5], m[8], gOneHalf), surfaceScale); } inline SkPoint3 topRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel( 0, 0, m[3], m[4], m[6], m[7], gTwoThirds), sobel(m[3], m[6], m[4], m[7], 0, 0, gTwoThirds), surfaceScale); } inline SkPoint3 leftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], m[7], m[8], gOneHalf), sobel( 0, 0, m[1], m[7], m[2], m[8], gOneThird), surfaceScale); } inline SkPoint3 interiorNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], m[6], m[8], gOneQuarter), sobel(m[0], m[6], m[1], m[7], m[2], m[8], gOneQuarter), surfaceScale); } inline SkPoint3 rightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], m[6], m[7], gOneHalf), sobel(m[0], m[6], m[1], m[7], 0, 0, gOneThird), surfaceScale); } inline SkPoint3 bottomLeftNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[1], m[2], m[4], m[5], 0, 0, gTwoThirds), sobel( 0, 0, m[1], m[4], m[2], m[5], gTwoThirds), surfaceScale); } inline SkPoint3 bottomNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[2], m[3], m[5], 0, 0, gOneThird), sobel(m[0], m[3], m[1], m[4], m[2], m[5], gOneHalf), surfaceScale); } inline SkPoint3 bottomRightNormal(int m[9], SkScalar surfaceScale) { return pointToNormal(sobel(m[0], m[1], m[3], m[4], 0, 0, gTwoThirds), sobel(m[0], m[3], m[1], m[4], 0, 0, gTwoThirds), surfaceScale); } template <class LightingType, class LightType> void lightBitmap(const LightingType& lightingType, const SkImageFilterLight* light, const SkBitmap& src, SkBitmap* dst, SkScalar surfaceScale, const SkIRect& bounds) { SkASSERT(dst->width() == bounds.width() && dst->height() == bounds.height()); const LightType* l = static_cast<const LightType*>(light); int left = bounds.left(), right = bounds.right(); int bottom = bounds.bottom(); int y = bounds.top(); SkPMColor* dptr = dst->getAddr32(0, 0); { int x = left; const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(topRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } for (++y; y < bottom - 1; ++y) { int x = left; const SkPMColor* row0 = src.getAddr32(x, y - 1); const SkPMColor* row1 = src.getAddr32(x, y); const SkPMColor* row2 = src.getAddr32(x, y + 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); m[7] = SkGetPackedA32(*row2++); m[8] = SkGetPackedA32(*row2++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(leftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); m[8] = SkGetPackedA32(*row2++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(interiorNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(rightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } { int x = left; const SkPMColor* row0 = src.getAddr32(x, bottom - 2); const SkPMColor* row1 = src.getAddr32(x, bottom - 1); int m[9]; m[1] = SkGetPackedA32(*row0++); m[2] = SkGetPackedA32(*row0++); m[4] = SkGetPackedA32(*row1++); m[5] = SkGetPackedA32(*row1++); SkPoint3 surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomLeftNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); for (++x; x < right - 1; ++x) { shiftMatrixLeft(m); m[2] = SkGetPackedA32(*row0++); m[5] = SkGetPackedA32(*row1++); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } shiftMatrixLeft(m); surfaceToLight = l->surfaceToLight(x, y, m[4], surfaceScale); *dptr++ = lightingType.light(bottomRightNormal(m, surfaceScale), surfaceToLight, l->lightColor(surfaceToLight)); } } SkPoint3 readPoint3(SkReadBuffer& buffer) { SkPoint3 point; point.fX = buffer.readScalar(); point.fY = buffer.readScalar(); point.fZ = buffer.readScalar(); buffer.validate(SkScalarIsFinite(point.fX) && SkScalarIsFinite(point.fY) && SkScalarIsFinite(point.fZ)); return point; }; void writePoint3(const SkPoint3& point, SkWriteBuffer& buffer) { buffer.writeScalar(point.fX); buffer.writeScalar(point.fY); buffer.writeScalar(point.fZ); }; enum BoundaryMode { kTopLeft_BoundaryMode, kTop_BoundaryMode, kTopRight_BoundaryMode, kLeft_BoundaryMode, kInterior_BoundaryMode, kRight_BoundaryMode, kBottomLeft_BoundaryMode, kBottom_BoundaryMode, kBottomRight_BoundaryMode, kBoundaryModeCount, }; class SkLightingImageFilterInternal : public SkLightingImageFilter { protected: SkLightingImageFilterInternal(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect) {} #if SK_SUPPORT_GPU bool canFilterImageGPU() const override { return true; } bool filterImageGPU(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; virtual GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode boundaryMode) const = 0; #endif private: #if SK_SUPPORT_GPU void drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const; #endif typedef SkLightingImageFilter INHERITED; }; #if SK_SUPPORT_GPU void SkLightingImageFilterInternal::drawRect(GrDrawContext* drawContext, GrTexture* src, const SkMatrix& matrix, const GrClip& clip, const SkRect& dstRect, BoundaryMode boundaryMode, const SkIRect& bounds) const { SkRect srcRect = dstRect.makeOffset(SkIntToScalar(bounds.x()), SkIntToScalar(bounds.y())); GrPaint paint; GrFragmentProcessor* fp = this->getFragmentProcessor(src, matrix, bounds, boundaryMode); paint.addColorFragmentProcessor(fp)->unref(); paint.setPorterDuffXPFactory(SkXfermode::kSrc_Mode); drawContext->fillRectToRect(clip, paint, SkMatrix::I(), dstRect, srcRect); } bool SkLightingImageFilterInternal::filterImageGPU(Proxy* proxy, const SkBitmap& src, const Context& ctx, SkBitmap* result, SkIPoint* offset) const { SkBitmap input = src; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInputGPU(0, proxy, src, ctx, &input, &srcOffset)) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, input, &srcOffset, &bounds, &input)) { return false; } SkRect dstRect = SkRect::MakeWH(SkIntToScalar(bounds.width()), SkIntToScalar(bounds.height())); GrTexture* srcTexture = input.getTexture(); GrContext* context = srcTexture->getContext(); GrSurfaceDesc desc; desc.fFlags = kRenderTarget_GrSurfaceFlag, desc.fWidth = bounds.width(); desc.fHeight = bounds.height(); desc.fConfig = kRGBA_8888_GrPixelConfig; SkAutoTUnref<GrTexture> dst(context->textureProvider()->createApproxTexture(desc)); if (!dst) { return false; } // setup new clip GrClip clip(dstRect); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-bounds.left()), SkIntToScalar(-bounds.top())); bounds.offset(-srcOffset); SkRect topLeft = SkRect::MakeXYWH(0, 0, 1, 1); SkRect top = SkRect::MakeXYWH(1, 0, dstRect.width() - 2, 1); SkRect topRight = SkRect::MakeXYWH(dstRect.width() - 1, 0, 1, 1); SkRect left = SkRect::MakeXYWH(0, 1, 1, dstRect.height() - 2); SkRect interior = dstRect.makeInset(1, 1); SkRect right = SkRect::MakeXYWH(dstRect.width() - 1, 1, 1, dstRect.height() - 2); SkRect bottomLeft = SkRect::MakeXYWH(0, dstRect.height() - 1, 1, 1); SkRect bottom = SkRect::MakeXYWH(1, dstRect.height() - 1, dstRect.width() - 2, 1); SkRect bottomRight = SkRect::MakeXYWH(dstRect.width() - 1, dstRect.height() - 1, 1, 1); SkAutoTUnref<GrDrawContext> drawContext(context->drawContext(dst->asRenderTarget())); if (!drawContext) { return false; } this->drawRect(drawContext, srcTexture, matrix, clip, topLeft, kTopLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, top, kTop_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, topRight, kTopRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, left, kLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, interior, kInterior_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, right, kRight_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomLeft, kBottomLeft_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottom, kBottom_BoundaryMode, bounds); this->drawRect(drawContext, srcTexture, matrix, clip, bottomRight, kBottomRight_BoundaryMode, bounds); GrWrapTextureInBitmap(dst, bounds.width(), bounds.height(), false, result); return true; } #endif class SkDiffuseLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkDiffuseLightingImageFilter) SkScalar kd() const { return fKD; } protected: SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; SkScalar fKD; }; class SkSpecularLightingImageFilter : public SkLightingImageFilterInternal { public: static SkImageFilter* Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter*, const CropRect*); SK_TO_STRING_OVERRIDE() SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkSpecularLightingImageFilter) SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } protected: SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect*); void flatten(SkWriteBuffer& buffer) const override; bool onFilterImage(Proxy*, const SkBitmap& src, const Context&, SkBitmap* result, SkIPoint* offset) const override; #if SK_SUPPORT_GPU GrFragmentProcessor* getFragmentProcessor(GrTexture*, const SkMatrix&, const SkIRect& bounds, BoundaryMode) const override; #endif private: SkScalar fKS; SkScalar fShininess; friend class SkLightingImageFilter; typedef SkLightingImageFilterInternal INHERITED; }; #if SK_SUPPORT_GPU class GrLightingEffect : public GrSingleTextureEffect { public: GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode); ~GrLightingEffect() override; const SkImageFilterLight* light() const { return fLight; } SkScalar surfaceScale() const { return fSurfaceScale; } const SkMatrix& filterMatrix() const { return fFilterMatrix; } BoundaryMode boundaryMode() const { return fBoundaryMode; } protected: bool onIsEqual(const GrFragmentProcessor&) const override; void onComputeInvariantOutput(GrInvariantOutput* inout) const override { // lighting shaders are complicated. We just throw up our hands. inout->mulByUnknownFourComponents(); } private: const SkImageFilterLight* fLight; SkScalar fSurfaceScale; SkMatrix fFilterMatrix; BoundaryMode fBoundaryMode; typedef GrSingleTextureEffect INHERITED; }; class GrDiffuseLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) { return new GrDiffuseLightingEffect(texture, light, surfaceScale, matrix, kd, boundaryMode); } const char* name() const override { return "DiffuseLighting"; } SkScalar kd() const { return fKD; } private: GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKD; }; class GrSpecularLightingEffect : public GrLightingEffect { public: static GrFragmentProcessor* Create(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) { return new GrSpecularLightingEffect(texture, light, surfaceScale, matrix, ks, shininess, boundaryMode); } const char* name() const override { return "SpecularLighting"; } GrGLSLFragmentProcessor* onCreateGLSLInstance() const override; SkScalar ks() const { return fKS; } SkScalar shininess() const { return fShininess; } private: void onGetGLSLProcessorKey(const GrGLSLCaps&, GrProcessorKeyBuilder*) const override; bool onIsEqual(const GrFragmentProcessor&) const override; GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode); GR_DECLARE_FRAGMENT_PROCESSOR_TEST; typedef GrLightingEffect INHERITED; SkScalar fKS; SkScalar fShininess; }; /////////////////////////////////////////////////////////////////////////////// class GrGLLight { public: virtual ~GrGLLight() {} /** * This is called by GrGLLightingEffect::emitCode() before either of the two virtual functions * below. It adds a vec3f uniform visible in the FS that represents the constant light color. */ void emitLightColorUniform(GrGLSLUniformHandler*); /** * These two functions are called from GrGLLightingEffect's emitCode() function. * emitSurfaceToLight places an expression in param out that is the vector from the surface to * the light. The expression will be used in the FS. emitLightColor writes an expression into * the FS that is the color of the light. Either function may add functions and/or uniforms to * the FS. The default of emitLightColor appends the name of the constant light color uniform * and so this function only needs to be overridden if the light color varies spatially. */ virtual void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) = 0; virtual void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight); // This is called from GrGLLightingEffect's setData(). Subclasses of GrGLLight must call // INHERITED::setData(). virtual void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const; protected: /** * Gets the constant light color uniform. Subclasses can use this in their emitLightColor * function. */ UniformHandle lightColorUni() const { return fColorUni; } private: UniformHandle fColorUni; typedef SkRefCnt INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDistantLight : public GrGLLight { public: virtual ~GrGLDistantLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fDirectionUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLPointLight : public GrGLLight { public: virtual ~GrGLPointLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; private: typedef GrGLLight INHERITED; UniformHandle fLocationUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpotLight : public GrGLLight { public: virtual ~GrGLSpotLight() {} void setData(const GrGLSLProgramDataManager&, const SkImageFilterLight* light) const override; void emitSurfaceToLight(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char* z) override; void emitLightColor(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, const char *surfaceToLight) override; private: typedef GrGLLight INHERITED; SkString fLightColorFunc; UniformHandle fLocationUni; UniformHandle fExponentUni; UniformHandle fCosOuterConeAngleUni; UniformHandle fCosInnerConeAngleUni; UniformHandle fConeScaleUni; UniformHandle fSUni; }; #else class GrGLLight; #endif }; /////////////////////////////////////////////////////////////////////////////// class SkImageFilterLight : public SkRefCnt { public: enum LightType { kDistant_LightType, kPoint_LightType, kSpot_LightType, }; virtual LightType type() const = 0; const SkPoint3& color() const { return fColor; } virtual GrGLLight* createGLLight() const = 0; virtual bool isEqual(const SkImageFilterLight& other) const { return fColor == other.fColor; } // Called to know whether the generated GrGLLight will require access to the fragment position. virtual bool requiresFragmentPosition() const = 0; virtual SkImageFilterLight* transform(const SkMatrix& matrix) const = 0; // Defined below SkLight's subclasses. void flattenLight(SkWriteBuffer& buffer) const; static SkImageFilterLight* UnflattenLight(SkReadBuffer& buffer); protected: SkImageFilterLight(SkColor color) { fColor = SkPoint3::Make(SkIntToScalar(SkColorGetR(color)), SkIntToScalar(SkColorGetG(color)), SkIntToScalar(SkColorGetB(color))); } SkImageFilterLight(const SkPoint3& color) : fColor(color) {} SkImageFilterLight(SkReadBuffer& buffer) { fColor = readPoint3(buffer); } virtual void onFlattenLight(SkWriteBuffer& buffer) const = 0; private: typedef SkRefCnt INHERITED; SkPoint3 fColor; }; /////////////////////////////////////////////////////////////////////////////// class SkDistantLight : public SkImageFilterLight { public: SkDistantLight(const SkPoint3& direction, SkColor color) : INHERITED(color), fDirection(direction) { } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { return fDirection; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kDistant_LightType; } const SkPoint3& direction() const { return fDirection; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLDistantLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return false; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kDistant_LightType) { return false; } const SkDistantLight& o = static_cast<const SkDistantLight&>(other); return INHERITED::isEqual(other) && fDirection == o.fDirection; } SkDistantLight(SkReadBuffer& buffer) : INHERITED(buffer) { fDirection = readPoint3(buffer); } protected: SkDistantLight(const SkPoint3& direction, const SkPoint3& color) : INHERITED(color), fDirection(direction) { } SkImageFilterLight* transform(const SkMatrix& matrix) const override { return new SkDistantLight(direction(), color()); } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fDirection, buffer); } private: SkPoint3 fDirection; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkPointLight : public SkImageFilterLight { public: SkPointLight(const SkPoint3& location, SkColor color) : INHERITED(color), fLocation(location) {} SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; const SkPoint3& lightColor(const SkPoint3&) const { return this->color(); } LightType type() const override { return kPoint_LightType; } const SkPoint3& location() const { return fLocation; } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLPointLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kPoint_LightType) { return false; } const SkPointLight& o = static_cast<const SkPointLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation; } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); return new SkPointLight(location, color()); } SkPointLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); } protected: SkPointLight(const SkPoint3& location, const SkPoint3& color) : INHERITED(color), fLocation(location) {} void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); } private: SkPoint3 fLocation; typedef SkImageFilterLight INHERITED; }; /////////////////////////////////////////////////////////////////////////////// class SkSpotLight : public SkImageFilterLight { public: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(SkScalarPin(specularExponent, kSpecularExponentMin, kSpecularExponentMax)) { fS = target - location; fast_normalize(&fS); fCosOuterConeAngle = SkScalarCos(SkDegreesToRadians(cutoffAngle)); const SkScalar antiAliasThreshold = 0.016f; fCosInnerConeAngle = fCosOuterConeAngle + antiAliasThreshold; fConeScale = SkScalarInvert(antiAliasThreshold); } SkImageFilterLight* transform(const SkMatrix& matrix) const override { SkPoint location2 = SkPoint::Make(fLocation.fX, fLocation.fY); matrix.mapPoints(&location2, 1); // Use X scale and Y scale on Z and average the result SkPoint locationZ = SkPoint::Make(fLocation.fZ, fLocation.fZ); matrix.mapVectors(&locationZ, 1); SkPoint3 location = SkPoint3::Make(location2.fX, location2.fY, SkScalarAve(locationZ.fX, locationZ.fY)); SkPoint target2 = SkPoint::Make(fTarget.fX, fTarget.fY); matrix.mapPoints(&target2, 1); SkPoint targetZ = SkPoint::Make(fTarget.fZ, fTarget.fZ); matrix.mapVectors(&targetZ, 1); SkPoint3 target = SkPoint3::Make(target2.fX, target2.fY, SkScalarAve(targetZ.fX, targetZ.fY)); SkPoint3 s = target - location; fast_normalize(&s); return new SkSpotLight(location, target, fSpecularExponent, fCosOuterConeAngle, fCosInnerConeAngle, fConeScale, s, color()); } SkPoint3 surfaceToLight(int x, int y, int z, SkScalar surfaceScale) const { SkPoint3 direction = SkPoint3::Make(fLocation.fX - SkIntToScalar(x), fLocation.fY - SkIntToScalar(y), fLocation.fZ - SkScalarMul(SkIntToScalar(z), surfaceScale)); fast_normalize(&direction); return direction; }; SkPoint3 lightColor(const SkPoint3& surfaceToLight) const { SkScalar cosAngle = -surfaceToLight.dot(fS); SkScalar scale = 0; if (cosAngle >= fCosOuterConeAngle) { scale = SkScalarPow(cosAngle, fSpecularExponent); if (cosAngle < fCosInnerConeAngle) { scale = SkScalarMul(scale, cosAngle - fCosOuterConeAngle); scale *= fConeScale; } } return this->color().makeScale(scale); } GrGLLight* createGLLight() const override { #if SK_SUPPORT_GPU return new GrGLSpotLight; #else SkDEBUGFAIL("Should not call in GPU-less build"); return nullptr; #endif } bool requiresFragmentPosition() const override { return true; } LightType type() const override { return kSpot_LightType; } const SkPoint3& location() const { return fLocation; } const SkPoint3& target() const { return fTarget; } SkScalar specularExponent() const { return fSpecularExponent; } SkScalar cosInnerConeAngle() const { return fCosInnerConeAngle; } SkScalar cosOuterConeAngle() const { return fCosOuterConeAngle; } SkScalar coneScale() const { return fConeScale; } const SkPoint3& s() const { return fS; } SkSpotLight(SkReadBuffer& buffer) : INHERITED(buffer) { fLocation = readPoint3(buffer); fTarget = readPoint3(buffer); fSpecularExponent = buffer.readScalar(); fCosOuterConeAngle = buffer.readScalar(); fCosInnerConeAngle = buffer.readScalar(); fConeScale = buffer.readScalar(); fS = readPoint3(buffer); buffer.validate(SkScalarIsFinite(fSpecularExponent) && SkScalarIsFinite(fCosOuterConeAngle) && SkScalarIsFinite(fCosInnerConeAngle) && SkScalarIsFinite(fConeScale)); } protected: SkSpotLight(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cosOuterConeAngle, SkScalar cosInnerConeAngle, SkScalar coneScale, const SkPoint3& s, const SkPoint3& color) : INHERITED(color), fLocation(location), fTarget(target), fSpecularExponent(specularExponent), fCosOuterConeAngle(cosOuterConeAngle), fCosInnerConeAngle(cosInnerConeAngle), fConeScale(coneScale), fS(s) { } void onFlattenLight(SkWriteBuffer& buffer) const override { writePoint3(fLocation, buffer); writePoint3(fTarget, buffer); buffer.writeScalar(fSpecularExponent); buffer.writeScalar(fCosOuterConeAngle); buffer.writeScalar(fCosInnerConeAngle); buffer.writeScalar(fConeScale); writePoint3(fS, buffer); } bool isEqual(const SkImageFilterLight& other) const override { if (other.type() != kSpot_LightType) { return false; } const SkSpotLight& o = static_cast<const SkSpotLight&>(other); return INHERITED::isEqual(other) && fLocation == o.fLocation && fTarget == o.fTarget && fSpecularExponent == o.fSpecularExponent && fCosOuterConeAngle == o.fCosOuterConeAngle; } private: static const SkScalar kSpecularExponentMin; static const SkScalar kSpecularExponentMax; SkPoint3 fLocation; SkPoint3 fTarget; SkScalar fSpecularExponent; SkScalar fCosOuterConeAngle; SkScalar fCosInnerConeAngle; SkScalar fConeScale; SkPoint3 fS; typedef SkImageFilterLight INHERITED; }; // According to the spec, the specular term should be in the range [1, 128] : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingSpecularExponentAttribute const SkScalar SkSpotLight::kSpecularExponentMin = 1.0f; const SkScalar SkSpotLight::kSpecularExponentMax = 128.0f; /////////////////////////////////////////////////////////////////////////////// void SkImageFilterLight::flattenLight(SkWriteBuffer& buffer) const { // Write type first, then baseclass, then subclass. buffer.writeInt(this->type()); writePoint3(fColor, buffer); this->onFlattenLight(buffer); } /*static*/ SkImageFilterLight* SkImageFilterLight::UnflattenLight(SkReadBuffer& buffer) { // Read type first. const SkImageFilterLight::LightType type = (SkImageFilterLight::LightType)buffer.readInt(); switch (type) { // Each of these constructors must first call SkLight's, so we'll read the baseclass // then subclass, same order as flattenLight. case SkImageFilterLight::kDistant_LightType: return new SkDistantLight(buffer); case SkImageFilterLight::kPoint_LightType: return new SkPointLight(buffer); case SkImageFilterLight::kSpot_LightType: return new SkSpotLight(buffer); default: SkDEBUGFAIL("Unknown LightType."); buffer.validate(false); return nullptr; } } /////////////////////////////////////////////////////////////////////////////// SkLightingImageFilter::SkLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkImageFilter* input, const CropRect* cropRect) : INHERITED(1, &input, cropRect) , fLight(SkRef(light)) , fSurfaceScale(surfaceScale / 255) {} SkImageFilter* SkLightingImageFilter::CreateDistantLitDiffuse(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitDiffuse(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitDiffuse(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkDiffuseLightingImageFilter::Create(light, surfaceScale, kd, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateDistantLitSpecular(const SkPoint3& direction, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkDistantLight(direction, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreatePointLitSpecular(const SkPoint3& location, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light(new SkPointLight(location, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkImageFilter* SkLightingImageFilter::CreateSpotLitSpecular(const SkPoint3& location, const SkPoint3& target, SkScalar specularExponent, SkScalar cutoffAngle, SkColor lightColor, SkScalar surfaceScale, SkScalar ks, SkScalar shine, SkImageFilter* input, const CropRect* cropRect) { SkAutoTUnref<SkImageFilterLight> light( new SkSpotLight(location, target, specularExponent, cutoffAngle, lightColor)); return SkSpecularLightingImageFilter::Create(light, surfaceScale, ks, shine, input, cropRect); } SkLightingImageFilter::~SkLightingImageFilter() {} void SkLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); fLight->flattenLight(buffer); buffer.writeScalar(fSurfaceScale * 255); } /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkDiffuseLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(kd)) { return nullptr; } // According to the spec, kd can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feDiffuseLightingElement if (kd < 0) { return nullptr; } return new SkDiffuseLightingImageFilter(light, surfaceScale, kd, input, cropRect); } SkDiffuseLightingImageFilter::SkDiffuseLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar kd, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKD(kd) { } SkFlattenable* SkDiffuseLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar kd = buffer.readScalar(); return Create(light, surfaceScale, kd, common.getInput(0), &common.cropRect()); } void SkDiffuseLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKD); } bool SkDiffuseLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); DiffuseLightingType lightingType(fKD); offset->fX = bounds.left(); offset->fY = bounds.top(); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<DiffuseLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<DiffuseLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<DiffuseLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkDiffuseLightingImageFilter::toString(SkString* str) const { str->appendf("SkDiffuseLightingImageFilter: ("); str->appendf("kD: %f\n", fKD); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkDiffuseLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode ) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrDiffuseLightingEffect::Create(texture, this->light(), scale, matrix, this->kd(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// SkImageFilter* SkSpecularLightingImageFilter::Create(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) { if (nullptr == light) { return nullptr; } if (!SkScalarIsFinite(surfaceScale) || !SkScalarIsFinite(ks) || !SkScalarIsFinite(shininess)) { return nullptr; } // According to the spec, ks can be any non-negative number : // http://www.w3.org/TR/SVG/filters.html#feSpecularLightingElement if (ks < 0) { return nullptr; } return new SkSpecularLightingImageFilter(light, surfaceScale, ks, shininess, input, cropRect); } SkSpecularLightingImageFilter::SkSpecularLightingImageFilter(SkImageFilterLight* light, SkScalar surfaceScale, SkScalar ks, SkScalar shininess, SkImageFilter* input, const CropRect* cropRect) : INHERITED(light, surfaceScale, input, cropRect), fKS(ks), fShininess(shininess) { } SkFlattenable* SkSpecularLightingImageFilter::CreateProc(SkReadBuffer& buffer) { SK_IMAGEFILTER_UNFLATTEN_COMMON(common, 1); SkAutoTUnref<SkImageFilterLight> light(SkImageFilterLight::UnflattenLight(buffer)); SkScalar surfaceScale = buffer.readScalar(); SkScalar ks = buffer.readScalar(); SkScalar shine = buffer.readScalar(); return Create(light, surfaceScale, ks, shine, common.getInput(0), &common.cropRect()); } void SkSpecularLightingImageFilter::flatten(SkWriteBuffer& buffer) const { this->INHERITED::flatten(buffer); buffer.writeScalar(fKS); buffer.writeScalar(fShininess); } bool SkSpecularLightingImageFilter::onFilterImage(Proxy* proxy, const SkBitmap& source, const Context& ctx, SkBitmap* dst, SkIPoint* offset) const { SkBitmap src = source; SkIPoint srcOffset = SkIPoint::Make(0, 0); if (!this->filterInput(0, proxy, source, ctx, &src, &srcOffset)) { return false; } if (src.colorType() != kN32_SkColorType) { return false; } SkIRect bounds; if (!this->applyCropRect(ctx, proxy, src, &srcOffset, &bounds, &src)) { return false; } if (bounds.width() < 2 || bounds.height() < 2) { return false; } SkAutoLockPixels alp(src); if (!src.getPixels()) { return false; } SkAutoTUnref<SkBaseDevice> device(proxy->createDevice(bounds.width(), bounds.height())); if (!device) { return false; } *dst = device->accessBitmap(false); SkAutoLockPixels alp_dst(*dst); SpecularLightingType lightingType(fKS, fShininess); offset->fX = bounds.left(); offset->fY = bounds.top(); SkMatrix matrix(ctx.ctm()); matrix.postTranslate(SkIntToScalar(-srcOffset.x()), SkIntToScalar(-srcOffset.y())); SkAutoTUnref<SkImageFilterLight> transformedLight(light()->transform(matrix)); bounds.offset(-srcOffset); switch (transformedLight->type()) { case SkImageFilterLight::kDistant_LightType: lightBitmap<SpecularLightingType, SkDistantLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kPoint_LightType: lightBitmap<SpecularLightingType, SkPointLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; case SkImageFilterLight::kSpot_LightType: lightBitmap<SpecularLightingType, SkSpotLight>(lightingType, transformedLight, src, dst, surfaceScale(), bounds); break; } return true; } #ifndef SK_IGNORE_TO_STRING void SkSpecularLightingImageFilter::toString(SkString* str) const { str->appendf("SkSpecularLightingImageFilter: ("); str->appendf("kS: %f shininess: %f", fKS, fShininess); str->append(")"); } #endif #if SK_SUPPORT_GPU GrFragmentProcessor* SkSpecularLightingImageFilter::getFragmentProcessor( GrTexture* texture, const SkMatrix& matrix, const SkIRect&, BoundaryMode boundaryMode) const { SkScalar scale = SkScalarMul(this->surfaceScale(), SkIntToScalar(255)); return GrSpecularLightingEffect::Create(texture, this->light(), scale, matrix, this->ks(), this->shininess(), boundaryMode); } #endif /////////////////////////////////////////////////////////////////////////////// #if SK_SUPPORT_GPU namespace { SkPoint3 random_point3(SkRandom* random) { return SkPoint3::Make(SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1()), SkScalarToFloat(random->nextSScalar1())); } SkImageFilterLight* create_random_light(SkRandom* random) { int type = random->nextULessThan(3); switch (type) { case 0: { return new SkDistantLight(random_point3(random), random->nextU()); } case 1: { return new SkPointLight(random_point3(random), random->nextU()); } case 2: { return new SkSpotLight(random_point3(random), random_point3(random), random->nextUScalar1(), random->nextUScalar1(), random->nextU()); } default: SkFAIL("Unexpected value."); return nullptr; } } SkString emitNormalFunc(BoundaryMode mode, const char* pointToNormalName, const char* sobelFuncName) { SkString result; switch (mode) { case kTopLeft_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[4], m[5], m[7], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kTop_BoundaryMode: result.printf("\treturn %s(%s(0.0, 0.0, m[3], m[5], m[6], m[8], %g),\n" "\t %s(0.0, 0.0, m[4], m[7], m[5], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kTopRight_BoundaryMode: result.printf("\treturn %s(%s( 0.0, 0.0, m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[3], m[6], m[4], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], m[7], m[8], %g),\n" "\t %s( 0.0, 0.0, m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kInterior_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], m[6], m[8], %g),\n" "\t %s(m[0], m[6], m[1], m[7], m[2], m[8], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneQuarter, sobelFuncName, gOneQuarter); break; case kRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], m[6], m[7], %g),\n" "\t %s(m[0], m[6], m[1], m[7], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneHalf, sobelFuncName, gOneThird); break; case kBottomLeft_BoundaryMode: result.printf("\treturn %s(%s(m[1], m[2], m[4], m[5], 0.0, 0.0, %g),\n" "\t %s( 0.0, 0.0, m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; case kBottom_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[2], m[3], m[5], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], m[2], m[5], %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gOneThird, sobelFuncName, gOneHalf); break; case kBottomRight_BoundaryMode: result.printf("\treturn %s(%s(m[0], m[1], m[3], m[4], 0.0, 0.0, %g),\n" "\t %s(m[0], m[3], m[1], m[4], 0.0, 0.0, %g),\n" "\t surfaceScale);\n", pointToNormalName, sobelFuncName, gTwoThirds, sobelFuncName, gTwoThirds); break; default: SkASSERT(false); break; } return result; } } class GrGLLightingEffect : public GrGLSLFragmentProcessor { public: GrGLLightingEffect(const GrProcessor&); virtual ~GrGLLightingEffect(); void emitCode(EmitArgs&) override; static inline void GenKey(const GrProcessor&, const GrGLSLCaps&, GrProcessorKeyBuilder* b); protected: /** * Subclasses of GrGLLightingEffect must call INHERITED::onSetData(); */ void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; virtual void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) = 0; private: typedef GrGLSLFragmentProcessor INHERITED; UniformHandle fImageIncrementUni; UniformHandle fSurfaceScaleUni; GrGLLight* fLight; BoundaryMode fBoundaryMode; }; /////////////////////////////////////////////////////////////////////////////// class GrGLDiffuseLightingEffect : public GrGLLightingEffect { public: GrGLDiffuseLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKDUni; }; /////////////////////////////////////////////////////////////////////////////// class GrGLSpecularLightingEffect : public GrGLLightingEffect { public: GrGLSpecularLightingEffect(const GrProcessor&); void emitLightFunc(GrGLSLUniformHandler*, GrGLSLFragmentBuilder*, SkString* funcName) override; protected: void onSetData(const GrGLSLProgramDataManager&, const GrProcessor&) override; private: typedef GrGLLightingEffect INHERITED; UniformHandle fKSUni; UniformHandle fShininessUni; }; /////////////////////////////////////////////////////////////////////////////// GrLightingEffect::GrLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, BoundaryMode boundaryMode) : INHERITED(texture, GrCoordTransform::MakeDivByTextureWHMatrix(texture)) , fLight(light) , fSurfaceScale(surfaceScale) , fFilterMatrix(matrix) , fBoundaryMode(boundaryMode) { fLight->ref(); if (light->requiresFragmentPosition()) { this->setWillReadFragmentPosition(); } } GrLightingEffect::~GrLightingEffect() { fLight->unref(); } bool GrLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrLightingEffect& s = sBase.cast<GrLightingEffect>(); return fLight->isEqual(*s.fLight) && fSurfaceScale == s.fSurfaceScale && fBoundaryMode == s.fBoundaryMode; } /////////////////////////////////////////////////////////////////////////////// GrDiffuseLightingEffect::GrDiffuseLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar kd, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode), fKD(kd) { this->initClassID<GrDiffuseLightingEffect>(); } bool GrDiffuseLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrDiffuseLightingEffect& s = sBase.cast<GrDiffuseLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->kd() == s.kd(); } void GrDiffuseLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLDiffuseLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrDiffuseLightingEffect::onCreateGLSLInstance() const { return new GrGLDiffuseLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrDiffuseLightingEffect); const GrFragmentProcessor* GrDiffuseLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar kd = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrDiffuseLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, kd, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLLightingEffect::GrGLLightingEffect(const GrProcessor& fp) { const GrLightingEffect& m = fp.cast<GrLightingEffect>(); fLight = m.light()->createGLLight(); fBoundaryMode = m.boundaryMode(); } GrGLLightingEffect::~GrGLLightingEffect() { delete fLight; } void GrGLLightingEffect::emitCode(EmitArgs& args) { GrGLSLUniformHandler* uniformHandler = args.fUniformHandler; fImageIncrementUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec2f_GrSLType, kDefault_GrSLPrecision, "ImageIncrement"); fSurfaceScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "SurfaceScale"); fLight->emitLightColorUniform(uniformHandler); GrGLSLFragmentBuilder* fragBuilder = args.fFragBuilder; SkString lightFunc; this->emitLightFunc(uniformHandler, fragBuilder, &lightFunc); static const GrGLSLShaderVar gSobelArgs[] = { GrGLSLShaderVar("a", kFloat_GrSLType), GrGLSLShaderVar("b", kFloat_GrSLType), GrGLSLShaderVar("c", kFloat_GrSLType), GrGLSLShaderVar("d", kFloat_GrSLType), GrGLSLShaderVar("e", kFloat_GrSLType), GrGLSLShaderVar("f", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString sobelFuncName; SkString coords2D = fragBuilder->ensureFSCoords2D(args.fCoords, 0); fragBuilder->emitFunction(kFloat_GrSLType, "sobel", SK_ARRAY_COUNT(gSobelArgs), gSobelArgs, "\treturn (-a + b - 2.0 * c + 2.0 * d -e + f) * scale;\n", &sobelFuncName); static const GrGLSLShaderVar gPointToNormalArgs[] = { GrGLSLShaderVar("x", kFloat_GrSLType), GrGLSLShaderVar("y", kFloat_GrSLType), GrGLSLShaderVar("scale", kFloat_GrSLType), }; SkString pointToNormalName; fragBuilder->emitFunction(kVec3f_GrSLType, "pointToNormal", SK_ARRAY_COUNT(gPointToNormalArgs), gPointToNormalArgs, "\treturn normalize(vec3(-x * scale, -y * scale, 1));\n", &pointToNormalName); static const GrGLSLShaderVar gInteriorNormalArgs[] = { GrGLSLShaderVar("m", kFloat_GrSLType, 9), GrGLSLShaderVar("surfaceScale", kFloat_GrSLType), }; SkString normalBody = emitNormalFunc(fBoundaryMode, pointToNormalName.c_str(), sobelFuncName.c_str()); SkString normalName; fragBuilder->emitFunction(kVec3f_GrSLType, "normal", SK_ARRAY_COUNT(gInteriorNormalArgs), gInteriorNormalArgs, normalBody.c_str(), &normalName); fragBuilder->codeAppendf("\t\tvec2 coord = %s;\n", coords2D.c_str()); fragBuilder->codeAppend("\t\tfloat m[9];\n"); const char* imgInc = uniformHandler->getUniformCStr(fImageIncrementUni); const char* surfScale = uniformHandler->getUniformCStr(fSurfaceScaleUni); int index = 0; for (int dy = 1; dy >= -1; dy--) { for (int dx = -1; dx <= 1; dx++) { SkString texCoords; texCoords.appendf("coord + vec2(%d, %d) * %s", dx, dy, imgInc); fragBuilder->codeAppendf("\t\tm[%d] = ", index++); fragBuilder->appendTextureLookup(args.fSamplers[0], texCoords.c_str()); fragBuilder->codeAppend(".a;\n"); } } fragBuilder->codeAppend("\t\tvec3 surfaceToLight = "); SkString arg; arg.appendf("%s * m[4]", surfScale); fLight->emitSurfaceToLight(uniformHandler, fragBuilder, arg.c_str()); fragBuilder->codeAppend(";\n"); fragBuilder->codeAppendf("\t\t%s = %s(%s(m, %s), surfaceToLight, ", args.fOutputColor, lightFunc.c_str(), normalName.c_str(), surfScale); fLight->emitLightColor(uniformHandler, fragBuilder, "surfaceToLight"); fragBuilder->codeAppend(");\n"); SkString modulate; GrGLSLMulVarBy4f(&modulate, args.fOutputColor, args.fInputColor); fragBuilder->codeAppend(modulate.c_str()); } void GrGLLightingEffect::GenKey(const GrProcessor& proc, const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); b->add32(lighting.boundaryMode() << 2 | lighting.light()->type()); } void GrGLLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { const GrLightingEffect& lighting = proc.cast<GrLightingEffect>(); GrTexture* texture = lighting.texture(0); float ySign = texture->origin() == kTopLeft_GrSurfaceOrigin ? -1.0f : 1.0f; pdman.set2f(fImageIncrementUni, 1.0f / texture->width(), ySign / texture->height()); pdman.set1f(fSurfaceScaleUni, lighting.surfaceScale()); SkAutoTUnref<SkImageFilterLight> transformedLight( lighting.light()->transform(lighting.filterMatrix())); fLight->setData(pdman, transformedLight); } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// GrGLDiffuseLightingEffect::GrGLDiffuseLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLDiffuseLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* kd; fKDUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KD", &kd); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tfloat colorScale = %s * dot(normal, surfaceToLight);\n", kd); lightBody.appendf("\treturn vec4(lightColor * clamp(colorScale, 0.0, 1.0), 1.0);\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLDiffuseLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& proc) { INHERITED::onSetData(pdman, proc); const GrDiffuseLightingEffect& diffuse = proc.cast<GrDiffuseLightingEffect>(); pdman.set1f(fKDUni, diffuse.kd()); } /////////////////////////////////////////////////////////////////////////////// GrSpecularLightingEffect::GrSpecularLightingEffect(GrTexture* texture, const SkImageFilterLight* light, SkScalar surfaceScale, const SkMatrix& matrix, SkScalar ks, SkScalar shininess, BoundaryMode boundaryMode) : INHERITED(texture, light, surfaceScale, matrix, boundaryMode) , fKS(ks) , fShininess(shininess) { this->initClassID<GrSpecularLightingEffect>(); } bool GrSpecularLightingEffect::onIsEqual(const GrFragmentProcessor& sBase) const { const GrSpecularLightingEffect& s = sBase.cast<GrSpecularLightingEffect>(); return INHERITED::onIsEqual(sBase) && this->ks() == s.ks() && this->shininess() == s.shininess(); } void GrSpecularLightingEffect::onGetGLSLProcessorKey(const GrGLSLCaps& caps, GrProcessorKeyBuilder* b) const { GrGLSpecularLightingEffect::GenKey(*this, caps, b); } GrGLSLFragmentProcessor* GrSpecularLightingEffect::onCreateGLSLInstance() const { return new GrGLSpecularLightingEffect(*this); } GR_DEFINE_FRAGMENT_PROCESSOR_TEST(GrSpecularLightingEffect); const GrFragmentProcessor* GrSpecularLightingEffect::TestCreate(GrProcessorTestData* d) { SkScalar surfaceScale = d->fRandom->nextSScalar1(); SkScalar ks = d->fRandom->nextUScalar1(); SkScalar shininess = d->fRandom->nextUScalar1(); SkAutoTUnref<SkImageFilterLight> light(create_random_light(d->fRandom)); SkMatrix matrix; for (int i = 0; i < 9; i++) { matrix[i] = d->fRandom->nextUScalar1(); } BoundaryMode mode = static_cast<BoundaryMode>(d->fRandom->nextU() % kBoundaryModeCount); return GrSpecularLightingEffect::Create(d->fTextures[GrProcessorUnitTest::kAlphaTextureIdx], light, surfaceScale, matrix, ks, shininess, mode); } /////////////////////////////////////////////////////////////////////////////// GrGLSpecularLightingEffect::GrGLSpecularLightingEffect(const GrProcessor& proc) : INHERITED(proc) { } void GrGLSpecularLightingEffect::emitLightFunc(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, SkString* funcName) { const char* ks; const char* shininess; fKSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "KS", &ks); fShininessUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Shininess", &shininess); static const GrGLSLShaderVar gLightArgs[] = { GrGLSLShaderVar("normal", kVec3f_GrSLType), GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType), GrGLSLShaderVar("lightColor", kVec3f_GrSLType) }; SkString lightBody; lightBody.appendf("\tvec3 halfDir = vec3(normalize(surfaceToLight + vec3(0, 0, 1)));\n"); lightBody.appendf("\tfloat colorScale = %s * pow(dot(normal, halfDir), %s);\n", ks, shininess); lightBody.appendf("\tvec3 color = lightColor * clamp(colorScale, 0.0, 1.0);\n"); lightBody.appendf("\treturn vec4(color, max(max(color.r, color.g), color.b));\n"); fragBuilder->emitFunction(kVec4f_GrSLType, "light", SK_ARRAY_COUNT(gLightArgs), gLightArgs, lightBody.c_str(), funcName); } void GrGLSpecularLightingEffect::onSetData(const GrGLSLProgramDataManager& pdman, const GrProcessor& effect) { INHERITED::onSetData(pdman, effect); const GrSpecularLightingEffect& spec = effect.cast<GrSpecularLightingEffect>(); pdman.set1f(fKSUni, spec.ks()); pdman.set1f(fShininessUni, spec.shininess()); } /////////////////////////////////////////////////////////////////////////////// void GrGLLight::emitLightColorUniform(GrGLSLUniformHandler* uniformHandler) { fColorUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightColor"); } void GrGLLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { fragBuilder->codeAppend(uniformHandler->getUniformCStr(this->lightColorUni())); } void GrGLLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { setUniformPoint3(pdman, fColorUni, light->color().makeScale(SkScalarInvert(SkIntToScalar(255)))); } /////////////////////////////////////////////////////////////////////////////// void GrGLDistantLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kDistant_LightType); const SkDistantLight* distantLight = static_cast<const SkDistantLight*>(light); setUniformNormal3(pdman, fDirectionUni, distantLight->direction()); } void GrGLDistantLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* dir; fDirectionUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightDirection", &dir); fragBuilder->codeAppend(dir); } /////////////////////////////////////////////////////////////////////////////// void GrGLPointLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kPoint_LightType); const SkPointLight* pointLight = static_cast<const SkPointLight*>(light); setUniformPoint3(pdman, fLocationUni, pointLight->location()); } void GrGLPointLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* loc; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &loc); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", loc, fragBuilder->fragmentPosition(), z); } /////////////////////////////////////////////////////////////////////////////// void GrGLSpotLight::setData(const GrGLSLProgramDataManager& pdman, const SkImageFilterLight* light) const { INHERITED::setData(pdman, light); SkASSERT(light->type() == SkImageFilterLight::kSpot_LightType); const SkSpotLight* spotLight = static_cast<const SkSpotLight *>(light); setUniformPoint3(pdman, fLocationUni, spotLight->location()); pdman.set1f(fExponentUni, spotLight->specularExponent()); pdman.set1f(fCosInnerConeAngleUni, spotLight->cosInnerConeAngle()); pdman.set1f(fCosOuterConeAngleUni, spotLight->cosOuterConeAngle()); pdman.set1f(fConeScaleUni, spotLight->coneScale()); setUniformNormal3(pdman, fSUni, spotLight->s()); } void GrGLSpotLight::emitSurfaceToLight(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char* z) { const char* location; fLocationUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "LightLocation", &location); fragBuilder->codeAppendf("normalize(%s - vec3(%s.xy, %s))", location, fragBuilder->fragmentPosition(), z); } void GrGLSpotLight::emitLightColor(GrGLSLUniformHandler* uniformHandler, GrGLSLFragmentBuilder* fragBuilder, const char *surfaceToLight) { const char* color = uniformHandler->getUniformCStr(this->lightColorUni()); // created by parent class. const char* exponent; const char* cosInner; const char* cosOuter; const char* coneScale; const char* s; fExponentUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "Exponent", &exponent); fCosInnerConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosInnerConeAngle", &cosInner); fCosOuterConeAngleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "CosOuterConeAngle", &cosOuter); fConeScaleUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kFloat_GrSLType, kDefault_GrSLPrecision, "ConeScale", &coneScale); fSUni = uniformHandler->addUniform(GrGLSLUniformHandler::kFragment_Visibility, kVec3f_GrSLType, kDefault_GrSLPrecision, "S", &s); static const GrGLSLShaderVar gLightColorArgs[] = { GrGLSLShaderVar("surfaceToLight", kVec3f_GrSLType) }; SkString lightColorBody; lightColorBody.appendf("\tfloat cosAngle = -dot(surfaceToLight, %s);\n", s); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosOuter); lightColorBody.appendf("\t\treturn vec3(0);\n"); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\tfloat scale = pow(cosAngle, %s);\n", exponent); lightColorBody.appendf("\tif (cosAngle < %s) {\n", cosInner); lightColorBody.appendf("\t\treturn %s * scale * (cosAngle - %s) * %s;\n", color, cosOuter, coneScale); lightColorBody.appendf("\t}\n"); lightColorBody.appendf("\treturn %s;\n", color); fragBuilder->emitFunction(kVec3f_GrSLType, "lightColor", SK_ARRAY_COUNT(gLightColorArgs), gLightColorArgs, lightColorBody.c_str(), &fLightColorFunc); fragBuilder->codeAppendf("%s(%s)", fLightColorFunc.c_str(), surfaceToLight); } #endif SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_START(SkLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkDiffuseLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_ENTRY(SkSpecularLightingImageFilter) SK_DEFINE_FLATTENABLE_REGISTRAR_GROUP_END
/* * Copyright (c) 2019 Rockchip Electronics Co. Ltd. * Author: Huaping Liao <huaping.liao@rock-chips.com> * * 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 "intc.h" #include <string.h> #include <stdint.h> #include <xtensa/hal.h> #include <xtensa/core-macros.h> #include <xtensa/xtruntime.h> #include "error.h" #include "io.h" #include "iomap.h" #include "section.h" #define REG_L 32 #define INTC_IRQ_TYPE IRQ_LEVEL0 /* DSP INTC registers */ #define INTC_IRQ_INTEN_L 0x00 #define INTC_IRQ_INTEN_H 0x04 #define INTC_IRQ_INTMASK_L 0x08 #define INTC_IRQ_INTMASK_H 0x0c #define INTC_IRQ_INTFORCE_L 0x10 #define INTC_IRQ_INTFORCE_H 0x14 #define INTC_IRQ_RAWSTATUS_L 0x18 #define INTC_IRQ_RAWSTATUS_H 0x1c #define INTC_IRQ_STATUS_L 0x20 #define INTC_IRQ_STATUS_H 0x24 #define INTC_IRQ_MASKSTATUS_L 0x28 #define INTC_IRQ_MASKSTATUS_H 0x2c #define INTC_IRQ_FINALSTATUS_L 0x30 #define INTC_IRQ_FINALSTATUS_H 0x34 #define INTC_IRQ_PLEVEL 0xd8 #define INTC_IRQ_PR_OFFSET 0xe8 struct irq_info { enum irq_num irq_num; isr_t isr; void *params; }; struct intc_regs { volatile uint32_t inten_l; volatile uint32_t inten_h; volatile uint32_t intmask_l; volatile uint32_t intmask_h; volatile uint32_t intforce_l; volatile uint32_t intforce_h; volatile uint32_t rawstatus_l; volatile uint32_t rawstatus_h; volatile uint32_t status_l; volatile uint32_t status_h; volatile uint32_t maskstatus_l; volatile uint32_t maskstatus_h; volatile uint32_t finalstatus_l; volatile uint32_t finalstatus_h; volatile uint32_t res0[0xd8 - 0x34]; volatile uint32_t plevel; volatile uint32_t res1[0xe8 - 0xd8]; volatile uint32_t pr_offset; }; static __sys_data__ struct irq_info g_irqs[IRQ_MAX_NUM]; extern "C" void intc_irq_handler(void *arg) { uint32_t irq_num; uint32_t status_l, status_h; struct intc_regs *intc_reg = (struct intc_regs *)DSP_INTC_BASE; // _xtos_clear_ints(INTC_IRQ_TYPE); status_l = intc_reg->status_l; status_h = intc_reg->status_h; for (irq_num = 0; irq_num < IRQ_MAX_NUM; irq_num++) { if (irq_num < REG_L) { if (status_l & 1) break; status_l >>= 1; } else { if (status_h & 1) break; status_h >>= 1; } } if (irq_num < IRQ_MAX_NUM && g_irqs[irq_num].isr) g_irqs[irq_num].isr((enum irq_num)irq_num, g_irqs[irq_num].params); return; } __sys__ int irq_mask(enum irq_num irq_num) { struct intc_regs *intc_reg = (struct intc_regs*)DSP_INTC_BASE; if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; if (irq_num < REG_L) intc_reg->intmask_l |= (0x1 << (irq_num & 0x1f)); else intc_reg->intmask_h |= (0x1 << ((irq_num - REG_L) & 0x1f)); return 0; } __sys__ int irq_unmask(enum irq_num irq_num) { struct intc_regs *intc_reg = (struct intc_regs *)DSP_INTC_BASE; if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; if (irq_num < REG_L) intc_reg->intmask_l &= (~(0x1 << (irq_num & 0x1f))); else intc_reg->intmask_h &= (~(0x1 << ((irq_num - REG_L) & 0x1f))); return 0; } __sys__ int irq_register_isr(enum irq_num irq_num, isr_t isr, void* params) { if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; g_irqs[irq_num].isr = isr; g_irqs[irq_num].irq_num = irq_num; g_irqs[irq_num].params = params; return 0; } __sys__ int irq_unregister_isr(enum irq_num irq_num) { if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; g_irqs[irq_num].isr = NULL; g_irqs[irq_num].irq_num = IRQ_MAX_NUM; g_irqs[irq_num].params = NULL; return 0; } __sys__ int irq_enable(enum irq_num irq_num) { struct intc_regs *intc_reg = (struct intc_regs *)DSP_INTC_BASE; if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; if (irq_num < REG_L) intc_reg->inten_l |= (0x1 << (irq_num & 0x1f)); else intc_reg->inten_h |= (0x1 << ((irq_num - REG_L) & 0x1f)); return 0; } __sys__ int irq_disable(enum irq_num irq_num) { struct intc_regs *intc_reg = (struct intc_regs *)DSP_INTC_BASE; if (irq_num >= IRQ_MAX_NUM || irq_num < 0) return -EINVALID; if (irq_num < REG_L) intc_reg->inten_l &= (~(0x1 << (irq_num & 0x1f))); else intc_reg->inten_h &= (~(0x1 << ((irq_num - REG_L) & 0x1f))); return 0; } __sys__ int intc_init(void) { memset(g_irqs, 0, sizeof(g_irqs)); _xtos_set_interrupt_handler(INTC_IRQ_TYPE, (_xtos_handler)&intc_irq_handler); _xtos_interrupt_enable(INTC_IRQ_TYPE); return 0; } __sys__ int intc_deinit(void) { _xtos_interrupt_disable(INTC_IRQ_TYPE); return 0; }
#include <iostream> using namespace std; int main(){ int n,x,p; int localmin,localmax; cin>>n; for (int i = 0; i < n; i++) { cin>>x; localmin = 100; localmax = 0; for (int i = 0; i < x; i++) { cin>>p; if(p>localmax){ localmax = p; } if(p<localmin){ localmin = p; } } cout<<(localmax-localmin)*2<<'\n'; } return 0; }
/* * Copyright (C) 2018 The Android Open Source Project * * 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 "private/backend/CommandStream.h" #include <utils/CallStack.h> #include <utils/Log.h> #include <utils/Profiler.h> #include <utils/Systrace.h> #include <functional> #ifdef ANDROID #include <sys/system_properties.h> #endif using namespace utils; namespace filament { namespace backend { // ------------------------------------------------------------------------------------------------ // A few utility functions for debugging... inline void printParameterPack(io::ostream& out) { } template<typename LAST> static void printParameterPack(io::ostream& out, const LAST& t) { out << t; } template<typename FIRST, typename... REMAINING> static void printParameterPack(io::ostream& out, const FIRST& first, const REMAINING& ... rest) { out << first << ", "; printParameterPack(out, rest...); } static UTILS_NOINLINE UTILS_UNUSED std::string extractMethodName(std::string& command) noexcept { constexpr const char startPattern[] = "::Command<&(filament::backend::Driver::"; auto pos = command.rfind(startPattern); auto end = command.rfind('('); pos += sizeof(startPattern) - 1; return command.substr(pos, end-pos); } // ------------------------------------------------------------------------------------------------ CommandStream::CommandStream(Driver& driver, CircularBuffer& buffer) noexcept : mDispatcher(&driver.getDispatcher()), mDriver(&driver), mCurrentBuffer(&buffer) #ifndef NDEBUG , mThreadId(std::this_thread::get_id()) #endif { #ifdef ANDROID char property[PROP_VALUE_MAX]; __system_property_get("filament.perfcounters", property); mUsePerformanceCounter = bool(atoi(property)); #endif } void CommandStream::execute(void* buffer) { SYSTRACE_CALL(); Profiler profiler; if (SYSTRACE_TAG) { if (UTILS_UNLIKELY(mUsePerformanceCounter)) { // we want to remove all this when tracing is completely disabled profiler.resetEvents(Profiler::EV_CPU_CYCLES | Profiler::EV_BPU_MISSES); profiler.start(); } } mDriver->execute([this, buffer]() { Driver& UTILS_RESTRICT driver = *mDriver; CommandBase* UTILS_RESTRICT base = static_cast<CommandBase*>(buffer); while (UTILS_LIKELY(base)) { base = base->execute(driver); } }); if (SYSTRACE_TAG) { if (UTILS_UNLIKELY(mUsePerformanceCounter)) { // we want to remove all this when tracing is completely disabled profiler.stop(); UTILS_UNUSED Profiler::Counters counters = profiler.readCounters(); SYSTRACE_VALUE32("GLThread (I)", counters.getInstructions()); SYSTRACE_VALUE32("GLThread (C)", counters.getCpuCycles()); SYSTRACE_VALUE32("GLThread (CPI x10)", counters.getCPI() * 10); SYSTRACE_VALUE32("GLThread (BPU miss)", counters.getBranchMisses()); SYSTRACE_VALUE32("GLThread (I / BPU miss)", counters.getInstructions() / counters.getBranchMisses()); } } } void CommandStream::queueCommand(std::function<void()> command) { new(allocateCommand(CustomCommand::align(sizeof(CustomCommand)))) CustomCommand(std::move(command)); } template<typename... ARGS> template<void (Driver::*METHOD)(ARGS...)> template<std::size_t... I> void CommandType<void (Driver::*)(ARGS...)>::Command<METHOD>::log(std::index_sequence<I...>) noexcept { #if DEBUG_COMMAND_STREAM static_assert(UTILS_HAS_RTTI, "DEBUG_COMMAND_STREAM can only be used with RTTI"); std::string command = utils::CallStack::demangleTypeName(typeid(Command).name()).c_str(); slog.d << extractMethodName(command) << " : size=" << sizeof(Command) << "\n\t"; printParameterPack(slog.d, std::get<I>(mArgs)...); slog.d << io::endl; #endif } template<typename... ARGS> template<void (Driver::*METHOD)(ARGS...)> void CommandType<void (Driver::*)(ARGS...)>::Command<METHOD>::log() noexcept { log(std::make_index_sequence<std::tuple_size<SavedParameters>::value>{}); } /* * When DEBUG_COMMAND_STREAM is activated, we need to explicitly instantiate the log() method * (this is because we don't want it in the header file) */ #if DEBUG_COMMAND_STREAM #define DECL_DRIVER_API_SYNCHRONOUS(RetType, methodName, paramsDecl, params) #define DECL_DRIVER_API(methodName, paramsDecl, params) \ template void CommandType<decltype(&Driver::methodName)>::Command<&Driver::methodName>::log() noexcept; #define DECL_DRIVER_API_RETURN(RetType, methodName, paramsDecl, params) \ template void CommandType<decltype(&Driver::methodName##R)>::Command<&Driver::methodName##R>::log() noexcept; #include "private/backend/DriverAPI.inc" #endif // ------------------------------------------------------------------------------------------------ void CustomCommand::execute(Driver&, CommandBase* base, intptr_t* next) noexcept { *next = CustomCommand::align(sizeof(CustomCommand)); static_cast<CustomCommand*>(base)->mCommand(); static_cast<CustomCommand*>(base)->~CustomCommand(); } } // namespace backend } // namespace filament // ------------------------------------------------------------------------------------------------ // Stream operators for all types in DriverEnums.h // (These must live outside of the filament namespace) // ------------------------------------------------------------------------------------------------ using namespace filament; using namespace backend; #if !defined(NDEBUG) && (DEBUG_COMMAND_STREAM != false) #define CASE(ENUM, VALUE) \ case ENUM::VALUE: { \ out << #VALUE; \ break; \ } io::ostream& operator<<(io::ostream& out, ShaderModel model) { switch (model) { CASE(ShaderModel, UNKNOWN) CASE(ShaderModel, GL_ES_30) CASE(ShaderModel, GL_CORE_41) } return out; } io::ostream& operator<<(io::ostream& out, PrimitiveType type) { switch (type) { CASE(PrimitiveType, TRIANGLES) CASE(PrimitiveType, LINES) CASE(PrimitiveType, POINTS) CASE(PrimitiveType, NONE) } return out; } io::ostream& operator<<(io::ostream& out, ElementType type) { switch (type) { CASE(ElementType, BYTE) CASE(ElementType, BYTE2) CASE(ElementType, BYTE3) CASE(ElementType, BYTE4) CASE(ElementType, UBYTE) CASE(ElementType, UBYTE2) CASE(ElementType, UBYTE3) CASE(ElementType, UBYTE4) CASE(ElementType, SHORT) CASE(ElementType, SHORT2) CASE(ElementType, SHORT3) CASE(ElementType, SHORT4) CASE(ElementType, USHORT) CASE(ElementType, USHORT2) CASE(ElementType, USHORT3) CASE(ElementType, USHORT4) CASE(ElementType, INT) CASE(ElementType, UINT) CASE(ElementType, FLOAT) CASE(ElementType, FLOAT2) CASE(ElementType, FLOAT3) CASE(ElementType, FLOAT4) CASE(ElementType, HALF) CASE(ElementType, HALF2) CASE(ElementType, HALF3) CASE(ElementType, HALF4) } return out; } io::ostream& operator<<(io::ostream& out, BufferUsage usage) { switch (usage) { CASE(BufferUsage, STATIC) CASE(BufferUsage, DYNAMIC) CASE(BufferUsage, STREAM) } return out; } io::ostream& operator<<(io::ostream& out, CullingMode mode) { switch (mode) { CASE(CullingMode, NONE) CASE(CullingMode, FRONT) CASE(CullingMode, BACK) CASE(CullingMode, FRONT_AND_BACK) } return out; } io::ostream& operator<<(io::ostream& out, SamplerType type) { switch (type) { CASE(SamplerType, SAMPLER_2D) CASE(SamplerType, SAMPLER_CUBEMAP) CASE(SamplerType, SAMPLER_EXTERNAL) } return out; } io::ostream& operator<<(io::ostream& out, SamplerFormat type) { switch (type) { CASE(SamplerFormat, INT) CASE(SamplerFormat, UINT) CASE(SamplerFormat, FLOAT) CASE(SamplerFormat, SHADOW) } return out; } io::ostream& operator<<(io::ostream& out, Precision precision) { switch (precision) { CASE(Precision, LOW) CASE(Precision, MEDIUM) CASE(Precision, HIGH) CASE(Precision, DEFAULT) } return out; } io::ostream& operator<<(io::ostream& out, PixelDataFormat format) { switch (format) { CASE(PixelDataFormat, R) CASE(PixelDataFormat, R_INTEGER) CASE(PixelDataFormat, RG) CASE(PixelDataFormat, RG_INTEGER) CASE(PixelDataFormat, RGB) CASE(PixelDataFormat, RGB_INTEGER) CASE(PixelDataFormat, RGBA) CASE(PixelDataFormat, RGBA_INTEGER) CASE(PixelDataFormat, DEPTH_COMPONENT) CASE(PixelDataFormat, DEPTH_STENCIL) CASE(PixelDataFormat, ALPHA) CASE(PixelDataFormat, UNUSED) } return out; } io::ostream& operator<<(io::ostream& out, PixelDataType format) { switch (format) { CASE(PixelDataType, UBYTE) CASE(PixelDataType, BYTE) CASE(PixelDataType, USHORT) CASE(PixelDataType, SHORT) CASE(PixelDataType, UINT) CASE(PixelDataType, INT) CASE(PixelDataType, HALF) CASE(PixelDataType, FLOAT) CASE(PixelDataType, COMPRESSED) CASE(PixelDataType, UINT_10F_11F_11F_REV) CASE(PixelDataType, USHORT_565) CASE(PixelDataType, UINT_2_10_10_10_REV) } return out; } io::ostream& operator<<(io::ostream& out, TextureFormat format) { switch (format) { CASE(TextureFormat, R8) CASE(TextureFormat, R8_SNORM) CASE(TextureFormat, R16F) CASE(TextureFormat, R32F) CASE(TextureFormat, R8UI) CASE(TextureFormat, R8I) CASE(TextureFormat, STENCIL8) CASE(TextureFormat, R16UI) CASE(TextureFormat, R16I) CASE(TextureFormat, R32UI) CASE(TextureFormat, R32I) CASE(TextureFormat, RG8) CASE(TextureFormat, RG8_SNORM) CASE(TextureFormat, RG16F) CASE(TextureFormat, RG32F) CASE(TextureFormat, RG8UI) CASE(TextureFormat, RG8I) CASE(TextureFormat, RG16UI) CASE(TextureFormat, RG16I) CASE(TextureFormat, RG32UI) CASE(TextureFormat, RG32I) CASE(TextureFormat, RGB8) CASE(TextureFormat, SRGB8) CASE(TextureFormat, RGB565) CASE(TextureFormat, RGB8_SNORM) CASE(TextureFormat, R11F_G11F_B10F) CASE(TextureFormat, RGB9_E5) CASE(TextureFormat, RGB16F) CASE(TextureFormat, RGB32F) CASE(TextureFormat, RGB8UI) CASE(TextureFormat, RGB8I) CASE(TextureFormat, RGB16UI) CASE(TextureFormat, RGB16I) CASE(TextureFormat, RGB32UI) CASE(TextureFormat, RGB32I) CASE(TextureFormat, RGBA8) CASE(TextureFormat, SRGB8_A8) CASE(TextureFormat, RGBA8_SNORM) CASE(TextureFormat, RGB5_A1) CASE(TextureFormat, RGBA4) CASE(TextureFormat, RGB10_A2) CASE(TextureFormat, RGBA16F) CASE(TextureFormat, RGBA32F) CASE(TextureFormat, RGBA8UI) CASE(TextureFormat, RGBA8I) CASE(TextureFormat, RGBA16UI) CASE(TextureFormat, RGBA16I) CASE(TextureFormat, RGBA32UI) CASE(TextureFormat, RGBA32I) CASE(TextureFormat, DEPTH16) CASE(TextureFormat, DEPTH24) CASE(TextureFormat, DEPTH32F) CASE(TextureFormat, DEPTH24_STENCIL8) CASE(TextureFormat, DEPTH32F_STENCIL8) // compressed formats... CASE(TextureFormat, EAC_R11) CASE(TextureFormat, EAC_R11_SIGNED) CASE(TextureFormat, EAC_RG11) CASE(TextureFormat, EAC_RG11_SIGNED) CASE(TextureFormat, ETC2_RGB8) CASE(TextureFormat, ETC2_SRGB8) CASE(TextureFormat, ETC2_RGB8_A1) CASE(TextureFormat, ETC2_SRGB8_A1) CASE(TextureFormat, ETC2_EAC_RGBA8) CASE(TextureFormat, ETC2_EAC_SRGBA8) CASE(TextureFormat, DXT1_RGB) CASE(TextureFormat, DXT1_SRGB) CASE(TextureFormat, DXT1_RGBA) CASE(TextureFormat, DXT1_SRGBA) CASE(TextureFormat, DXT3_RGBA) CASE(TextureFormat, DXT3_SRGBA) CASE(TextureFormat, DXT5_RGBA) CASE(TextureFormat, DXT5_SRGBA) CASE(TextureFormat, UNUSED) CASE(TextureFormat, RGBA_ASTC_4x4) CASE(TextureFormat, RGBA_ASTC_5x4) CASE(TextureFormat, RGBA_ASTC_5x5) CASE(TextureFormat, RGBA_ASTC_6x5) CASE(TextureFormat, RGBA_ASTC_6x6) CASE(TextureFormat, RGBA_ASTC_8x5) CASE(TextureFormat, RGBA_ASTC_8x6) CASE(TextureFormat, RGBA_ASTC_8x8) CASE(TextureFormat, RGBA_ASTC_10x5) CASE(TextureFormat, RGBA_ASTC_10x6) CASE(TextureFormat, RGBA_ASTC_10x8) CASE(TextureFormat, RGBA_ASTC_10x10) CASE(TextureFormat, RGBA_ASTC_12x10) CASE(TextureFormat, RGBA_ASTC_12x12) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_4x4) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_5x4) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_5x5) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_6x5) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_6x6) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_8x5) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_8x6) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_8x8) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_10x5) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_10x6) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_10x8) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_10x10) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_12x10) CASE(TextureFormat, SRGB8_ALPHA8_ASTC_12x12) } return out; } io::ostream& operator<<(io::ostream& out, TextureUsage usage) { switch (usage) { CASE(TextureUsage, DEFAULT) CASE(TextureUsage, COLOR_ATTACHMENT) CASE(TextureUsage, DEPTH_ATTACHMENT) CASE(TextureUsage, STENCIL_ATTACHMENT) CASE(TextureUsage, UPLOADABLE) CASE(TextureUsage, SAMPLEABLE) } return out; } io::ostream& operator<<(io::ostream& out, TextureCubemapFace face) { switch (face) { CASE(TextureCubemapFace, NEGATIVE_X) CASE(TextureCubemapFace, POSITIVE_X) CASE(TextureCubemapFace, NEGATIVE_Y) CASE(TextureCubemapFace, POSITIVE_Y) CASE(TextureCubemapFace, NEGATIVE_Z) CASE(TextureCubemapFace, POSITIVE_Z) } return out; } io::ostream& operator<<(io::ostream& out, SamplerWrapMode wrap) { switch (wrap) { CASE(SamplerWrapMode, REPEAT) CASE(SamplerWrapMode, CLAMP_TO_EDGE) CASE(SamplerWrapMode, MIRRORED_REPEAT) } return out; } io::ostream& operator<<(io::ostream& out, SamplerMinFilter filter) { switch (filter) { CASE(SamplerMinFilter, NEAREST) CASE(SamplerMinFilter, LINEAR) CASE(SamplerMinFilter, NEAREST_MIPMAP_NEAREST) CASE(SamplerMinFilter, LINEAR_MIPMAP_NEAREST) CASE(SamplerMinFilter, NEAREST_MIPMAP_LINEAR) CASE(SamplerMinFilter, LINEAR_MIPMAP_LINEAR) } return out; } io::ostream& operator<<(io::ostream& out, SamplerMagFilter filter) { switch (filter) { CASE(SamplerMagFilter, NEAREST) CASE(SamplerMagFilter, LINEAR) } return out; } io::ostream& operator<<(io::ostream& out, SamplerCompareMode mode) { switch (mode) { CASE(SamplerCompareMode, NONE) CASE(SamplerCompareMode, COMPARE_TO_TEXTURE) } return out; } io::ostream& operator<<(io::ostream& out, SamplerCompareFunc func) { switch (func) { CASE(SamplerCompareFunc, LE) CASE(SamplerCompareFunc, GE) CASE(SamplerCompareFunc, L) CASE(SamplerCompareFunc, G) CASE(SamplerCompareFunc, E) CASE(SamplerCompareFunc, NE) CASE(SamplerCompareFunc, A) CASE(SamplerCompareFunc, N) } return out; } io::ostream& operator<<(io::ostream& out, SamplerParams params) { out << "SamplerParams{ " << params.filterMin << ", " << params.filterMag << ", " << params.wrapS << ", " << params.wrapT << ", " << params.wrapR << ", " << (1u << params.anisotropyLog2) << ", " << params.compareMode << ", " << params.compareFunc << " }"; return out; } io::ostream& operator<<(io::ostream& out, const AttributeArray& type) { return out << "AttributeArray[" << type.max_size() << "]{}"; } io::ostream& operator<<(io::ostream& out, const FaceOffsets& type) { return out << "FaceOffsets{" << type[0] << ", " << type[1] << ", " << type[2] << ", " << type[3] << ", " << type[4] << ", " << type[5] << "}"; } io::ostream& operator<<(io::ostream& out, const RasterState& rs) { // TODO: implement decoding of enums return out << "RasterState{" << rs.culling << ", " << uint8_t(rs.blendEquationRGB) << ", " << uint8_t(rs.blendEquationAlpha) << ", " << uint8_t(rs.blendFunctionSrcRGB) << ", " << uint8_t(rs.blendFunctionSrcAlpha) << ", " << uint8_t(rs.blendFunctionDstRGB) << ", " << uint8_t(rs.blendFunctionDstAlpha) << "}"; } io::ostream& operator<<(io::ostream& out, const TargetBufferInfo& tbi) { return out << "TargetBufferInfo{" << "h=" << tbi.handle << ", " << "level=" << tbi.level << ", " << "face=" << tbi.face << "}"; } io::ostream& operator<<(io::ostream& out, const PolygonOffset& po) { return out << "PolygonOffset{" << "slope=" << po.slope << ", " << "constant=" << po.constant << "}"; } io::ostream& operator<<(io::ostream& out, const PipelineState& ps) { return out << "PipelineState{" << "program=" << ps.program << ", " << "rasterState=" << ps.rasterState << ", " << "polygonOffset=" << ps.polygonOffset << "}"; } UTILS_PRIVATE io::ostream& operator<<(io::ostream& out, BufferDescriptor const& b) { out << "BufferDescriptor { buffer=" << b.buffer << ", size=" << b.size << ", callback=" << b.getCallback() << ", user=" << b.getUser() << " }"; return out; } UTILS_PRIVATE io::ostream& operator<<(io::ostream& out, PixelBufferDescriptor const& b) { BufferDescriptor const& base = static_cast<BufferDescriptor const&>(b); out << "PixelBufferDescriptor { " << base << ", left=" << b.left << ", top=" << b.top << ", stride=" << b.stride << ", format=" << b.format << ", type=" << b.type << ", alignment=" << b.alignment << " }"; return out; } UTILS_PRIVATE io::ostream& operator<<(io::ostream& out, filament::backend::Viewport const& viewport) { out << "Viewport{" << ", left=" << viewport.left << ", bottom=" << viewport.bottom << ", width=" << viewport.width << ", height=" << viewport.height << "}"; return out; } UTILS_PRIVATE io::ostream& operator<<(io::ostream& out, TargetBufferFlags flags) { // TODO: implement decoding of enum out << uint8_t(flags); return out; } UTILS_PRIVATE io::ostream& operator<<(io::ostream& out, RenderPassParams const& params) { out << "RenderPassParams{" << "clear=" << params.flags.clear << ", discardStart=" << params.flags.discardStart << ", discardEnd=" << params.flags.discardEnd << ", left=" << params.viewport.left << ", bottom=" << params.viewport.bottom << ", width=" << params.viewport.width << ", height=" << params.viewport.height << ", clearColor=" << params.clearColor << ", clearDepth=" << params.clearDepth << ", clearStencil=" << params.clearStencil << "}"; return out; } io::ostream& operator<<(io::ostream& out, BufferObjectBinding wrap) { switch (wrap) { CASE(BufferObjectBinding, VERTEX) } return out; } #undef CASE #endif // !NDEBUG
#ifndef DLP4500_PATTERN_H #define DLP4500_PATTERN_H #include "linux_fbuffer.hpp" #define I_MAX 255 typedef struct pattern_parameters { unsigned char intensity = 255; // in rgb color level unsigned int period = 50; // in pixels float phase = 0; // in radians unsigned int exposure = 1000000; // in microseconds unsigned char color = 7; // codification from 1 (red) to 7 (white) } PatternParams; void draw_pixel(Screen screen, char *fbuffer, int x, int y, unsigned char *color); void draw_fringe_pattern(Screen screen, char *fbuffer, PatternParams pattern); void draw_binary_pattern(Screen screen, char *fbuffer, PatternParams pattern); void draw_hspeed_pattern(Screen screen, char *fbuffer, PatternParams pattern); #endif // DLP4500_PATTERN_H
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include <config/bitcoin-config.h> #endif #include <qt/sendcoinsentry.h> #include <qt/forms/ui_sendcoinsentry.h> #include <qt/addressbookpage.h> #include <qt/addresstablemodel.h> #include <qt/guiutil.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/walletmodel.h> #include <QApplication> #include <QClipboard> SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) : QStackedWidget(parent), ui(new Ui::SendCoinsEntry), model(nullptr), platformStyle(_platformStyle) { ui->setupUi(this); ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->pasteButton->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste")); ui->deleteButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->deleteButton_is->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->deleteButton_s->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); setCurrentWidget(ui->SendCoins); if (platformStyle->getUseExtraSpacing()) ui->payToLayout->setSpacing(4); // normal bitcoin address field GUIUtil::setupAddressWidget(ui->payTo, this); // just a label for displaying bitcoin address(es) ui->payTo_is->setFont(GUIUtil::fixedPitchFont()); // Connect signals connect(ui->payAmount, &BitcoinAmountField::valueChanged, this, &SendCoinsEntry::payAmountChanged); connect(ui->checkboxSubtractFeeFromAmount, &QCheckBox::toggled, this, &SendCoinsEntry::subtractFeeFromAmountChanged); connect(ui->deleteButton, &QPushButton::clicked, this, &SendCoinsEntry::deleteClicked); connect(ui->deleteButton_is, &QPushButton::clicked, this, &SendCoinsEntry::deleteClicked); connect(ui->deleteButton_s, &QPushButton::clicked, this, &SendCoinsEntry::deleteClicked); connect(ui->useAvailableBalanceButton, &QPushButton::clicked, this, &SendCoinsEntry::useAvailableBalanceClicked); } SendCoinsEntry::~SendCoinsEntry() { delete ui; } void SendCoinsEntry::on_pasteButton_clicked() { // Paste text from clipboard into recipient field ui->payTo->setText(QApplication::clipboard()->text()); } void SendCoinsEntry::on_addressBookButton_clicked() { if(!model) return; AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if(dlg.exec()) { ui->payTo->setText(dlg.getReturnValue()); ui->payAmount->setFocus(); } } void SendCoinsEntry::on_payTo_textChanged(const QString &address) { updateLabel(address); } void SendCoinsEntry::setModel(WalletModel *_model) { this->model = _model; if (_model && _model->getOptionsModel()) connect(_model->getOptionsModel(), &OptionsModel::displayUnitChanged, this, &SendCoinsEntry::updateDisplayUnit); clear(); } void SendCoinsEntry::clear() { // clear UI elements for normal payment ui->payTo->clear(); ui->addAsLabel->clear(); ui->payAmount->clear(); ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked); ui->messageTextLabel->clear(); ui->messageTextLabel->hide(); ui->messageLabel->hide(); // clear UI elements for unauthenticated payment request ui->payTo_is->clear(); ui->memoTextLabel_is->clear(); ui->payAmount_is->clear(); // clear UI elements for authenticated payment request ui->payTo_s->clear(); ui->memoTextLabel_s->clear(); ui->payAmount_s->clear(); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void SendCoinsEntry::checkSubtractFeeFromAmount() { ui->checkboxSubtractFeeFromAmount->setChecked(true); } void SendCoinsEntry::deleteClicked() { Q_EMIT removeEntry(this); } void SendCoinsEntry::useAvailableBalanceClicked() { Q_EMIT useAvailableBalance(this); } bool SendCoinsEntry::validate(interfaces::Node& node) { if (!model) return false; // Check input validity bool retval = true; if (!model->validateAddress(ui->payTo->text())) { ui->payTo->setValid(false); retval = false; } if (!ui->payAmount->validate()) { retval = false; } // Sending a zero amount is invalid if (ui->payAmount->value(nullptr) <= 0) { ui->payAmount->setValid(false); retval = false; } // Reject dust outputs: if (retval && GUIUtil::isDust(node, ui->payTo->text(), ui->payAmount->value())) { ui->payAmount->setValid(false); retval = false; } return retval; } SendCoinsRecipient SendCoinsEntry::getValue() { recipient.address = ui->payTo->text(); recipient.label = ui->addAsLabel->text(); recipient.amount = ui->payAmount->value(); recipient.message = ui->messageTextLabel->text(); recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked); return recipient; } QWidget *SendCoinsEntry::setupTabChain(QWidget *prev) { QWidget::setTabOrder(prev, ui->payTo); QWidget::setTabOrder(ui->payTo, ui->addAsLabel); QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel); QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount); QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton); QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); return ui->deleteButton; } void SendCoinsEntry::setValue(const SendCoinsRecipient &value) { recipient = value; { // message ui->messageTextLabel->setText(recipient.message); ui->messageTextLabel->setVisible(!recipient.message.isEmpty()); ui->messageLabel->setVisible(!recipient.message.isEmpty()); ui->addAsLabel->clear(); ui->payTo->setText(recipient.address); // this may set a label from addressbook if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label ui->addAsLabel->setText(recipient.label); ui->payAmount->setValue(recipient.amount); } } void SendCoinsEntry::setAddress(const QString &address) { ui->payTo->setText(address); ui->payAmount->setFocus(); } void SendCoinsEntry::setAmount(const CAmount &amount) { ui->payAmount->setValue(amount); } bool SendCoinsEntry::isClear() { return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty(); } void SendCoinsEntry::setFocus() { ui->payTo->setFocus(); } void SendCoinsEntry::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update payAmount with the current unit ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); } } void SendCoinsEntry::changeEvent(QEvent* e) { #ifdef Q_OS_MACOS if (e->type() == QEvent::PaletteChange) { ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/address-book"))); ui->pasteButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/editpaste"))); ui->deleteButton->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); ui->deleteButton_is->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); ui->deleteButton_s->setIcon(platformStyle->SingleColorIcon(QStringLiteral(":/icons/remove"))); } #endif } bool SendCoinsEntry::updateLabel(const QString &address) { if(!model) return false; // Fill in label from address book, if address has an associated label QString associatedLabel = model->getAddressTableModel()->labelForAddress(address); if(!associatedLabel.isEmpty()) { ui->addAsLabel->setText(associatedLabel); return true; } return false; }
#include <bits/stdc++.h> using namespace std; void solve() { int n; cin >> n; vector<int> a(n+1, 0); auto sieve = [&](){ int cnt = 1; for (int p = 2; p <= n; p++) { if (!a[p]) { a[p] = cnt; for (long long i = 1ll*p*p; i <= n; i+=p) { a[i] = cnt; } cnt++; } } }; sieve(); for (int i = 2; i <= n; i++) { cout << a[i] << ' '; } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); solve(); cout << endl; }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__new_int_01.cpp Label Definition File: CWE401_Memory_Leak__new.label.xml Template File: sources-sinks-01.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using new * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call delete on data * BadSink : no deallocation of data * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" #ifndef _WIN32 #include <wchar.h> #endif namespace CWE401_Memory_Leak__new_int_01 { #ifndef OMITBAD void bad() { int * data; data = NULL; /* POTENTIAL FLAW: Allocate memory on the heap */ data = new int; /* Initialize and make use of data */ *data = 5; printIntLine(*data); /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { int * data; data = NULL; /* FIX: Use memory allocated on the stack */ int dataGoodBuffer; data = &dataGoodBuffer; /* Initialize and make use of data */ *data = 5; printIntLine(*data); /* POTENTIAL FLAW: No deallocation */ ; /* empty statement needed for some flow variants */ } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { int * data; data = NULL; /* POTENTIAL FLAW: Allocate memory on the heap */ data = new int; /* Initialize and make use of data */ *data = 5; printIntLine(*data); /* FIX: Deallocate memory */ delete data; } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE401_Memory_Leak__new_int_01; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* * test/rectrace.cpp * Copyright 2013 Google Inc. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "backward.hpp" #include "test/test.hpp" #include <stdio.h> using namespace backward; typedef StackTrace stacktrace_t; void end_of_our_journey(stacktrace_t &st) { if (not st.size()) { st.load_here(); } } int rec(stacktrace_t &st, int level) { if (level <= 1) { end_of_our_journey(st); return 0; } return rec(st, level - 1); } namespace toto { namespace titi { struct foo { union bar { __attribute__((noinline)) static int trampoline(stacktrace_t &st, int level) { return rec(st, level); } }; }; } // namespace titi } // namespace toto TEST(recursion) { { // lexical scope. stacktrace_t st; const int input = 3; int r = toto::titi::foo::bar::trampoline(st, input); std::cout << "rec(" << input << ") == " << r << std::endl; Printer printer; // printer.address = true; printer.object = true; printer.print(st, stdout); } } int fib(StackTrace &st, int level) { if (level == 2) { return 1; } if (level <= 1) { end_of_our_journey(st); return 0; } return fib(st, level - 1) + fib(st, level - 2); } TEST(fibrecursive) { StackTrace st; const int input = 6; int r = fib(st, input); std::cout << "fib(" << input << ") == " << r << std::endl; Printer printer; printer.print(st, stdout); }
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "ColorBarConfigUnit.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.dfm" TColorBarConfigForm *ColorBarConfigForm; //--------------------------------------------------------------------------- __fastcall TColorBarConfigForm::TColorBarConfigForm(TComponent* Owner) : TForm(Owner) { } //---------------------------------------------------------------------------
#include "GamePlayer.h" #define PLAYER_LIFE_MAX 100; GamePlayer::GamePlayer(int player_id, double init_location_x, double init_location_y, double init_location_z) { this->player_id = player_id; this->location_x = init_location_x; this->location_y = init_location_y; this->location_z = init_location_z; this->quaternion["x"] = 0; this->quaternion["y"] = 0; this->quaternion["z"] = 0; this->quaternion["w"] = 0; this->score = 0; this->life = PLAYER_LIFE_MAX; } GamePlayer::~GamePlayer() { //dtor } double GamePlayer::get_location_x() { return this->location_x; } double GamePlayer::get_location_y() { return this->location_y; } double GamePlayer::get_location_z() { return this->location_z; } void GamePlayer::set_location_x(double new_location_x) { this->location_x = new_location_x; } void GamePlayer::set_quaternion(json new_quaternion) { this->quaternion = new_quaternion; } void GamePlayer::set_location_y(double new_location_y) { this->location_y = new_location_y; } void GamePlayer::set_location_z(double new_location_z) { this->location_z = new_location_z; } json GamePlayer::to_json() { json player_json; player_json["i"] = player_id; player_json["l"] = life; player_json["x"] = location_x; player_json["y"] = location_y; player_json["z"] = location_z; // player_json["q"] = quaternion; player_json["s"] = score; return player_json; } void GamePlayer::hurt(int life_to_decrease) { life -= life_to_decrease; } void GamePlayer::add_score(int score_to_add){ score += score_to_add; } int GamePlayer::get_score(){ return score; } int GamePlayer::get_life(){ return life; }
#include "JoyInfoExString.h" JoyInfoExString::JoyInfoExString(void) { } JoyInfoExString::~JoyInfoExString(void) { } tstring JoyInfoExString::ToString(JOYINFOEX* joyInfoEx) { tstringstream stream; stream << _T("----- JoyInfoEx -----") << endl << _T("dwSize:") << joyInfoEx->dwSize << endl << _T("dwFlags:") << joyInfoEx->dwFlags << endl << _T("dwXpos:") << joyInfoEx->dwXpos << endl << _T("dwYpos:") << joyInfoEx->dwYpos << endl << _T("dwZpos:") << joyInfoEx->dwZpos << endl << _T("dwRpos:") << joyInfoEx->dwRpos << endl << _T("dwUpos:") << joyInfoEx->dwUpos << endl << _T("dwVpos:") << joyInfoEx->dwVpos << endl << _T("dwButtons:") << joyInfoEx->dwButtons << endl << _T("dwButtonNumber:") << joyInfoEx->dwButtonNumber << endl << _T("dwPOV:") << joyInfoEx->dwPOV << endl << _T("dwReserved1:") << joyInfoEx->dwReserved1 << endl << _T("dwReserved2:") << joyInfoEx->dwReserved2 << endl; return stream.str(); }
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <memory> #include <transformations_visibility.hpp> #include "ngraph/op/op.hpp" namespace ngraph { namespace op { class TRANSFORMATIONS_API ScaleShiftIE : public Op { public: static constexpr NodeTypeInfo type_info{"ScaleShiftIE", 1}; const NodeTypeInfo& get_type_info() const override { return type_info; } ScaleShiftIE(const Output<Node>& data_batch, const Output<Node>& weights, const Output<Node>& bias); void validate_and_infer_types() override; std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override; }; } // namespace op } // namespace ngraph
#include <doctest/doctest.h> #include <array> #include <chess/position.hpp> #include <cstdint> #include <string> #include <swizzles/search/root.hpp> TEST_SUITE_BEGIN("Search"); TEST_CASE("Search - Tactics") { using pair_type = std::pair<std::string, std::string>; const std::array<pair_type, 2> tests = {{ {"4k3/q7/1P6/8/8/8/8/4K3 w - - 0 1", "b6a7"}, {"4k3/8/8/3q4/8/8/3Q4/4K3 w - - 0 1", "d2d5"}, }}; auto state = swizzles::uci::UCIState(); state.tt = std::make_shared<TT<swizzles::TTEntry>>(1); // Search settings auto settings = swizzles::search::SearchSettings(); settings.type = swizzles::search::SearchType::Depth; settings.depth = 4; std::atomic<bool> stop = false; for (const auto &[fen, movestr] : tests) { INFO("FEN: ", fen); state.pos.set_fen(fen); const auto results = swizzles::search::root(state, settings, stop); REQUIRE(static_cast<std::string>(results.bestmove) == movestr); } } TEST_SUITE_END();
//============================================================================ // Name : // Author : Avi // Revision : $Revision: #11 $ // // Copyright 2009-2020 ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. // // Description : //============================================================================ #include <stdexcept> #include "DayParser.hpp" #include "DefsStructureParser.hpp" #include "Node.hpp" using namespace std; bool DayParser::doParse( const std::string& line, std::vector<std::string >& lineTokens ) { // day monday # free expired // day tuesday # expired if ( lineTokens.size() < 2 ) { throw std::runtime_error( "DayParser::doParse: Invalid day :" + line ); } if ( nodeStack().empty() ) { throw std::runtime_error("DayParser::doParse: Could not add day as node stack is empty at line: " + line ); } // parse day and state nodeStack_top()->addDay( DayAttr::create(lineTokens, rootParser()->get_file_type() != PrintStyle::DEFS)); return true; }
#include <boost/circular_buffer.hpp> #include <iostream> using namespace std; int main() { typedef boost::circular_buffer<int> circular_buffer; circular_buffer cb{3}; cb.push_back(0); cb.push_back(1); cb.push_back(2); cb.push_back(3); cout << boolalpha << cb.is_linearized() << endl; circular_buffer::array_range ar1, ar2; ar1 = cb.array_one(); ar2 = cb.array_two(); cout << ar1.second << ";" << ar2.second << endl; for (int i: cb) cout << i << endl; cb.linearize(); ar1 = cb.array_one(); ar2 = cb.array_two(); cout << ar1.second << ";" << ar2.second << endl; }
/*Exercise 4 - Functions Write a program to calculate the function called nCr which is defined as nCr = n!/ r!(n−r)! Where n! is the factorial of n. Implement the functions long Factorial(int no); long nCr(int n, int r); Do not modify the main function.*/ #include <iostream> long Factorial(int no); long nCr(int n, int r); int main() { int n, r; std::cout << "Enter a value for n "; std::cin >> n; std::cout << "Enter a value for r "; std::cin >> r; std::cout << "nCr = "; std::cout << nCr(n,r); std::cout << std::endl; return 0; } long Factorial(int no) { long fac = 1; for (int r=no; r >= 1; r--) { fac = fac * r; } return fac; } long nCr(int n, int r) { long nCr=Factorial( n)/Factorial( r)*Factorial( n-r); return nCr; }
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. #include <UIRibbon.h> #include "CommandHandler.h" #include "RibbonFramework.h" #include <UIRibbonPropertyHelpers.h> // Static method to create an instance of the object. __checkReturn HRESULT CCommandHandler::CreateInstance(__deref_out IUICommandHandler **ppCommandHandler) { if (!ppCommandHandler) { return E_POINTER; } *ppCommandHandler = NULL; HRESULT hr = S_OK; CCommandHandler* pCommandHandler = new CCommandHandler(); if (pCommandHandler != NULL) { *ppCommandHandler = static_cast<IUICommandHandler *>(pCommandHandler); } else { hr = E_OUTOFMEMORY; } return hr; } // IUnknown method implementations. STDMETHODIMP_(ULONG) CCommandHandler::AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) CCommandHandler::Release() { LONG cRef = InterlockedDecrement(&m_cRef); if (cRef == 0) { delete this; } return cRef; } STDMETHODIMP CCommandHandler::QueryInterface(REFIID iid, void** ppv) { if (iid == __uuidof(IUnknown)) { *ppv = static_cast<IUnknown*>(this); } else if (iid == __uuidof(IUICommandHandler)) { *ppv = static_cast<IUICommandHandler*>(this); } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return S_OK; } // // FUNCTION: UpdateProperty() // // PURPOSE: Called by the Ribbon framework when a command property (PKEY) needs to be updated. // // COMMENTS: // // This function is used to provide new command property values, such as labels, icons, or // tooltip information, when requested by the Ribbon framework. // // STDMETHODIMP CCommandHandler::UpdateProperty( UINT nCmdID, __in REFPROPERTYKEY key, __in_opt const PROPVARIANT* ppropvarCurrentValue, __out PROPVARIANT* ppropvarNewValue) { UNREFERENCED_PARAMETER(nCmdID); HRESULT hr = E_NOTIMPL; if (key == UI_PKEY_FontProperties) { hr = E_POINTER; if (ppropvarCurrentValue != NULL) { // Get the font values for the selected text in the font control. IPropertyStore *pValues; hr = UIPropertyToInterface(UI_PKEY_FontProperties, *ppropvarCurrentValue, &pValues); if (SUCCEEDED(hr)) { g_pFCSampleAppManager->GetValues(pValues); // Provide the new values to the font control. hr = UIInitPropertyFromInterface(UI_PKEY_FontProperties, pValues, ppropvarNewValue); pValues->Release(); } } } return hr; } // // FUNCTION: Execute() // // PURPOSE: Called by the Ribbon framework when a command is executed by the user. For example, when // a button is pressed. // STDMETHODIMP CCommandHandler::Execute( UINT nCmdID, UI_EXECUTIONVERB verb, __in_opt const PROPERTYKEY* key, __in_opt const PROPVARIANT* ppropvarValue, __in_opt IUISimplePropertySet* pCommandExecutionProperties) { UNREFERENCED_PARAMETER(nCmdID); HRESULT hr = E_NOTIMPL; if ((key) && (*key == UI_PKEY_FontProperties)) { // Font properties have changed. switch (verb) { case UI_EXECUTIONVERB_EXECUTE: { hr = E_POINTER; if (pCommandExecutionProperties != NULL) { // Get the changed properties. PROPVARIANT varChanges; hr = pCommandExecutionProperties->GetValue(UI_PKEY_FontProperties_ChangedProperties, &varChanges); if (SUCCEEDED(hr)) { IPropertyStore *pChanges; hr = UIPropertyToInterface(UI_PKEY_FontProperties, varChanges, &pChanges); if (SUCCEEDED(hr)) { // Using the changed properties, set the new font on the selection on RichEdit control. g_pFCSampleAppManager->SetValues(pChanges); pChanges->Release(); } PropVariantClear(&varChanges); } } break; } case UI_EXECUTIONVERB_PREVIEW: { hr = E_POINTER; if (pCommandExecutionProperties != NULL) { // Get the changed properties for the preview event. PROPVARIANT varChanges; hr = pCommandExecutionProperties->GetValue(UI_PKEY_FontProperties_ChangedProperties, &varChanges); if (SUCCEEDED(hr)) { IPropertyStore *pChanges; hr = UIPropertyToInterface(UI_PKEY_FontProperties, varChanges, &pChanges); if (SUCCEEDED(hr)) { // Set the previewed values on the RichEdit control. g_pFCSampleAppManager->SetPreviewValues(pChanges); pChanges->Release(); } PropVariantClear(&varChanges); } } break; } case UI_EXECUTIONVERB_CANCELPREVIEW: { hr = E_POINTER; if (ppropvarValue != NULL) { // Cancel the preview. IPropertyStore *pValues; hr = UIPropertyToInterface(UI_PKEY_FontProperties, *ppropvarValue, &pValues); if (SUCCEEDED(hr)) { g_pFCSampleAppManager->CancelPreview(pValues); pValues->Release(); } } break; } } } return hr; }
/* * Copyright (c) 2015, Nagoya University * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of Autoware 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. */ /* Localization and mapping program using Normal Distributions Transform Yuki KITSUKAWA */ #define OUTPUT // If you want to output "position_log.txt", "#define OUTPUT". #include <fstream> #include <iostream> #include <sstream> #include <string> #include <nav_msgs/Odometry.h> #include <ros/ros.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/PointCloud2.h> #include <std_msgs/Bool.h> #include <std_msgs/Float32.h> #include <velodyne_pointcloud/point_types.h> #include <velodyne_pointcloud/rawdata.h> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> #include <pcl/io/io.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl_conversions/pcl_conversions.h> #include <ndt_cpu/NormalDistributionsTransform.h> #include <pcl/registration/ndt.h> #ifdef CUDA_FOUND #include <ndt_gpu/NormalDistributionsTransform.h> #endif #ifdef USE_PCL_OPENMP #include <pcl_omp_registration/ndt.h> #endif #include <autoware_msgs/ConfigNdtMapping.h> #include <autoware_msgs/ConfigNdtMappingOutput.h> #include <time.h> struct pose { double x; double y; double z; double roll; double pitch; double yaw; }; enum class MethodType { PCL_GENERIC = 0, PCL_ANH = 1, PCL_ANH_GPU = 2, PCL_OPENMP = 3, }; static MethodType _method_type = MethodType::PCL_GENERIC; // global variables static pose previous_pose, guess_pose, guess_pose_imu, guess_pose_odom, guess_pose_imu_odom, current_pose, current_pose_imu, current_pose_odom, current_pose_imu_odom, ndt_pose, added_pose, localizer_pose; static ros::Time current_scan_time; static ros::Time previous_scan_time; static ros::Duration scan_duration; static double diff = 0.0; static double diff_x = 0.0, diff_y = 0.0, diff_z = 0.0, diff_yaw; // current_pose - previous_pose static double offset_imu_x, offset_imu_y, offset_imu_z, offset_imu_roll, offset_imu_pitch, offset_imu_yaw; static double offset_odom_x, offset_odom_y, offset_odom_z, offset_odom_roll, offset_odom_pitch, offset_odom_yaw; static double offset_imu_odom_x, offset_imu_odom_y, offset_imu_odom_z, offset_imu_odom_roll, offset_imu_odom_pitch, offset_imu_odom_yaw; static double current_velocity_x = 0.0; static double current_velocity_y = 0.0; static double current_velocity_z = 0.0; static double current_velocity_imu_x = 0.0; static double current_velocity_imu_y = 0.0; static double current_velocity_imu_z = 0.0; static pcl::PointCloud<pcl::PointXYZI> map; static pcl::NormalDistributionsTransform<pcl::PointXYZI, pcl::PointXYZI> ndt; static cpu::NormalDistributionsTransform<pcl::PointXYZI, pcl::PointXYZI> anh_ndt; #ifdef CUDA_FOUND static gpu::GNormalDistributionsTransform anh_gpu_ndt; #endif #ifdef USE_PCL_OPENMP static pcl_omp::NormalDistributionsTransform<pcl::PointXYZI, pcl::PointXYZI> omp_ndt; #endif // Default values static int max_iter = 30; // Maximum iterations static float ndt_res = 1.0; // Resolution static double step_size = 0.1; // Step size static double trans_eps = 0.01; // Transformation epsilon // Leaf size of VoxelGrid filter. static double voxel_leaf_size = 2.0; static ros::Time callback_start, callback_end, t1_start, t1_end, t2_start, t2_end, t3_start, t3_end, t4_start, t4_end, t5_start, t5_end; static ros::Duration d_callback, d1, d2, d3, d4, d5; static ros::Publisher ndt_map_pub; static ros::Publisher current_pose_pub; static ros::Publisher guess_pose_linaer_pub; static geometry_msgs::PoseStamped current_pose_msg, guess_pose_msg; static ros::Publisher ndt_stat_pub; static std_msgs::Bool ndt_stat_msg; static int initial_scan_loaded = 0; static Eigen::Matrix4f gnss_transform = Eigen::Matrix4f::Identity(); static double min_scan_range = 5.0; static double max_scan_range = 200.0; static double min_add_scan_shift = 1.0; static double _tf_x, _tf_y, _tf_z, _tf_roll, _tf_pitch, _tf_yaw; static Eigen::Matrix4f tf_btol, tf_ltob; static bool _use_imu = false; static bool _use_odom = false; static bool _imu_upside_down = false; static bool _incremental_voxel_update = false; static std::string _imu_topic = "/imu_raw"; static double fitness_score; static bool has_converged; static int final_num_iteration; static double transformation_probability; static sensor_msgs::Imu imu; static nav_msgs::Odometry odom; static std::ofstream ofs; static std::string filename; static void param_callback(const autoware_msgs::ConfigNdtMapping::ConstPtr& input) { ndt_res = input->resolution; step_size = input->step_size; trans_eps = input->trans_epsilon; max_iter = input->max_iterations; voxel_leaf_size = input->leaf_size; min_scan_range = input->min_scan_range; max_scan_range = input->max_scan_range; min_add_scan_shift = input->min_add_scan_shift; std::cout << "param_callback" << std::endl; std::cout << "ndt_res: " << ndt_res << std::endl; std::cout << "step_size: " << step_size << std::endl; std::cout << "trans_epsilon: " << trans_eps << std::endl; std::cout << "max_iter: " << max_iter << std::endl; std::cout << "voxel_leaf_size: " << voxel_leaf_size << std::endl; std::cout << "min_scan_range: " << min_scan_range << std::endl; std::cout << "max_scan_range: " << max_scan_range << std::endl; std::cout << "min_add_scan_shift: " << min_add_scan_shift << std::endl; } static void output_callback(const autoware_msgs::ConfigNdtMappingOutput::ConstPtr& input) { double filter_res = input->filter_res; std::string filename = input->filename; std::cout << "output_callback" << std::endl; std::cout << "filter_res: " << filter_res << std::endl; std::cout << "filename: " << filename << std::endl; pcl::PointCloud<pcl::PointXYZI>::Ptr map_ptr(new pcl::PointCloud<pcl::PointXYZI>(map)); pcl::PointCloud<pcl::PointXYZI>::Ptr map_filtered(new pcl::PointCloud<pcl::PointXYZI>()); map_ptr->header.frame_id = "map"; map_filtered->header.frame_id = "map"; sensor_msgs::PointCloud2::Ptr map_msg_ptr(new sensor_msgs::PointCloud2); // Apply voxelgrid filter if (filter_res == 0.0) { std::cout << "Original: " << map_ptr->points.size() << " points." << std::endl; pcl::toROSMsg(*map_ptr, *map_msg_ptr); } else { pcl::VoxelGrid<pcl::PointXYZI> voxel_grid_filter; voxel_grid_filter.setLeafSize(filter_res, filter_res, filter_res); voxel_grid_filter.setInputCloud(map_ptr); voxel_grid_filter.filter(*map_filtered); std::cout << "Original: " << map_ptr->points.size() << " points." << std::endl; std::cout << "Filtered: " << map_filtered->points.size() << " points." << std::endl; pcl::toROSMsg(*map_filtered, *map_msg_ptr); } ndt_map_pub.publish(*map_msg_ptr); // Writing Point Cloud data to PCD file if (filter_res == 0.0) { pcl::io::savePCDFileASCII(filename, *map_ptr); std::cout << "Saved " << map_ptr->points.size() << " data points to " << filename << "." << std::endl; } else { pcl::io::savePCDFileASCII(filename, *map_filtered); std::cout << "Saved " << map_filtered->points.size() << " data points to " << filename << "." << std::endl; } } static void imu_odom_calc(ros::Time current_time) { static ros::Time previous_time = current_time; double diff_time = (current_time - previous_time).toSec(); double diff_imu_roll = imu.angular_velocity.x * diff_time; double diff_imu_pitch = imu.angular_velocity.y * diff_time; double diff_imu_yaw = imu.angular_velocity.z * diff_time; current_pose_imu_odom.roll += diff_imu_roll; current_pose_imu_odom.pitch += diff_imu_pitch; current_pose_imu_odom.yaw += diff_imu_yaw; double diff_distance = odom.twist.twist.linear.x * diff_time; offset_imu_odom_x += diff_distance * cos(-current_pose_imu_odom.pitch) * cos(current_pose_imu_odom.yaw); offset_imu_odom_y += diff_distance * cos(-current_pose_imu_odom.pitch) * sin(current_pose_imu_odom.yaw); offset_imu_odom_z += diff_distance * sin(-current_pose_imu_odom.pitch); offset_imu_odom_roll += diff_imu_roll; offset_imu_odom_pitch += diff_imu_pitch; offset_imu_odom_yaw += diff_imu_yaw; guess_pose_imu_odom.x = previous_pose.x + offset_imu_odom_x; guess_pose_imu_odom.y = previous_pose.y + offset_imu_odom_y; guess_pose_imu_odom.z = previous_pose.z + offset_imu_odom_z; guess_pose_imu_odom.roll = previous_pose.roll + offset_imu_odom_roll; guess_pose_imu_odom.pitch = previous_pose.pitch + offset_imu_odom_pitch; guess_pose_imu_odom.yaw = previous_pose.yaw + offset_imu_odom_yaw; previous_time = current_time; } static void odom_calc(ros::Time current_time) { static ros::Time previous_time = current_time; double diff_time = (current_time - previous_time).toSec(); double diff_odom_roll = odom.twist.twist.angular.x * diff_time; double diff_odom_pitch = odom.twist.twist.angular.y * diff_time; double diff_odom_yaw = odom.twist.twist.angular.z * diff_time; current_pose_odom.roll += diff_odom_roll; current_pose_odom.pitch += diff_odom_pitch; current_pose_odom.yaw += diff_odom_yaw; double diff_distance = odom.twist.twist.linear.x * diff_time; offset_odom_x += diff_distance * cos(-current_pose_odom.pitch) * cos(current_pose_odom.yaw); offset_odom_y += diff_distance * cos(-current_pose_odom.pitch) * sin(current_pose_odom.yaw); offset_odom_z += diff_distance * sin(-current_pose_odom.pitch); offset_odom_roll += diff_odom_roll; offset_odom_pitch += diff_odom_pitch; offset_odom_yaw += diff_odom_yaw; guess_pose_odom.x = previous_pose.x + offset_odom_x; guess_pose_odom.y = previous_pose.y + offset_odom_y; guess_pose_odom.z = previous_pose.z + offset_odom_z; guess_pose_odom.roll = previous_pose.roll + offset_odom_roll; guess_pose_odom.pitch = previous_pose.pitch + offset_odom_pitch; guess_pose_odom.yaw = previous_pose.yaw + offset_odom_yaw; previous_time = current_time; } static void imu_calc(ros::Time current_time) { static ros::Time previous_time = current_time; double diff_time = (current_time - previous_time).toSec(); double diff_imu_roll = imu.angular_velocity.x * diff_time; double diff_imu_pitch = imu.angular_velocity.y * diff_time; double diff_imu_yaw = imu.angular_velocity.z * diff_time; current_pose_imu.roll += diff_imu_roll; current_pose_imu.pitch += diff_imu_pitch; current_pose_imu.yaw += diff_imu_yaw; double accX1 = imu.linear_acceleration.x; double accY1 = std::cos(current_pose_imu.roll) * imu.linear_acceleration.y - std::sin(current_pose_imu.roll) * imu.linear_acceleration.z; double accZ1 = std::sin(current_pose_imu.roll) * imu.linear_acceleration.y + std::cos(current_pose_imu.roll) * imu.linear_acceleration.z; double accX2 = std::sin(current_pose_imu.pitch) * accZ1 + std::cos(current_pose_imu.pitch) * accX1; double accY2 = accY1; double accZ2 = std::cos(current_pose_imu.pitch) * accZ1 - std::sin(current_pose_imu.pitch) * accX1; double accX = std::cos(current_pose_imu.yaw) * accX2 - std::sin(current_pose_imu.yaw) * accY2; double accY = std::sin(current_pose_imu.yaw) * accX2 + std::cos(current_pose_imu.yaw) * accY2; double accZ = accZ2; offset_imu_x += current_velocity_imu_x * diff_time + accX * diff_time * diff_time / 2.0; offset_imu_y += current_velocity_imu_y * diff_time + accY * diff_time * diff_time / 2.0; offset_imu_z += current_velocity_imu_z * diff_time + accZ * diff_time * diff_time / 2.0; current_velocity_imu_x += accX * diff_time; current_velocity_imu_y += accY * diff_time; current_velocity_imu_z += accZ * diff_time; offset_imu_roll += diff_imu_roll; offset_imu_pitch += diff_imu_pitch; offset_imu_yaw += diff_imu_yaw; guess_pose_imu.x = previous_pose.x + offset_imu_x; guess_pose_imu.y = previous_pose.y + offset_imu_y; guess_pose_imu.z = previous_pose.z + offset_imu_z; guess_pose_imu.roll = previous_pose.roll + offset_imu_roll; guess_pose_imu.pitch = previous_pose.pitch + offset_imu_pitch; guess_pose_imu.yaw = previous_pose.yaw + offset_imu_yaw; previous_time = current_time; } static double wrapToPm(double a_num, const double a_max) { if (a_num >= a_max) { a_num -= 2.0 * a_max; } return a_num; } static double wrapToPmPi(double a_angle_rad) { return wrapToPm(a_angle_rad, M_PI); } static double calcDiffForRadian(const double lhs_rad, const double rhs_rad) { double diff_rad = lhs_rad - rhs_rad; if (diff_rad >= M_PI) diff_rad = diff_rad - 2 * M_PI; else if (diff_rad < -M_PI) diff_rad = diff_rad + 2 * M_PI; return diff_rad; } static void odom_callback(const nav_msgs::Odometry::ConstPtr& input) { // std::cout << __func__ << std::endl; odom = *input; odom_calc(input->header.stamp); } static void imuUpsideDown(const sensor_msgs::Imu::Ptr input) { double input_roll, input_pitch, input_yaw; tf::Quaternion input_orientation; tf::quaternionMsgToTF(input->orientation, input_orientation); tf::Matrix3x3(input_orientation).getRPY(input_roll, input_pitch, input_yaw); input->angular_velocity.x *= -1; input->angular_velocity.y *= -1; input->angular_velocity.z *= -1; input->linear_acceleration.x *= -1; input->linear_acceleration.y *= -1; input->linear_acceleration.z *= -1; input_roll *= -1; input_pitch *= -1; input_yaw *= -1; input->orientation = tf::createQuaternionMsgFromRollPitchYaw(input_roll, input_pitch, input_yaw); } static void imu_callback(const sensor_msgs::Imu::Ptr& input) { // std::cout << __func__ << std::endl; if (_imu_upside_down) imuUpsideDown(input); const ros::Time current_time = input->header.stamp; static ros::Time previous_time = current_time; const double diff_time = (current_time - previous_time).toSec(); double imu_roll, imu_pitch, imu_yaw; tf::Quaternion imu_orientation; tf::quaternionMsgToTF(input->orientation, imu_orientation); tf::Matrix3x3(imu_orientation).getRPY(imu_roll, imu_pitch, imu_yaw); imu_roll = wrapToPmPi(imu_roll); imu_pitch = wrapToPmPi(imu_pitch); imu_yaw = wrapToPmPi(imu_yaw); static double previous_imu_roll = imu_roll, previous_imu_pitch = imu_pitch, previous_imu_yaw = imu_yaw; const double diff_imu_roll = calcDiffForRadian(imu_roll, previous_imu_roll); const double diff_imu_pitch = calcDiffForRadian(imu_pitch, previous_imu_pitch); const double diff_imu_yaw = calcDiffForRadian(imu_yaw, previous_imu_yaw); imu.header = input->header; imu.linear_acceleration.x = input->linear_acceleration.x; // imu.linear_acceleration.y = input->linear_acceleration.y; // imu.linear_acceleration.z = input->linear_acceleration.z; imu.linear_acceleration.y = 0; imu.linear_acceleration.z = 0; if (diff_time != 0) { imu.angular_velocity.x = diff_imu_roll / diff_time; imu.angular_velocity.y = diff_imu_pitch / diff_time; imu.angular_velocity.z = diff_imu_yaw / diff_time; } else { imu.angular_velocity.x = 0; imu.angular_velocity.y = 0; imu.angular_velocity.z = 0; } imu_calc(input->header.stamp); previous_time = current_time; previous_imu_roll = imu_roll; previous_imu_pitch = imu_pitch; previous_imu_yaw = imu_yaw; } static void points_callback(const sensor_msgs::PointCloud2::ConstPtr& input) { double r; pcl::PointXYZI p; pcl::PointCloud<pcl::PointXYZI> tmp, scan; pcl::PointCloud<pcl::PointXYZI>::Ptr filtered_scan_ptr(new pcl::PointCloud<pcl::PointXYZI>()); pcl::PointCloud<pcl::PointXYZI>::Ptr transformed_scan_ptr(new pcl::PointCloud<pcl::PointXYZI>()); tf::Quaternion q; Eigen::Matrix4f t_localizer(Eigen::Matrix4f::Identity()); Eigen::Matrix4f t_base_link(Eigen::Matrix4f::Identity()); static tf::TransformBroadcaster br; tf::Transform transform; current_scan_time = input->header.stamp; pcl::fromROSMsg(*input, tmp); for (pcl::PointCloud<pcl::PointXYZI>::const_iterator item = tmp.begin(); item != tmp.end(); item++) { p.x = (double)item->x; p.y = (double)item->y; p.z = (double)item->z; p.intensity = (double)item->intensity; r = sqrt(pow(p.x, 2.0) + pow(p.y, 2.0)); if (min_scan_range < r && r < max_scan_range) { scan.push_back(p); } } pcl::PointCloud<pcl::PointXYZI>::Ptr scan_ptr(new pcl::PointCloud<pcl::PointXYZI>(scan)); // Add initial point cloud to velodyne_map if (initial_scan_loaded == 0) { pcl::transformPointCloud(*scan_ptr, *transformed_scan_ptr, tf_btol); map += *transformed_scan_ptr; initial_scan_loaded = 1; } // Apply voxelgrid filter pcl::VoxelGrid<pcl::PointXYZI> voxel_grid_filter; voxel_grid_filter.setLeafSize(voxel_leaf_size, voxel_leaf_size, voxel_leaf_size); voxel_grid_filter.setInputCloud(scan_ptr); voxel_grid_filter.filter(*filtered_scan_ptr); pcl::PointCloud<pcl::PointXYZI>::Ptr map_ptr(new pcl::PointCloud<pcl::PointXYZI>(map)); if (_method_type == MethodType::PCL_GENERIC) { ndt.setTransformationEpsilon(trans_eps); ndt.setStepSize(step_size); ndt.setResolution(ndt_res); ndt.setMaximumIterations(max_iter); ndt.setInputSource(filtered_scan_ptr); } else if (_method_type == MethodType::PCL_ANH) { anh_ndt.setTransformationEpsilon(trans_eps); anh_ndt.setStepSize(step_size); anh_ndt.setResolution(ndt_res); anh_ndt.setMaximumIterations(max_iter); anh_ndt.setInputSource(filtered_scan_ptr); } #ifdef CUDA_FOUND else if (_method_type == MethodType::PCL_ANH_GPU) { anh_gpu_ndt.setTransformationEpsilon(trans_eps); anh_gpu_ndt.setStepSize(step_size); anh_gpu_ndt.setResolution(ndt_res); anh_gpu_ndt.setMaximumIterations(max_iter); anh_gpu_ndt.setInputSource(filtered_scan_ptr); } #endif #ifdef USE_PCL_OPENMP else if (_method_type == MethodType::PCL_OPENMP) { omp_ndt.setTransformationEpsilon(trans_eps); omp_ndt.setStepSize(step_size); omp_ndt.setResolution(ndt_res); omp_ndt.setMaximumIterations(max_iter); omp_ndt.setInputSource(filtered_scan_ptr); } #endif static bool is_first_map = true; if (is_first_map == true) { if (_method_type == MethodType::PCL_GENERIC) ndt.setInputTarget(map_ptr); else if (_method_type == MethodType::PCL_ANH) anh_ndt.setInputTarget(map_ptr); #ifdef CUDA_FOUND else if (_method_type == MethodType::PCL_ANH_GPU) anh_gpu_ndt.setInputTarget(map_ptr); #endif #ifdef USE_PCL_OPENMP else if (_method_type == MethodType::PCL_OPENMP) omp_ndt.setInputTarget(map_ptr); #endif is_first_map = false; } guess_pose.x = previous_pose.x + diff_x; guess_pose.y = previous_pose.y + diff_y; guess_pose.z = previous_pose.z + diff_z; guess_pose.roll = previous_pose.roll; guess_pose.pitch = previous_pose.pitch; guess_pose.yaw = previous_pose.yaw + diff_yaw; if (_use_imu == true && _use_odom == true) imu_odom_calc(current_scan_time); if (_use_imu == true && _use_odom == false) imu_calc(current_scan_time); if (_use_imu == false && _use_odom == true) odom_calc(current_scan_time); pose guess_pose_for_ndt; if (_use_imu == true && _use_odom == true) guess_pose_for_ndt = guess_pose_imu_odom; else if (_use_imu == true && _use_odom == false) guess_pose_for_ndt = guess_pose_imu; else if (_use_imu == false && _use_odom == true) guess_pose_for_ndt = guess_pose_odom; else guess_pose_for_ndt = guess_pose; Eigen::AngleAxisf init_rotation_x(guess_pose_for_ndt.roll, Eigen::Vector3f::UnitX()); Eigen::AngleAxisf init_rotation_y(guess_pose_for_ndt.pitch, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf init_rotation_z(guess_pose_for_ndt.yaw, Eigen::Vector3f::UnitZ()); Eigen::Translation3f init_translation(guess_pose_for_ndt.x, guess_pose_for_ndt.y, guess_pose_for_ndt.z); Eigen::Matrix4f init_guess = (init_translation * init_rotation_z * init_rotation_y * init_rotation_x).matrix() * tf_btol; t3_end = ros::Time::now(); d3 = t3_end - t3_start; t4_start = ros::Time::now(); pcl::PointCloud<pcl::PointXYZI>::Ptr output_cloud(new pcl::PointCloud<pcl::PointXYZI>); if (_method_type == MethodType::PCL_GENERIC) { ndt.align(*output_cloud, init_guess); fitness_score = ndt.getFitnessScore(); t_localizer = ndt.getFinalTransformation(); has_converged = ndt.hasConverged(); final_num_iteration = ndt.getFinalNumIteration(); transformation_probability = ndt.getTransformationProbability(); } else if (_method_type == MethodType::PCL_ANH) { anh_ndt.align(init_guess); fitness_score = anh_ndt.getFitnessScore(); t_localizer = anh_ndt.getFinalTransformation(); has_converged = anh_ndt.hasConverged(); final_num_iteration = anh_ndt.getFinalNumIteration(); } #ifdef CUDA_FOUND else if (_method_type == MethodType::PCL_ANH_GPU) { anh_gpu_ndt.align(init_guess); fitness_score = anh_gpu_ndt.getFitnessScore(); t_localizer = anh_gpu_ndt.getFinalTransformation(); has_converged = anh_gpu_ndt.hasConverged(); final_num_iteration = anh_gpu_ndt.getFinalNumIteration(); } #endif #ifdef USE_PCL_OPENMP else if (_method_type == MethodType::PCL_OPENMP) { omp_ndt.align(*output_cloud, init_guess); fitness_score = omp_ndt.getFitnessScore(); t_localizer = omp_ndt.getFinalTransformation(); has_converged = omp_ndt.hasConverged(); final_num_iteration = omp_ndt.getFinalNumIteration(); } #endif t_base_link = t_localizer * tf_ltob; pcl::transformPointCloud(*scan_ptr, *transformed_scan_ptr, t_localizer); tf::Matrix3x3 mat_l, mat_b; mat_l.setValue(static_cast<double>(t_localizer(0, 0)), static_cast<double>(t_localizer(0, 1)), static_cast<double>(t_localizer(0, 2)), static_cast<double>(t_localizer(1, 0)), static_cast<double>(t_localizer(1, 1)), static_cast<double>(t_localizer(1, 2)), static_cast<double>(t_localizer(2, 0)), static_cast<double>(t_localizer(2, 1)), static_cast<double>(t_localizer(2, 2))); mat_b.setValue(static_cast<double>(t_base_link(0, 0)), static_cast<double>(t_base_link(0, 1)), static_cast<double>(t_base_link(0, 2)), static_cast<double>(t_base_link(1, 0)), static_cast<double>(t_base_link(1, 1)), static_cast<double>(t_base_link(1, 2)), static_cast<double>(t_base_link(2, 0)), static_cast<double>(t_base_link(2, 1)), static_cast<double>(t_base_link(2, 2))); // Update localizer_pose. localizer_pose.x = t_localizer(0, 3); localizer_pose.y = t_localizer(1, 3); localizer_pose.z = t_localizer(2, 3); mat_l.getRPY(localizer_pose.roll, localizer_pose.pitch, localizer_pose.yaw, 1); // Update ndt_pose. ndt_pose.x = t_base_link(0, 3); ndt_pose.y = t_base_link(1, 3); ndt_pose.z = t_base_link(2, 3); mat_b.getRPY(ndt_pose.roll, ndt_pose.pitch, ndt_pose.yaw, 1); current_pose.x = ndt_pose.x; current_pose.y = ndt_pose.y; current_pose.z = ndt_pose.z; current_pose.roll = ndt_pose.roll; current_pose.pitch = ndt_pose.pitch; current_pose.yaw = ndt_pose.yaw; transform.setOrigin(tf::Vector3(current_pose.x, current_pose.y, current_pose.z)); q.setRPY(current_pose.roll, current_pose.pitch, current_pose.yaw); transform.setRotation(q); br.sendTransform(tf::StampedTransform(transform, current_scan_time, "map", "base_link")); scan_duration = current_scan_time - previous_scan_time; double secs = scan_duration.toSec(); // Calculate the offset (curren_pos - previous_pos) diff_x = current_pose.x - previous_pose.x; diff_y = current_pose.y - previous_pose.y; diff_z = current_pose.z - previous_pose.z; diff_yaw = calcDiffForRadian(current_pose.yaw, previous_pose.yaw); diff = sqrt(diff_x * diff_x + diff_y * diff_y + diff_z * diff_z); current_velocity_x = diff_x / secs; current_velocity_y = diff_y / secs; current_velocity_z = diff_z / secs; current_pose_imu.x = current_pose.x; current_pose_imu.y = current_pose.y; current_pose_imu.z = current_pose.z; current_pose_imu.roll = current_pose.roll; current_pose_imu.pitch = current_pose.pitch; current_pose_imu.yaw = current_pose.yaw; current_pose_odom.x = current_pose.x; current_pose_odom.y = current_pose.y; current_pose_odom.z = current_pose.z; current_pose_odom.roll = current_pose.roll; current_pose_odom.pitch = current_pose.pitch; current_pose_odom.yaw = current_pose.yaw; current_pose_imu_odom.x = current_pose.x; current_pose_imu_odom.y = current_pose.y; current_pose_imu_odom.z = current_pose.z; current_pose_imu_odom.roll = current_pose.roll; current_pose_imu_odom.pitch = current_pose.pitch; current_pose_imu_odom.yaw = current_pose.yaw; current_velocity_imu_x = current_velocity_x; current_velocity_imu_y = current_velocity_y; current_velocity_imu_z = current_velocity_z; // Update position and posture. current_pos -> previous_pos previous_pose.x = current_pose.x; previous_pose.y = current_pose.y; previous_pose.z = current_pose.z; previous_pose.roll = current_pose.roll; previous_pose.pitch = current_pose.pitch; previous_pose.yaw = current_pose.yaw; previous_scan_time.sec = current_scan_time.sec; previous_scan_time.nsec = current_scan_time.nsec; offset_imu_x = 0.0; offset_imu_y = 0.0; offset_imu_z = 0.0; offset_imu_roll = 0.0; offset_imu_pitch = 0.0; offset_imu_yaw = 0.0; offset_odom_x = 0.0; offset_odom_y = 0.0; offset_odom_z = 0.0; offset_odom_roll = 0.0; offset_odom_pitch = 0.0; offset_odom_yaw = 0.0; offset_imu_odom_x = 0.0; offset_imu_odom_y = 0.0; offset_imu_odom_z = 0.0; offset_imu_odom_roll = 0.0; offset_imu_odom_pitch = 0.0; offset_imu_odom_yaw = 0.0; // Calculate the shift between added_pos and current_pos double shift = sqrt(pow(current_pose.x - added_pose.x, 2.0) + pow(current_pose.y - added_pose.y, 2.0)); if (shift >= min_add_scan_shift) { map += *transformed_scan_ptr; added_pose.x = current_pose.x; added_pose.y = current_pose.y; added_pose.z = current_pose.z; added_pose.roll = current_pose.roll; added_pose.pitch = current_pose.pitch; added_pose.yaw = current_pose.yaw; if (_method_type == MethodType::PCL_GENERIC) ndt.setInputTarget(map_ptr); else if (_method_type == MethodType::PCL_ANH) { if (_incremental_voxel_update == true) anh_ndt.updateVoxelGrid(transformed_scan_ptr); else anh_ndt.setInputTarget(map_ptr); } #ifdef CUDA_FOUND else if (_method_type == MethodType::PCL_ANH_GPU) anh_gpu_ndt.setInputTarget(map_ptr); #endif #ifdef USE_PCL_OPENMP else if (_method_type == MethodType::PCL_OPENMP) omp_ndt.setInputTarget(map_ptr); #endif } sensor_msgs::PointCloud2::Ptr map_msg_ptr(new sensor_msgs::PointCloud2); pcl::toROSMsg(*map_ptr, *map_msg_ptr); ndt_map_pub.publish(*map_msg_ptr); q.setRPY(current_pose.roll, current_pose.pitch, current_pose.yaw); current_pose_msg.header.frame_id = "map"; current_pose_msg.header.stamp = current_scan_time; current_pose_msg.pose.position.x = current_pose.x; current_pose_msg.pose.position.y = current_pose.y; current_pose_msg.pose.position.z = current_pose.z; current_pose_msg.pose.orientation.x = q.x(); current_pose_msg.pose.orientation.y = q.y(); current_pose_msg.pose.orientation.z = q.z(); current_pose_msg.pose.orientation.w = q.w(); current_pose_pub.publish(current_pose_msg); // Write log if (!ofs) { std::cerr << "Could not open " << filename << "." << std::endl; exit(1); } ofs << input->header.seq << "," << input->header.stamp << "," << input->header.frame_id << "," << scan_ptr->size() << "," << filtered_scan_ptr->size() << "," << std::fixed << std::setprecision(5) << current_pose.x << "," << std::fixed << std::setprecision(5) << current_pose.y << "," << std::fixed << std::setprecision(5) << current_pose.z << "," << current_pose.roll << "," << current_pose.pitch << "," << current_pose.yaw << "," << final_num_iteration << "," << fitness_score << "," << ndt_res << "," << step_size << "," << trans_eps << "," << max_iter << "," << voxel_leaf_size << "," << min_scan_range << "," << max_scan_range << "," << min_add_scan_shift << std::endl; std::cout << "-----------------------------------------------------------------" << std::endl; std::cout << "Sequence number: " << input->header.seq << std::endl; std::cout << "Number of scan points: " << scan_ptr->size() << " points." << std::endl; std::cout << "Number of filtered scan points: " << filtered_scan_ptr->size() << " points." << std::endl; std::cout << "transformed_scan_ptr: " << transformed_scan_ptr->points.size() << " points." << std::endl; std::cout << "map: " << map.points.size() << " points." << std::endl; std::cout << "NDT has converged: " << has_converged << std::endl; std::cout << "Fitness score: " << fitness_score << std::endl; std::cout << "Number of iteration: " << final_num_iteration << std::endl; std::cout << "(x,y,z,roll,pitch,yaw):" << std::endl; std::cout << "(" << current_pose.x << ", " << current_pose.y << ", " << current_pose.z << ", " << current_pose.roll << ", " << current_pose.pitch << ", " << current_pose.yaw << ")" << std::endl; std::cout << "Transformation Matrix:" << std::endl; std::cout << t_localizer << std::endl; std::cout << "shift: " << shift << std::endl; std::cout << "-----------------------------------------------------------------" << std::endl; } int main(int argc, char** argv) { previous_pose.x = 0.0; previous_pose.y = 0.0; previous_pose.z = 0.0; previous_pose.roll = 0.0; previous_pose.pitch = 0.0; previous_pose.yaw = 0.0; ndt_pose.x = 0.0; ndt_pose.y = 0.0; ndt_pose.z = 0.0; ndt_pose.roll = 0.0; ndt_pose.pitch = 0.0; ndt_pose.yaw = 0.0; current_pose.x = 0.0; current_pose.y = 0.0; current_pose.z = 0.0; current_pose.roll = 0.0; current_pose.pitch = 0.0; current_pose.yaw = 0.0; current_pose_imu.x = 0.0; current_pose_imu.y = 0.0; current_pose_imu.z = 0.0; current_pose_imu.roll = 0.0; current_pose_imu.pitch = 0.0; current_pose_imu.yaw = 0.0; guess_pose.x = 0.0; guess_pose.y = 0.0; guess_pose.z = 0.0; guess_pose.roll = 0.0; guess_pose.pitch = 0.0; guess_pose.yaw = 0.0; added_pose.x = 0.0; added_pose.y = 0.0; added_pose.z = 0.0; added_pose.roll = 0.0; added_pose.pitch = 0.0; added_pose.yaw = 0.0; diff_x = 0.0; diff_y = 0.0; diff_z = 0.0; diff_yaw = 0.0; offset_imu_x = 0.0; offset_imu_y = 0.0; offset_imu_z = 0.0; offset_imu_roll = 0.0; offset_imu_pitch = 0.0; offset_imu_yaw = 0.0; offset_odom_x = 0.0; offset_odom_y = 0.0; offset_odom_z = 0.0; offset_odom_roll = 0.0; offset_odom_pitch = 0.0; offset_odom_yaw = 0.0; offset_imu_odom_x = 0.0; offset_imu_odom_y = 0.0; offset_imu_odom_z = 0.0; offset_imu_odom_roll = 0.0; offset_imu_odom_pitch = 0.0; offset_imu_odom_yaw = 0.0; ros::init(argc, argv, "ndt_mapping"); ros::NodeHandle nh; ros::NodeHandle private_nh("~"); // Set log file name. char buffer[80]; std::time_t now = std::time(NULL); std::tm* pnow = std::localtime(&now); std::strftime(buffer, 80, "%Y%m%d_%H%M%S", pnow); filename = "ndt_mapping_" + std::string(buffer) + ".csv"; ofs.open(filename.c_str(), std::ios::app); // write header for log file if (!ofs) { std::cerr << "Could not open " << filename << "." << std::endl; exit(1); } ofs << "input->header.seq" << "," << "input->header.stamp" << "," << "input->header.frame_id" << "," << "scan_ptr->size()" << "," << "filtered_scan_ptr->size()" << "," << "current_pose.x" << "," << "current_pose.y" << "," << "current_pose.z" << "," << "current_pose.roll" << "," << "current_pose.pitch" << "," << "current_pose.yaw" << "," << "final_num_iteration" << "," << "fitness_score" << "," << "ndt_res" << "," << "step_size" << "," << "trans_eps" << "," << "max_iter" << "," << "voxel_leaf_size" << "," << "min_scan_range" << "," << "max_scan_range" << "," << "min_add_scan_shift" << std::endl; // setting parameters int method_type_tmp = 0; private_nh.getParam("method_type", method_type_tmp); _method_type = static_cast<MethodType>(method_type_tmp); private_nh.getParam("imu_upside_down", _imu_upside_down); private_nh.getParam("imu_topic", _imu_topic); private_nh.getParam("incremental_voxel_update", _incremental_voxel_update); std::cout << "method_type: " << static_cast<int>(_method_type) << std::endl; std::cout << "use_odom: " << _use_odom << std::endl; std::cout << "use_imu: " << _use_imu << std::endl; std::cout << "imu_upside_down: " << _imu_upside_down << std::endl; std::cout << "imu_topic: " << _imu_topic << std::endl; std::cout << "incremental_voxel_update: " << _incremental_voxel_update << std::endl; if (nh.getParam("tf_x", _tf_x) == false) { std::cout << "tf_x is not set." << std::endl; return 1; } if (nh.getParam("tf_y", _tf_y) == false) { std::cout << "tf_y is not set." << std::endl; return 1; } if (nh.getParam("tf_z", _tf_z) == false) { std::cout << "tf_z is not set." << std::endl; return 1; } if (nh.getParam("tf_roll", _tf_roll) == false) { std::cout << "tf_roll is not set." << std::endl; return 1; } if (nh.getParam("tf_pitch", _tf_pitch) == false) { std::cout << "tf_pitch is not set." << std::endl; return 1; } if (nh.getParam("tf_yaw", _tf_yaw) == false) { std::cout << "tf_yaw is not set." << std::endl; return 1; } std::cout << "(tf_x,tf_y,tf_z,tf_roll,tf_pitch,tf_yaw): (" << _tf_x << ", " << _tf_y << ", " << _tf_z << ", " << _tf_roll << ", " << _tf_pitch << ", " << _tf_yaw << ")" << std::endl; #ifndef CUDA_FOUND if (_method_type == MethodType::PCL_ANH_GPU) { std::cerr << "**************************************************************" << std::endl; std::cerr << "[ERROR]PCL_ANH_GPU is not built. Please use other method type." << std::endl; std::cerr << "**************************************************************" << std::endl; exit(1); } #endif #ifndef USE_PCL_OPENMP if (_method_type == MethodType::PCL_OPENMP) { std::cerr << "**************************************************************" << std::endl; std::cerr << "[ERROR]PCL_OPENMP is not built. Please use other method type." << std::endl; std::cerr << "**************************************************************" << std::endl; exit(1); } #endif Eigen::Translation3f tl_btol(_tf_x, _tf_y, _tf_z); // tl: translation Eigen::AngleAxisf rot_x_btol(_tf_roll, Eigen::Vector3f::UnitX()); // rot: rotation Eigen::AngleAxisf rot_y_btol(_tf_pitch, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf rot_z_btol(_tf_yaw, Eigen::Vector3f::UnitZ()); tf_btol = (tl_btol * rot_z_btol * rot_y_btol * rot_x_btol).matrix(); Eigen::Translation3f tl_ltob((-1.0) * _tf_x, (-1.0) * _tf_y, (-1.0) * _tf_z); // tl: translation Eigen::AngleAxisf rot_x_ltob((-1.0) * _tf_roll, Eigen::Vector3f::UnitX()); // rot: rotation Eigen::AngleAxisf rot_y_ltob((-1.0) * _tf_pitch, Eigen::Vector3f::UnitY()); Eigen::AngleAxisf rot_z_ltob((-1.0) * _tf_yaw, Eigen::Vector3f::UnitZ()); tf_ltob = (tl_ltob * rot_z_ltob * rot_y_ltob * rot_x_ltob).matrix(); map.header.frame_id = "map"; ndt_map_pub = nh.advertise<sensor_msgs::PointCloud2>("/ndt_map", 1000); current_pose_pub = nh.advertise<geometry_msgs::PoseStamped>("/current_pose", 1000); ros::Subscriber param_sub = nh.subscribe("config/ndt_mapping", 10, param_callback); ros::Subscriber output_sub = nh.subscribe("config/ndt_mapping_output", 10, output_callback); ros::Subscriber points_sub = nh.subscribe("points_raw", 100000, points_callback); ros::Subscriber odom_sub = nh.subscribe("/vehicle/odom", 100000, odom_callback); ros::Subscriber imu_sub = nh.subscribe(_imu_topic, 100000, imu_callback); ros::spin(); return 0; }
// Copyright (c) 2011-2020 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 <util/settings.h> #include <test/util/setup_common.h> #include <test/util/str.h> #include <boost/test/unit_test.hpp> #include <univalue.h> #include <util/strencodings.h> #include <util/string.h> #include <util/system.h> #include <vector> inline bool operator==(const util::SettingsValue& a, const util::SettingsValue& b) { return a.write() == b.write(); } inline std::ostream& operator<<(std::ostream& os, const util::SettingsValue& value) { os << value.write(); return os; } inline std::ostream& operator<<(std::ostream& os, const std::pair<std::string, util::SettingsValue>& kv) { util::SettingsValue out(util::SettingsValue::VOBJ); out.__pushKV(kv.first, kv.second); os << out.write(); return os; } inline void WriteText(const fs::path& path, const std::string& text) { fsbridge::ofstream file; file.open(path); file << text; } BOOST_FIXTURE_TEST_SUITE(settings_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(ReadWrite) { fs::path path = GetDataDir() / "settings.json"; WriteText(path, R"({ "string": "string", "num": 5, "bool": true, "null": null })"); std::map<std::string, util::SettingsValue> expected{ {"string", "string"}, {"num", 5}, {"bool", true}, {"null", {}}, }; // Check file read. std::map<std::string, util::SettingsValue> values; std::vector<std::string> errors; BOOST_CHECK(util::ReadSettings(path, values, errors)); BOOST_CHECK_EQUAL_COLLECTIONS(values.begin(), values.end(), expected.begin(), expected.end()); BOOST_CHECK(errors.empty()); // Check no errors if file doesn't exist. fs::remove(path); BOOST_CHECK(util::ReadSettings(path, values, errors)); BOOST_CHECK(values.empty()); BOOST_CHECK(errors.empty()); // Check duplicate keys not allowed WriteText(path, R"({ "dupe": "string", "dupe": "dupe" })"); BOOST_CHECK(!util::ReadSettings(path, values, errors)); std::vector<std::string> dup_keys = {strprintf("Found duplicate key dupe in settings file %s", path.string())}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), dup_keys.begin(), dup_keys.end()); // Check non-kv json files not allowed WriteText(path, R"("non-kv")"); BOOST_CHECK(!util::ReadSettings(path, values, errors)); std::vector<std::string> non_kv = {strprintf("Found non-object value \"non-kv\" in settings file %s", path.string())}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), non_kv.begin(), non_kv.end()); // Check invalid json not allowed WriteText(path, R"(invalid json)"); BOOST_CHECK(!util::ReadSettings(path, values, errors)); std::vector<std::string> fail_parse = {strprintf("Unable to parse settings file %s", path.string())}; BOOST_CHECK_EQUAL_COLLECTIONS(errors.begin(), errors.end(), fail_parse.begin(), fail_parse.end()); } //! Check settings struct contents against expected json strings. static void CheckValues(const util::Settings& settings, const std::string& single_val, const std::string& list_val) { util::SettingsValue single_value = GetSetting(settings, "section", "name", false, false); util::SettingsValue list_value(util::SettingsValue::VARR); for (const auto& item : GetSettingsList(settings, "section", "name", false)) { list_value.push_back(item); } BOOST_CHECK_EQUAL(single_value.write().c_str(), single_val); BOOST_CHECK_EQUAL(list_value.write().c_str(), list_val); }; // Simple settings merge test case. BOOST_AUTO_TEST_CASE(Simple) { util::Settings settings; settings.command_line_options["name"].push_back("val1"); settings.command_line_options["name"].push_back("val2"); settings.ro_config["section"]["name"].push_back(2); // The last given arg takes precedence when specified via commandline. CheckValues(settings, R"("val2")", R"(["val1","val2",2])"); util::Settings settings2; settings2.ro_config["section"]["name"].push_back("val2"); settings2.ro_config["section"]["name"].push_back("val3"); // The first given arg takes precedence when specified via config file. CheckValues(settings2, R"("val2")", R"(["val2","val3"])"); } // Confirm that a high priority setting overrides a lower priority setting even // if the high priority setting is null. This behavior is useful for a high // priority setting source to be able to effectively reset any setting back to // its default value. BOOST_AUTO_TEST_CASE(NullOverride) { util::Settings settings; settings.command_line_options["name"].push_back("value"); BOOST_CHECK_EQUAL(R"("value")", GetSetting(settings, "section", "name", false, false).write().c_str()); settings.forced_settings["name"] = {}; BOOST_CHECK_EQUAL(R"(null)", GetSetting(settings, "section", "name", false, false).write().c_str()); } // Test different ways settings can be merged, and verify results. This test can // be used to confirm that updates to settings code don't change behavior // unintentionally. struct MergeTestingSetup : public BasicTestingSetup { //! Max number of actions to sequence together. Can decrease this when //! debugging to make test results easier to understand. static constexpr int MAX_ACTIONS = 3; enum Action { END, SET, NEGATE, SECTION_SET, SECTION_NEGATE }; using ActionList = Action[MAX_ACTIONS]; //! Enumerate all possible test configurations. template <typename Fn> void ForEachMergeSetup(Fn&& fn) { ActionList arg_actions = {}; // command_line_options do not have sections. Only iterate over SET and NEGATE ForEachNoDup(arg_actions, SET, NEGATE, [&]{ ActionList conf_actions = {}; ForEachNoDup(conf_actions, SET, SECTION_NEGATE, [&]{ for (bool force_set : {false, true}) { for (bool ignore_default_section_config : {false, true}) { fn(arg_actions, conf_actions, force_set, ignore_default_section_config); } } }); }); } }; // Regression test covering different ways config settings can be merged. The // test parses and merges settings, representing the results as strings that get // compared against an expected hash. To debug, the result strings can be dumped // to a file (see comments below). BOOST_FIXTURE_TEST_CASE(Merge, MergeTestingSetup) { CHash256 out_sha; FILE* out_file = nullptr; if (const char* out_path = getenv("SETTINGS_MERGE_TEST_OUT")) { out_file = fsbridge::fopen(out_path, "w"); if (!out_file) throw std::system_error(errno, std::generic_category(), "fopen failed"); } const std::string& network = CBaseChainParams::MAIN; ForEachMergeSetup([&](const ActionList& arg_actions, const ActionList& conf_actions, bool force_set, bool ignore_default_section_config) { std::string desc; int value_suffix = 0; util::Settings settings; const std::string& name = ignore_default_section_config ? "wallet" : "server"; auto push_values = [&](Action action, const char* value_prefix, const std::string& name_prefix, std::vector<util::SettingsValue>& dest) { if (action == SET || action == SECTION_SET) { for (int i = 0; i < 2; ++i) { dest.push_back(value_prefix + ToString(++value_suffix)); desc += " " + name_prefix + name + "=" + dest.back().get_str(); } } else if (action == NEGATE || action == SECTION_NEGATE) { dest.push_back(false); desc += " " + name_prefix + "no" + name; } }; if (force_set) { settings.forced_settings[name] = "forced"; desc += " " + name + "=forced"; } for (Action arg_action : arg_actions) { push_values(arg_action, "a", "-", settings.command_line_options[name]); } for (Action conf_action : conf_actions) { bool use_section = conf_action == SECTION_SET || conf_action == SECTION_NEGATE; push_values(conf_action, "c", use_section ? network + "." : "", settings.ro_config[use_section ? network : ""][name]); } desc += " || "; desc += GetSetting(settings, network, name, ignore_default_section_config, /* get_chain_name= */ false).write(); desc += " |"; for (const auto& s : GetSettingsList(settings, network, name, ignore_default_section_config)) { desc += " "; desc += s.write(); } desc += " |"; if (OnlyHasDefaultSectionSetting(settings, network, name)) desc += " ignored"; desc += "\n"; out_sha.Write(MakeUCharSpan(desc)); if (out_file) { BOOST_REQUIRE(fwrite(desc.data(), 1, desc.size(), out_file) == desc.size()); } }); if (out_file) { if (fclose(out_file)) throw std::system_error(errno, std::generic_category(), "fclose failed"); out_file = nullptr; } unsigned char out_sha_bytes[CSHA256::OUTPUT_SIZE]; out_sha.Finalize(out_sha_bytes); std::string out_sha_hex = HexStr(out_sha_bytes); // If check below fails, should manually dump the results with: // // SETTINGS_MERGE_TEST_OUT=results.txt ./test_agrocoin --run_test=settings_tests/Merge // // And verify diff against previous results to make sure the changes are expected. // // Results file is formatted like: // // <input> || GetSetting() | GetSettingsList() | OnlyHasDefaultSectionSetting() BOOST_CHECK_EQUAL(out_sha_hex, "79db02d74e3e193196541b67c068b40ebd0c124a24b3ecbe9cbf7e85b1c4ba7a"); } BOOST_AUTO_TEST_SUITE_END()
/* * 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/kinesis/model/EncryptionType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace Kinesis { namespace Model { namespace EncryptionTypeMapper { static const int NONE_HASH = HashingUtils::HashString("NONE"); static const int KMS_HASH = HashingUtils::HashString("KMS"); EncryptionType GetEncryptionTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == NONE_HASH) { return EncryptionType::NONE; } else if (hashCode == KMS_HASH) { return EncryptionType::KMS; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<EncryptionType>(hashCode); } return EncryptionType::NOT_SET; } Aws::String GetNameForEncryptionType(EncryptionType enumValue) { switch(enumValue) { case EncryptionType::NONE: return "NONE"; case EncryptionType::KMS: return "KMS"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace EncryptionTypeMapper } // namespace Model } // namespace Kinesis } // namespace Aws
// (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_FILE_HPP_INCLUDED #define BOOST_IOSTREAMS_FILE_HPP_INCLUDED #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/iostreams/detail/config/wide_streams.hpp> #ifndef BOOST_IOSTREAMS_NO_LOCALE # include <locale> #endif #include <string> // pathnames, char_traits. #include <boost/iostreams/categories.hpp> #include <boost/iostreams/detail/ios.hpp> // openmode, seekdir, int types. #include <boost/iostreams/detail/fstream.hpp> #include <boost/iostreams/operations.hpp> // seek. #include <boost/shared_ptr.hpp> // Must come last. #include <boost/iostreams/detail/config/disable_warnings.hpp> // MSVC. namespace boost { namespace iostreams { template<typename Ch> class basic_file { public: typedef Ch char_type; struct category : public seekable_device_tag, public closable_tag, public localizable_tag, public flushable_tag { }; basic_file( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::in | BOOST_IOS::out, BOOST_IOS::openmode base_mode = BOOST_IOS::in | BOOST_IOS::out ); std::streamsize read(char_type* s, std::streamsize n); bool putback(char_type c); std::streamsize write(const char_type* s, std::streamsize n); std::streampos seek( stream_offset off, BOOST_IOS::seekdir way, BOOST_IOS::openmode which = BOOST_IOS::in | BOOST_IOS::out ); void open( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::in | BOOST_IOS::out, BOOST_IOS::openmode base_mode = BOOST_IOS::in | BOOST_IOS::out ); bool is_open() const; void close(); bool flush(); #ifndef BOOST_IOSTREAMS_NO_LOCALE void imbue(const std::locale& loc) { pimpl_->file_.pubimbue(loc); } #endif private: struct impl { impl(const std::string& path, BOOST_IOS::openmode mode) { file_.open(path.c_str(), mode); } ~impl() { if (file_.is_open()) file_.close(); } BOOST_IOSTREAMS_BASIC_FILEBUF(Ch) file_; }; shared_ptr<impl> pimpl_; }; typedef basic_file<char> file; typedef basic_file<wchar_t> wfile; template<typename Ch> struct basic_file_source : private basic_file<Ch> { typedef Ch char_type; struct category : input_seekable, device_tag, closable_tag { }; using basic_file<Ch>::read; using basic_file<Ch>::putback; using basic_file<Ch>::seek; using basic_file<Ch>::is_open; using basic_file<Ch>::close; basic_file_source( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::in ) : basic_file<Ch>(path, mode & ~BOOST_IOS::out, BOOST_IOS::in) { } void open( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::in ) { basic_file<Ch>::open(path, mode & ~BOOST_IOS::out, BOOST_IOS::in); } }; typedef basic_file_source<char> file_source; typedef basic_file_source<wchar_t> wfile_source; template<typename Ch> struct basic_file_sink : private basic_file<Ch> { typedef Ch char_type; struct category : output_seekable, device_tag, closable_tag, flushable_tag { }; using basic_file<Ch>::write; using basic_file<Ch>::seek; using basic_file<Ch>::is_open; using basic_file<Ch>::close; using basic_file<Ch>::flush; basic_file_sink( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::out ) : basic_file<Ch>(path, mode & ~BOOST_IOS::in, BOOST_IOS::out) { } void open( const std::string& path, BOOST_IOS::openmode mode = BOOST_IOS::out ) { basic_file<Ch>::open(path, mode & ~BOOST_IOS::in, BOOST_IOS::out); } }; typedef basic_file_sink<char> file_sink; typedef basic_file_sink<wchar_t> wfile_sink; //------------------Implementation of basic_file------------------------------// template<typename Ch> basic_file<Ch>::basic_file ( const std::string& path, BOOST_IOS::openmode mode, BOOST_IOS::openmode base_mode ) { open(path, mode, base_mode); } template<typename Ch> inline std::streamsize basic_file<Ch>::read (char_type* s, std::streamsize n) { std::streamsize result = pimpl_->file_.sgetn(s, n); return result != 0 ? result : -1; } template<typename Ch> inline bool basic_file<Ch>::putback(char_type c) { return !!pimpl_->file_.sputbackc(c); } template<typename Ch> inline std::streamsize basic_file<Ch>::write (const char_type* s, std::streamsize n) { return pimpl_->file_.sputn(s, n); } template<typename Ch> std::streampos basic_file<Ch>::seek ( stream_offset off, BOOST_IOS::seekdir way, BOOST_IOS::openmode ) { return iostreams::seek(pimpl_->file_, off, way); } template<typename Ch> void basic_file<Ch>::open ( const std::string& path, BOOST_IOS::openmode mode, BOOST_IOS::openmode base_mode ) { pimpl_.reset(new impl(path, mode | base_mode)); } template<typename Ch> bool basic_file<Ch>::is_open() const { return pimpl_->file_.is_open(); } template<typename Ch> void basic_file<Ch>::close() { pimpl_->file_.close(); } template<typename Ch> bool basic_file<Ch>::flush() { return pimpl_->file_.BOOST_IOSTREAMS_PUBSYNC() == 0; } //----------------------------------------------------------------------------// } } // End namespaces iostreams, boost. #include <boost/iostreams/detail/config/enable_warnings.hpp> // MSVC #endif // #ifndef BOOST_IOSTREAMS_FILE_HPP_INCLUDED
/* * QuickStartPluginApi.hpp * * Copyright (C) 2019-20 by RStudio, PBC * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #ifndef LAUNCHER_PLUGINS_QUICK_START_PLUGIN_API_HPP #define LAUNCHER_PLUGINS_QUICK_START_PLUGIN_API_HPP #include <api/AbstractPluginApi.hpp> namespace rstudio { namespace launcher_plugins { namespace quickstart { /** * @brief Launcher Plugin API for the QuickStart Plugin. */ class QuickStartPluginApi : public api::AbstractPluginApi { public: /** * @brief Constructor. * * @param in_launcherCommunicator The communicator to use for sending and receiving messages from the RStudio * Launcher. */ explicit QuickStartPluginApi(std::shared_ptr<comms::AbstractLauncherCommunicator> in_launcherCommunicator); private: /** * @brief Creates the job repository which stores any RStudio Launcher jobs currently in the job scheduling system. * * @param in_jobStatusNotifier The job status notifier, which is used by the AbstractJobRepository to keep * track of new jobs. * * @return The job repository. */ jobs::JobRepositoryPtr createJobRepository( const jobs::JobStatusNotifierPtr& in_jobStatusNotifier) const override; /** * @brief Creates the job source which can communicate with this Plugin's job scheduling system. * * @param in_jobRepository The job repository, from which to look up jobs. * @param in_jobStatusNotifier The job status notifier to which to post or from which to receive job status * updates. * * @return The job source for this Plugin implementation. */ std::shared_ptr<api::IJobSource> createJobSource( jobs::JobRepositoryPtr in_jobRepository, jobs::JobStatusNotifierPtr in_jobStatusNotifier) const override; /** * @brief This method is responsible for initializing all components necessary to communicate with the job launching * system supported by this Plugin, such as initializing the communication method (e.g. a TCP socket). * * @return Success if all components of the Plugin API could be initialized; Error otherwise. */ Error doInitialize() override; }; } // namespace quickstart } // namespace launcher_plugins } // namespace rstudio #endif
/** * Copyright 2020 Huawei Technologies Co., Ltd * * 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 "c_ops/logical_not.h" namespace mindspore { REGISTER_PRIMITIVE_C(kNameLogicalNot, LogicalNot); } // namespace mindspore
// Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "key.h" #include "eckey.h" int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) { while (c1len > c2len) { if (*c1) return 1; c1++; c1len--; }; while (c2len > c1len) { if (*c2) return -1; c2++; c2len--; }; while (c1len > 0) { if (*c1 > *c2) return 1; if (*c2 > *c1) return -1; c1++; c2++; c1len--; }; return 0; } // Order of secp256k1's generator minus 1. const unsigned char vchMaxModOrder[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 }; // Half of the order of secp256k1's generator minus 1. const unsigned char vchMaxModHalfOrder[32] = { 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D, 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0 }; const unsigned char vchZero[0] = {}; bool CKey::Check(const unsigned char *vch) { // Do not convert to OpenSSL's data structures for range-checking keys, // it's easy enough to do directly. static const unsigned char vchMax[32] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 }; bool fIsZero = true; for (int i=0; i<32 && fIsZero; i++) if (vch[i] != 0) fIsZero = false; if (fIsZero) return false; for (int i=0; i<32; i++) { if (vch[i] < vchMax[i]) return true; if (vch[i] > vchMax[i]) return false; } return true; } bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) { return CompareBigEndian(vch, len, vchZero, 0) > 0 && CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0; } bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig) { unsigned char *pos; if (vchSig.empty()) return false; pos = &vchSig[0]; ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size()); if (sig == NULL) return false; bool ret = false; int nSize = i2d_ECDSA_SIG(sig, NULL); if (nSize > 0) { vchSig.resize(nSize); // grow or shrink as needed pos = &vchSig[0]; i2d_ECDSA_SIG(sig, &pos); ret = true; } ECDSA_SIG_free(sig); return ret; } void CKey::MakeNewKey(bool fCompressedIn) { do { RAND_bytes(vch, sizeof(vch)); } while (!Check(vch)); fValid = true; fCompressed = fCompressedIn; } bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) { CECKey key; if (!key.SetPrivKey(privkey)) return false; key.GetSecretBytes(vch); fCompressed = fCompressedIn; fValid = true; return true; } CPrivKey CKey::GetPrivKey() const { assert(fValid); CECKey key; key.SetSecretBytes(vch); CPrivKey privkey; key.GetPrivKey(privkey, fCompressed); return privkey; } CPubKey CKey::GetPubKey() const { assert(fValid); CECKey key; key.SetSecretBytes(vch); CPubKey pubkey; key.GetPubKey(pubkey, fCompressed); return pubkey; } CPubKey CKey::GetPubKey(bool fForceCompressed) const { assert(fValid); CECKey key; key.SetSecretBytes(vch); CPubKey pubkey; key.GetPubKey(pubkey, fForceCompressed); return pubkey; } bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const { if (!fValid) return false; CECKey key; key.SetSecretBytes(vch); return key.Sign(hash, vchSig); } bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const { if (!fValid) return false; CECKey key; key.SetSecretBytes(vch); vchSig.resize(65); int rec = -1; if (!key.SignCompact(hash, &vchSig[1], rec)) return false; assert(rec != -1); vchSig[0] = 27 + rec + (fCompressed ? 4 : 0); return true; } bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) { CECKey key; if (!key.SetPrivKey(privkey, fSkipCheck)) return false; key.GetSecretBytes(vch); fCompressed = vchPubKey.IsCompressed(); fValid = true; if (fSkipCheck) return true; if (GetPubKey() != vchPubKey) return false; return true; } bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const { if (!IsValid()) return false; CECKey key; if (!key.SetPubKey(*this)) return false; if (!key.Verify(hash, vchSig)) return false; return true; } bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) { if (vchSig.size() != 65) return false; CECKey key; if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4)) return false; key.GetPubKey(*this, (vchSig[0] - 27) & 4); return true; } bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const { if (!IsValid()) return false; if (vchSig.size() != 65) return false; CECKey key; if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4)) return false; CPubKey pubkeyRec; key.GetPubKey(pubkeyRec, IsCompressed()); if (*this != pubkeyRec) return false; return true; } bool CPubKey::IsFullyValid() const { if (!IsValid()) return false; CECKey key; if (!key.SetPubKey(*this)) return false; return true; } bool CPubKey::Decompress() { if (!IsValid()) return false; CECKey key; if (!key.SetPubKey(*this)) return false; key.GetPubKey(*this, false); return true; } void static BIP32Hash(const unsigned char chainCode[32], unsigned int nChild, unsigned char header, const unsigned char data[32], unsigned char output[64]) { unsigned char num[4]; num[0] = (nChild >> 24) & 0xFF; num[1] = (nChild >> 16) & 0xFF; num[2] = (nChild >> 8) & 0xFF; num[3] = (nChild >> 0) & 0xFF; HMAC_SHA512_CTX ctx; HMAC_SHA512_Init(&ctx, chainCode, 32); HMAC_SHA512_Update(&ctx, &header, 1); HMAC_SHA512_Update(&ctx, data, 32); HMAC_SHA512_Update(&ctx, num, 4); HMAC_SHA512_Final(output, &ctx); } bool CKey::Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const { assert(IsValid()); assert(IsCompressed()); unsigned char out[64]; LockObject(out); if ((nChild >> 31) == 0) { CPubKey pubkey = GetPubKey(); assert(pubkey.begin() + 33 == pubkey.end()); BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, out); } else { assert(begin() + 32 == end()); BIP32Hash(cc, nChild, 0, begin(), out); }; memcpy(ccChild, out+32, 32); bool ret = TweakSecret((unsigned char*)keyChild.begin(), begin(), out); UnlockObject(out); keyChild.fCompressed = true; keyChild.fValid = ret; return ret; } bool CKey::VerifyPubKey(const CPubKey& pubkey) const { if (pubkey.IsCompressed() != fCompressed) { return false; } unsigned char rnd[8]; std::string str = "Bitcoin key verification\n"; RAND_bytes(rnd, sizeof(rnd)); uint256 hash = CHashWriter(SER_GETHASH, 0).write((char*)str.data(), str.size()).write((char*)rnd, sizeof(rnd)).GetHash(); std::vector<unsigned char> vchSig; Sign(hash, vchSig); return pubkey.Verify(hash, vchSig); } bool CPubKey::Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const { assert(IsValid()); assert((nChild >> 31) == 0); assert(begin() + 33 == end()); unsigned char out[64]; BIP32Hash(cc, nChild, *begin(), begin()+1, out); memcpy(ccChild, out+32, 32); CECKey key; bool ret = key.SetPubKey(*this); ret &= key.TweakPublic(out); key.GetPubKey(pubkeyChild, true); return ret; } bool CExtKey::Derive(CExtKey &out, unsigned int nChild) const { out.nDepth = nDepth + 1; CKeyID id = key.GetPubKey().GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = nChild; return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode); } void CExtKey::SetMaster(const unsigned char *seed, unsigned int nSeedLen) { static const char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'}; HMAC_SHA512_CTX ctx; HMAC_SHA512_Init(&ctx, hashkey, sizeof(hashkey)); HMAC_SHA512_Update(&ctx, seed, nSeedLen); unsigned char out[64]; LockObject(out); HMAC_SHA512_Final(out, &ctx); key.Set(&out[0], &out[32], true); memcpy(vchChainCode, &out[32], 32); UnlockObject(out); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); } int CExtKey::SetKeyCode(const unsigned char *pkey, const unsigned char *pcode) { key.Set(pkey, true); memcpy(vchChainCode, pcode, 32); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); return 0; } CExtPubKey CExtKey::Neutered() const { CExtPubKey ret; ret.nDepth = nDepth; memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4); ret.nChild = nChild; ret.pubkey = key.GetPubKey(); memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32); return ret; } void CExtKey::Encode(unsigned char code[74]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF; code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF; memcpy(code+9, vchChainCode, 32); code[41] = 0; assert(key.size() == 32); memcpy(code+42, key.begin(), 32); } void CExtKey::Decode(const unsigned char code[74]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8]; memcpy(vchChainCode, code+9, 32); key.Set(code+42, code+74, true); } void CExtPubKey::Encode(unsigned char code[74]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF; code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF; memcpy(code+9, vchChainCode, 32); assert(pubkey.size() == 33); memcpy(code+41, pubkey.begin(), 33); } void CExtPubKey::Decode(const unsigned char code[74]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8]; memcpy(vchChainCode, code+9, 32); pubkey.Set(code+41, code+74); } bool CExtPubKey::Derive(CExtPubKey &out, unsigned int nChild) const { out.nDepth = nDepth + 1; CKeyID id = pubkey.GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = nChild; return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode); } void CExtKeyPair::EncodeV(unsigned char code[74]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF; code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF; memcpy(code+9, vchChainCode, 32); code[41] = 0; assert(key.size() == 32); memcpy(code+42, key.begin(), 32); }; void CExtKeyPair::DecodeV(const unsigned char code[74]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8]; memcpy(vchChainCode, code+9, 32); key.Set(code+42, code+74, true); pubkey = key.GetPubKey(); }; void CExtKeyPair::EncodeP(unsigned char code[74]) const { code[0] = nDepth; memcpy(code+1, vchFingerprint, 4); code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF; code[7] = (nChild >> 8) & 0xFF; code[8] = (nChild >> 0) & 0xFF; memcpy(code+9, vchChainCode, 32); //assert(pubkey.size() == 33); memcpy(code+41, pubkey.begin(), 33); }; void CExtKeyPair::DecodeP(const unsigned char code[74]) { nDepth = code[0]; memcpy(vchFingerprint, code+1, 4); nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8]; memcpy(vchChainCode, code+9, 32); pubkey.Set(code+41, code+74); key.Clear(); }; bool CExtKeyPair::Derive(CExtKey &out, unsigned int nChild) const { if (!key.IsValid()) return false; out.nDepth = nDepth + 1; CKeyID id = key.GetPubKey().GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = nChild; return key.Derive(out.key, out.vchChainCode, nChild, vchChainCode); }; bool CExtKeyPair::Derive(CExtPubKey &out, unsigned int nChild) const { if ((nChild >> 31) == 0) { out.nDepth = nDepth + 1; CKeyID id = pubkey.GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = nChild; return pubkey.Derive(out.pubkey, out.vchChainCode, nChild, vchChainCode); }; if (!key.IsValid()) return false; out.nDepth = nDepth + 1; CKeyID id = pubkey.GetID(); memcpy(&out.vchFingerprint[0], &id, 4); out.nChild = nChild; CKey tkey; if (!key.Derive(tkey, out.vchChainCode, nChild, vchChainCode)) return false; out.pubkey = tkey.GetPubKey(); return true; }; bool CExtKeyPair::Derive(CKey &out, unsigned int nChild) const { if (!key.IsValid()) return false; unsigned char temp[32]; return key.Derive(out, temp, nChild, vchChainCode); }; bool CExtKeyPair::Derive(CPubKey &out, unsigned int nChild) const { unsigned char temp[32]; if ((nChild >> 31) == 0) { return pubkey.Derive(out, temp, nChild, vchChainCode); }; if (!key.IsValid()) return false; CKey tkey; if (!key.Derive(tkey, temp, nChild, vchChainCode)) return false; out = tkey.GetPubKey(); return true; }; CExtPubKey CExtKeyPair::GetExtPubKey() const { CExtPubKey ret; ret.nDepth = nDepth; memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4); ret.nChild = nChild; ret.pubkey = pubkey; memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32); return ret; }; CExtKeyPair CExtKeyPair::Neutered() const { CExtKeyPair ret; ret.nDepth = nDepth; memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4); ret.nChild = nChild; ret.pubkey = pubkey; ret.key.Clear(); memcpy(&ret.vchChainCode[0], &vchChainCode[0], 32); return ret; } void CExtKeyPair::SetMaster(const unsigned char *seed, unsigned int nSeedLen) { static const char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'}; HMAC_SHA512_CTX ctx; HMAC_SHA512_Init(&ctx, hashkey, sizeof(hashkey)); HMAC_SHA512_Update(&ctx, seed, nSeedLen); unsigned char out[64]; LockObject(out); HMAC_SHA512_Final(out, &ctx); key.Set(&out[0], &out[32], true); pubkey = key.GetPubKey(); memcpy(vchChainCode, &out[32], 32); UnlockObject(out); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); }; int CExtKeyPair::SetKeyCode(const unsigned char *pkey, const unsigned char *pcode) { key.Set(pkey, true); pubkey = key.GetPubKey(); memcpy(vchChainCode, pcode, 32); nDepth = 0; nChild = 0; memset(vchFingerprint, 0, sizeof(vchFingerprint)); return 0; }; bool ECC_InitSanityCheck() { EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1); if(pkey == NULL) return false; EC_KEY_free(pkey); // TODO Is there more EC functionality that could be missing? return true; }
#include <cassert> #include <ref/utils/StructuralContext.hpp> #include "../examples/company.hpp" #include <iostream> #include <set> #include <algorithm> using namespace ref; using namespace std; int main(int argc, char **argv) { auto companyDesc = example::Company::getClassDescriptorInstance(); auto departmentDesc = example::Department::getClassDescriptorInstance(); auto employeeDesc = example::Employee::getClassDescriptorInstance(); const StructuralContext ctx(companyDesc); // getRootClass and getAllClasses { assert(ctx.getRootClass() == companyDesc); assert(ctx.getAllClasses().size() == 4); const set<string> expected = {"ref::ModelClass", "example::Department", "example::Employee", "example::Company"}; const auto allClasses = ctx.getAllClasses(); set<string> fqns; for (auto d: allClasses) { fqns.insert(d->getFqn()); } assert(fqns == expected); } // References { assert(ctx.getIncomingReferences(companyDesc).size() == 0); assert(ctx.getIncomingReferences(departmentDesc).size() == 1); assert(ctx.getIncomingReferences(employeeDesc).size() == 2); assert(ctx.getAllIncomingReferences(companyDesc).size() == 0); assert(ctx.getAllIncomingReferences(departmentDesc).size() == 1); assert(ctx.getAllIncomingReferences(employeeDesc).size() == 2); assert(ctx.getOutgoingReferences(companyDesc).size() == 1); assert(ctx.getOutgoingReferences(departmentDesc).size() == 1); assert(ctx.getOutgoingReferences(employeeDesc).size() == 1); assert(ctx.getAllOutgoingReferences(companyDesc).size() == 1); assert(ctx.getAllOutgoingReferences(departmentDesc).size() == 1); assert(ctx.getAllOutgoingReferences(employeeDesc).size() == 1); auto empInRefs = ctx.getIncomingReferences(employeeDesc); for (const auto& it: empInRefs) { assert(it.referencedClassDesc == employeeDesc); } assert(empInRefs[0].classDesc == departmentDesc); assert(empInRefs[0].featureDesc == departmentDesc->getFeatureDescriptor("Employees")); assert(empInRefs[1].classDesc == employeeDesc); assert(empInRefs[1].featureDesc == employeeDesc->getFeatureDescriptor("Manager")); // isReference assert( ctx.isReference(departmentDesc->getFeatureDescriptor("Employees"))); assert(!ctx.isReference(departmentDesc->getFeatureDescriptor("Name"))); assert( ctx.isReference(companyDesc->getFeatureDescriptor("Departments"))); assert(!ctx.isReference(companyDesc->getFeatureDescriptor("Name"))); } return 0; }
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @file * @brief Internal wrapper layer on top of a uint_8 array. * */ #pragma once #include <azure/core/http/http.hpp> #include <azure/core/internal/json/json_serializable.hpp> #include <string> #include <vector> namespace Azure { namespace Security { namespace KeyVault { namespace Keys { namespace _detail { struct KeyBackup : public Azure::Core::Json::_internal::JsonSerializable { std::vector<uint8_t> Value; std::string Serialize() const override; static KeyBackup Deserialize(Azure::Core::Http::RawResponse const& rawResponse); }; }}}}} // namespace Azure::Security::KeyVault::Keys::_detail
// Copyright (c) 2011 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 "net/base/net_errors.h" #include "net/base/static_cookie_policy.h" #include "testing/gtest/include/gtest/gtest.h" #include "googleurl/src/gurl.h" namespace net { class StaticCookiePolicyTest : public testing::Test { public: StaticCookiePolicyTest() : url_google_("http://www.google.izzle"), url_google_secure_("https://www.google.izzle"), url_google_mail_("http://mail.google.izzle"), url_google_analytics_("http://www.googleanalytics.izzle") { } void SetPolicyType(StaticCookiePolicy::Type type) { policy_.set_type(type); } int CanGetCookies(const GURL& url, const GURL& first_party) { return policy_.CanGetCookies(url, first_party); } int CanSetCookie(const GURL& url, const GURL& first_party) { return policy_.CanSetCookie(url, first_party, std::string()); } protected: StaticCookiePolicy policy_; GURL url_google_; GURL url_google_secure_; GURL url_google_mail_; GURL url_google_analytics_; }; TEST_F(StaticCookiePolicyTest, DefaultPolicyTest) { EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_mail_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanGetCookies(url_google_, GURL())); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_mail_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, AllowAllCookiesTest) { SetPolicyType(StaticCookiePolicy::ALLOW_ALL_COOKIES); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_mail_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanGetCookies(url_google_, GURL())); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_mail_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, BlockSettingThirdPartyCookiesTest) { SetPolicyType(StaticCookiePolicy::BLOCK_SETTING_THIRD_PARTY_COOKIES); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_mail_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanGetCookies(url_google_, GURL())); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_mail_)); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, BlockAllThirdPartyCookiesTest) { SetPolicyType(StaticCookiePolicy::BLOCK_ALL_THIRD_PARTY_COOKIES); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanGetCookies(url_google_, url_google_mail_)); EXPECT_NE(OK, CanGetCookies(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanGetCookies(url_google_, GURL())); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_secure_)); EXPECT_EQ(OK, CanSetCookie(url_google_, url_google_mail_)); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_analytics_)); EXPECT_EQ(OK, CanSetCookie(url_google_, GURL())); } TEST_F(StaticCookiePolicyTest, BlockAllCookiesTest) { SetPolicyType(StaticCookiePolicy::BLOCK_ALL_COOKIES); EXPECT_NE(OK, CanGetCookies(url_google_, url_google_)); EXPECT_NE(OK, CanGetCookies(url_google_, url_google_secure_)); EXPECT_NE(OK, CanGetCookies(url_google_, url_google_mail_)); EXPECT_NE(OK, CanGetCookies(url_google_, url_google_analytics_)); EXPECT_NE(OK, CanGetCookies(url_google_, GURL())); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_)); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_secure_)); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_mail_)); EXPECT_NE(OK, CanSetCookie(url_google_, url_google_analytics_)); EXPECT_NE(OK, CanSetCookie(url_google_, GURL())); } } // namespace net
// 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/v8.h" #include "src/handles.h" namespace v8 { namespace internal { int HandleScope::NumberOfHandles(Isolate* isolate) { HandleScopeImplementer* impl = isolate->handle_scope_implementer(); int n = impl->blocks()->length(); if (n == 0) return 0; return ((n - 1) * kHandleBlockSize) + static_cast<int>( (isolate->handle_scope_data()->next - impl->blocks()->last())); } Object** HandleScope::Extend(Isolate* isolate) { HandleScopeData* current = isolate->handle_scope_data(); Object** result = current->next; ASSERT(result == current->limit); // Make sure there's at least one scope on the stack and that the // top of the scope stack isn't a barrier. if (!Utils::ApiCheck(current->level != 0, "v8::HandleScope::CreateHandle()", "Cannot create a handle without a HandleScope")) { return NULL; } HandleScopeImplementer* impl = isolate->handle_scope_implementer(); // If there's more room in the last block, we use that. This is used // for fast creation of scopes after scope barriers. if (!impl->blocks()->is_empty()) { Object** limit = &impl->blocks()->last()[kHandleBlockSize]; if (current->limit != limit) { current->limit = limit; ASSERT(limit - current->next < kHandleBlockSize); } } // If we still haven't found a slot for the handle, we extend the // current handle scope by allocating a new handle block. if (result == current->limit) { // If there's a spare block, use it for growing the current scope. result = impl->GetSpareOrNewBlock(); // Add the extension to the global list of blocks, but count the // extension as part of the current scope. impl->blocks()->Add(result); current->limit = &result[kHandleBlockSize]; } return result; } void HandleScope::DeleteExtensions(Isolate* isolate) { HandleScopeData* current = isolate->handle_scope_data(); isolate->handle_scope_implementer()->DeleteExtensions(current->limit); } #ifdef ENABLE_HANDLE_ZAPPING void HandleScope::ZapRange(Object** start, Object** end) { ASSERT(end - start <= kHandleBlockSize); for (Object** p = start; p != end; p++) { *reinterpret_cast<Address*>(p) = v8::internal::kHandleZapValue; } } #endif Address HandleScope::current_level_address(Isolate* isolate) { return reinterpret_cast<Address>(&isolate->handle_scope_data()->level); } Address HandleScope::current_next_address(Isolate* isolate) { return reinterpret_cast<Address>(&isolate->handle_scope_data()->next); } Address HandleScope::current_limit_address(Isolate* isolate) { return reinterpret_cast<Address>(&isolate->handle_scope_data()->limit); } DeferredHandleScope::DeferredHandleScope(Isolate* isolate) : impl_(isolate->handle_scope_implementer()) { impl_->BeginDeferredScope(); HandleScopeData* data = impl_->isolate()->handle_scope_data(); Object** new_next = impl_->GetSpareOrNewBlock(); Object** new_limit = &new_next[kHandleBlockSize]; ASSERT(data->limit == &impl_->blocks()->last()[kHandleBlockSize]); impl_->blocks()->Add(new_next); #ifdef DEBUG prev_level_ = data->level; #endif data->level++; prev_limit_ = data->limit; prev_next_ = data->next; data->next = new_next; data->limit = new_limit; } DeferredHandleScope::~DeferredHandleScope() { impl_->isolate()->handle_scope_data()->level--; ASSERT(handles_detached_); ASSERT(impl_->isolate()->handle_scope_data()->level == prev_level_); } DeferredHandles* DeferredHandleScope::Detach() { DeferredHandles* deferred = impl_->Detach(prev_limit_); HandleScopeData* data = impl_->isolate()->handle_scope_data(); data->next = prev_next_; data->limit = prev_limit_; #ifdef DEBUG handles_detached_ = true; #endif return deferred; } } } // namespace v8::internal
/** * Copyright (C) 2010 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kAccessControl #include "mongo/platform/basic.h" #include "mongo/db/commands/authentication_commands.h" #include <string> #include <vector> #include "mongo/base/status.h" #include "mongo/bson/mutable/algorithm.h" #include "mongo/bson/mutable/document.h" #include "mongo/client/sasl_client_authenticate.h" #include "mongo/config.h" #include "mongo/db/audit.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/auth/privilege.h" #include "mongo/db/auth/sasl_options.h" #include "mongo/db/auth/security_key.h" #include "mongo/db/client.h" #include "mongo/db/commands.h" #include "mongo/db/commands/test_commands_enabled.h" #include "mongo/db/operation_context.h" #include "mongo/platform/random.h" #include "mongo/stdx/memory.h" #include "mongo/transport/session.h" #include "mongo/util/concurrency/mutex.h" #include "mongo/util/log.h" #include "mongo/util/net/ssl_manager.h" #include "mongo/util/net/ssl_types.h" #include "mongo/util/text.h" namespace mongo { using std::hex; using std::string; using std::stringstream; static bool _isX509AuthDisabled; static const char _nonceAuthenticationDisabledMessage[] = "Challenge-response authentication using getnonce and authenticate commands is disabled."; static const char _x509AuthenticationDisabledMessage[] = "x.509 authentication is disabled."; void CmdAuthenticate::disableAuthMechanism(std::string authMechanism) { if (authMechanism == "MONGODB-X509") { _isX509AuthDisabled = true; } } /** * Returns a random 64-bit nonce. * * Previously, this command would have been called prior to {authenticate: ...} * when using the MONGODB-CR authentication mechanism. * Since that mechanism has been removed from MongoDB 3.8, * it is nominally no longer required. * * Unfortunately, mongo-tools uses a connection library * which optimistically invokes {getnonce: 1} upon connection * under the assumption that it will eventually be used as part * of "classic" authentication. * If the command dissapeared, then all of mongo-tools would * fail to connect, despite using SCRAM-SHA-1 or another valid * auth mechanism. Thus, we have to keep this command around for now. * * Note that despite nonces being available, they are not bound * to the AuthorizationSession anymore, and the authenticate * command doesn't acknowledge their existence. */ class CmdGetNonce : public BasicCommand { public: CmdGetNonce() : BasicCommand("getnonce"), _random(SecureRandom::create()) {} AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { return AllowedOnSecondary::kAlways; } std::string help() const final { return "internal"; } bool supportsWriteConcern(const BSONObj& cmd) const final { return false; } void addRequiredPrivileges(const std::string& dbname, const BSONObj& cmdObj, std::vector<Privilege>* out) const final { // No auth required since this command was explicitly part // of an authentication workflow. } bool run(OperationContext* opCtx, const string&, const BSONObj& cmdObj, BSONObjBuilder& result) final { auto n = getNextNonce(); stringstream ss; ss << hex << n; result.append("nonce", ss.str()); return true; } private: int64_t getNextNonce() { stdx::lock_guard<SimpleMutex> lk(_randMutex); return _random->nextInt64(); } SimpleMutex _randMutex; // Synchronizes accesses to _random. std::unique_ptr<SecureRandom> _random; } cmdGetNonce; bool CmdAuthenticate::run(OperationContext* opCtx, const string& dbname, const BSONObj& cmdObj, BSONObjBuilder& result) { if (!serverGlobalParams.quiet.load()) { mutablebson::Document cmdToLog(cmdObj, mutablebson::Document::kInPlaceDisabled); log() << " authenticate db: " << dbname << " " << cmdToLog; } std::string mechanism = cmdObj.getStringField("mechanism"); if (mechanism.empty()) { CommandHelpers::appendCommandStatus(result, {ErrorCodes::BadValue, "Auth mechanism not specified"}); return false; } UserName user; auto& sslPeerInfo = SSLPeerInfo::forSession(opCtx->getClient()->session()); if (mechanism == "MONGODB-X509" && !cmdObj.hasField("user")) { user = UserName(sslPeerInfo.subjectName, dbname); } else { user = UserName(cmdObj.getStringField("user"), dbname); } if (getTestCommandsEnabled() && user.getDB() == "admin" && user.getUser() == internalSecurity.user->getName().getUser()) { // Allows authenticating as the internal user against the admin database. This is to // support the auth passthrough test framework on mongos (since you can't use the local // database on a mongos, so you can't auth as the internal user without this). user = internalSecurity.user->getName(); } Status status = _authenticate(opCtx, mechanism, user, cmdObj); audit::logAuthentication(Client::getCurrent(), mechanism, user, status.code()); if (!status.isOK()) { if (!serverGlobalParams.quiet.load()) { auto const client = opCtx->getClient(); log() << "Failed to authenticate " << user << (client->hasRemote() ? (" from client " + client->getRemote().toString()) : "") << " with mechanism " << mechanism << ": " << status; } if (status.code() == ErrorCodes::AuthenticationFailed) { // Statuses with code AuthenticationFailed may contain messages we do not wish to // reveal to the user, so we return a status with the message "auth failed". CommandHelpers::appendCommandStatus( result, Status(ErrorCodes::AuthenticationFailed, "auth failed")); } else { CommandHelpers::appendCommandStatus(result, status); } sleepmillis(saslGlobalParams.authFailedDelay.load()); return false; } result.append("dbname", user.getDB()); result.append("user", user.getUser()); return true; } Status CmdAuthenticate::_authenticate(OperationContext* opCtx, const std::string& mechanism, const UserName& user, const BSONObj& cmdObj) { #ifdef MONGO_CONFIG_SSL if (mechanism == "MONGODB-X509") { return _authenticateX509(opCtx, user, cmdObj); } #endif return Status(ErrorCodes::BadValue, "Unsupported mechanism: " + mechanism); } #ifdef MONGO_CONFIG_SSL Status CmdAuthenticate::_authenticateX509(OperationContext* opCtx, const UserName& user, const BSONObj& cmdObj) { if (!getSSLManager()) { return Status(ErrorCodes::ProtocolError, "SSL support is required for the MONGODB-X509 mechanism."); } if (user.getDB() != "$external") { return Status(ErrorCodes::ProtocolError, "X.509 authentication must always use the $external database."); } Client* client = Client::getCurrent(); AuthorizationSession* authorizationSession = AuthorizationSession::get(client); auto clientName = SSLPeerInfo::forSession(client->session()).subjectName; if (!getSSLManager()->getSSLConfiguration().hasCA) { return Status(ErrorCodes::AuthenticationFailed, "Unable to verify x.509 certificate, as no CA has been provided."); } else if (user.getUser() != clientName) { return Status(ErrorCodes::AuthenticationFailed, "There is no x.509 client certificate matching the user."); } else { // Handle internal cluster member auth, only applies to server-server connections if (getSSLManager()->getSSLConfiguration().isClusterMember(clientName)) { int clusterAuthMode = serverGlobalParams.clusterAuthMode.load(); if (clusterAuthMode == ServerGlobalParams::ClusterAuthMode_undefined || clusterAuthMode == ServerGlobalParams::ClusterAuthMode_keyFile) { return Status(ErrorCodes::AuthenticationFailed, "The provided certificate " "can only be used for cluster authentication, not client " "authentication. The current configuration does not allow " "x.509 cluster authentication, check the --clusterAuthMode flag"); } authorizationSession->grantInternalAuthorization(); } // Handle normal client authentication, only applies to client-server connections else { if (_isX509AuthDisabled) { return Status(ErrorCodes::BadValue, _x509AuthenticationDisabledMessage); } Status status = authorizationSession->addAndAuthorizeUser(opCtx, user); if (!status.isOK()) { return status; } } return Status::OK(); } } #endif CmdAuthenticate cmdAuthenticate; class CmdLogout : public BasicCommand { public: AllowedOnSecondary secondaryAllowed(ServiceContext*) const override { return AllowedOnSecondary::kAlways; } virtual void addRequiredPrivileges(const std::string& dbname, const BSONObj& cmdObj, std::vector<Privilege>* out) const {} // No auth required std::string help() const override { return "de-authenticate"; } virtual bool supportsWriteConcern(const BSONObj& cmd) const override { return false; } CmdLogout() : BasicCommand("logout") {} bool run(OperationContext* opCtx, const string& dbname, const BSONObj& cmdObj, BSONObjBuilder& result) { AuthorizationSession* authSession = AuthorizationSession::get(Client::getCurrent()); authSession->logoutDatabase(dbname); if (getTestCommandsEnabled() && dbname == "admin") { // Allows logging out as the internal user against the admin database, however // this actually logs out of the local database as well. This is to // support the auth passthrough test framework on mongos (since you can't use the // local database on a mongos, so you can't logout as the internal user // without this). authSession->logoutDatabase("local"); } return true; } } cmdLogout; }
// Copyright 2014 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 "components/data_reduction_proxy/core/browser/data_reduction_proxy_compression_stats.h" #include <stddef.h> #include <stdint.h> #include <string> #include <utility> #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/histogram_tester.h" #include "base/test/scoped_task_environment.h" #include "base/time/time.h" #include "base/values.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_prefs.h" #include "components/data_reduction_proxy/core/browser/data_reduction_proxy_test_utils.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_pref_names.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_switches.h" #include "components/data_reduction_proxy/proto/data_store.pb.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/pref_service.h" #include "components/prefs/testing_pref_service.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const int kWriteDelayMinutes = 60; // Each bucket holds data usage for a 15 minute interval. History is maintained // for 60 days. const int kNumExpectedBuckets = 60 * 24 * 60 / 15; int64_t GetListPrefInt64Value(const base::ListValue& list_update, size_t index) { std::string string_value; EXPECT_TRUE(list_update.GetString(index, &string_value)); int64_t value = 0; EXPECT_TRUE(base::StringToInt64(string_value, &value)); return value; } class DataUsageLoadVerifier { public: DataUsageLoadVerifier( std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>> expected) { expected_ = std::move(expected); } void OnLoadDataUsage( std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>> actual) { EXPECT_EQ(expected_->size(), actual->size()); // We are iterating through 2 vectors, |actual| and |expected|, so using an // index rather than an iterator. for (size_t i = 0; i < expected_->size(); ++i) { data_reduction_proxy::DataUsageBucket* actual_bucket = &(actual->at(i)); data_reduction_proxy::DataUsageBucket* expected_bucket = &(expected_->at(i)); EXPECT_EQ(expected_bucket->connection_usage_size(), actual_bucket->connection_usage_size()); for (int j = 0; j < expected_bucket->connection_usage_size(); ++j) { data_reduction_proxy::PerConnectionDataUsage actual_connection_usage = actual_bucket->connection_usage(j); data_reduction_proxy::PerConnectionDataUsage expected_connection_usage = expected_bucket->connection_usage(j); EXPECT_EQ(expected_connection_usage.site_usage_size(), actual_connection_usage.site_usage_size()); for (auto expected_site_usage : expected_connection_usage.site_usage()) { data_reduction_proxy::PerSiteDataUsage actual_site_usage; for (auto it = actual_connection_usage.site_usage().begin(); it != actual_connection_usage.site_usage().end(); ++it) { if (it->hostname() == expected_site_usage.hostname()) { actual_site_usage = *it; } } EXPECT_EQ(expected_site_usage.data_used(), actual_site_usage.data_used()); EXPECT_EQ(expected_site_usage.original_size(), actual_site_usage.original_size()); } } } } private: std::unique_ptr<std::vector<data_reduction_proxy::DataUsageBucket>> expected_; }; } // namespace namespace data_reduction_proxy { // The initial last update time used in test. There is no leap second a few // days around this time used in the test. // Note: No time zone is specified. Local time will be assumed by // base::Time::FromString below. const char kLastUpdateTime[] = "Wed, 18 Sep 2013 03:45:26"; class DataReductionProxyCompressionStatsTest : public testing::Test { protected: DataReductionProxyCompressionStatsTest() : scoped_task_environment_( base::test::ScopedTaskEnvironment::MainThreadType::UI) { EXPECT_TRUE(base::Time::FromString(kLastUpdateTime, &now_)); } void SetUp() override { drp_test_context_ = DataReductionProxyTestContext::Builder().Build(); compression_stats_.reset(new DataReductionProxyCompressionStats( data_reduction_proxy_service(), pref_service(), base::TimeDelta())); } void ResetCompressionStatsWithDelay(const base::TimeDelta& delay) { compression_stats_.reset(new DataReductionProxyCompressionStats( data_reduction_proxy_service(), pref_service(), delay)); } base::Time FakeNow() const { return now_ + now_delta_; } void SetFakeTimeDeltaInHours(int hours) { now_delta_ = base::TimeDelta::FromHours(hours); } void AddFakeTimeDeltaInHours(int hours) { now_delta_ += base::TimeDelta::FromHours(hours); } DataReductionProxyCompressionStats::SiteUsageMap* DataUsageMap() { return &compression_stats_->data_usage_map_; } void SetUpPrefs() { CreatePrefList(prefs::kDailyHttpOriginalContentLength); CreatePrefList(prefs::kDailyHttpReceivedContentLength); const int64_t kOriginalLength = 150; const int64_t kReceivedLength = 100; compression_stats_->SetInt64( prefs::kHttpOriginalContentLength, kOriginalLength); compression_stats_->SetInt64( prefs::kHttpReceivedContentLength, kReceivedLength); base::ListValue* original_daily_content_length_list = compression_stats_->GetList(prefs::kDailyHttpOriginalContentLength); base::ListValue* received_daily_content_length_list = compression_stats_->GetList(prefs::kDailyHttpReceivedContentLength); for (size_t i = 0; i < kNumDaysInHistory; ++i) { original_daily_content_length_list->Set( i, base::MakeUnique<base::Value>(base::SizeTToString(i))); } received_daily_content_length_list->Clear(); for (size_t i = 0; i < kNumDaysInHistory / 2; ++i) { received_daily_content_length_list->AppendString(base::SizeTToString(i)); } } // Create daily pref list of |kNumDaysInHistory| zero values. void CreatePrefList(const char* pref) { base::ListValue* update = compression_stats_->GetList(pref); update->Clear(); for (size_t i = 0; i < kNumDaysInHistory; ++i) { update->Insert(0, base::MakeUnique<base::Value>(base::Int64ToString(0))); } } // Verify the pref list values in |pref_service_| are equal to those in // |simple_pref_service| for |pref|. void VerifyPrefListWasWritten(const char* pref) { const base::ListValue* delayed_list = compression_stats_->GetList(pref); const base::ListValue* written_list = pref_service()->GetList(pref); ASSERT_EQ(delayed_list->GetSize(), written_list->GetSize()); size_t count = delayed_list->GetSize(); for (size_t i = 0; i < count; ++i) { EXPECT_EQ(GetListPrefInt64Value(*delayed_list, i), GetListPrefInt64Value(*written_list, i)); } } // Verify the pref value in |pref_service_| are equal to that in // |simple_pref_service|. void VerifyPrefWasWritten(const char* pref) { int64_t delayed_pref = compression_stats_->GetInt64(pref); int64_t written_pref = pref_service()->GetInt64(pref); EXPECT_EQ(delayed_pref, written_pref); } // Verify the pref values in |dict| are equal to that in |compression_stats_|. void VerifyPrefs(base::DictionaryValue* dict) { base::string16 dict_pref_string; int64_t dict_pref; int64_t service_pref; dict->GetString("historic_original_content_length", &dict_pref_string); base::StringToInt64(dict_pref_string, &dict_pref); service_pref = compression_stats_->GetInt64(prefs::kHttpOriginalContentLength); EXPECT_EQ(service_pref, dict_pref); dict->GetString("historic_received_content_length", &dict_pref_string); base::StringToInt64(dict_pref_string, &dict_pref); service_pref = compression_stats_->GetInt64(prefs::kHttpReceivedContentLength); EXPECT_EQ(service_pref, dict_pref); } // Verify the pref list values are equal to the given values. // If the count of values is less than kNumDaysInHistory, zeros are assumed // at the beginning. void VerifyPrefList(const char* pref, const int64_t* values, size_t count, size_t num_days_in_history) { ASSERT_GE(num_days_in_history, count); base::ListValue* update = compression_stats_->GetList(pref); ASSERT_EQ(num_days_in_history, update->GetSize()) << "Pref: " << pref; for (size_t i = 0; i < count; ++i) { EXPECT_EQ(values[i], GetListPrefInt64Value(*update, num_days_in_history - count + i)) << pref << "; index=" << (num_days_in_history - count + i); } for (size_t i = 0; i < num_days_in_history - count; ++i) { EXPECT_EQ(0, GetListPrefInt64Value(*update, i)) << "index=" << i; } } // Verify that the pref value is equal to given value. void VerifyPrefInt64(const char* pref, const int64_t value) { EXPECT_EQ(value, compression_stats_->GetInt64(pref)); } // Verify all daily data saving pref list values. void VerifyDailyDataSavingContentLengthPrefLists( const int64_t* original_values, size_t original_count, const int64_t* received_values, size_t received_count, const int64_t* original_with_data_reduction_proxy_enabled_values, size_t original_with_data_reduction_proxy_enabled_count, const int64_t* received_with_data_reduction_proxy_enabled_values, size_t received_with_data_reduction_proxy_count, const int64_t* original_via_data_reduction_proxy_values, size_t original_via_data_reduction_proxy_count, const int64_t* received_via_data_reduction_proxy_values, size_t received_via_data_reduction_proxy_count, size_t num_days_in_history) { VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpOriginalContentLength, original_values, original_count, num_days_in_history); VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpReceivedContentLength, received_values, received_count, num_days_in_history); VerifyPrefList(data_reduction_proxy::prefs:: kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count, num_days_in_history); VerifyPrefList(data_reduction_proxy::prefs:: kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count, num_days_in_history); VerifyPrefList(data_reduction_proxy::prefs:: kDailyOriginalContentLengthViaDataReductionProxy, original_via_data_reduction_proxy_values, original_via_data_reduction_proxy_count, num_days_in_history); VerifyPrefList( data_reduction_proxy::prefs::kDailyContentLengthViaDataReductionProxy, received_via_data_reduction_proxy_values, received_via_data_reduction_proxy_count, num_days_in_history); VerifyPrefInt64( data_reduction_proxy::prefs::kDailyHttpOriginalContentLengthApplication, original_values ? original_values[original_count - 1] : 0); VerifyPrefInt64( data_reduction_proxy::prefs::kDailyHttpReceivedContentLengthApplication, received_values ? received_values[received_count - 1] : 0); VerifyPrefInt64( data_reduction_proxy::prefs:: kDailyOriginalContentLengthWithDataReductionProxyEnabledApplication, original_with_data_reduction_proxy_enabled_values ? original_with_data_reduction_proxy_enabled_values [original_with_data_reduction_proxy_enabled_count - 1] : 0); VerifyPrefInt64( data_reduction_proxy::prefs:: kDailyContentLengthWithDataReductionProxyEnabledApplication, received_with_data_reduction_proxy_enabled_values ? received_with_data_reduction_proxy_enabled_values [received_with_data_reduction_proxy_count - 1] : 0); VerifyPrefInt64( data_reduction_proxy::prefs:: kDailyOriginalContentLengthViaDataReductionProxyApplication, original_via_data_reduction_proxy_values ? original_via_data_reduction_proxy_values [original_via_data_reduction_proxy_count - 1] : 0); VerifyPrefInt64(data_reduction_proxy::prefs:: kDailyContentLengthViaDataReductionProxyApplication, received_via_data_reduction_proxy_values ? received_via_data_reduction_proxy_values [received_via_data_reduction_proxy_count - 1] : 0); } // Verify daily data saving pref for request types. void VerifyDailyRequestTypeContentLengthPrefLists( const int64_t* original_values, size_t original_count, const int64_t* received_values, size_t received_count, const int64_t* original_with_data_reduction_proxy_enabled_values, size_t original_with_data_reduction_proxy_enabled_count, const int64_t* received_with_data_reduction_proxy_enabled_values, size_t received_with_data_reduction_proxy_count, const int64_t* https_with_data_reduction_proxy_enabled_values, size_t https_with_data_reduction_proxy_enabled_count, const int64_t* short_bypass_with_data_reduction_proxy_enabled_values, size_t short_bypass_with_data_reduction_proxy_enabled_count, const int64_t* long_bypass_with_data_reduction_proxy_enabled_values, size_t long_bypass_with_data_reduction_proxy_enabled_count, const int64_t* unknown_with_data_reduction_proxy_enabled_values, size_t unknown_with_data_reduction_proxy_enabled_count) { VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpOriginalContentLength, original_values, original_count, kNumDaysInHistory); VerifyPrefList(data_reduction_proxy::prefs::kDailyHttpReceivedContentLength, received_values, received_count, kNumDaysInHistory); VerifyPrefList(data_reduction_proxy::prefs:: kDailyOriginalContentLengthWithDataReductionProxyEnabled, original_with_data_reduction_proxy_enabled_values, original_with_data_reduction_proxy_enabled_count, kNumDaysInHistory); VerifyPrefList(data_reduction_proxy::prefs:: kDailyContentLengthWithDataReductionProxyEnabled, received_with_data_reduction_proxy_enabled_values, received_with_data_reduction_proxy_count, kNumDaysInHistory); VerifyPrefList(data_reduction_proxy::prefs:: kDailyContentLengthHttpsWithDataReductionProxyEnabled, https_with_data_reduction_proxy_enabled_values, https_with_data_reduction_proxy_enabled_count, kNumDaysInHistory); VerifyPrefList( data_reduction_proxy::prefs:: kDailyContentLengthShortBypassWithDataReductionProxyEnabled, short_bypass_with_data_reduction_proxy_enabled_values, short_bypass_with_data_reduction_proxy_enabled_count, kNumDaysInHistory); VerifyPrefList( data_reduction_proxy::prefs:: kDailyContentLengthLongBypassWithDataReductionProxyEnabled, long_bypass_with_data_reduction_proxy_enabled_values, long_bypass_with_data_reduction_proxy_enabled_count, kNumDaysInHistory); VerifyPrefList(data_reduction_proxy::prefs:: kDailyContentLengthUnknownWithDataReductionProxyEnabled, unknown_with_data_reduction_proxy_enabled_values, unknown_with_data_reduction_proxy_enabled_count, kNumDaysInHistory); } int64_t GetInt64(const char* pref_path) { return compression_stats_->GetInt64(pref_path); } void SetInt64(const char* pref_path, int64_t pref_value) { compression_stats_->SetInt64(pref_path, pref_value); } std::string NormalizeHostname(const std::string& hostname) { return DataReductionProxyCompressionStats::NormalizeHostname(hostname); } void RecordContentLengthPrefs(int64_t received_content_length, int64_t original_content_length, bool with_data_reduction_proxy_enabled, DataReductionProxyRequestType request_type, const std::string& mime_type, base::Time now) { compression_stats_->RecordRequestSizePrefs( received_content_length, original_content_length, with_data_reduction_proxy_enabled, request_type, mime_type, now); } void RecordContentLengthPrefs(int64_t received_content_length, int64_t original_content_length, bool with_data_reduction_proxy_enabled, DataReductionProxyRequestType request_type, base::Time now) { RecordContentLengthPrefs(received_content_length, original_content_length, with_data_reduction_proxy_enabled, request_type, "application/octet-stream", now); } void RecordDataUsage(const std::string& data_usage_host, int64_t data_used, int64_t original_size, const base::Time& time) { compression_stats_->RecordDataUseByHost(data_usage_host, data_used, original_size, time); } void GetHistoricalDataUsage( const HistoricalDataUsageCallback& onLoadDataUsage, const base::Time& now) { compression_stats_->GetHistoricalDataUsageImpl(onLoadDataUsage, now); } void LoadHistoricalDataUsage( const HistoricalDataUsageCallback& onLoadDataUsage) { compression_stats_->service_->LoadHistoricalDataUsage(onLoadDataUsage); } void DeleteHistoricalDataUsage() { compression_stats_->DeleteHistoricalDataUsage(); } void ClearDataSavingStatistics() { compression_stats_->ClearDataSavingStatistics(); } void DeleteBrowsingHistory(const base::Time& start, const base::Time& end) { compression_stats_->DeleteBrowsingHistory(start, end); } void EnableDataUsageReporting() { pref_service()->SetBoolean(prefs::kDataUsageReportingEnabled, true); } void DisableDataUsageReporting() { pref_service()->SetBoolean(prefs::kDataUsageReportingEnabled, false); } DataReductionProxyCompressionStats* compression_stats() { return compression_stats_.get(); } void ForceWritePrefs() { compression_stats_->WritePrefs(); } bool IsDelayedWriteTimerRunning() const { return compression_stats_->pref_writer_timer_.IsRunning(); } TestingPrefServiceSimple* pref_service() { return drp_test_context_->pref_service(); } DataReductionProxyService* data_reduction_proxy_service() { return drp_test_context_->data_reduction_proxy_service(); } bool IsDataReductionProxyEnabled() { return drp_test_context_->IsDataReductionProxyEnabled(); } private: base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<DataReductionProxyTestContext> drp_test_context_; std::unique_ptr<DataReductionProxyCompressionStats> compression_stats_; base::Time now_; base::TimeDelta now_delta_; }; TEST_F(DataReductionProxyCompressionStatsTest, WritePrefsDirect) { SetUpPrefs(); VerifyPrefWasWritten(prefs::kHttpOriginalContentLength); VerifyPrefWasWritten(prefs::kHttpReceivedContentLength); VerifyPrefListWasWritten(prefs::kDailyHttpOriginalContentLength); VerifyPrefListWasWritten(prefs::kDailyHttpReceivedContentLength); } TEST_F(DataReductionProxyCompressionStatsTest, WritePrefsDelayed) { ResetCompressionStatsWithDelay( base::TimeDelta::FromMinutes(kWriteDelayMinutes)); EXPECT_EQ(0, pref_service()->GetInt64(prefs::kHttpOriginalContentLength)); EXPECT_EQ(0, pref_service()->GetInt64(prefs::kHttpReceivedContentLength)); EXPECT_FALSE(IsDelayedWriteTimerRunning()); SetUpPrefs(); EXPECT_TRUE(IsDelayedWriteTimerRunning()); ForceWritePrefs(); VerifyPrefWasWritten(prefs::kHttpOriginalContentLength); VerifyPrefWasWritten(prefs::kHttpReceivedContentLength); VerifyPrefListWasWritten(prefs::kDailyHttpOriginalContentLength); VerifyPrefListWasWritten(prefs::kDailyHttpReceivedContentLength); } TEST_F(DataReductionProxyCompressionStatsTest, HistoricNetworkStatsInfoToValue) { const int64_t kOriginalLength = 150; const int64_t kReceivedLength = 100; ResetCompressionStatsWithDelay( base::TimeDelta::FromMinutes(kWriteDelayMinutes)); base::DictionaryValue* dict = nullptr; std::unique_ptr<base::Value> stats_value( compression_stats()->HistoricNetworkStatsInfoToValue()); EXPECT_TRUE(stats_value->GetAsDictionary(&dict)); VerifyPrefs(dict); SetInt64(prefs::kHttpOriginalContentLength, kOriginalLength); SetInt64(prefs::kHttpReceivedContentLength, kReceivedLength); stats_value = compression_stats()->HistoricNetworkStatsInfoToValue(); EXPECT_TRUE(stats_value->GetAsDictionary(&dict)); VerifyPrefs(dict); } TEST_F(DataReductionProxyCompressionStatsTest, HistoricNetworkStatsInfoToValueDirect) { const int64_t kOriginalLength = 150; const int64_t kReceivedLength = 100; base::DictionaryValue* dict = nullptr; std::unique_ptr<base::Value> stats_value( compression_stats()->HistoricNetworkStatsInfoToValue()); EXPECT_TRUE(stats_value->GetAsDictionary(&dict)); VerifyPrefs(dict); SetInt64(prefs::kHttpOriginalContentLength, kOriginalLength); SetInt64(prefs::kHttpReceivedContentLength, kReceivedLength); stats_value = compression_stats()->HistoricNetworkStatsInfoToValue(); EXPECT_TRUE(stats_value->GetAsDictionary(&dict)); VerifyPrefs(dict); } TEST_F(DataReductionProxyCompressionStatsTest, StatsRestoredOnOnRestart) { base::ListValue list_value; list_value.Insert(0, base::MakeUnique<base::Value>(base::Int64ToString(1234))); pref_service()->Set(prefs::kDailyHttpOriginalContentLength, list_value); ResetCompressionStatsWithDelay( base::TimeDelta::FromMinutes(kWriteDelayMinutes)); const base::ListValue* value = pref_service()->GetList( prefs::kDailyHttpOriginalContentLength); std::string string_value; value->GetString(0, &string_value); EXPECT_EQ("1234", string_value); } TEST_F(DataReductionProxyCompressionStatsTest, TotalLengths) { const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; compression_stats()->RecordDataUseWithMimeType( kReceivedLength, kOriginalLength, IsDataReductionProxyEnabled(), UNKNOWN_TYPE, std::string()); EXPECT_EQ(kReceivedLength, GetInt64(data_reduction_proxy::prefs::kHttpReceivedContentLength)); EXPECT_FALSE(IsDataReductionProxyEnabled()); EXPECT_EQ(kOriginalLength, GetInt64(data_reduction_proxy::prefs::kHttpOriginalContentLength)); // Record the same numbers again, and total lengths should be doubled. compression_stats()->RecordDataUseWithMimeType( kReceivedLength, kOriginalLength, IsDataReductionProxyEnabled(), UNKNOWN_TYPE, std::string()); EXPECT_EQ(kReceivedLength * 2, GetInt64(data_reduction_proxy::prefs::kHttpReceivedContentLength)); EXPECT_FALSE(IsDataReductionProxyEnabled()); EXPECT_EQ(kOriginalLength * 2, GetInt64(data_reduction_proxy::prefs::kHttpOriginalContentLength)); } TEST_F(DataReductionProxyCompressionStatsTest, OneResponse) { const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; int64_t original[] = {kOriginalLength}; int64_t received[] = {kReceivedLength}; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original, 1, received, 1, original, 1, received, 1, kNumDaysInHistory); } TEST_F(DataReductionProxyCompressionStatsTest, MultipleResponses) { const int64_t kOriginalLength = 150; const int64_t kReceivedLength = 100; int64_t original[] = {kOriginalLength}; int64_t received[] = {kReceivedLength}; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, false, UNKNOWN_TYPE, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists(original, 1, received, 1, NULL, 0, NULL, 0, NULL, 0, NULL, 0, kNumDaysInHistory); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, UNKNOWN_TYPE, FakeNow()); original[0] += kOriginalLength; received[0] += kReceivedLength; int64_t original_proxy_enabled[] = {kOriginalLength}; int64_t received_proxy_enabled[] = {kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original_proxy_enabled, 1, received_proxy_enabled, 1, NULL, 0, NULL, 0, kNumDaysInHistory); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); original[0] += kOriginalLength; received[0] += kReceivedLength; original_proxy_enabled[0] += kOriginalLength; received_proxy_enabled[0] += kReceivedLength; int64_t original_via_proxy[] = {kOriginalLength}; int64_t received_via_proxy[] = {kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original_proxy_enabled, 1, received_proxy_enabled, 1, original_via_proxy, 1, received_via_proxy, 1, kNumDaysInHistory); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, UNKNOWN_TYPE, FakeNow()); original[0] += kOriginalLength; received[0] += kReceivedLength; original_proxy_enabled[0] += kOriginalLength; received_proxy_enabled[0] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original_proxy_enabled, 1, received_proxy_enabled, 1, original_via_proxy, 1, received_via_proxy, 1, kNumDaysInHistory); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, false, UNKNOWN_TYPE, FakeNow()); original[0] += kOriginalLength; received[0] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original_proxy_enabled, 1, received_proxy_enabled, 1, original_via_proxy, 1, received_via_proxy, 1, kNumDaysInHistory); } TEST_F(DataReductionProxyCompressionStatsTest, RequestType) { const int64_t kContentLength = 200; int64_t received[] = {0}; int64_t https_received[] = {0}; int64_t total_received[] = {0}; int64_t proxy_enabled_received[] = {0}; RecordContentLengthPrefs( kContentLength, kContentLength, true, HTTPS, FakeNow()); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; https_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 0, // short bypass received, 0, // long bypass received, 0); // unknown // Data reduction proxy is not enabled. RecordContentLengthPrefs( kContentLength, kContentLength, false, HTTPS, FakeNow()); total_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 0, // short bypass received, 0, // long bypass received, 0); // unknown RecordContentLengthPrefs( kContentLength, kContentLength, true, HTTPS, FakeNow()); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; https_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 0, // short bypass received, 0, // long bypass received, 0); // unknown RecordContentLengthPrefs( kContentLength, kContentLength, true, SHORT_BYPASS, FakeNow()); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 1, // short bypass received, 0, // long bypass received, 0); // unknown RecordContentLengthPrefs( kContentLength, kContentLength, true, LONG_BYPASS, FakeNow()); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, // total proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 1, // short bypass received, 1, // long bypass received, 0); // unknown RecordContentLengthPrefs( kContentLength, kContentLength, true, UNKNOWN_TYPE, FakeNow()); total_received[0] += kContentLength; proxy_enabled_received[0] += kContentLength; VerifyDailyRequestTypeContentLengthPrefLists( total_received, 1, total_received, 1, proxy_enabled_received, 1, proxy_enabled_received, 1, https_received, 1, received, 1, // short bypass received, 1, // long bypass received, 1); // unknown } TEST_F(DataReductionProxyCompressionStatsTest, ForwardOneDay) { const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); // Forward one day. SetFakeTimeDeltaInHours(24); // Proxy not enabled. Not via proxy. RecordContentLengthPrefs( kReceivedLength, kOriginalLength, false, UNKNOWN_TYPE, FakeNow()); int64_t original[] = {kOriginalLength, kOriginalLength}; int64_t received[] = {kReceivedLength, kReceivedLength}; int64_t original_with_data_reduction_proxy_enabled[] = {kOriginalLength, 0}; int64_t received_with_data_reduction_proxy_enabled[] = {kReceivedLength, 0}; int64_t original_via_data_reduction_proxy[] = {kOriginalLength, 0}; int64_t received_via_data_reduction_proxy[] = {kReceivedLength, 0}; VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original_with_data_reduction_proxy_enabled, 2, received_with_data_reduction_proxy_enabled, 2, original_via_data_reduction_proxy, 2, received_via_data_reduction_proxy, 2, kNumDaysInHistory); // Proxy enabled. Not via proxy. RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, UNKNOWN_TYPE, FakeNow()); original[1] += kOriginalLength; received[1] += kReceivedLength; original_with_data_reduction_proxy_enabled[1] += kOriginalLength; received_with_data_reduction_proxy_enabled[1] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original_with_data_reduction_proxy_enabled, 2, received_with_data_reduction_proxy_enabled, 2, original_via_data_reduction_proxy, 2, received_via_data_reduction_proxy, 2, kNumDaysInHistory); // Proxy enabled and via proxy. RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); original[1] += kOriginalLength; received[1] += kReceivedLength; original_with_data_reduction_proxy_enabled[1] += kOriginalLength; received_with_data_reduction_proxy_enabled[1] += kReceivedLength; original_via_data_reduction_proxy[1] += kOriginalLength; received_via_data_reduction_proxy[1] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original_with_data_reduction_proxy_enabled, 2, received_with_data_reduction_proxy_enabled, 2, original_via_data_reduction_proxy, 2, received_via_data_reduction_proxy, 2, kNumDaysInHistory); // Proxy enabled and via proxy, with content length greater than max int32_t. const int64_t kBigOriginalLength = 0x300000000LL; // 12G. const int64_t kBigReceivedLength = 0x200000000LL; // 8G. RecordContentLengthPrefs(kBigReceivedLength, kBigOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); original[1] += kBigOriginalLength; received[1] += kBigReceivedLength; original_with_data_reduction_proxy_enabled[1] += kBigOriginalLength; received_with_data_reduction_proxy_enabled[1] += kBigReceivedLength; original_via_data_reduction_proxy[1] += kBigOriginalLength; received_via_data_reduction_proxy[1] += kBigReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original_with_data_reduction_proxy_enabled, 2, received_with_data_reduction_proxy_enabled, 2, original_via_data_reduction_proxy, 2, received_via_data_reduction_proxy, 2, kNumDaysInHistory); } TEST_F(DataReductionProxyCompressionStatsTest, PartialDayTimeChange) { const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; int64_t original[] = {0, kOriginalLength}; int64_t received[] = {0, kReceivedLength}; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original, 2, received, 2, original, 2, received, 2, kNumDaysInHistory); // Forward 10 hours, stay in the same day. // See kLastUpdateTime: "Now" in test is 03:45am. SetFakeTimeDeltaInHours(10); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); original[1] += kOriginalLength; received[1] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 2, received, 2, original, 2, received, 2, original, 2, received, 2, kNumDaysInHistory); // Forward 11 more hours, comes to tomorrow. AddFakeTimeDeltaInHours(11); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); int64_t original2[] = {kOriginalLength * 2, kOriginalLength}; int64_t received2[] = {kReceivedLength * 2, kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original2, 2, received2, 2, original2, 2, received2, 2, original2, 2, received2, 2, kNumDaysInHistory); } TEST_F(DataReductionProxyCompressionStatsTest, ForwardMultipleDays) { base::HistogramTester histogram_tester; const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 1); // Forward three days. SetFakeTimeDeltaInHours(3 * 24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 2); int64_t original[] = {kOriginalLength, 0, 0, kOriginalLength}; int64_t received[] = {kReceivedLength, 0, 0, kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original, 4, received, 4, original, 4, received, 4, original, 4, received, 4, kNumDaysInHistory); // Forward four more days. AddFakeTimeDeltaInHours(4 * 24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); int64_t original2[] = { kOriginalLength, 0, 0, kOriginalLength, 0, 0, 0, kOriginalLength, }; int64_t received2[] = { kReceivedLength, 0, 0, kReceivedLength, 0, 0, 0, kReceivedLength, }; VerifyDailyDataSavingContentLengthPrefLists( original2, 8, received2, 8, original2, 8, received2, 8, original2, 8, received2, 8, kNumDaysInHistory); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 3); // Forward |kNumDaysInHistory| more days. AddFakeTimeDeltaInHours(kNumDaysInHistory * 24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); int64_t original3[] = {kOriginalLength}; int64_t received3[] = {kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original3, 1, received3, 1, original3, 1, received3, 1, original3, 1, received3, 1, kNumDaysInHistory); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 4); // Forward |kNumDaysInHistory| + 1 more days. AddFakeTimeDeltaInHours((kNumDaysInHistory + 1)* 24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists( original3, 1, received3, 1, original3, 1, received3, 1, original3, 1, received3, 1, kNumDaysInHistory); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 5); } TEST_F(DataReductionProxyCompressionStatsTest, BackwardAndForwardOneDay) { base::HistogramTester histogram_tester; const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; int64_t original[] = {kOriginalLength}; int64_t received[] = {kReceivedLength}; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 1); // Backward one day. SetFakeTimeDeltaInHours(-24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); original[0] += kOriginalLength; received[0] += kReceivedLength; VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original, 1, received, 1, original, 1, received, 1, kNumDaysInHistory); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 2); // Then, Forward one day AddFakeTimeDeltaInHours(24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); int64_t original2[] = {kOriginalLength * 2, kOriginalLength}; int64_t received2[] = {kReceivedLength * 2, kReceivedLength}; VerifyDailyDataSavingContentLengthPrefLists( original2, 2, received2, 2, original2, 2, received2, 2, original2, 2, received2, 2, kNumDaysInHistory); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 3); } TEST_F(DataReductionProxyCompressionStatsTest, BackwardTwoDays) { base::HistogramTester histogram_tester; const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; int64_t original[] = {kOriginalLength}; int64_t received[] = {kReceivedLength}; RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectUniqueSample( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 1); // Backward two days. SetFakeTimeDeltaInHours(-2 * 24); RecordContentLengthPrefs( kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original, 1, received, 1, original, 1, received, 1, kNumDaysInHistory); histogram_tester.ExpectTotalCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", 2); histogram_tester.ExpectBucketCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", true, 1); VerifyPrefInt64(prefs::kDataReductionProxySavingsClearedNegativeSystemClock, FakeNow().ToInternalValue()); // Backward two days. SetFakeTimeDeltaInHours(-4 * 24); RecordContentLengthPrefs(kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectTotalCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", 3); histogram_tester.ExpectBucketCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", true, 2); // Forward 10 days. AddFakeTimeDeltaInHours(10 * 24); RecordContentLengthPrefs(kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); histogram_tester.ExpectTotalCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", 4); histogram_tester.ExpectBucketCount( "DataReductionProxy.SavingsCleared.NegativeSystemClock", false, 2); } TEST_F(DataReductionProxyCompressionStatsTest, NormalizeHostname) { EXPECT_EQ("www.foo.com", NormalizeHostname("http://www.foo.com")); EXPECT_EQ("foo.com", NormalizeHostname("https://foo.com")); EXPECT_EQ("bar.co.uk", NormalizeHostname("http://bar.co.uk")); EXPECT_EQ("http.www.co.in", NormalizeHostname("http://http.www.co.in")); } TEST_F(DataReductionProxyCompressionStatsTest, RecordUma) { const int64_t kOriginalLength = 15000; const int64_t kReceivedLength = 10000; base::HistogramTester tester; RecordContentLengthPrefs(kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); // Forward one day. SetFakeTimeDeltaInHours(24); // Proxy not enabled. Not via proxy. RecordContentLengthPrefs(kReceivedLength, kOriginalLength, false, UNKNOWN_TYPE, FakeNow()); // 15000 falls into the 12 KB bucket tester.ExpectUniqueSample("Net.DailyOriginalContentLength", 12, 1); tester.ExpectUniqueSample("Net.DailyOriginalContentLength_Application", 12, 1); tester.ExpectUniqueSample( "Net.DailyOriginalContentLength_DataReductionProxyEnabled", 12, 1); tester.ExpectUniqueSample( "Net.DailyOriginalContentLength_DataReductionProxyEnabled_Application", 12, 1); tester.ExpectUniqueSample( "Net.DailyOriginalContentLength_ViaDataReductionProxy", 12, 1); tester.ExpectUniqueSample( "Net.DailyOriginalContentLength_ViaDataReductionProxy_Application", 12, 1); // 10000 falls into the 9 KB bucket tester.ExpectUniqueSample("Net.DailyContentLength", 9, 1); tester.ExpectUniqueSample("Net.DailyReceivedContentLength_Application", 9, 1); tester.ExpectUniqueSample("Net.DailyContentLength_DataReductionProxyEnabled", 9, 1); tester.ExpectUniqueSample( "Net.DailyContentLength_DataReductionProxyEnabled_Application", 9, 1); tester.ExpectUniqueSample("Net.DailyContentLength_ViaDataReductionProxy", 9, 1); tester.ExpectUniqueSample( "Net.DailyContentLength_ViaDataReductionProxy_Application", 9, 1); // floor((15000 - 10000) * 100) = 33. tester.ExpectUniqueSample("Net.DailyContentSavingPercent", 33, 1); tester.ExpectUniqueSample( "Net.DailyContentSavingPercent_DataReductionProxyEnabled", 33, 1); tester.ExpectUniqueSample( "Net.DailyContentSavingPercent_ViaDataReductionProxy", 33, 1); tester.ExpectUniqueSample("Net.DailyContentPercent_DataReductionProxyEnabled", 100, 1); tester.ExpectUniqueSample("Net.DailyContentPercent_ViaDataReductionProxy", 100, 1); tester.ExpectUniqueSample( "Net.DailyContentPercent_DataReductionProxyEnabled_Unknown", 0, 1); } TEST_F(DataReductionProxyCompressionStatsTest, RecordDataUsageSingleSite) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); RecordDataUsage("https://www.foo.com", 1000, 1250, now); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 1).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.foo.com"); site_usage->set_data_used(1000); site_usage->set_original_size(1250); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, DisableDataUsageRecording) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); RecordDataUsage("https://www.foo.com", 1000, 1250, now); DisableDataUsageReporting(); base::RunLoop().RunUntilIdle(); #if !defined(OS_ANDROID) // Data usage on disk must be deleted. auto expected_data_usage1 = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); DataUsageLoadVerifier verifier1(std::move(expected_data_usage1)); LoadHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier1))); // Public API must return an empty array. auto expected_data_usage2 = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>(); DataUsageLoadVerifier verifier2(std::move(expected_data_usage2)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier2)), now); #else // For Android don't delete data usage. auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 1).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.foo.com"); site_usage->set_data_used(1000); site_usage->set_original_size(1250); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); #endif base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, RecordDataUsageMultipleSites) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); RecordDataUsage("https://www.foo.com", 1000, 1250, now); RecordDataUsage("https://bar.com", 1001, 1251, now); RecordDataUsage("http://foobar.com", 1002, 1252, now); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 1).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.foo.com"); site_usage->set_data_used(1000); site_usage->set_original_size(1250); site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("bar.com"); site_usage->set_data_used(1001); site_usage->set_original_size(1251); site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("foobar.com"); site_usage->set_data_used(1002); site_usage->set_original_size(1252); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, RecordDataUsageConsecutiveBuckets) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); base::Time fifteen_mins_ago = now - TimeDelta::FromMinutes(15); RecordDataUsage("https://www.foo.com", 1000, 1250, fifteen_mins_ago); RecordDataUsage("https://bar.com", 1001, 1251, now); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 2).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.foo.com"); site_usage->set_data_used(1000); site_usage->set_original_size(1250); connection_usage = expected_data_usage->at(kNumExpectedBuckets - 1).add_connection_usage(); site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("bar.com"); site_usage->set_data_used(1001); site_usage->set_original_size(1251); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); } // Test that the last entry in data usage bucket vector is for the current // interval even when current interval does not have any data usage. TEST_F(DataReductionProxyCompressionStatsTest, RecordDataUsageEmptyCurrentInterval) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); base::Time fifteen_mins_ago = now - TimeDelta::FromMinutes(15); RecordDataUsage("https://www.foo.com", 1000, 1250, fifteen_mins_ago); auto expected_data_usage = base::WrapUnique(new std::vector<data_reduction_proxy::DataUsageBucket>( kNumExpectedBuckets)); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 2).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.foo.com"); site_usage->set_data_used(1000); site_usage->set_original_size(1250); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, DeleteHistoricalDataUsage) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); base::Time fifteen_mins_ago = now - TimeDelta::FromMinutes(15); // Fake record to be from 15 minutes ago so that it is flushed to storage. RecordDataUsage("https://www.bar.com", 900, 1100, fifteen_mins_ago); RecordDataUsage("https://www.foo.com", 1000, 1250, now); DeleteHistoricalDataUsage(); base::RunLoop().RunUntilIdle(); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, DeleteBrowsingHistory) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); base::Time fifteen_mins_ago = now - TimeDelta::FromMinutes(15); // Fake record to be from 15 minutes ago so that it is flushed to storage. RecordDataUsage("https://www.bar.com", 900, 1100, fifteen_mins_ago); // This data usage will be in kept in memory. RecordDataUsage("https://www.foo.com", 1000, 1250, now); // This should only delete in-memory usage. DeleteBrowsingHistory(now, now); base::RunLoop().RunUntilIdle(); ASSERT_TRUE(DataUsageMap()->empty()); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); data_reduction_proxy::PerConnectionDataUsage* connection_usage = expected_data_usage->at(kNumExpectedBuckets - 1).add_connection_usage(); data_reduction_proxy::PerSiteDataUsage* site_usage = connection_usage->add_site_usage(); site_usage->set_hostname("www.bar.com"); site_usage->set_data_used(900); site_usage->set_original_size(1100); DataUsageLoadVerifier verifier1(std::move(expected_data_usage)); LoadHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier1))); base::RunLoop().RunUntilIdle(); // This should delete in-storage usage as well. DeleteBrowsingHistory(fifteen_mins_ago, now); base::RunLoop().RunUntilIdle(); expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); DataUsageLoadVerifier verifier2(std::move(expected_data_usage)); LoadHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier2))); base::RunLoop().RunUntilIdle(); } TEST_F(DataReductionProxyCompressionStatsTest, ClearDataSavingStatistics) { EnableDataUsageReporting(); base::RunLoop().RunUntilIdle(); base::Time now = base::Time::Now(); base::Time fifteen_mins_ago = now - TimeDelta::FromMinutes(15); // Fake record to be from 15 minutes ago so that it is flushed to storage. RecordDataUsage("https://www.bar.com", 900, 1100, fifteen_mins_ago); RecordDataUsage("https://www.foo.com", 1000, 1250, now); const int64_t kOriginalLength = 200; const int64_t kReceivedLength = 100; int64_t original[] = {kOriginalLength}; int64_t received[] = {kReceivedLength}; RecordContentLengthPrefs(kReceivedLength, kOriginalLength, true, VIA_DATA_REDUCTION_PROXY, FakeNow()); VerifyDailyDataSavingContentLengthPrefLists( original, 1, received, 1, original, 1, received, 1, original, 1, received, 1, kNumDaysInHistory); ClearDataSavingStatistics(); base::RunLoop().RunUntilIdle(); auto expected_data_usage = base::MakeUnique<std::vector<data_reduction_proxy::DataUsageBucket>>( kNumExpectedBuckets); DataUsageLoadVerifier verifier(std::move(expected_data_usage)); GetHistoricalDataUsage(base::Bind(&DataUsageLoadVerifier::OnLoadDataUsage, base::Unretained(&verifier)), now); base::RunLoop().RunUntilIdle(); VerifyDailyDataSavingContentLengthPrefLists(nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, nullptr, 0, 0); } } // namespace data_reduction_proxy
#include "fast_ber/ber_types/Identifier.hpp" #include "fast_ber/ber_types/Integer.hpp" #include "fast_ber/util/DecodeHelpers.hpp" #include "fast_ber/util/EncodeHelpers.hpp" #include <catch2/catch.hpp> TEST_CASE("Identifier: Encode ExplicitIdentifier") { fast_ber::Integer<> i(4); std::array<uint8_t, 100> buffer = {}; std::array<uint8_t, 3> expected = {0x02, 0x01, 0x04}; size_t enc_size = fast_ber::encoded_length(i); size_t size = fast_ber::encode(std::span<uint8_t>(buffer.data(), buffer.size()), i).length; REQUIRE(size == 3); REQUIRE(enc_size == 3); REQUIRE(std::span(buffer.data(), 3) == std::span(expected)); } TEST_CASE("Identifier: Encode TaggedExplicitIdentifier") { fast_ber::Integer<fast_ber::DoubleId<fast_ber::Id<fast_ber::Class::context_specific, 20>, fast_ber::ExplicitId<fast_ber::UniversalTag::integer>>> i(4); std::array<uint8_t, 100> buffer = {}; std::array<uint8_t, 5> expected = {0xB4, 0x03, 0x02, 0x01, 0x04}; size_t enc_size = fast_ber::encoded_length(i); size_t size = fast_ber::encode(std::span<uint8_t>(buffer.data(), buffer.size()), i).length; REQUIRE(size == 5); REQUIRE(enc_size == 5); REQUIRE(std::span(buffer.data(), 5) == std::span(expected)); } TEST_CASE("Identifier: Encode Id") { fast_ber::Integer<fast_ber::Id<fast_ber::Class::context_specific, 20>> i(4); std::array<uint8_t, 100> buffer = {}; std::array<uint8_t, 3> expected = {0x94, 0x01, 0x04}; size_t enc_size = fast_ber::encoded_length(i); size_t size = fast_ber::encode(std::span<uint8_t>(buffer.data(), buffer.size()), i).length; REQUIRE(size == 3); REQUIRE(enc_size == 3); REQUIRE(std::span(buffer.data(), 3) == std::span(expected)); } TEST_CASE("Identifier: Decode ExplicitIdentifier") { std::array<uint8_t, 3> data = {0x02, 0x01, 0x04}; auto iterator = fast_ber::BerViewIterator(std::span<uint8_t>(data.data(), data.size())); fast_ber::Integer<> i = 500; bool success = fast_ber::decode(iterator, i).success; REQUIRE(success); REQUIRE(i == 4); } TEST_CASE("Identifier: Decode TaggedExplicitIdentifier") { std::array<uint8_t, 5> data = {0xB4, 0x03, 0x02, 0x01, 0x04}; auto iterator = fast_ber::BerViewIterator(std::span<uint8_t>(data.data(), data.size())); fast_ber::Integer<fast_ber::DoubleId<fast_ber::Id<fast_ber::Class::context_specific, 20>, fast_ber::ExplicitId<fast_ber::UniversalTag::integer>>> i = 500; bool success = fast_ber::decode(iterator, i).success; REQUIRE(success); REQUIRE(i == 4); } TEST_CASE("Identifier: Decode Id") { std::array<uint8_t, 3> data = {0x94, 0x01, 0x04}; auto iterator = fast_ber::BerViewIterator(std::span<uint8_t>(data.data(), data.size())); fast_ber::Integer<fast_ber::Id<fast_ber::Class::context_specific, 20>> i = 500; bool success = fast_ber::decode(iterator, i).success; REQUIRE(success); REQUIRE(i == 4); }
#include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include <math.h> #include "FusionEKF.h" #include "tools.h" using namespace std; // for convenience using json = nlohmann::json; // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. std::string hasData(std::string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_first_of("]"); if (found_null != std::string::npos) { return ""; } else if (b1 != std::string::npos && b2 != std::string::npos) { return s.substr(b1, b2 - b1 + 1); } return ""; } int main() { uWS::Hub h; // Create a Kalman Filter instance FusionEKF fusionEKF; // used to compute the RMSE later Tools tools; vector<VectorXd> estimations; vector<VectorXd> ground_truth; h.onMessage([&fusionEKF,&tools,&estimations,&ground_truth](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(std::string(data)); if (s != "") { auto j = json::parse(s); std::string event = j[0].get<std::string>(); if (event == "telemetry") { // j[1] is the data JSON object string sensor_measurment = j[1]["sensor_measurement"]; MeasurementPackage meas_package; istringstream iss(sensor_measurment); long long timestamp; // reads first element from the current line string sensor_type; iss >> sensor_type; if (sensor_type.compare("L") == 0) { meas_package.sensor_type_ = MeasurementPackage::LASER; meas_package.raw_measurements_ = VectorXd(2); float px; float py; iss >> px; iss >> py; meas_package.raw_measurements_ << px, py; iss >> timestamp; meas_package.timestamp_ = timestamp; } else if (sensor_type.compare("R") == 0) { meas_package.sensor_type_ = MeasurementPackage::RADAR; meas_package.raw_measurements_ = VectorXd(3); float ro; float theta; float ro_dot; iss >> ro; iss >> theta; iss >> ro_dot; meas_package.raw_measurements_ << ro,theta, ro_dot; iss >> timestamp; meas_package.timestamp_ = timestamp; } float x_gt; float y_gt; float vx_gt; float vy_gt; iss >> x_gt; iss >> y_gt; iss >> vx_gt; iss >> vy_gt; VectorXd gt_values(4); gt_values(0) = x_gt; gt_values(1) = y_gt; gt_values(2) = vx_gt; gt_values(3) = vy_gt; ground_truth.push_back(gt_values); //Call ProcessMeasurment(meas_package) for Kalman filter fusionEKF.ProcessMeasurement(meas_package); //Push the current estimated x,y positon from the Kalman filter's state vector VectorXd estimate(4); double p_x = fusionEKF.ekf_.x_(0); double p_y = fusionEKF.ekf_.x_(1); double v1 = fusionEKF.ekf_.x_(2); double v2 = fusionEKF.ekf_.x_(3); estimate(0) = p_x; estimate(1) = p_y; estimate(2) = v1; estimate(3) = v2; estimations.push_back(estimate); VectorXd RMSE = tools.CalculateRMSE(estimations, ground_truth); json msgJson; msgJson["estimate_x"] = p_x; msgJson["estimate_y"] = p_y; msgJson["rmse_x"] = RMSE(0); msgJson["rmse_y"] = RMSE(1); msgJson["rmse_vx"] = RMSE(2); msgJson["rmse_vy"] = RMSE(3); auto msg = "42[\"estimate_marker\"," + msgJson.dump() + "]"; // std::cout << msg << std::endl; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { std::string msg = "42[\"manual\",{}]"; ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); // We don't need this since we're not using HTTP but if it's removed the program // doesn't compile :-( h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) { const std::string s = "<h1>Hello world!</h1>"; if (req.getUrl().valueLength == 1) { res->end(s.data(), s.length()); } else { // i guess this should be done more gracefully? res->end(nullptr, 0); } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { ws.close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen(port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }
#pragma once #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "amuse/AudioGroupData.hpp" #include "amuse/Common.hpp" namespace amuse { class ContainerRegistry { public: enum class Type { Invalid = -1, Raw4 = 0, MetroidPrime, MetroidPrime2, RogueSquadronPC, RogueSquadronN64, Factor5N64Rev, RogueSquadron2, RogueSquadron3 }; struct SongData { std::unique_ptr<uint8_t[]> m_data; size_t m_size; int16_t m_groupId; int16_t m_setupId; SongData(std::unique_ptr<uint8_t[]>&& data, size_t size, int16_t groupId, int16_t setupId) : m_data(std::move(data)), m_size(size), m_groupId(groupId), m_setupId(setupId) {} }; static const char* TypeToName(Type tp); static Type DetectContainerType(const char* path); static std::vector<std::pair<std::string, IntrusiveAudioGroupData>> LoadContainer(const char* path); static std::vector<std::pair<std::string, IntrusiveAudioGroupData>> LoadContainer(const char* path, Type& typeOut); static std::vector<std::pair<std::string, SongData>> LoadSongs(const char* path); }; } // namespace amuse
#ifndef MS_FUZZER_RTC_RTCP_FEEDBACK_PS #define MS_FUZZER_RTC_RTCP_FEEDBACK_PS #include "common.hpp" #include "RTC/RTCP/Packet.hpp" namespace Fuzzer { namespace RTC { namespace RTCP { namespace FeedbackPs { void Fuzz(::RTC::RTCP::Packet* packet); } } // namespace RTCP } // namespace RTC } // namespace Fuzzer #endif
#include <algorithm> #include <iostream> #include <map> #include <queue> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <unordered_set> #include <vector> using namespace std; typedef unsigned long long ull; typedef pair<int, int> ipair; class Tree { public: int i = -1; Tree *parent = nullptr; Tree *l = nullptr; Tree *r = nullptr; Tree() : i(-1), l(nullptr), r(nullptr), parent(nullptr){}; Tree(int _i) : i(_i){}; void print() { if (i == -1 && l != nullptr && r != nullptr) { // printf("{%d}[", lvl); printf("["); l->print(); printf(","); r->print(); printf("]"); } else { printf("%d", i); } } Tree *copy() { Tree *ret = new Tree(); if (i == -1) { Tree *left = l->copy(); Tree *right = r->copy(); ret->l = left; ret->l->parent = ret; ret->r = right; ret->r->parent = ret; } ret->i = i; return ret; } bool explode(int lvl) { if (i != -1) { return false; } else if (lvl > 4 && (l->i != -1 || r->i != -1)) { // printf("to explode %d %d\n", l->i, r->i); parent->distributeUp(true, l->i, this); // printf("to exploded r\n"); parent->distributeUp(false, r->i, this); i = 0; // delete l; // delete r; // l = nullptr; // r = nullptr; // printf("exploded "); return true; } else { return l->explode(lvl + 1) || r->explode(lvl + 1); } } bool split() { if (i == -1) { return l->split() || r->split(); } else if (i > 9) { int half = i / 2; l = new Tree(half); if (i % 2 == 0) { r = new Tree(half); } else { r = new Tree(half + 1); } r->parent = this; l->parent = this; i = -1; // printf("split "); return true; } else { return false; } } Tree *add(Tree *r) { Tree *ret = new Tree(); ret->l = this; ret->r = r; ret->l->parent = ret; ret->r->parent = ret; while (ret->explode(1) || ret->split()) { } return ret; } int mag() { if (i == -1) { return (3 * l->mag()) + (2 * r->mag()); } else { return i; } } private: void distributeDown(bool left, int num) { Tree *child = left ? l : r; if (i == -1) child->distributeDown(left, num); else { i += num; } } void distributeUp(bool left, int num, Tree *prev) { // printf("distribute up %d %d\n", r, parent); Tree *child = left ? l : r; if (prev == child) { if (parent != nullptr) { parent->distributeUp(left, num, this); } } else { child->distributeDown(!left, num); } } }; Tree *parse(stringstream &s) { Tree *tree = new Tree(); if (s.peek() == '[') { s.ignore(); Tree *l = parse(s); s.ignore(); Tree *r = parse(s); s.ignore(); l->parent = tree; tree->l = l; r->parent = tree; tree->r = r; } else { int num; s >> num; tree->i = num; } return tree; }; int main() { string s; vector<Tree *> exprss; for (; getline(cin, s);) { stringstream ss(s); exprss.push_back(parse(ss)); } int maxMag = 0; for (int i = 0; i < exprss.size(); i++) { for (int j = i; j < exprss.size(); j++) { // exprss[i]->print(); // exprss[j]->print(); // printf("\n"); Tree *expr = exprss[i]->copy()->add(exprss[j]->copy()); int mag = expr->mag(); if (maxMag < mag) { maxMag = mag; } // printf("mag: %d\n", mag); // exprss[i]->print(); // printf(" "); // exprss[j]->print(); // printf("\n"); } } printf("%d\n", maxMag); return 0; }
/* * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file implements the OpenThread SRP client buffers and service pool APIs. */ #include "openthread-core-config.h" #include <openthread/srp_client_buffers.h> #include "common/instance.hpp" #include "common/locator-getters.hpp" #include "utils/srp_client_buffers.hpp" using namespace ot; #if OPENTHREAD_CONFIG_SRP_CLIENT_BUFFERS_ENABLE char *otSrpClientBuffersGetHostNameString(otInstance *aInstance, uint16_t *aSize) { Instance &instance = *static_cast<Instance *>(aInstance); return instance.Get<Utils::SrpClientBuffers>().GetHostNameString(*aSize); } otIp6Address *otSrpClientBuffersGetHostAddressesArray(otInstance *aInstance, uint8_t *aArrayLength) { Instance &instance = *static_cast<Instance *>(aInstance); return instance.Get<Utils::SrpClientBuffers>().GetHostAddressesArray(*aArrayLength); } otSrpClientBuffersServiceEntry *otSrpClientBuffersAllocateService(otInstance *aInstance) { Instance &instance = *static_cast<Instance *>(aInstance); return instance.Get<Utils::SrpClientBuffers>().AllocateService(); } void otSrpClientBuffersFreeService(otInstance *aInstance, otSrpClientBuffersServiceEntry *aService) { Instance &instance = *static_cast<Instance *>(aInstance); instance.Get<Utils::SrpClientBuffers>().FreeService( *static_cast<Utils::SrpClientBuffers::ServiceEntry *>(aService)); } void otSrpClientBuffersFreeAllServices(otInstance *aInstance) { Instance &instance = *static_cast<Instance *>(aInstance); instance.Get<Utils::SrpClientBuffers>().FreeAllServices(); } char *otSrpClientBuffersGetServiceEntryServiceNameString(otSrpClientBuffersServiceEntry *aEntry, uint16_t *aSize) { return static_cast<Utils::SrpClientBuffers::ServiceEntry *>(aEntry)->GetServiceNameString(*aSize); } char *otSrpClientBuffersGetServiceEntryInstanceNameString(otSrpClientBuffersServiceEntry *aEntry, uint16_t *aSize) { return static_cast<Utils::SrpClientBuffers::ServiceEntry *>(aEntry)->GetInstanceNameString(*aSize); } uint8_t *otSrpClientBuffersGetServiceEntryTxtBuffer(otSrpClientBuffersServiceEntry *aEntry, uint16_t *aSize) { return static_cast<Utils::SrpClientBuffers::ServiceEntry *>(aEntry)->GetTxtBuffer(*aSize); } #endif // OPENTHREAD_CONFIG_SRP_CLIENT_BUFFERS_ENABLE
#include <iostream> #include <string> #include "myclass.h" using namespace std; int main() { Customer user("Tom", "8IENVO3VN10N4030V3NA0V303NVQ3"); user.printname(); user.printID(); return 0; }
/* * JackAss VST plugin * Copyright (C) 2013-2014 Filipe Coelho <falktx@falktx.com> * * Permission to use, copy, modify, and/or distribute this software for any purpose with * or without fee is hereby granted, provided that the above copyright notice and this * permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD * TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN * NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <cstdio> #include <cstdlib> #include <cstring> #include <list> #include <pthread.h> #ifndef __cdecl # define __cdecl #endif #include "jackbridge/JackBridge.cpp" #include "public.sdk/source/vst2.x/audioeffect.cpp" #include "public.sdk/source/vst2.x/audioeffectx.cpp" #include "public.sdk/source/vst2.x/vstplugmain.cpp" // ------------------------------------------------- // uncomment to enable midi-programs //#define USE_PROGRAMS // ------------------------------------------------- // Parameters static const unsigned char kParamMap[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53, 0x54, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F }; static const int kParamVolume = 5; static const int kParamBalance = 6; static const int kParamPan = 8; static const int kParamCount = sizeof(kParamMap); #ifdef USE_PROGRAMS static const int kProgramCount = 128; #else static const int kProgramCount = 0; #endif // ------------------------------------------------- // Data limits static const int kMaxMidiEvents = 512; static const int kProgramNameSize = 32; // ------------------------------------------------- // Midi data struct midi_data_t { unsigned char data[4]; unsigned char size; VstInt32 time; midi_data_t() : size(0), time(0) { std::memset(data, 0, 4*sizeof(char)); } }; // ------------------------------------------------- // Global JACK client static jack_client_t* gJackClient = nullptr; static volatile bool gNeedMidiResend = false; // ------------------------------------------------- // single JackAss instance, containing 1 MIDI port class JackAssInstance { public: JackAssInstance(jack_port_t* const port) : fPort(port) { pthread_mutex_init(&fMutex, nullptr); } ~JackAssInstance() { pthread_mutex_lock(&fMutex); pthread_mutex_unlock(&fMutex); pthread_mutex_destroy(&fMutex); if (fPort != nullptr) { if (gJackClient != nullptr) jackbridge_port_unregister(gJackClient, fPort); fPort = nullptr; } } void putEvent(const unsigned char data[4], const unsigned char size, const VstInt32 time) { pthread_mutex_lock(&fMutex); for (int i=0; i < kMaxMidiEvents; ++i) { if (fData[i].data[0] != 0) continue; fData[i].data[0] = data[0]; fData[i].data[1] = data[1]; fData[i].data[2] = data[2]; fData[i].data[3] = data[3]; fData[i].size = size; fData[i].time = time; break; } pthread_mutex_unlock(&fMutex); } void putEvent(const unsigned char data1, const unsigned char data2, const unsigned char data3, const unsigned char size, const VstInt32 time) { const unsigned char data[4] = { data1, data2, data3, 0 }; putEvent(data, size, time); } void jprocess(const jack_nframes_t nframes) { void* const portBuffer(jackbridge_port_get_buffer(fPort, nframes)); if (portBuffer == nullptr) return; jackbridge_midi_clear_buffer(portBuffer); pthread_mutex_lock(&fMutex); for (int i=0; i < kMaxMidiEvents; ++i) { if (fData[i].data[0] == 0) break; if (unsigned char* const buffer = jackbridge_midi_event_reserve(portBuffer, fData[i].time, fData[i].size)) std::memcpy(buffer, fData[i].data, fData[i].size); fData[i].data[0] = 0; // set as invalid } pthread_mutex_unlock(&fMutex); } private: jack_port_t* fPort; midi_data_t fData[kMaxMidiEvents]; pthread_mutex_t fMutex; }; // ------------------------------------------------- // static list of JackAss instances static std::list<JackAssInstance*> gInstances; static pthread_mutex_t gInstancesMutex = PTHREAD_MUTEX_INITIALIZER; // ------------------------------------------------- // JACK calls static int jprocess_callback(const jack_nframes_t nframes, void*) { pthread_mutex_lock(&gInstancesMutex); for (std::list<JackAssInstance*>::iterator it = gInstances.begin(), end = gInstances.end(); it != end; ++it) (*it)->jprocess(nframes); pthread_mutex_unlock(&gInstancesMutex); return 0; } static void jconnect_callback(const jack_port_id_t a, const jack_port_id_t b, const int connect_, void*) { if (connect_ == 0) return; if (jackbridge_port_is_mine(gJackClient, jackbridge_port_by_id(gJackClient, a)) || jackbridge_port_is_mine(gJackClient, jackbridge_port_by_id(gJackClient, b))) gNeedMidiResend = true; } // ------------------------------------------------- // JackAss plugin class JackAss : public AudioEffectX { public: JackAss(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, kProgramCount, kParamCount), fInstance(nullptr) { for (int i=0; i < kParamCount; ++i) fParamBuffers[i] = 0.0f; fParamBuffers[kParamVolume] = 100.0f/127.0f; fParamBuffers[kParamBalance] = 0.5f; fParamBuffers[kParamPan] = 0.5f; #ifdef USE_PROGRAMS for (int i=0; i < kProgramCount; ++i) { fProgramNames[i] = new char[kProgramNameSize+1]; std::snprintf(fProgramNames[i], kProgramNameSize, "Program #%i", i+1); fProgramNames[i][kProgramNameSize] = '\0'; } #endif if (audioMaster == nullptr) return; #ifdef JACKASS_SYNTH isSynth(); setNumInputs(0); setNumOutputs(2); setUniqueID(CCONST('J', 'A', 's', 's')); #else setNumInputs(2); setNumOutputs(2); setUniqueID(CCONST('J', 'A', 's', 'x')); #endif char strBuf[0xff+1]; // Register global JACK client if needed if (gJackClient == nullptr) { std::memset(strBuf, 0, sizeof(char)*0xff+1); if (getHostProductString(strBuf) && strBuf[0] != '\0') { char tmp[std::strlen(strBuf)+1]; std::strcpy(tmp, strBuf); #ifdef JACKASS_SYNTH std::strcpy(strBuf, "JackAss-"); #else std::strcpy(strBuf, "JackAssFX-"); #endif std::strncat(strBuf, tmp, 0xff-11); strBuf[0xff] = '\0'; } else { #ifdef JACKASS_SYNTH std::strcpy(strBuf, "JackAss"); #else std::strcpy(strBuf, "JackAssFX"); #endif } gJackClient = jackbridge_client_open(strBuf, JackNullOption, nullptr); if (gJackClient == nullptr) return; jackbridge_set_port_connect_callback(gJackClient, jconnect_callback, nullptr); jackbridge_set_process_callback(gJackClient, jprocess_callback, nullptr); jackbridge_activate(gJackClient); } // Create instance + jack-port for this plugin std::sprintf(strBuf, "midi-out_%02u", (int)gInstances.size() + 1); if (jack_port_t* const jport = jackbridge_port_register(gJackClient, strBuf, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0)) { fInstance = new JackAssInstance(jport); pthread_mutex_lock(&gInstancesMutex); gInstances.push_back(fInstance); pthread_mutex_unlock(&gInstancesMutex); } } ~JackAss() override { #ifdef USE_PROGRAMS for (int i=0; i < kProgramCount; ++i) { if (fProgramNames[i] != nullptr) { delete[] fProgramNames[i]; fProgramNames[i] = nullptr; } } #endif if (fInstance != nullptr) { pthread_mutex_lock(&gInstancesMutex); gInstances.remove(fInstance); pthread_mutex_unlock(&gInstancesMutex); delete fInstance; fInstance = nullptr; } // Close global JACK client if needed if (gJackClient != nullptr && gInstances.size() == 0) { jackbridge_deactivate(gJackClient); jackbridge_client_close(gJackClient); gJackClient = nullptr; } } // --------------------------------------------- void processReplacing(float** inputs, float** const outputs, const VstInt32 sampleFrames) override { #ifdef JACKASS_SYNTH // Silent output std::memset(outputs[0], 0, sizeof(float)*sampleFrames); std::memset(outputs[1], 0, sizeof(float)*sampleFrames); #else // Bypass std::memcpy(outputs[0], inputs[0], sizeof(float)*sampleFrames); std::memcpy(outputs[1], inputs[1], sizeof(float)*sampleFrames); #endif if (gNeedMidiResend && fInstance != nullptr) { for (int i=0; i < kParamCount; ++i) fInstance->putEvent(0xB0, kParamMap[i], int(fParamBuffers[i]*127.0f), 3, 0); gNeedMidiResend = false; } #ifdef JACKASS_SYNTH return; // unused (void)inputs; #endif } #ifdef JACKASS_SYNTH VstInt32 processEvents(VstEvents* const events) override { if (fInstance == nullptr || events == nullptr) return 0; // FIXME? for (VstInt32 i=0; i < events->numEvents; ++i) { if (events->events[i] == nullptr) break; if (events->events[i]->type != kVstMidiType) continue; VstMidiEvent* const midiEvent((VstMidiEvent*)events->events[i]); fInstance->putEvent(midiEvent->midiData[0], midiEvent->midiData[1], midiEvent->midiData[2], 3, midiEvent->deltaFrames); } return 0; } #endif // --------------------------------------------- #ifdef USE_PROGRAMS void setProgram(const VstInt32 program) override { if (curProgram < 0 || curProgram >= kProgramCount) return; if (fInstance != nullptr) { // bank select fInstance->putEvent(0xB0, 0x00, 0, 3, 0); // program select fInstance->putEvent(0xC0, program, 0, 2, 0); } AudioEffectX::setProgram(program); } void setProgramName(char* const name) override { if (curProgram < 0 || curProgram >= kProgramCount) return; std::strncpy(fProgramNames[curProgram], name, kProgramNameSize); } void getProgramName(char* const name) override { if (curProgram < 0 || curProgram >= kProgramCount) return AudioEffectX::getProgramName(name); // TODO: REMOVE std::strncpy(name, fProgramNames[curProgram], kVstMaxProgNameLen); } #endif // --------------------------------------------- void setParameter(const VstInt32 index, const float value) override { if (index < 0 || index >= kParamCount) return; if (fParamBuffers[index] != value) { fParamBuffers[index] = value; if (fInstance != nullptr) fInstance->putEvent(0xB0, kParamMap[index], int(value*127.0f), 3, 0); } } float getParameter(const VstInt32 index) override { if (index < 0 || index >= kParamCount) return 0.0f; return fParamBuffers[index]; } void getParameterLabel(const VstInt32 index, char* const label) override { // TODO AudioEffectX::getParameterLabel(index, label); } void getParameterDisplay(const VstInt32 index, char* const text) override { if (index < 0 || index >= kParamCount) return AudioEffectX::getParameterDisplay(index, text); // TODO: REMOVE char strBuf[kVstMaxParamStrLen+1]; std::snprintf(strBuf, kVstMaxParamStrLen, "%i", int(fParamBuffers[index]*127.0f)); strBuf[kVstMaxParamStrLen] = '\0'; std::strncpy(text, strBuf, kVstMaxParamStrLen); } void getParameterName(const VstInt32 index, char* const text) override { if (index < 0 || index >= kParamCount) return AudioEffectX::getParameterName(index, text); // TODO: REMOVE static const int kMaxParamLen = 18+1; //28; switch (kParamMap[index]) { case 0x01: std::strncpy(text, "0x01 Modulation", kMaxParamLen); break; case 0x02: std::strncpy(text, "0x02 Breath", kMaxParamLen); break; case 0x03: std::strncpy(text, "0x03 (Undefined)", kMaxParamLen); break; case 0x04: std::strncpy(text, "0x04 Foot", kMaxParamLen); break; case 0x05: std::strncpy(text, "0x05 Portamento", kMaxParamLen); break; case 0x07: std::strncpy(text, "0x07 Volume", kMaxParamLen); break; case 0x08: std::strncpy(text, "0x08 Balance", kMaxParamLen); break; case 0x09: std::strncpy(text, "0x09 (Undefined)", kMaxParamLen); break; case 0x0A: std::strncpy(text, "0x0A Pan", kMaxParamLen); break; case 0x0B: std::strncpy(text, "0x0B Expression", kMaxParamLen); break; case 0x0C: std::strncpy(text, "0x0C FX Control 1", kMaxParamLen); break; case 0x0D: std::strncpy(text, "0x0D FX Control 2", kMaxParamLen); break; case 0x0E: std::strncpy(text, "0x0E (Undefined)", kMaxParamLen); break; case 0x0F: std::strncpy(text, "0x0F (Undefined)", kMaxParamLen); break; case 0x10: std::strncpy(text, "0x10 Gen Purpose 1", kMaxParamLen); break; case 0x11: std::strncpy(text, "0x11 Gen Purpose 2", kMaxParamLen); break; case 0x12: std::strncpy(text, "0x12 Gen Purpose 3", kMaxParamLen); break; case 0x13: std::strncpy(text, "0x13 Gen Purpose 4", kMaxParamLen); break; case 0x14: std::strncpy(text, "0x14 (Undefined)", kMaxParamLen); break; case 0x15: std::strncpy(text, "0x15 (Undefined)", kMaxParamLen); break; case 0x16: std::strncpy(text, "0x16 (Undefined)", kMaxParamLen); break; case 0x17: std::strncpy(text, "0x17 (Undefined)", kMaxParamLen); break; case 0x18: std::strncpy(text, "0x18 (Undefined)", kMaxParamLen); break; case 0x19: std::strncpy(text, "0x19 (Undefined)", kMaxParamLen); break; case 0x1A: std::strncpy(text, "0x1A (Undefined)", kMaxParamLen); break; case 0x1B: std::strncpy(text, "0x1B (Undefined)", kMaxParamLen); break; case 0x1C: std::strncpy(text, "0x1C (Undefined)", kMaxParamLen); break; case 0x1D: std::strncpy(text, "0x1D (Undefined)", kMaxParamLen); break; case 0x1E: std::strncpy(text, "0x1E (Undefined)", kMaxParamLen); break; case 0x1F: std::strncpy(text, "0x1F (Undefined)", kMaxParamLen); break; case 0x46: std::strncpy(text, "0x46 Control 1", kMaxParamLen); // [Variation] break; case 0x47: std::strncpy(text, "0x47 Control 2", kMaxParamLen); // [Timbre] break; case 0x48: std::strncpy(text, "0x48 Control 3", kMaxParamLen); // [Release] break; case 0x49: std::strncpy(text, "0x49 Control 4", kMaxParamLen); // [Attack] break; case 0x4A: std::strncpy(text, "0x4A Control 5", kMaxParamLen); // [Brightness] break; case 0x4B: std::strncpy(text, "0x4B Control 6", kMaxParamLen); // [Decay] break; case 0x4C: std::strncpy(text, "0x4C Control 7", kMaxParamLen); // [Vib Rate] break; case 0x4D: std::strncpy(text, "0x4D Control 8", kMaxParamLen); // [Vib Depth] break; case 0x4E: std::strncpy(text, "0x4E Control 9", kMaxParamLen); // [Vib Delay] break; case 0x4F: std::strncpy(text, "0x4F Control 10", kMaxParamLen); // [Undefined] break; case 0x50: std::strncpy(text, "0x50 Gen Purpose 5", kMaxParamLen); break; case 0x51: std::strncpy(text, "0x51 Gen Purpose 6", kMaxParamLen); break; case 0x52: std::strncpy(text, "0x52 Gen Purpose 7", kMaxParamLen); break; case 0x53: std::strncpy(text, "0x53 Gen Purpose 8", kMaxParamLen); break; case 0x54: std::strncpy(text, "0x54 Portamento", kMaxParamLen); break; case 0x5B: std::strncpy(text, "0x5B FX 1 Depth", kMaxParamLen); // [Reverb] break; case 0x5C: std::strncpy(text, "0x5C FX 2 Depth", kMaxParamLen); // [Tremolo] break; case 0x5D: std::strncpy(text, "0x5D FX 3 Depth", kMaxParamLen); // [Chorus] break; case 0x5E: std::strncpy(text, "0x5E FX 4 Depth", kMaxParamLen); // [Detune] break; case 0x5F: std::strncpy(text, "0x5F FX 5 Depth", kMaxParamLen); // [Phaser] break; default: AudioEffectX::getParameterName(index, text); // TODO: REMOVE break; } } // --------------------------------------------- bool getEffectName(char* const name) override { #ifdef JACKASS_SYNTH std::strncpy(name, "JackAss", kVstMaxEffectNameLen); #else std::strncpy(name, "JackAssFX", kVstMaxEffectNameLen); #endif return true; } bool getProductString(char* const text) override { #ifdef JACKASS_SYNTH std::strncpy(text, "JackAss", kVstMaxProductStrLen); #else std::strncpy(text, "JackAssFX", kVstMaxProductStrLen); #endif return true; } bool getVendorString(char* const text) override { std::strncpy(text, "falkTX", kVstMaxVendorStrLen); return true; } VstInt32 getVendorVersion() override { return 1000; } VstInt32 canDo(char* const text) override { #ifdef JACKASS_SYNTH if (std::strcmp(text, "receiveVstEvents") == 0) return 1; if (std::strcmp(text, "receiveVstMidiEvent") == 0) return 1; #endif return -1; // maybe unused (void)text; } VstPlugCategory getPlugCategory() override { #ifdef JACKASS_SYNTH return kPlugCategSynth; #else return kPlugCategEffect; #endif } // --------------------------------------------- VstInt32 getNumMidiInputChannels() override { #ifdef JACKASS_SYNTH return 16; #else return 0; #endif } VstInt32 getNumMidiOutputChannels() override { return 0; } // --------------------------------------------- private: JackAssInstance* fInstance; float fParamBuffers[kParamCount]; #ifdef USE_PROGRAMS char* fProgramNames[kProgramCount]; #endif }; // ------------------------------------------------- // DLL entry point AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { return new JackAss(audioMaster); } // -------------------------------------------------
#include "extensions/filters/http/ip_tagging/ip_tagging_filter.h" #include "envoy/api/v3alpha/core/address.pb.h" #include "envoy/config/filter/http/ip_tagging/v3alpha/ip_tagging.pb.h" #include "common/http/header_map_impl.h" #include "common/http/headers.h" #include "absl/strings/str_join.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace IpTagging { IpTaggingFilterConfig::IpTaggingFilterConfig( const envoy::config::filter::http::ip_tagging::v3alpha::IPTagging& config, const std::string& stat_prefix, Stats::Scope& scope, Runtime::Loader& runtime) : request_type_(requestTypeEnum(config.request_type())), scope_(scope), runtime_(runtime), stat_name_set_(scope.symbolTable().makeSet("IpTagging")), stats_prefix_(stat_name_set_->add(stat_prefix + "ip_tagging")), hit_(stat_name_set_->add("hit")), no_hit_(stat_name_set_->add("no_hit")), total_(stat_name_set_->add("total")) { // Once loading IP tags from a file system is supported, the restriction on the size // of the set should be removed and observability into what tags are loaded needs // to be implemented. // TODO(ccaraman): Remove size check once file system support is implemented. // Work is tracked by issue https://github.com/envoyproxy/envoy/issues/2695. if (config.ip_tags().empty()) { throw EnvoyException("HTTP IP Tagging Filter requires ip_tags to be specified."); } std::vector<std::pair<std::string, std::vector<Network::Address::CidrRange>>> tag_data; tag_data.reserve(config.ip_tags().size()); for (const auto& ip_tag : config.ip_tags()) { std::vector<Network::Address::CidrRange> cidr_set; cidr_set.reserve(ip_tag.ip_list().size()); for (const envoy::api::v3alpha::core::CidrRange& entry : ip_tag.ip_list()) { // Currently, CidrRange::create doesn't guarantee that the CidrRanges are valid. Network::Address::CidrRange cidr_entry = Network::Address::CidrRange::create(entry); if (cidr_entry.isValid()) { cidr_set.emplace_back(std::move(cidr_entry)); } else { throw EnvoyException( fmt::format("invalid ip/mask combo '{}/{}' (format is <ip>/<# mask bits>)", entry.address_prefix(), entry.prefix_len().value())); } } tag_data.emplace_back(ip_tag.ip_tag_name(), cidr_set); } trie_ = std::make_unique<Network::LcTrie::LcTrie<std::string>>(tag_data); } void IpTaggingFilterConfig::incCounter(Stats::StatName name, absl::string_view tag) { Stats::SymbolTable::StoragePtr storage = scope_.symbolTable().join({stats_prefix_, stat_name_set_->getDynamic(tag), name}); scope_.counterFromStatName(Stats::StatName(storage.get())).inc(); } IpTaggingFilter::IpTaggingFilter(IpTaggingFilterConfigSharedPtr config) : config_(config) {} IpTaggingFilter::~IpTaggingFilter() = default; void IpTaggingFilter::onDestroy() {} Http::FilterHeadersStatus IpTaggingFilter::decodeHeaders(Http::HeaderMap& headers, bool) { const bool is_internal_request = headers.EnvoyInternalRequest() && (headers.EnvoyInternalRequest()->value() == Http::Headers::get().EnvoyInternalRequestValues.True.c_str()); if ((is_internal_request && config_->requestType() == FilterRequestType::EXTERNAL) || (!is_internal_request && config_->requestType() == FilterRequestType::INTERNAL) || !config_->runtime().snapshot().featureEnabled("ip_tagging.http_filter_enabled", 100)) { return Http::FilterHeadersStatus::Continue; } std::vector<std::string> tags = config_->trie().getData(callbacks_->streamInfo().downstreamRemoteAddress()); if (!tags.empty()) { const std::string tags_join = absl::StrJoin(tags, ","); headers.appendEnvoyIpTags(tags_join, ","); // We must clear the route cache or else we can't match on x-envoy-ip-tags. callbacks_->clearRouteCache(); // For a large number(ex > 1000) of tags, stats cardinality will be an issue. // If there are use cases with a large set of tags, a way to opt into these stats // should be exposed and other observability options like logging tags need to be implemented. for (const std::string& tag : tags) { config_->incHit(tag); } } else { config_->incNoHit(); } config_->incTotal(); return Http::FilterHeadersStatus::Continue; } Http::FilterDataStatus IpTaggingFilter::decodeData(Buffer::Instance&, bool) { return Http::FilterDataStatus::Continue; } Http::FilterTrailersStatus IpTaggingFilter::decodeTrailers(Http::HeaderMap&) { return Http::FilterTrailersStatus::Continue; } void IpTaggingFilter::setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) { callbacks_ = &callbacks; } } // namespace IpTagging } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
/* * libjingle * Copyright 2013, Google 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. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "talk/app/webrtc/test/peerconnectiontestwrapper.h" #include "talk/app/webrtc/test/mockpeerconnectionobservers.h" #include "talk/base/gunit.h" #include "talk/base/logging.h" #include "talk/base/ssladapter.h" #include "talk/base/sslstreamadapter.h" #include "talk/base/stringencode.h" #include "talk/base/stringutils.h" #define MAYBE_SKIP_TEST(feature) \ if (!(feature())) { \ LOG(LS_INFO) << "Feature disabled... skipping"; \ return; \ } using webrtc::DataChannelInterface; using webrtc::FakeConstraints; using webrtc::MediaConstraintsInterface; using webrtc::MediaStreamInterface; using webrtc::PeerConnectionInterface; namespace { const char kExternalGiceUfrag[] = "1234567890123456"; const char kExternalGicePwd[] = "123456789012345678901234"; const size_t kMaxWait = 10000; void RemoveLinesFromSdp(const std::string& line_start, std::string* sdp) { const char kSdpLineEnd[] = "\r\n"; size_t ssrc_pos = 0; while ((ssrc_pos = sdp->find(line_start, ssrc_pos)) != std::string::npos) { size_t end_ssrc = sdp->find(kSdpLineEnd, ssrc_pos); sdp->erase(ssrc_pos, end_ssrc - ssrc_pos + strlen(kSdpLineEnd)); } } // Add |newlines| to the |message| after |line|. void InjectAfter(const std::string& line, const std::string& newlines, std::string* message) { const std::string tmp = line + newlines; talk_base::replace_substrs(line.c_str(), line.length(), tmp.c_str(), tmp.length(), message); } void Replace(const std::string& line, const std::string& newlines, std::string* message) { talk_base::replace_substrs(line.c_str(), line.length(), newlines.c_str(), newlines.length(), message); } void UseExternalSdes(std::string* sdp) { // Remove current crypto specification. RemoveLinesFromSdp("a=crypto", sdp); RemoveLinesFromSdp("a=fingerprint", sdp); // Add external crypto. const char kAudioSdes[] = "a=crypto:1 AES_CM_128_HMAC_SHA1_80 " "inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR\r\n"; const char kVideoSdes[] = "a=crypto:1 AES_CM_128_HMAC_SHA1_80 " "inline:d0RmdmcmVCspeEc3QGZiNWpVLFJhQX1cfHAwJSoj\r\n"; const char kDataSdes[] = "a=crypto:1 AES_CM_128_HMAC_SHA1_80 " "inline:NzB4d1BINUAvLEw6UzF3WSJ+PSdFcGdUJShpX1Zj\r\n"; InjectAfter("a=mid:audio\r\n", kAudioSdes, sdp); InjectAfter("a=mid:video\r\n", kVideoSdes, sdp); InjectAfter("a=mid:data\r\n", kDataSdes, sdp); } void UseGice(std::string* sdp) { InjectAfter("t=0 0\r\n", "a=ice-options:google-ice\r\n", sdp); std::string ufragline = "a=ice-ufrag:"; std::string pwdline = "a=ice-pwd:"; RemoveLinesFromSdp(ufragline, sdp); RemoveLinesFromSdp(pwdline, sdp); ufragline.append(kExternalGiceUfrag); ufragline.append("\r\n"); pwdline.append(kExternalGicePwd); pwdline.append("\r\n"); const std::string ufrag_pwd = ufragline + pwdline; InjectAfter("a=mid:audio\r\n", ufrag_pwd, sdp); InjectAfter("a=mid:video\r\n", ufrag_pwd, sdp); InjectAfter("a=mid:data\r\n", ufrag_pwd, sdp); } void RemoveBundle(std::string* sdp) { RemoveLinesFromSdp("a=group:BUNDLE", sdp); } } // namespace class PeerConnectionEndToEndTest : public sigslot::has_slots<>, public testing::Test { public: typedef std::vector<talk_base::scoped_refptr<DataChannelInterface> > DataChannelList; PeerConnectionEndToEndTest() : caller_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>( "caller")), callee_(new talk_base::RefCountedObject<PeerConnectionTestWrapper>( "callee")) { talk_base::InitializeSSL(NULL); } void CreatePcs() { CreatePcs(NULL); } void CreatePcs(const MediaConstraintsInterface* pc_constraints) { EXPECT_TRUE(caller_->CreatePc(pc_constraints)); EXPECT_TRUE(callee_->CreatePc(pc_constraints)); PeerConnectionTestWrapper::Connect(caller_.get(), callee_.get()); caller_->SignalOnDataChannel.connect( this, &PeerConnectionEndToEndTest::OnCallerAddedDataChanel); callee_->SignalOnDataChannel.connect( this, &PeerConnectionEndToEndTest::OnCalleeAddedDataChannel); } void GetAndAddUserMedia() { FakeConstraints audio_constraints; FakeConstraints video_constraints; GetAndAddUserMedia(true, audio_constraints, true, video_constraints); } void GetAndAddUserMedia(bool audio, FakeConstraints audio_constraints, bool video, FakeConstraints video_constraints) { caller_->GetAndAddUserMedia(audio, audio_constraints, video, video_constraints); callee_->GetAndAddUserMedia(audio, audio_constraints, video, video_constraints); } void Negotiate() { caller_->CreateOffer(NULL); } void WaitForCallEstablished() { caller_->WaitForCallEstablished(); callee_->WaitForCallEstablished(); } void WaitForConnection() { caller_->WaitForConnection(); callee_->WaitForConnection(); } void SetupLegacySdpConverter() { caller_->SignalOnSdpCreated.connect( this, &PeerConnectionEndToEndTest::ConvertToLegacySdp); callee_->SignalOnSdpCreated.connect( this, &PeerConnectionEndToEndTest::ConvertToLegacySdp); } void ConvertToLegacySdp(std::string* sdp) { UseExternalSdes(sdp); UseGice(sdp); RemoveBundle(sdp); LOG(LS_INFO) << "ConvertToLegacySdp: " << *sdp; } void SetupGiceConverter() { caller_->SignalOnIceCandidateCreated.connect( this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate); callee_->SignalOnIceCandidateCreated.connect( this, &PeerConnectionEndToEndTest::AddGiceCredsToCandidate); } void AddGiceCredsToCandidate(std::string* sdp) { std::string gice_creds = " username "; gice_creds.append(kExternalGiceUfrag); gice_creds.append(" password "); gice_creds.append(kExternalGicePwd); gice_creds.append("\r\n"); Replace("\r\n", gice_creds, sdp); LOG(LS_INFO) << "AddGiceCredsToCandidate: " << *sdp; } void OnCallerAddedDataChanel(DataChannelInterface* dc) { caller_signaled_data_channels_.push_back(dc); } void OnCalleeAddedDataChannel(DataChannelInterface* dc) { callee_signaled_data_channels_.push_back(dc); } // Tests that |dc1| and |dc2| can send to and receive from each other. void TestDataChannelSendAndReceive( DataChannelInterface* dc1, DataChannelInterface* dc2) { talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc1_observer( new webrtc::MockDataChannelObserver(dc1)); talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc2_observer( new webrtc::MockDataChannelObserver(dc2)); static const std::string kDummyData = "abcdefg"; webrtc::DataBuffer buffer(kDummyData); EXPECT_TRUE(dc1->Send(buffer)); EXPECT_EQ_WAIT(kDummyData, dc2_observer->last_message(), kMaxWait); EXPECT_TRUE(dc2->Send(buffer)); EXPECT_EQ_WAIT(kDummyData, dc1_observer->last_message(), kMaxWait); EXPECT_EQ(1U, dc1_observer->received_message_count()); EXPECT_EQ(1U, dc2_observer->received_message_count()); } void WaitForDataChannelsToOpen(DataChannelInterface* local_dc, const DataChannelList& remote_dc_list, size_t remote_dc_index) { EXPECT_EQ_WAIT(DataChannelInterface::kOpen, local_dc->state(), kMaxWait); EXPECT_TRUE_WAIT(remote_dc_list.size() > remote_dc_index, kMaxWait); EXPECT_EQ_WAIT(DataChannelInterface::kOpen, remote_dc_list[remote_dc_index]->state(), kMaxWait); EXPECT_EQ(local_dc->id(), remote_dc_list[remote_dc_index]->id()); } void CloseDataChannels(DataChannelInterface* local_dc, const DataChannelList& remote_dc_list, size_t remote_dc_index) { local_dc->Close(); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, local_dc->state(), kMaxWait); EXPECT_EQ_WAIT(DataChannelInterface::kClosed, remote_dc_list[remote_dc_index]->state(), kMaxWait); } ~PeerConnectionEndToEndTest() { talk_base::CleanupSSL(); } protected: talk_base::scoped_refptr<PeerConnectionTestWrapper> caller_; talk_base::scoped_refptr<PeerConnectionTestWrapper> callee_; DataChannelList caller_signaled_data_channels_; DataChannelList callee_signaled_data_channels_; }; // Disable for TSan v2, see // https://code.google.com/p/webrtc/issues/detail?id=1205 for details. #if !defined(THREAD_SANITIZER) TEST_F(PeerConnectionEndToEndTest, Call) { CreatePcs(); GetAndAddUserMedia(); Negotiate(); WaitForCallEstablished(); } // Disabled per b/14899892 TEST_F(PeerConnectionEndToEndTest, DISABLED_CallWithLegacySdp) { FakeConstraints pc_constraints; pc_constraints.AddMandatory(MediaConstraintsInterface::kEnableDtlsSrtp, false); CreatePcs(&pc_constraints); SetupLegacySdpConverter(); SetupGiceConverter(); GetAndAddUserMedia(); Negotiate(); WaitForCallEstablished(); } // Verifies that a DataChannel created before the negotiation can transition to // "OPEN" and transfer data. TEST_F(PeerConnectionEndToEndTest, CreateDataChannelBeforeNegotiate) { MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp); CreatePcs(); webrtc::DataChannelInit init; talk_base::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("data", init)); talk_base::scoped_refptr<DataChannelInterface> callee_dc( callee_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 0); WaitForDataChannelsToOpen(callee_dc, caller_signaled_data_channels_, 0); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[0]); TestDataChannelSendAndReceive(callee_dc, caller_signaled_data_channels_[0]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 0); CloseDataChannels(callee_dc, caller_signaled_data_channels_, 0); } // Verifies that a DataChannel created after the negotiation can transition to // "OPEN" and transfer data. TEST_F(PeerConnectionEndToEndTest, CreateDataChannelAfterNegotiate) { MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp); CreatePcs(); webrtc::DataChannelInit init; // This DataChannel is for creating the data content in the negotiation. talk_base::scoped_refptr<DataChannelInterface> dummy( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); // Creates new DataChannels after the negotiation and verifies their states. talk_base::scoped_refptr<DataChannelInterface> caller_dc( caller_->CreateDataChannel("hello", init)); talk_base::scoped_refptr<DataChannelInterface> callee_dc( callee_->CreateDataChannel("hello", init)); WaitForDataChannelsToOpen(caller_dc, callee_signaled_data_channels_, 1); WaitForDataChannelsToOpen(callee_dc, caller_signaled_data_channels_, 0); TestDataChannelSendAndReceive(caller_dc, callee_signaled_data_channels_[1]); TestDataChannelSendAndReceive(callee_dc, caller_signaled_data_channels_[0]); CloseDataChannels(caller_dc, callee_signaled_data_channels_, 1); CloseDataChannels(callee_dc, caller_signaled_data_channels_, 0); } // Verifies that DataChannel IDs are even/odd based on the DTLS roles. TEST_F(PeerConnectionEndToEndTest, DataChannelIdAssignment) { MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp); CreatePcs(); webrtc::DataChannelInit init; talk_base::scoped_refptr<DataChannelInterface> caller_dc_1( caller_->CreateDataChannel("data", init)); talk_base::scoped_refptr<DataChannelInterface> callee_dc_1( callee_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); EXPECT_EQ(1U, caller_dc_1->id() % 2); EXPECT_EQ(0U, callee_dc_1->id() % 2); talk_base::scoped_refptr<DataChannelInterface> caller_dc_2( caller_->CreateDataChannel("data", init)); talk_base::scoped_refptr<DataChannelInterface> callee_dc_2( callee_->CreateDataChannel("data", init)); EXPECT_EQ(1U, caller_dc_2->id() % 2); EXPECT_EQ(0U, callee_dc_2->id() % 2); } // Verifies that the message is received by the right remote DataChannel when // there are multiple DataChannels. TEST_F(PeerConnectionEndToEndTest, MessageTransferBetweenTwoPairsOfDataChannels) { MAYBE_SKIP_TEST(talk_base::SSLStreamAdapter::HaveDtlsSrtp); CreatePcs(); webrtc::DataChannelInit init; talk_base::scoped_refptr<DataChannelInterface> caller_dc_1( caller_->CreateDataChannel("data", init)); talk_base::scoped_refptr<DataChannelInterface> caller_dc_2( caller_->CreateDataChannel("data", init)); Negotiate(); WaitForConnection(); WaitForDataChannelsToOpen(caller_dc_1, callee_signaled_data_channels_, 0); WaitForDataChannelsToOpen(caller_dc_2, callee_signaled_data_channels_, 1); talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc_1_observer( new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[0])); talk_base::scoped_ptr<webrtc::MockDataChannelObserver> dc_2_observer( new webrtc::MockDataChannelObserver(callee_signaled_data_channels_[1])); const std::string message_1 = "hello 1"; const std::string message_2 = "hello 2"; caller_dc_1->Send(webrtc::DataBuffer(message_1)); EXPECT_EQ_WAIT(message_1, dc_1_observer->last_message(), kMaxWait); caller_dc_2->Send(webrtc::DataBuffer(message_2)); EXPECT_EQ_WAIT(message_2, dc_2_observer->last_message(), kMaxWait); EXPECT_EQ(1U, dc_1_observer->received_message_count()); EXPECT_EQ(1U, dc_2_observer->received_message_count()); } #endif // if !defined(THREAD_SANITIZER)
#include <Cerbi.h> class Sandbox : public Cerbi::Application { public: Sandbox() { } ~Sandbox() { } }; Cerbi::Application* Cerbi::CreateApplication() { return new Sandbox(); }
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License. */ #include <gtest/gtest.h> #include "clients/meta/FileBasedClusterIdMan.h" #include "common/base/Base.h" #include "common/fs/TempDir.h" namespace nebula { namespace meta { TEST(FileBasedClusterIdManTest, ReadWriteTest) { fs::TempDir rootPath("/tmp/FileBasedClusterIdManTest.XXXXXX"); auto clusterId = FileBasedClusterIdMan::create("127.0.0.1:44500"); CHECK_NE(0, clusterId); auto file = folly::stringPrintf("%s/cluster.id", rootPath.path()); CHECK(FileBasedClusterIdMan::persistInFile(clusterId, file)); auto ret = FileBasedClusterIdMan::getClusterIdFromFile(file); CHECK_EQ(clusterId, ret); } } // namespace meta } // namespace nebula int main(int argc, char** argv) { testing::InitGoogleTest(&argc, argv); folly::init(&argc, &argv, true); google::SetStderrLogging(google::INFO); return RUN_ALL_TESTS(); }
#include "UsingTimerService.h" #include <optional_bundles/logging_bundle/LoggerAdmin.h> #ifdef USE_SPDLOG #include <optional_bundles/logging_bundle/SpdlogFrameworkLogger.h> #include <optional_bundles/logging_bundle/SpdlogLogger.h> #define FRAMEWORK_LOGGER_TYPE SpdlogFrameworkLogger #define LOGGER_TYPE SpdlogLogger #else #include <optional_bundles/logging_bundle/CoutFrameworkLogger.h> #include <optional_bundles/logging_bundle/CoutLogger.h> #define FRAMEWORK_LOGGER_TYPE CoutFrameworkLogger #define LOGGER_TYPE CoutLogger #endif #include <chrono> #include <iostream> using namespace std::string_literals; int main() { std::locale::global(std::locale("en_US.UTF-8")); auto start = std::chrono::system_clock::now(); DependencyManager dm{}; dm.createServiceManager<FRAMEWORK_LOGGER_TYPE, IFrameworkLogger>(); #ifdef USE_SPDLOG dm.createServiceManager<SpdlogSharedService, ISpdlogSharedService>(); #endif dm.createServiceManager<LoggerAdmin<LOGGER_TYPE>, ILoggerAdmin>(); dm.createServiceManager<UsingTimerService, IUsingTimerService>(); dm.createServiceManager<UsingTimerService, IUsingTimerService>(); dm.start(); auto end = std::chrono::system_clock::now(); std::cout << fmt::format("Program ran for {:L} µs\n", std::chrono::duration_cast<std::chrono::microseconds>(end-start).count()); return 0; }
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> START_ATF_NAMESPACE struct _ACTRL_ACCESS_INFOW { unsigned int fAccessPermission; wchar_t *lpAccessPermissionName; }; END_ATF_NAMESPACE
// This code contains NVIDIA Confidential Information and is disclosed to you // under a form of NVIDIA software license agreement provided separately to you. // // Notice // NVIDIA Corporation and its licensors retain all intellectual property and // proprietary rights in and to this software and related documentation and // any modifications thereto. Any use, reproduction, disclosure, or // distribution of this software and related documentation without an express // license agreement from NVIDIA Corporation is strictly prohibited. // // ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES // NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO // THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT, // MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE. // // Information and code furnished is believed to be accurate and reliable. // However, NVIDIA Corporation assumes no responsibility for the consequences of use of such // information or for any infringement of patents or other rights of third parties that may // result from its use. No license is granted by implication or otherwise under any patent // or patent rights of NVIDIA Corporation. Details are subject to change without notice. // This code supersedes and replaces all information previously supplied. // NVIDIA Corporation products are not authorized for use as critical // components in life support devices or systems without express written approval of // NVIDIA Corporation. // // Copyright (c) 2008-2014 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "PxPhysXConfig.h" #if PX_USE_CLOTH_API #include "extensions/PxClothTetherCooker.h" #include "PxStrideIterator.h" // from shared foundation #include <PsFoundation.h> #include <PsSort.h> #include <Ps.h> #include <PsMathUtils.h> #include "PxVec4.h" #include "foundation/PxMemory.h" using namespace physx; namespace { // calculate the inclusive prefix sum, equivalent of std::partial_sum template <typename T> void prefixSum(const T* first, const T* last, T* dest) { if (first != last) { *(dest++) = *(first++); for (; first != last; ++first, ++dest) *dest = *(dest-1) + *first; } } template <typename T> void gatherAdjacencies(shdfnd::Array<PxU32>& valency, shdfnd::Array<PxU32>& adjacencies, const PxBoundedData& triangles, const PxBoundedData& quads) { // count number of edges per vertex PxStrideIterator<const T> tIt, qIt; tIt = PxMakeIterator((const T*)triangles.data, triangles.stride); for(PxU32 i=0; i<triangles.count; ++i, ++tIt, ++qIt) { for(PxU32 j=0; j<3; ++j) valency[tIt.ptr()[j]] += 2; } qIt = PxMakeIterator((const T*)quads.data, quads.stride); for(PxU32 i=0; i<quads.count; ++i, ++tIt, ++qIt) { for(PxU32 j=0; j<4; ++j) valency[qIt.ptr()[j]] += 2; } prefixSum(valency.begin(), valency.end(), valency.begin()); adjacencies.resize(valency.back()); // gather adjacent vertices tIt = PxMakeIterator((const T*)triangles.data, triangles.stride); for(PxU32 i=0; i<triangles.count; ++i, ++tIt) { for(PxU32 j=0; j<3; ++j) { adjacencies[--valency[tIt.ptr()[j]]] = tIt.ptr()[(j+1)%3]; adjacencies[--valency[tIt.ptr()[j]]] = tIt.ptr()[(j+2)%3]; } } qIt = PxMakeIterator((const T*)quads.data, quads.stride); for(PxU32 i=0; i<quads.count; ++i, ++qIt) { for(PxU32 j=0; j<4; ++j) { adjacencies[--valency[qIt.ptr()[j]]] = qIt.ptr()[(j+1)%4]; adjacencies[--valency[qIt.ptr()[j]]] = qIt.ptr()[(j+3)%4]; } } } template <typename T> void gatherIndices(shdfnd::Array<PxU32>& indices, const PxBoundedData& triangles, const PxBoundedData& quads) { PxStrideIterator<const T> tIt, qIt; indices.reserve(triangles.count * 3 + quads.count * 6); tIt = PxMakeIterator((const T*)triangles.data, triangles.stride); for(PxU32 i=0; i<triangles.count; ++i, ++tIt) { indices.pushBack(tIt.ptr()[0]); indices.pushBack(tIt.ptr()[1]); indices.pushBack(tIt.ptr()[2]); } qIt = PxMakeIterator((const T*)quads.data, quads.stride); for(PxU32 i=0; i<quads.count; ++i, ++qIt) { indices.pushBack(qIt.ptr()[0]); indices.pushBack(qIt.ptr()[1]); indices.pushBack(qIt.ptr()[2]); indices.pushBack(qIt.ptr()[0]); indices.pushBack(qIt.ptr()[2]); indices.pushBack(qIt.ptr()[3]); } } // maintain heap status after elements have been pushed (heapify) template<typename T> void pushHeap(shdfnd::Array<T> &heap, const T &value) { heap.pushBack(value); T* begin = heap.begin(); T* end = heap.end(); if (end <= begin) return; PxU32 current = PxU32(end - begin) - 1; while (current > 0) { const PxU32 parent = (current - 1) / 2; if (!(begin[parent] < begin[current])) break; shdfnd::swap(begin[parent], begin[current]); current = parent; } } // pop one element from the heap template<typename T> T popHeap(shdfnd::Array<T> &heap) { T* begin = heap.begin(); T* end = heap.end(); shdfnd::swap(begin[0], end[-1]); // exchange elements // shift down end--; PxU32 current = 0; while (begin + (current * 2 + 1) < end) { PxU32 child = current * 2 + 1; if (begin + child + 1 < end && begin[child] < begin[child + 1]) ++child; if (!(begin[current] < begin[child])) break; shdfnd::swap(begin[current], begin[child]); current = child; } return heap.popBack(); } // --------------------------------------------------------------------------------------- struct VertexDistanceCount { VertexDistanceCount(int vert, float dist, int count) : vertNr(vert), distance(dist), edgeCount(count) {} int vertNr; float distance; int edgeCount; bool operator < (const VertexDistanceCount& v) const { return v.distance < distance; } }; // --------------------------------------------------------------------------------------- struct PathIntersection { PxU32 vertOrTriangle; PxU32 index; // vertex id or triangle edge id float s; // only used for edge intersection float distance; // computed distance public: PathIntersection() {} PathIntersection(PxU32 vort, PxU32 in_index, float in_distance, float in_s = 0.0f) : vertOrTriangle(vort), index(in_index), s(in_s), distance(in_distance) { } }; //--------------------------------------------------------------------------------------- struct VertTriangle { VertTriangle(int vert, int triangle) : mVertIndex(vert), mTriangleIndex(triangle) { } bool operator<(const VertTriangle &vt) const { return mVertIndex == vt.mVertIndex ? mTriangleIndex < vt.mTriangleIndex : mVertIndex < vt.mVertIndex; } int mVertIndex; int mTriangleIndex; }; // --------------------------------------------------------------------------------------- struct MeshEdge { MeshEdge(int v0, int v1, int halfEdgeIndex) : mFromVertIndex(v0), mToVertIndex(v1), mHalfEdgeIndex(halfEdgeIndex) { if(mFromVertIndex > mToVertIndex) shdfnd::swap(mFromVertIndex, mToVertIndex); } bool operator<(const MeshEdge& e) const { return mFromVertIndex == e.mFromVertIndex ? mToVertIndex < e.mToVertIndex : mFromVertIndex < e.mFromVertIndex; } bool operator==(const MeshEdge& e) const { return mFromVertIndex == e.mFromVertIndex && mToVertIndex == e.mToVertIndex; } int mFromVertIndex, mToVertIndex; int mHalfEdgeIndex; }; // check if the edge is following triangle order or not bool checkEdgeOrientation(const MeshEdge &e, const shdfnd::Array<PxU32> &indices) { int offset0 = e.mHalfEdgeIndex % 3; int offset1 = (offset0 < 2) ? 1 : -2; int v0 = (int)indices[PxU32(e.mHalfEdgeIndex)]; int v1 = (int)indices[PxU32(e.mHalfEdgeIndex + offset1)]; if ((e.mFromVertIndex == v0) && (e.mToVertIndex == v1)) return true; return false; } // check if two index pairs represent same edge regardless of order. inline bool checkEdge(int ei0, int ei1, int ej0, int ej1) { return ( (ei0 == ej0) && (ei1 == ej1) ) || ( (ei0 == ej1) && (ei1 == ej0) ); } // compute ray edge intersection bool intersectRayEdge(const PxVec3 &O, const PxVec3 &D, const PxVec3 &A, const PxVec3 &B, float &s, float &t) { // point on edge P = A + s * AB // point on ray R = o + t * d // for this two points to intersect, we have // |AB -d| | s t | = o - A const float eps = 1e-4; PxVec3 OA = O - A; PxVec3 AB = B - A; float a = AB.dot(AB), b = -AB.dot(D); float c = b, d = D.dot(D); float e = AB.dot(OA); float f = -D.dot(OA); float det = a * d - b * c; if (fabs(det) < eps) // coplanar case return false; float inv_det = 1.0f / det; s = (d * inv_det) * e + (-b * inv_det) * f; t = (-c * inv_det) * e + (a * inv_det) * f; return true; } } struct physx::PxClothGeodesicTetherCookerImpl { PxClothGeodesicTetherCookerImpl(const PxClothMeshDesc& desc); PxU32 getCookerStatus() const; PxU32 getNbTethersPerParticle() const; void getTetherData(PxU32* userTetherAnchors, PxReal* userTetherLengths) const; public: // input const PxClothMeshDesc& mDesc; // internal variables PxU32 mNumParticles; shdfnd::Array<PxVec3> mVertices; shdfnd::Array<PxU32> mIndices; shdfnd::Array<PxU8> mAttached; shdfnd::Array<PxU32> mFirstVertTriAdj; shdfnd::Array<PxU32> mVertTriAdjs; shdfnd::Array<PxU32> mTriNeighbors; // needs changing for non-manifold support // error status PxU32 mCookerStatus; // output shdfnd::Array<PxU32> mTetherAnchors; shdfnd::Array<PxReal> mTetherLengths; protected: void createTetherData(const PxClothMeshDesc &desc); int computeVertexIntersection(PxU32 parent, PxU32 src, PathIntersection &path); int computeEdgeIntersection(PxU32 parent, PxU32 edge, float in_s, PathIntersection &path); float computeGeodesicDistance(PxU32 i, PxU32 parent, int &errorCode); PxU32 findTriNeighbors(); void findVertTriNeighbors(); private: PxClothGeodesicTetherCookerImpl& operator=(const PxClothGeodesicTetherCookerImpl&); }; PxClothGeodesicTetherCooker::PxClothGeodesicTetherCooker(const PxClothMeshDesc& desc) : mImpl(new PxClothGeodesicTetherCookerImpl(desc)) { } PxClothGeodesicTetherCooker::~PxClothGeodesicTetherCooker() { delete mImpl; } PxU32 PxClothGeodesicTetherCooker::getCookerStatus() const { return mImpl->getCookerStatus(); } PxU32 PxClothGeodesicTetherCooker::getNbTethersPerParticle() const { return mImpl->getNbTethersPerParticle(); } void PxClothGeodesicTetherCooker::getTetherData(PxU32* userTetherAnchors, PxReal* userTetherLengths) const { mImpl->getTetherData(userTetherAnchors, userTetherLengths); } /////////////////////////////////////////////////////////////////////////////// PxClothGeodesicTetherCookerImpl::PxClothGeodesicTetherCookerImpl(const PxClothMeshDesc &desc) :mDesc(desc), mCookerStatus(0) { createTetherData(desc); } /////////////////////////////////////////////////////////////////////////////// void PxClothGeodesicTetherCookerImpl::createTetherData(const PxClothMeshDesc &desc) { mNumParticles = desc.points.count; if (!desc.invMasses.data) return; // assemble points mVertices.resize(mNumParticles); mAttached.resize(mNumParticles); PxStrideIterator<const PxVec3> pIt((const PxVec3*)desc.points.data, desc.points.stride); PxStrideIterator<const PxReal> wIt((const PxReal*)desc.invMasses.data, desc.invMasses.stride); for(PxU32 i=0; i<mNumParticles; ++i) { mVertices[i] = *pIt++; mAttached[i] = PxU8(wIt.ptr() ? (*wIt++ == 0.0f) : 0); } // build triangle indices if(desc.flags & PxMeshFlag::e16_BIT_INDICES) gatherIndices<PxU16>(mIndices, desc.triangles, desc.quads); else gatherIndices<PxU32>(mIndices, desc.triangles, desc.quads); // build vertex-triangle adjacencies findVertTriNeighbors(); // build triangle-triangle adjacencies mCookerStatus = findTriNeighbors(); if (mCookerStatus != 0) return; // build adjacent vertex list shdfnd::Array<PxU32> valency(mNumParticles+1, 0); shdfnd::Array<PxU32> adjacencies; if(desc.flags & PxMeshFlag::e16_BIT_INDICES) gatherAdjacencies<PxU16>(valency, adjacencies, desc.triangles, desc.quads); else gatherAdjacencies<PxU32>(valency, adjacencies, desc.triangles, desc.quads); // build unique neighbors from adjacencies shdfnd::Array<PxU32> mark(valency.size(), 0); shdfnd::Array<PxU32> neighbors; neighbors.reserve(adjacencies.size()); for(PxU32 i=1, j=0; i<valency.size(); ++i) { for(; j<valency[i]; ++j) { PxU32 k = adjacencies[j]; if(mark[k] != i) { mark[k] = i; neighbors.pushBack(k); } } valency[i] = neighbors.size(); } // create islands of attachment points shdfnd::Array<PxU32> vertexIsland(mNumParticles); shdfnd::Array<VertexDistanceCount> vertexIslandHeap; // put all the attachments in heap for (PxU32 i = 0; i < mNumParticles; ++i) { // we put each attached point with large distance so that // we can prioritize things that are added during mesh traversal. vertexIsland[i] = PxU32(-1); if (mAttached[i]) vertexIslandHeap.pushBack(VertexDistanceCount((int)i, FLT_MAX, 0)); } PxU32 attachedCnt = vertexIslandHeap.size(); // no attached vertices if (vertexIslandHeap.empty()) return; // identify islands of attached vertices shdfnd::Array<PxU32> islandIndices; shdfnd::Array<PxU32> islandFirst; PxU32 islandCnt = 0; PxU32 islandIndexCnt = 0; islandIndices.reserve(attachedCnt); islandFirst.reserve(attachedCnt+1); // while the island heap is not empty while (!vertexIslandHeap.empty()) { // pop vi from heap VertexDistanceCount vi = popHeap(vertexIslandHeap); // new cluster if (vertexIsland[(PxU32)vi.vertNr] == PxU32(-1)) { islandFirst.pushBack(islandIndexCnt++); vertexIsland[(PxU32)vi.vertNr] = islandCnt++; vi.distance = 0; islandIndices.pushBack((PxU32)vi.vertNr); } // for each adjacent vj that's not visited const PxU32 begin = (PxU32)valency[(PxU32)vi.vertNr]; const PxU32 end = (PxU32)valency[PxU32(vi.vertNr + 1)]; for (PxU32 j = begin; j < end; ++j) { const PxU32 vj = neighbors[j]; // do not expand unattached vertices if (!mAttached[vj]) continue; // already visited if (vertexIsland[vj] != PxU32(-1)) continue; islandIndices.pushBack(vj); islandIndexCnt++; vertexIsland[vj] = vertexIsland[PxU32(vi.vertNr)]; pushHeap(vertexIslandHeap, VertexDistanceCount((int)vj, vi.distance + 1.0f, 0)); } } islandFirst.pushBack(islandIndexCnt); PX_ASSERT(islandCnt == (islandFirst.size() - 1)); ///////////////////////////////////////////////////////// PxU32 bufferSize = mNumParticles * islandCnt; PX_ASSERT(bufferSize > 0); shdfnd::Array<float> vertexDistanceBuffer(bufferSize, PX_MAX_F32); shdfnd::Array<PxU32> vertexParentBuffer(bufferSize, 0); shdfnd::Array<VertexDistanceCount> vertexHeap; // now process each island for (PxU32 i = 0; i < islandCnt; i++) { vertexHeap.clear(); float* vertexDistance = &vertexDistanceBuffer[0] + (i * mNumParticles); PxU32* vertexParent = &vertexParentBuffer[0] + (i * mNumParticles); // initialize parent and distance for (PxU32 j = 0; j < mNumParticles; ++j) { vertexParent[j] = j; vertexDistance[j] = PX_MAX_F32; } // put all the attached vertices in this island to heap const PxU32 beginIsland = islandFirst[i]; const PxU32 endIsland = islandFirst[i+1]; for (PxU32 j = beginIsland; j < endIsland; j++) { PxU32 vj = islandIndices[j]; vertexDistance[vj] = 0.0f; vertexHeap.pushBack(VertexDistanceCount((int)vj, 0.0f, 0)); } // no attached vertices in this island (error?) PX_ASSERT(vertexHeap.empty() == false); if (vertexHeap.empty()) continue; // while heap is not empty while (!vertexHeap.empty()) { // pop vi from heap VertexDistanceCount vi = popHeap(vertexHeap); // obsolete entry ( we already found better distance) if (vi.distance > vertexDistance[vi.vertNr]) continue; // for each adjacent vj that's not visited const PxI32 begin = (PxI32)valency[(PxU32)vi.vertNr]; const PxI32 end = (PxI32)valency[PxU32(vi.vertNr + 1)]; for (PxI32 j = begin; j < end; ++j) { const PxI32 vj = (PxI32)neighbors[(PxU32)j]; PxVec3 edge = mVertices[(PxU32)vj] - mVertices[(PxU32)vi.vertNr]; const PxF32 edgeLength = edge.magnitude(); float newDistance = vi.distance + edgeLength; if (newDistance < vertexDistance[vj]) { vertexDistance[vj] = newDistance; vertexParent[vj] = vertexParent[vi.vertNr]; pushHeap(vertexHeap, VertexDistanceCount(vj, newDistance, 0)); } } } } const PxU32 maxTethersPerParticle = 4; // max tethers const PxU32 nbTethersPerParticle = (islandCnt > maxTethersPerParticle) ? maxTethersPerParticle : islandCnt; PxU32 nbTethers = nbTethersPerParticle * mNumParticles; mTetherAnchors.resize(nbTethers); mTetherLengths.resize(nbTethers); // now process the parent and distance and add to fibers for (PxU32 i = 0; i < mNumParticles; i++) { // we use the heap to sort out N-closest island vertexHeap.clear(); for (PxU32 j = 0; j < islandCnt; j++) { int parent = (int)vertexParentBuffer[j * mNumParticles + i]; float edgeDistance = vertexDistanceBuffer[j * mNumParticles + i]; pushHeap(vertexHeap, VertexDistanceCount(parent, edgeDistance, 0)); } // take out N-closest island from the heap for (PxU32 j = 0; j < nbTethersPerParticle; j++) { VertexDistanceCount vi = popHeap(vertexHeap); PxU32 parent = (PxU32)vi.vertNr; float distance = 0.0f; if (parent != i) { float euclideanDistance = (mVertices[i] - mVertices[parent]).magnitude(); float dijkstraDistance = vi.distance; int errorCode = 0; float geodesicDistance = computeGeodesicDistance(i,parent, errorCode); if (errorCode < 0) geodesicDistance = dijkstraDistance; distance = PxMax(euclideanDistance, geodesicDistance); } PxU32 tetherLoc = j * mNumParticles + i; mTetherAnchors[ tetherLoc ] = parent; mTetherLengths[ tetherLoc ] = distance; } } } /////////////////////////////////////////////////////////////////////////////// PxU32 PxClothGeodesicTetherCookerImpl::getCookerStatus() const { return mCookerStatus; } /////////////////////////////////////////////////////////////////////////////// PxU32 PxClothGeodesicTetherCookerImpl::getNbTethersPerParticle() const { return mTetherAnchors.size() / mNumParticles; } /////////////////////////////////////////////////////////////////////////////// void PxClothGeodesicTetherCookerImpl::getTetherData(PxU32* userTetherAnchors, PxReal* userTetherLengths) const { PxMemCopy(userTetherAnchors, mTetherAnchors.begin(), mTetherAnchors.size() * sizeof(PxU32)); PxMemCopy(userTetherLengths, mTetherLengths.begin(), mTetherLengths.size() * sizeof(PxReal)); } /////////////////////////////////////////////////////////////////////////////// // find triangle-triangle adjacency (return non-zero if there is an error) PxU32 PxClothGeodesicTetherCookerImpl::findTriNeighbors() { shdfnd::Array<MeshEdge> edges; mTriNeighbors.resize(mIndices.size(), PxU32(-1)); // assemble all edges PxU32 numTriangles = mIndices.size() / 3; for (PxU32 i = 0; i < numTriangles; ++i) { PxU32 i0 = mIndices[3 * i]; PxU32 i1 = mIndices[3 * i + 1]; PxU32 i2 = mIndices[3 * i + 2]; edges.pushBack(MeshEdge((int)i0, (int)i1, int(3*i))); edges.pushBack(MeshEdge((int)i1, (int)i2, int(3*i+1))); edges.pushBack(MeshEdge((int)i2, (int)i0, int(3*i+2))); } shdfnd::sort(edges.begin(), edges.size()); int numEdges = (int)edges.size(); for(int i=0; i < numEdges; ) { const MeshEdge& e0 = edges[(PxU32)i]; bool orientation0 = checkEdgeOrientation(e0, mIndices); int j = i; while(++i < numEdges && edges[(PxU32)i] == e0) ; if(i - j > 2) return 1; // non-manifold while(++j < i) { const MeshEdge& e1 = edges[(PxU32)j]; bool orientation1 = checkEdgeOrientation(e1, mIndices); mTriNeighbors[(PxU32)e0.mHalfEdgeIndex] = (PxU32)e1.mHalfEdgeIndex/3; mTriNeighbors[(PxU32)e1.mHalfEdgeIndex] = (PxU32)e0.mHalfEdgeIndex/3; if (orientation0 == orientation1) return 2; // bad winding } } return 0; } /////////////////////////////////////////////////////////////////////////////// // find vertex triangle adjacency information void PxClothGeodesicTetherCookerImpl::findVertTriNeighbors() { shdfnd::Array<VertTriangle> vertTriangles; vertTriangles.reserve(mIndices.size()); int numTriangles = (int)mIndices.size() / 3; for (int i = 0; i < numTriangles; ++i) { vertTriangles.pushBack(VertTriangle((int)mIndices[PxU32(3*i)], i)); vertTriangles.pushBack(VertTriangle((int)mIndices[PxU32(3*i+1)], i)); vertTriangles.pushBack(VertTriangle((int)mIndices[PxU32(3*i+2)], i)); } shdfnd::sort(vertTriangles.begin(), vertTriangles.size(), shdfnd::Less<VertTriangle>()); mFirstVertTriAdj.resize(mNumParticles); mVertTriAdjs.reserve(mIndices.size()); for (PxU32 i = 0; i < (PxU32)vertTriangles.size(); ) { int v = vertTriangles[i].mVertIndex; mFirstVertTriAdj[(PxU32)v] = i; while ((i < mIndices.size()) && (vertTriangles[i].mVertIndex == v)) { int t = vertTriangles[i].mTriangleIndex; mVertTriAdjs.pushBack((PxU32)t); i++; } } } /////////////////////////////////////////////////////////////////////////////// // compute intersection of a ray from a source vertex in direction toward parent int PxClothGeodesicTetherCookerImpl::computeVertexIntersection(PxU32 parent, PxU32 src, PathIntersection &path) { if (src == parent) { path = PathIntersection(true, src, 0.0); return 0; } float maxdot = -1.0f; int closestVert = -1; // gradient is toward the parent vertex PxVec3 g = (mVertices[parent] - mVertices[src]).getNormalized(); // for every triangle incident on this vertex, we intersect against opposite edge of the triangle PxU32 sfirst = mFirstVertTriAdj[src]; PxU32 slast = (src < ((PxU32)mNumParticles-1)) ? mFirstVertTriAdj[src+1] : (PxU32)mVertTriAdjs.size(); for (PxU32 adj = sfirst; adj < slast; adj++) { PxU32 tid = mVertTriAdjs[adj]; PxU32 i0 = mIndices[tid*3]; PxU32 i1 = mIndices[tid*3+1]; PxU32 i2 = mIndices[tid*3+2]; int eid = 0; if (i0 == src) eid = 1; else if (i1 == src) eid = 2; else if (i2 == src) eid = 0; else continue; // error // reshuffle so that src is located at i2 i0 = mIndices[tid*3 + eid]; i1 = mIndices[tid*3 + (eid+1)%3]; i2 = src; PxVec3 p0 = mVertices[i0]; PxVec3 p1 = mVertices[i1]; PxVec3 p2 = mVertices[i2]; // check if we hit source immediately from this triangle if (i0 == parent) { path = PathIntersection(true, parent, (p0 - p2).magnitude()); return 1; } if (i1 == parent) { path = PathIntersection(true, parent, (p1 - p2).magnitude()); return 1; } // ray direction is the gradient projected on the plane of this triangle PxVec3 n = ((p0 - p2).cross(p1 - p2)).getNormalized(); PxVec3 d = (g - g.dot(n) * n).getNormalized(); // find intersection of ray (p2, d) against the edge (p0,p1) float s, t; bool result = intersectRayEdge(p2, d, p0, p1, s, t); if (result == false) continue; // t should be positive, otherwise we just hit the triangle in opposite direction, so ignore const float eps = 1e-5; if (t > -eps) { PxVec3 ip; // intersection point if (( s > -eps ) && (s < (1.0f + eps))) { // if intersection point is too close to each vertex, we record a vertex intersection if ( ( s < eps) || (s > (1.0f-eps))) { path.vertOrTriangle = true; path.index = (s < eps) ? i0 : i1; path.distance = (p2 - mVertices[path.index]).magnitude(); } else // found an edge instersection { ip = p0 + s * (p1 - p0); path = PathIntersection(false, tid*3 + eid, (p2 - ip).magnitude(), s); } return 1; } } // for fall back (see below) PxVec3 d0 = (p0 - p2).getNormalized(); PxVec3 d1 = (p1 - p2).getNormalized(); float d0dotg = d0.dot(d); float d1dotg = d1.dot(d); if (d0dotg > maxdot) { closestVert = (int)i0; maxdot = d0dotg; } if (d1dotg > maxdot) { closestVert = (int)i1; maxdot = d1dotg; } } // end for (PxU32 adj = sfirst... // Fall back to use greedy (Dijkstra-like) path selection. // This happens as triangles are curved and we may not find intersection on any triangle. // In this case, we choose a vertex closest to the gradient direction. if (closestVert > 0) { path = PathIntersection(true, (PxU32)closestVert, (mVertices[src] - mVertices[(PxU32)closestVert]).magnitude()); return 1; } // Error, (possibly dangling vertex) return -1; } /////////////////////////////////////////////////////////////////////////////// // compute intersection of a ray from a source vertex in direction toward parent int PxClothGeodesicTetherCookerImpl::computeEdgeIntersection(PxU32 parent, PxU32 edge, float in_s, PathIntersection &path) { int tid = (int)edge / 3; int eid = (int)edge % 3; PxU32 e0 = mIndices[PxU32(tid*3 + eid)]; PxU32 e1 = mIndices[PxU32(tid*3 + (eid+1)%3)]; PxVec3 v0 = mVertices[e0]; PxVec3 v1 = mVertices[e1]; PxVec3 v = v0 + in_s * (v1 - v0); PxVec3 g = mVertices[parent] - v; PxU32 triNbr = mTriNeighbors[edge]; if (triNbr == PxU32(-1)) // boundary edge { float dir = g.dot(v1-v0); PxU32 vid = (dir > 0) ? e1 : e0; path = PathIntersection(true, vid, (mVertices[vid] - v).magnitude()); return 1; } PxU32 i0 = mIndices[triNbr*3]; PxU32 i1 = mIndices[triNbr*3+1]; PxU32 i2 = mIndices[triNbr*3+2]; // vertex is sorted s.t i0,i1 contains the edge point if ( checkEdge((int)i0, (int)i1, (int)e0, (int)e1)) { eid = 0; } else if ( checkEdge((int)i1, (int)i2, (int)e0, (int)e1)) { eid = 1; PxU32 tmp = i2; i2 = i0; i0 = i1; i1 = tmp; } else if ( checkEdge((int)i2, (int)i0, (int)e0, (int)e1)) { eid = 2; PxU32 tmp = i0; i0 = i2; i2 = i1; i1 = tmp; } // we hit the parent if (i2 == parent) { path = PathIntersection(true, i2, (mVertices[i2] - v).magnitude()); return 1; } PxVec3 p0 = mVertices[i0]; PxVec3 p1 = mVertices[i1]; PxVec3 p2 = mVertices[i2]; // project gradient vector on the plane of the triangle PxVec3 n = ((p0 - p2).cross(p1 - p2)).getNormalized(); g = (g - g.dot(n) * n).getNormalized(); float s = 0.0f, t = 0.0f; const float eps = 1e-5; PxVec3 ip; // intersect against edge form p2 to p0 if (intersectRayEdge(v, g, p2, p0, s, t) && ( s >= -eps) && ( s <= (1.0f+eps) ) && (t > -eps)) { if ( ( s < eps) || (s > (1.0f-eps))) { path.vertOrTriangle = true; path.index = (s < eps) ? i2 : i0; path.distance = (mVertices[path.index] - v).magnitude(); } else { ip = p2 + s * (p0 - p2); path = PathIntersection(false, triNbr*3 + (eid + 2) % 3, (ip - v).magnitude(), s); } return 1; } // intersect against edge form p1 to p2 if (intersectRayEdge(v, g, p1, p2, s, t) && ( s >= -eps) && ( s <= (1.0f+eps) ) && (t > -eps)) { if ( ( s < eps) || (s > (1.0f-eps))) { path.vertOrTriangle = true; path.index = (s < eps) ? i1 : i2; path.distance = (mVertices[path.index] - v).magnitude(); } else { ip = p1 + s * (p2 - p1); path = PathIntersection(false, triNbr*3 + (eid + 1) % 3, (ip - v).magnitude(), s); } return 1; } // fallback to pick closer vertex when no edges intersect float dir = g.dot(v1-v0); path.vertOrTriangle = true; path.index = (dir > 0) ? e1 : e0; path.distance = (mVertices[path.index] - v).magnitude(); return 1; } /////////////////////////////////////////////////////////////////////////////// // compute geodesic distance and path from vertex i to its parent float PxClothGeodesicTetherCookerImpl::computeGeodesicDistance(PxU32 i, PxU32 parent, int &errorCode) { if (i == parent) return 0.0f; PathIntersection path; errorCode = 0; // find intial intersection int status = computeVertexIntersection(parent, i, path); if (status < 0) { errorCode = -1; return 0; } int pathcnt = 0; float geodesicDistance = 0; while (status > 0) { geodesicDistance += path.distance; if (path.vertOrTriangle) status = computeVertexIntersection(parent, path.index, path); else status = computeEdgeIntersection(parent, path.index, path.s, path); // cannot find valid path if (status < 0) { errorCode = -2; return 0.0f; } // possibly cycles, too many path if (pathcnt > 1000) { errorCode = -3; return 0.0f; } pathcnt++; } return geodesicDistance; } #endif //PX_USE_CLOTH_API
#include "perfect_neighbors.hpp" namespace odgi { namespace algorithms { /// Return true if nodes share all paths and the mappings they share in these paths /// are adjacent, in the specified relative order and orientation. bool nodes_are_perfect_path_neighbors(const PathHandleGraph& graph, handle_t left_handle, handle_t right_handle) { #ifdef debug std::cerr << "Check if " << graph.get_id(left_handle) << (graph.get_is_reverse(left_handle) ? "-" : "+") << " and " << graph.get_id(right_handle) << (graph.get_is_reverse(right_handle) ? "-" : "+") << " are perfect path neighbors" << std::endl; #endif // Set this false if we find an impermissible step bool ok = true; // Count the number of permissible steps on the next node we find size_t expected_next = 0; graph.for_each_step_on_handle(left_handle, [&](const step_handle_t& here) { // For each path step on the left // We need to work out if the path traverses this handle backward. bool step_is_to_reverse_of_handle = (graph.get_handle_of_step(here) != left_handle); #ifdef debug std::cerr << "Consider visit of path " << graph.get_path_name(graph.get_path_handle_of_step(here)) << " to " << (step_is_to_reverse_of_handle ? "reverse" : "forward") << " orientation of handle" << std::endl; #endif if (!(step_is_to_reverse_of_handle ? graph.has_previous_step(here) : graph.has_next_step(here))) { // If there's no visit to the right of this handle, it can't be to the right next place #ifdef debug std::cerr << "Path stops here so no subsequent handle is a perfect path neighbor" << std::endl; #endif ok = false; return false; } // Walk along the path whatever direction is forward relative to our left handle. step_handle_t step_to_right = step_is_to_reverse_of_handle ? graph.get_previous_step(here) : graph.get_next_step(here); handle_t handle_to_right = graph.get_handle_of_step(step_to_right); if (step_is_to_reverse_of_handle) { // If we had to walk back along the reverse strand of the path, we have to flip where we ended up. handle_to_right = graph.flip(handle_to_right); } if (handle_to_right != right_handle) { // It goes to the wrong next place #ifdef debug std::cerr << "Path goes to the wrong place (" << graph.get_id(handle_to_right) << (graph.get_is_reverse(handle_to_right) ? "-" : "+") << ") and so these nodes are not perfect path neighbors" << std::endl; #endif ok = false; return false; } // Otherwise, record a step that is allowed to exist on the next handle expected_next++; return true; }); if (!ok) { // We found a bad step, or the path stopped. return false; } // Now count up the path steps on the right handle size_t observed_next = 0; graph.for_each_step_on_handle(right_handle, [&](const step_handle_t& ignored) { #ifdef debug std::cerr << "Next node has path " << graph.get_path_name(graph.get_path_handle_of_step(ignored)) << std::endl; #endif observed_next++; }); #ifdef debug if (observed_next != expected_next) { std::cerr << "Next node has " << observed_next << " path visits but should have " << expected_next << std::endl; } #endif // If there are any steps on the right node that weren't accounted for on // the left node, fail. Otherwise, succeed. return observed_next == expected_next; } } }
// -*-Mode: C++;-*- // * BeginRiceCopyright ***************************************************** // // $HeadURL$ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2021, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * // This file builds and prints an hpcstruct file with loops and inline // sequences based on input from the ParseAPI Control-Flow Graph // support in Dyninst. We no longer use Open Analysis or the // Prof::Struct classes. // // The internal representation of the structure info is defined in two // files: // // Struct-Skel.hpp -- defines the top-level skeleton classes for // Files, Groups and Procedures (Functions). // // Struct-Inline.hpp -- defines the Inline Tree classes for Loops, // Statements (Instructions) and inline sequences. // // Printing the internal objects in the hpcstruct XML format is // handled in Struct-Output.cpp. //*************************************************************************** #include <sys/types.h> #include <sys/resource.h> #include <sys/time.h> #include <stdlib.h> #include <string.h> #include <include/uint.h> #if ENABLE_VG_ANNOTATIONS == 1 #include <helgrind.h> #include <drd.h> #else #define ANNOTATE_HAPPENS_BEFORE(X) #define ANNOTATE_HAPPENS_AFTER(X) #endif #include <algorithm> #include <map> #include <set> #include <string> #include <vector> #include <mutex> #include <ostream> #include <sstream> #include <lib/binutils/BinUtils.hpp> #include <lib/binutils/VMAInterval.hpp> #include <lib/binutils/ElfHelper.hpp> #include <lib/binutils/InputFile.hpp> #include <lib/support/FileNameMap.hpp> #include <lib/support/FileUtil.hpp> #include <lib/support/RealPathMgr.hpp> #include <lib/support/StringTable.hpp> #include <lib/support/dictionary.h> #include <boost/atomic.hpp> #include <CFG.h> #include <CodeObject.h> #include <CodeSource.h> #include <Function.h> #include <Instruction.h> #include <Module.h> #include <Region.h> #include <Symtab.h> #include <include/hpctoolkit-config.h> #include "Struct.hpp" #include "Struct-Inline.hpp" #include "Struct-Output.hpp" #include "Struct-Skel.hpp" #include "gpu/ReadCudaCFG.hpp" #ifdef ENABLE_IGC #include "gpu/ReadIntelCFG.hpp" #endif // ENABLE_IGC #ifdef ENABLE_OPENMP #include <omp.h> #endif using namespace Dyninst; using namespace Inline; using namespace InstructionAPI; using namespace SymtabAPI; using namespace ParseAPI; using namespace std; //****************************************************************************** // macros //****************************************************************************** #ifdef DYNINST_USE_CUDA #define SYMTAB_ARCH_CUDA(symtab) \ ((symtab)->getArchitecture() == Dyninst::Arch_cuda) #else #define SYMTAB_ARCH_CUDA(symtab) 0 #endif #define DEBUG_CFG_SOURCE 0 #define DEBUG_MAKE_SKEL 0 #define DEBUG_SHOW_GAPS 0 #define DEBUG_SKEL_SUMMARY 0 #if DEBUG_CFG_SOURCE || DEBUG_MAKE_SKEL || DEBUG_SHOW_GAPS #define DEBUG_ANY_ON 1 #else #define DEBUG_ANY_ON 0 #endif #define CUDA_PROC_SEARCH_LEN 32 #define WORK_LIST_PCT 0.05 static int merge_irred_loops = 1; //****************************************************************************** // variables //****************************************************************************** // Copied from lib/support/dictionary.h static const string & unknown_file = UNKNOWN_FILE; static const string & unknown_proc = UNKNOWN_PROC; static const string & unknown_link = UNKNOWN_LINK; // FIXME: temporary until the line map problems are resolved static Symtab * the_symtab = NULL; static int cuda_arch = 0; static int intel_gpu_arch = 0; // We relocate the symbols and line maps of cubins to 'original_offset+cubin_size' // to handle the cases in which relocated offsets conflicts with original information static size_t cubin_size = 0; static BAnal::Struct::Options opts; //---------------------------------------------------------------------- namespace BAnal { namespace Struct { class HeaderInfo; class WorkEnv; class WorkItem; class LineMapCache; typedef map <Block *, bool> BlockSet; typedef map <VMA, HeaderInfo> HeaderList; typedef map <VMA, Region *> RegionMap; typedef vector <Statement::Ptr> StatementVector; typedef vector <WorkItem *> WorkList; static FileMap * makeSkeleton(CodeObject *, const string &); static void doWorkItem(WorkItem *, string &, bool, bool); static void makeWorkList(FileMap *, WorkList &, WorkList &); static void printWorkList(WorkList &, uint &, ostream *, ostream *, string &); static void doFunctionList(WorkEnv &, FileInfo *, GroupInfo *, bool); static LoopList * doLoopTree(WorkEnv &, FileInfo *, GroupInfo *, ParseAPI::Function *, BlockSet &, LoopTreeNode *); static TreeNode * doLoopLate(WorkEnv &, GroupInfo *, ParseAPI::Function *, BlockSet &, Loop *, const string &); static void doBlock(WorkEnv &, GroupInfo *, ParseAPI::Function *, BlockSet &, Block *, TreeNode *); static void addGaps(WorkEnv & env, FileInfo *, GroupInfo *); static void getStatement(StatementVector &, Offset, SymtabAPI::Function *); static LoopInfo * findLoopHeader(WorkEnv & env, FileInfo *, GroupInfo *, ParseAPI::Function *, TreeNode *, Loop *, const string &); static TreeNode * deleteInlinePrefix(WorkEnv &, TreeNode *, Inline::InlineSeqn); static void mergeIrredLoops(WorkEnv &, LoopInfo *); static void computeGaps(VMAIntervalSet &, VMAIntervalSet &, VMA, VMA); static void doUnparsableFunctionList(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo); static void doUnparsableFunction(WorkEnv & env, GroupInfo * ginfo, ParseAPI::Function * func, TreeNode * root); //---------------------------------------------------------------------- #if DEBUG_ANY_ON #define DEBUG_ANY(expr) std::cout << expr static string debugPrettyName(const string &); static void debugElfHeader(ElfFile *); static void debugFuncHeader(FileInfo *, ProcInfo *, long, long, string = ""); static void debugStmt(VMA, int, string &, SrcFile::ln, RealPathMgr *); static void debugEdges(Block * block); static void debugLoop(GroupInfo *, ParseAPI::Function *, Loop *, const string &, vector <Edge *> &, HeaderList &, RealPathMgr *); static void debugInlineTree(TreeNode *, LoopInfo *, HPC::StringTable &, int, bool); #else // ! DEBUG_ANY_ON #define DEBUG_ANY(expr) #endif #if DEBUG_CFG_SOURCE #define DEBUG_CFG(expr) std::cout << expr #else #define DEBUG_CFG(expr) #endif #if DEBUG_MAKE_SKEL #define DEBUG_SKEL(expr) std::cout << expr #else #define DEBUG_SKEL(expr) #endif #if DEBUG_SHOW_GAPS #define DEBUG_GAPS(expr) std::cout << expr #else #define DEBUG_GAPS(expr) #endif //---------------------------------------------------------------------- // Info on candidates for loop header. class HeaderInfo { public: Block * block; bool is_src; bool is_excl; int depth; long file_index; long base_index; long line_num; vector <FLPIndex> flp_path; HeaderInfo(Block * blk = NULL) { block = blk; is_src = false; is_excl = false; depth = 0; file_index = 0; base_index = 0; line_num = 0; flp_path.clear(); } }; //---------------------------------------------------------------------- // The environment for interpreting paths, strings, etc. We allocate // one environ per thread to avoid lock contention. // class WorkEnv { public: HPC::StringTable * strTab; RealPathMgr * realPath; WorkEnv() { strTab = NULL; realPath = NULL; } }; // One item in the work list for openmp parallel region. class WorkItem { public: FileInfo * finfo; GroupInfo * ginfo; WorkEnv env; double cost; bool first_proc; bool last_proc; bool promote; boost::atomic <bool> is_done; WorkItem(FileInfo * fi, GroupInfo * gi, bool first, bool last, double cst) { finfo = fi; ginfo = gi; cost = cst; first_proc = first; last_proc = last; promote = false; is_done.store(false); } }; //---------------------------------------------------------------------- // A simple cache of getStatement() that stores one line range. This // saves extra calls to getSourceLines() if we don't need them. // class LineMapCache { private: SymtabAPI::Function * sym_func; RealPathMgr * realPath; string cache_filenm; uint cache_line; VMA start; VMA end; public: LineMapCache(SymtabAPI::Function * sf, RealPathMgr * rp) { sym_func = sf; realPath = rp; cache_filenm = ""; cache_line = 0; start = 1; end = 0; } bool getLineInfo(VMA vma, string & filenm, uint & line) { // try cache first if (start <= vma && vma < end) { filenm = cache_filenm; line = cache_line; return true; } // lookup with getStatement() and getSourceLines() StatementVector svec; getStatement(svec, vma, sym_func); if (! svec.empty()) { filenm = svec[0]->getFile(); line = svec[0]->getLine(); realPath->realpath(filenm); cache_filenm = filenm; cache_line = line; start = svec[0]->startAddr(); end = svec[0]->endAddr(); return true; } // no line info available filenm = ""; line = 0; return false; } }; //---------------------------------------------------------------------- // Comparison functions to sort blocks, edges, loops for more // deterministic output. // Sort Blocks by start address, low to high. static bool BlockLessThan(Block * b1, Block * b2) { return b1->start() < b2->start(); } // Sort Edges first by target address (usually all the same), and then // by source address. static bool EdgeLessThan(Edge * e1, Edge * e2) { return (e1->trg()->start() < e2->trg()->start()) || (e1->trg()->start() == e2->trg()->start() && e1->src()->last() < e2->src()->last()); } // Sort Work Items by the expected 'cost' of their proc group, largest // to smallest. static bool WorkItemGreaterThan(WorkItem * w1, WorkItem * w2) { return w1->cost > w2->cost; } // Returns: the min entry VMA for the loop, or else 0 if the loop is // somehow invalid. Irreducible loops have more than one entry // address. static VMA LoopMinEntryAddr(Loop * loop) { if (loop == NULL) { return 0; } vector <Block *> entBlocks; int num_ents = loop->getLoopEntries(entBlocks); if (num_ents < 1) { return 0; } VMA ans = VMA_MAX; for (int i = 0; i < num_ents; i++) { ans = std::min(ans, entBlocks[i]->start()); } return ans; } // Sort Loops (from their LoopTreeNodes) by min entry VMAs. static bool LoopTreeLessThan(LoopTreeNode * n1, LoopTreeNode * n2) { return LoopMinEntryAddr(n1->loop) < LoopMinEntryAddr(n2->loop); } // Sort LoopInfo objects by min entry VMAs. static bool LoopInfoLessThan(LoopInfo * l1, LoopInfo * l2) { return l1->entry_vma < l2->entry_vma; } //---------------------------------------------------------------------- // Line map info from SymtabAPI. Try the Module associated with the // Symtab Function as a hint first, else look for other modules that // might contain vma. // static void getStatement(StatementVector & svec, Offset vma, SymtabAPI::Function * sym_func) { svec.clear(); // try the Module in sym_func first as a hint if (sym_func != NULL) { Module * mod = sym_func->getModule(); if (mod != NULL) { mod->getSourceLines(svec, vma /*+ cubin_size*/); } } // else look for other modules if (svec.empty()) { set <Module *> modSet; the_symtab->findModuleByOffset(modSet, vma); for (auto mit = modSet.begin(); mit != modSet.end(); ++mit) { (*mit)->getSourceLines(svec, vma /*+ cubin_size*/); if (! svec.empty()) { break; } } } // a known file and unknown line is now legal, but we require that // any line map must contain a file name if (! svec.empty() && svec[0]->getFile() == "") { svec.clear(); } } //---------------------------------------------------------------------- // // Display time and space usage per phase in makeStructure. // static void printTime(const char *label, struct timeval *tv_prev, struct rusage *ru_prev, struct timeval *tv_now, struct rusage *ru_now) { gettimeofday(tv_now, NULL); getrusage(RUSAGE_SELF, ru_now); float delta = (float)(tv_now->tv_sec - tv_prev->tv_sec) + ((float)(tv_now->tv_usec - tv_prev->tv_usec))/1000000.0; printf("%s %8.1f sec %8ld meg %8ld meg", label, delta, (ru_now->ru_maxrss - ru_prev->ru_maxrss)/1024, ru_now->ru_maxrss/1024); cout << endl; } // // makeStructure -- the main entry point for hpcstruct realmain(). // // Read the binutils load module and the parseapi code object, iterate // over functions, loops and blocks, make an internal inline tree and // write an hpcstruct file to 'outFile'. // // Fixme: may want to rethink the split between tool/hpcstruct and // lib/banal. // void makeStructure(string filename, ostream * outFile, ostream * gapsFile, string gaps_filenm, string search_path, Struct::Options & structOpts) { struct timeval tv_init, tv_symtab, tv_parse, tv_fini; struct rusage ru_init, ru_symtab, ru_parse, ru_fini; opts = structOpts; #ifdef ENABLE_OPENMP omp_set_num_threads(opts.jobs_symtab); #endif InputFile inputFile; // failure throws an error up the call chain inputFile.openFile(filename, InputFileError_Error); ElfFileVector * elfFileVector = inputFile.fileVector(); string & sfilename = inputFile.fileName(); const char * cfilename = inputFile.CfileName(); if (elfFileVector == NULL || elfFileVector->empty()) { return; } Output::printStructFileBegin(outFile, gapsFile, sfilename); for (uint i = 0; i < elfFileVector->size(); i++) { bool parsable = true; ElfFile *elfFile = (*elfFileVector)[i]; if (opts.show_time) { cout << "file: " << elfFile->getFileName() << "\n" << "symtab threads: " << opts.jobs_symtab << " parse: " << opts.jobs_parse << " struct: " << opts.jobs_struct << "\n\n"; printTime("init: ", &tv_init, &ru_init, &tv_init, &ru_init); } #if DEBUG_ANY_ON debugElfHeader(elfFile); #endif #ifdef ENABLE_OPENMP omp_set_num_threads(opts.jobs_symtab); #endif Symtab * symtab = Inline::openSymtab(elfFile); if (symtab == NULL) { continue; } the_symtab = symtab; bool cuda_file = SYMTAB_ARCH_CUDA(symtab); // pre-compute line map info vector <Module *> modVec; the_symtab->getAllModules(modVec); #pragma omp parallel shared(modVec) { #pragma omp for schedule(dynamic, 1) for (uint i = 0; i < modVec.size(); i++) { Module * mod = modVec[i]; mod->parseLineInformation(); } } // end parallel if (opts.show_time) { printTime("symtab:", &tv_init, &ru_init, &tv_symtab, &ru_symtab); } CodeSource *code_src = NULL; CodeObject *code_obj = NULL; #ifdef ENABLE_OPENMP omp_set_num_threads(opts.jobs_parse); #endif bool intel_file = elfFile->isIntelGPUFile(); if (cuda_file) { // don't run parseapi on cuda binary cuda_arch = elfFile->getArch(); cubin_size = elfFile->getLength(); parsable = readCudaCFG(search_path, elfFile, the_symtab, structOpts.compute_gpu_cfg, &code_src, &code_obj); } else if (intel_file) { // don't run parseapi on intel binary // TODO(Aaron): determine which generation of intel gpu it is intel_gpu_arch = 1; #ifdef ENABLE_IGC parsable = readIntelCFG(search_path, elfFile, the_symtab, structOpts.compute_gpu_cfg, &code_src, &code_obj); #endif // ENABLE_IGC } else { code_src = new SymtabCodeSource(symtab); code_obj = new CodeObject(code_src); code_obj->parse(); intel_gpu_arch = 0; cuda_arch = 0; cubin_size = 0; } if (opts.show_time) { printTime("parse: ", &tv_symtab, &ru_symtab, &tv_parse, &ru_parse); } #ifdef ENABLE_OPENMP omp_set_num_threads(opts.jobs_struct); #endif string basename = FileUtil::basename(cfilename); FileMap * fileMap = makeSkeleton(code_obj, basename); // // make two work lists: // wlPrint -- the output order in the struct file as determined // by files and procs from makeSkeleton(), // wlLaunch -- the order we launch doWorkItem(), mostly print // order but with a few, very large funcs moved to the front of // the list. // WorkList wlPrint; WorkList wlLaunch; uint num_done = 0; mutex output_mtx; makeWorkList(fileMap, wlPrint, wlLaunch); Output::printLoadModuleBegin(outFile, elfFile->getFileName()); #pragma omp parallel default(none) \ shared(wlPrint, wlLaunch, num_done, output_mtx) \ firstprivate(outFile, gapsFile, search_path, gaps_filenm, parsable) { #pragma omp for schedule(dynamic, 1) for (uint i = 0; i < wlLaunch.size(); i++) { doWorkItem(wlLaunch[i], search_path, parsable, gapsFile != NULL); // the printing must be single threaded if (output_mtx.try_lock()) { printWorkList(wlPrint, num_done, outFile, gapsFile, gaps_filenm); output_mtx.unlock(); } } } // end parallel // with try_lock(), there are interleavings where not all items // have been printed. printWorkList(wlPrint, num_done, outFile, gapsFile, gaps_filenm); Output::printLoadModuleEnd(outFile); if (opts.show_time) { printTime("struct:", &tv_parse, &ru_parse, &tv_fini, &ru_fini); printTime("total: ", &tv_init, &ru_init, &tv_fini, &ru_fini); cout << "\nnum funcs: " << wlPrint.size() << "\n" << endl; } // if this is the last (or only) elf file, then don't bother with // piecemeal cleanup. if (i + 1 < elfFileVector->size()) { for (uint i = 0; i < wlPrint.size(); i++) { delete wlPrint[i]; } delete code_obj; #if 0 // FIXME: CodeSource::~CodeSource needs to be public delete code_src; #endif Inline::closeSymtab(); } } Output::printStructFileEnd(outFile, gapsFile); } //---------------------------------------------------------------------- // // Make the inline tree for funcs in one proc group. This much can // run concurrently. // static void doWorkItem(WorkItem * witem, string & search_path, bool parsable, bool fullGaps) { FileInfo * finfo = witem->finfo; GroupInfo * ginfo = witem->ginfo; // each work item gets its own string table and path manager to // avoid lock contention. HPC::StringTable * strTab = new HPC::StringTable; strTab->str2index(""); PathFindMgr * pathFind = new PathFindMgr; PathReplacementMgr * pathReplace = new PathReplacementMgr; RealPathMgr * realPath = new RealPathMgr(pathFind, pathReplace); realPath->searchPaths(search_path); witem->env.strTab = strTab; witem->env.realPath = realPath; if (parsable) { doFunctionList(witem->env, finfo, ginfo, fullGaps); } else { doUnparsableFunctionList(witem->env, finfo, ginfo); } ANNOTATE_HAPPENS_BEFORE(&witem->is_done); witem->is_done.exchange(true); } //---------------------------------------------------------------------- // // Make work lists for the print order and parallel launch order from // the skeleton file map. The launch order is mostly the print order // with a few, very large funcs moved to the front. // // There are two extremes to avoid: (1) we don't want the printing to // be blocked by one early func that was started late, and (2) we // don't want one large func to run at the end when all the other // threads are idle. // static void makeWorkList(FileMap * fileMap, WorkList & wlPrint, WorkList & wlLaunch) { double total_cost = 0.0; wlPrint.clear(); wlLaunch.clear(); // the print order is determined by the hierarchy of files and // groups in the skeleton. for (auto fit = fileMap->begin(); fit != fileMap->end(); ++fit) { FileInfo * finfo = fit->second; auto group_begin = finfo->groupMap.begin(); auto group_end = finfo->groupMap.end(); for (auto git = group_begin; git != group_end; ++git) { GroupInfo * ginfo = git->second; auto next_git = git; ++next_git; // the estimated time is non-linear in the size of the region double cost = ginfo->end - ginfo->start; cost *= cost; total_cost += cost; WorkItem * witem = new WorkItem(finfo, ginfo, (git == group_begin), (next_git == group_end), cost); wlPrint.push_back(witem); } } // if single-threaded, then order doesn't matter if (opts.jobs_struct == 1) { wlLaunch = wlPrint; return; } // // if the expected cost of one function is more than 5% of the ideal // parallel run time, then promote it to start early. // double threshold = WORK_LIST_PCT * total_cost / ((double) opts.jobs_struct); for (auto wit = wlPrint.begin(); wit != wlPrint.end(); ++wit) { WorkItem * witem = *wit; if (witem->cost > threshold) { wlLaunch.push_back(witem); witem->promote = true; } } std::sort(wlLaunch.begin(), wlLaunch.end(), WorkItemGreaterThan); // add the small items in print order for (auto wit = wlPrint.begin(); wit != wlPrint.end(); ++wit) { WorkItem * witem = *wit; if (! witem->promote) { wlLaunch.push_back(witem); } } } //---------------------------------------------------------------------- // // Scan the work list from num_done to end for items that are ready to // be printed. The output order is always work list order, regardless // of order finished. // // Note: the output functions have state (index number), so this must // be called locked or else single threaded. // static void printWorkList(WorkList & workList, uint & num_done, ostream * outFile, ostream * gapsFile, string & gaps_filenm) { while (num_done < workList.size() && workList[num_done]->is_done.load()) { ANNOTATE_HAPPENS_AFTER(&workList[num_done]->is_done); WorkItem * witem = workList[num_done]; FileInfo * finfo = witem->finfo; GroupInfo * ginfo = witem->ginfo; HPC::StringTable * strTab = witem->env.strTab; if (witem->first_proc) { Output::printFileBegin(outFile, finfo); } for (auto pit = ginfo->procMap.begin(); pit != ginfo->procMap.end(); ++pit) { ProcInfo * pinfo = pit->second; if (! pinfo->gap_only) { Output::printProc(outFile, gapsFile, gaps_filenm, finfo, ginfo, pinfo, *strTab); } delete pinfo->root; pinfo->root = NULL; } if (witem->last_proc) { Output::printFileEnd(outFile, finfo); } // delete the work environment delete strTab; witem->env.strTab = NULL; delete witem->env.realPath; witem->env.realPath = NULL; num_done++; } } //---------------------------------------------------------------------- // codeMap is a map of all code regions from start vma to Region *. // Used to find the region containing a vma and thus the region's end. // static void makeCodeMap(RegionMap & codeMap) { DEBUG_SKEL("\n"); vector <Region *> regVec; the_symtab->getCodeRegions(regVec); codeMap.clear(); for (auto it = regVec.begin(); it != regVec.end(); ++it) { Region * reg = *it; VMA start = reg->getMemOffset(); codeMap[start] = reg; DEBUG_SKEL("code region: 0x" << hex << start << "--0x" << (start + reg->getMemSize()) << dec << " " << reg->getRegionName() << "\n"); } #if DEBUG_MAKE_SKEL // print the list of modules vector <Module *> modVec; the_symtab->getAllModules(modVec); cout << "\n"; for (auto mit = modVec.begin(); mit != modVec.end(); ++mit) { Module * mod = *mit; if (mod != NULL) { cout << "module: 0x" << hex << mod->addr() << dec << " (lang " << mod->language() << ")" << " " << mod->fullName() << "\n"; } } #endif } // Note: normally, code regions don't overlap, but if they do, then we // find the Region with the highest start address that contains vma. // // Returns: the Region containing vma, or else NULL. // static Region * findCodeRegion(RegionMap & codeMap, VMA vma) { auto it = codeMap.upper_bound(vma); // invariant: vma is not in range it...end while (it != codeMap.begin()) { --it; Region * reg = it->second; VMA start = reg->getMemOffset(); VMA end = start + reg->getMemSize(); if (start <= vma && vma < end) { return reg; } } return NULL; } //---------------------------------------------------------------------- // getProcLineMap -- helper for makeSkeleton() to find line map info // for the start of a Procedure. // // Some compilers, especially for CUDA binaries, and sometimes dyninst // or libdwarf, omit or fail to read line map info for the first few // bytes of a function. Rather than returning 'unknown file', we try // scanning the first few hundred bytes in the proc. // static void getProcLineMap(StatementVector & svec, Offset vma, Offset end, SymtabAPI::Function * sym_func) { svec.clear(); if (cuda_arch > 0) { // TODO(Keren): Use the same method below and remove magic numbers for instruction length // mod->getSourceLines(svec, next + cubin_size); int len = (cuda_arch >= 70) ? 16 : 8; StatementVector tmp; // find the minimal line only for the first few instructions for (size_t i = vma; i < end && i < vma + len * CUDA_PROC_SEARCH_LEN; i += len) { getStatement(tmp, i, sym_func); if (!tmp.empty()) { if (svec.empty()) { svec.push_back(tmp[0]); } else if (tmp[0]->getFile() == svec[0]->getFile() && tmp[0]->getLine() < svec[0]->getLine()) { svec[0] = tmp[0]; } } } if (!svec.empty()) { return; } // if no line mapping information found, iterating the whole function until find one for (size_t i = vma + len * CUDA_PROC_SEARCH_LEN; i < end; i += len) { getStatement(tmp, i, sym_func); if (!tmp.empty()) { if (svec.empty()) { svec.push_back(tmp[0]); return; } } } return; } // try a full module lookup first getStatement(svec, vma, sym_func); if (! svec.empty()) { return; } // confine further searches to the primary module if (sym_func == NULL) { return; } Module * mod = sym_func->getModule(); if (mod == NULL) { return; } // retry every 'step' bytes, but double the step every 8 tries to // make a logarithmic search const int init_step = 2; const int max_tries = 8; int step = init_step; int num_tries = 0; end = std::min(end, vma + 800); for (;;) { // invariant: vma does not have line info, but next might Offset next = vma + step; if (next >= end) { break; } mod->getSourceLines(svec, next + cubin_size); num_tries++; if (! svec.empty()) { // rescan the range [vma, next) but start over with a small step if (step <= init_step) { break; } svec.clear(); step = init_step; num_tries = 0; } else { // advance vma and double the step after 8 tries vma = next; if (num_tries >= max_tries) { step *= 2; num_tries = 0; } } } } // addProc -- helper for makeSkeleton() to locate and add one ProcInfo // object into the global file map. // static void addProc(FileMap * fileMap, ProcInfo * pinfo, string & filenm, SymtabAPI::Function * sym_func, VMA start, VMA end, bool alt_file = false) { // locate in file map, or else insert FileInfo * finfo = NULL; auto fit = fileMap->find(filenm); if (fit != fileMap->end()) { finfo = fit->second; } else { finfo = new FileInfo(filenm); (*fileMap)[filenm] = finfo; } // locate in group map, or else insert GroupInfo * ginfo = NULL; auto git = finfo->groupMap.find(start); if (git != finfo->groupMap.end()) { ginfo = git->second; } else { ginfo = new GroupInfo(sym_func, start, end, alt_file); finfo->groupMap[start] = ginfo; } ginfo->procMap[pinfo->entry_vma] = pinfo; #if DEBUG_MAKE_SKEL cout << "link: " << pinfo->linkName << "\n" << "pretty: " << pinfo->prettyName << "\n" << (alt_file ? "alt-file: " : "file: ") << finfo->fileName << "\n" << "group: 0x" << hex << ginfo->start << "--0x" << ginfo->end << dec << "\n"; #endif } //---------------------------------------------------------------------- // getFuncNames -- helper for makeSkeleton() to select the pretty // (demangled) and link (mangled) names for a SymtabAPI::Function. // // Some functions have multiple symbols with different names for the // same address (global and weak syms). We sort the symbol names to // make the choice deterministic. We could prefer a global symbol, // but global is not always unique. // // Note: prettynm and linknm are passed in with default (unknown proc) // values, so don't overwrite them unless there is at least one valid // name. // // Note: we now use symtab only for mangled names and do all the // demangling ourselves. // static void getFuncNames(SymtabAPI::Function * sym_func, string & prettynm, string & linknm) { auto mangled_begin = sym_func->mangled_names_begin(); auto mangled_end = sym_func->mangled_names_end(); for (auto mit = mangled_begin; mit != mangled_end; ++mit) { string new_mangled = *mit; // sort by: longer mangled name (more info), or else by // alphabetically lower name (arbitrary). if (mit == mangled_begin || (new_mangled.length() > linknm.length()) || (new_mangled.length() == linknm.length() && new_mangled.compare(linknm) < 0)) { linknm = new_mangled; prettynm = BinUtil::demangleProcName(linknm); } } } //---------------------------------------------------------------------- // makeSkeleton -- the new buildLMSkeleton // // In the ParseAPI version, we iterate over the ParseAPI list of // functions and match them up with the SymtabAPI functions by entry // address. We now use Symtab for the line map info. // // Note: several parseapi functions (targ410aa7) may map to the same // symtab proc, so we make a func list (group). // static FileMap * makeSkeleton(CodeObject * code_obj, const string & basename) { FileMap * fileMap = new FileMap; string unknown_base = "[" + basename + "]"; bool is_shared = ! (the_symtab->isExec()); // map of code regions to find end of region RegionMap codeMap; makeCodeMap(codeMap); // iterate over the ParseAPI Functions, order by vma const CodeObject::funclist & funcList = code_obj->funcs(); map <VMA, ParseAPI::Function *> funcMap; for (auto flit = funcList.begin(); flit != funcList.end(); ++flit) { ParseAPI::Function * func = *flit; funcMap[func->addr()] = func; } for (auto fmit = funcMap.begin(); fmit != funcMap.end(); ++fmit) { ParseAPI::Function * func = fmit->second; SymtabAPI::Function * sym_func = NULL; VMA vma = func->addr(); auto next_it = fmit; ++next_it; VMA next_vma = (next_it != funcMap.end()) ? next_it->second->addr() : 0; stringstream buf; buf << "0x" << hex << vma << dec; string vma_str = buf.str(); DEBUG_SKEL("\nskel: " << vma_str << " " << func->name() << "\n"); // see if entry vma lies within a valid symtab function bool found = the_symtab->getContainingFunction(vma, sym_func); VMA sym_start = 0; VMA sym_end = 0; Region * region = NULL; VMA reg_start = 0; VMA reg_end = 0; if (found && sym_func != NULL) { sym_start = sym_func->getOffset(); sym_end = sym_start + sym_func->getSize(); region = sym_func->getRegion(); if (region != NULL) { reg_start = region->getMemOffset(); reg_end = reg_start + region->getMemSize(); } } DEBUG_SKEL("symbol: 0x" << hex << sym_start << "--0x" << sym_end << " next: 0x" << next_vma << " region: 0x" << reg_start << "--0x" << reg_end << dec << "\n"); // symtab doesn't recognize plt funcs and puts them in the wrong // region. to be a valid symbol, the func entry must lie within // the symbol's region. if (found && sym_func != NULL && region != NULL && reg_start <= vma && vma < reg_end) { string filenm = unknown_base; string linknm = unknown_link + vma_str; string prettynm = unknown_proc + " " + vma_str + " [" + basename + "]"; SrcFile::ln line = 0; // symtab lets some funcs (_init) spill into the next region if (sym_start < reg_end && reg_end < sym_end) { sym_end = reg_end; } // line map for symtab func vector <Statement::Ptr> svec; getProcLineMap(svec, sym_start, sym_end, sym_func); if (! svec.empty()) { filenm = svec[0]->getFile(); line = svec[0]->getLine(); RealPathMgr::singleton().realpath(filenm); } if (vma == sym_start) { // // case 1 -- group leader of a valid symtab func. take proc // names from symtab func. this is the normal case (but other // cases are also valid). // DEBUG_SKEL("(case 1)\n"); getFuncNames(sym_func, prettynm, linknm); if (is_shared) { prettynm += " [" + basename + "]"; } ProcInfo * pinfo = new ProcInfo(func, NULL, linknm, prettynm, line, sym_func->getFirstSymbol()->getIndex()); addProc(fileMap, pinfo, filenm, sym_func, sym_start, sym_end); } else { // outline func -- see if parseapi and symtab file names match string parse_filenm = unknown_base; SrcFile::ln parse_line = 0; // line map for parseapi func vector <Statement::Ptr> pvec; getProcLineMap(pvec, vma, sym_end, sym_func); stringstream buf; buf << "<unknown procedure> " << vma_str; if (! pvec.empty()) { parse_filenm = pvec[0]->getFile(); parse_line = pvec[0]->getLine(); RealPathMgr::singleton().realpath(parse_filenm); string parse_base = FileUtil::basename(parse_filenm.c_str()); buf << " " << parse_base; if (parse_line > 0) buf << ":" << parse_line; } if (is_shared) { buf << " [" << basename << "]"; } linknm = func->name(); prettynm = buf.str(); if (filenm == parse_filenm) { // // case 2 -- outline func inside symtab func with same file // name. use 'outline 0xxxxxx' proc name. // DEBUG_SKEL("(case 2)\n"); ProcInfo * pinfo = new ProcInfo(func, NULL, linknm, prettynm, parse_line); addProc(fileMap, pinfo, filenm, sym_func, sym_start, sym_end); } else { // // case 3 -- outline func but from a different file name. // add proc info to both files: outline file for full parse // (but no gaps), and symtab file for gap only. // DEBUG_SKEL("(case 3)\n"); ProcInfo * pinfo = new ProcInfo(func, NULL, linknm, prettynm, parse_line); addProc(fileMap, pinfo, parse_filenm, sym_func, sym_start, sym_end, true); pinfo = new ProcInfo(func, NULL, "", "", 0, 0, true); addProc(fileMap, pinfo, filenm, sym_func, sym_start, sym_end); } } } else { // // case 4 -- no symtab symbol claiming this vma (and thus no // line map). make a fake group at the parseapi entry vma. // this normally only happens for plt funcs. // string linknm = func->name(); string prettynm = BinUtil::demangleProcName(linknm); VMA end = 0; // symtab doesn't offer any guidance on demangling in this case if (linknm != prettynm && prettynm.find_first_of("()<>") == string::npos) { prettynm = linknm; } region = findCodeRegion(codeMap, vma); reg_start = (region != NULL) ? region->getMemOffset() : 0; reg_end = (region != NULL) ? (reg_start + region->getMemSize()) : 0; DEBUG_SKEL("region: 0x" << hex << reg_start << "--0x" << reg_end << dec << "\n"); DEBUG_SKEL("(case 4)\n"); if (next_it != funcMap.end()) { end = next_vma; if (region != NULL && vma < reg_end && reg_end < end) { end = reg_end; } } else if (region != NULL && vma < reg_end) { end = reg_end; } else { end = vma + 20; } // treat short parseapi functions with no symtab symbol as a plt // stub. not an ideal test, but I (krentel) can't find any // counter examples. if (end - vma <= 32) { int len = linknm.length(); const char *str = linknm.c_str(); if (len < 5 || strncasecmp(&str[len-4], "@plt", 4) != 0) { linknm += "@plt"; prettynm += "@plt"; } } if (is_shared) { prettynm += " [" + basename + "]"; } ProcInfo * pinfo = new ProcInfo(func, NULL, linknm, prettynm, 0); addProc(fileMap, pinfo, unknown_base, NULL, vma, end); } } #if DEBUG_SKEL_SUMMARY // print the skeleton map cout << "\n------------------------------------------------------------\n"; for (auto fit = fileMap->begin(); fit != fileMap->end(); ++fit) { auto finfo = fit->second; for (auto git = finfo->groupMap.begin(); git != finfo->groupMap.end(); ++git) { auto ginfo = git->second; long size = ginfo->procMap.size(); long num = 0; for (auto pit = ginfo->procMap.begin(); pit != ginfo->procMap.end(); ++pit) { auto pinfo = pit->second; num++; cout << "\nentry: 0x" << hex << pinfo->entry_vma << dec << " (" << num << "/" << size << ")\n" << "group: 0x" << hex << ginfo->start << "--0x" << ginfo->end << dec << "\n" << "file: " << finfo->fileName << "\n" << "link: " << pinfo->linkName << "\n" << "pretty: " << pinfo->prettyName << "\n" << "parse: " << pinfo->func->name() << "\n" << "line: " << pinfo->line_num << "\n"; } } } cout << "\n"; #endif return fileMap; } //**************************************************************************** // ParseAPI code for functions, loops and blocks //**************************************************************************** // Remaining TO-DO items: // // 4. Irreducible loops -- study entry blocks, loop header, adjacent // nested loops. Some nested irreducible loops share entry blocks and // maybe should be merged. // // 5. Compute line ranges for loops and procs to help decide what is // alien code when the symtab inline info is not available. // // 6. Handle code movement wrt loops: loop fusion, fission, moving // code in/out of loops. // // 10. Decide how to handle basic blocks that belong to multiple // functions. // // 11. Improve demangle proc names -- the problem is more if/when to // demangle rather than how. Maybe keep a map of symtab mangled to // pretty names. //---------------------------------------------------------------------- // Process the functions in one binutils group. For each ParseAPI // function in the group, create the inline tree and fill in the // TreeNode ptr in ProcInfo. // // One binutils proc may contain multiple embedded parseapi functions. // In that case, we create new proc/file scope nodes for each function // and strip the inline prefix at the call source from the embed // function. This often happens with openmp parallel pragmas. // static void doFunctionList(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo, bool fullGaps) { long num_funcs = ginfo->procMap.size(); set <Address> coveredFuncs; VMAIntervalSet covered; // make a map of internal call edges (from target to source) across // all funcs in this group. we use this to strip the inline seqn at // the call source from the target func. // map <VMA, VMA> callMap; if (ginfo->sym_func != NULL && !ginfo->alt_file && num_funcs > 1) { for (auto pit = ginfo->procMap.begin(); pit != ginfo->procMap.end(); ++pit) { ParseAPI::Function * func = pit->second->func; const ParseAPI::Function::edgelist & elist = func->callEdges(); for (auto eit = elist.begin(); eit != elist.end(); ++eit) { VMA src = (*eit)->src()->last(); VMA targ = (*eit)->trg()->start(); callMap[targ] = src; } } } // one binutils proc may contain several parseapi funcs long num = 0; for (auto pit = ginfo->procMap.begin(); pit != ginfo->procMap.end(); ++pit) { ProcInfo * pinfo = pit->second; ParseAPI::Function * func = pinfo->func; Address entry_addr = func->addr(); num++; // only used for cuda functions pinfo->symbol_index = 0; // compute the inline seqn for the call site for this func, if // there is one. Inline::InlineSeqn prefix; auto call_it = callMap.find(entry_addr); if (call_it != callMap.end()) { analyzeAddr(prefix, call_it->second, env.realPath); } #if DEBUG_CFG_SOURCE debugFuncHeader(finfo, pinfo, num, num_funcs); if (call_it != callMap.end()) { cout << "\ncall site prefix: 0x" << hex << call_it->second << " -> 0x" << call_it->first << dec << "\n"; for (auto pit = prefix.begin(); pit != prefix.end(); ++pit) { cout << "inline: l=" << pit->getLineNum() << " f='" << pit->getFileName() << "' p='" << debugPrettyName(pit->getPrettyName()) << "'\n"; } } #endif // see if this function is entirely contained within another // function (as determined by its entry block). if yes, then we // don't parse the func. but we still use its blocks for gaps, // unless we've already added the containing func. // int num_contain = func->entry()->containingFuncs(); bool add_blocks = true; if (num_contain > 1) { vector <ParseAPI::Function *> funcVec; func->entry()->getFuncs(funcVec); // see if we've already added the containing func for (auto fit = funcVec.begin(); fit != funcVec.end(); ++fit) { Address entry = (*fit)->addr(); if (coveredFuncs.find(entry) != coveredFuncs.end()) { add_blocks = false; break; } } } // skip duplicated function, blocks already added if (! add_blocks) { DEBUG_CFG("\nskipping duplicated function: '" << func->name() << "'\n"); continue; } // basic blocks for this function. put into a vector and sort by // start VMA for deterministic output. vector <Block *> bvec; BlockSet visited; const ParseAPI::Function::blocklist & blist = func->blocks(); for (auto bit = blist.begin(); bit != blist.end(); ++bit) { Block * block = *bit; bvec.push_back(block); visited[block] = false; } std::sort(bvec.begin(), bvec.end(), BlockLessThan); // add to the group's set of covered blocks if (! ginfo->alt_file) { for (auto bit = bvec.begin(); bit != bvec.end(); ++bit) { Block * block = *bit; covered.insert(block->start(), block->end()); } coveredFuncs.insert(entry_addr); } // skip duplicated function, blocks added just now if (num_contain > 1) { DEBUG_CFG("\nskipping duplicated function: '" << func->name() << "'\n"); continue; } // if the outline func file name does not match the enclosing // symtab func, then do the full parse in the outline file // (alt-file) and use the symtab file for gaps only. if (pinfo->gap_only) { DEBUG_CFG("\nskipping full parse (gap only) for function: '" << func->name() << "'\n"); continue; } TreeNode * root = new TreeNode; // traverse the loop (Tarjan) tree LoopList *llist = doLoopTree(env, finfo, ginfo, func, visited, func->getLoopTree()); DEBUG_CFG("\nnon-loop blocks:\n"); // process any blocks not in a loop for (auto bit = bvec.begin(); bit != bvec.end(); ++bit) { Block * block = *bit; if (! visited[block]) { doBlock(env, ginfo, func, visited, block, root); } } // merge the loops into the proc's inline tree FLPSeqn empty; for (auto it = llist->begin(); it != llist->end(); ++it) { mergeInlineLoop(root, empty, *it); } // delete the inline prefix from this func, if non-empty if (! prefix.empty()) { root = deleteInlinePrefix(env, root, prefix); } // add inline tree to proc info pinfo->root = root; #if DEBUG_CFG_SOURCE cout << "\nfinal inline tree: (" << num << "/" << num_funcs << ")" << " link='" << pinfo->linkName << "'\n" << "parse: '" << func->name() << "'\n"; if (call_it != callMap.end()) { cout << "\ncall site prefix: 0x" << hex << call_it->second << " -> 0x" << call_it->first << dec << "\n"; for (auto pit = prefix.begin(); pit != prefix.end(); ++pit) { cout << "inline: l=" << pit->getLineNum() << " f='" << pit->getFileName() << "' p='" << debugPrettyName(pit->getPrettyName()) << "'\n"; } } cout << "\n"; debugInlineTree(root, NULL, *(env.strTab), 0, true); cout << "\nend proc: (" << num << "/" << num_funcs << ")" << " link='" << pinfo->linkName << "'\n" << "parse: '" << func->name() << "'\n"; #endif } // computeGaps relies Block::start() and Block::end() to have // the correct address range for a block to detect gaps. // // Cubins often have branch instructions used as delay slots after // the return instruction of a function. These branches may have PC // samples. However, the CFGs from nvdisasm (at least for cuda-11.2) // do not include delay slot instructions, which causes samples taken // for delay slot instructions to be out of function ranges. // We use gap computation to mitigate this problem. if (intel_gpu_arch == 0) { // add unclaimed regions (gaps) to the group leader, but skip groups // in an alternate file (handled in orig file). if (! ginfo->alt_file) { computeGaps(covered, ginfo->gapSet, ginfo->start, ginfo->end); if (! fullGaps) { addGaps(env, finfo, ginfo); } } } #if DEBUG_SHOW_GAPS auto pit = ginfo->procMap.begin(); ProcInfo * pinfo = pit->second; cout << "\nfunc: 0x" << hex << pinfo->entry_vma << dec << " (1/" << num_funcs << ")\n" << "link: " << pinfo->linkName << "\n" << "parse: " << pinfo->func->name() << "\n" << "0x" << hex << ginfo->start << "--0x" << ginfo->end << dec << "\n"; if (! ginfo->alt_file) { cout << "\ncovered:\n" << covered.toString() << "\n" << "\ngaps:\n" << ginfo->gapSet.toString() << "\n"; } else { cout << "\ngaps: alt-file\n"; } #endif } //---------------------------------------------------------------------- // Returns: list of LoopInfo objects. // // If the loop at this node is non-null (internal node), then the list // contains one element for that loop. If the loop is null (root), // then the list contains one element for each subtree. // static LoopList * doLoopTree(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo, ParseAPI::Function * func, BlockSet & visited, LoopTreeNode * ltnode) { LoopList * myList = new LoopList; if (ltnode == NULL) { return myList; } Loop *loop = ltnode->loop; // process the children of the loop tree vector <LoopTreeNode *> clist = ltnode->children; std::sort(clist.begin(), clist.end(), LoopTreeLessThan); for (uint i = 0; i < clist.size(); i++) { LoopList *subList = doLoopTree(env, finfo, ginfo, func, visited, clist[i]); for (auto sit = subList->begin(); sit != subList->end(); ++sit) { myList->push_back(*sit); } delete subList; } // if no loop at this node (root node), then return the list of // children. if (loop == NULL) { return myList; } // otherwise, finish this loop, put into LoopInfo format, insert the // subloops and return a list of one. string loopName = ltnode->name(); FLPSeqn empty; TreeNode * myLoop = doLoopLate(env, ginfo, func, visited, loop, loopName); for (auto it = myList->begin(); it != myList->end(); ++it) { mergeInlineLoop(myLoop, empty, *it); } // reparent the tree and put into LoopInfo format LoopInfo * myInfo = findLoopHeader(env, finfo, ginfo, func, myLoop, loop, loopName); if (merge_irred_loops) { mergeIrredLoops(env, myInfo); } myList->clear(); myList->push_back(myInfo); return myList; } //---------------------------------------------------------------------- // Post-order process for one loop, after the subloops. Add any // leftover inclusive blocks, select the loop header, reparent as // needed, remove the top inline spine, and put into the LoopInfo // format. // // Returns: the raw inline tree for this loop. // static TreeNode * doLoopLate(WorkEnv & env, GroupInfo * ginfo, ParseAPI::Function * func, BlockSet & visited, Loop * loop, const string & loopName) { TreeNode * root = new TreeNode; DEBUG_CFG("\nbegin loop: " << loopName << " '" << func->name() << "'\n"); // add the inclusive blocks not contained in a subloop vector <Block *> bvec; loop->getLoopBasicBlocks(bvec); std::sort(bvec.begin(), bvec.end(), BlockLessThan); for (uint i = 0; i < bvec.size(); i++) { if (! visited[bvec[i]]) { doBlock(env, ginfo, func, visited, bvec[i], root); } } return root; } //---------------------------------------------------------------------- // Process one basic block. // static void doBlock(WorkEnv & env, GroupInfo * ginfo, ParseAPI::Function * func, BlockSet & visited, Block * block, TreeNode * root) { if (block == NULL || visited[block]) { return; } visited[block] = true; DEBUG_CFG("\nblock:\n"); // see if this block ends with a call edge const Block::edgelist & outEdges = block->targets(); bool is_call = false; bool is_sink = false; VMA target = 0; for (auto eit = outEdges.begin(); eit != outEdges.end(); ++eit) { Edge * edge = *eit; if (edge->type() == ParseAPI::CALL) { is_call = true; is_sink = edge->sinkEdge(); target = edge->trg()->start(); break; } } LineMapCache lmcache (ginfo->sym_func, env.realPath); // iterate through the instructions in this block map <Offset, Instruction> imap; block->getInsns(imap); int len = 0; string device; if (cuda_arch > 0) { device = "NVIDIA sm_" + std::to_string(cuda_arch); } else if (intel_gpu_arch > 0) { device = "INTEL GPU"; } for (auto iit = imap.begin(); iit != imap.end(); ++iit) { auto next_it = iit; next_it++; Offset vma = iit->first; string filenm = ""; uint line = 0; len = iit->second.size(); lmcache.getLineInfo(vma, filenm, line); #if DEBUG_CFG_SOURCE debugStmt(vma, len, filenm, line, env.realPath); #endif // a call must be the last instruction in the block if (next_it == imap.end() && is_call) { addStmtToTree(root, *(env.strTab), env.realPath, vma, len, filenm, line, device, is_call, is_sink, target); } else { addStmtToTree(root, *(env.strTab), env.realPath, vma, len, filenm, line, device); } } #if DEBUG_CFG_SOURCE debugEdges(block); #endif } //---------------------------------------------------------------------- // Unparsable functions // static void doUnparsableFunctionList(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo) { // not sure if cuda generates multiple functions, but we'll handle // this case until proven otherwise. long num = 0; for (auto pit = ginfo->procMap.begin(); pit != ginfo->procMap.end(); ++pit) { ProcInfo * pinfo = pit->second; ParseAPI::Function * func = pinfo->func; num++; #if DEBUG_CFG_SOURCE long num_funcs = ginfo->procMap.size(); debugFuncHeader(finfo, pinfo, num, num_funcs, "cuda"); #endif TreeNode * root = new TreeNode; doUnparsableFunction(env, ginfo, func, root); pinfo->root = root; } } static void doUnparsableFunction(WorkEnv & env, GroupInfo * ginfo, ParseAPI::Function * func, TreeNode * root) { LineMapCache lmcache (ginfo->sym_func, env.realPath); int len = 4; for (Offset vma = ginfo->start; vma < ginfo->end; vma += len) { string filenm = ""; uint line = 0; lmcache.getLineInfo(vma, filenm, line); string device; addStmtToTree(root, *(env.strTab), env.realPath, vma, len, filenm, line, device); } } //---------------------------------------------------------------------- // Add unclaimed regions (gaps) to the group leader. // // This is the basic version -- if line map exists, add a top-level // stmt to the func for each line map range, else assign to the first // line of func. The full version is handled in Struct-Output.cpp. // static void addGaps(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo) { if (ginfo->procMap.begin() == ginfo->procMap.end()) { return; } ProcInfo * pinfo = ginfo->procMap.begin()->second; // if one function is entirely contained within another function, // then it's possible that ProcInfo has no statements and a NULL // TreeNode. if (pinfo->root == NULL) { pinfo->root = new TreeNode; } TreeNode * root = pinfo->root; for (auto git = ginfo->gapSet.begin(); git != ginfo->gapSet.end(); ++git) { VMA vma = git->beg(); VMA end_gap = git->end(); while (vma < end_gap) { StatementVector svec; getStatement(svec, vma, ginfo->sym_func); if (! svec.empty()) { string filenm = svec[0]->getFile(); SrcFile::ln line = svec[0]->getLine(); VMA end = std::min(((VMA) svec[0]->endAddr()), end_gap); string device; addStmtToTree(root, *(env.strTab), env.realPath, vma, end - vma, filenm, line, device); vma = end; } else { // fixme: could be better at finding end of range VMA end = std::min(vma + 4, end_gap); string device; addStmtToTree(root, *(env.strTab), env.realPath, vma, end - vma, finfo->fileName, pinfo->line_num, device); vma = end; } } } } //**************************************************************************** // Support functions //**************************************************************************** // New heuristic for identifying loop header inside inline tree. // Start at the root, descend the inline tree and try to find where // the loop begins. This is the central problem of all hpcstruct: // where to locate a loop inside an inline sequence. // // Note: loop "headers" are no longer tied to a specific VMA and // machine instruction. They are strictly file and line number. // (For some loops, there is no right VMA.) // // Returns: detached LoopInfo object. // static LoopInfo * findLoopHeader(WorkEnv & env, FileInfo * finfo, GroupInfo * ginfo, ParseAPI::Function * func, TreeNode * root, Loop * loop, const string & loopName) { HPC::StringTable * strTab = env.strTab; long empty_index = strTab->str2index(""); //------------------------------------------------------------ // Step 1 -- build the list of loop exit conditions //------------------------------------------------------------ vector <Block *> inclBlocks; set <Block *> bset; HeaderList clist; loop->getLoopBasicBlocks(inclBlocks); for (auto bit = inclBlocks.begin(); bit != inclBlocks.end(); ++bit) { bset.insert(*bit); } // a stmt is a loop exit condition if it has outgoing edges to // blocks both inside and outside the loop. but don't include call // edges. (don't need to sort blocks and edges here because the // real answer is clist and clist is a map.) // for (auto bit = inclBlocks.begin(); bit != inclBlocks.end(); ++bit) { Block * block = *bit; const Block::edgelist & outEdges = block->targets(); VMA src_vma = block->last(); bool in_loop = false, out_loop = false; for (auto eit = outEdges.begin(); eit != outEdges.end(); ++eit) { Block *dest = (*eit)->trg(); int type = (*eit)->type(); if (type != ParseAPI::CALL && type != ParseAPI::CALL_FT) { if (bset.find(dest) != bset.end()) { in_loop = true; } else { out_loop = true; } } } if (in_loop && out_loop) { string filenm = ""; SrcFile::ln line = 0; // terminal line map info StatementVector svec; getStatement(svec, src_vma, ginfo->sym_func); if (! svec.empty()) { filenm = svec[0]->getFile(); line = svec[0]->getLine(); env.realPath->realpath(filenm); } InlineSeqn seqn; analyzeAddr(seqn, src_vma, env.realPath); clist[src_vma] = HeaderInfo(block); clist[src_vma].is_excl = loop->hasBlockExclusive(block); clist[src_vma].depth = seqn.size(); clist[src_vma].file_index = strTab->str2index(filenm); clist[src_vma].base_index = strTab->str2index(FileUtil::basename(filenm)); clist[src_vma].line_num = line; // inline sequence as vector of flp index clist[src_vma].flp_path.clear(); for (auto it = seqn.begin(); it != seqn.end(); ++it) { InlineNode node = *it; clist[src_vma].flp_path.push_back(FLPIndex(*strTab, node)); } } } // see if stmt is also a back edge source. (we sort the back edges // only for debug output.) vector <Edge *> backEdges; loop->getBackEdges(backEdges); std::sort(backEdges.begin(), backEdges.end(), EdgeLessThan); for (auto eit = backEdges.begin(); eit != backEdges.end(); ++eit) { VMA src_vma = (*eit)->src()->last(); auto it = clist.find(src_vma); if (it != clist.end()) { it->second.is_src = true; } } #if DEBUG_CFG_SOURCE cout << "\nraw inline tree: " << loopName << " '" << func->name() << "'\n" << "file: '" << finfo->fileName << "'\n\n"; debugInlineTree(root, NULL, *strTab, 0, false); debugLoop(ginfo, func, loop, loopName, backEdges, clist, env.realPath); #endif //------------------------------------------------------------ // Step 2 -- find the right inline depth //------------------------------------------------------------ // start at the root, descend the inline tree and try to find the // right level for the loop. an inline branch or subloop is an // absolute stopping point. the hard case is one inline subtree // plus statements. we stop if there is a loop condition, else // continue and reparent the stmts. always reparent any stmt in a // different file from the inline callsite. FLPSeqn path; StmtMap stmts; int depth_root = 0; DEBUG_CFG("\nsearching for loop depth ...\n"); while (root->nodeMap.size() == 1 && root->loopList.size() == 0) { FLPIndex flp = root->nodeMap.begin()->first; // look for loop cond at this level for (auto cit = clist.begin(); cit != clist.end(); ++cit) { VMA vma = cit->first; if (root->stmtMap.member(vma)) { DEBUG_CFG("exit cond at this level: 0x" << hex << vma << dec << "\n"); goto found_level; } // reparented stmts must also match file name StmtInfo * sinfo = stmts.findStmt(vma); if (sinfo != NULL && sinfo->base_index == flp.base_index) { DEBUG_CFG("unable to reparent stmts: 0x" << hex << vma << dec << "\n"); goto found_level; } } // reparent the stmts and proceed to the next level for (auto sit = root->stmtMap.begin(); sit != root->stmtMap.end(); ++sit) { stmts.insert(sit->second); } root->stmtMap.clear(); TreeNode *subtree = root->nodeMap.begin()->second; root->nodeMap.clear(); delete root; root = subtree; path.push_back(flp); depth_root++; DEBUG_CFG("inline: l=" << flp.line_num << " f='" << strTab->index2str(flp.file_index) << "' p='" << debugPrettyName(strTab->index2str(flp.pretty_index)) << "'\n"); } #if DEBUG_CFG_SOURCE if (root->nodeMap.size() > 1) { cout << "inline split\n"; } else if (root->nodeMap.size() == 0) { cout << "end of inline steps\n"; } else if (root->loopList.size() > 0) { cout << "subloop\n"; } else { cout << "unknown end\n"; } #endif found_level: #if DEBUG_CFG_SOURCE if (root->nodeMap.size() > 0) { cout << "\nremaining inline subtrees:\n"; for (auto nit = root->nodeMap.begin(); nit != root->nodeMap.end(); ++nit) { FLPIndex flp = nit->first; cout << "inline: l=" << flp.line_num << " f='" << strTab->index2str(flp.file_index) << "' p='" << debugPrettyName(strTab->index2str(flp.pretty_index)) << "'\n"; } } #endif //------------------------------------------------------------ // Step 3 -- reattach stmts into this level //------------------------------------------------------------ // fixme: want to attach some stmts below this level for (auto sit = stmts.begin(); sit != stmts.end(); ++sit) { root->stmtMap.insert(sit->second); } stmts.clear(); //------------------------------------------------------------ // Step 4 -- choose a loop header file/line at this level //------------------------------------------------------------ // choose loop header file based on exit conditions, and then min // line within that file. ideally, we want a file that is both an // exit cond and matches some other anchor: either the enclosing // func (if top-level), or else an inline subtree. long proc_file = strTab->str2index(finfo->fileName); long proc_base = strTab->str2index(FileUtil::basename(finfo->fileName)); long file_ans = empty_index; long base_ans = empty_index; long line_ans = 0; DEBUG_CFG("\nsearching for loop file and line ...\n"); // first choice is the file for the enclosing func that matches some // exit cond at top-level, but only if no inline steps if (depth_root == 0) { for (auto cit = clist.begin(); cit != clist.end(); ++cit) { HeaderInfo * info = &(cit->second); if (info->depth == depth_root && info->base_index != empty_index && info->base_index == proc_base) { file_ans = proc_file; base_ans = proc_base; DEBUG_CFG("file: exit cond at top-level func\n"); goto found_file; } } } // also good is an inline subtree that matches an exit cond for (auto nit = root->nodeMap.begin(); nit != root->nodeMap.end(); ++nit) { FLPIndex flp = nit->first; for (auto cit = clist.begin(); cit != clist.end(); ++cit) { HeaderInfo * info = &(cit->second); if (info->depth == depth_root && info->base_index != empty_index && info->base_index == flp.base_index) { file_ans = flp.file_index; base_ans = flp.base_index; DEBUG_CFG("file: exit cond at inline subtree\n"); goto found_file; } } } // settle for any exit cond at root level. this is the last of the // good answers. for (auto cit = clist.begin(); cit != clist.end(); ++cit) { HeaderInfo * info = &(cit->second); if (info->depth == depth_root && info->base_index != empty_index) { file_ans = info->file_index; base_ans = info->base_index; DEBUG_CFG("file: unmatched exit cond\n"); goto found_file; } } // enclosing func file, but without exit cond if (depth_root == 0 && proc_file != empty_index) { file_ans = proc_file; base_ans = proc_base; DEBUG_CFG("file: enclosing func but no exit cond\n"); goto found_file; } // inline subtree, but without exit cond for (auto nit = root->nodeMap.begin(); nit != root->nodeMap.end(); ++nit) { FLPIndex flp = nit->first; if (flp.file_index != empty_index) { file_ans = flp.file_index; base_ans = flp.base_index; DEBUG_CFG("file: inline subtree but no exit cond\n"); goto found_file; } } // subloop at root level for (auto lit = root->loopList.begin(); lit != root->loopList.end(); ++lit) { LoopInfo * linfo = *lit; if (linfo->file_index != empty_index) { file_ans = linfo->file_index; base_ans = linfo->base_index; DEBUG_CFG("file: any subloop\n"); goto found_file; } } // any stmt at root level for (auto sit = root->stmtMap.begin(); sit != root->stmtMap.end(); ++sit) { StmtInfo * sinfo = sit->second; if (sinfo->file_index != empty_index) { file_ans = sinfo->file_index; base_ans = sinfo->base_index; line_ans = sinfo->line_num; DEBUG_CFG("file: any stmt\n"); goto found_file; } } found_file: // if we can't find a file name, then don't look for a line if (file_ans == empty_index) { DEBUG_CFG("unable to find file, skipping line\n"); line_ans = 0; goto found_line; } // // line num -- the best answer is an exit cond at this level where // the file name matches (with terminal line map). it's ok to have // multiple exit conds, pick the one with the min line number. // for (auto cit = clist.begin(); cit != clist.end(); ++cit) { HeaderInfo * info = &(cit->second); if (info->depth == depth_root && info->base_index == base_ans && info->line_num > 0) { long line = info->line_num; if (line_ans == 0 || line < line_ans) { line_ans = line; } DEBUG_CFG("line: " << line << " (exit cond at loop level) 0x" << hex << cit->first << dec << "\n"); } } // // equally good is an exit cond that is inlined below the current // depth if the file matches the next inline step. // for (auto cit = clist.begin(); cit != clist.end(); ++cit) { HeaderInfo * info = &(cit->second); if (info->depth > depth_root && info->flp_path[depth_root].base_index == base_ans && info->flp_path[depth_root].line_num > 0) { long line = info->flp_path[depth_root].line_num; if (line_ans == 0 || line < line_ans) { line_ans = line; } DEBUG_CFG("line: " << line << " (exit cond at loop +" << (info->depth - depth_root) << ") 0x" << hex << cit->first << dec << "\n"); } } // // never locate the loop at a higher line number than a subloop // for (auto lit = root->loopList.begin(); lit != root->loopList.end(); ++lit) { LoopInfo * linfo = *lit; if (linfo->base_index == base_ans && linfo->line_num > 0) { long line = linfo->line_num; if (line_ans == 0 || line < line_ans) { line_ans = line; } DEBUG_CFG("line: " << line_ans << " (subloop) " << linfo->name << "\n"); } } found_line: DEBUG_CFG("\nheader: l=" << line_ans << " f='" << strTab->index2str(file_ans) << "'\n"); vector <Block *> entryBlocks; loop->getLoopEntries(entryBlocks); VMA entry_vma = VMA_MAX; for (auto bit = entryBlocks.begin(); bit != entryBlocks.end(); ++bit) { entry_vma = std::min(entry_vma, (*bit)->start()); } LoopInfo *info = new LoopInfo(root, path, loopName, entry_vma, file_ans, base_ans, line_ans, entryBlocks.size() > 1); #if DEBUG_CFG_SOURCE cout << "\nreparented inline tree: " << loopName << " '" << func->name() << "'\n\n"; debugInlineTree(root, info, *strTab, 0, false); #endif return info; } //---------------------------------------------------------------------- // Delete the inline sequence 'prefix' from root's tree and reparent // any statements or loops. We expect there to be no statements, // loops or subtrees along the deleted spine, but if there are, move // them to the subtree. // // Returns: the subtree at the end of prefix. // static TreeNode * deleteInlinePrefix(WorkEnv & env, TreeNode * root, Inline::InlineSeqn prefix) { StmtMap stmts; LoopList loops; // walk the prefix and collect any stmts or loops for (auto pit = prefix.begin(); pit != prefix.end(); ++pit) { FLPIndex flp(*(env.strTab), *pit); auto nit = root->nodeMap.find(flp); if (nit != root->nodeMap.end()) { TreeNode * subtree = nit->second; // statements for (auto sit = root->stmtMap.begin(); sit != root->stmtMap.end(); ++sit) { stmts.insert(sit->second); } root->stmtMap.clear(); // loops for (auto lit = root->loopList.begin(); lit != root->loopList.end(); ++lit) { loops.push_back(*lit); } root->loopList.clear(); // subtrees for (auto it = root->nodeMap.begin(); it != root->nodeMap.end(); ++it) { TreeNode * node = it->second; if (node != subtree) { mergeInlineEdge(subtree, it->first, node); } } root->nodeMap.clear(); delete root; root = subtree; } } // reattach the stmts and loops for (auto sit = stmts.begin(); sit != stmts.end(); ++sit) { root->stmtMap.insert(sit->second); } stmts.clear(); for (auto lit = loops.begin(); lit != loops.end(); ++lit) { root->loopList.push_back(*lit); } loops.clear(); return root; } //---------------------------------------------------------------------- // Merge irreducible loops. If L1 is an irreducible loop and L2 is an // irreducible subloop and L1 and L2 have the same file and line // attribution, then it's likely there is really only one loop in the // source code, so merge L2 into L1. // // This only applies to irreducible loops. Natural (reducible) loops // are assumed to be correct. // static void mergeIrredLoops(WorkEnv & env, LoopInfo * L1) { // if L1 is reducible, then do nothing if (L1 == NULL || ! L1->irred) { return; } TreeNode * node1 = L1->node; LoopList & list1 = node1->loopList; // if there are no irreducible subloops, then do nothing bool has_irred = false; for (auto it = list1.begin(); it != list1.end(); ++it) { LoopInfo * L2 = *it; if (L2->irred) { has_irred = true; break; } } if (! has_irred) { return; } DEBUG_CFG("\n"); // iterate through L1's subloops and merge L2 into L1 when they // match. merging requires moving L2's subloops onto L1's list, the // very list we are iterating through. to maintain correctness, put // the loops on a new list and copy them back. vector <LoopInfo *> newList; for (auto it1 = list1.begin(); it1 != list1.end(); ++it1) { LoopInfo * L2 = *it1; TreeNode * node2 = L2->node; LoopList & list2 = node2->loopList; if (L2->irred && L1->base_index == L2->base_index && L1->line_num == L2->line_num) { // merge L2 into L1 and put L2's subloops on the new list DEBUG_CFG("merge: " << L2->name << " into " << L1->name << "\n"); for (auto it2 = list2.begin(); it2 != list2.end(); ++it2) { newList.push_back(*it2); } list2.clear(); mergeInlineTree(node1, node2); delete L2; } else { // do not merge, keep entire L2 intact on new list newList.push_back(L2); } } std::sort(newList.begin(), newList.end(), LoopInfoLessThan); // copy new list back to L1 list1.clear(); for (auto nit = newList.begin(); nit != newList.end(); ++nit) { list1.push_back(*nit); } newList.clear(); #if DEBUG_CFG_SOURCE cout << "\n"; debugInlineTree(node1, L1, *(env.strTab), 0, false); #endif } //---------------------------------------------------------------------- // Compute gaps = the set of intervals in [start, end) that are not // covered in vset. // static void computeGaps(VMAIntervalSet & vset, VMAIntervalSet & gaps, VMA start, VMA end) { gaps.clear(); auto it = vset.begin(); while (start < end) { if (it == vset.end()) { gaps.insert(start, end); break; } else if (it->end() <= start) { // it entirely left of start ++it; } else if (it->beg() <= start) { // it contains start start = it->end(); ++it; } else { // it entirely right of start VMA gap_end = std::min(it->beg(), end); gaps.insert(start, gap_end); start = it->end(); ++it; } } } //**************************************************************************** // Debug functions //**************************************************************************** #if DEBUG_ANY_ON // Debug functions to display the raw input data from ParseAPI for // loops, blocks, stmts, file names, proc names and line numbers. #define INDENT " " // Cleanup and shorten the proc name: demangle plus collapse nested // <...> and (...) to just <> and (). For example: // // std::map<int,long>::myfunc(int) --> std::map<>::myfunc() // // This is only for more compact debug output. Internal decisions are // always made on the full string. // static string debugPrettyName(const string & procnm) { string str = procnm; string ans = ""; size_t str_len = str.size(); size_t pos = 0; while (pos < str_len) { size_t next = str.find_first_of("<(", pos); char open, close; if (next == string::npos) { ans += str.substr(pos); break; } if (str[next] == '<') { open = '<'; close = '>'; } else { open = '('; close = ')'; } ans += str.substr(pos, next - pos) + open + close; int depth = 1; for (pos = next + 1; pos < str_len && depth > 0; pos++) { if (str[pos] == open) { depth++; } else if (str[pos] == close) { depth--; } } } return ans; } //---------------------------------------------------------------------- static void debugElfHeader(ElfFile * elfFile) { size_t len = elfFile->getLength(); cout << "\n============================================================\n" << "Elf File: " << elfFile->getFileName() << "\n" << "length: 0x" << hex << len << dec << " (" << len << ")\n" << "============================================================\n"; } //---------------------------------------------------------------------- static void debugFuncHeader(FileInfo * finfo, ProcInfo * pinfo, long num, long num_funcs, string label) { ParseAPI::Function * func = pinfo->func; Address entry_addr = func->addr(); cout << "\n------------------------------------------------------------\n"; if (label != "") { cout << label << " "; } cout << "func: 0x" << hex << entry_addr << dec << " (" << num << "/" << num_funcs << ")" << " link='" << pinfo->linkName << "'\n" << "parse: '" << func->name() << "'\n" << "file: '" << finfo->fileName << "'\n"; } //---------------------------------------------------------------------- static void debugStmt(VMA vma, int len, string & filenm, SrcFile::ln line, RealPathMgr * realPath) { cout << "stmt: 0x" << hex << vma << dec << " (" << len << ")" << " l=" << line << " f='" << filenm << "'\n"; Inline::InlineSeqn nodeList; Inline::analyzeAddr(nodeList, vma, realPath); // list is outermost to innermost for (auto nit = nodeList.begin(); nit != nodeList.end(); ++nit) { cout << INDENT << "inline: l=" << nit->getLineNum() << " f='" << nit->getFileName() << "' p='" << debugPrettyName(nit->getPrettyName()) << "'\n"; } } //---------------------------------------------------------------------- static string edgeType(int type) { if (type == ParseAPI::CALL) { return "call"; } if (type == ParseAPI::COND_TAKEN) { return "cond-take"; } if (type == ParseAPI::COND_NOT_TAKEN) { return "cond-not"; } if (type == ParseAPI::INDIRECT) { return "indirect"; } if (type == ParseAPI::DIRECT) { return "direct"; } if (type == ParseAPI::FALLTHROUGH) { return "fallthr"; } if (type == ParseAPI::CATCH) { return "catch"; } if (type == ParseAPI::CALL_FT) { return "call-ft"; } if (type == ParseAPI::RET) { return "return"; } return "unknown"; } static void debugEdges(Block * block) { const Block::edgelist & outEdges = block->targets(); vector <Edge *> edgeVec; for (auto eit = outEdges.begin(); eit != outEdges.end(); ++eit) { edgeVec.push_back(*eit); } std::sort(edgeVec.begin(), edgeVec.end(), EdgeLessThan); cout << "out edges:" << hex; for (auto eit = edgeVec.begin(); eit != edgeVec.end(); ++eit) { Edge * edge = *eit; cout << " 0x" << edge->trg()->start() << " (" << edgeType(edge->type()); if (edge->interproc()) { cout << ", interproc"; } cout << ")"; } cout << dec << "\n"; } //---------------------------------------------------------------------- static void debugAddr(GroupInfo * ginfo, VMA vma, RealPathMgr * realPath) { StatementVector svec; string filenm = ""; SrcFile::ln line = 0; getStatement(svec, vma, ginfo->sym_func); if (! svec.empty()) { filenm = svec[0]->getFile(); line = svec[0]->getLine(); realPath->realpath(filenm); } cout << "0x" << hex << vma << dec << " l=" << line << " f='" << filenm << "'\n"; } //---------------------------------------------------------------------- static void debugLoop(GroupInfo * ginfo, ParseAPI::Function * func, Loop * loop, const string & loopName, vector <Edge *> & backEdges, HeaderList & clist, RealPathMgr * realPath) { vector <Block *> entBlocks; int num_ents = loop->getLoopEntries(entBlocks); std::sort(entBlocks.begin(), entBlocks.end(), BlockLessThan); cout << "\nheader info: " << loopName << ((num_ents == 1) ? " (reducible)" : " (irreducible)") << " '" << func->name() << "'\n"; cout << "\nfunc header:\n"; debugAddr(ginfo, func->addr(), realPath); cout << "\nentry blocks:" << hex; for (auto bit = entBlocks.begin(); bit != entBlocks.end(); ++bit) { cout << " 0x" << (*bit)->start(); } cout << "\nback edge sources:"; for (auto eit = backEdges.begin(); eit != backEdges.end(); ++eit) { cout << " 0x" << (*eit)->src()->last(); } cout << "\nback edge targets:"; for (auto eit = backEdges.begin(); eit != backEdges.end(); ++eit) { cout << " 0x" << (*eit)->trg()->start(); } cout << dec; cout << "\n\nexit conditions:\n"; for (auto cit = clist.begin(); cit != clist.end(); ++cit) { VMA vma = cit->first; HeaderInfo * info = &(cit->second); SrcFile::ln line = 0; string filenm = ""; StatementVector svec; getStatement(svec, vma, ginfo->sym_func); if (! svec.empty()) { filenm = svec[0]->getFile(); line = svec[0]->getLine(); realPath->realpath(filenm); } cout << "0x" << hex << vma << dec << " " << (info->is_src ? "src " : "cond") << " excl: " << info->is_excl << " depth: " << info->depth << " l=" << line << " f='" << filenm << "'\n"; } } //---------------------------------------------------------------------- // If LoopInfo is non-null, then treat 'node' as a detached loop and // prepend the FLP seqn from 'info' above the tree. Else, 'node' is // the tree. // static void debugInlineTree(TreeNode * node, LoopInfo * info, HPC::StringTable & strTab, int depth, bool expand_loops) { // treat node as a detached loop with FLP seqn above it. if (info != NULL) { depth = 0; for (auto pit = info->path.begin(); pit != info->path.end(); ++pit) { for (int i = 1; i <= depth; i++) { cout << INDENT; } FLPIndex flp = *pit; cout << "inline: l=" << flp.line_num << " f='" << strTab.index2str(flp.file_index) << "' p='" << debugPrettyName(strTab.index2str(flp.pretty_index)) << "'\n"; depth++; } for (int i = 1; i <= depth; i++) { cout << INDENT; } cout << "loop: " << info->name << (info->irred ? " (irred)" : "") << " l=" << info->line_num << " f='" << strTab.index2str(info->file_index) << "'\n"; depth++; } // print the terminal statements for (auto sit = node->stmtMap.begin(); sit != node->stmtMap.end(); ++sit) { StmtInfo *sinfo = sit->second; for (int i = 1; i <= depth; i++) { cout << INDENT; } cout << "stmt: 0x" << hex << sinfo->vma << dec << " (" << sinfo->len << (sinfo->is_call ? "/c" : "") << ")" << " l=" << sinfo->line_num << " f='" << strTab.index2str(sinfo->file_index) << "'\n"; } // recur on the subtrees for (auto nit = node->nodeMap.begin(); nit != node->nodeMap.end(); ++nit) { FLPIndex flp = nit->first; for (int i = 1; i <= depth; i++) { cout << INDENT; } cout << "inline: l=" << flp.line_num << " f='" << strTab.index2str(flp.file_index) << "' p='" << debugPrettyName(strTab.index2str(flp.pretty_index)) << "'\n"; debugInlineTree(nit->second, NULL, strTab, depth + 1, expand_loops); } // recur on the loops for (auto lit = node->loopList.begin(); lit != node->loopList.end(); ++lit) { LoopInfo *info = *lit; for (int i = 1; i <= depth; i++) { cout << INDENT; } cout << "loop: " << info->name << (info->irred ? " (irred)" : "") << " l=" << info->line_num << " f='" << strTab.index2str(info->file_index) << "'\n"; if (expand_loops) { debugInlineTree(info->node, NULL, strTab, depth + 1, expand_loops); } } } #endif // DEBUG_CFG_SOURCE } // namespace Struct } // namespace BAnal
#pragma once #include <time.h> #include "exemodel/timespec.hpp" namespace exemodel { timespec_t get_clk_res(int clk_id); timespec_t get_clk_time(int clk_id); void set_clk_time(int clk_id, const timespec_t & tp); template<int clk_id> class clk_info { public: static timespec_t get_res() { return get_clk_res(clk_id); } static timespec_t get_time() { return get_clk_time(clk_id); } static void set_time(const timespec_t & tp) { set_clk_time(clk_id, tp); } }; typedef clk_info<CLOCK_REALTIME> rt_clk_info; typedef clk_info<CLOCK_MONOTONIC> mono_clk_info; }
#define PROBLEM "https://judge.yosupo.jp/problem/subset_convolution" #include "../../src/math/subset_convolution.hpp" #include "../../src/math/modint.hpp" #include "../../src/misc/fastio/printer.hpp" #include "../../src/misc/fastio/scanner.hpp" int main() { using mint = modint_998244353; const auto N = in.val<int>(); const auto as = in.vec<mint>(1 << N); const auto bs = in.vec<mint>(1 << N); const auto cs = subsetConvolute(as, bs); Vec<int> ans(cs.size()); for (int i : rep(1 << N)) { ans[i] = cs[i].val(); } out.ln(ans); return 0; }
#ifndef ENTT_ENTITY_FWD_HPP #define ENTT_ENTITY_FWD_HPP #include "../core/fwd.hpp" namespace entt { /*! @class basic_registry */ template <typename> class basic_registry; /*! @class basic_view */ template<typename...> class basic_view; /*! @class basic_runtime_view */ template<typename> class basic_runtime_view; /*! @class basic_group */ template<typename...> class basic_group; /*! @class basic_observer */ template<typename> class basic_observer; /*! @struct basic_actor */ template <typename> struct basic_actor; /*! @class basic_snapshot */ template<typename> class basic_snapshot; /*! @class basic_snapshot_loader */ template<typename> class basic_snapshot_loader; /*! @class basic_continuous_loader */ template<typename> class basic_continuous_loader; /*! @enum entity */ enum class entity: id_type; /*! @brief Alias declaration for the most common use case. */ using registry = basic_registry<entity>; /*! @brief Alias declaration for the most common use case. */ using observer = basic_observer<entity>; /*! @brief Alias declaration for the most common use case. */ using actor [[deprecated("Consider using the handle class instead")]] = basic_actor<entity>; /*! @brief Alias declaration for the most common use case. */ using snapshot = basic_snapshot<entity>; /*! @brief Alias declaration for the most common use case. */ using snapshot_loader = basic_snapshot_loader<entity>; /*! @brief Alias declaration for the most common use case. */ using continuous_loader = basic_continuous_loader<entity>; /** * @brief Alias declaration for the most common use case. * @tparam Types Types of components iterated by the view. */ template<typename... Types> using view = basic_view<entity, Types...>; /*! @brief Alias declaration for the most common use case. */ using runtime_view = basic_runtime_view<entity>; /** * @brief Alias declaration for the most common use case. * @tparam Types Types of components iterated by the group. */ template<typename... Types> using group = basic_group<entity, Types...>; } #endif
/** * @file exces/func_adaptors/cp.hpp * @brief Adaptors for various functors making them usable with for_each * * Copyright 2012-2014 Matus Chochlik. 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 EXCES_FUNC_ADAPTORS_CP_1404292124_HPP #define EXCES_FUNC_ADAPTORS_CP_1404292124_HPP #include <exces/detail/func_adaptors.hpp> #include <functional> namespace exces { // Pointers-to-components ... /// Adapts a functor accepting a pack of Component pointers for use with for_each /** This adaptor adapts a functor, that accepts one or several pointers to * various Components so that it can be used with the for_each member function * of manager, collection or classification. * * @ingroup func_adaptors * * @see adapt_func_cp */ template <typename Functor, typename ... Components> struct func_adaptor_cp : aux_::auto_update_func_adaptor<Components...> { Functor _functor; /// Adapts the specified functor func_adaptor_cp(const Functor& functor) : _functor(functor) { } template <typename Group, typename Component> Component* _get_ptr( manager<Group>& m, typename manager<Group>::entity_key k ) const { Component* ptr = nullptr; if(m.template has<Component>(k)) { ptr = &m.template raw_access<Component>(k); } return ptr; } /// The function call operator /** If the entity managed by manager @p m, referenced by key @p k * has some of the specified Components, the adapted functor is called * by using manager::raw_access to get the references to the component * instances. If the entity has the i-th component then the address * of the component instance is passed to the functor, if the entity * doesn't have the i-th component then a null pointer is passed. */ template <typename Group> bool operator()( const iter_info&, manager<Group>& m, typename manager<Group>::entity_key k ) { if(m.template has_some<Components...>(k)) { auto up_op = this->begin_update(m, k); bool cont = _functor( _get_ptr<Group, Components>(m, k)... ); this->finish_update(m, k, up_op); if(!cont) return false; } return true; } }; /// Constructs a new instance of func_adaptor_cp /** * @ingroup func_adaptors */ template <typename ... Components, typename Functor> inline func_adaptor_cp<Functor, Components...> adapt_func_cp(const Functor& functor) { return func_adaptor_cp<Functor, Components...>(functor); } /// Constructs a new instance of func_adaptor_cp adapting a std::function /** * @ingroup func_adaptors */ template <typename ... Components> inline func_adaptor_cp<std::function<bool(Components*...)>, Components...> adapt_func(const std::function<bool(Components*...)>& functor) { return adapt_func_cp<Components...>(functor); } } // namespace exces #endif //include guard
// 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. #ifndef __MASTER_METRICS_HPP__ #define __MASTER_METRICS_HPP__ #include <string> #include <vector> #include <process/metrics/counter.hpp> #include <process/metrics/gauge.hpp> #include <process/metrics/metrics.hpp> #include <stout/hashmap.hpp> #include "mesos/mesos.hpp" #include "mesos/type_utils.hpp" namespace mesos { namespace internal { namespace master { class Master; struct Metrics { explicit Metrics(const Master& master); ~Metrics(); process::metrics::Gauge uptime_secs; process::metrics::Gauge elected; process::metrics::Gauge slaves_connected; process::metrics::Gauge slaves_disconnected; process::metrics::Gauge slaves_active; process::metrics::Gauge slaves_inactive; process::metrics::Gauge slaves_unreachable; process::metrics::Gauge frameworks_connected; process::metrics::Gauge frameworks_disconnected; process::metrics::Gauge frameworks_active; process::metrics::Gauge frameworks_inactive; process::metrics::Gauge outstanding_offers; // Task state metrics. process::metrics::Gauge tasks_staging; process::metrics::Gauge tasks_starting; process::metrics::Gauge tasks_running; process::metrics::Gauge tasks_unreachable; process::metrics::Gauge tasks_killing; process::metrics::Counter tasks_finished; process::metrics::Counter tasks_failed; process::metrics::Counter tasks_killed; process::metrics::Counter tasks_lost; process::metrics::Counter tasks_error; process::metrics::Counter tasks_dropped; process::metrics::Counter tasks_gone; process::metrics::Counter tasks_gone_by_operator; typedef hashmap<TaskStatus::Reason, process::metrics::Counter> Reasons; typedef hashmap<TaskStatus::Source, Reasons> SourcesReasons; // NOTE: We only track metrics sources and reasons for terminal states. hashmap<TaskState, SourcesReasons> tasks_states; // Message counters. process::metrics::Counter dropped_messages; // Metrics specific to frameworks of a common principal. // These metrics have names prefixed by "frameworks/<principal>/". struct Frameworks { // Counters for messages from all frameworks of this principal. // Note: We only count messages from active scheduler // *instances* while they are *registered*. i.e., messages // prior to the completion of (re)registration // (AuthenticateMessage and (Re)RegisterFrameworkMessage) and // messages from an inactive scheduler instance (after the // framework has failed over) are not counted. // Framework messages received (before processing). process::metrics::Counter messages_received; // Framework messages processed. // NOTE: This doesn't include dropped messages. Processing of // a message may be throttled by a RateLimiter if one is // configured for this principal. Also due to Master's // asynchronous nature, this doesn't necessarily mean the work // requested by this message has finished. process::metrics::Counter messages_processed; explicit Frameworks(const std::string& principal) : messages_received("frameworks/" + principal + "/messages_received"), messages_processed("frameworks/" + principal + "/messages_processed") { process::metrics::add(messages_received); process::metrics::add(messages_processed); } ~Frameworks() { process::metrics::remove(messages_received); process::metrics::remove(messages_processed); } }; // Per-framework-principal metrics keyed by the framework // principal. hashmap<std::string, process::Owned<Frameworks>> frameworks; // Messages from schedulers. process::metrics::Counter messages_register_framework; process::metrics::Counter messages_reregister_framework; process::metrics::Counter messages_unregister_framework; process::metrics::Counter messages_deactivate_framework; process::metrics::Counter messages_kill_task; process::metrics::Counter messages_status_update_acknowledgement; process::metrics::Counter messages_resource_request; process::metrics::Counter messages_launch_tasks; process::metrics::Counter messages_decline_offers; process::metrics::Counter messages_revive_offers; process::metrics::Counter messages_suppress_offers; process::metrics::Counter messages_reconcile_tasks; process::metrics::Counter messages_framework_to_executor; // Messages from executors. process::metrics::Counter messages_executor_to_framework; // Messages from slaves. process::metrics::Counter messages_register_slave; process::metrics::Counter messages_reregister_slave; process::metrics::Counter messages_unregister_slave; process::metrics::Counter messages_status_update; process::metrics::Counter messages_exited_executor; process::metrics::Counter messages_update_slave; // Messages from both schedulers and slaves. process::metrics::Counter messages_authenticate; process::metrics::Counter valid_framework_to_executor_messages; process::metrics::Counter invalid_framework_to_executor_messages; process::metrics::Counter valid_executor_to_framework_messages; process::metrics::Counter invalid_executor_to_framework_messages; process::metrics::Counter valid_status_updates; process::metrics::Counter invalid_status_updates; process::metrics::Counter valid_status_update_acknowledgements; process::metrics::Counter invalid_status_update_acknowledgements; // Recovery counters. process::metrics::Counter recovery_slave_removals; // Process metrics. process::metrics::Gauge event_queue_messages; process::metrics::Gauge event_queue_dispatches; process::metrics::Gauge event_queue_http_requests; // Successful registry operations. process::metrics::Counter slave_registrations; process::metrics::Counter slave_reregistrations; process::metrics::Counter slave_removals; process::metrics::Counter slave_removals_reason_unhealthy; process::metrics::Counter slave_removals_reason_unregistered; process::metrics::Counter slave_removals_reason_registered; // Slave observer metrics. // // TODO(neilc): The `slave_shutdowns_xxx` metrics are deprecated and // will always be zero. Remove in Mesos 2.0. process::metrics::Counter slave_shutdowns_scheduled; process::metrics::Counter slave_shutdowns_completed; process::metrics::Counter slave_shutdowns_canceled; process::metrics::Counter slave_unreachable_scheduled; process::metrics::Counter slave_unreachable_completed; process::metrics::Counter slave_unreachable_canceled; // Non-revocable resources. std::vector<process::metrics::Gauge> resources_total; std::vector<process::metrics::Gauge> resources_used; std::vector<process::metrics::Gauge> resources_percent; // Revocable resources. std::vector<process::metrics::Gauge> resources_revocable_total; std::vector<process::metrics::Gauge> resources_revocable_used; std::vector<process::metrics::Gauge> resources_revocable_percent; void incrementTasksStates( const TaskState& state, const TaskStatus::Source& source, const TaskStatus::Reason& reason); }; } // namespace master { } // namespace internal { } // namespace mesos { #endif // __MASTER_METRICS_HPP__
#include "mex.h" #include "GLTree.cpp" /* the gateway function */ //la chiamata deve essere DeleteGLtree(Tree) void mexFunction( int nlhs,const mxArray *plhs[], int nrhs, const mxArray *prhs[1]) { //dichiarazione variabili GLTREE* Tree; double *ptrtree; if(nrhs!=1){ mexErrMsgTxt("Only one input supported.");} ptrtree = mxGetPr(prhs[0]);//puntatore all'albero precedentemente fornito Tree=(GLTREE*)((long)(ptrtree[0]));//ritrasformo il puntatore passato if(Tree==NULL) { mexErrMsgTxt("Invalid tree pointer"); } //chiamo il distruttore delete Tree; // Tree.~GLTREE(); //trying to remake it a tree pointer // verifico se la conversione riporta al puntatore originario //ptr=(GLTREE*)(long(ptrtree[0])); // mexPrintf("puntatore= %4.4x\n",ptr); }
/* * Copyright (C) 2015 - 2017 Intel Corporation. * 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(s), * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice(s), * 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 HOLDER(S) ``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(S) 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 <stdio.h> #include <assert.h> #include <iostream> #include <vector> #include "Configuration.hpp" #include "AllocatorFactory.hpp" #include "TaskFactory.hpp" #include "Task.hpp" #include "ConsoleLog.hpp" #include "Stats.hpp" #include "Thread.hpp" #include "Tests.hpp" #include "CommandLine.hpp" #include "FunctionCallsPerformanceTask.h" #include "StressIncreaseToMax.h" /* Command line description. Syntax: key=value Options: - 'test' - specify the test case. This option can be used with the following values: 'calls', 'all' or 'self', where: 'calls' - function calls performance test, 'all' - execute both above ('footprint' and 'calls') tests, 'self' - execute self tests 's1' - stress tests (perform allocations until the maximum amount of allocated memory has been reached, than frees allocated memory. If the time interval has not been exceed, than repeat the test), - 'operations' - the number of memory operations per thread - 'size_from' - lower bound for the random sizes of allocation - 'size_to' - upper bound for the random sizes of allocation - 'seed' - random seed - 'threads_num' - the number of threads per test case - 'time' - minimum execution time interval - 'kind' - the kind to test - 'csv_log' - if 'true' then log to csv file memory operations and statistics - 'call' specify the allocation function call. This option can be used with the following values: 'malloc' (default), 'calloc', 'realloc', - 'requested_memory_limit' test stops when the requested memory limit has been reached * - maximum of available memory in OS, or maximum memory based 'operations' parameter Example: 1. Performance test: ./perf_tool test=all operations=1000 size_from=32 size_to=20480 seed=11 threads_num=200 2. Stress test ./perf_tool test=s1 time=120 kind=MEMKIND_HBW size_from=1048576 csv_log=true requested_memory_limit=1048576 */ int main(int argc, char* argv[]) { unsigned mem_operations_num = 1000; size_t size_from = 32, size_to = 2048*1024; unsigned seed = 11; //should be at least one size_t threads_number = 10; CommandLine cmd_line(argc, argv); if((argc >= 1) && cmd_line.is_option_set("test", "self")) { execute_self_tests(); getchar(); } cmd_line.parse_with_strtol("operations", mem_operations_num); cmd_line.parse_with_strtol("size_from", size_from); cmd_line.parse_with_strtol("size_to", size_to); cmd_line.parse_with_strtol("seed", seed); cmd_line.parse_with_strtol("threads_num", threads_number); bool is_csv_log_enabled = cmd_line.is_option_set("csv_log", "true"); //Heap Manager initialization std::vector<AllocatorFactory::initialization_stat> stats = AllocatorFactory().initialization_test(); if(!cmd_line.is_option_set("print_init_stats", "false")) { printf("\nInitialization overhead:\n"); for (int i=0; i<stats.size(); i++) { AllocatorFactory::initialization_stat stat = stats[i]; printf("%32s : time=%7.7f.s, ref_delta_time=%15f, node0=%10fMB, node1=%7.7fMB\n", AllocatorTypes::allocator_name(stat.allocator_type).c_str(), stat.total_time, stat.ref_delta_time, stat.memory_overhead[0], stat.memory_overhead[1]); } } //Stress test by repeatedly increasing memory (to maximum), until given time interval has been exceed. if(cmd_line.is_option_set("test", "s1")) { printf("Stress test (StressIncreaseToMax) start. \n"); if(!cmd_line.is_option_present("operations")) mem_operations_num = 1000000; unsigned time = 120; //Default time interval. cmd_line.parse_with_strtol("time", time); size_t requested_memory_limit = 1024*1024; cmd_line.parse_with_strtol("requested_memory_limit", requested_memory_limit); unsigned allocator = AllocatorTypes::MEMKIND_HBW; if(cmd_line.is_option_present("kind")) { //Enable memkind allocator and specify kind. allocator = AllocatorTypes::allocator_type(cmd_line.get_option_value("kind")); } TypesConf allocator_types; allocator_types.enable_type(allocator); TypesConf enable_func_calls; enable_func_calls.enable_type(FunctionCalls::MALLOC); TaskConf task_conf = { mem_operations_num, { mem_operations_num, size_from, //No random sizes. size_from }, enable_func_calls, allocator_types, 11, is_csv_log_enabled, }; StressIncreaseToMax::execute_test_iterations(task_conf, time, requested_memory_limit); return 0; } printf("\nTest configuration: \n"); printf("\t memory operations per thread = %u \n", mem_operations_num); printf("\t seed = %d\n", seed); printf("\t number of threads = %zu\n", threads_number); printf("\t size from-to = %zu-%zu\n\n", size_from, size_to); assert(size_from <= size_to); TypesConf func_calls; func_calls.enable_type(FunctionCalls::FREE); if(cmd_line.is_option_present("call")) { //Enable heap manager function call. func_calls.enable_type(FunctionCalls::function_type(cmd_line.get_option_value("call"))); } else { func_calls.enable_type(FunctionCalls::MALLOC); } TypesConf allocator_types; if(cmd_line.is_option_present("allocator")) { allocator_types.enable_type(AllocatorTypes::allocator_type(cmd_line.get_option_value("allocator"))); } else { for(unsigned i=0; i<=AllocatorTypes::MEMKIND_HBW_PREFERRED; i++) { allocator_types.enable_type(i); } } TaskConf conf = { mem_operations_num, //number memory operations { mem_operations_num, //number of memory operations size_from, //min. size of single allocation size_to //max. size of single allocatioion }, func_calls, //enable function calls allocator_types, //enable allocators seed, //random seed is_csv_log_enabled, }; //Function calls test if(cmd_line.is_option_set("test", "calls") || cmd_line.is_option_set("test", "all")) { TaskFactory task_factory; std::vector<Thread*> threads; std::vector<Task*> tasks; for (int i=0; i<threads_number; i++) { FunctionCallsPerformanceTask* task = static_cast<FunctionCallsPerformanceTask*>( task_factory.create(conf) ); tasks.push_back(task); threads.push_back(new Thread(task)); conf.seed += 1; } ThreadsManager threads_manager(threads); threads_manager.start(); threads_manager.barrier(); TimeStats stats; for (int i=0; i<tasks.size(); i++) { stats += tasks[i]->get_results(); } ConsoleLog::print_table(stats); ConsoleLog::print_requested_memory(stats, "func. calls test"); threads_manager.release(); } return 0; }
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The Christian Team developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "addresstablemodel.h" #include "askpassphrasedialog.h" #include "bitcoinunits.h" #include "clientmodel.h" #include "coincontroldialog.h" #include "guiutil.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "walletmodel.h" #include "base58.h" #include "coincontrol.h" #include "ui_interface.h" #include "utilmoneystr.h" #include "wallet.h" #include <QMessageBox> #include <QScrollBar> #include <QSettings> #include <QTextDocument> SendCoinsDialog::SendCoinsDialog(QWidget* parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), clientModel(0), model(0), fNewRecipientAllowed(true), fFeeMinimized(true) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif GUIUtil::setupAddressWidget(ui->lineEditCoinControlChange, this); addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString&)), this, SLOT(coinControlChangeEdited(const QString&))); // UTXO Splitter connect(ui->splitBlockCheckBox, SIGNAL(stateChanged(int)), this, SLOT(splitBlockChecked(int))); connect(ui->splitBlockLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(splitBlockLineEditChanged(const QString&))); // cteam specific QSettings settings; if (!settings.contains("bUseObfuScation")) settings.setValue("bUseObfuScation", false); if (!settings.contains("bUseSwiftTX")) settings.setValue("bUseSwiftTX", false); bool useObfuScation = settings.value("bUseObfuScation").toBool(); bool useSwiftTX = settings.value("bUseSwiftTX").toBool(); if (fLiteMode) { ui->checkUseObfuscation->setChecked(false); ui->checkUseObfuscation->setVisible(false); ui->checkSwiftTX->setVisible(false); CoinControlDialog::coinControl->useObfuScation = false; CoinControlDialog::coinControl->useSwiftTX = false; } else { ui->checkUseObfuscation->setChecked(useObfuScation); ui->checkSwiftTX->setChecked(useSwiftTX); CoinControlDialog::coinControl->useObfuScation = useObfuScation; CoinControlDialog::coinControl->useSwiftTX = useSwiftTX; } connect(ui->checkUseObfuscation, SIGNAL(stateChanged(int)), this, SLOT(updateDisplayUnit())); connect(ui->checkSwiftTX, SIGNAL(stateChanged(int)), this, SLOT(updateSwiftTX())); // Coin Control: clipboard actions QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction* clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction* clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction* clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction* clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction* clipboardLowOutputAction = new QAction(tr("Copy dust"), this); QAction* clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); // init transaction fee section if (!settings.contains("fFeeSectionMinimized")) settings.setValue("fFeeSectionMinimized", true); if (!settings.contains("nFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nFeeRadio", 1); // custom if (!settings.contains("nFeeRadio")) settings.setValue("nFeeRadio", 0); // recommended if (!settings.contains("nCustomFeeRadio") && settings.contains("nTransactionFee") && settings.value("nTransactionFee").toLongLong() > 0) // compatibility settings.setValue("nCustomFeeRadio", 1); // total at least if (!settings.contains("nCustomFeeRadio")) settings.setValue("nCustomFeeRadio", 0); // per kilobyte if (!settings.contains("nSmartFeeSliderPosition")) settings.setValue("nSmartFeeSliderPosition", 0); if (!settings.contains("nTransactionFee")) settings.setValue("nTransactionFee", (qint64)DEFAULT_TRANSACTION_FEE); if (!settings.contains("fPayOnlyMinFee")) settings.setValue("fPayOnlyMinFee", false); if (!settings.contains("fSendFreeTransactions")) settings.setValue("fSendFreeTransactions", false); ui->groupFee->setId(ui->radioSmartFee, 0); ui->groupFee->setId(ui->radioCustomFee, 1); ui->groupFee->button((int)std::max(0, std::min(1, settings.value("nFeeRadio").toInt())))->setChecked(true); ui->groupCustomFee->setId(ui->radioCustomPerKilobyte, 0); ui->groupCustomFee->setId(ui->radioCustomAtLeast, 1); ui->groupCustomFee->button((int)std::max(0, std::min(1, settings.value("nCustomFeeRadio").toInt())))->setChecked(true); ui->sliderSmartFee->setValue(settings.value("nSmartFeeSliderPosition").toInt()); ui->customFee->setValue(settings.value("nTransactionFee").toLongLong()); ui->checkBoxMinimumFee->setChecked(settings.value("fPayOnlyMinFee").toBool()); ui->checkBoxFreeTx->setChecked(settings.value("fSendFreeTransactions").toBool()); minimizeFeeSection(settings.value("fFeeSectionMinimized").toBool()); } void SendCoinsDialog::setClientModel(ClientModel* clientModel) { this->clientModel = clientModel; if (clientModel) { connect(clientModel, SIGNAL(numBlocksChanged(int)), this, SLOT(updateSmartFeeLabel())); } } void SendCoinsDialog::setModel(WalletModel* model) { this->model = model; if (model && model->getOptionsModel()) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { entry->setModel(model); } } setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); connect(model, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this, SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); updateDisplayUnit(); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); // fee section connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateSmartFeeLabel())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->sliderSmartFee, SIGNAL(valueChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateFeeSectionControls())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->groupCustomFee, SIGNAL(buttonClicked(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(updateGlobalFeeVariables())); connect(ui->customFee, SIGNAL(valueChanged()), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(setMinimumFee())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateFeeSectionControls())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxMinimumFee, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(updateGlobalFeeVariables())); connect(ui->checkBoxFreeTx, SIGNAL(stateChanged(int)), this, SLOT(coinControlUpdateLabels())); ui->customFee->setSingleStep(CWallet::minTxFee.GetFeePerK()); updateFeeSectionControls(); updateMinFeeLabel(); updateSmartFeeLabel(); updateGlobalFeeVariables(); } } SendCoinsDialog::~SendCoinsDialog() { QSettings settings; settings.setValue("fFeeSectionMinimized", fFeeMinimized); settings.setValue("nFeeRadio", ui->groupFee->checkedId()); settings.setValue("nCustomFeeRadio", ui->groupCustomFee->checkedId()); settings.setValue("nSmartFeeSliderPosition", ui->sliderSmartFee->value()); settings.setValue("nTransactionFee", (qint64)ui->customFee->value()); settings.setValue("fPayOnlyMinFee", ui->checkBoxMinimumFee->isChecked()); settings.setValue("fSendFreeTransactions", ui->checkBoxFreeTx->isChecked()); delete ui; } void SendCoinsDialog::on_sendButton_clicked() { if (!model || !model->getOptionsModel()) return; QList<SendCoinsRecipient> recipients; bool valid = true; for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); //UTXO splitter - address should be our own CBitcoinAddress address = entry->getValue().address.toStdString(); if (!model->isMine(address) && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work when sending to outside addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (entry) { if (entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if (!valid || recipients.isEmpty()) { return; } //set split block in model CoinControlDialog::coinControl->fSplitBlock = ui->splitBlockCheckBox->checkState() == Qt::Checked; if (ui->entries->count() > 1 && ui->splitBlockCheckBox->checkState() == Qt::Checked) { CoinControlDialog::coinControl->fSplitBlock = false; ui->splitBlockCheckBox->setCheckState(Qt::Unchecked); QMessageBox::warning(this, tr("Send Coins"), tr("The split block tool does not work with multiple addresses. Try again."), QMessageBox::Ok, QMessageBox::Ok); return; } if (CoinControlDialog::coinControl->fSplitBlock) CoinControlDialog::coinControl->nSplitBlock = int(ui->splitBlockLineEdit->text().toInt()); QString strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>"; QString strFee = ""; recipients[0].inputType = ONLY_DENOMINATED; if (ui->checkUseObfuscation->isChecked()) { recipients[0].inputType = ONLY_DENOMINATED; strFunds = tr("using") + " <b>" + tr("anonymous funds") + "</b>"; QString strNearestAmount( BitcoinUnits::formatWithUnit( model->getOptionsModel()->getDisplayUnit(), 0.1 * COIN)); strFee = QString(tr( "(obfuscation requires this amount to be rounded up to the nearest %1).") .arg(strNearestAmount)); } else { recipients[0].inputType = ALL_COINS; strFunds = tr("using") + " <b>" + tr("any available funds (not recommended)") + "</b>"; } if (ui->checkSwiftTX->isChecked()) { recipients[0].useSwiftTX = true; strFunds += " "; strFunds += tr("and SwiftTX"); } else { recipients[0].useSwiftTX = false; } // Format confirmation message QStringList formatted; foreach (const SendCoinsRecipient& rcp, recipients) { // generate bold amount string QString amount = "<b>" + BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), rcp.amount); amount.append("</b> ").append(strFunds); // generate monospace address string QString address = "<span style='font-family: monospace;'>" + rcp.address; address.append("</span>"); QString recipientElement; if (!rcp.paymentRequest.IsInitialized()) // normal payment { if (rcp.label.length() > 0) // label with address { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.label)); recipientElement.append(QString(" (%1)").arg(address)); } else // just address { recipientElement = tr("%1 to %2").arg(amount, address); } } else if (!rcp.authenticatedMerchant.isEmpty()) // secure payment request { recipientElement = tr("%1 to %2").arg(amount, GUIUtil::HtmlEscape(rcp.authenticatedMerchant)); } else // insecure payment request { recipientElement = tr("%1 to %2").arg(amount, address); } if (fSplitBlock) { recipientElement.append(tr(" split into %1 outputs using the UTXO splitter.").arg(CoinControlDialog::coinControl->nSplitBlock)); } formatted.append(recipientElement); } fNewRecipientAllowed = false; // request unlock only if was locked or unlocked for mixing: // this way we let users unlock by walletpassphrase or by menu // and make many transactions while unlocking through this dialog // will call relock WalletModel::EncryptionStatus encStatus = model->getEncryptionStatus(); if (encStatus == model->Locked || encStatus == model->UnlockedForAnonymizationOnly) { WalletModel::UnlockContext ctx(model->requestUnlock(true)); if (!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } send(recipients, strFee, formatted); return; } // already unlocked or not encrypted at all send(recipients, strFee, formatted); } void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients, QString strFee, QStringList formatted) { // prepare transaction for getting txFee earlier WalletModelTransaction currentTransaction(recipients); WalletModel::SendCoinsReturn prepareStatus; if (model->getOptionsModel()->getCoinControlFeatures()) // coin control enabled prepareStatus = model->prepareTransaction(currentTransaction, CoinControlDialog::coinControl); else prepareStatus = model->prepareTransaction(currentTransaction); // process prepareStatus and on error generate message shown to user processSendCoinsReturn(prepareStatus, BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), currentTransaction.getTransactionFee()), true); if (prepareStatus.status != WalletModel::OK) { fNewRecipientAllowed = true; return; } CAmount txFee = currentTransaction.getTransactionFee(); QString questionString = tr("Are you sure you want to send?"); questionString.append("<br /><br />%1"); if (txFee > 0) { // append fee string if a fee is required questionString.append("<hr /><span style='color:#aa0000;'>"); questionString.append(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), txFee)); questionString.append("</span> "); questionString.append(tr("are added as transaction fee")); questionString.append(" "); questionString.append(strFee); // append transaction size questionString.append(" (" + QString::number((double)currentTransaction.getTransactionSize() / 1000) + " kB)"); } // add total amount in all subdivision units questionString.append("<hr />"); CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee; QStringList alternativeUnits; foreach (BitcoinUnits::Unit u, BitcoinUnits::availableUnits()) { if (u != model->getOptionsModel()->getDisplayUnit()) alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount)); } // Show total amount + all alternative units questionString.append(tr("Total Amount = <b>%1</b><br />= %2") .arg(BitcoinUnits::formatHtmlWithUnit(model->getOptionsModel()->getDisplayUnit(), totalAmount)) .arg(alternativeUnits.join("<br />= "))); // Limit number of displayed entries int messageEntries = formatted.size(); int displayedEntries = 0; for (int i = 0; i < formatted.size(); i++) { if (i >= MAX_SEND_POPUP_ENTRIES) { formatted.removeLast(); i--; } else { displayedEntries = i + 1; } } questionString.append("<hr />"); questionString.append(tr("<b>(%1 of %2 entries displayed)</b>").arg(displayedEntries).arg(messageEntries)); // Display message box QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), questionString.arg(formatted.join("<br />")), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if (retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } // now send the prepared transaction WalletModel::SendCoinsReturn sendStatus = model->sendCoins(currentTransaction); // process sendStatus and on error generate message shown to user processSendCoinsReturn(sendStatus); if (sendStatus.status == WalletModel::OK) { accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while (ui->entries->count()) { ui->entries->takeAt(0)->widget()->deleteLater(); } addEntry(); updateTabsAndLabels(); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry* SendCoinsDialog::addEntry() { SendCoinsEntry* entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateTabsAndLabels(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); qApp->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if (bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateTabsAndLabels() { setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { entry->hide(); // If the last entry is about to be removed add an empty one if (ui->entries->count() == 1) addEntry(); entry->deleteLater(); updateTabsAndLabels(); } QWidget* SendCoinsDialog::setupTabChain(QWidget* prev) { for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->sendButton); QWidget::setTabOrder(ui->sendButton, ui->clearButton); QWidget::setTabOrder(ui->clearButton, ui->addButton); return ui->addButton; } void SendCoinsDialog::setAddress(const QString& address) { SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setAddress(address); } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient& rv) { if (!fNewRecipientAllowed) return; SendCoinsEntry* entry = 0; // Replace the first entry if it is still unused if (ui->entries->count() == 1) { SendCoinsEntry* first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if (first->isClear()) { entry = first; } } if (!entry) { entry = addEntry(); } entry->setValue(rv); updateTabsAndLabels(); } bool SendCoinsDialog::handlePaymentRequest(const SendCoinsRecipient& rv) { // Just paste the entry, all pre-checks // are done in paymentserver.cpp. pasteEntry(rv); return true; } void SendCoinsDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance, const CAmount& watchBalance, const CAmount& watchUnconfirmedBalance, const CAmount& watchImmatureBalance) { Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); Q_UNUSED(anonymizedBalance); Q_UNUSED(watchBalance); Q_UNUSED(watchUnconfirmedBalance); Q_UNUSED(watchImmatureBalance); if (model && model->getOptionsModel()) { uint64_t bal = 0; QSettings settings; settings.setValue("bUseObfuScation", ui->checkUseObfuscation->isChecked()); if (ui->checkUseObfuscation->isChecked()) { bal = anonymizedBalance; } else { bal = balance; } ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), bal)); } } void SendCoinsDialog::updateDisplayUnit() { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance(), model->getWatchBalance(), model->getWatchUnconfirmedBalance(), model->getWatchImmatureBalance()); CoinControlDialog::coinControl->useObfuScation = ui->checkUseObfuscation->isChecked(); coinControlUpdateLabels(); ui->customFee->setDisplayUnit(model->getOptionsModel()->getDisplayUnit()); updateMinFeeLabel(); updateSmartFeeLabel(); } void SendCoinsDialog::updateSwiftTX() { QSettings settings; settings.setValue("bUseSwiftTX", ui->checkSwiftTX->isChecked()); CoinControlDialog::coinControl->useSwiftTX = ui->checkSwiftTX->isChecked(); coinControlUpdateLabels(); } void SendCoinsDialog::processSendCoinsReturn(const WalletModel::SendCoinsReturn& sendCoinsReturn, const QString& msgArg, bool fPrepare) { bool fAskForUnlock = false; QPair<QString, CClientUIInterface::MessageBoxFlags> msgParams; // Default to a warning message, override if error message is needed msgParams.second = CClientUIInterface::MSG_WARNING; // This comment is specific to SendCoinsDialog usage of WalletModel::SendCoinsReturn. // WalletModel::TransactionCommitFailed is used only in WalletModel::sendCoins() // all others are used only in WalletModel::prepareTransaction() switch (sendCoinsReturn.status) { case WalletModel::InvalidAddress: msgParams.first = tr("The recipient address is not valid, please recheck."); break; case WalletModel::InvalidAmount: msgParams.first = tr("The amount to pay must be larger than 0."); break; case WalletModel::AmountExceedsBalance: msgParams.first = tr("The amount exceeds your balance."); break; case WalletModel::AmountWithFeeExceedsBalance: msgParams.first = tr("The total exceeds your balance when the %1 transaction fee is included.").arg(msgArg); break; case WalletModel::DuplicateAddress: msgParams.first = tr("Duplicate address found, can only send to each address once per send operation."); break; case WalletModel::TransactionCreationFailed: msgParams.first = tr("Transaction creation failed!"); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::TransactionCommitFailed: msgParams.first = tr("The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); msgParams.second = CClientUIInterface::MSG_ERROR; break; case WalletModel::AnonymizeOnlyUnlocked: // Unlock is only need when the coins are send if(!fPrepare) fAskForUnlock = true; else msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins."); break; case WalletModel::InsaneFee: msgParams.first = tr("A fee %1 times higher than %2 per kB is considered an insanely high fee.").arg(10000).arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ::minRelayTxFee.GetFeePerK())); break; // included to prevent a compiler warning. case WalletModel::OK: default: return; } // Unlock wallet if it wasn't fully unlocked already if(fAskForUnlock) { model->requestUnlock(false); if(model->getEncryptionStatus () != WalletModel::Unlocked) { msgParams.first = tr("Error: The wallet was unlocked only to anonymize coins. Unlock canceled."); } else { // Wallet unlocked return; } } emit message(tr("Send Coins"), msgParams.first, msgParams.second); } void SendCoinsDialog::minimizeFeeSection(bool fMinimize) { ui->labelFeeMinimized->setVisible(fMinimize); ui->buttonChooseFee->setVisible(fMinimize); ui->buttonMinimizeFee->setVisible(!fMinimize); ui->frameFeeSelection->setVisible(!fMinimize); ui->horizontalLayoutSmartFee->setContentsMargins(0, (fMinimize ? 0 : 6), 0, 0); fFeeMinimized = fMinimize; } void SendCoinsDialog::on_buttonChooseFee_clicked() { minimizeFeeSection(false); } void SendCoinsDialog::on_buttonMinimizeFee_clicked() { updateFeeMinimizedLabel(); minimizeFeeSection(true); } void SendCoinsDialog::setMinimumFee() { ui->radioCustomPerKilobyte->setChecked(true); ui->customFee->setValue(CWallet::minTxFee.GetFeePerK()); } void SendCoinsDialog::updateFeeSectionControls() { ui->sliderSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee2->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFee3->setEnabled(ui->radioSmartFee->isChecked()); ui->labelFeeEstimation->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeNormal->setEnabled(ui->radioSmartFee->isChecked()); ui->labelSmartFeeFast->setEnabled(ui->radioSmartFee->isChecked()); ui->checkBoxMinimumFee->setEnabled(ui->radioCustomFee->isChecked()); ui->labelMinFeeWarning->setEnabled(ui->radioCustomFee->isChecked()); ui->radioCustomPerKilobyte->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->radioCustomAtLeast->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); ui->customFee->setEnabled(ui->radioCustomFee->isChecked() && !ui->checkBoxMinimumFee->isChecked()); } void SendCoinsDialog::updateGlobalFeeVariables() { if (ui->radioSmartFee->isChecked()) { nTxConfirmTarget = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); payTxFee = CFeeRate(0); } else { nTxConfirmTarget = 25; payTxFee = CFeeRate(ui->customFee->value()); fPayAtLeastCustomFee = ui->radioCustomAtLeast->isChecked(); } fSendFreeTransactions = ui->checkBoxFreeTx->isChecked(); } void SendCoinsDialog::updateFeeMinimizedLabel() { if (!model || !model->getOptionsModel()) return; if (ui->radioSmartFee->isChecked()) ui->labelFeeMinimized->setText(ui->labelSmartFee->text()); else { ui->labelFeeMinimized->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), ui->customFee->value()) + ((ui->radioCustomPerKilobyte->isChecked()) ? "/kB" : "")); } } void SendCoinsDialog::updateMinFeeLabel() { if (model && model->getOptionsModel()) ui->checkBoxMinimumFee->setText(tr("Pay only the minimum fee of %1").arg(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB")); } void SendCoinsDialog::updateSmartFeeLabel() { if (!model || !model->getOptionsModel()) return; int nBlocksToConfirm = (int)25 - (int)std::max(0, std::min(24, ui->sliderSmartFee->value())); CFeeRate feeRate = mempool.estimateFee(nBlocksToConfirm); if (feeRate <= CFeeRate(0)) // not enough data => minfee { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), CWallet::minTxFee.GetFeePerK()) + "/kB"); ui->labelSmartFee2->show(); // (Smart fee not initialized yet. This usually takes a few blocks...) ui->labelFeeEstimation->setText(""); } else { ui->labelSmartFee->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), feeRate.GetFeePerK()) + "/kB"); ui->labelSmartFee2->hide(); ui->labelFeeEstimation->setText(tr("Estimated to begin confirmation within %n block(s).", "", nBlocksToConfirm)); } updateFeeMinimizedLabel(); } // UTXO splitter void SendCoinsDialog::splitBlockChecked(int state) { if (model) { CoinControlDialog::coinControl->fSplitBlock = (state == Qt::Checked); fSplitBlock = (state == Qt::Checked); ui->splitBlockLineEdit->setEnabled((state == Qt::Checked)); ui->labelBlockSizeText->setEnabled((state == Qt::Checked)); ui->labelBlockSize->setEnabled((state == Qt::Checked)); coinControlUpdateLabels(); } } //UTXO splitter void SendCoinsDialog::splitBlockLineEditChanged(const QString& text) { //grab the amount in Coin Control AFter Fee field QString qAfterFee = ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "").simplified().replace(" ", ""); //convert to CAmount CAmount nAfterFee; ParseMoney(qAfterFee.toStdString().c_str(), nAfterFee); //if greater than 0 then divide after fee by the amount of blocks CAmount nSize = nAfterFee; int nBlocks = text.toInt(); if (nAfterFee && nBlocks) nSize = nAfterFee / nBlocks; //assign to split block dummy, which is used to recalculate the fee amount more outputs CoinControlDialog::nSplitBlockDummy = nBlocks; //update labels ui->labelBlockSize->setText(QString::fromStdString(FormatMoney(nSize))); coinControlUpdateLabels(); } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { GUIUtil::setClipboard(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { GUIUtil::setClipboard(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { GUIUtil::setClipboard(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" ")).replace("~", "")); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { GUIUtil::setClipboard(ui->labelCoinControlBytes->text().replace("~", "")); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { GUIUtil::setClipboard(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Dust" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { GUIUtil::setClipboard(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { GUIUtil::setClipboard(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" ")).replace("~", "")); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); if (checked) coinControlUpdateLabels(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (state == Qt::Unchecked) { CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->clear(); } else // use this to re-validate an already entered address coinControlChangeEdited(ui->lineEditCoinControlChange->text()); ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString& text) { if (model && model->getAddressTableModel()) { // Default to no change address until verified CoinControlDialog::coinControl->destChange = CNoDestination(); ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); CBitcoinAddress addr = CBitcoinAddress(text.toStdString()); if (text.isEmpty()) // Nothing entered { ui->labelCoinControlChangeLabel->setText(""); } else if (!addr.IsValid()) // Invalid address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Invalid cteam address")); } else // Valid address { CPubKey pubkey; CKeyID keyid; addr.GetKeyID(keyid); if (!model->getPubKey(keyid, pubkey)) // Unknown change address { ui->labelCoinControlChangeLabel->setText(tr("Warning: Unknown change address")); } else // Known change address { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:black;}"); // Query label QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else ui->labelCoinControlChangeLabel->setText(tr("(no label)")); CoinControlDialog::coinControl->destChange = addr.Get(); } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for (int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if (entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } ui->checkUseObfuscation->setChecked(CoinControlDialog::coinControl->useObfuScation); if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
/* * Copyright (C) 2020 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <rmf_mock_adapter/adapter.hpp> #include <rmf_traffic/schedule/Database.hpp> #include <iostream> namespace rmf_mock_adapter { //============================================================================== class RobotUpdateHandle::Implementation { public: rmf_traffic::schedule::Participant participant; std::shared_ptr<rmf_traffic::agv::Planner> planner; rmf_traffic::agv::Planner::Options options; std::weak_ptr<RobotCommandHandle> weak_command; std::vector<rmf_traffic::agv::Plan::Start> position; rmf_utils::optional<rmf_traffic::agv::Plan::Goal> goal = rmf_utils::nullopt; bool finished = false; void send_path_command() { if (!goal) { std::cerr << "ERROR: Trying to issue a path command to [" << participant.description().name() << "] before a goal is set!" << std::endl; return; } const auto command = weak_command.lock(); if (!command) { std::cerr << "ERROR: Trying to issue a path command to [" << participant.description().name() << "] after its command " << "handle has expired" << std::endl; return; } auto result = planner->plan(position, *goal); if (!result) { std::cerr << "Unable to find a feasible plan.\nStart conditions:"; for (const auto& s : position) { std::cout << " -- initial waypoint: " << s.waypoint(); if (s.location()) { std::cout << " | initial location: (" << s.location()->transpose() << ")"; } if (s.lane()) { std::cout << " | initial lane: " << *s.lane() << std::endl; } } return; } finished = false; participant.set(result->get_itinerary()); std::cout << "Issuing new path command to [" << participant.description().name() << "]" << std::endl; command->follow_new_path( result->get_waypoints(), [&]() { std::cout << "[" << participant.description().name() << "] has reported " << "finishing!" << std::endl; finished = true; }); } static std::shared_ptr<RobotUpdateHandle> make_shared( const rmf_traffic::schedule::Viewer& viewer, rmf_traffic::schedule::Participant participant, std::shared_ptr<rmf_traffic::agv::Planner> planner, std::shared_ptr<RobotCommandHandle> command, std::vector<rmf_traffic::agv::Plan::Start> position) { auto handle = std::shared_ptr<RobotUpdateHandle>(new RobotUpdateHandle); auto options = rmf_traffic::agv::Planner::Options( rmf_utils::make_clone<rmf_traffic::agv::ScheduleRouteValidator>( viewer, participant.id(), participant.description().profile())); handle->_pimpl = rmf_utils::make_unique_impl<Implementation>( Implementation{ std::move(participant), std::move(planner), std::move(options), std::move(command), std::move(position) }); return handle; } static void set_goal( RobotUpdateHandle& handle, rmf_traffic::agv::Plan::Goal goal) { handle._pimpl->goal = std::move(goal); handle._pimpl->send_path_command(); } static bool is_finished(const RobotUpdateHandle& handle) { return handle._pimpl->finished; } }; //============================================================================== std::vector<rmf_traffic::agv::Plan::Start> make_starts( std::size_t initial_waypoint, double orientation) { const auto now = std::chrono::steady_clock::now(); return {rmf_traffic::agv::Plan::Start(now, initial_waypoint, orientation)}; } //============================================================================== std::vector<rmf_traffic::agv::Plan::Start> make_starts( const rmf_traffic::agv::Graph& nav_graph, const Eigen::Vector3d& initial_position, const std::vector<std::size_t>& initial_lanes) { assert(!initial_lanes.empty()); const auto now = std::chrono::steady_clock::now(); std::vector<rmf_traffic::agv::Plan::Start> starts; for (const std::size_t l : initial_lanes) { const auto wp = nav_graph.get_lane(l).exit().waypoint_index(); starts.emplace_back( now, wp, initial_position[2], Eigen::Vector2d(initial_position.block<2,1>(0,0)), l); } return starts; } //============================================================================== void RobotUpdateHandle::add_delay(rmf_traffic::Duration duration) { _pimpl->participant.delay(std::chrono::steady_clock::now(), duration); } //============================================================================== void RobotUpdateHandle::interrupted() { std::cout << "[" << _pimpl->participant.description().name() << "] was interrupted! We will send a new plan." << std::endl; _pimpl->send_path_command(); } //============================================================================== void RobotUpdateHandle::update_position( std::size_t waypoint, double orientation) { _pimpl->position = make_starts(waypoint, orientation); } //============================================================================== void RobotUpdateHandle::update_position( const Eigen::Vector3d& position, const std::vector<std::size_t>& lanes) { _pimpl->position = make_starts( _pimpl->planner->get_configuration().graph(), position, lanes); } //============================================================================== void RobotUpdateHandle::update_position( const std::string& map_name, const Eigen::Vector3d& position) { const auto now = std::chrono::steady_clock::now(); _pimpl->position = rmf_traffic::agv::compute_plan_starts( _pimpl->planner->get_configuration().graph(), map_name, position, now); } //============================================================================== class FleetUpdateHandle::Implementation { public: std::shared_ptr<rmf_traffic::schedule::Database> database; std::string fleet_name; std::shared_ptr<rmf_traffic::agv::Planner> planner; static FleetUpdateHandle make( std::shared_ptr<rmf_traffic::schedule::Database> database, std::string fleet_name, rmf_traffic::agv::Graph nav_graph, rmf_traffic::agv::VehicleTraits traits) { auto planner = std::make_shared<rmf_traffic::agv::Planner>( rmf_traffic::agv::Planner::Configuration( nav_graph, traits), rmf_traffic::agv::Planner::Options(nullptr)); FleetUpdateHandle handle; handle._pimpl = rmf_utils::make_unique_impl<Implementation>( Implementation{ std::move(database), std::move(fleet_name), std::move(planner) }); return handle; } std::shared_ptr<RobotUpdateHandle> add_robot( std::shared_ptr<RobotCommandHandle> command, const std::string& name, const rmf_traffic::Profile& profile, std::vector<rmf_traffic::agv::Plan::Start> position) { auto description = rmf_traffic::schedule::ParticipantDescription( name, fleet_name, rmf_traffic::schedule::ParticipantDescription::Rx::Responsive, profile); auto participant = rmf_traffic::schedule::make_participant( std::move(description), *database); return RobotUpdateHandle::Implementation::make_shared( *database, std::move(participant), planner, std::move(command), std::move(position)); } }; //============================================================================== std::shared_ptr<RobotUpdateHandle> FleetUpdateHandle::add_robot( std::shared_ptr<RobotCommandHandle> handle, const std::string& name, const rmf_traffic::Profile& profile, std::size_t initial_waypoint, double orientation) { return _pimpl->add_robot( handle, name, profile, make_starts(initial_waypoint, orientation)); } //============================================================================== std::shared_ptr<RobotUpdateHandle> FleetUpdateHandle::add_robot( std::shared_ptr<RobotCommandHandle> handle, const std::string& name, const rmf_traffic::Profile& profile, const Eigen::Vector3d& initial_position, const std::vector<std::size_t>& initial_lanes) { return _pimpl->add_robot( handle, name, profile, make_starts( _pimpl->planner->get_configuration().graph(), initial_position, initial_lanes)); } //============================================================================== FleetUpdateHandle::FleetUpdateHandle() { // Do nothing } //============================================================================== class TestScenario::Implementation { public: std::shared_ptr<rmf_traffic::schedule::Database> database; std::vector<std::shared_ptr<RobotUpdateHandle>> handles; Implementation() : database(std::make_shared<rmf_traffic::schedule::Database>()) { // Do nothing } }; //============================================================================== FleetUpdateHandle TestScenario::add_fleet( std::string fleet_name, rmf_traffic::agv::Graph nav_graph, rmf_traffic::agv::VehicleTraits traits) { return FleetUpdateHandle::Implementation::make( _pimpl->database, std::move(fleet_name), std::move(nav_graph), std::move(traits)); } //============================================================================== void TestScenario::test(std::vector<Condition> conditions) { for (const auto& condition : conditions) { RobotUpdateHandle::Implementation::set_goal( *condition.robot, condition.goal); _pimpl->handles.push_back(condition.robot); } } //============================================================================== bool TestScenario::finished() const { for (const auto& handle : _pimpl->handles) if (!RobotUpdateHandle::Implementation::is_finished(*handle)) return false; return true; } //============================================================================== TestScenario::TestScenario() : _pimpl(rmf_utils::make_unique_impl<Implementation>()) { // Do nothing } } // namespace rmf_mock_adapter
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "splashscreen.h" #include "clientversion.h" #include "init.h" #include "networkstyle.h" #include "ui_interface.h" #include "util.h" #include "version.h" #ifdef ENABLE_WALLET #include "wallet.h" #endif #include <QApplication> #include <QCloseEvent> #include <QDesktopWidget> #include <QPainter> SplashScreen::SplashScreen(Qt::WindowFlags f, const NetworkStyle* networkStyle) : QWidget(0, f), curAlignment(0) { // set reference point, paddings int paddingLeft = 14; int paddingTop = 470; int titleVersionVSpace = 17; int titleCopyrightVSpace = 32; float fontFactor = 1.0; // define text to place QString titleText = tr("Bitcoinlegend [BCL]"); QString versionText = QString(tr("Version %1")).arg(QString::fromStdString(FormatFullVersion())); QString copyrightTextBtc = QChar(0xA9) + QString(" 2009-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoin Core developers")); QString copyrightTextDash = QChar(0xA9) + QString(" 2014-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Dash Core developers")); QString copyrightTextPIVX = QChar(0xA9) + QString(" 2015-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The PIVX Core developers")); QString copyrightTextBitcoinlegend = QChar(0xA9) + QString(" 2017-%1 ").arg(COPYRIGHT_YEAR) + QString(tr("The Bitcoinlegend Core developers")); QString titleAddText = networkStyle->getTitleAddText(); QString font = QApplication::font().toString(); // load the bitmap for writing some text over it pixmap = networkStyle->getSplashImage(); QPainter pixPaint(&pixmap); pixPaint.setPen(QColor(100, 100, 100)); // check font size and drawing with pixPaint.setFont(QFont(font, 28 * fontFactor)); QFontMetrics fm = pixPaint.fontMetrics(); int titleTextWidth = fm.width(titleText); if (titleTextWidth > 160) { // strange font rendering, Arial probably not found fontFactor = 0.75; } pixPaint.setFont(QFont(font, 28 * fontFactor)); fm = pixPaint.fontMetrics(); //titleTextWidth = fm.width(titleText); pixPaint.drawText(paddingLeft, paddingTop, titleText); pixPaint.setFont(QFont(font, 15 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleVersionVSpace, versionText); // draw copyright stuff pixPaint.setFont(QFont(font, 10 * fontFactor)); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace, copyrightTextBtc); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 12, copyrightTextDash); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 24, copyrightTextPIVX); pixPaint.drawText(paddingLeft, paddingTop + titleCopyrightVSpace + 36, copyrightTextBitcoinlegend); // draw additional text if special network if (!titleAddText.isEmpty()) { QFont boldFont = QFont(font, 10 * fontFactor); boldFont.setWeight(QFont::Bold); pixPaint.setFont(boldFont); fm = pixPaint.fontMetrics(); int titleAddTextWidth = fm.width(titleAddText); pixPaint.drawText(pixmap.width() - titleAddTextWidth - 10, pixmap.height() - 25, titleAddText); } pixPaint.end(); // Set window title setWindowTitle(titleText + " " + titleAddText); // Resize window and move to center of desktop, disallow resizing QRect r(QPoint(), pixmap.size()); resize(r.size()); setFixedSize(r.size()); move(QApplication::desktop()->screenGeometry().center() - r.center()); subscribeToCoreSignals(); } SplashScreen::~SplashScreen() { unsubscribeFromCoreSignals(); } void SplashScreen::slotFinish(QWidget* mainWin) { Q_UNUSED(mainWin); hide(); } static void InitMessage(SplashScreen* splash, const std::string& message) { QMetaObject::invokeMethod(splash, "showMessage", Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(message)), Q_ARG(int, Qt::AlignBottom | Qt::AlignHCenter), Q_ARG(QColor, QColor(100, 100, 100))); } static void ShowProgress(SplashScreen* splash, const std::string& title, int nProgress) { InitMessage(splash, title + strprintf("%d", nProgress) + "%"); } #ifdef ENABLE_WALLET static void ConnectWallet(SplashScreen* splash, CWallet* wallet) { wallet->ShowProgress.connect(boost::bind(ShowProgress, splash, _1, _2)); } #endif void SplashScreen::subscribeToCoreSignals() { // Connect signals to client uiInterface.InitMessage.connect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET uiInterface.LoadWallet.connect(boost::bind(ConnectWallet, this, _1)); #endif } void SplashScreen::unsubscribeFromCoreSignals() { // Disconnect signals from client uiInterface.InitMessage.disconnect(boost::bind(InitMessage, this, _1)); uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2)); #endif } void SplashScreen::showMessage(const QString& message, int alignment, const QColor& color) { curMessage = message; curAlignment = alignment; curColor = color; update(); } void SplashScreen::paintEvent(QPaintEvent* event) { QPainter painter(this); painter.drawPixmap(0, 0, pixmap); QRect r = rect().adjusted(5, 5, -5, -5); painter.setPen(curColor); painter.drawText(r, curAlignment, curMessage); } void SplashScreen::closeEvent(QCloseEvent* event) { StartShutdown(); // allows an "emergency" shutdown during startup event->ignore(); }
//===--- SerializedDiagnosticPrinter.cpp - Serializer for diagnostics -----===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "clang/Frontend/SerializedDiagnosticPrinter.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Version.h" #include "clang/Frontend/DiagnosticRenderer.h" #include "clang/Frontend/FrontendDiagnostic.h" #include "clang/Frontend/SerializedDiagnosticReader.h" #include "clang/Frontend/SerializedDiagnostics.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Lexer.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/raw_ostream.h" #include <vector> using namespace clang; using namespace clang::serialized_diags; namespace { class AbbreviationMap { llvm::DenseMap<unsigned, unsigned> Abbrevs; public: AbbreviationMap() {} void set(unsigned recordID, unsigned abbrevID) { assert(Abbrevs.find(recordID) == Abbrevs.end() && "Abbreviation already set."); Abbrevs[recordID] = abbrevID; } unsigned get(unsigned recordID) { assert(Abbrevs.find(recordID) != Abbrevs.end() && "Abbreviation not set."); return Abbrevs[recordID]; } }; typedef SmallVector<uint64_t, 64> RecordData; typedef SmallVectorImpl<uint64_t> RecordDataImpl; class SDiagsWriter; class SDiagsRenderer : public DiagnosticNoteRenderer { SDiagsWriter &Writer; public: SDiagsRenderer(SDiagsWriter &Writer, const LangOptions &LangOpts, DiagnosticOptions *DiagOpts) : DiagnosticNoteRenderer(LangOpts, DiagOpts), Writer(Writer) {} virtual ~SDiagsRenderer() {} protected: void emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<CharSourceRange> Ranges, const SourceManager *SM, DiagOrStoredDiag D) override; void emitDiagnosticLoc(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, ArrayRef<CharSourceRange> Ranges, const SourceManager &SM) override {} void emitNote(SourceLocation Loc, StringRef Message, const SourceManager *SM) override; void emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level, SmallVectorImpl<CharSourceRange>& Ranges, ArrayRef<FixItHint> Hints, const SourceManager &SM) override; void beginDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) override; void endDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) override; }; typedef llvm::DenseMap<unsigned, unsigned> AbbrevLookup; class SDiagsMerger : SerializedDiagnosticReader { SDiagsWriter &Writer; AbbrevLookup FileLookup; AbbrevLookup CategoryLookup; AbbrevLookup DiagFlagLookup; public: SDiagsMerger(SDiagsWriter &Writer) : SerializedDiagnosticReader(), Writer(Writer) {} std::error_code mergeRecordsFromFile(const char *File) { return readDiagnostics(File); } protected: std::error_code visitStartOfDiagnostic() override; std::error_code visitEndOfDiagnostic() override; std::error_code visitCategoryRecord(unsigned ID, StringRef Name) override; std::error_code visitDiagFlagRecord(unsigned ID, StringRef Name) override; std::error_code visitDiagnosticRecord( unsigned Severity, const serialized_diags::Location &Location, unsigned Category, unsigned Flag, StringRef Message) override; std::error_code visitFilenameRecord(unsigned ID, unsigned Size, unsigned Timestamp, StringRef Name) override; std::error_code visitFixitRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End, StringRef CodeToInsert) override; std::error_code visitSourceRangeRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End) override; private: std::error_code adjustSourceLocFilename(RecordData &Record, unsigned int offset); void adjustAbbrevID(RecordData &Record, AbbrevLookup &Lookup, unsigned NewAbbrev); void writeRecordWithAbbrev(unsigned ID, RecordData &Record); void writeRecordWithBlob(unsigned ID, RecordData &Record, StringRef Blob); }; class SDiagsWriter : public DiagnosticConsumer { friend class SDiagsRenderer; friend class SDiagsMerger; struct SharedState; explicit SDiagsWriter(IntrusiveRefCntPtr<SharedState> State) : LangOpts(nullptr), OriginalInstance(false), MergeChildRecords(false), State(State) {} public: SDiagsWriter(StringRef File, DiagnosticOptions *Diags, bool MergeChildRecords) : LangOpts(nullptr), OriginalInstance(true), MergeChildRecords(MergeChildRecords), State(new SharedState(File, Diags)) { if (MergeChildRecords) RemoveOldDiagnostics(); EmitPreamble(); } ~SDiagsWriter() {} void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) override; void BeginSourceFile(const LangOptions &LO, const Preprocessor *PP) override { LangOpts = &LO; } void finish() override; private: /// \brief Build a DiagnosticsEngine to emit diagnostics about the diagnostics DiagnosticsEngine *getMetaDiags(); /// \brief Remove old copies of the serialized diagnostics. This is necessary /// so that we can detect when subprocesses write diagnostics that we should /// merge into our own. void RemoveOldDiagnostics(); /// \brief Emit the preamble for the serialized diagnostics. void EmitPreamble(); /// \brief Emit the BLOCKINFO block. void EmitBlockInfoBlock(); /// \brief Emit the META data block. void EmitMetaBlock(); /// \brief Start a DIAG block. void EnterDiagBlock(); /// \brief End a DIAG block. void ExitDiagBlock(); /// \brief Emit a DIAG record. void EmitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, const SourceManager *SM, DiagOrStoredDiag D); /// \brief Emit FIXIT and SOURCE_RANGE records for a diagnostic. void EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints, const SourceManager &SM); /// \brief Emit a record for a CharSourceRange. void EmitCharSourceRange(CharSourceRange R, const SourceManager &SM); /// \brief Emit the string information for the category. unsigned getEmitCategory(unsigned category = 0); /// \brief Emit the string information for diagnostic flags. unsigned getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID = 0); unsigned getEmitDiagnosticFlag(StringRef DiagName); /// \brief Emit (lazily) the file string and retrieved the file identifier. unsigned getEmitFile(const char *Filename); /// \brief Add SourceLocation information the specified record. void AddLocToRecord(SourceLocation Loc, const SourceManager *SM, PresumedLoc PLoc, RecordDataImpl &Record, unsigned TokSize = 0); /// \brief Add SourceLocation information the specified record. void AddLocToRecord(SourceLocation Loc, RecordDataImpl &Record, const SourceManager *SM, unsigned TokSize = 0) { AddLocToRecord(Loc, SM, SM ? SM->getPresumedLoc(Loc) : PresumedLoc(), Record, TokSize); } /// \brief Add CharSourceRange information the specified record. void AddCharSourceRangeToRecord(CharSourceRange R, RecordDataImpl &Record, const SourceManager &SM); /// \brief Language options, which can differ from one clone of this client /// to another. const LangOptions *LangOpts; /// \brief Whether this is the original instance (rather than one of its /// clones), responsible for writing the file at the end. bool OriginalInstance; /// \brief Whether this instance should aggregate diagnostics that are /// generated from child processes. bool MergeChildRecords; /// \brief State that is shared among the various clones of this diagnostic /// consumer. struct SharedState : RefCountedBase<SharedState> { SharedState(StringRef File, DiagnosticOptions *Diags) : DiagOpts(Diags), Stream(Buffer), OutputFile(File.str()), EmittedAnyDiagBlocks(false) {} /// \brief Diagnostic options. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; /// \brief The byte buffer for the serialized content. SmallString<1024> Buffer; /// \brief The BitStreamWriter for the serialized diagnostics. llvm::BitstreamWriter Stream; /// \brief The name of the diagnostics file. std::string OutputFile; /// \brief The set of constructed record abbreviations. AbbreviationMap Abbrevs; /// \brief A utility buffer for constructing record content. RecordData Record; /// \brief A text buffer for rendering diagnostic text. SmallString<256> diagBuf; /// \brief The collection of diagnostic categories used. llvm::DenseSet<unsigned> Categories; /// \brief The collection of files used. llvm::DenseMap<const char *, unsigned> Files; typedef llvm::DenseMap<const void *, std::pair<unsigned, StringRef> > DiagFlagsTy; /// \brief Map for uniquing strings. DiagFlagsTy DiagFlags; /// \brief Whether we have already started emission of any DIAG blocks. Once /// this becomes \c true, we never close a DIAG block until we know that we're /// starting another one or we're done. bool EmittedAnyDiagBlocks; /// \brief Engine for emitting diagnostics about the diagnostics. std::unique_ptr<DiagnosticsEngine> MetaDiagnostics; }; /// \brief State shared among the various clones of this diagnostic consumer. IntrusiveRefCntPtr<SharedState> State; }; } // end anonymous namespace namespace clang { namespace serialized_diags { std::unique_ptr<DiagnosticConsumer> create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords) { return llvm::make_unique<SDiagsWriter>(OutputFile, Diags, MergeChildRecords); } } // end namespace serialized_diags } // end namespace clang //===----------------------------------------------------------------------===// // Serialization methods. //===----------------------------------------------------------------------===// /// \brief Emits a block ID in the BLOCKINFO block. static void EmitBlockID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, RecordDataImpl &Record) { Record.clear(); Record.push_back(ID); Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record); // Emit the block name if present. if (!Name || Name[0] == 0) return; Record.clear(); while (*Name) Record.push_back(*Name++); Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record); } /// \brief Emits a record ID in the BLOCKINFO block. static void EmitRecordID(unsigned ID, const char *Name, llvm::BitstreamWriter &Stream, RecordDataImpl &Record){ Record.clear(); Record.push_back(ID); while (*Name) Record.push_back(*Name++); Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record); } void SDiagsWriter::AddLocToRecord(SourceLocation Loc, const SourceManager *SM, PresumedLoc PLoc, RecordDataImpl &Record, unsigned TokSize) { if (PLoc.isInvalid()) { // Emit a "sentinel" location. Record.push_back((unsigned)0); // File. Record.push_back((unsigned)0); // Line. Record.push_back((unsigned)0); // Column. Record.push_back((unsigned)0); // Offset. return; } Record.push_back(getEmitFile(PLoc.getFilename())); Record.push_back(PLoc.getLine()); Record.push_back(PLoc.getColumn()+TokSize); Record.push_back(SM->getFileOffset(Loc)); } void SDiagsWriter::AddCharSourceRangeToRecord(CharSourceRange Range, RecordDataImpl &Record, const SourceManager &SM) { AddLocToRecord(Range.getBegin(), Record, &SM); unsigned TokSize = 0; if (Range.isTokenRange()) TokSize = Lexer::MeasureTokenLength(Range.getEnd(), SM, *LangOpts); AddLocToRecord(Range.getEnd(), Record, &SM, TokSize); } unsigned SDiagsWriter::getEmitFile(const char *FileName){ if (!FileName) return 0; unsigned &entry = State->Files[FileName]; if (entry) return entry; // Lazily generate the record for the file. entry = State->Files.size(); RecordData Record; Record.push_back(RECORD_FILENAME); Record.push_back(entry); Record.push_back(0); // For legacy. Record.push_back(0); // For legacy. StringRef Name(FileName); Record.push_back(Name.size()); State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_FILENAME), Record, Name); return entry; } void SDiagsWriter::EmitCharSourceRange(CharSourceRange R, const SourceManager &SM) { State->Record.clear(); State->Record.push_back(RECORD_SOURCE_RANGE); AddCharSourceRangeToRecord(R, State->Record, SM); State->Stream.EmitRecordWithAbbrev(State->Abbrevs.get(RECORD_SOURCE_RANGE), State->Record); } /// \brief Emits the preamble of the diagnostics file. void SDiagsWriter::EmitPreamble() { // Emit the file header. State->Stream.Emit((unsigned)'D', 8); State->Stream.Emit((unsigned)'I', 8); State->Stream.Emit((unsigned)'A', 8); State->Stream.Emit((unsigned)'G', 8); EmitBlockInfoBlock(); EmitMetaBlock(); } static void AddSourceLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) { using namespace llvm; Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // File ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Line. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Column. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Offset; } static void AddRangeLocationAbbrev(llvm::BitCodeAbbrev *Abbrev) { AddSourceLocationAbbrev(Abbrev); AddSourceLocationAbbrev(Abbrev); } void SDiagsWriter::EmitBlockInfoBlock() { State->Stream.EnterBlockInfoBlock(3); using namespace llvm; llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; // ==---------------------------------------------------------------------==// // The subsequent records and Abbrevs are for the "Meta" block. // ==---------------------------------------------------------------------==// EmitBlockID(BLOCK_META, "Meta", Stream, Record); EmitRecordID(RECORD_VERSION, "Version", Stream, Record); BitCodeAbbrev *Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_VERSION)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); Abbrevs.set(RECORD_VERSION, Stream.EmitBlockInfoAbbrev(BLOCK_META, Abbrev)); // ==---------------------------------------------------------------------==// // The subsequent records and Abbrevs are for the "Diagnostic" block. // ==---------------------------------------------------------------------==// EmitBlockID(BLOCK_DIAG, "Diag", Stream, Record); EmitRecordID(RECORD_DIAG, "DiagInfo", Stream, Record); EmitRecordID(RECORD_SOURCE_RANGE, "SrcRange", Stream, Record); EmitRecordID(RECORD_CATEGORY, "CatName", Stream, Record); EmitRecordID(RECORD_DIAG_FLAG, "DiagFlag", Stream, Record); EmitRecordID(RECORD_FILENAME, "FileName", Stream, Record); EmitRecordID(RECORD_FIXIT, "FixIt", Stream, Record); // Emit abbreviation for RECORD_DIAG. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Diag level. AddSourceLocationAbbrev(Abbrev); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Category. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Diagnostc text. Abbrevs.set(RECORD_DIAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); // Emit abbrevation for RECORD_CATEGORY. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_CATEGORY)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Category ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 8)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Category text. Abbrevs.set(RECORD_CATEGORY, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); // Emit abbrevation for RECORD_SOURCE_RANGE. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_SOURCE_RANGE)); AddRangeLocationAbbrev(Abbrev); Abbrevs.set(RECORD_SOURCE_RANGE, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); // Emit the abbreviation for RECORD_DIAG_FLAG. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_DIAG_FLAG)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped Diag ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Flag name text. Abbrevs.set(RECORD_DIAG_FLAG, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); // Emit the abbreviation for RECORD_FILENAME. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FILENAME)); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 10)); // Mapped file ID. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // Modifcation time. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name text. Abbrevs.set(RECORD_FILENAME, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); // Emit the abbreviation for RECORD_FIXIT. Abbrev = new BitCodeAbbrev(); Abbrev->Add(BitCodeAbbrevOp(RECORD_FIXIT)); AddRangeLocationAbbrev(Abbrev); Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Text size. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // FixIt text. Abbrevs.set(RECORD_FIXIT, Stream.EmitBlockInfoAbbrev(BLOCK_DIAG, Abbrev)); Stream.ExitBlock(); } void SDiagsWriter::EmitMetaBlock() { llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; Stream.EnterSubblock(BLOCK_META, 3); Record.clear(); Record.push_back(RECORD_VERSION); Record.push_back(VersionNumber); Stream.EmitRecordWithAbbrev(Abbrevs.get(RECORD_VERSION), Record); Stream.ExitBlock(); } unsigned SDiagsWriter::getEmitCategory(unsigned int category) { if (!State->Categories.insert(category).second) return category; // We use a local version of 'Record' so that we can be generating // another record when we lazily generate one for the category entry. RecordData Record; Record.push_back(RECORD_CATEGORY); Record.push_back(category); StringRef catName = DiagnosticIDs::getCategoryNameFromID(category); Record.push_back(catName.size()); State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_CATEGORY), Record, catName); return category; } unsigned SDiagsWriter::getEmitDiagnosticFlag(DiagnosticsEngine::Level DiagLevel, unsigned DiagID) { if (DiagLevel == DiagnosticsEngine::Note) return 0; // No flag for notes. StringRef FlagName = DiagnosticIDs::getWarningOptionForDiag(DiagID); return getEmitDiagnosticFlag(FlagName); } unsigned SDiagsWriter::getEmitDiagnosticFlag(StringRef FlagName) { if (FlagName.empty()) return 0; // Here we assume that FlagName points to static data whose pointer // value is fixed. This allows us to unique by diagnostic groups. const void *data = FlagName.data(); std::pair<unsigned, StringRef> &entry = State->DiagFlags[data]; if (entry.first == 0) { entry.first = State->DiagFlags.size(); entry.second = FlagName; // Lazily emit the string in a separate record. RecordData Record; Record.push_back(RECORD_DIAG_FLAG); Record.push_back(entry.first); Record.push_back(FlagName.size()); State->Stream.EmitRecordWithBlob(State->Abbrevs.get(RECORD_DIAG_FLAG), Record, FlagName); } return entry.first; } void SDiagsWriter::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { // Enter the block for a non-note diagnostic immediately, rather than waiting // for beginDiagnostic, in case associated notes are emitted before we get // there. if (DiagLevel != DiagnosticsEngine::Note) { if (State->EmittedAnyDiagBlocks) ExitDiagBlock(); EnterDiagBlock(); State->EmittedAnyDiagBlocks = true; } // Compute the diagnostic text. State->diagBuf.clear(); Info.FormatDiagnostic(State->diagBuf); if (Info.getLocation().isInvalid()) { // Special-case diagnostics with no location. We may not have entered a // source file in this case, so we can't use the normal DiagnosticsRenderer // machinery. // Make sure we bracket all notes as "sub-diagnostics". This matches // the behavior in SDiagsRenderer::emitDiagnostic(). if (DiagLevel == DiagnosticsEngine::Note) EnterDiagBlock(); EmitDiagnosticMessage(SourceLocation(), PresumedLoc(), DiagLevel, State->diagBuf, nullptr, &Info); if (DiagLevel == DiagnosticsEngine::Note) ExitDiagBlock(); return; } assert(Info.hasSourceManager() && LangOpts && "Unexpected diagnostic with valid location outside of a source file"); SDiagsRenderer Renderer(*this, *LangOpts, &*State->DiagOpts); Renderer.emitDiagnostic(Info.getLocation(), DiagLevel, State->diagBuf.str(), Info.getRanges(), Info.getFixItHints(), &Info.getSourceManager(), &Info); } static serialized_diags::Level getStableLevel(DiagnosticsEngine::Level Level) { switch (Level) { #define CASE(X) case DiagnosticsEngine::X: return serialized_diags::X; CASE(Ignored) CASE(Note) CASE(Remark) CASE(Warning) CASE(Error) CASE(Fatal) #undef CASE } llvm_unreachable("invalid diagnostic level"); } void SDiagsWriter::EmitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, const SourceManager *SM, DiagOrStoredDiag D) { llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; // Emit the RECORD_DIAG record. Record.clear(); Record.push_back(RECORD_DIAG); Record.push_back(getStableLevel(Level)); AddLocToRecord(Loc, SM, PLoc, Record); if (const Diagnostic *Info = D.dyn_cast<const Diagnostic*>()) { // Emit the category string lazily and get the category ID. unsigned DiagID = DiagnosticIDs::getCategoryNumberForDiag(Info->getID()); Record.push_back(getEmitCategory(DiagID)); // Emit the diagnostic flag string lazily and get the mapped ID. Record.push_back(getEmitDiagnosticFlag(Level, Info->getID())); } else { Record.push_back(getEmitCategory()); Record.push_back(getEmitDiagnosticFlag(Level)); } Record.push_back(Message.size()); Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Message); } void SDiagsRenderer::emitDiagnosticMessage(SourceLocation Loc, PresumedLoc PLoc, DiagnosticsEngine::Level Level, StringRef Message, ArrayRef<clang::CharSourceRange> Ranges, const SourceManager *SM, DiagOrStoredDiag D) { Writer.EmitDiagnosticMessage(Loc, PLoc, Level, Message, SM, D); } void SDiagsWriter::EnterDiagBlock() { State->Stream.EnterSubblock(BLOCK_DIAG, 4); } void SDiagsWriter::ExitDiagBlock() { State->Stream.ExitBlock(); } void SDiagsRenderer::beginDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) { if (Level == DiagnosticsEngine::Note) Writer.EnterDiagBlock(); } void SDiagsRenderer::endDiagnostic(DiagOrStoredDiag D, DiagnosticsEngine::Level Level) { // Only end note diagnostics here, because we can't be sure when we've seen // the last note associated with a non-note diagnostic. if (Level == DiagnosticsEngine::Note) Writer.ExitDiagBlock(); } void SDiagsWriter::EmitCodeContext(SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints, const SourceManager &SM) { llvm::BitstreamWriter &Stream = State->Stream; RecordData &Record = State->Record; AbbreviationMap &Abbrevs = State->Abbrevs; // Emit Source Ranges. for (ArrayRef<CharSourceRange>::iterator I = Ranges.begin(), E = Ranges.end(); I != E; ++I) if (I->isValid()) EmitCharSourceRange(*I, SM); // Emit FixIts. for (ArrayRef<FixItHint>::iterator I = Hints.begin(), E = Hints.end(); I != E; ++I) { const FixItHint &Fix = *I; if (Fix.isNull()) continue; Record.clear(); Record.push_back(RECORD_FIXIT); AddCharSourceRangeToRecord(Fix.RemoveRange, Record, SM); Record.push_back(Fix.CodeToInsert.size()); Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_FIXIT), Record, Fix.CodeToInsert); } } void SDiagsRenderer::emitCodeContext(SourceLocation Loc, DiagnosticsEngine::Level Level, SmallVectorImpl<CharSourceRange> &Ranges, ArrayRef<FixItHint> Hints, const SourceManager &SM) { Writer.EmitCodeContext(Ranges, Hints, SM); } void SDiagsRenderer::emitNote(SourceLocation Loc, StringRef Message, const SourceManager *SM) { Writer.EnterDiagBlock(); PresumedLoc PLoc = SM ? SM->getPresumedLoc(Loc) : PresumedLoc(); Writer.EmitDiagnosticMessage(Loc, PLoc, DiagnosticsEngine::Note, Message, SM, DiagOrStoredDiag()); Writer.ExitDiagBlock(); } DiagnosticsEngine *SDiagsWriter::getMetaDiags() { // FIXME: It's slightly absurd to create a new diagnostics engine here, but // the other options that are available today are worse: // // 1. Teach DiagnosticsConsumers to emit diagnostics to the engine they are a // part of. The DiagnosticsEngine would need to know not to send // diagnostics back to the consumer that failed. This would require us to // rework ChainedDiagnosticsConsumer and teach the engine about multiple // consumers, which is difficult today because most APIs interface with // consumers rather than the engine itself. // // 2. Pass a DiagnosticsEngine to SDiagsWriter on creation - this would need // to be distinct from the engine the writer was being added to and would // normally not be used. if (!State->MetaDiagnostics) { IntrusiveRefCntPtr<DiagnosticIDs> IDs(new DiagnosticIDs()); auto Client = new TextDiagnosticPrinter(llvm::errs(), State->DiagOpts.get()); State->MetaDiagnostics = llvm::make_unique<DiagnosticsEngine>( IDs, State->DiagOpts.get(), Client); } return State->MetaDiagnostics.get(); } void SDiagsWriter::RemoveOldDiagnostics() { if (!llvm::sys::fs::remove(State->OutputFile)) return; getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure); // Disable merging child records, as whatever is in this file may be // misleading. MergeChildRecords = false; } void SDiagsWriter::finish() { // The original instance is responsible for writing the file. if (!OriginalInstance) return; // Finish off any diagnostic we were in the process of emitting. if (State->EmittedAnyDiagBlocks) ExitDiagBlock(); if (MergeChildRecords) { if (!State->EmittedAnyDiagBlocks) // We have no diagnostics of our own, so we can just leave the child // process' output alone return; if (llvm::sys::fs::exists(State->OutputFile)) if (SDiagsMerger(*this).mergeRecordsFromFile(State->OutputFile.c_str())) getMetaDiags()->Report(diag::warn_fe_serialized_diag_merge_failure); } std::error_code EC; auto OS = llvm::make_unique<llvm::raw_fd_ostream>(State->OutputFile.c_str(), EC, llvm::sys::fs::F_None); if (EC) { getMetaDiags()->Report(diag::warn_fe_serialized_diag_failure) << State->OutputFile << EC.message(); return; } // Write the generated bitstream to "Out". OS->write((char *)&State->Buffer.front(), State->Buffer.size()); OS->flush(); } std::error_code SDiagsMerger::visitStartOfDiagnostic() { Writer.EnterDiagBlock(); return std::error_code(); } std::error_code SDiagsMerger::visitEndOfDiagnostic() { Writer.ExitDiagBlock(); return std::error_code(); } std::error_code SDiagsMerger::visitSourceRangeRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End) { RecordData Record; Record.push_back(RECORD_SOURCE_RANGE); Record.push_back(FileLookup[Start.FileID]); Record.push_back(Start.Line); Record.push_back(Start.Col); Record.push_back(Start.Offset); Record.push_back(FileLookup[End.FileID]); Record.push_back(End.Line); Record.push_back(End.Col); Record.push_back(End.Offset); Writer.State->Stream.EmitRecordWithAbbrev( Writer.State->Abbrevs.get(RECORD_SOURCE_RANGE), Record); return std::error_code(); } std::error_code SDiagsMerger::visitDiagnosticRecord( unsigned Severity, const serialized_diags::Location &Location, unsigned Category, unsigned Flag, StringRef Message) { RecordData MergedRecord; MergedRecord.push_back(RECORD_DIAG); MergedRecord.push_back(Severity); MergedRecord.push_back(FileLookup[Location.FileID]); MergedRecord.push_back(Location.Line); MergedRecord.push_back(Location.Col); MergedRecord.push_back(Location.Offset); MergedRecord.push_back(CategoryLookup[Category]); MergedRecord.push_back(Flag ? DiagFlagLookup[Flag] : 0); MergedRecord.push_back(Message.size()); Writer.State->Stream.EmitRecordWithBlob( Writer.State->Abbrevs.get(RECORD_DIAG), MergedRecord, Message); return std::error_code(); } std::error_code SDiagsMerger::visitFixitRecord(const serialized_diags::Location &Start, const serialized_diags::Location &End, StringRef Text) { RecordData Record; Record.push_back(RECORD_FIXIT); Record.push_back(FileLookup[Start.FileID]); Record.push_back(Start.Line); Record.push_back(Start.Col); Record.push_back(Start.Offset); Record.push_back(FileLookup[End.FileID]); Record.push_back(End.Line); Record.push_back(End.Col); Record.push_back(End.Offset); Record.push_back(Text.size()); Writer.State->Stream.EmitRecordWithBlob( Writer.State->Abbrevs.get(RECORD_FIXIT), Record, Text); return std::error_code(); } std::error_code SDiagsMerger::visitFilenameRecord(unsigned ID, unsigned Size, unsigned Timestamp, StringRef Name) { FileLookup[ID] = Writer.getEmitFile(Name.str().c_str()); return std::error_code(); } std::error_code SDiagsMerger::visitCategoryRecord(unsigned ID, StringRef Name) { CategoryLookup[ID] = Writer.getEmitCategory(ID); return std::error_code(); } std::error_code SDiagsMerger::visitDiagFlagRecord(unsigned ID, StringRef Name) { DiagFlagLookup[ID] = Writer.getEmitDiagnosticFlag(Name); return std::error_code(); }
// Copyright (c) 2012-2017, The CryptoNote developers, The Bytecoin developers // Copyright (c) 2018-2019, The Qwertycoin developers // // This file is part of Qwertycoin. // // Qwertycoin is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Qwertycoin 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 Qwertycoin. If not, see <http://www.gnu.org/licenses/>. #include "WalletUtils.h" #include "CryptoNote.h" #include "crypto/crypto.h" #include "Wallet/WalletErrors.h" namespace CryptoNote { void throwIfKeysMissmatch(const Crypto::SecretKey& secretKey, const Crypto::PublicKey& expectedPublicKey, const std::string& message) { Crypto::PublicKey pub; bool r = Crypto::secret_key_to_public_key(secretKey, pub); if (!r || expectedPublicKey != pub) { throw std::system_error(make_error_code(CryptoNote::error::WRONG_PASSWORD), message); } } bool validateAddress(const std::string& address, const CryptoNote::Currency& currency) { CryptoNote::AccountPublicAddress ignore; return currency.parseAccountAddressString(address, ignore); } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletTransactionState state) { switch (state) { case CryptoNote::WalletTransactionState::SUCCEEDED: os << "SUCCEEDED"; break; case CryptoNote::WalletTransactionState::FAILED: os << "FAILED"; break; case CryptoNote::WalletTransactionState::CANCELLED: os << "CANCELLED"; break; case CryptoNote::WalletTransactionState::CREATED: os << "CREATED"; break; case CryptoNote::WalletTransactionState::DELETED: os << "DELETED"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(state) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletTransferType type) { switch (type) { case CryptoNote::WalletTransferType::USUAL: os << "USUAL"; break; case CryptoNote::WalletTransferType::DONATION: os << "DONATION"; break; case CryptoNote::WalletTransferType::CHANGE: os << "CHANGE"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(type) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletGreen::WalletState state) { switch (state) { case CryptoNote::WalletGreen::WalletState::INITIALIZED: os << "INITIALIZED"; break; case CryptoNote::WalletGreen::WalletState::NOT_INITIALIZED: os << "NOT_INITIALIZED"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(state) << ')'; } std::ostream& operator<<(std::ostream& os, CryptoNote::WalletGreen::WalletTrackingMode mode) { switch (mode) { case CryptoNote::WalletGreen::WalletTrackingMode::TRACKING: os << "TRACKING"; break; case CryptoNote::WalletGreen::WalletTrackingMode::NOT_TRACKING: os << "NOT_TRACKING"; break; case CryptoNote::WalletGreen::WalletTrackingMode::NO_ADDRESSES: os << "NO_ADDRESSES"; break; default: os << "<UNKNOWN>"; } return os << " (" << static_cast<int>(mode) << ')'; } TransferListFormatter::TransferListFormatter(const CryptoNote::Currency& currency, const WalletGreen::TransfersRange& range) : m_currency(currency), m_range(range) { } void TransferListFormatter::print(std::ostream& os) const { for (auto it = m_range.first; it != m_range.second; ++it) { os << '\n' << std::setw(21) << m_currency.formatAmount(it->second.amount) << ' ' << (it->second.address.empty() ? "<UNKNOWN>" : it->second.address) << ' ' << it->second.type; } } std::ostream& operator<<(std::ostream& os, const TransferListFormatter& formatter) { formatter.print(os); return os; } WalletOrderListFormatter::WalletOrderListFormatter(const CryptoNote::Currency& currency, const std::vector<CryptoNote::WalletOrder>& walletOrderList) : m_currency(currency), m_walletOrderList(walletOrderList) { } void WalletOrderListFormatter::print(std::ostream& os) const { os << '{'; if (!m_walletOrderList.empty()) { os << '<' << m_currency.formatAmount(m_walletOrderList.front().amount) << ", " << m_walletOrderList.front().address << '>'; for (auto it = std::next(m_walletOrderList.begin()); it != m_walletOrderList.end(); ++it) { os << '<' << m_currency.formatAmount(it->amount) << ", " << it->address << '>'; } } os << '}'; } std::ostream& operator<<(std::ostream& os, const WalletOrderListFormatter& formatter) { formatter.print(os); return os; } }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <lib/statement/if_branch_statement.h> #include <lib/expression/constant_expression.h> using namespace HPHP; using namespace std; using namespace boost; /////////////////////////////////////////////////////////////////////////////// // constructors/destructors IfBranchStatement::IfBranchStatement (STATEMENT_CONSTRUCTOR_PARAMETERS, ExpressionPtr condition, StatementPtr stmt) : Statement(STATEMENT_CONSTRUCTOR_PARAMETER_VALUES), m_condition(condition), m_stmt(stmt) { } StatementPtr IfBranchStatement::clone() { IfBranchStatementPtr stmt(new IfBranchStatement(*this)); stmt->m_condition = Clone(m_condition); stmt->m_stmt = Clone(m_stmt); return stmt; } /////////////////////////////////////////////////////////////////////////////// // parser functions /////////////////////////////////////////////////////////////////////////////// // static analysis functions void IfBranchStatement::analyzeProgram(AnalysisResultPtr ar) { if (m_condition) m_condition->analyzeProgram(ar); if (m_stmt) m_stmt->analyzeProgram(ar); } ConstructPtr IfBranchStatement::getNthKid(int n) const { switch (n) { case 0: return m_condition; case 1: return m_stmt; default: return ConstructPtr(); } ASSERT(0); } int IfBranchStatement::getKidCount() const { return 2; } int IfBranchStatement::setNthKid(int n, ConstructPtr cp) { switch (n) { case 0: m_condition = boost::dynamic_pointer_cast<Expression>(cp); return 1; case 1: m_stmt = boost::dynamic_pointer_cast<Statement>(cp); return 1; default: return 0; } ASSERT(0); } StatementPtr IfBranchStatement::preOptimize(AnalysisResultPtr ar) { ar->preOptimize(m_condition); ar->preOptimize(m_stmt); return StatementPtr(); } StatementPtr IfBranchStatement::postOptimize(AnalysisResultPtr ar) { ar->postOptimize(m_condition); ar->postOptimize(m_stmt); return StatementPtr(); } void IfBranchStatement::inferTypes(AnalysisResultPtr ar) { if (m_condition) m_condition->inferAndCheck(ar, Type::Boolean, false); if (m_stmt) m_stmt->inferTypes(ar); } /////////////////////////////////////////////////////////////////////////////// // code generation functions void IfBranchStatement::outputPHP(CodeGenerator &cg, AnalysisResultPtr ar) { if (m_condition) { cg.printf("if ("); m_condition->outputPHP(cg, ar); cg.printf(") "); } else { cg.printf(" "); } if (m_stmt) { m_stmt->outputPHP(cg, ar); } else { cg.printf("{}\n"); } } void IfBranchStatement::outputCPP(CodeGenerator &cg, AnalysisResultPtr ar) { if (m_condition) { cg.printf("if ("); m_condition->outputCPP(cg, ar); cg.printf(") "); } if (m_stmt) { m_stmt->outputCPP(cg, ar); } else { cg.printf("{}\n"); } }
/* * Copyright (c) 2001 Intel Corporation. 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * gui: Win32 GUI Trutella interface. */ #include "gui.h" CTrutellaApp g_app; IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) //{{AFX_MSG_MAP(CMainFrame) ON_WM_CREATE() //}}AFX_MSG_MAP END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; CMainFrame::CMainFrame() { // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators( indicators, sizeof(indicators) / sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; } return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { return CFrameWnd::PreCreateWindow(cs); } void CMainFrame::SetStatusText(CString s) { m_wndStatusBar.SetPaneText(0, s); } IMPLEMENT_DYNCREATE(CPrefConnectionPage, CPropertyPage) CPrefConnectionPage::CPrefConnectionPage() : CPropertyPage(CPrefConnectionPage::IDD) { //{{AFX_DATA_INIT(CPrefConnectionPage) m_Host = _T(""); //}}AFX_DATA_INIT } CPrefConnectionPage::~CPrefConnectionPage() { } void CPrefConnectionPage::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPrefConnectionPage) DDX_Control(pDX, IDC_HOSTS_LIST, m_ctlHostList); DDX_Text(pDX, IDC_HOST, m_Host); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPrefConnectionPage, CPropertyPage) //{{AFX_MSG_MAP(CPrefConnectionPage) ON_BN_CLICKED(IDC_ADDHOST, OnAddhost) ON_BN_CLICKED(IDC_REMOVEHOST, OnRemovehost) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CPrefConnectionPage::OnInitDialog() { CPropertyPage::OnInitDialog(); DWORD style = m_ctlHostList.GetExtendedStyle() | LVS_EX_FULLROWSELECT; m_ctlHostList.SetExtendedStyle(style); m_ctlHostList.InsertColumn(0, "Host", LVCFMT_LEFT, 167); m_ctlHostList.InsertColumn(1, "Address", LVCFMT_LEFT, 100); m_ctlHostList.InsertColumn(2, "Port", LVCFMT_LEFT, 50); return TRUE; } void CPrefConnectionPage::OnAddhost() { UpdateData(TRUE); if(m_Host == "") return; CWaitCursor c; Trut::Host *host = g_app.trut->AddHost(m_Host); if(!host) { MessageBox("Cannot connect to " + m_Host + "."); return; } AddListItem(host); } void CPrefConnectionPage::OnRemovehost() { POSITION pos = m_ctlHostList.GetFirstSelectedItemPosition(); if(!pos) return; UINT nIndex = m_ctlHostList.GetNextSelectedItem(pos); Trut::Host *host = (Trut::Host *)m_ctlHostList.GetItemData(nIndex); if (!host) return; g_app.trut->RemoveHost(host); m_ctlHostList.DeleteItem(nIndex); } void CPrefConnectionPage::AddListItem(Trut::Host *host) { if(!host) return; CString ip; g_app.FormatIPAddr(host->GetIp(), ip); CString port; port.Format("%d", host->GetPort()); UINT item = m_ctlHostList.InsertItem( LVIF_TEXT | LVIF_PARAM, m_ctlHostList.GetItemCount(), host->GetUrl(), 0, 0, 0, (LPARAM)host); m_ctlHostList.SetItem(item, 1, LVIF_TEXT, ip, 0, 0, 0, 0); m_ctlHostList.SetItem(item, 2, LVIF_TEXT, port, 0, 0, 0, 0); } BOOL CPrefConnectionPage::OnSetActive() { m_ctlHostList.DeleteAllItems(); CTrutellaApp::HostList::iterator i = g_app.hosts.begin(); for (i = g_app.hosts.begin(); i != g_app.hosts.end(); i++) { Trut::Host *host = *i; AddListItem(host); } return CPropertyPage::OnSetActive(); } IMPLEMENT_DYNCREATE(CPrefGroups, CPropertyPage) CPrefGroups::CPrefGroups() : CPropertyPage(CPrefGroups::IDD) { //{{AFX_DATA_INIT(CPrefGroups) m_GroupName = _T(""); //}}AFX_DATA_INIT } CPrefGroups::~CPrefGroups() { } void CPrefGroups::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPrefGroups) DDX_Control(pDX, IDC_GROUPLIST, m_ctlGroupList); DDX_Text(pDX, IDC_GROUPNAME, m_GroupName); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPrefGroups, CPropertyPage) //{{AFX_MSG_MAP(CPrefGroups) ON_BN_CLICKED(IDC_LEAVEGROUP, OnLeavegroup) ON_BN_CLICKED(IDC_JOINGROUP, OnJoingroup) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CPrefGroups::OnInitDialog() { CPropertyPage::OnInitDialog(); DWORD style = m_ctlGroupList.GetExtendedStyle() | LVS_EX_FULLROWSELECT; m_ctlGroupList.SetExtendedStyle(style); m_ctlGroupList.InsertColumn(0, "Name", LVCFMT_LEFT, 317); return TRUE; } struct JoinContext { CPrefGroups *pref; CEvent event; }; void CPrefGroups::OnJoingroup() { UpdateData(TRUE); if(m_GroupName == "") return; CWaitCursor c; JoinContext context; context.pref = this; g_app.trut->JoinGroup(m_GroupName, 2, JoinCallback, AcceptCallback, &context); CSingleLock lock(&context.event); lock.Lock(); } void CPrefGroups::JoinCallback(Trut::Group *group, Trut::JoinStatus status, void *context) { JoinContext *joinctx = (JoinContext*) context; if (!joinctx) return; joinctx->event.SetEvent(); CPrefGroups *pref = joinctx->pref; switch(status) { case Trut::JOIN_CREATED: pref->MessageBox("No active group members could be found, " "so a new group has been created."); g_app.groups.push_back(group); pref->m_ctlGroupList.InsertItem( LVIF_TEXT | LVIF_PARAM, pref->m_ctlGroupList.GetItemCount(), group->GetName(), 0, 0, 0, (LPARAM) group); break; case Trut::JOIN_OK: g_app.groups.push_back(group); pref->m_ctlGroupList.InsertItem( LVIF_TEXT | LVIF_PARAM, pref->m_ctlGroupList.GetItemCount(), group->GetName(), 0, 0, 0, (LPARAM) group); break; default: pref->MessageBox("You were denied access to the group."); break; } } int CPrefGroups::AcceptCallback(Trut::Group *group, const char *id, void *context) { HWND hwnd = g_app.m_pMainWnd ? g_app.m_pMainWnd->m_hWnd:NULL; return (::MessageBox(hwnd, (CString) id + " is trying to join the group " + (CString)group->GetName() + ". Will you allow this person to " "join your group?", "Trutella", MB_YESNO) == IDYES); } void CPrefGroups::OnLeavegroup() { POSITION pos = m_ctlGroupList.GetFirstSelectedItemPosition(); if(!pos) return; UINT item = m_ctlGroupList.GetNextSelectedItem(pos); Trut::Group *group = (Trut::Group*) m_ctlGroupList.GetItemData(item); if (!group) return; m_ctlGroupList.DeleteItem(item); CTrutellaApp::ShareList::iterator i = g_app.shares.begin(); while (i != g_app.shares.end()) { Trut::Shared *shared = *i; i++; if (shared && shared->GetGroup() == group) g_app.shares.remove(shared); } g_app.groups.remove(group); g_app.trut->LeaveGroup(group); } BOOL CPrefGroups::OnSetActive() { m_ctlGroupList.DeleteAllItems(); CTrutellaApp::GroupList::iterator i; for (i = g_app.groups.begin(); i != g_app.groups.end(); i++) { Trut::Group *group = *i; if (group) m_ctlGroupList.InsertItem( LVIF_TEXT | LVIF_PARAM, m_ctlGroupList.GetItemCount(), group->GetName(), 0, 0, 0, (LPARAM)group); } return CPropertyPage::OnSetActive(); } IMPLEMENT_DYNCREATE(CPrefSharing, CPropertyPage) CPrefSharing::CPrefSharing() : CPropertyPage(CPrefSharing::IDD) { //{{AFX_DATA_INIT(CPrefSharing) m_ext = _T(""); m_groupItem = -1; //}}AFX_DATA_INIT m_current = NULL; } CPrefSharing::~CPrefSharing() { } void CPrefSharing::DoDataExchange(CDataExchange* pDX) { CPropertyPage::DoDataExchange(pDX); //{{AFX_DATA_MAP(CPrefSharing) DDX_Control(pDX, IDC_RESCANSHARE, m_ctlRescanBtn); DDX_Control(pDX, IDC_REMOVESHARE, m_ctlRemoveBtn); DDX_Control(pDX, IDC_ADDSHARE, m_ctlAddBtn); DDX_Control(pDX, IDC_SHAREEXT, m_ctlExtensions); DDX_Control(pDX, IDC_SHAREGROUP, m_ctlGroup); DDX_Control(pDX, IDC_SHARELIST, m_ctlShareList); DDX_Text(pDX, IDC_SHAREEXT, m_ext); DDX_CBIndex(pDX, IDC_SHAREGROUP, m_groupItem); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CPrefSharing, CPropertyPage) //{{AFX_MSG_MAP(CPrefSharing) ON_BN_CLICKED(IDC_ADDSHARE, OnAddshare) ON_BN_CLICKED(IDC_REMOVESHARE, OnRemoveshare) ON_WM_DESTROY() ON_NOTIFY(NM_CLICK, IDC_SHARELIST, OnClickSharelist) ON_BN_CLICKED(IDC_RESCANSHARE, OnRescanshare) //}}AFX_MSG_MAP END_MESSAGE_MAP() BOOL CPrefSharing::OnInitDialog() { CPropertyPage::OnInitDialog(); DWORD style = m_ctlShareList.GetExtendedStyle() | LVS_EX_FULLROWSELECT; m_ctlShareList.SetExtendedStyle(style); m_ctlShareList.InsertColumn(0, "Path", LVCFMT_LEFT, 317); return TRUE; } void CPrefSharing::OnClickSharelist(NMHDR* pNMHDR, LRESULT* pResult) { SaveCurrent(); POSITION pos = m_ctlShareList.GetFirstSelectedItemPosition(); if (!pos) return; UINT selected = m_ctlShareList.GetNextSelectedItem(pos); Trut::Shared *shared = (Trut::Shared*) m_ctlShareList.GetItemData(selected); if (!shared) return; m_current = shared; m_ext = shared->GetExt(); m_groupItem = m_ctlGroup.GetCount() - 1; UpdateData(FALSE); if (shared->GetGroup()) m_ctlGroup.SelectString(-1, shared->GetGroup()->GetName()); m_ctlGroup.EnableWindow(); m_ctlExtensions.EnableWindow(); m_ctlAddBtn.EnableWindow(); m_ctlRescanBtn.EnableWindow(); m_ctlRemoveBtn.EnableWindow(); *pResult = 0; } void CPrefSharing::OnAddshare() { SaveCurrent(); char *path = GetPath(); if (!path) return; CString ext; ext.LoadString(IDS_SHAREEXT_DEFAULTS); Trut::Shared *shared = g_app.trut->AddShared(path, ext, NULL); if (!shared) return; g_app.shares.push_back(shared); m_ctlShareList.InsertItem(LVIF_TEXT | LVIF_PARAM | LVIF_STATE, m_ctlShareList.GetItemCount(), shared->GetPath(), LVIS_SELECTED, LVIS_SELECTED, 0, (LPARAM) shared); m_current = shared; m_ext = shared->GetExt(); m_groupItem = m_ctlGroup.GetCount() - 1; UpdateData(FALSE); m_ctlGroup.EnableWindow(); m_ctlExtensions.EnableWindow(); m_ctlRemoveBtn.EnableWindow(); } void CPrefSharing::OnRemoveshare() { SaveCurrent(); POSITION pos = m_ctlShareList.GetFirstSelectedItemPosition(); if (!pos) return; UINT item = m_ctlShareList.GetNextSelectedItem(pos); Trut::Shared *shared = (Trut::Shared*) m_ctlShareList.GetItemData(item); if (!shared) return; m_ctlShareList.DeleteItem(item); g_app.shares.remove(shared); g_app.trut->RemoveShared(shared); if (m_ctlShareList.GetItemCount() <= 0) { m_ctlGroup.EnableWindow(FALSE); m_ctlExtensions.EnableWindow(FALSE); m_ctlRemoveBtn.EnableWindow(FALSE); } } void CPrefSharing::OnDestroy() { g_app.trut->RescanAllShared(); CPropertyPage::OnDestroy(); } void CPrefSharing::OnRescanshare() { SaveCurrent(); g_app.trut->RescanAllShared(); } BOOL CPrefSharing::OnSetActive() { m_ctlShareList.DeleteAllItems(); CTrutellaApp::ShareList::iterator i; for(i = g_app.shares.begin(); i != g_app.shares.end(); i++) { Trut::Shared *shared = *i; if (shared) m_ctlShareList.InsertItem(LVIF_TEXT | LVIF_PARAM, m_ctlShareList.GetItemCount(), shared->GetPath(), 0, 0, 0, (LPARAM) shared); } m_ctlGroup.ResetContent(); m_ctlGroup.AddString("All of GnutellaNet"); m_ctlGroup.SetItemDataPtr(0, NULL); CTrutellaApp::GroupList::iterator j; for(j = g_app.groups.begin(); j != g_app.groups.end(); j++) { Trut::Group *group = *j; int item = m_ctlGroup.AddString(group->GetName()); m_ctlGroup.SetItemDataPtr(item, group); } m_ext = _T(""); m_groupItem = -1; UpdateData(FALSE); m_ctlGroup.EnableWindow(FALSE); m_ctlExtensions.EnableWindow(FALSE); m_ctlRemoveBtn.EnableWindow(FALSE); return CPropertyPage::OnSetActive(); } BOOL CPrefSharing::OnKillActive() { SaveCurrent(); return CPropertyPage::OnKillActive(); } char *CPrefSharing::GetPath() { BROWSEINFO bi; bi.hwndOwner = m_hWnd; bi.pidlRoot = NULL; bi.pszDisplayName = NULL; bi.lpszTitle = _T("Select a Directory to Share"); bi.ulFlags = BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS; bi.lpfn = NULL; bi.lParam = 0; LPITEMIDLIST pidl = ::SHBrowseForFolder(&bi); char path[MAX_PATH]; if (!pidl || !::SHGetPathFromIDList(pidl, path)) return NULL; int size = strlen(path); if(path[size - 1] == '\\') path[size - 1] = '\0'; return strdup(path); } void CPrefSharing::SaveCurrent() { Trut::Shared *shared = m_current; if (!shared) return; m_current = NULL; char ext[128]; ext[0] = '\0'; int len = m_ctlExtensions.GetLine(0, ext, sizeof(ext)); if (len >= 0) ext[len] = '\0'; Trut::Group *group = NULL; UINT item = m_ctlGroup.GetCurSel(); if (item == CB_ERR) return; group = (Trut::Group*) m_ctlGroup.GetItemDataPtr(item); g_app.trut->UpdateShared(shared, ext, group); } IMPLEMENT_DYNAMIC(CPrefSheet, CPropertySheet) CPrefSheet::CPrefSheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { } CPrefSheet::CPrefSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) :CPropertySheet(pszCaption, pParentWnd, iSelectPage) { } CPrefSheet::~CPrefSheet() { } BEGIN_MESSAGE_MAP(CPrefSheet, CPropertySheet) //{{AFX_MSG_MAP(CPrefSheet) //}}AFX_MSG_MAP END_MESSAGE_MAP() BEGIN_MESSAGE_MAP(CTrutellaApp, CWinApp) //{{AFX_MSG_MAP(CTrutellaApp) ON_COMMAND(ID_APP_ABOUT, OnAppAbout) ON_COMMAND(ID_FILE_PREFS, OnFilePrefs) //}}AFX_MSG_MAP // Standard file based document commands ON_COMMAND(ID_FILE_NEW, CWinApp::OnFileNew) ON_COMMAND(ID_FILE_OPEN, CWinApp::OnFileOpen) END_MESSAGE_MAP() CTrutellaApp::CTrutellaApp() { } BOOL CTrutellaApp::InitInstance() { CWaitCursor c; m_InitFailed = FALSE; AfxEnableControlContainer(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. #if 0 #ifdef _AFXDLL Enable3dControls(); // Call this when using MFC in a shared DLL #else // Call this when linking to MFC statically Enable3dControlsStatic(); #endif #endif // Change the registry key under which our settings are stored. SetRegistryKey(_T("Intel")); // Load standard INI file options (including MRU) LoadStdProfileSettings(0); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views. CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CTrutellaDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CTrutellaView)); AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); // Dispatch commands specified on the command line if (!ProcessShellCommand(cmdInfo)) { m_InitFailed = TRUE; return FALSE; } // Create directories CreateDirectory("C:\\Ptl", NULL); CreateDirectory("C:\\Ptl\\Downloads", NULL); SetCurrentDirectory("C:\\Ptl\\Downloads"); // Load certificates store = new PTP::Store(HKEY_CURRENT_USER, "Software\\PTL\\Cert", NULL, NULL); if (store->Load()) { m_InitFailed = TRUE; return FALSE; } // Load identity settings PTP::Identity *local = store->Find(NULL, 1); if (local) m_IdFriendlyName = local->GetName(); trut = new Trut(store); // Start listening on the default port trut->SetOpenCallback(OpenCallback); trut->SetCloseCallback(CloseCallback); trut->AddPort(0); // The one and only window has been initialized, so show and update it. m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); ((CMainFrame *)m_pMainWnd)->GetActiveDocument()->UpdateAllViews(NULL); // Try to re-establish host connections // Load registry settings and restore connections UINT i, n; CString Name, Key; n = GetProfileInt("Hosts", "Count", 0); for(i = 0; i < n; i++) { Key.Format("%d", i); Name = GetProfileString("Hosts", Key, ""); if(Name != "") { SetStatusText("Connecting to " + Name + "..."); Trut::Host *host = trut->AddHost(Name); if(!host) { MessageBox(m_pMainWnd->m_hWnd, "Could not restore connection to " + Name + ".", "Trutella", MB_OK); } } } // Final aesthetics SetStatusText("Ready"); m_pMainWnd->SetFocus(); return TRUE; } int CTrutellaApp::ExitInstance() { if(!m_InitFailed) { WriteProfileInt("Hosts", "Count", hosts.size()); HostList::iterator hostPos; UINT i; for(hostPos = hosts.begin(), i = 0; hostPos != hosts.end(); hostPos++, i++) { CString key; key.Format("%d", i); WriteProfileString("Hosts", key, (*hostPos)->GetUrl()); } } delete trut; delete store; return CWinApp::ExitInstance(); } void CTrutellaApp::OpenCallback(Trut::Host *host, void **context) { if (host->GetDirection() == PTP::Net::Connection::OUTBOUND) g_app.hosts.push_back(host); } void CTrutellaApp::CloseCallback(Trut::Host *host, void *context) { if (host->GetDirection() == PTP::Net::Connection::OUTBOUND) g_app.hosts.remove(host); } ///////////////////////////////////////////////////////////////////////////// // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data //{{AFX_DATA(CAboutDlg) enum { IDD = IDD_ABOUTBOX }; //}}AFX_DATA // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CAboutDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: //{{AFX_MSG(CAboutDlg) // No message handlers //}}AFX_MSG DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { //{{AFX_DATA_INIT(CAboutDlg) //}}AFX_DATA_INIT } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAboutDlg) //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) //{{AFX_MSG_MAP(CAboutDlg) // No message handlers //}}AFX_MSG_MAP END_MESSAGE_MAP() // App command to run the dialog void CTrutellaApp::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } void CTrutellaApp::OnFilePrefs() { // Build and display the preferences dialog CPrefSheet dlg("Trutella Preferences"); CPrefConnectionPage pgConnections; CPrefSharing pgSharing; CPrefGroups pgGroups; dlg.AddPage(&pgConnections); dlg.AddPage(&pgSharing); dlg.AddPage(&pgGroups); if(dlg.DoModal() == IDOK) { // Get data from the dialog objects... } // Update the application window with changes CMainFrame *pMainFrame = (CMainFrame*)GetMainWnd(); pMainFrame->GetActiveDocument()->UpdateAllViews(NULL); } void CTrutellaApp::FormatIPAddr(UINT ip, CString &str) { str.Format("%d.%d.%d.%d", (ip & 0xff000000) >> 24, (ip & 0xff0000) >> 16, (ip & 0xff00) >> 8, ip & 0xff); } void CTrutellaApp::SetStatusText(CString s) { CMainFrame *pMainFrame = (CMainFrame *)AfxGetMainWnd(); if(pMainFrame) pMainFrame->SetStatusText(s); } IMPLEMENT_DYNCREATE(CTrutellaDoc, CDocument) BEGIN_MESSAGE_MAP(CTrutellaDoc, CDocument) //{{AFX_MSG_MAP(CTrutellaDoc) //}}AFX_MSG_MAP END_MESSAGE_MAP() CTrutellaDoc::CTrutellaDoc() { // TODO: add one-time construction code here } CTrutellaDoc::~CTrutellaDoc() { } BOOL CTrutellaDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; SetTitle(g_app.m_IdFriendlyName); return TRUE; } void CTrutellaDoc::Serialize(CArchive& ar) { if (ar.IsStoring()) { // TODO: add storing code here } else { // TODO: add loading code here } } IMPLEMENT_DYNCREATE(CTrutellaView, CFormView) BEGIN_MESSAGE_MAP(CTrutellaView, CFormView) //{{AFX_MSG_MAP(CTrutellaView) ON_BN_CLICKED(IDC_SEARCH, OnSearch) ON_WM_DESTROY() ON_NOTIFY(NM_DBLCLK, IDC_SEARCHRESULTS, OnDblclkSearchresults) ON_BN_CLICKED(IDC_KILLXFER, OnKillxfer) ON_BN_CLICKED(IDC_REMOVEERRORS, OnRemoveerrors) //}}AFX_MSG_MAP END_MESSAGE_MAP() CTrutellaView::CTrutellaView() : CFormView(CTrutellaView::IDD) { //{{AFX_DATA_INIT(CTrutellaView) m_SearchText = _T(""); m_nGroupID = -1; m_nXferMode = -1; //}}AFX_DATA_INIT // TODO: add construction code here } CTrutellaView::~CTrutellaView() { } void CTrutellaView::DoDataExchange(CDataExchange* pDX) { CFormView::DoDataExchange(pDX); //{{AFX_DATA_MAP(CTrutellaView) DDX_Control(pDX, IDC_GROUP, m_ctlGroupCombo); DDX_Control(pDX, IDC_XFERSEL, m_ctlXferMode); DDX_Control(pDX, IDC_XFERS, m_ctlXferList); DDX_Control(pDX, IDC_SEARCHRESULTS, m_ctlSearchResults); DDX_Text(pDX, IDC_SEARCHTEXT, m_SearchText); DDX_CBIndex(pDX, IDC_GROUP, m_nGroupID); DDX_CBIndex(pDX, IDC_XFERSEL, m_nXferMode); //}}AFX_DATA_MAP } BOOL CTrutellaView::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return CFormView::PreCreateWindow(cs); } void CTrutellaView::OnInitialUpdate() { CFormView::OnInitialUpdate(); GetParentFrame()->RecalcLayout(); ResizeParentToFit(); // Set up list view columns DWORD dwStyle; dwStyle = m_ctlSearchResults.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; m_ctlSearchResults.SetExtendedStyle(dwStyle); dwStyle = m_ctlXferList.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; m_ctlXferList.SetExtendedStyle(dwStyle); m_ctlSearchResults.InsertColumn(0, "Path", LVCFMT_LEFT, 250); m_ctlSearchResults.InsertColumn(1, "Size", LVCFMT_LEFT, 100); m_ctlSearchResults.InsertColumn(2, "Group", LVCFMT_LEFT, 150); m_ctlXferList.InsertColumn(0, "Path", LVCFMT_LEFT, 250); m_ctlXferList.InsertColumn(1, "Transferred", LVCFMT_LEFT, 100); m_ctlXferList.InsertColumn(2, "Status", LVCFMT_LEFT, 150); m_ctlXferMode.SetCurSel(0); m_ctlXferMode.EnableWindow(FALSE); } void CTrutellaView::OnSearch() { UpdateData(TRUE); if(m_SearchText == "") return; // Remove current search results CleanSearchResults(); // Get group pointer referenced by current combobox item, // or NULL for the world. UINT nIndex = m_ctlGroupCombo.GetCurSel(); Trut::Group *group = NULL; if(nIndex != CB_ERR) group = (Trut::Group*)m_ctlGroupCombo.GetItemDataPtr(nIndex); g_app.trut->Search(m_SearchText, SearchCallback, &m_ctlSearchResults, group); } void CTrutellaView::SearchCallback(Trut::File *file, void *context) { static CCriticalSection lock; lock.Lock(); CListCtrl *results = (CListCtrl*) context; UINT item = results->GetItemCount(); results->InsertItem(LVIF_TEXT | LVIF_PARAM, item, file->GetName(), 0, 0, 0, (LPARAM) file); CString size; size.Format("%d", file->GetSize()); results->SetItem(item, 1, LVIF_TEXT, size, 0, 0, 0, 0); const char *name = (file->GetGroup() ? file->GetGroup()->GetName():"None (public)"); results->SetItem(item, 2, LVIF_TEXT, name, 0, 0, 0, 0); lock.Unlock(); } void CTrutellaView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint) { GetDocument()->SetTitle(g_app.m_IdFriendlyName); m_ctlGroupCombo.ResetContent(); m_ctlGroupCombo.AddString("All of GnutellaNet"); m_ctlGroupCombo.SetItemDataPtr(0, NULL); CTrutellaApp::GroupList::iterator i; for(i = g_app.groups.begin(); i != g_app.groups.end(); i++) { Trut::Group *group = *i; int item = m_ctlGroupCombo.AddString(group->GetName()); m_ctlGroupCombo.SetItemDataPtr(item, group); } m_ctlGroupCombo.SetCurSel(m_ctlGroupCombo.GetCount() - 1); } void CTrutellaView::CleanSearchResults() { for(int i = 0; i < (int) m_ctlSearchResults.GetItemCount(); i++) { Trut::File *file = (Trut::File*) m_ctlSearchResults.GetItemData(i); delete file; } m_ctlSearchResults.DeleteAllItems(); } void CTrutellaView::OnDestroy() { CFormView::OnDestroy(); CleanSearchResults(); } void CTrutellaView::OnDblclkSearchresults(NMHDR* pNMHDR, LRESULT* pResult) { POSITION pos = m_ctlSearchResults.GetFirstSelectedItemPosition(); if (!pos) return; int selected = m_ctlSearchResults.GetNextSelectedItem(pos); Trut::File *file = (Trut::File *) m_ctlSearchResults.GetItemData(selected); if (!file) return; TransferCallback(file, Trut::GET_OK, NULL, 0, &m_ctlXferList); g_app.trut->Get(file, file->GetName(), TransferCallback, &m_ctlXferList); *pResult = 0; } void CTrutellaView::TransferCallback(Trut::File *file, Trut::GetStatus status, BYTE *data, unsigned long size, void *context) { if(!file || !context) return; static CCriticalSection lock; lock.Lock(); CListCtrl *list = (CListCtrl*)context; LVFINDINFO info; info.flags = LVFI_PARAM; info.lParam = (LPARAM)file; int item = list->FindItem(&info); if(item == -1) { // not found, add a new item item = list->InsertItem( LVIF_TEXT | LVIF_PARAM, list->GetItemCount(), file->GetName(), 0, 0, 0, (LPARAM) file); } // Update subitems CString strSize, strStat; strSize.Format("%d", size); switch(status) { case Trut::GET_OK: strStat = "Transferring"; break; case Trut::GET_DONE: strStat = "Done"; break; default: strStat = "Error"; break; } list->SetItem(item, 1, LVIF_TEXT, strSize, 0, 0, 0, 0); list->SetItem(item, 2, LVIF_TEXT, strStat, 0, 0, 0, 0); // Mark transfer as finished by disassociating it from the Trut::File if(status == Trut::GET_DONE || status == Trut::GET_ERROR) list->SetItemData(item, NULL); lock.Unlock(); } void CTrutellaView::OnKillxfer() { POSITION pos = m_ctlXferList.GetFirstSelectedItemPosition(); if(!pos) { MessageBox("Please select the transfer you'd like to stop."); return; } int selected = m_ctlXferList.GetNextSelectedItem(pos); Trut::File *file = (Trut::File*)m_ctlXferList.GetItemData(selected); if(file) { g_app.trut->GetStop(file); m_ctlXferList.DeleteItem(selected); } else { MessageBox("This transfer has already completed."); } } void CTrutellaView::OnRemoveerrors() { CWaitCursor c; int nItem; for(nItem = m_ctlXferList.GetItemCount() - 1; nItem >= 0; nItem--) { Trut::File *file = (Trut::File*) m_ctlXferList.GetItemData(nItem); if(!file) m_ctlXferList.DeleteItem(nItem); } }
/* * Copyright 2017 MapD Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CodeGenerator.h" #include "DateTimeUtils.h" #include "Execute.h" using namespace DateTimeUtils; namespace { const char* get_extract_function_name(ExtractField field) { switch (field) { case kEPOCH: return "extract_epoch"; case kDATEEPOCH: return "extract_dateepoch"; case kQUARTERDAY: return "extract_quarterday"; case kHOUR: return "extract_hour"; case kMINUTE: return "extract_minute"; case kSECOND: return "extract_second"; case kMILLISECOND: return "extract_millisecond"; case kMICROSECOND: return "extract_microsecond"; case kNANOSECOND: return "extract_nanosecond"; case kDOW: return "extract_dow"; case kISODOW: return "extract_isodow"; case kDAY: return "extract_day"; case kWEEK: return "extract_week"; case kDOY: return "extract_day_of_year"; case kMONTH: return "extract_month"; case kQUARTER: return "extract_quarter"; case kYEAR: return "extract_year"; } UNREACHABLE(); return ""; } } // namespace llvm::Value* CodeGenerator::codegen(const Analyzer::ExtractExpr* extract_expr, const CompilationOptions& co) { AUTOMATIC_IR_METADATA(cgen_state_); auto from_expr = codegen(extract_expr->get_from_expr(), true, co).front(); const int32_t extract_field{extract_expr->get_field()}; const auto& extract_expr_ti = extract_expr->get_from_expr()->get_type_info(); if (extract_field == kEPOCH) { CHECK(extract_expr_ti.get_type() == kTIMESTAMP || extract_expr_ti.get_type() == kDATE); if (from_expr->getType()->isIntegerTy(32)) { from_expr = cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt, from_expr, get_int_type(64, cgen_state_->context_)); return from_expr; } } CHECK(from_expr->getType()->isIntegerTy(64)); if (extract_expr_ti.is_high_precision_timestamp()) { from_expr = codegenExtractHighPrecisionTimestamps( from_expr, extract_expr_ti, extract_expr->get_field()); } if (!extract_expr_ti.is_high_precision_timestamp() && is_subsecond_extract_field(extract_expr->get_field())) { from_expr = extract_expr_ti.get_notnull() ? cgen_state_->ir_builder_.CreateMul( from_expr, cgen_state_->llInt( get_extract_timestamp_precision_scale(extract_expr->get_field()))) : cgen_state_->emitCall( "mul_int64_t_nullable_lhs", {from_expr, cgen_state_->llInt( get_extract_timestamp_precision_scale(extract_expr->get_field())), cgen_state_->inlineIntNull(extract_expr_ti)}); } const auto extract_fname = get_extract_function_name(extract_expr->get_field()); if (!extract_expr_ti.get_notnull()) { llvm::BasicBlock* extract_nullcheck_bb{nullptr}; llvm::PHINode* extract_nullcheck_value{nullptr}; { GroupByAndAggregate::DiamondCodegen null_check( cgen_state_->ir_builder_.CreateICmp( llvm::ICmpInst::ICMP_EQ, from_expr, cgen_state_->inlineIntNull(extract_expr_ti)), executor(), false, "extract_nullcheck", nullptr, false); // generate a phi node depending on whether we got a null or not extract_nullcheck_bb = llvm::BasicBlock::Create( cgen_state_->context_, "extract_nullcheck_bb", cgen_state_->row_func_); // update the blocks created by diamond codegen to point to the newly created phi // block cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_true_); cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb); cgen_state_->ir_builder_.SetInsertPoint(null_check.cond_false_); auto extract_call = cgen_state_->emitExternalCall(extract_fname, get_int_type(64, cgen_state_->context_), std::vector<llvm::Value*>{from_expr}); cgen_state_->ir_builder_.CreateBr(extract_nullcheck_bb); cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb); extract_nullcheck_value = cgen_state_->ir_builder_.CreatePHI( get_int_type(64, cgen_state_->context_), 2, "extract_value"); extract_nullcheck_value->addIncoming(extract_call, null_check.cond_false_); extract_nullcheck_value->addIncoming(cgen_state_->inlineIntNull(extract_expr_ti), null_check.cond_true_); } // diamond codegen will set the insert point in its destructor. override it to // continue using the extract nullcheck bb CHECK(extract_nullcheck_bb); cgen_state_->ir_builder_.SetInsertPoint(extract_nullcheck_bb); CHECK(extract_nullcheck_value); return extract_nullcheck_value; } else { return cgen_state_->emitExternalCall(extract_fname, get_int_type(64, cgen_state_->context_), std::vector<llvm::Value*>{from_expr}); } } llvm::Value* CodeGenerator::codegen(const Analyzer::DateaddExpr* dateadd_expr, const CompilationOptions& co) { AUTOMATIC_IR_METADATA(cgen_state_); const auto& dateadd_expr_ti = dateadd_expr->get_type_info(); CHECK(dateadd_expr_ti.get_type() == kTIMESTAMP || dateadd_expr_ti.get_type() == kDATE); auto datetime = codegen(dateadd_expr->get_datetime_expr(), true, co).front(); CHECK(datetime->getType()->isIntegerTy(64)); auto number = codegen(dateadd_expr->get_number_expr(), true, co).front(); const auto& datetime_ti = dateadd_expr->get_datetime_expr()->get_type_info(); std::vector<llvm::Value*> dateadd_args{ cgen_state_->llInt(static_cast<int32_t>(dateadd_expr->get_field())), number, datetime}; std::string dateadd_fname{"DateAdd"}; if (is_subsecond_dateadd_field(dateadd_expr->get_field()) || dateadd_expr_ti.is_high_precision_timestamp()) { dateadd_fname += "HighPrecision"; dateadd_args.push_back( cgen_state_->llInt(static_cast<int32_t>(datetime_ti.get_dimension()))); } if (!datetime_ti.get_notnull()) { dateadd_args.push_back(cgen_state_->inlineIntNull(datetime_ti)); dateadd_fname += "Nullable"; } return cgen_state_->emitExternalCall(dateadd_fname, get_int_type(64, cgen_state_->context_), dateadd_args, {llvm::Attribute::NoUnwind, llvm::Attribute::ReadNone, llvm::Attribute::Speculatable}); } llvm::Value* CodeGenerator::codegen(const Analyzer::DatediffExpr* datediff_expr, const CompilationOptions& co) { AUTOMATIC_IR_METADATA(cgen_state_); auto start = codegen(datediff_expr->get_start_expr(), true, co).front(); CHECK(start->getType()->isIntegerTy(64)); auto end = codegen(datediff_expr->get_end_expr(), true, co).front(); CHECK(end->getType()->isIntegerTy(32) || end->getType()->isIntegerTy(64)); const auto& start_ti = datediff_expr->get_start_expr()->get_type_info(); const auto& end_ti = datediff_expr->get_end_expr()->get_type_info(); std::vector<llvm::Value*> datediff_args{ cgen_state_->llInt(static_cast<int32_t>(datediff_expr->get_field())), start, end}; std::string datediff_fname{"DateDiff"}; if (start_ti.is_high_precision_timestamp() || end_ti.is_high_precision_timestamp()) { datediff_fname += "HighPrecision"; datediff_args.push_back( cgen_state_->llInt(static_cast<int32_t>(start_ti.get_dimension()))); datediff_args.push_back( cgen_state_->llInt(static_cast<int32_t>(end_ti.get_dimension()))); } const auto& ret_ti = datediff_expr->get_type_info(); if (!start_ti.get_notnull() || !end_ti.get_notnull()) { datediff_args.push_back(cgen_state_->inlineIntNull(ret_ti)); datediff_fname += "Nullable"; } return cgen_state_->emitExternalCall( datediff_fname, get_int_type(64, cgen_state_->context_), datediff_args); } llvm::Value* CodeGenerator::codegen(const Analyzer::DatetruncExpr* datetrunc_expr, const CompilationOptions& co) { AUTOMATIC_IR_METADATA(cgen_state_); auto from_expr = codegen(datetrunc_expr->get_from_expr(), true, co).front(); const auto& datetrunc_expr_ti = datetrunc_expr->get_from_expr()->get_type_info(); CHECK(from_expr->getType()->isIntegerTy(64)); DatetruncField const field = datetrunc_expr->get_field(); if (datetrunc_expr_ti.is_high_precision_timestamp()) { return codegenDateTruncHighPrecisionTimestamps(from_expr, datetrunc_expr_ti, field); } static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive."); static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive."); static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive."); if (dtSECOND <= field && field <= dtNANOSECOND) { return cgen_state_->ir_builder_.CreateCast(llvm::Instruction::CastOps::SExt, from_expr, get_int_type(64, cgen_state_->context_)); } std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen; const bool is_nullable = !datetrunc_expr_ti.get_notnull(); if (is_nullable) { nullcheck_codegen = std::make_unique<NullCheckCodegen>( cgen_state_, executor(), from_expr, datetrunc_expr_ti, "date_trunc_nullcheck"); } char const* const fname = datetrunc_fname_lookup.at(field); auto ret = cgen_state_->emitExternalCall( fname, get_int_type(64, cgen_state_->context_), {{from_expr}}); if (is_nullable) { ret = nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ret); } return ret; } llvm::Value* CodeGenerator::codegenExtractHighPrecisionTimestamps( llvm::Value* ts_lv, const SQLTypeInfo& ti, const ExtractField& field) { AUTOMATIC_IR_METADATA(cgen_state_); CHECK(ti.is_high_precision_timestamp()); CHECK(ts_lv->getType()->isIntegerTy(64)); if (is_subsecond_extract_field(field)) { const auto result = get_extract_high_precision_adjusted_scale(field, ti.get_dimension()); if (result.first == kMULTIPLY) { return ti.get_notnull() ? cgen_state_->ir_builder_.CreateMul( ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second))) : cgen_state_->emitCall( "mul_int64_t_nullable_lhs", {ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)), cgen_state_->inlineIntNull(ti)}); } else if (result.first == kDIVIDE) { return ti.get_notnull() ? cgen_state_->ir_builder_.CreateSDiv( ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second))) : cgen_state_->emitCall( "floor_div_nullable_lhs", {ts_lv, cgen_state_->llInt(static_cast<int64_t>(result.second)), cgen_state_->inlineIntNull(ti)}); } else { return ts_lv; } } return ti.get_notnull() ? cgen_state_->ir_builder_.CreateSDiv( ts_lv, cgen_state_->llInt(static_cast<int64_t>( get_timestamp_precision_scale(ti.get_dimension())))) : cgen_state_->emitCall( "floor_div_nullable_lhs", {ts_lv, cgen_state_->llInt(get_timestamp_precision_scale(ti.get_dimension())), cgen_state_->inlineIntNull(ti)}); } llvm::Value* CodeGenerator::codegenDateTruncHighPrecisionTimestamps( llvm::Value* ts_lv, const SQLTypeInfo& ti, const DatetruncField& field) { // Only needed for i in { 0, 3, 6, 9 }. constexpr int64_t pow10[10]{1, 0, 0, 1000, 0, 0, 1000000, 0, 0, 1000000000}; AUTOMATIC_IR_METADATA(cgen_state_); CHECK(ti.is_high_precision_timestamp()); CHECK(ts_lv->getType()->isIntegerTy(64)); bool const is_nullable = !ti.get_notnull(); static_assert(dtSECOND + 1 == dtMILLISECOND, "Please keep these consecutive."); static_assert(dtMILLISECOND + 1 == dtMICROSECOND, "Please keep these consecutive."); static_assert(dtMICROSECOND + 1 == dtNANOSECOND, "Please keep these consecutive."); if (dtSECOND <= field && field <= dtNANOSECOND) { unsigned const start_dim = ti.get_dimension(); // 0, 3, 6, 9 unsigned const trunc_dim = (field - dtSECOND) * 3; // 0, 3, 6, 9 if (start_dim <= trunc_dim) { return ts_lv; // Truncating to an equal or higher precision has no effect. } int64_t const dscale = pow10[start_dim - trunc_dim]; // 1e3, 1e6, 1e9 if (is_nullable) { ts_lv = cgen_state_->emitCall( "floor_div_nullable_lhs", {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)}); return cgen_state_->emitCall( "mul_int64_t_nullable_lhs", {ts_lv, cgen_state_->llInt(dscale), cgen_state_->inlineIntNull(ti)}); } else { ts_lv = cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(dscale)); return cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(dscale)); } } int64_t const scale = pow10[ti.get_dimension()]; ts_lv = is_nullable ? cgen_state_->emitCall( "floor_div_nullable_lhs", {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)}) : cgen_state_->ir_builder_.CreateSDiv(ts_lv, cgen_state_->llInt(scale)); std::unique_ptr<CodeGenerator::NullCheckCodegen> nullcheck_codegen; if (is_nullable) { nullcheck_codegen = std::make_unique<NullCheckCodegen>( cgen_state_, executor(), ts_lv, ti, "date_trunc_hp_nullcheck"); } char const* const fname = datetrunc_fname_lookup.at(field); ts_lv = cgen_state_->emitExternalCall( fname, get_int_type(64, cgen_state_->context_), {{ts_lv}}); if (is_nullable) { ts_lv = nullcheck_codegen->finalize(ll_int(NULL_BIGINT, cgen_state_->context_), ts_lv); } return is_nullable ? cgen_state_->emitCall( "mul_int64_t_nullable_lhs", {ts_lv, cgen_state_->llInt(scale), cgen_state_->inlineIntNull(ti)}) : cgen_state_->ir_builder_.CreateMul(ts_lv, cgen_state_->llInt(scale)); }
/* Hello World Example This example code is in the Public Domain (or CC0 licensed, at your option.) Unless required by applicable law or agreed to in writing, this software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "esp_system.h" #include "esp_spi_flash.h" #include "BNO055ESP32.h" extern "C" { void app_main(void); } static const int I2CPortNumber = 0; static const int SDAPin = 26; static const int SCLPin = 27; BNO055* bno055 = NULL; void app_main() { printf("Hello BNO055\n"); static i2c_config_t Config; memset( &Config, 0, sizeof( i2c_config_t ) ); Config.mode = I2C_MODE_MASTER; Config.sda_io_num = (gpio_num_t)SDAPin; Config.sda_pullup_en = GPIO_PULLUP_ENABLE; Config.scl_io_num = (gpio_num_t)SCLPin; Config.scl_pullup_en = GPIO_PULLUP_ENABLE; Config.master.clk_speed = 500000; i2c_param_config( (i2c_port_t)I2CPortNumber, &Config ); i2c_driver_install( (i2c_port_t)I2CPortNumber, Config.mode, 0, 0, 0 ); i2c_set_timeout((i2c_port_t)I2CPortNumber, (I2C_APB_CLK_FREQ / Config.master.clk_speed)*1024); vTaskDelay(750 / portTICK_PERIOD_MS); /* * init BNO055 ... */ bno055 = new BNO055((i2c_port_t)I2CPortNumber,0x28); bno055->begin(); // BNO055 is in CONFIG_MODE until it is changed bno055->enableExternalCrystal(); //bno.setSensorOffsets(storedOffsets); //bno055->setAxisRemap(BNO055_REMAP_CONFIG_P5, BNO055_REMAP_SIGN_P0); // see datasheet, section 3.4 /* you can specify a PoWeRMode using: - setPwrModeNormal(); (Default on startup) - setPwrModeLowPower(); - setPwrModeSuspend(); (while suspended bno055 must remain in CONFIG_MODE) */ bno055->setOprModeNdof(); while(1) { int8_t t = bno055->getTemp(); bno055_vector_t v = bno055->getVectorEuler(); bno055_calibration_t c = bno055->getCalibration(); printf("Temp: %d°C Calib: %d %d %d %d Euler: %f %f %f\n", t, c.sys,c.gyro,c.mag,c.accel, v.x,v.y,v.z); vTaskDelay(500 / portTICK_PERIOD_MS); } }
// Copyright (c) 2018, The X-CASH Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <lmdb.h> #include <boost/algorithm/string.hpp> #include <boost/range/adaptor/transformed.hpp> #include <boost/filesystem.hpp> #include "misc_log_ex.h" #include "misc_language.h" #include "wallet_errors.h" #include "ringdb.h" #undef XCASH_DEFAULT_LOG_CATEGORY #define XCASH_DEFAULT_LOG_CATEGORY "wallet.ringdb" static const char zerokey[8] = {0}; static const MDB_val zerokeyval = { sizeof(zerokey), (void *)zerokey }; static int compare_hash32(const MDB_val *a, const MDB_val *b) { uint32_t *va = (uint32_t*) a->mv_data; uint32_t *vb = (uint32_t*) b->mv_data; for (int n = 7; n >= 0; n--) { if (va[n] == vb[n]) continue; return va[n] < vb[n] ? -1 : 1; } return 0; } static int compare_uint64(const MDB_val *a, const MDB_val *b) { const uint64_t va = *(const uint64_t*) a->mv_data; const uint64_t vb = *(const uint64_t*) b->mv_data; return va < vb ? -1 : va > vb; } static std::string compress_ring(const std::vector<uint64_t> &ring) { std::string s; for (uint64_t out: ring) s += tools::get_varint_data(out); return s; } static std::vector<uint64_t> decompress_ring(const std::string &s) { std::vector<uint64_t> ring; int read = 0; for (std::string::const_iterator i = s.begin(); i != s.cend(); std::advance(i, read)) { uint64_t out; std::string tmp(i, s.cend()); read = tools::read_varint(tmp.begin(), tmp.end(), out); THROW_WALLET_EXCEPTION_IF(read <= 0 || read > 256, tools::error::wallet_internal_error, "Internal error decompressing ring"); ring.push_back(out); } return ring; } std::string get_rings_filename(boost::filesystem::path filename) { if (!boost::filesystem::is_directory(filename)) filename.remove_filename(); return filename.string(); } static crypto::chacha_iv make_iv(const crypto::key_image &key_image, const crypto::chacha_key &key) { static const char salt[] = "ringdsb"; uint8_t buffer[sizeof(key_image) + sizeof(key) + sizeof(salt)]; memcpy(buffer, &key_image, sizeof(key_image)); memcpy(buffer + sizeof(key_image), &key, sizeof(key)); memcpy(buffer + sizeof(key_image) + sizeof(key), salt, sizeof(salt)); crypto::hash hash; crypto::cn_fast_hash(buffer, sizeof(buffer), hash.data); static_assert(sizeof(hash) >= CHACHA_IV_SIZE, "Incompatible hash and chacha IV sizes"); crypto::chacha_iv iv; memcpy(&iv, &hash, CHACHA_IV_SIZE); return iv; } static std::string encrypt(const std::string &plaintext, const crypto::key_image &key_image, const crypto::chacha_key &key) { const crypto::chacha_iv iv = make_iv(key_image, key); std::string ciphertext; ciphertext.resize(plaintext.size() + sizeof(iv)); crypto::chacha20(plaintext.data(), plaintext.size(), key, iv, &ciphertext[sizeof(iv)]); memcpy(&ciphertext[0], &iv, sizeof(iv)); return ciphertext; } static std::string encrypt(const crypto::key_image &key_image, const crypto::chacha_key &key) { return encrypt(std::string((const char*)&key_image, sizeof(key_image)), key_image, key); } static std::string decrypt(const std::string &ciphertext, const crypto::key_image &key_image, const crypto::chacha_key &key) { const crypto::chacha_iv iv = make_iv(key_image, key); std::string plaintext; THROW_WALLET_EXCEPTION_IF(ciphertext.size() < sizeof(iv), tools::error::wallet_internal_error, "Bad ciphertext text"); plaintext.resize(ciphertext.size() - sizeof(iv)); crypto::chacha20(ciphertext.data() + sizeof(iv), ciphertext.size() - sizeof(iv), key, iv, &plaintext[0]); return plaintext; } static void store_relative_ring(MDB_txn *txn, MDB_dbi &dbi, const crypto::key_image &key_image, const std::vector<uint64_t> &relative_ring, const crypto::chacha_key &chacha_key) { MDB_val key, data; std::string key_ciphertext = encrypt(key_image, chacha_key); key.mv_data = (void*)key_ciphertext.data(); key.mv_size = key_ciphertext.size(); std::string compressed_ring = compress_ring(relative_ring); std::string data_ciphertext = encrypt(compressed_ring, key_image, chacha_key); data.mv_size = data_ciphertext.size(); data.mv_data = (void*)data_ciphertext.c_str(); int dbr = mdb_put(txn, dbi, &key, &data, 0); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set ring for key image in LMDB table: " + std::string(mdb_strerror(dbr))); } static int resize_env(MDB_env *env, const char *db_path, size_t needed) { MDB_envinfo mei; MDB_stat mst; int ret; needed = std::max(needed, (size_t)(100ul * 1024 * 1024)); // at least 100 MB ret = mdb_env_info(env, &mei); if (ret) return ret; ret = mdb_env_stat(env, &mst); if (ret) return ret; uint64_t size_used = mst.ms_psize * mei.me_last_pgno; uint64_t mapsize = mei.me_mapsize; if (size_used + needed > mei.me_mapsize) { try { boost::filesystem::path path(db_path); boost::filesystem::space_info si = boost::filesystem::space(path); if(si.available < needed) { MERROR("!! WARNING: Insufficient free space to extend database !!: " << (si.available >> 20L) << " MB available"); return ENOSPC; } } catch(...) { // print something but proceed. MWARNING("Unable to query free disk space."); } mapsize += needed; } return mdb_env_set_mapsize(env, mapsize); } static size_t get_ring_data_size(size_t n_entries) { return n_entries * (32 + 1024); // highball 1kB for the ring data to make sure } enum { BLACKBALL_BLACKBALL, BLACKBALL_UNBLACKBALL, BLACKBALL_QUERY, BLACKBALL_CLEAR}; namespace tools { ringdb::ringdb(std::string filename, const std::string &genesis): filename(filename), env(NULL) { MDB_txn *txn; bool tx_active = false; int dbr; tools::create_directories_if_necessary(filename); dbr = mdb_env_create(&env); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LDMB environment: " + std::string(mdb_strerror(dbr))); dbr = mdb_env_set_maxdbs(env, 2); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set max env dbs: " + std::string(mdb_strerror(dbr))); const std::string actual_filename = get_rings_filename(filename); dbr = mdb_env_open(env, actual_filename.c_str(), 0, 0664); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to open rings database file '" + actual_filename + "': " + std::string(mdb_strerror(dbr))); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; dbr = mdb_dbi_open(txn, ("rings-" + genesis).c_str(), MDB_CREATE, &dbi_rings); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr))); mdb_set_compare(txn, dbi_rings, compare_hash32); dbr = mdb_dbi_open(txn, ("blackballs2-" + genesis).c_str(), MDB_CREATE | MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, &dbi_blackballs); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to open LMDB dbi: " + std::string(mdb_strerror(dbr))); mdb_set_dupsort(txn, dbi_blackballs, compare_uint64); dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn creating/opening database: " + std::string(mdb_strerror(dbr))); tx_active = false; } ringdb::~ringdb() { close(); } void ringdb::close() { if (env) { mdb_dbi_close(env, dbi_rings); mdb_dbi_close(env, dbi_blackballs); mdb_env_close(env); env = NULL; } } bool ringdb::add_rings(const crypto::chacha_key &chacha_key, const cryptonote::transaction_prefix &tx) { MDB_txn *txn; int dbr; bool tx_active = false; dbr = resize_env(env, filename.c_str(), get_ring_data_size(tx.vin.size())); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set env map size"); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; for (const auto &in: tx.vin) { if (in.type() != typeid(cryptonote::txin_to_key)) continue; const auto &txin = boost::get<cryptonote::txin_to_key>(in); const uint32_t ring_size = txin.key_offsets.size(); if (ring_size == 1) continue; store_relative_ring(txn, dbi_rings, txin.k_image, txin.key_offsets, chacha_key); } dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn adding ring to database: " + std::string(mdb_strerror(dbr))); tx_active = false; return true; } bool ringdb::remove_rings(const crypto::chacha_key &chacha_key, const cryptonote::transaction_prefix &tx) { MDB_txn *txn; int dbr; bool tx_active = false; dbr = resize_env(env, filename.c_str(), 0); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set env map size"); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; for (const auto &in: tx.vin) { if (in.type() != typeid(cryptonote::txin_to_key)) continue; const auto &txin = boost::get<cryptonote::txin_to_key>(in); const uint32_t ring_size = txin.key_offsets.size(); if (ring_size == 1) continue; MDB_val key, data; std::string key_ciphertext = encrypt(txin.k_image, chacha_key); key.mv_data = (void*)key_ciphertext.data(); key.mv_size = key_ciphertext.size(); dbr = mdb_get(txn, dbi_rings, &key, &data); THROW_WALLET_EXCEPTION_IF(dbr && dbr != MDB_NOTFOUND, tools::error::wallet_internal_error, "Failed to look for key image in LMDB table: " + std::string(mdb_strerror(dbr))); if (dbr == MDB_NOTFOUND) continue; THROW_WALLET_EXCEPTION_IF(data.mv_size <= 0, tools::error::wallet_internal_error, "Invalid ring data size"); MDEBUG("Removing ring data for key image " << txin.k_image); dbr = mdb_del(txn, dbi_rings, &key, NULL); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to remove ring to database: " + std::string(mdb_strerror(dbr))); } dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn removing ring to database: " + std::string(mdb_strerror(dbr))); tx_active = false; return true; } bool ringdb::get_ring(const crypto::chacha_key &chacha_key, const crypto::key_image &key_image, std::vector<uint64_t> &outs) { MDB_txn *txn; int dbr; bool tx_active = false; dbr = resize_env(env, filename.c_str(), 0); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set env map size: " + std::string(mdb_strerror(dbr))); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; MDB_val key, data; std::string key_ciphertext = encrypt(key_image, chacha_key); key.mv_data = (void*)key_ciphertext.data(); key.mv_size = key_ciphertext.size(); dbr = mdb_get(txn, dbi_rings, &key, &data); THROW_WALLET_EXCEPTION_IF(dbr && dbr != MDB_NOTFOUND, tools::error::wallet_internal_error, "Failed to look for key image in LMDB table: " + std::string(mdb_strerror(dbr))); if (dbr == MDB_NOTFOUND) return false; THROW_WALLET_EXCEPTION_IF(data.mv_size <= 0, tools::error::wallet_internal_error, "Invalid ring data size"); std::string data_plaintext = decrypt(std::string((const char*)data.mv_data, data.mv_size), key_image, chacha_key); outs = decompress_ring(data_plaintext); MDEBUG("Found ring for key image " << key_image << ":"); MDEBUG("Relative: " << boost::join(outs | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " ")); outs = cryptonote::relative_output_offsets_to_absolute(outs); MDEBUG("Absolute: " << boost::join(outs | boost::adaptors::transformed([](uint64_t out){return std::to_string(out);}), " ")); dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn getting ring from database: " + std::string(mdb_strerror(dbr))); tx_active = false; return true; } bool ringdb::set_ring(const crypto::chacha_key &chacha_key, const crypto::key_image &key_image, const std::vector<uint64_t> &outs, bool relative) { MDB_txn *txn; int dbr; bool tx_active = false; dbr = resize_env(env, filename.c_str(), outs.size() * 64); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set env map size: " + std::string(mdb_strerror(dbr))); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; store_relative_ring(txn, dbi_rings, key_image, relative ? outs : cryptonote::absolute_output_offsets_to_relative(outs), chacha_key); dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn setting ring to database: " + std::string(mdb_strerror(dbr))); tx_active = false; return true; } bool ringdb::blackball_worker(const std::vector<std::pair<uint64_t, uint64_t>> &outputs, int op) { MDB_txn *txn; MDB_cursor *cursor; int dbr; bool tx_active = false; bool ret = true; THROW_WALLET_EXCEPTION_IF(outputs.size() > 1 && op == BLACKBALL_QUERY, tools::error::wallet_internal_error, "Blackball query only makes sense for a single output"); dbr = resize_env(env, filename.c_str(), 32 * 2 * outputs.size()); // a pubkey, and some slack THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to set env map size: " + std::string(mdb_strerror(dbr))); dbr = mdb_txn_begin(env, NULL, 0, &txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create LMDB transaction: " + std::string(mdb_strerror(dbr))); epee::misc_utils::auto_scope_leave_caller txn_dtor = epee::misc_utils::create_scope_leave_handler([&](){if (tx_active) mdb_txn_abort(txn);}); tx_active = true; dbr = mdb_cursor_open(txn, dbi_blackballs, &cursor); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to create cursor for blackballs table: " + std::string(mdb_strerror(dbr))); MDB_val key, data; for (const std::pair<uint64_t, uint64_t> &output: outputs) { key.mv_data = (void*)&output.first; key.mv_size = sizeof(output.first); data.mv_data = (void*)&output.second; data.mv_size = sizeof(output.second); switch (op) { case BLACKBALL_BLACKBALL: MDEBUG("Marking output " << output.first << "/" << output.second << " as spent"); dbr = mdb_cursor_put(cursor, &key, &data, MDB_APPENDDUP); if (dbr == MDB_KEYEXIST) dbr = 0; break; case BLACKBALL_UNBLACKBALL: MDEBUG("Marking output " << output.first << "/" << output.second << " as unspent"); dbr = mdb_cursor_get(cursor, &key, &data, MDB_GET_BOTH); if (dbr == 0) dbr = mdb_cursor_del(cursor, 0); break; case BLACKBALL_QUERY: dbr = mdb_cursor_get(cursor, &key, &data, MDB_GET_BOTH); THROW_WALLET_EXCEPTION_IF(dbr && dbr != MDB_NOTFOUND, tools::error::wallet_internal_error, "Failed to lookup in blackballs table: " + std::string(mdb_strerror(dbr))); ret = dbr != MDB_NOTFOUND; if (dbr == MDB_NOTFOUND) dbr = 0; break; case BLACKBALL_CLEAR: break; default: THROW_WALLET_EXCEPTION(tools::error::wallet_internal_error, "Invalid blackball op"); } THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to query blackballs table: " + std::string(mdb_strerror(dbr))); } mdb_cursor_close(cursor); if (op == BLACKBALL_CLEAR) { dbr = mdb_drop(txn, dbi_blackballs, 0); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to clear blackballs table: " + std::string(mdb_strerror(dbr))); } dbr = mdb_txn_commit(txn); THROW_WALLET_EXCEPTION_IF(dbr, tools::error::wallet_internal_error, "Failed to commit txn blackballing output to database: " + std::string(mdb_strerror(dbr))); tx_active = false; return ret; } bool ringdb::blackball(const std::vector<std::pair<uint64_t, uint64_t>> &outputs) { return blackball_worker(outputs, BLACKBALL_BLACKBALL); } bool ringdb::blackball(const std::pair<uint64_t, uint64_t> &output) { std::vector<std::pair<uint64_t, uint64_t>> outputs(1, output); return blackball_worker(outputs, BLACKBALL_BLACKBALL); } bool ringdb::unblackball(const std::pair<uint64_t, uint64_t> &output) { std::vector<std::pair<uint64_t, uint64_t>> outputs(1, output); return blackball_worker(outputs, BLACKBALL_UNBLACKBALL); } bool ringdb::blackballed(const std::pair<uint64_t, uint64_t> &output) { std::vector<std::pair<uint64_t, uint64_t>> outputs(1, output); return blackball_worker(outputs, BLACKBALL_QUERY); } bool ringdb::clear_blackballs() { return blackball_worker(std::vector<std::pair<uint64_t, uint64_t>>(), BLACKBALL_CLEAR); } }
// Copyright (c) 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/component_updater/sw_reporter_installer_win.h" #include <string> #include <vector> #include "base/base_paths.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/metrics/histogram.h" #include "base/metrics/sparse_histogram.h" #include "base/path_service.h" #include "base/prefs/pref_registry_simple.h" #include "base/prefs/pref_service.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/task_runner_util.h" #include "base/threading/worker_pool.h" #include "base/win/registry.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/component_updater/component_updater_service.h" #include "chrome/browser/component_updater/component_updater_utils.h" #include "chrome/browser/component_updater/default_component_installer.h" #include "components/component_updater/component_updater_paths.h" #include "components/component_updater/pref_names.h" #include "content/public/browser/browser_thread.h" using content::BrowserThread; namespace component_updater { namespace { // These values are used to send UMA information and are replicated in the // histograms.xml file, so the order MUST NOT CHANGE. enum SwReporterUmaValue { SW_REPORTER_EXPLICIT_REQUEST = 0, SW_REPORTER_STARTUP_RETRY = 1, SW_REPORTER_RETRIED_TOO_MANY_TIMES = 2, SW_REPORTER_START_EXECUTION = 3, SW_REPORTER_FAILED_TO_START = 4, SW_REPORTER_REGISTRY_EXIT_CODE = 5, SW_REPORTER_RESET_RETRIES = 6, SW_REPORTER_MAX, }; // The maximum number of times to retry a download on startup. const int kMaxRetry = 20; // CRX hash. The extension id is: gkmgaooipdjhmangpemjhigmamcehddo. The hash was // generated in Python with something like this: // hashlib.sha256().update(open("<file>.crx").read()[16:16+294]).digest(). const uint8 kSha256Hash[] = {0x6a, 0xc6, 0x0e, 0xe8, 0xf3, 0x97, 0xc0, 0xd6, 0xf4, 0xc9, 0x78, 0x6c, 0x0c, 0x24, 0x73, 0x3e, 0x05, 0xa5, 0x62, 0x4b, 0x2e, 0xc7, 0xb7, 0x1c, 0x5f, 0xea, 0xf0, 0x88, 0xf6, 0x97, 0x9b, 0xc7}; const base::FilePath::CharType kSwReporterExeName[] = FILE_PATH_LITERAL("software_reporter_tool.exe"); // Where to fetch the reporter exit code in the registry. const wchar_t kSoftwareRemovalToolRegistryKey[] = L"Software\\Google\\Software Removal Tool"; const wchar_t kExitCodeRegistryValueName[] = L"ExitCode"; void ReportUmaStep(SwReporterUmaValue value) { UMA_HISTOGRAM_ENUMERATION("SoftwareReporter.Step", value, SW_REPORTER_MAX); } // This function is called on the UI thread to report the SwReporter exit code // and then clear it from the registry as well as clear the execution state // from the local state. This could be called from an interruptible worker // thread so should be resilient to unexpected shutdown. void ReportAndClearExitCode(int exit_code) { UMA_HISTOGRAM_SPARSE_SLOWLY("SoftwareReporter.ExitCode", exit_code); base::win::RegKey srt_key( HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_WRITE); srt_key.DeleteValue(kExitCodeRegistryValueName); // Now that we are done we can reset the try count. g_browser_process->local_state()->SetInteger( prefs::kSwReporterExecuteTryCount, 0); } // This function is called from a worker thread to launch the SwReporter and // wait for termination to collect its exit code. This task could be interrupted // by a shutdown at anytime, so it shouldn't depend on anything external that // could be shutdown beforehand. void LaunchAndWaitForExit(const base::FilePath& exe_path) { const base::CommandLine reporter_command_line(exe_path); base::ProcessHandle scan_reporter_process = base::kNullProcessHandle; if (!base::LaunchProcess(reporter_command_line, base::LaunchOptions(), &scan_reporter_process)) { ReportUmaStep(SW_REPORTER_FAILED_TO_START); return; } ReportUmaStep(SW_REPORTER_START_EXECUTION); int exit_code = -1; bool success = base::WaitForExitCode(scan_reporter_process, &exit_code); DCHECK(success); base::CloseProcessHandle(scan_reporter_process); scan_reporter_process = base::kNullProcessHandle; // It's OK if this doesn't complete, the work will continue on next startup. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(&ReportAndClearExitCode, exit_code)); } void ExecuteReporter(const base::FilePath& install_dir) { base::WorkerPool::PostTask( FROM_HERE, base::Bind(&LaunchAndWaitForExit, install_dir.Append(kSwReporterExeName)), true); } class SwReporterInstallerTraits : public ComponentInstallerTraits { public: explicit SwReporterInstallerTraits(PrefService* prefs) : prefs_(prefs) {} virtual ~SwReporterInstallerTraits() {} virtual bool VerifyInstallation(const base::FilePath& dir) const { return base::PathExists(dir.Append(kSwReporterExeName)); } virtual bool CanAutoUpdate() const { return true; } virtual bool OnCustomInstall(const base::DictionaryValue& manifest, const base::FilePath& install_dir) { return true; } virtual void ComponentReady(const base::Version& version, const base::FilePath& install_dir, scoped_ptr<base::DictionaryValue> manifest) { wcsncpy_s(version_dir_, _MAX_PATH, install_dir.value().c_str(), install_dir.value().size()); // Only execute the reporter if there is still a pending request for it. if (prefs_->GetInteger(prefs::kSwReporterExecuteTryCount) > 0) ExecuteReporter(install_dir); } virtual base::FilePath GetBaseDirectory() const { return install_dir(); } virtual void GetHash(std::vector<uint8>* hash) const { GetPkHash(hash); } virtual std::string GetName() const { return "Software Reporter Tool"; } static base::FilePath install_dir() { // The base directory on windows looks like: // <profile>\AppData\Local\Google\Chrome\User Data\SwReporter\. base::FilePath result; PathService::Get(DIR_SW_REPORTER, &result); return result; } static std::string ID() { CrxComponent component; component.version = Version("0.0.0.0"); GetPkHash(&component.pk_hash); return component_updater::GetCrxComponentID(component); } static base::FilePath VersionPath() { return base::FilePath(version_dir_); } private: static void GetPkHash(std::vector<uint8>* hash) { DCHECK(hash); hash->assign(kSha256Hash, kSha256Hash + sizeof(kSha256Hash)); } PrefService* prefs_; static wchar_t version_dir_[_MAX_PATH]; }; wchar_t SwReporterInstallerTraits::version_dir_[] = {}; void RegisterComponent(ComponentUpdateService* cus, PrefService* prefs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); scoped_ptr<ComponentInstallerTraits> traits( new SwReporterInstallerTraits(prefs)); // |cus| will take ownership of |installer| during installer->Register(cus). DefaultComponentInstaller* installer = new DefaultComponentInstaller(traits.Pass()); installer->Register(cus); } // We need a conditional version of register component so that it can be called // back on the UI thread after validating on the File thread that the component // path exists and we must re-register on startup for example. void MaybeRegisterComponent(ComponentUpdateService* cus, PrefService* prefs, bool register_component) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (register_component) RegisterComponent(cus, prefs); } } // namespace void ExecuteSwReporter(ComponentUpdateService* cus, PrefService* prefs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // If we have a pending execution, send metrics about it so we can account for // missing executions. if (prefs->GetInteger(prefs::kSwReporterExecuteTryCount) > 0) ReportUmaStep(SW_REPORTER_RESET_RETRIES); // This is an explicit call, so let's forget about previous incomplete // execution attempts and start from scratch. prefs->SetInteger(prefs::kSwReporterExecuteTryCount, kMaxRetry); ReportUmaStep(SW_REPORTER_EXPLICIT_REQUEST); const std::vector<std::string> registered_components(cus->GetComponentIDs()); if (std::find(registered_components.begin(), registered_components.end(), SwReporterInstallerTraits::ID()) == registered_components.end()) { RegisterComponent(cus, prefs); } else if (!SwReporterInstallerTraits::VersionPath().empty()) { // Here, we already have a fully registered and installed component // available for immediate use. This doesn't handle cases where the version // folder is there but the executable is not within in. This is a corruption // we don't want to handle here. ExecuteReporter(SwReporterInstallerTraits::VersionPath()); } // If the component is registered but the version path is not available, it // means the component was not fully installed yet, and it should run the // reporter when ComponentReady is called. } void ExecutePendingSwReporter(ComponentUpdateService* cus, PrefService* prefs) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // Register the existing component for updates. base::PostTaskAndReplyWithResult( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE), FROM_HERE, base::Bind(&base::PathExists, SwReporterInstallerTraits::install_dir()), base::Bind(&MaybeRegisterComponent, cus, prefs)); // Run the reporter if there is a pending execution request. int execute_try_count = prefs->GetInteger(prefs::kSwReporterExecuteTryCount); if (execute_try_count > 0) { // Retrieve the results if the pending request has completed. base::win::RegKey srt_key( HKEY_CURRENT_USER, kSoftwareRemovalToolRegistryKey, KEY_READ); DWORD exit_code; if (srt_key.Valid() && srt_key.ReadValueDW(kExitCodeRegistryValueName, &exit_code) == ERROR_SUCCESS) { ReportUmaStep(SW_REPORTER_REGISTRY_EXIT_CODE); ReportAndClearExitCode(exit_code); return; } // The previous request has not completed. The reporter will run again // when ComponentReady is called or the request is abandoned if it has // been tried too many times. prefs->SetInteger(prefs::kSwReporterExecuteTryCount, --execute_try_count); if (execute_try_count > 0) ReportUmaStep(SW_REPORTER_STARTUP_RETRY); else ReportUmaStep(SW_REPORTER_RETRIED_TOO_MANY_TIMES); } } void RegisterPrefsForSwReporter(PrefRegistrySimple* registry) { registry->RegisterIntegerPref(prefs::kSwReporterExecuteTryCount, 0); } } // namespace component_updater
/* * ConceptNetEdge.cpp * * Created on: Feb 23, 2017 * Author: stefan */ #include "containers/ConceptNetEdge.h" #include "containers/ConceptNetConcept.h" #include <sstream> #include <string> namespace kbcr { ConceptNetEdge::ConceptNetEdge(QString id, QString language, std::shared_ptr<ConceptNetConcept> firstConcept, std::shared_ptr<ConceptNetConcept> secondConcept, QString relation, double weight) { this->id = id; this->language = language; this->firstConcept = firstConcept; this->secondConcept = secondConcept; this->weight = weight; this->relation = relation; } ConceptNetEdge::~ConceptNetEdge() { } std::string ConceptNetEdge::toString() { std::stringstream ss; ss << "Edge: " << this->firstConcept->term.toStdString() << " Sense: " << this->firstConcept->senseLabel.toStdString() << " " << this->relation.toStdString() << " " << this->secondConcept->term.toStdString() << " Sense: " << this->secondConcept->senseLabel.toStdString() << " Weight: " << this->weight << " Number of sources: " << this->sources.size() << std::endl; return ss.str(); } } /* namespace kbcr */
// Copyright (c) 2014-2017 The Dash Core developers // Copyright (c) 2017-2018 The Dinero Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "chainparams.h" #include "validation.h" #include "messagesigner.h" #include "net_processing.h" #include "spork.h" #include <boost/lexical_cast.hpp> class CSporkMessage; class CSporkManager; CSporkManager sporkManager; std::map<uint256, CSporkMessage> mapSporks; void CSporkManager::ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fLiteMode) return; // disable all Dinero specific functionality if (strCommand == NetMsgType::SPORK) { CSporkMessage spork; vRecv >> spork; uint256 hash = spork.GetHash(); std::string strLogMsg; { LOCK(cs_main); pfrom->setAskFor.erase(hash); if(!chainActive.Tip()) return; strLogMsg = strprintf("SPORK -- hash: %s id: %d value: %10d bestHeight: %d peer=%d", hash.ToString(), spork.nSporkID, spork.nValue, chainActive.Height(), pfrom->id); } if(mapSporksActive.count(spork.nSporkID)) { if (mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned) { LogPrint("spork", "%s seen\n", strLogMsg); return; } else { LogPrintf("%s updated\n", strLogMsg); } } else { LogPrintf("%s new\n", strLogMsg); } if(!spork.CheckSignature()) { LogPrintf("CSporkManager::ProcessSpork -- invalid signature\n"); Misbehaving(pfrom->GetId(), 100); return; } mapSporks[hash] = spork; mapSporksActive[spork.nSporkID] = spork; spork.Relay(connman); //does a task if needed ExecuteSpork(spork.nSporkID, spork.nValue); } else if (strCommand == NetMsgType::GETSPORKS) { std::map<int, CSporkMessage>::iterator it = mapSporksActive.begin(); while(it != mapSporksActive.end()) { connman.PushMessage(pfrom, NetMsgType::SPORK, it->second); it++; } } } void CSporkManager::ExecuteSpork(int nSporkID, int nValue) { //correct fork via spork technology if(nSporkID == SPORK_12_RECONSIDER_BLOCKS && nValue > 0) { // allow to reprocess 24h of blocks max, which should be enough to resolve any issues int64_t nMaxBlocks = 576; // this potentially can be a heavy operation, so only allow this to be executed once per 10 minutes int64_t nTimeout = 10 * 60; static int64_t nTimeExecuted = 0; // i.e. it was never executed before if(GetTime() - nTimeExecuted < nTimeout) { LogPrint("spork", "CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider blocks, too soon - %d/%d\n", GetTime() - nTimeExecuted, nTimeout); return; } if(nValue > nMaxBlocks) { LogPrintf("CSporkManager::ExecuteSpork -- ERROR: Trying to reconsider too many blocks %d/%d\n", nValue, nMaxBlocks); return; } LogPrintf("CSporkManager::ExecuteSpork -- Reconsider Last %d Blocks\n", nValue); ReprocessBlocks(nValue); nTimeExecuted = GetTime(); } } bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue, CConnman& connman) { CSporkMessage spork = CSporkMessage(nSporkID, nValue, GetAdjustedTime()); if(spork.Sign(strMasterPrivKey)) { spork.Relay(connman); mapSporks[spork.GetHash()] = spork; mapSporksActive[nSporkID] = spork; return true; } return false; } // grab the spork, otherwise say it's off bool CSporkManager::IsSporkActive(int nSporkID) { int64_t r = -1; if(mapSporksActive.count(nSporkID)){ r = mapSporksActive[nSporkID].nValue; } else { switch (nSporkID) { case SPORK_2_INSTANTSEND_ENABLED: r = SPORK_2_INSTANTSEND_ENABLED_DEFAULT; break; case SPORK_3_INSTANTSEND_BLOCK_FILTERING: r = SPORK_3_INSTANTSEND_BLOCK_FILTERING_DEFAULT; break; case SPORK_5_INSTANTSEND_MAX_VALUE: r = SPORK_5_INSTANTSEND_MAX_VALUE_DEFAULT; break; case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: r = SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT; break; case SPORK_9_SUPERBLOCKS_ENABLED: r = SPORK_9_SUPERBLOCKS_ENABLED_DEFAULT; break; case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: r = SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT; break; case SPORK_12_RECONSIDER_BLOCKS: r = SPORK_12_RECONSIDER_BLOCKS_DEFAULT; break; case SPORK_13_OLD_SUPERBLOCK_FLAG: r = SPORK_13_OLD_SUPERBLOCK_FLAG_DEFAULT; break; case SPORK_14_REQUIRE_SENTINEL_FLAG: r = SPORK_14_REQUIRE_SENTINEL_FLAG_DEFAULT; break; default: LogPrint("spork", "CSporkManager::IsSporkActive -- Unknown Spork ID %d\n", nSporkID); r = 4070908800ULL; // 2099-1-1 i.e. off by default break; } } return r < GetAdjustedTime(); } // grab the value of the spork on the network, or the default int64_t CSporkManager::GetSporkValue(int nSporkID) { if (mapSporksActive.count(nSporkID)) return mapSporksActive[nSporkID].nValue; switch (nSporkID) { case SPORK_2_INSTANTSEND_ENABLED: return SPORK_2_INSTANTSEND_ENABLED_DEFAULT; case SPORK_3_INSTANTSEND_BLOCK_FILTERING: return SPORK_3_INSTANTSEND_BLOCK_FILTERING_DEFAULT; case SPORK_5_INSTANTSEND_MAX_VALUE: return SPORK_5_INSTANTSEND_MAX_VALUE_DEFAULT; case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT; case SPORK_9_SUPERBLOCKS_ENABLED: return SPORK_9_SUPERBLOCKS_ENABLED_DEFAULT; case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT; case SPORK_12_RECONSIDER_BLOCKS: return SPORK_12_RECONSIDER_BLOCKS_DEFAULT; case SPORK_13_OLD_SUPERBLOCK_FLAG: return SPORK_13_OLD_SUPERBLOCK_FLAG_DEFAULT; case SPORK_14_REQUIRE_SENTINEL_FLAG: return SPORK_14_REQUIRE_SENTINEL_FLAG_DEFAULT; default: LogPrint("spork", "CSporkManager::GetSporkValue -- Unknown Spork ID %d\n", nSporkID); return -1; } } int CSporkManager::GetSporkIDByName(std::string strName) { if (strName == "SPORK_2_INSTANTSEND_ENABLED") return SPORK_2_INSTANTSEND_ENABLED; if (strName == "SPORK_3_INSTANTSEND_BLOCK_FILTERING") return SPORK_3_INSTANTSEND_BLOCK_FILTERING; if (strName == "SPORK_5_INSTANTSEND_MAX_VALUE") return SPORK_5_INSTANTSEND_MAX_VALUE; if (strName == "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT") return SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT; if (strName == "SPORK_9_SUPERBLOCKS_ENABLED") return SPORK_9_SUPERBLOCKS_ENABLED; if (strName == "SPORK_10_MASTERNODE_PAY_UPDATED_NODES") return SPORK_10_MASTERNODE_PAY_UPDATED_NODES; if (strName == "SPORK_12_RECONSIDER_BLOCKS") return SPORK_12_RECONSIDER_BLOCKS; if (strName == "SPORK_13_OLD_SUPERBLOCK_FLAG") return SPORK_13_OLD_SUPERBLOCK_FLAG; if (strName == "SPORK_14_REQUIRE_SENTINEL_FLAG") return SPORK_14_REQUIRE_SENTINEL_FLAG; LogPrint("spork", "CSporkManager::GetSporkIDByName -- Unknown Spork name '%s'\n", strName); return -1; } std::string CSporkManager::GetSporkNameByID(int nSporkID) { switch (nSporkID) { case SPORK_2_INSTANTSEND_ENABLED: return "SPORK_2_INSTANTSEND_ENABLED"; case SPORK_3_INSTANTSEND_BLOCK_FILTERING: return "SPORK_3_INSTANTSEND_BLOCK_FILTERING"; case SPORK_5_INSTANTSEND_MAX_VALUE: return "SPORK_5_INSTANTSEND_MAX_VALUE"; case SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT: return "SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT"; case SPORK_9_SUPERBLOCKS_ENABLED: return "SPORK_9_SUPERBLOCKS_ENABLED"; case SPORK_10_MASTERNODE_PAY_UPDATED_NODES: return "SPORK_10_MASTERNODE_PAY_UPDATED_NODES"; case SPORK_12_RECONSIDER_BLOCKS: return "SPORK_12_RECONSIDER_BLOCKS"; case SPORK_13_OLD_SUPERBLOCK_FLAG: return "SPORK_13_OLD_SUPERBLOCK_FLAG"; case SPORK_14_REQUIRE_SENTINEL_FLAG: return "SPORK_14_REQUIRE_SENTINEL_FLAG"; default: LogPrint("spork", "CSporkManager::GetSporkNameByID -- Unknown Spork ID %d\n", nSporkID); return "Unknown"; } } bool CSporkManager::SetPrivKey(std::string strPrivKey) { CSporkMessage spork; spork.Sign(strPrivKey); if(spork.CheckSignature()){ // Test signing successful, proceed LogPrintf("CSporkManager::SetPrivKey -- Successfully initialized as spork signer\n"); strMasterPrivKey = strPrivKey; return true; } else { return false; } } bool CSporkMessage::Sign(std::string strSignKey) { CKey key; CPubKey pubkey; std::string strError = ""; std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned); if(!CMessageSigner::GetKeysFromSecret(strSignKey, key, pubkey)) { LogPrintf("CSporkMessage::Sign -- GetKeysFromSecret() failed, invalid spork key %s\n", strSignKey); return false; } if(!CMessageSigner::SignMessage(strMessage, vchSig, key)) { LogPrintf("CSporkMessage::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) { LogPrintf("CSporkMessage::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CSporkMessage::CheckSignature() { //note: need to investigate why this is failing std::string strError = ""; std::string strMessage = boost::lexical_cast<std::string>(nSporkID) + boost::lexical_cast<std::string>(nValue) + boost::lexical_cast<std::string>(nTimeSigned); CPubKey pubkey(ParseHex(Params().SporkPubKey())); if(!CMessageSigner::VerifyMessage(pubkey, vchSig, strMessage, strError)) { LogPrintf("CSporkMessage::CheckSignature -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } void CSporkMessage::Relay(CConnman& connman) { CInv inv(MSG_SPORK, GetHash()); connman.RelayInv(inv); }
/* 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/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/common.h" #include "tensorflow/lite/kernels/internal/compatibility.h" #include "tensorflow/lite/kernels/internal/quantization_util.h" #include "tensorflow/lite/kernels/internal/tensor_ctypes.h" #include "tensorflow/lite/kernels/kernel_util.h" #include "tensorflow/lite/kernels/op_macros.h" #include "tensorflow/lite/micro/kernels/kernel_util.h" /* * The circular buffer custom operator is used to implement strided streaming * convolutions on TFLite Micro. Each time this operator is invoked, it checks * whether or not to run, based on a predetermined stride in time. If the op * runs, it inserts the input into the end of the output buffer and shifts the * output values towards the start of the buffer. It discards the oldest value * in the output buffer. * * Input: [<input N+1] * Before shifting: * Output: [<input 1>, <input 2>, <input ...>, <input N>] * * After shifting: * Output: [<input 2>, <input 3>, <input ...>, <input N+1>] * * We make some assumptions in this custom operator: * - Input shape must be [1, 1, 1, depth] * - Output shape must be [1, num_slots, 1, depth] * - Input and output types must match. * - Input and output quantization params must be identical. */ namespace tflite { namespace ops { namespace micro { namespace circular_buffer { namespace { // The CircularBuffer op has one input and one output tensor. constexpr int kInputTensor = 0; constexpr int kOutputTensor = 0; // TODO(b/149795762): Add this to TfLiteStatus enum. constexpr int kTfLiteAbort = -9; // These fields control the stride period of a strided streaming model. This op // returns kTfLiteAbort until cycles_until_run-- is zero. At this time, // cycles_until_run is reset to cycles_max. struct OpData { int cycles_until_run; int cycles_max; }; // These constants represent constants specific to the music detect model. // They exist until (b/132070898) is fixed. constexpr int kMaxOpDataSize = 7; int op_data_counter = 0; OpData op_data_array[kMaxOpDataSize]; } // namespace void Free(TfLiteContext* context, void* buffer) { op_data_counter = 0; } TfLiteStatus Prepare(TfLiteContext* context, TfLiteNode* node) { const TfLiteTensor* input = GetInput(context, node, kInputTensor); TF_LITE_ENSURE(context, input != nullptr); TfLiteTensor* output = GetOutput(context, node, kOutputTensor); TF_LITE_ENSURE(context, output != nullptr); TF_LITE_ENSURE(context, input != nullptr); TF_LITE_ENSURE(context, output != nullptr); TF_LITE_ENSURE_EQ(context, 1, output->dims->data[0]); TF_LITE_ENSURE_EQ(context, 1, input->dims->data[0]); TF_LITE_ENSURE_EQ(context, 1, input->dims->data[1]); TF_LITE_ENSURE_EQ(context, 1, output->dims->data[2]); TF_LITE_ENSURE_EQ(context, 1, input->dims->data[2]); TF_LITE_ENSURE_EQ(context, output->dims->data[3], input->dims->data[3]); TF_LITE_ENSURE_TYPES_EQ(context, input->type, output->type); // The circular buffer custom operator currently only supports int8_t. TF_LITE_ENSURE_TYPES_EQ(context, input->type, kTfLiteInt8); // TODO(b/132070898): Use statically slotted OpData structures until a // scratch memory API is ready. TFLITE_DCHECK_LE(op_data_counter, kMaxOpDataSize); OpData* op_data = &op_data_array[op_data_counter++]; // The last circular buffer layer (length 5) simply accumulates outputs, and // does not run periodically. // TODO(b/150001379): Move this special case logic to the tflite flatbuffer. if (output->dims->data[1] == 5) { op_data->cycles_max = 1; } else { op_data->cycles_max = 2; } op_data->cycles_until_run = op_data->cycles_max; node->user_data = op_data; return kTfLiteOk; } // Shifts buffer over by the output depth, and write new input to end of buffer. // num_slots is the number of samples stored in the output buffer. // depth is the size of each sample. void EvalInt8(const int8_t* input, int num_slots, int depth, int8_t* output) { memmove(output, &output[depth], (num_slots - 1) * depth); memcpy(&output[(num_slots - 1) * depth], input, depth); } TfLiteStatus Eval(TfLiteContext* context, TfLiteNode* node) { const TfLiteEvalTensor* input = tflite::micro::GetEvalInput(context, node, kInputTensor); TfLiteEvalTensor* output = tflite::micro::GetEvalOutput(context, node, kOutputTensor); OpData* data = reinterpret_cast<OpData*>(node->user_data); int num_slots = output->dims->data[1]; int depth = output->dims->data[3]; if (input->type == kTfLiteInt8) { EvalInt8(tflite::micro::GetTensorData<int8_t>(input), num_slots, depth, tflite::micro::GetTensorData<int8_t>(output)); } else { TF_LITE_KERNEL_LOG(context, "Type %s (%d) not supported.", TfLiteTypeGetName(input->type), input->type); return kTfLiteError; } if (--data->cycles_until_run != 0) { // Signal the interpreter to end current run if the delay before op invoke // has not been reached. // TODO(b/149795762): Add kTfLiteAbort to TfLiteStatus enum. return static_cast<TfLiteStatus>(kTfLiteAbort); } // If prepare is ever called more than one time (for example, when testing the // ambient model, the interpreter is created a few times), this op data // counter needs to be reset so that future instances do not overrun this op // data array. op_data_counter = 0; data->cycles_until_run = data->cycles_max; return kTfLiteOk; } } // namespace circular_buffer TfLiteRegistration* Register_CIRCULAR_BUFFER() { static TfLiteRegistration r = {/*init=*/nullptr, /*free=*/circular_buffer::Free, /*prepare=*/circular_buffer::Prepare, /*invoke=*/circular_buffer::Eval, /*profiling_string=*/nullptr, /*builtin_code=*/0, /*custom_name=*/nullptr, /*version=*/0}; return &r; } } // namespace micro } // namespace ops } // namespace tflite
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef SHAPE_HPP #define SHAPE_HPP // mapnik #include <mapnik/datasource.hpp> #include <mapnik/params.hpp> #include <mapnik/query.hpp> #include <mapnik/feature.hpp> #include <mapnik/box2d.hpp> #include <mapnik/coord.hpp> #include <mapnik/feature_layer_desc.hpp> #include <mapnik/value_types.hpp> // boost #include <boost/optional.hpp> #include <memory> // stl #include <vector> #include <string> #include "shape_io.hpp" using mapnik::datasource; using mapnik::parameters; using mapnik::query; using mapnik::featureset_ptr; using mapnik::layer_descriptor; using mapnik::coord2d; class shape_datasource : public datasource { public: shape_datasource(parameters const& params); virtual ~shape_datasource(); datasource::datasource_t type() const; static const char * name(); featureset_ptr features(query const& q) const; featureset_ptr features_at_point(coord2d const& pt, double tol = 0) const; box2d<double> envelope() const; boost::optional<mapnik::datasource_geometry_t> get_geometry_type() const; layer_descriptor get_descriptor() const; private: void init(shape_io& shape); datasource::datasource_t type_; std::string shape_name_; shape_io::shapeType shape_type_; long file_length_; box2d<double> extent_; bool indexed_; const int row_limit_; layer_descriptor desc_; }; #endif //SHAPE_HPP
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2019, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC 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 RateCtrl.cpp \brief Rate control manager class */ #include "RateCtrl.h" #include "../CommonLib/ChromaFormat.h" #include <cmath> #define LAMBDA_PREC 1000000 using namespace std; //sequence level EncRCSeq::EncRCSeq() { m_totalFrames = 0; m_targetRate = 0; m_frameRate = 0; m_targetBits = 0; m_GOPSize = 0; m_picWidth = 0; m_picHeight = 0; m_LCUWidth = 0; m_LCUHeight = 0; m_numberOfLevel = 0; m_numberOfLCU = 0; m_averageBits = 0; m_bitsRatio = NULL; m_GOPID2Level = NULL; m_picPara = NULL; m_LCUPara = NULL; m_numberOfPixel = 0; m_framesLeft = 0; m_bitsLeft = 0; m_useLCUSeparateModel = false; m_adaptiveBit = 0; m_lastLambda = 0.0; m_bitDepth = 0; } EncRCSeq::~EncRCSeq() { destroy(); } void EncRCSeq::create( int totalFrames, int targetBitrate, int frameRate, int GOPSize, int picWidth, int picHeight, int LCUWidth, int LCUHeight, int numberOfLevel, bool useLCUSeparateModel, int adaptiveBit ) { destroy(); m_totalFrames = totalFrames; m_targetRate = targetBitrate; m_frameRate = frameRate; m_GOPSize = GOPSize; m_picWidth = picWidth; m_picHeight = picHeight; m_LCUWidth = LCUWidth; m_LCUHeight = LCUHeight; m_numberOfLevel = numberOfLevel; m_useLCUSeparateModel = useLCUSeparateModel; m_numberOfPixel = m_picWidth * m_picHeight; m_targetBits = (int64_t)m_totalFrames * (int64_t)m_targetRate / (int64_t)m_frameRate; m_seqTargetBpp = (double)m_targetRate / (double)m_frameRate / (double)m_numberOfPixel; if ( m_seqTargetBpp < 0.03 ) { m_alphaUpdate = 0.01; m_betaUpdate = 0.005; } else if ( m_seqTargetBpp < 0.08 ) { m_alphaUpdate = 0.05; m_betaUpdate = 0.025; } else if ( m_seqTargetBpp < 0.2 ) { m_alphaUpdate = 0.1; m_betaUpdate = 0.05; } else if ( m_seqTargetBpp < 0.5 ) { m_alphaUpdate = 0.2; m_betaUpdate = 0.1; } else { m_alphaUpdate = 0.4; m_betaUpdate = 0.2; } m_averageBits = (int)(m_targetBits / totalFrames); int picWidthInBU = ( m_picWidth % m_LCUWidth ) == 0 ? m_picWidth / m_LCUWidth : m_picWidth / m_LCUWidth + 1; int picHeightInBU = ( m_picHeight % m_LCUHeight ) == 0 ? m_picHeight / m_LCUHeight : m_picHeight / m_LCUHeight + 1; m_numberOfLCU = picWidthInBU * picHeightInBU; m_bitsRatio = new int[m_GOPSize]; for ( int i=0; i<m_GOPSize; i++ ) { m_bitsRatio[i] = 1; } m_GOPID2Level = new int[m_GOPSize]; for ( int i=0; i<m_GOPSize; i++ ) { m_GOPID2Level[i] = 1; } m_picPara = new TRCParameter[m_numberOfLevel]; for ( int i=0; i<m_numberOfLevel; i++ ) { m_picPara[i].m_alpha = 0.0; m_picPara[i].m_beta = 0.0; m_picPara[i].m_validPix = -1; } if ( m_useLCUSeparateModel ) { m_LCUPara = new TRCParameter*[m_numberOfLevel]; for ( int i=0; i<m_numberOfLevel; i++ ) { m_LCUPara[i] = new TRCParameter[m_numberOfLCU]; for ( int j=0; j<m_numberOfLCU; j++) { m_LCUPara[i][j].m_alpha = 0.0; m_LCUPara[i][j].m_beta = 0.0; m_LCUPara[i][j].m_validPix = -1; } } } m_framesLeft = m_totalFrames; m_bitsLeft = m_targetBits; m_adaptiveBit = adaptiveBit; m_lastLambda = 0.0; } void EncRCSeq::destroy() { if (m_bitsRatio != NULL) { delete[] m_bitsRatio; m_bitsRatio = NULL; } if ( m_GOPID2Level != NULL ) { delete[] m_GOPID2Level; m_GOPID2Level = NULL; } if ( m_picPara != NULL ) { delete[] m_picPara; m_picPara = NULL; } if ( m_LCUPara != NULL ) { for ( int i=0; i<m_numberOfLevel; i++ ) { delete[] m_LCUPara[i]; } delete[] m_LCUPara; m_LCUPara = NULL; } } void EncRCSeq::initBitsRatio( int bitsRatio[]) { for (int i=0; i<m_GOPSize; i++) { m_bitsRatio[i] = bitsRatio[i]; } } void EncRCSeq::initGOPID2Level( int GOPID2Level[] ) { for ( int i=0; i<m_GOPSize; i++ ) { m_GOPID2Level[i] = GOPID2Level[i]; } } void EncRCSeq::initPicPara( TRCParameter* picPara ) { CHECK( m_picPara == NULL, "Object does not exist" ); if ( picPara == NULL ) { for ( int i=0; i<m_numberOfLevel; i++ ) { if (i>0) { int bitdepth_luma_scale = 2 * (m_bitDepth - 8 - DISTORTION_PRECISION_ADJUSTMENT(m_bitDepth)); m_picPara[i].m_alpha = 3.2003 * pow(2.0, bitdepth_luma_scale); m_picPara[i].m_beta = -1.367; } else { int bitdepth_luma_scale = 2 * (m_bitDepth - 8 - DISTORTION_PRECISION_ADJUSTMENT(m_bitDepth)); m_picPara[i].m_alpha = pow(2.0, bitdepth_luma_scale) * ALPHA; m_picPara[i].m_beta = BETA2; } } } else { for ( int i=0; i<m_numberOfLevel; i++ ) { m_picPara[i] = picPara[i]; } } } void EncRCSeq::initLCUPara( TRCParameter** LCUPara ) { if ( m_LCUPara == NULL ) { return; } if ( LCUPara == NULL ) { for ( int i=0; i<m_numberOfLevel; i++ ) { for ( int j=0; j<m_numberOfLCU; j++) { m_LCUPara[i][j].m_alpha = m_picPara[i].m_alpha; m_LCUPara[i][j].m_beta = m_picPara[i].m_beta; } } } else { for ( int i=0; i<m_numberOfLevel; i++ ) { for ( int j=0; j<m_numberOfLCU; j++) { m_LCUPara[i][j] = LCUPara[i][j]; } } } } void EncRCSeq::updateAfterPic ( int bits ) { m_bitsLeft -= bits; m_framesLeft--; } void EncRCSeq::setAllBitRatio( double basicLambda, double* equaCoeffA, double* equaCoeffB ) { int* bitsRatio = new int[m_GOPSize]; for ( int i=0; i<m_GOPSize; i++ ) { bitsRatio[i] = (int)(equaCoeffA[i] * pow(basicLambda, equaCoeffB[i]) * (double)getPicPara(getGOPID2Level(i)).m_validPix); } initBitsRatio( bitsRatio ); delete[] bitsRatio; } //GOP level EncRCGOP::EncRCGOP() { m_encRCSeq = NULL; m_picTargetBitInGOP = NULL; m_numPic = 0; m_targetBits = 0; m_picLeft = 0; m_bitsLeft = 0; } EncRCGOP::~EncRCGOP() { destroy(); } void EncRCGOP::create( EncRCSeq* encRCSeq, int numPic ) { destroy(); int targetBits = xEstGOPTargetBits( encRCSeq, numPic ); if ( encRCSeq->getAdaptiveBits() > 0 && encRCSeq->getLastLambda() > 0.1 ) { double targetBpp = (double)targetBits / encRCSeq->getNumPixel(); double basicLambda = 0.0; double* lambdaRatio = new double[encRCSeq->getGOPSize()]; double* equaCoeffA = new double[encRCSeq->getGOPSize()]; double* equaCoeffB = new double[encRCSeq->getGOPSize()]; if ( encRCSeq->getAdaptiveBits() == 1 ) // for GOP size =4, low delay case { if ( encRCSeq->getLastLambda() < 120.0 ) { lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.5793; lambdaRatio[0] = 1.3 * lambdaRatio[1]; lambdaRatio[2] = 1.3 * lambdaRatio[1]; lambdaRatio[3] = 1.0; } else { lambdaRatio[0] = 5.0; lambdaRatio[1] = 4.0; lambdaRatio[2] = 5.0; lambdaRatio[3] = 1.0; } } else if ( encRCSeq->getAdaptiveBits() == 2 ) // for GOP size = 8, random access case { if ( encRCSeq->getLastLambda() < 90.0 ) { lambdaRatio[0] = 1.0; lambdaRatio[1] = 0.725 * log( encRCSeq->getLastLambda() ) + 0.7963; lambdaRatio[2] = 1.3 * lambdaRatio[1]; lambdaRatio[3] = 3.25 * lambdaRatio[1]; lambdaRatio[4] = 3.25 * lambdaRatio[1]; lambdaRatio[5] = 1.3 * lambdaRatio[1]; lambdaRatio[6] = 3.25 * lambdaRatio[1]; lambdaRatio[7] = 3.25 * lambdaRatio[1]; } else { lambdaRatio[0] = 1.0; lambdaRatio[1] = 4.0; lambdaRatio[2] = 5.0; lambdaRatio[3] = 12.3; lambdaRatio[4] = 12.3; lambdaRatio[5] = 5.0; lambdaRatio[6] = 12.3; lambdaRatio[7] = 12.3; } } else if (encRCSeq->getAdaptiveBits() == 3) // for GOP size = 16, random access case { { int bitdepth_luma_scale = 2 * (encRCSeq->getbitDepth() - 8 - DISTORTION_PRECISION_ADJUSTMENT(encRCSeq->getbitDepth())); double hierarQp = 4.2005 * log(encRCSeq->getLastLambda() / pow(2.0, bitdepth_luma_scale)) + 13.7122; // the qp of POC16 double qpLev2 = (hierarQp + 0.0) + 0.2016 * (hierarQp + 0.0) - 4.8848; double qpLev3 = (hierarQp + 3.0) + 0.22286 * (hierarQp + 3.0) - 5.7476; double qpLev4 = (hierarQp + 4.0) + 0.2333 * (hierarQp + 4.0) - 5.9; double qpLev5 = (hierarQp + 5.0) + 0.3 * (hierarQp + 5.0) - 7.1444; double lambdaLev1 = exp((hierarQp - 13.7122) / 4.2005) *pow(2.0, bitdepth_luma_scale); double lambdaLev2 = exp((qpLev2 - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); double lambdaLev3 = exp((qpLev3 - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); double lambdaLev4 = exp((qpLev4 - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); double lambdaLev5 = exp((qpLev5 - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); lambdaRatio[0] = 1.0; lambdaRatio[1] = lambdaLev2 / lambdaLev1; lambdaRatio[2] = lambdaLev3 / lambdaLev1; lambdaRatio[3] = lambdaLev4 / lambdaLev1; lambdaRatio[4] = lambdaLev5 / lambdaLev1; lambdaRatio[5] = lambdaLev5 / lambdaLev1; lambdaRatio[6] = lambdaLev4 / lambdaLev1; lambdaRatio[7] = lambdaLev5 / lambdaLev1; lambdaRatio[8] = lambdaLev5 / lambdaLev1; lambdaRatio[9] = lambdaLev3 / lambdaLev1; lambdaRatio[10] = lambdaLev4 / lambdaLev1; lambdaRatio[11] = lambdaLev5 / lambdaLev1; lambdaRatio[12] = lambdaLev5 / lambdaLev1; lambdaRatio[13] = lambdaLev4 / lambdaLev1; lambdaRatio[14] = lambdaLev5 / lambdaLev1; lambdaRatio[15] = lambdaLev5 / lambdaLev1; } } xCalEquaCoeff( encRCSeq, lambdaRatio, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize() ); basicLambda = xSolveEqua(encRCSeq, targetBpp, equaCoeffA, equaCoeffB, encRCSeq->getGOPSize()); encRCSeq->setAllBitRatio( basicLambda, equaCoeffA, equaCoeffB ); delete []lambdaRatio; delete []equaCoeffA; delete []equaCoeffB; } m_picTargetBitInGOP = new int[numPic]; int i; int totalPicRatio = 0; int currPicRatio = 0; for ( i=0; i<numPic; i++ ) { totalPicRatio += encRCSeq->getBitRatio( i ); } for ( i=0; i<numPic; i++ ) { currPicRatio = encRCSeq->getBitRatio( i ); m_picTargetBitInGOP[i] = (int)( ((double)targetBits) * currPicRatio / totalPicRatio ); } m_encRCSeq = encRCSeq; m_numPic = numPic; m_targetBits = targetBits; m_picLeft = m_numPic; m_bitsLeft = m_targetBits; } void EncRCGOP::xCalEquaCoeff( EncRCSeq* encRCSeq, double* lambdaRatio, double* equaCoeffA, double* equaCoeffB, int GOPSize ) { for ( int i=0; i<GOPSize; i++ ) { int frameLevel = encRCSeq->getGOPID2Level(i); double alpha = encRCSeq->getPicPara(frameLevel).m_alpha; double beta = encRCSeq->getPicPara(frameLevel).m_beta; equaCoeffA[i] = pow( 1.0/alpha, 1.0/beta ) * pow( lambdaRatio[i], 1.0/beta ); equaCoeffB[i] = 1.0/beta; } } double EncRCGOP::xSolveEqua(EncRCSeq* encRCSeq, double targetBpp, double* equaCoeffA, double* equaCoeffB, int GOPSize) { double solution = 100.0; double minNumber = 0.1; double maxNumber = 10000.0; for ( int i=0; i<g_RCIterationNum; i++ ) { double fx = 0.0; for ( int j=0; j<GOPSize; j++ ) { double tmpBpp = equaCoeffA[j] * pow(solution, equaCoeffB[j]); double actualBpp = tmpBpp * (double)encRCSeq->getPicPara(encRCSeq->getGOPID2Level(j)).m_validPix / (double)encRCSeq->getNumPixel(); fx += actualBpp; } if ( fabs( fx - targetBpp ) < 0.000001 ) { break; } if ( fx > targetBpp ) { minNumber = solution; solution = ( solution + maxNumber ) / 2.0; } else { maxNumber = solution; solution = ( solution + minNumber ) / 2.0; } } solution = Clip3( 0.1, 10000.0, solution ); return solution; } void EncRCGOP::destroy() { m_encRCSeq = NULL; if ( m_picTargetBitInGOP != NULL ) { delete[] m_picTargetBitInGOP; m_picTargetBitInGOP = NULL; } } void EncRCGOP::updateAfterPicture( int bitsCost ) { m_bitsLeft -= bitsCost; m_picLeft--; } int EncRCGOP::xEstGOPTargetBits( EncRCSeq* encRCSeq, int GOPSize ) { int realInfluencePicture = min( g_RCSmoothWindowSize, encRCSeq->getFramesLeft() ); int averageTargetBitsPerPic = (int)( encRCSeq->getTargetBits() / encRCSeq->getTotalFrames() ); int currentTargetBitsPerPic = (int)( ( encRCSeq->getBitsLeft() - averageTargetBitsPerPic * (encRCSeq->getFramesLeft() - realInfluencePicture) ) / realInfluencePicture ); int targetBits = currentTargetBitsPerPic * GOPSize; if ( targetBits < 200 ) { targetBits = 200; // at least allocate 200 bits for one GOP } return targetBits; } //picture level EncRCPic::EncRCPic() { m_encRCSeq = NULL; m_encRCGOP = NULL; m_frameLevel = 0; m_numberOfPixel = 0; m_numberOfLCU = 0; m_targetBits = 0; m_estHeaderBits = 0; m_estPicQP = 0; m_estPicLambda = 0.0; m_LCULeft = 0; m_bitsLeft = 0; m_pixelsLeft = 0; m_LCUs = NULL; m_picActualHeaderBits = 0; m_picActualBits = 0; m_picQP = 0; m_picLambda = 0.0; m_picMSE = 0.0; m_validPixelsInPic = 0; } EncRCPic::~EncRCPic() { destroy(); } int EncRCPic::xEstPicTargetBits( EncRCSeq* encRCSeq, EncRCGOP* encRCGOP ) { int targetBits = 0; int GOPbitsLeft = encRCGOP->getBitsLeft(); int i; int currPicPosition = encRCGOP->getNumPic()-encRCGOP->getPicLeft(); int currPicRatio = encRCSeq->getBitRatio( currPicPosition ); int totalPicRatio = 0; for ( i=currPicPosition; i<encRCGOP->getNumPic(); i++ ) { totalPicRatio += encRCSeq->getBitRatio( i ); } targetBits = int( ((double)GOPbitsLeft) * currPicRatio / totalPicRatio ); if ( targetBits < 100 ) { targetBits = 100; // at least allocate 100 bits for one picture } if ( m_encRCSeq->getFramesLeft() > 16 ) { targetBits = int( g_RCWeightPicRargetBitInBuffer * targetBits + g_RCWeightPicTargetBitInGOP * m_encRCGOP->getTargetBitInGOP( currPicPosition ) ); } return targetBits; } int EncRCPic::xEstPicHeaderBits( list<EncRCPic*>& listPreviousPictures, int frameLevel ) { int numPreviousPics = 0; int totalPreviousBits = 0; list<EncRCPic*>::iterator it; for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ ) { if ( (*it)->getFrameLevel() == frameLevel ) { totalPreviousBits += (*it)->getPicActualHeaderBits(); numPreviousPics++; } } int estHeaderBits = 0; if ( numPreviousPics > 0 ) { estHeaderBits = totalPreviousBits / numPreviousPics; } return estHeaderBits; } #if V0078_ADAPTIVE_LOWER_BOUND int EncRCPic::xEstPicLowerBound(EncRCSeq* encRCSeq, EncRCGOP* encRCGOP) { int lowerBound = 0; int GOPbitsLeft = encRCGOP->getBitsLeft(); const int nextPicPosition = (encRCGOP->getNumPic() - encRCGOP->getPicLeft() + 1) % encRCGOP->getNumPic(); const int nextPicRatio = encRCSeq->getBitRatio(nextPicPosition); int totalPicRatio = 0; for (int i = nextPicPosition; i < encRCGOP->getNumPic(); i++) { totalPicRatio += encRCSeq->getBitRatio(i); } if (nextPicPosition == 0) { GOPbitsLeft = encRCGOP->getTargetBits(); } else { GOPbitsLeft -= m_targetBits; } lowerBound = int(((double)GOPbitsLeft) * nextPicRatio / totalPicRatio); if (lowerBound < 100) { lowerBound = 100; // at least allocate 100 bits for one picture } if (m_encRCSeq->getFramesLeft() > 16) { lowerBound = int(g_RCWeightPicRargetBitInBuffer * lowerBound + g_RCWeightPicTargetBitInGOP * m_encRCGOP->getTargetBitInGOP(nextPicPosition)); } return lowerBound; } #endif void EncRCPic::addToPictureLsit( list<EncRCPic*>& listPreviousPictures ) { if ( listPreviousPictures.size() > g_RCMaxPicListSize ) { EncRCPic* p = listPreviousPictures.front(); listPreviousPictures.pop_front(); p->destroy(); delete p; } listPreviousPictures.push_back( this ); } void EncRCPic::create( EncRCSeq* encRCSeq, EncRCGOP* encRCGOP, int frameLevel, list<EncRCPic*>& listPreviousPictures ) { destroy(); m_encRCSeq = encRCSeq; m_encRCGOP = encRCGOP; int targetBits = xEstPicTargetBits( encRCSeq, encRCGOP ); int estHeaderBits = xEstPicHeaderBits( listPreviousPictures, frameLevel ); if ( targetBits < estHeaderBits + 100 ) { targetBits = estHeaderBits + 100; // at least allocate 100 bits for picture data } m_frameLevel = frameLevel; m_numberOfPixel = encRCSeq->getNumPixel(); m_numberOfLCU = encRCSeq->getNumberOfLCU(); m_estPicLambda = 100.0; m_targetBits = targetBits; m_estHeaderBits = estHeaderBits; m_bitsLeft = m_targetBits; int picWidth = encRCSeq->getPicWidth(); int picHeight = encRCSeq->getPicHeight(); int LCUWidth = encRCSeq->getLCUWidth(); int LCUHeight = encRCSeq->getLCUHeight(); int picWidthInLCU = ( picWidth % LCUWidth ) == 0 ? picWidth / LCUWidth : picWidth / LCUWidth + 1; int picHeightInLCU = ( picHeight % LCUHeight ) == 0 ? picHeight / LCUHeight : picHeight / LCUHeight + 1; #if V0078_ADAPTIVE_LOWER_BOUND m_lowerBound = xEstPicLowerBound( encRCSeq, encRCGOP ); #endif m_LCULeft = m_numberOfLCU; m_bitsLeft -= m_estHeaderBits; m_pixelsLeft = m_numberOfPixel; m_LCUs = new TRCLCU[m_numberOfLCU]; int i, j; int LCUIdx; for ( i=0; i<picWidthInLCU; i++ ) { for ( j=0; j<picHeightInLCU; j++ ) { LCUIdx = j*picWidthInLCU + i; m_LCUs[LCUIdx].m_actualBits = 0; m_LCUs[LCUIdx].m_actualSSE = 0.0; m_LCUs[LCUIdx].m_actualMSE = 0.0; m_LCUs[LCUIdx].m_QP = 0; m_LCUs[LCUIdx].m_lambda = 0.0; m_LCUs[LCUIdx].m_targetBits = 0; m_LCUs[LCUIdx].m_bitWeight = 1.0; int currWidth = ( (i == picWidthInLCU -1) ? picWidth - LCUWidth *(picWidthInLCU -1) : LCUWidth ); int currHeight = ( (j == picHeightInLCU-1) ? picHeight - LCUHeight*(picHeightInLCU-1) : LCUHeight ); m_LCUs[LCUIdx].m_numberOfPixel = currWidth * currHeight; } } m_picActualHeaderBits = 0; m_picActualBits = 0; m_picQP = 0; m_picLambda = 0.0; m_validPixelsInPic = 0; m_picMSE = 0.0; } void EncRCPic::destroy() { if( m_LCUs != NULL ) { delete[] m_LCUs; m_LCUs = NULL; } m_encRCSeq = NULL; m_encRCGOP = NULL; } double EncRCPic::estimatePicLambda( list<EncRCPic*>& listPreviousPictures, bool isIRAP) { double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha; double beta = m_encRCSeq->getPicPara( m_frameLevel ).m_beta; double bpp = (double)m_targetBits/(double)m_numberOfPixel; int lastPicValPix = 0; if (listPreviousPictures.size() > 0) { lastPicValPix = m_encRCSeq->getPicPara(m_frameLevel).m_validPix; } if (lastPicValPix > 0) { bpp = (double)m_targetBits / (double)lastPicValPix; } double estLambda; if (isIRAP) { estLambda = calculateLambdaIntra(alpha, beta, pow(m_totalCostIntra/(double)m_numberOfPixel, BETA1), bpp); } else { estLambda = alpha * pow( bpp, beta ); } double lastLevelLambda = -1.0; double lastPicLambda = -1.0; double lastValidLambda = -1.0; list<EncRCPic*>::iterator it; for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ ) { if ( (*it)->getFrameLevel() == m_frameLevel ) { lastLevelLambda = (*it)->getPicActualLambda(); } lastPicLambda = (*it)->getPicActualLambda(); if ( lastPicLambda > 0.0 ) { lastValidLambda = lastPicLambda; } } if ( lastLevelLambda > 0.0 ) { lastLevelLambda = Clip3( 0.1, 10000.0, lastLevelLambda ); estLambda = Clip3( lastLevelLambda * pow( 2.0, -3.0/3.0 ), lastLevelLambda * pow( 2.0, 3.0/3.0 ), estLambda ); } if ( lastPicLambda > 0.0 ) { lastPicLambda = Clip3( 0.1, 2000.0, lastPicLambda ); estLambda = Clip3( lastPicLambda * pow( 2.0, -10.0/3.0 ), lastPicLambda * pow( 2.0, 10.0/3.0 ), estLambda ); } else if ( lastValidLambda > 0.0 ) { lastValidLambda = Clip3( 0.1, 2000.0, lastValidLambda ); estLambda = Clip3( lastValidLambda * pow(2.0, -10.0/3.0), lastValidLambda * pow(2.0, 10.0/3.0), estLambda ); } else { estLambda = Clip3( 0.1, 10000.0, estLambda ); } if ( estLambda < 0.1 ) { estLambda = 0.1; } //Avoid different results in different platforms. The problem is caused by the different results of pow() in different platforms. estLambda = double(int64_t(estLambda * (double)LAMBDA_PREC + 0.5)) / (double)LAMBDA_PREC; m_estPicLambda = estLambda; double totalWeight = 0.0; // initial BU bit allocation weight for ( int i=0; i<m_numberOfLCU; i++ ) { double alphaLCU, betaLCU; if ( m_encRCSeq->getUseLCUSeparateModel() ) { alphaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_alpha; betaLCU = m_encRCSeq->getLCUPara( m_frameLevel, i ).m_beta; } else { alphaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha; betaLCU = m_encRCSeq->getPicPara( m_frameLevel ).m_beta; } m_LCUs[i].m_bitWeight = m_LCUs[i].m_numberOfPixel * pow( estLambda/alphaLCU, 1.0/betaLCU ); if ( m_LCUs[i].m_bitWeight < 0.01 ) { m_LCUs[i].m_bitWeight = 0.01; } totalWeight += m_LCUs[i].m_bitWeight; } for ( int i=0; i<m_numberOfLCU; i++ ) { double BUTargetBits = m_targetBits * m_LCUs[i].m_bitWeight / totalWeight; m_LCUs[i].m_bitWeight = BUTargetBits; } return estLambda; } int EncRCPic::estimatePicQP( double lambda, list<EncRCPic*>& listPreviousPictures ) { int bitdepth_luma_scale = 2 * (m_encRCSeq->getbitDepth() - 8 - DISTORTION_PRECISION_ADJUSTMENT(m_encRCSeq->getbitDepth())); int QP = int(4.2005 * log(lambda / pow(2.0, bitdepth_luma_scale)) + 13.7122 + 0.5); int lastLevelQP = g_RCInvalidQPValue; int lastPicQP = g_RCInvalidQPValue; int lastValidQP = g_RCInvalidQPValue; list<EncRCPic*>::iterator it; for ( it = listPreviousPictures.begin(); it != listPreviousPictures.end(); it++ ) { if ( (*it)->getFrameLevel() == m_frameLevel ) { lastLevelQP = (*it)->getPicActualQP(); } lastPicQP = (*it)->getPicActualQP(); if ( lastPicQP > g_RCInvalidQPValue ) { lastValidQP = lastPicQP; } } if ( lastLevelQP > g_RCInvalidQPValue ) { QP = Clip3( lastLevelQP - 3, lastLevelQP + 3, QP ); } if( lastPicQP > g_RCInvalidQPValue ) { QP = Clip3( lastPicQP - 10, lastPicQP + 10, QP ); } else if( lastValidQP > g_RCInvalidQPValue ) { QP = Clip3( lastValidQP - 10, lastValidQP + 10, QP ); } return QP; } double EncRCPic::getLCUTargetBpp(bool isIRAP) { int LCUIdx = getLCUCoded(); double bpp = -1.0; int avgBits = 0; if (isIRAP) { int noOfLCUsLeft = m_numberOfLCU - LCUIdx + 1; int bitrateWindow = min(4,noOfLCUsLeft); double MAD = getLCU(LCUIdx).m_costIntra; if (m_remainingCostIntra > 0.1 ) { double weightedBitsLeft = (m_bitsLeft*bitrateWindow+(m_bitsLeft-getLCU(LCUIdx).m_targetBitsLeft)*noOfLCUsLeft)/(double)bitrateWindow; avgBits = int( MAD*weightedBitsLeft/m_remainingCostIntra ); } else { avgBits = int( m_bitsLeft / m_LCULeft ); } m_remainingCostIntra -= MAD; } else { double totalWeight = 0; for ( int i=LCUIdx; i<m_numberOfLCU; i++ ) { totalWeight += m_LCUs[i].m_bitWeight; } int realInfluenceLCU = min( g_RCLCUSmoothWindowSize, getLCULeft() ); avgBits = (int)( m_LCUs[LCUIdx].m_bitWeight - ( totalWeight - m_bitsLeft ) / realInfluenceLCU + 0.5 ); } if ( avgBits < 1 ) { avgBits = 1; } bpp = ( double )avgBits/( double )m_LCUs[ LCUIdx ].m_numberOfPixel; m_LCUs[ LCUIdx ].m_targetBits = avgBits; return bpp; } double EncRCPic::getLCUEstLambda( double bpp ) { int LCUIdx = getLCUCoded(); double alpha; double beta; if ( m_encRCSeq->getUseLCUSeparateModel() ) { alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha; beta = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta; } else { alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha; beta = m_encRCSeq->getPicPara( m_frameLevel ).m_beta; } double estLambda = alpha * pow( bpp, beta ); //for Lambda clip, picture level clip double clipPicLambda = m_estPicLambda; //for Lambda clip, LCU level clip double clipNeighbourLambda = -1.0; for ( int i=LCUIdx - 1; i>=0; i-- ) { if ( m_LCUs[i].m_lambda > 0 ) { clipNeighbourLambda = m_LCUs[i].m_lambda; break; } } if ( clipNeighbourLambda > 0.0 ) { estLambda = Clip3( clipNeighbourLambda * pow( 2.0, -1.0/3.0 ), clipNeighbourLambda * pow( 2.0, 1.0/3.0 ), estLambda ); } if ( clipPicLambda > 0.0 ) { estLambda = Clip3( clipPicLambda * pow( 2.0, -2.0/3.0 ), clipPicLambda * pow( 2.0, 2.0/3.0 ), estLambda ); } else { estLambda = Clip3( 10.0, 1000.0, estLambda ); } if ( estLambda < 0.1 ) { estLambda = 0.1; } //Avoid different results in different platforms. The problem is caused by the different results of pow() in different platforms. estLambda = double(int64_t(estLambda * (double)LAMBDA_PREC + 0.5)) / (double)LAMBDA_PREC; return estLambda; } int EncRCPic::getLCUEstQP( double lambda, int clipPicQP ) { int LCUIdx = getLCUCoded(); int bitdepth_luma_scale = 2 * (m_encRCSeq->getbitDepth() - 8 - DISTORTION_PRECISION_ADJUSTMENT(m_encRCSeq->getbitDepth())); int estQP = int(4.2005 * log(lambda / pow(2.0, bitdepth_luma_scale)) + 13.7122 + 0.5); //for Lambda clip, LCU level clip int clipNeighbourQP = g_RCInvalidQPValue; for ( int i=LCUIdx - 1; i>=0; i-- ) { if ( (getLCU(i)).m_QP > g_RCInvalidQPValue ) { clipNeighbourQP = getLCU(i).m_QP; break; } } if ( clipNeighbourQP > g_RCInvalidQPValue ) { estQP = Clip3( clipNeighbourQP - 1, clipNeighbourQP + 1, estQP ); } estQP = Clip3( clipPicQP - 2, clipPicQP + 2, estQP ); return estQP; } void EncRCPic::updateAfterCTU( int LCUIdx, int bits, int QP, double lambda, bool updateLCUParameter ) { m_LCUs[LCUIdx].m_actualBits = bits; m_LCUs[LCUIdx].m_QP = QP; m_LCUs[LCUIdx].m_lambda = lambda; m_LCUs[LCUIdx].m_actualSSE = m_LCUs[LCUIdx].m_actualMSE * m_LCUs[LCUIdx].m_numberOfPixel; m_LCULeft--; m_bitsLeft -= bits; m_pixelsLeft -= m_LCUs[LCUIdx].m_numberOfPixel; if ( !updateLCUParameter ) { return; } if ( !m_encRCSeq->getUseLCUSeparateModel() ) { return; } double alpha = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_alpha; double beta = m_encRCSeq->getLCUPara( m_frameLevel, LCUIdx ).m_beta; int LCUActualBits = m_LCUs[LCUIdx].m_actualBits; int LCUTotalPixels = m_LCUs[LCUIdx].m_numberOfPixel; double bpp = ( double )LCUActualBits/( double )LCUTotalPixels; double calLambda = alpha * pow( bpp, beta ); double inputLambda = m_LCUs[LCUIdx].m_lambda; if( inputLambda < 0.01 || calLambda < 0.01 || bpp < 0.0001 ) { alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 ); beta *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 ); alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha ); beta = Clip3( g_RCBetaMinValue, g_RCBetaMaxValue, beta ); TRCParameter rcPara; rcPara.m_alpha = alpha; rcPara.m_beta = beta; if (QP == g_RCInvalidQPValue && m_encRCSeq->getAdaptiveBits() == 1) { rcPara.m_validPix = 0; } else { rcPara.m_validPix = LCUTotalPixels; } double MSE = m_LCUs[LCUIdx].m_actualMSE; double updatedK = bpp * inputLambda / MSE; double updatedC = MSE / pow(bpp, -updatedK); rcPara.m_alpha = updatedC * updatedK; rcPara.m_beta = -updatedK - 1.0; if (bpp > 0 && updatedK > 0.0001) { m_encRCSeq->setLCUPara(m_frameLevel, LCUIdx, rcPara); } else { rcPara.m_alpha = Clip3(0.0001, g_RCAlphaMaxValue, rcPara.m_alpha); m_encRCSeq->setLCUPara(m_frameLevel, LCUIdx, rcPara); } return; } calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda ); alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha; double lnbpp = log( bpp ); lnbpp = Clip3( -5.0, -0.1, lnbpp ); beta += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp; alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha ); beta = Clip3( g_RCBetaMinValue, g_RCBetaMaxValue, beta ); TRCParameter rcPara; rcPara.m_alpha = alpha; rcPara.m_beta = beta; if (QP == g_RCInvalidQPValue && m_encRCSeq->getAdaptiveBits() == 1) { rcPara.m_validPix = 0; } else { rcPara.m_validPix = LCUTotalPixels; } double MSE = m_LCUs[LCUIdx].m_actualMSE; double updatedK = bpp * inputLambda / MSE; double updatedC = MSE / pow(bpp, -updatedK); rcPara.m_alpha = updatedC * updatedK; rcPara.m_beta = -updatedK - 1.0; if (bpp > 0 && updatedK > 0.0001) { m_encRCSeq->setLCUPara(m_frameLevel, LCUIdx, rcPara); } else { rcPara.m_alpha = Clip3(0.0001, g_RCAlphaMaxValue, rcPara.m_alpha); m_encRCSeq->setLCUPara(m_frameLevel, LCUIdx, rcPara); } } double EncRCPic::calAverageQP() { int totalQPs = 0; int numTotalLCUs = 0; int i; for ( i=0; i<m_numberOfLCU; i++ ) { if ( m_LCUs[i].m_QP > 0 ) { totalQPs += m_LCUs[i].m_QP; numTotalLCUs++; } } double avgQP = 0.0; if ( numTotalLCUs == 0 ) { avgQP = g_RCInvalidQPValue; } else { avgQP = ((double)totalQPs) / ((double)numTotalLCUs); } return avgQP; } double EncRCPic::calAverageLambda() { double totalLambdas = 0.0; int numTotalLCUs = 0; double totalSSE = 0.0; int totalPixels = 0; int i; for ( i=0; i<m_numberOfLCU; i++ ) { if ( m_LCUs[i].m_lambda > 0.01 ) { if (m_LCUs[i].m_QP > 0 || m_encRCSeq->getAdaptiveBits() != 1) { m_validPixelsInPic += m_LCUs[i].m_numberOfPixel; totalLambdas += log(m_LCUs[i].m_lambda); numTotalLCUs++; } if (m_LCUs[i].m_QP > 0 || m_encRCSeq->getAdaptiveBits() != 1) { totalSSE += m_LCUs[i].m_actualSSE; totalPixels += m_LCUs[i].m_numberOfPixel; } } } setPicMSE(totalPixels > 0 ? totalSSE / (double)totalPixels : 1.0); //1.0 is useless in the following process, just to make sure the divisor not be 0 double avgLambda; if( numTotalLCUs == 0 ) { avgLambda = -1.0; } else { avgLambda = pow( 2.7183, totalLambdas / numTotalLCUs ); } return avgLambda; } void EncRCPic::updateAfterPicture( int actualHeaderBits, int actualTotalBits, double averageQP, double averageLambda, bool isIRAP) { m_picActualHeaderBits = actualHeaderBits; m_picActualBits = actualTotalBits; if ( averageQP > 0.0 ) { m_picQP = int( averageQP + 0.5 ); } else { m_picQP = g_RCInvalidQPValue; } m_picLambda = averageLambda; double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha; double beta = m_encRCSeq->getPicPara( m_frameLevel ).m_beta; if (isIRAP) { updateAlphaBetaIntra(&alpha, &beta); } else { // update parameters double picActualBits = ( double )m_picActualBits; double picActualBpp = picActualBits / (double)m_validPixelsInPic; double calLambda = alpha * pow( picActualBpp, beta ); double inputLambda = m_picLambda; if ( inputLambda < 0.01 || calLambda < 0.01 || picActualBpp < 0.0001 ) { alpha *= ( 1.0 - m_encRCSeq->getAlphaUpdate() / 2.0 ); beta *= ( 1.0 - m_encRCSeq->getBetaUpdate() / 2.0 ); alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha ); beta = Clip3( g_RCBetaMinValue, g_RCBetaMaxValue, beta ); TRCParameter rcPara; rcPara.m_alpha = alpha; rcPara.m_beta = beta; double avgMSE = getPicMSE(); double updatedK = picActualBpp * averageLambda / avgMSE; double updatedC = avgMSE / pow(picActualBpp, -updatedK); if (m_frameLevel > 0) //only use for level > 0 { rcPara.m_alpha = updatedC * updatedK; rcPara.m_beta = -updatedK - 1.0; } rcPara.m_validPix = m_validPixelsInPic; if (m_validPixelsInPic > 0) { m_encRCSeq->setPicPara(m_frameLevel, rcPara); } return; } calLambda = Clip3( inputLambda / 10.0, inputLambda * 10.0, calLambda ); alpha += m_encRCSeq->getAlphaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * alpha; double lnbpp = log( picActualBpp ); lnbpp = Clip3( -5.0, -0.1, lnbpp ); beta += m_encRCSeq->getBetaUpdate() * ( log( inputLambda ) - log( calLambda ) ) * lnbpp; alpha = Clip3( g_RCAlphaMinValue, g_RCAlphaMaxValue, alpha ); beta = Clip3( g_RCBetaMinValue, g_RCBetaMaxValue, beta ); } TRCParameter rcPara; rcPara.m_alpha = alpha; rcPara.m_beta = beta; double picActualBpp = (double)m_picActualBits / (double)m_validPixelsInPic; double avgMSE = getPicMSE(); double updatedK = picActualBpp * averageLambda / avgMSE; double updatedC = avgMSE / pow(picActualBpp, -updatedK); if (m_frameLevel > 0) //only use for level > 0 { rcPara.m_alpha = updatedC * updatedK; rcPara.m_beta = -updatedK - 1.0; } rcPara.m_validPix = m_validPixelsInPic; if (m_validPixelsInPic > 0) { m_encRCSeq->setPicPara(m_frameLevel, rcPara); } if ( m_frameLevel == 1 ) { double currLambda = Clip3( 0.1, 10000.0, m_picLambda ); double updateLastLambda = g_RCWeightHistoryLambda * m_encRCSeq->getLastLambda() + g_RCWeightCurrentLambda * currLambda; m_encRCSeq->setLastLambda( updateLastLambda ); } } int EncRCPic::getRefineBitsForIntra( int orgBits ) { double alpha=0.25, beta=0.5582; int iIntraBits; if (orgBits*40 < m_numberOfPixel) { alpha=0.25; } else { alpha=0.30; } iIntraBits = (int)(alpha* pow(m_totalCostIntra*4.0/(double)orgBits, beta)*(double)orgBits+0.5); return iIntraBits; } double EncRCPic::calculateLambdaIntra(double alpha, double beta, double MADPerPixel, double bitsPerPixel) { return ( (alpha/256.0) * pow( MADPerPixel/bitsPerPixel, beta ) ); } void EncRCPic::updateAlphaBetaIntra(double *alpha, double *beta) { double lnbpp = log(pow(m_totalCostIntra / (double)m_numberOfPixel, BETA1)); double diffLambda = (*beta)*(log((double)m_picActualBits)-log((double)m_targetBits)); diffLambda = Clip3(-0.125, 0.125, 0.25*diffLambda); *alpha = (*alpha) * exp(diffLambda); *beta = (*beta) + diffLambda / lnbpp; } void EncRCPic::getLCUInitTargetBits() { int iAvgBits = 0; m_remainingCostIntra = m_totalCostIntra; for (int i=m_numberOfLCU-1; i>=0; i--) { iAvgBits += int(m_targetBits * getLCU(i).m_costIntra/m_totalCostIntra); getLCU(i).m_targetBitsLeft = iAvgBits; } } double EncRCPic::getLCUEstLambdaAndQP(double bpp, int clipPicQP, int *estQP) { int LCUIdx = getLCUCoded(); double alpha = m_encRCSeq->getPicPara( m_frameLevel ).m_alpha; double beta = m_encRCSeq->getPicPara( m_frameLevel ).m_beta; double costPerPixel = getLCU(LCUIdx).m_costIntra/(double)getLCU(LCUIdx).m_numberOfPixel; costPerPixel = pow(costPerPixel, BETA1); double estLambda = calculateLambdaIntra(alpha, beta, costPerPixel, bpp); int clipNeighbourQP = g_RCInvalidQPValue; for (int i=LCUIdx-1; i>=0; i--) { if ((getLCU(i)).m_QP > g_RCInvalidQPValue) { clipNeighbourQP = getLCU(i).m_QP; break; } } int minQP = clipPicQP - 2; int maxQP = clipPicQP + 2; if ( clipNeighbourQP > g_RCInvalidQPValue ) { maxQP = min(clipNeighbourQP + 1, maxQP); minQP = max(clipNeighbourQP - 1, minQP); } int bitdepth_luma_scale = 2 * (m_encRCSeq->getbitDepth() - 8 - DISTORTION_PRECISION_ADJUSTMENT(m_encRCSeq->getbitDepth())); double maxLambda = exp(((double)(maxQP + 0.49) - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); double minLambda = exp(((double)(minQP - 0.49) - 13.7122) / 4.2005) * pow(2.0, bitdepth_luma_scale); estLambda = Clip3(minLambda, maxLambda, estLambda); //Avoid different results in different platforms. The problem is caused by the different results of pow() in different platforms. estLambda = double(int64_t(estLambda * (double)LAMBDA_PREC + 0.5)) / (double)LAMBDA_PREC; *estQP = int(4.2005 * log(estLambda / pow(2.0, bitdepth_luma_scale)) + 13.7122 + 0.5); *estQP = Clip3(minQP, maxQP, *estQP); return estLambda; } RateCtrl::RateCtrl() { m_encRCSeq = NULL; m_encRCGOP = NULL; m_encRCPic = NULL; } RateCtrl::~RateCtrl() { destroy(); } void RateCtrl::destroy() { if ( m_encRCSeq != NULL ) { delete m_encRCSeq; m_encRCSeq = NULL; } if ( m_encRCGOP != NULL ) { delete m_encRCGOP; m_encRCGOP = NULL; } while ( m_listRCPictures.size() > 0 ) { EncRCPic* p = m_listRCPictures.front(); m_listRCPictures.pop_front(); delete p; } } void RateCtrl::init(int totalFrames, int targetBitrate, int frameRate, int GOPSize, int picWidth, int picHeight, int LCUWidth, int LCUHeight, int bitDepth, int keepHierBits, bool useLCUSeparateModel, GOPEntry GOPList[MAX_GOP]) { destroy(); bool isLowdelay = true; for ( int i=0; i<GOPSize-1; i++ ) { if ( GOPList[i].m_POC > GOPList[i+1].m_POC ) { isLowdelay = false; break; } } int numberOfLevel = 1; int adaptiveBit = 0; if ( keepHierBits > 0 ) { numberOfLevel = int( log((double)GOPSize)/log(2.0) + 0.5 ) + 1; } if (!isLowdelay && (GOPSize == 16 || GOPSize == 8)) { numberOfLevel = int( log((double)GOPSize)/log(2.0) + 0.5 ) + 1; } numberOfLevel++; // intra picture numberOfLevel++; // non-reference picture int* bitsRatio; bitsRatio = new int[ GOPSize ]; for ( int i=0; i<GOPSize; i++ ) { bitsRatio[i] = 10; if ( !GOPList[i].m_refPic ) { bitsRatio[i] = 2; } } if ( keepHierBits > 0 ) { double bpp = (double)( targetBitrate / (double)( frameRate*picWidth*picHeight ) ); if ( GOPSize == 4 && isLowdelay ) { if ( bpp > 0.2 ) { bitsRatio[0] = 2; bitsRatio[1] = 3; bitsRatio[2] = 2; bitsRatio[3] = 6; } else if( bpp > 0.1 ) { bitsRatio[0] = 2; bitsRatio[1] = 3; bitsRatio[2] = 2; bitsRatio[3] = 10; } else if ( bpp > 0.05 ) { bitsRatio[0] = 2; bitsRatio[1] = 3; bitsRatio[2] = 2; bitsRatio[3] = 12; } else { bitsRatio[0] = 2; bitsRatio[1] = 3; bitsRatio[2] = 2; bitsRatio[3] = 14; } if ( keepHierBits == 2 ) { adaptiveBit = 1; } } else if ( GOPSize == 8 && !isLowdelay ) { if ( bpp > 0.2 ) { bitsRatio[0] = 15; bitsRatio[1] = 5; bitsRatio[2] = 4; bitsRatio[3] = 1; bitsRatio[4] = 1; bitsRatio[5] = 4; bitsRatio[6] = 1; bitsRatio[7] = 1; } else if ( bpp > 0.1 ) { bitsRatio[0] = 20; bitsRatio[1] = 6; bitsRatio[2] = 4; bitsRatio[3] = 1; bitsRatio[4] = 1; bitsRatio[5] = 4; bitsRatio[6] = 1; bitsRatio[7] = 1; } else if ( bpp > 0.05 ) { bitsRatio[0] = 25; bitsRatio[1] = 7; bitsRatio[2] = 4; bitsRatio[3] = 1; bitsRatio[4] = 1; bitsRatio[5] = 4; bitsRatio[6] = 1; bitsRatio[7] = 1; } else { bitsRatio[0] = 30; bitsRatio[1] = 8; bitsRatio[2] = 4; bitsRatio[3] = 1; bitsRatio[4] = 1; bitsRatio[5] = 4; bitsRatio[6] = 1; bitsRatio[7] = 1; } if ( keepHierBits == 2 ) { adaptiveBit = 2; } } else if (GOPSize == 16 && !isLowdelay) { if (bpp > 0.2) { bitsRatio[0] = 10; bitsRatio[1] = 8; bitsRatio[2] = 4; bitsRatio[3] = 2; bitsRatio[4] = 1; bitsRatio[5] = 1; bitsRatio[6] = 2; bitsRatio[7] = 1; bitsRatio[8] = 1; bitsRatio[9] = 4; bitsRatio[10] = 2; bitsRatio[11] = 1; bitsRatio[12] = 1; bitsRatio[13] = 2; bitsRatio[14] = 1; bitsRatio[15] = 1; } else if (bpp > 0.1) { bitsRatio[0] = 15; bitsRatio[1] = 9; bitsRatio[2] = 4; bitsRatio[3] = 2; bitsRatio[4] = 1; bitsRatio[5] = 1; bitsRatio[6] = 2; bitsRatio[7] = 1; bitsRatio[8] = 1; bitsRatio[9] = 4; bitsRatio[10] = 2; bitsRatio[11] = 1; bitsRatio[12] = 1; bitsRatio[13] = 2; bitsRatio[14] = 1; bitsRatio[15] = 1; } else if (bpp > 0.05) { bitsRatio[0] = 40; bitsRatio[1] = 17; bitsRatio[2] = 7; bitsRatio[3] = 2; bitsRatio[4] = 1; bitsRatio[5] = 1; bitsRatio[6] = 2; bitsRatio[7] = 1; bitsRatio[8] = 1; bitsRatio[9] = 7; bitsRatio[10] = 2; bitsRatio[11] = 1; bitsRatio[12] = 1; bitsRatio[13] = 2; bitsRatio[14] = 1; bitsRatio[15] = 1; } else { bitsRatio[0] = 40; bitsRatio[1] = 15; bitsRatio[2] = 6; bitsRatio[3] = 3; bitsRatio[4] = 1; bitsRatio[5] = 1; bitsRatio[6] = 3; bitsRatio[7] = 1; bitsRatio[8] = 1; bitsRatio[9] = 6; bitsRatio[10] = 3; bitsRatio[11] = 1; bitsRatio[12] = 1; bitsRatio[13] = 3; bitsRatio[14] = 1; bitsRatio[15] = 1; } if (keepHierBits == 2) { adaptiveBit = 3; } } else { msg( WARNING, "\n hierarchical bit allocation is not support for the specified coding structure currently.\n" ); } } int* GOPID2Level = new int[ GOPSize ]; for ( int i=0; i<GOPSize; i++ ) { GOPID2Level[i] = 1; if ( !GOPList[i].m_refPic ) { GOPID2Level[i] = 2; } } if ( keepHierBits > 0 ) { if ( GOPSize == 4 && isLowdelay ) { GOPID2Level[0] = 3; GOPID2Level[1] = 2; GOPID2Level[2] = 3; GOPID2Level[3] = 1; } else if ( GOPSize == 8 && !isLowdelay ) { GOPID2Level[0] = 1; GOPID2Level[1] = 2; GOPID2Level[2] = 3; GOPID2Level[3] = 4; GOPID2Level[4] = 4; GOPID2Level[5] = 3; GOPID2Level[6] = 4; GOPID2Level[7] = 4; } else if (GOPSize == 16 && !isLowdelay) { GOPID2Level[0] = 1; GOPID2Level[1] = 2; GOPID2Level[2] = 3; GOPID2Level[3] = 4; GOPID2Level[4] = 5; GOPID2Level[5] = 5; GOPID2Level[6] = 4; GOPID2Level[7] = 5; GOPID2Level[8] = 5; GOPID2Level[9] = 3; GOPID2Level[10] = 4; GOPID2Level[11] = 5; GOPID2Level[12] = 5; GOPID2Level[13] = 4; GOPID2Level[14] = 5; GOPID2Level[15] = 5; } } if ( !isLowdelay && GOPSize == 8 ) { GOPID2Level[0] = 1; GOPID2Level[1] = 2; GOPID2Level[2] = 3; GOPID2Level[3] = 4; GOPID2Level[4] = 4; GOPID2Level[5] = 3; GOPID2Level[6] = 4; GOPID2Level[7] = 4; } else if (GOPSize == 16 && !isLowdelay) { GOPID2Level[0] = 1; GOPID2Level[1] = 2; GOPID2Level[2] = 3; GOPID2Level[3] = 4; GOPID2Level[4] = 5; GOPID2Level[5] = 5; GOPID2Level[6] = 4; GOPID2Level[7] = 5; GOPID2Level[8] = 5; GOPID2Level[9] = 3; GOPID2Level[10] = 4; GOPID2Level[11] = 5; GOPID2Level[12] = 5; GOPID2Level[13] = 4; GOPID2Level[14] = 5; GOPID2Level[15] = 5; } m_encRCSeq = new EncRCSeq; m_encRCSeq->create( totalFrames, targetBitrate, frameRate, GOPSize, picWidth, picHeight, LCUWidth, LCUHeight, numberOfLevel, useLCUSeparateModel, adaptiveBit ); m_encRCSeq->initBitsRatio( bitsRatio ); m_encRCSeq->initGOPID2Level( GOPID2Level ); m_encRCSeq->setBitDepth(bitDepth); m_encRCSeq->initPicPara(); if ( useLCUSeparateModel ) { m_encRCSeq->initLCUPara(); } #if U0132_TARGET_BITS_SATURATION m_CpbSaturationEnabled = false; m_cpbSize = targetBitrate; m_cpbState = (uint32_t)(m_cpbSize*0.5f); m_bufferingRate = (int)(targetBitrate / frameRate); #endif delete[] bitsRatio; delete[] GOPID2Level; } void RateCtrl::initRCPic( int frameLevel ) { m_encRCPic = new EncRCPic; m_encRCPic->create( m_encRCSeq, m_encRCGOP, frameLevel, m_listRCPictures ); } void RateCtrl::initRCGOP( int numberOfPictures ) { m_encRCGOP = new EncRCGOP; m_encRCGOP->create( m_encRCSeq, numberOfPictures ); } #if U0132_TARGET_BITS_SATURATION int RateCtrl::updateCpbState(int actualBits) { int cpbState = 1; m_cpbState -= actualBits; if (m_cpbState < 0) { cpbState = -1; } m_cpbState += m_bufferingRate; if (m_cpbState > m_cpbSize) { cpbState = 0; } return cpbState; } void RateCtrl::initHrdParam(const HRD* pcHrd, int iFrameRate, double fInitialCpbFullness) { m_CpbSaturationEnabled = true; m_cpbSize = (pcHrd->getCpbSizeValueMinus1(0, 0, 0) + 1) << (4 + pcHrd->getCpbSizeScale()); m_cpbState = (uint32_t)(m_cpbSize*fInitialCpbFullness); m_bufferingRate = (uint32_t)(((pcHrd->getBitRateValueMinus1(0, 0, 0) + 1) << (6 + pcHrd->getBitRateScale())) / iFrameRate); msg( NOTICE, "\nHRD - [Initial CPB state %6d] [CPB Size %6d] [Buffering Rate %6d]\n", m_cpbState, m_cpbSize, m_bufferingRate); } #endif void RateCtrl::destroyRCGOP() { delete m_encRCGOP; m_encRCGOP = NULL; }
#include "EpisodeListView.h" #include "SubscriptionColumn.h" #include "MyColumnTypes.h" #include <Box.h> #include <Catalog.h> #include <ControlLook.h> #include <ScrollBar.h> #include <StringFormat.h> #include <Window.h> #include "EpisodeListItem.h" #include "FileStatusColumn.h" #include "Colors.h" #include "StatusView.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "DL-Episode-ListView" EpisodeListView::EpisodeListView(BRect r): BColumnListView(r,"EpisodeListView",B_FOLLOW_ALL, B_WILL_DRAW|B_NAVIGABLE,B_NO_BORDER,true) { BColumn *icon = new BBitmapColumn(B_TRANSLATE("Icon"),16,16,16,B_ALIGN_CENTER); BColumn *title = new BStringColumn(B_TRANSLATE("Title"),140,10,500,B_TRUNCATE_MIDDLE,B_ALIGN_LEFT); BColumn *date = new BPositiveDateColumn(B_TRANSLATE("Date"),70,10,250,B_ALIGN_LEFT); BColumn *size = new BPositiveSizeColumn(B_TRANSLATE("Size"),80,10,150,B_ALIGN_LEFT); int index = 0; AddColumn(icon,index++); AddColumn(title,index++); AddColumn(date,index++); AddColumn(size,index++); AddColumn(new FileStatusColumn(B_TRANSLATE("Status"),200,110,400,0,B_ALIGN_LEFT),index++); SetColumnFlags((column_flags)(B_ALLOW_COLUMN_REMOVE|B_ALLOW_COLUMN_RESIZE|B_ALLOW_COLUMN_POPUP|B_ALLOW_COLUMN_MOVE)); SetSelectionMode(B_MULTIPLE_SELECTION_LIST); SetSortingEnabled(true); SetSortColumn(date,false,false); BScrollBar* scrollBar = (BScrollBar*)FindView("horizontal_scroll_bar"); AddStatusView(fStatusView=new StatusView(scrollBar)); } void EpisodeListView::SelectionChanged(){ uint32 buttons = 0; BMessage *msg = Window()->CurrentMessage(); if(msg) //don't remove. msg->FindInt32("buttons", (int32 *)&buttons) ; if(SelectionMessage()) SelectionMessage()->ReplaceInt32("buttons",buttons); // EpisodeListItem* sel = (EpisodeListItem*)CurrentSelection(); // SelectionMessage()->RemoveName("entry_ref"); // SelectionMessage()->AddRef("entry_ref",&sel->fRef); BColumnListView::SelectionChanged(); } void EpisodeListView::AddRow(BRow* row, BRow *parent){ BColumnListView::AddRow(row,parent); ExpandOrCollapse(row, true); UpdateCount(); } void EpisodeListView::RemoveRow(BRow* row){ BColumnListView::RemoveRow(row); UpdateCount(); } void EpisodeListView::AddRow(BRow* row, int32 index, BRow *parent){ BColumnListView::AddRow(row,index,parent); ExpandOrCollapse(row, true); UpdateCount(); } void EpisodeListView::Clear(){ BColumnListView::Clear(); UpdateCount(); } void EpisodeListView::UpdateCount(){ BString text; static BStringFormat format(B_TRANSLATE("{0, plural," "=0{no episodes}" "=1{1 episode}" "other{# episodes}}")); format.Format(text, CountRows()); fStatusView->Update(text, "", ""); } //--
/*! * Copyright (c) 2017 by Contributors * \file opencl_device_api.cc */ #include "./opencl_common.h" #if TVM_OPENCL_RUNTIME #include <tvm/runtime/registry.h> #include <dmlc/thread_local.h> namespace tvm { namespace runtime { namespace cl { const std::shared_ptr<OpenCLWorkspace>& OpenCLWorkspace::Global() { static std::shared_ptr<OpenCLWorkspace> inst = std::make_shared<OpenCLWorkspace>(); return inst; } void OpenCLWorkspace::SetDevice(TVMContext ctx) { OpenCLThreadEntry::ThreadLocal()->context.device_id = ctx.device_id; } void OpenCLWorkspace::GetAttr( TVMContext ctx, DeviceAttrKind kind, TVMRetValue* rv) { this->Init(); size_t index = static_cast<size_t>(ctx.device_id); if (kind == kExist) { *rv = static_cast<int>(index< devices.size()); return; } CHECK_LT(index, devices.size()) << "Invalid device id " << index; size_t value; switch (kind) { case kMaxThreadsPerBlock: { OPENCL_CALL(clGetDeviceInfo( devices[index], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof(size_t), &value, nullptr)); *rv = static_cast<int64_t>(value); break; } case kWarpSize: { *rv = 1; break; } case kComputeVersion: return; case kExist: break; } } void* OpenCLWorkspace::AllocDataSpace( TVMContext ctx, size_t size, size_t alignment) { this->Init(); CHECK(context != nullptr) << "No OpenCL device"; cl_int err_code; cl_mem mptr = clCreateBuffer( this->context, CL_MEM_READ_WRITE, size, nullptr, &err_code); OPENCL_CHECK_ERROR(err_code); return mptr; } void OpenCLWorkspace::FreeDataSpace(TVMContext ctx, void* ptr) { cl_mem mptr = static_cast<cl_mem>(ptr); OPENCL_CALL(clReleaseMemObject(mptr)); } void OpenCLWorkspace::CopyDataFromTo(const void* from, size_t from_offset, void* to, size_t to_offset, size_t size, TVMContext ctx_from, TVMContext ctx_to, TVMStreamHandle stream) { this->Init(); CHECK(stream == nullptr); if (ctx_from.device_type == kOpenCL && ctx_to.device_type == kOpenCL) { OPENCL_CALL(clEnqueueCopyBuffer( this->GetQueue(ctx_to), static_cast<cl_mem>((void*)from), // NOLINT(*) static_cast<cl_mem>(to), from_offset, to_offset, size, 0, nullptr, nullptr)); } else if (ctx_from.device_type == kOpenCL && ctx_to.device_type == kCPU) { OPENCL_CALL(clEnqueueReadBuffer( this->GetQueue(ctx_from), static_cast<cl_mem>((void*)from), // NOLINT(*) CL_FALSE, from_offset, size, static_cast<char*>(to) + to_offset, 0, nullptr, nullptr)); OPENCL_CALL(clFinish(this->GetQueue(ctx_from))); } else if (ctx_from.device_type == kCPU && ctx_to.device_type == kOpenCL) { OPENCL_CALL(clEnqueueWriteBuffer( this->GetQueue(ctx_to), static_cast<cl_mem>(to), CL_FALSE, to_offset, size, static_cast<const char*>(from) + from_offset, 0, nullptr, nullptr)); OPENCL_CALL(clFinish(this->GetQueue(ctx_to))); } else { LOG(FATAL) << "Expect copy from/to OpenCL or between OpenCL"; } } void OpenCLWorkspace::StreamSync(TVMContext ctx, TVMStreamHandle stream) { CHECK(stream == nullptr); OPENCL_CALL(clFinish(this->GetQueue(ctx))); } void* OpenCLWorkspace::AllocWorkspace(TVMContext ctx, size_t size) { return OpenCLThreadEntry::ThreadLocal()->pool.AllocWorkspace(ctx, size); } void OpenCLWorkspace::FreeWorkspace(TVMContext ctx, void* data) { OpenCLThreadEntry::ThreadLocal()->pool.FreeWorkspace(ctx, data); } typedef dmlc::ThreadLocalStore<OpenCLThreadEntry> OpenCLThreadStore; OpenCLThreadEntry* OpenCLThreadEntry::ThreadLocal() { return OpenCLThreadStore::Get(); } std::string GetPlatformInfo( cl_platform_id pid, cl_platform_info param_name) { size_t ret_size; OPENCL_CALL(clGetPlatformInfo(pid, param_name, 0, nullptr, &ret_size)); std::string ret; ret.resize(ret_size); OPENCL_CALL(clGetPlatformInfo(pid, param_name, ret_size, &ret[0], nullptr)); return ret; } std::string GetDeviceInfo( cl_device_id pid, cl_device_info param_name) { size_t ret_size; OPENCL_CALL(clGetDeviceInfo(pid, param_name, 0, nullptr, &ret_size)); std::string ret; ret.resize(ret_size); OPENCL_CALL(clGetDeviceInfo(pid, param_name, ret_size, &ret[0], nullptr)); return ret; } std::vector<cl_platform_id> GetPlatformIDs() { cl_uint ret_size; cl_int code = clGetPlatformIDs(0, nullptr, &ret_size); std::vector<cl_platform_id> ret; if (code != CL_SUCCESS) return ret; ret.resize(ret_size); OPENCL_CALL(clGetPlatformIDs(ret_size, &ret[0], nullptr)); return ret; } std::vector<cl_device_id> GetDeviceIDs( cl_platform_id pid, std::string device_type) { cl_device_type dtype = CL_DEVICE_TYPE_ALL; if (device_type == "cpu") dtype = CL_DEVICE_TYPE_CPU; if (device_type == "gpu") dtype = CL_DEVICE_TYPE_GPU; if (device_type == "accelerator") dtype = CL_DEVICE_TYPE_ACCELERATOR; cl_uint ret_size; cl_int code = clGetDeviceIDs(pid, dtype, 0, nullptr, &ret_size); std::vector<cl_device_id> ret; if (code != CL_SUCCESS) return ret; ret.resize(ret_size); OPENCL_CALL(clGetDeviceIDs(pid, dtype, ret_size, &ret[0], nullptr)); return ret; } bool MatchPlatformInfo( cl_platform_id pid, cl_platform_info param_name, std::string value) { if (value.length() == 0) return true; std::string param_value = GetPlatformInfo(pid, param_name); return param_value.find(value) != std::string::npos; } void OpenCLWorkspace::Init() { if (initialized_) return; std::lock_guard<std::mutex>(this->mu); if (initialized_) return; initialized_ = true; if (context != nullptr) return; // matched platforms std::vector<cl_platform_id> platform_matched = cl::GetPlatformIDs(); if (platform_matched.size() == 0) { LOG(WARNING) << "No OpenCL platform matched given existing options ..."; return; } if (platform_matched.size() > 1) { LOG(WARNING) << "Multiple OpenCL platforms matched, use the first one ... "; } this->platform_id = platform_matched[0]; LOG(INFO) << "Initialize OpenCL platform \'" << cl::GetPlatformInfo(this->platform_id, CL_PLATFORM_NAME) << '\''; std::vector<cl_device_id> devices_matched = cl::GetDeviceIDs(this->platform_id, "gpu"); if (devices_matched.size() == 0) { LOG(WARNING) << "No OpenCL device any device matched given the options"; return; } this->devices = devices_matched; cl_int err_code; this->context = clCreateContext( nullptr, this->devices.size(), &(this->devices[0]), nullptr, nullptr, &err_code); OPENCL_CHECK_ERROR(err_code); CHECK_EQ(this->queues.size(), 0U); for (size_t i = 0; i < this->devices.size(); ++i) { cl_device_id did = this->devices[i]; this->queues.push_back( clCreateCommandQueue(this->context, did, 0, &err_code)); OPENCL_CHECK_ERROR(err_code); LOG(INFO) << "opencl(" << i << ")=\'" << cl::GetDeviceInfo(did, CL_DEVICE_NAME) << "\' cl_device_id=" << did; } } bool InitOpenCL(TVMArgs args, TVMRetValue* rv) { cl::OpenCLWorkspace::Global()->Init(); return true; } TVM_REGISTER_GLOBAL("device_api.opencl") .set_body([](TVMArgs args, TVMRetValue* rv) { DeviceAPI* ptr = OpenCLWorkspace::Global().get(); *rv = static_cast<void*>(ptr); }); } // namespace cl } // namespace runtime } // namespace tvm #endif // TVM_OPENCL_RUNTIME
/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2014--2015 */ /* V0p2 boards physical actuator support. */ #include <stdint.h> #include <limits.h> #include <util/atomic.h> #include <Wire.h> // Arduino I2C library. #include "Actuator.h" #include "V0p2_Main.h" #include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers. #include "V0p2_Actuators.h" // I/O code access. #include "Serial_IO.h" #include "Power_Management.h" #ifdef DIRECT_MOTOR_DRIVE_V1 // Call to actually run/stop low-level motor. // May take as much as 200ms eg to change direction. // Stopping (removing power) should typically be very fast, << 100ms. void ValveMotorDirectV1HardwareDriver::motorRun(const motor_drive dir) { // *** MUST NEVER HAVE L AND R LOW AT THE SAME TIME else board may be destroyed at worst. *** // Operates as quickly as reasonably possible, eg to move to stall detection quickly... // TODO: consider making atomic to block some interrupt-related accidents... // TODO: note that the mapping between L/R and open/close not yet defined. // DHD20150205: 1st cut REV7 all-in-in-valve, seen looking down from valve into base, cw => close (ML=HIGH), ccw = open (MR=HIGH). switch(dir) { case motorDriveClosing: { // Pull one side high immediately *FIRST* for safety. // Stops motor if other side is not already low. // (Has no effect if motor is already running in the correct direction.) fastDigitalWrite(MOTOR_DRIVE_ML, HIGH); pinMode(MOTOR_DRIVE_ML, OUTPUT); // Ensure that the HIGH side is an output (can be done after, as else will be safe weak pull-up). nap(WDTO_120MS); // Let H-bridge respond and settle, and motor slow down. pinMode(MOTOR_DRIVE_MR, OUTPUT); // Ensure that the LOW side is an output. fastDigitalWrite(MOTOR_DRIVE_MR, LOW); // Pull LOW last. nap(WDTO_15MS); // Let H-bridge respond and settle. //LED_HEATCALL_ON(); //LED_UI2_OFF(); break; // Fall through to common case. } case motorDriveOpening: { // Pull one side high immediately *FIRST* for safety. // Stops motor if other side is not already low. // (Has no effect if motor is already running in the correct direction.) fastDigitalWrite(MOTOR_DRIVE_MR, HIGH); pinMode(MOTOR_DRIVE_MR, OUTPUT); // Ensure that the HIGH side is an output (can be done after, as else will be safe weak pull-up). nap(WDTO_120MS); // Let H-bridge respond and settle, and motor slow down. pinMode(MOTOR_DRIVE_ML, OUTPUT); // Ensure that the LOW side is an output. fastDigitalWrite(MOTOR_DRIVE_ML, LOW); // Pull LOW last. nap(WDTO_15MS); // Let H-bridge respond and settle. //LED_HEATCALL_OFF(); //LED_UI2_ON(); break; // Fall through to common case. } case motorOff: default: // Explicit off, and default for safety. { // Everything off... fastDigitalWrite(MOTOR_DRIVE_MR, HIGH); // Belt and braces force pin logical output state high. pinMode(MOTOR_DRIVE_MR, INPUT_PULLUP); // Switch to weak pull-up; slow but possibly marginally safer. nap(WDTO_15MS); // Let H-bridge respond and settle. fastDigitalWrite(MOTOR_DRIVE_ML, HIGH); // Belt and braces force pin logical output state high. pinMode(MOTOR_DRIVE_ML, INPUT_PULLUP); // Switch to weak pull-up; slow but possibly marginally safer. nap(WDTO_15MS); // Let H-bridge respond and settle. return; // Return, not fall through. } } } #define MI_NEEDS_ADC // Defined if MI output swing is not enough to use fast comparator. // Enable/disable end-stop detection and shaft-encoder. // Disabling should usually forces the motor off, // with a small pause for any residual movement to complete. void ValveMotorDirectV1HardwareDriver::enableFeedback(const bool enable, HardwareMotorDriverInterfaceCallbackHandler &callback) { // Check for high motor current indicating hitting an end-stop. #if !defined(MI_NEEDS_ADC) const bool currentSense = analogueVsBandgapRead(MOTOR_DRIVE_MI_AIN, true); #else // Measure motor current against (fixed) internal reference. const uint16_t mi = analogueNoiseReducedRead(MOTOR_DRIVE_MI_AIN, INTERNAL); const uint16_t miHigh = 250; // Typical *start* current 430 observed at 2.4V, REV7 board DHD20150205 (370@2.0V, 550@3.3V). const bool currentSense = (mi > miHigh) && // Recheck the value read in case spiky. (analogueNoiseReducedRead(MOTOR_DRIVE_MI_AIN, INTERNAL) > miHigh) && (analogueNoiseReducedRead(MOTOR_DRIVE_MI_AIN, INTERNAL) > miHigh); if(mi > ((3*miHigh)/4)) { DEBUG_SERIAL_PRINT(mi); DEBUG_SERIAL_PRINTLN(); } #endif if(currentSense) { LED_UI2_ON(); } else { LED_UI2_OFF(); } if(currentSense) { callback.signalHittingEndStop(); } } // Actuator/driver for direct local (radiator) valve motor control. uint8_t ValveMotorDirectV1::read() { // Call the generic read() first. // AbstractCurrentSenseValveMotorDirectV1::read(); // TODO } //#if 1 && defined(ALT_MAIN_LOOP) && defined(DEBUG) //// Drive motor back and forth (toggle direction each call) just for testing/fun. //void ValveMotorDirectV1::flip() // { // static bool open; // open = !open; // motorDrive(open ? motorDriveOpening : motorDriveClosing); // } //#endif // Minimally wiggles the motor to give tactile feedback and/or show to be working. // Does not itself track movement against shaft encoder, etc, or check for stall. // May take a significant fraction of a second. // Finishes with the motor turned off. void ValveMotorDirectV1::wiggle() { // motorDrive(motorOff); // motorDrive(motorDriveOpening); // nap(WDTO_120MS); // motorDrive(motorDriveClosing); // nap(WDTO_120MS); // motorDrive(motorOff); } //// Turn motor off, or on for a given drive direction. //// This routine is very careful to avoid setting outputs into any illegal/'bad' state. //// Sets flags accordingly. //// Does not provide any monitoring of stall, position encoding, etc. //// May take significant time (~150ms) to gently stop motor. //void ValveMotorDirectV1::motorDrive(const motor_drive dir) // { // // *** MUST NEVER HAVE L AND R LOW AT THE SAME TIME else board may be destroyed at worst. *** // // Operates as quickly as reasonably possible, eg to move to stall detection quickly... // // TODO: consider making atomic to block some interrupt-related accidents... // // TODO: note that the mapping between L/R and open/close not yet defined. // switch(dir) // { // case motorDriveOpening: // { // fastDigitalWrite(MOTOR_DRIVE_ML, HIGH); // Pull one side high immediately *FIRST* for safety. // nap(WDTO_120MS); // Let H-bridge respond and settle, and motor slow down. // pinMode(MOTOR_DRIVE_MR, OUTPUT); // Ensure that the LOW side is an output. // fastDigitalWrite(MOTOR_DRIVE_MR, LOW); // Pull other side side low after. // nap(WDTO_15MS); // Let H-bridge respond and settle. ////LED_HEATCALL_ON(); ////LED_UI2_OFF(); // break; // Fall through to common case. // } // // case motorDriveClosing: // { // fastDigitalWrite(MOTOR_DRIVE_MR, HIGH); // Pull one side high immediately *FIRST* for safety. // nap(WDTO_120MS); // Let H-bridge respond and settle, and motor slow down. // pinMode(MOTOR_DRIVE_ML, OUTPUT); // Ensure that the LOW side is an output. // fastDigitalWrite(MOTOR_DRIVE_ML, LOW); // Pull other side side low after. // nap(WDTO_15MS); // Let H-bridge respond and settle. ////LED_HEATCALL_OFF(); ////LED_UI2_ON(); // break; // Fall through to common case. // } // // case motorOff: default: // Explicit off, and default for safety. // { // // Everything off... // fastDigitalWrite(MOTOR_DRIVE_MR, HIGH); // Belt and braces force pin logical output state high. // pinMode(MOTOR_DRIVE_MR, INPUT_PULLUP); // Switch to weak pull-up; slow but possibly marginally safer. // nap(WDTO_15MS); // Let H-bridge respond and settle. // fastDigitalWrite(MOTOR_DRIVE_ML, HIGH); // Belt and braces force pin logical output state high. // pinMode(MOTOR_DRIVE_ML, INPUT_PULLUP); // Switch to weak pull-up; slow but possibly marginally safer. // nap(WDTO_15MS); // Let H-bridge respond and settle. // motorDriveStatus = motorOff; // Ensure value state even if 'dir' invalid. // return; // Return, not fall through. // } // } // // // If state has changed to new 'active' state, // // force both lines to outputs (which may be relatively slow) // // and update this instance's state. // if(motorDriveStatus != dir) // { // pinMode(MOTOR_DRIVE_ML, OUTPUT); // pinMode(MOTOR_DRIVE_MR, OUTPUT); // motorDriveStatus = dir; // } // } // Singleton implementation/instance. ValveMotorDirectV1 ValveDirect; #endif #if defined(ENABLE_BOILER_HUB) // Boiler output control. // Set thresholds for per-value and minimum-aggregate percentages to fire the boiler. // Coerces values to be valid: // minIndividual in range [1,100] and minAggregate in range [minIndividual,100]. void OnOffBoilerDriverLogic::setThresholds(const uint8_t minIndividual, const uint8_t minAggregate) { minIndividualPC = constrain(minIndividual, 1, 100); minAggregatePC = constrain(minAggregate, minIndividual, 100); } // Called upon incoming notification of status or call for heat from given (valid) ID. // ISR-/thread- safe to allow for interrupt-driven comms, and as quick as possible. // Returns false if the signal is rejected, eg from an unauthorised ID. // The basic behaviour is that a signal with sufficient percent open // is good for 2 minutes (120s, 60 ticks) unless explicitly cancelled earler, // for all valve types including FS20/FHT8V-style. // That may be slightly adjusted for IDs that indicate FS20 housecodes, etc. // * id is the two-byte ID or house code; 0xffffu is never valid // * percentOpen percentage open that the remote valve is reporting bool OnOffBoilerDriverLogic::receiveSignal(const uint16_t id, const uint8_t percentOpen) { if((badID == id) || (percentOpen > 100)) { return(false); } // Reject bad args. bool accepted = false; // Under lock to be ISR-safe. ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { #if defined(BOILER_RESPOND_TO_SPECIFIED_IDS_ONLY) // Reject unrecognised IDs if any in the auth list with false return. if(badID != authedIDs[0]) { // TODO } #endif // Find current entry in list if present and update, // else extend list if possible, // or replace 0 entry if available to make space, // or replace lower/lowest entry if this passed 'individual' threshold, // else reject update. // Find entry for current ID if present or create one at end if space, // but note in passing lowest % lower than current signal in case above not possible. } return(accepted); } #if defined(OnOffBoilerDriverLogic_CLEANUP) // Do some incremental clean-up to speed up future operations. // Aim to free up at least one status slot if possible. void OnOffBoilerDriverLogic::cleanup() { // Swap more-recently-heard-from items towards lower indexes. // Kill off trailing old entries. // Don't necessarily run on every tick: // possibly only run when something actually expires or when out of space. ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { if(badID != status[0].id) { // TODO } } } #endif // Fetches statuses of valves recently heard from and returns the count; 0 if none. // Optionally filters to return only those still live and apparently calling for heat. // * valves array to copy status to the start of; never null // * size size of valves[] in entries (not bytes), no more entries than that are used, // and no more than maxRadiators entries are ever needed // * onlyLiveAndCallingForHeat if true retrieves only current entries // 'calling for heat' by percentage uint8_t OnOffBoilerDriverLogic::valvesStatus(PerIDStatus valves[], const uint8_t size, const bool onlyLiveAndCallingForHeat) const { uint8_t result = 0; ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { for(volatile const PerIDStatus *p = status; (p < status+maxRadiators) && (badID != p->id); ++p) { // Stop if retun array full. if(result >= size) { break; } // Skip if filtering and current item not of interest. if(onlyLiveAndCallingForHeat && ((p->ticksUntilOff < 0) || (p->percentOpen < minIndividualPC))) { continue; } // Copy data into result array and increment count. valves[result++] = *(PerIDStatus *)p; } } return(result); } // Poll every 2 seconds in real/virtual time to update state in particular the callForHeat value. // Not to be called from ISRs, // in part because this may perform occasional expensive-ish operations // such as incremental clean-up. // Because this does not assume a tick is in real time // this remains entirely unit testable, // and no use of wall-clack time is made within this or sibling class methods. void OnOffBoilerDriverLogic::tick2s() { bool doCleanup = false; // If individual and aggregate limits are passed by set of IDs (and minimumTicksUntilOn is zero) // then nominally turn boiler on else nominally turn it off. // Such change of state may be prevented/delayed by duty-cycle limits. // // Adjust all expiry timers too. // // Be careful not to lock out interrupts (ie hold the lock) too long. // Set true if at least one valve has met/passed the individual % threshold to be considered calling for heat. bool atLeastOneValceCallingForHeat = false; // Partial cumulative percent open (stops accumulating once threshold has been passed). uint8_t partialCumulativePC = 0; ATOMIC_BLOCK (ATOMIC_RESTORESTATE) { for(volatile PerIDStatus *p = status; (p < status+maxRadiators) && (badID != p->id); ++p) { // Decrement time-until-expiry until lower limit is reached, at which point call for a cleanup! volatile int8_t &t = p->ticksUntilOff; if(t > -128) { --t; } else { doCleanup = true; continue; } // Ignore stale entries for boiler-state calculation. if(t < 0) { continue; } // Check if at least one valve is really open. if(!atLeastOneValceCallingForHeat && (p->percentOpen >= minIndividualPC)) { atLeastOneValceCallingForHeat = true; } // Check if aggregate limits are being reached. if(partialCumulativePC < minAggregatePC) { partialCumulativePC += p->percentOpen; } } } // Compute desired boiler state unconstrained by duty-cycle limits. // Boiler should be on if both individual and aggregate limits are met. const bool desiredBoilerState = atLeastOneValceCallingForHeat && (partialCumulativePC >= minAggregatePC); #if defined(OnOffBoilerDriverLogic_CLEANUP) if(doCleanup) { cleanup(); } #endif // Note passage of a tick in current state. if(ticksInCurrentState < 0xff) { ++ticksInCurrentState; } // If already in the correct state then nothing to do. if(desiredBoilerState == callForHeat) { return; } // If not enough ticks have passed to change state then don't. if(ticksInCurrentState < minTicksInEitherState) { return; } // Change boiler state and reset counter. callForHeat = desiredBoilerState; ticksInCurrentState = 0; } uint8_t BoilerDriver::read() { logic.tick2s(); value = (logic.isCallingForHeat()) ? 0 : 100; return(value); } // Singleton implementation/instance. extern BoilerDriver BoilerControl; #endif
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/sas/model/FixCheckWarningsRequest.h> using AlibabaCloud::Sas::Model::FixCheckWarningsRequest; FixCheckWarningsRequest::FixCheckWarningsRequest() : RpcServiceRequest("sas", "2018-12-03", "FixCheckWarnings") { setMethod(HttpRequest::Method::Post); } FixCheckWarningsRequest::~FixCheckWarningsRequest() {} long FixCheckWarningsRequest::getRiskId()const { return riskId_; } void FixCheckWarningsRequest::setRiskId(long riskId) { riskId_ = riskId; setParameter("RiskId", std::to_string(riskId)); } std::string FixCheckWarningsRequest::getCheckParams()const { return checkParams_; } void FixCheckWarningsRequest::setCheckParams(const std::string& checkParams) { checkParams_ = checkParams; setParameter("CheckParams", checkParams); } std::string FixCheckWarningsRequest::getSourceIp()const { return sourceIp_; } void FixCheckWarningsRequest::setSourceIp(const std::string& sourceIp) { sourceIp_ = sourceIp; setParameter("SourceIp", sourceIp); } std::string FixCheckWarningsRequest::getLang()const { return lang_; } void FixCheckWarningsRequest::setLang(const std::string& lang) { lang_ = lang; setParameter("Lang", lang); } std::string FixCheckWarningsRequest::getUuids()const { return uuids_; } void FixCheckWarningsRequest::setUuids(const std::string& uuids) { uuids_ = uuids; setParameter("Uuids", uuids); }
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_RUCKSACK_MINIMUM_SIZE_FWD_HPP_INCLUDED #define SGE_RUCKSACK_MINIMUM_SIZE_FWD_HPP_INCLUDED #include <sge/rucksack/scalar.hpp> #include <fcppt/declare_strong_typedef.hpp> namespace sge::rucksack { FCPPT_DECLARE_STRONG_TYPEDEF(sge::rucksack::scalar, minimum_size); } #endif
#include "db.h" #include <stdlib.h> using namespace std; void CAddrInfo::Update(bool good) { uint32_t now = time(NULL); if (ourLastTry == 0) ourLastTry = now - MIN_RETRY; int age = now - ourLastTry; lastTry = now; ourLastTry = now; total++; if (good) { success++; ourLastSuccess = now; } stat2H.Update(good, age, 3600*2); stat8H.Update(good, age, 3600*8); stat1D.Update(good, age, 3600*24); stat1W.Update(good, age, 3600*24*7); stat1M.Update(good, age, 3600*24*30); int ign = GetIgnoreTime(); if (ign && (ignoreTill==0 || ignoreTill < ign+now)) ignoreTill = ign+now; // printf("%s: got %s result: success=%i/%i; 2H:%.2f%%-%.2f%%(%.2f) 8H:%.2f%%-%.2f%%(%.2f) 1D:%.2f%%-%.2f%%(%.2f) 1W:%.2f%%-%.2f%%(%.2f) \n", ToString(ip).c_str(), good ? "good" : "bad", success, total, // 100.0 * stat2H.reliability, 100.0 * (stat2H.reliability + 1.0 - stat2H.weight), stat2H.count, // 100.0 * stat8H.reliability, 100.0 * (stat8H.reliability + 1.0 - stat8H.weight), stat8H.count, // 100.0 * stat1D.reliability, 100.0 * (stat1D.reliability + 1.0 - stat1D.weight), stat1D.count, // 100.0 * stat1W.reliability, 100.0 * (stat1W.reliability + 1.0 - stat1W.weight), stat1W.count); } bool CAddrDb::Get_(CServiceResult &ip, int &wait) { int64 now = time(NULL); int cont = 0; int tot = unkId.size() + ourId.size(); if (tot == 0) { wait = 5; return false; } do { int rnd = rand() % tot; int ret; if (rnd < unkId.size()) { set<int>::iterator it = unkId.end(); it--; ret = *it; unkId.erase(it); } else { ret = ourId.front(); if (time(NULL) - idToInfo[ret].ourLastTry < MIN_RETRY) return false; ourId.pop_front(); } if (idToInfo[ret].ignoreTill && idToInfo[ret].ignoreTill < now) { ourId.push_back(ret); idToInfo[ret].ourLastTry = now; } else { ip.service = idToInfo[ret].ip; ip.ourLastSuccess = idToInfo[ret].ourLastSuccess; break; } } while(1); nDirty++; return true; } int CAddrDb::Lookup_(const CService &ip) { if (ipToId.count(ip)) return ipToId[ip]; return -1; } void CAddrDb::Good_(const CService &addr, int clientV, std::string clientSV, int blocks) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); banned.erase(addr); CAddrInfo &info = idToInfo[id]; info.clientVersion = clientV; info.clientSubVersion = clientSV; info.blocks = blocks; info.Update(true); if (info.IsGood() && goodId.count(id)==0) { goodId.insert(id); // printf("%s: good; %i good nodes now\n", ToString(addr).c_str(), (int)goodId.size()); } nDirty++; ourId.push_back(id); } void CAddrDb::Bad_(const CService &addr, int ban) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); CAddrInfo &info = idToInfo[id]; info.Update(false); uint32_t now = time(NULL); int ter = info.GetBanTime(); if (ter) { // printf("%s: terrible\n", ToString(addr).c_str()); if (ban < ter) ban = ter; } if (ban > 0) { // printf("%s: ban for %i seconds\n", ToString(addr).c_str(), ban); banned[info.ip] = ban + now; ipToId.erase(info.ip); goodId.erase(id); idToInfo.erase(id); } else { if (/*!info.IsGood() && */ goodId.count(id)==1) { goodId.erase(id); // printf("%s: not good; %i good nodes left\n", ToString(addr).c_str(), (int)goodId.size()); } ourId.push_back(id); } nDirty++; } void CAddrDb::Skipped_(const CService &addr) { int id = Lookup_(addr); if (id == -1) return; unkId.erase(id); ourId.push_back(id); // printf("%s: skipped\n", ToString(addr).c_str()); nDirty++; } void CAddrDb::Add_(const CAddress &addr, bool force) { if (!force && !addr.IsRoutable()) return; CService ipp(addr); if (banned.count(ipp)) { time_t bantime = banned[ipp]; if (force || (bantime < time(NULL) && addr.nTime > bantime)) banned.erase(ipp); else return; } if (ipToId.count(ipp)) { CAddrInfo &ai = idToInfo[ipToId[ipp]]; if (addr.nTime > ai.lastTry || ai.services != addr.nServices) { ai.lastTry = addr.nTime; ai.services |= addr.nServices; // printf("%s: updated\n", ToString(addr).c_str()); } if (force) { ai.ignoreTill = 0; } return; } CAddrInfo ai; ai.ip = ipp; ai.services = addr.nServices; ai.lastTry = addr.nTime; ai.ourLastTry = 0; ai.total = 0; ai.success = 0; int id = nId++; idToInfo[id] = ai; ipToId[ipp] = id; // printf("%s: added\n", ToString(ipp).c_str(), ipToId[ipp]); unkId.insert(id); nDirty++; } void CAddrDb::GetIPs_(set<CNetAddr>& ips, int max, const bool* nets) { if (goodId.size() == 0) { int id = -1; if (ourId.size() == 0) { if (unkId.size() == 0) return; id = *unkId.begin(); } else { id = *ourId.begin(); } if (id >= 0) { ips.insert(idToInfo[id].ip); } return; } if (max > goodId.size() / 2) max = goodId.size() / 2; if (max < 1) max = 1; int low = *goodId.begin(); int high = *goodId.rbegin(); set<int> ids; while (ids.size() < max) { int range = high-low+1; int pos = low + (rand() % range); int id = *(goodId.lower_bound(pos)); ids.insert(id); } for (set<int>::const_iterator it = ids.begin(); it != ids.end(); it++) { CService &ip = idToInfo[*it].ip; if (nets[ip.GetNetwork()]) ips.insert(ip); } }